KiCad PCB EDA Suite
Loading...
Searching...
No Matches
windows/printing.cpp
Go to the documentation of this file.
1/*
2* This program source code file is part of KiCad, a free EDA CAD application.
3*
4* Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5*
6* This program is free software: you can redistribute it and/or modify it
7* under the terms of the GNU General Public License as published by the
8* Free Software Foundation, either version 3 of the License, or (at your
9* option) any later version.
10*
11* This program is distributed in the hope that it will be useful, but
12* WITHOUT ANY WARRANTY; without even the implied warranty of
13* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14* General Public License for more details.
15*
16* You should have received a copy of the GNU General Public License
17* along with this program. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20#ifndef __MINGW32__
21// wx pins NTDDI_VERSION to Vista when it includes windows.h first, which hides these interop headers
22#include <windows.h>
23#include <PrintManagerInterop.h>
24#include <windows.ui.xaml.hosting.desktopwindowxamlsource.h>
25#endif
26
27#include <printing.h>
28
29#include <wx/print.h>
30#include <wx/cmndata.h>
31
32#ifndef __MINGW32__
33#include <algorithm>
34#include <atomic>
35#include <future>
36#include <memory>
37#include <vector>
38
39#include <winrt/base.h>
40#include <winrt/Windows.Data.Pdf.h>
41#include <winrt/Windows.Foundation.h>
42#include <winrt/Windows.Foundation.Collections.h>
43#include <winrt/Windows.Graphics.Imaging.h>
44#include <winrt/Windows.Graphics.Printing.h>
45#include <winrt/Windows.Storage.h>
46#include <winrt/Windows.Storage.Streams.h>
47#include <winrt/Windows.UI.Xaml.h>
48#include <winrt/Windows.UI.Xaml.Controls.h>
49#include <winrt/Windows.UI.Xaml.Hosting.h>
50#include <winrt/Windows.UI.Xaml.Media.h>
51#include <winrt/Windows.UI.Xaml.Media.Imaging.h>
52#include <winrt/Windows.UI.Xaml.Printing.h>
53
54#include <wx/filename.h>
55#include <wx/log.h>
56
57namespace wdp = winrt::Windows::Data::Pdf;
58namespace wf = winrt::Windows::Foundation;
59namespace wgi = winrt::Windows::Graphics::Imaging;
60namespace wgp = winrt::Windows::Graphics::Printing;
61namespace wss = winrt::Windows::Storage::Streams;
62namespace wux = winrt::Windows::UI::Xaml;
63
64namespace
65{
66// Paper rasters are capped because every page stays decoded until the job has spooled
67constexpr double PRINT_MAX_DPI = 300.0;
68constexpr double PREVIEW_MAX_DPI = 150.0;
69
70
77template <typename FUNC>
78auto runInMta( FUNC&& aFunc )
79{
80 return std::async( std::launch::async,
81 [&aFunc]()
82 {
83 winrt::init_apartment( winrt::apartment_type::multi_threaded );
84
85 struct UNINIT
86 {
87 ~UNINIT() { winrt::uninit_apartment(); }
88 } uninit;
89
90 return aFunc();
91 } )
92 .get();
93}
94
95
102template <typename PRED>
103bool pumpUntil( PRED&& aDone )
104{
105 MSG msg;
106
107 while( !aDone() )
108 {
109 // Completion events arrive on pool threads without a message, so poll as well
110 ::MsgWaitForMultipleObjectsEx( 0, nullptr, 50, QS_ALLINPUT, MWMO_INPUTAVAILABLE );
111
112 while( ::PeekMessageW( &msg, nullptr, 0, 0, PM_REMOVE ) )
113 {
114 if( msg.message == WM_QUIT )
115 {
116 ::PostQuitMessage( static_cast<int>( msg.wParam ) );
117 return false;
118 }
119
120 ::TranslateMessage( &msg );
121 ::DispatchMessageW( &msg );
122 }
123 }
124
125 return true;
126}
127
128
135wss::InMemoryRandomAccessStream renderPage( const wdp::PdfDocument& aPdf, uint32_t aIndex,
136 const wgp::PrintPageDescription& aPaper, double aMaxDpi )
137{
138 wdp::PdfPage page = aPdf.GetPage( aIndex );
139 wf::Size src = page.Size();
140 wf::Rect area = aPaper.ImageableRect;
141 bool rotate = ( src.Width > src.Height ) != ( area.Width > area.Height );
142 double fitW = rotate ? src.Height : src.Width;
143 double fitH = rotate ? src.Width : src.Height;
144 double scale = std::min( area.Width / fitW, area.Height / fitH );
145 double dpi = aPaper.DpiX > 0 ? std::min<double>( aPaper.DpiX, aMaxDpi ) : aMaxDpi;
146 double pxPerDip = scale * dpi / 96.0;
147
148 wdp::PdfPageRenderOptions opts;
149 opts.DestinationWidth( static_cast<uint32_t>( std::max( 1.0, src.Width * pxPerDip ) ) );
150 opts.DestinationHeight( static_cast<uint32_t>( std::max( 1.0, src.Height * pxPerDip ) ) );
151
152 wss::InMemoryRandomAccessStream stream;
153 page.RenderToStreamAsync( stream, opts ).get();
154
155 if( !rotate )
156 return stream;
157
158 stream.Seek( 0 );
159 wgi::BitmapDecoder decoder = wgi::BitmapDecoder::CreateAsync( stream ).get();
160 wss::InMemoryRandomAccessStream rotated;
161 wgi::BitmapEncoder encoder = wgi::BitmapEncoder::CreateForTranscodingAsync( rotated, decoder ).get();
162
163 encoder.BitmapTransform().Rotation( wgi::BitmapRotation::Clockwise270Degrees );
164 encoder.FlushAsync().get();
165 return rotated;
166}
167
168
174wux::UIElement makePageElement( const wss::InMemoryRandomAccessStream& aStream,
175 const wgp::PrintPageDescription& aPaper )
176{
177 wux::Media::Imaging::BitmapImage bitmap;
178 aStream.Seek( 0 );
179 bitmap.SetSource( aStream );
180
181 wf::Rect area = aPaper.ImageableRect;
182 wux::Controls::Image image;
183 image.Source( bitmap );
184 image.Stretch( wux::Media::Stretch::Uniform );
185 image.Width( area.Width );
186 image.Height( area.Height );
187 image.Margin( wux::Thickness{ static_cast<double>( area.X ), static_cast<double>( area.Y ), 0.0, 0.0 } );
188 image.HorizontalAlignment( wux::HorizontalAlignment::Left );
189 image.VerticalAlignment( wux::VerticalAlignment::Top );
190
191 wux::Controls::Grid root;
192 root.Children().Append( image );
193 return root;
194}
195
196
197// Shared with the print task's Completed handler, which can outlive the printer object
198struct JOB_STATE
199{
200 std::atomic<bool> done{ false };
201 std::atomic<wgp::PrintTaskCompletion> completion{ wgp::PrintTaskCompletion::Abandoned };
202};
203
204
205class WIN_PDF_PRINTER
206{
207public:
208 WIN_PDF_PRINTER( HWND aOwner, const wdp::PdfDocument& aPdf, const winrt::hstring& aJobName, int aCurrentPage ) :
209 m_owner( aOwner ),
210 m_pdf( aPdf ),
211 m_jobName( aJobName ),
212 m_pageCount( aPdf.PageCount() ),
213 m_currentPage( aCurrentPage ),
214 m_job( std::make_shared<JOB_STATE>() )
215 {
216 }
217
218 ~WIN_PDF_PRINTER() { cleanup(); }
219
221 {
223
224 // XAML fail-fasts if restarted on a thread after its last island closed, so pin it until exit
225 [[maybe_unused]] thread_local void* xamlCore =
226 winrt::detach_abi( wux::Hosting::WindowsXamlManager::InitializeForCurrentThread() );
227
228 // The print UI needs a XAML host in this process even though nothing is shown in it
229 m_xamlSource = wux::Hosting::DesktopWindowXamlSource();
230
231 m_host = ::CreateWindowExW( 0, L"STATIC", L"", WS_CHILD, 0, 0, 1, 1, m_owner, nullptr,
232 ::GetModuleHandleW( nullptr ), nullptr );
233
234 if( !m_host )
235 {
236 wxLogTrace( PRINTING_TRACE, "Failed to create XAML host window" );
237 return PRINT_RESULT::FAILED_TO_PRINT;
238 }
239
240 winrt::check_hresult( m_xamlSource.as<IDesktopWindowXamlSourceNative>()->AttachToWindow( m_host ) );
241 m_xamlSource.Content( wux::Controls::Grid() );
242
243 m_printDoc = wux::Printing::PrintDocument();
244 m_docSource = m_printDoc.DocumentSource();
245
246 m_paginateToken = m_printDoc.Paginate(
247 [this]( const wf::IInspectable&, const wux::Printing::PaginateEventArgs& aArgs )
248 {
249 // Paper or orientation changed, so every cached preview is stale
250 m_previewPaper = aArgs.PrintTaskOptions().GetPageDescription( 1 );
251 m_previewPages.clear();
252 m_printDoc.SetPreviewPageCount( m_pageCount, wux::Printing::PreviewPageCountType::Final );
253 } );
254
255 m_previewToken = m_printDoc.GetPreviewPage(
256 [this]( const wf::IInspectable&, const wux::Printing::GetPreviewPageEventArgs& aArgs )
257 {
258 onPreviewPage( aArgs.PageNumber() );
259 } );
260
261 m_addPagesToken = m_printDoc.AddPages(
262 [this]( const wf::IInspectable&, const wux::Printing::AddPagesEventArgs& aArgs )
263 {
264 onAddPages( aArgs.PrintTaskOptions() );
265 } );
266
267 auto factory = winrt::get_activation_factory<wgp::PrintManager, IPrintManagerInterop>();
268
269 winrt::check_hresult( factory->GetForWindow( m_owner, winrt::guid_of<wgp::PrintManager>(),
270 winrt::put_abi( m_printManager ) ) );
271
272 std::shared_ptr<JOB_STATE> job = m_job;
273 wgp::IPrintDocumentSource source = m_docSource;
274 winrt::hstring jobName = m_jobName;
275 bool offerCurrent = m_currentPage > 0;
276
277 m_taskRequestedToken = m_printManager.PrintTaskRequested(
278 [job, source, jobName, offerCurrent]( const wgp::PrintManager&,
279 const wgp::PrintTaskRequestedEventArgs& aArgs )
280 {
281 wgp::PrintTask task = aArgs.Request().CreatePrintTask(
282 jobName,
283 [source]( const wgp::PrintTaskSourceRequestedArgs& aSourceArgs )
284 {
285 aSourceArgs.SetSource( source );
286 } );
287
288 wgp::PrintPageRangeOptions ranges = task.Options().PageRangeOptions();
289 ranges.AllowAllPages( true );
290 ranges.AllowCurrentPage( offerCurrent );
291 ranges.AllowCustomSetOfPages( true );
292 task.Options().DisplayedOptions().Append( wgp::StandardPrintTaskOptions::CustomPageRanges() );
293
294 task.Completed(
295 [job]( const wgp::PrintTask&, const wgp::PrintTaskCompletedEventArgs& aDone )
296 {
297 job->completion = aDone.Completion();
298 job->done = true;
299 } );
300 } );
301
302 wf::IAsyncOperation<bool> showOp{ nullptr };
303
304 winrt::check_hresult( factory->ShowPrintUIForWindowAsync( m_owner, winrt::guid_of<wf::IAsyncOperation<bool>>(),
305 winrt::put_abi( showOp ) ) );
306
307 if( !pumpUntil(
308 [&]()
309 {
310 return showOp.Status() != wf::AsyncStatus::Started;
311 } ) )
312 return PRINT_RESULT::CANCELLED;
313
314 if( showOp.Status() != wf::AsyncStatus::Completed || !showOp.GetResults() )
315 {
316 int32_t hr = showOp.Status() == wf::AsyncStatus::Error ? int32_t( showOp.ErrorCode() ) : 0;
317 wxLogTrace( PRINTING_TRACE, "Print UI was not shown, status %d hr 0x%08x", int( showOp.Status() ), hr );
318 return PRINT_RESULT::FAILED_TO_PRINT;
319 }
320
321 // The print UI is modeless, so keep the owner from starting a second job underneath it
322 m_reenableOwner = !::EnableWindow( m_owner, FALSE );
323
324 // The rendered pages and the PDF have to outlive spooling, which ends after the UI closes
325 if( !pumpUntil(
326 [&]()
327 {
328 return job->done.load();
329 } ) )
330 return PRINT_RESULT::CANCELLED;
331
332 switch( job->completion.load() )
333 {
334 case wgp::PrintTaskCompletion::Submitted: return PRINT_RESULT::OK;
335 case wgp::PrintTaskCompletion::Failed: return PRINT_RESULT::FAILED_TO_PRINT;
336 default: return PRINT_RESULT::CANCELLED;
337 }
338 }
339
340private:
341 void onPreviewPage( int32_t aPageNumber )
342 {
343 uint32_t index = static_cast<uint32_t>( aPageNumber - 1 );
344
345 try
346 {
347 if( m_previewPages.size() < m_pageCount )
348 m_previewPages.resize( m_pageCount, nullptr );
349
350 if( !m_previewPages[index] )
351 {
352 wss::InMemoryRandomAccessStream stream = runInMta(
353 [&]()
354 {
355 return renderPage( m_pdf, index, m_previewPaper, PREVIEW_MAX_DPI );
356 } );
357
358 m_previewPages[index] = makePageElement( stream, m_previewPaper );
359 }
360
361 m_printDoc.SetPreviewPage( aPageNumber, m_previewPages[index] );
362 }
363 catch( const winrt::hresult_error& e )
364 {
365 wxLogTrace( PRINTING_TRACE, "Failed to preview page %d: %s", aPageNumber, winrt::to_string( e.message() ) );
366 }
367 }
368
369 void onAddPages( const wgp::PrintTaskOptions& aOptions )
370 {
371 try
372 {
373 std::vector<uint32_t> pages = selectedPages( aOptions );
374 std::vector<wgp::PrintPageDescription> papers;
375
376 for( uint32_t i = 0; i < pages.size(); ++i )
377 papers.push_back( aOptions.GetPageDescription( i + 1 ) );
378
379 std::vector<wss::InMemoryRandomAccessStream> streams = runInMta(
380 [&]()
381 {
382 std::vector<wss::InMemoryRandomAccessStream> rendered;
383
384 for( uint32_t i = 0; i < pages.size(); ++i )
385 rendered.push_back( renderPage( m_pdf, pages[i], papers[i], PRINT_MAX_DPI ) );
386
387 return rendered;
388 } );
389
390 for( uint32_t i = 0; i < pages.size(); ++i )
391 {
392 m_printPages.push_back( makePageElement( streams[i], papers[i] ) );
393 m_printDoc.AddPage( m_printPages.back() );
394 }
395 }
396 catch( const winrt::hresult_error& e )
397 {
398 wxLogTrace( PRINTING_TRACE, "Failed to render pages for printing: %s", winrt::to_string( e.message() ) );
399 }
400
401 m_printDoc.AddPagesComplete();
402 }
403
404 // Zero-based PDF pages to spool, from the page selection made in the print UI
405 std::vector<uint32_t> selectedPages( const wgp::PrintTaskOptions& aOptions ) const
406 {
407 std::vector<uint32_t> pages;
408
409 for( const wgp::PrintPageRange& range : aOptions.CustomPageRanges() )
410 {
411 wxLogTrace( PRINTING_TRACE, "Selected page range %d-%d", range.FirstPageNumber(), range.LastPageNumber() );
412
413 for( int32_t page = range.FirstPageNumber(); page <= range.LastPageNumber(); ++page )
414 {
415 if( page >= 1 && static_cast<uint32_t>( page ) <= m_pageCount )
416 pages.push_back( static_cast<uint32_t>( page - 1 ) );
417 }
418 }
419
420 if( pages.empty() )
421 {
422 for( uint32_t i = 0; i < m_pageCount; ++i )
423 pages.push_back( i );
424 }
425
426 return pages;
427 }
428
429 void cleanup()
430 {
431 if( m_reenableOwner )
432 {
433 ::EnableWindow( m_owner, TRUE );
434 m_reenableOwner = false;
435 }
436
437 if( m_printManager )
438 m_printManager.PrintTaskRequested( m_taskRequestedToken );
439
440 if( m_printDoc )
441 {
442 m_printDoc.AddPages( m_addPagesToken );
443 m_printDoc.GetPreviewPage( m_previewToken );
444 m_printDoc.Paginate( m_paginateToken );
445 }
446
447 m_previewPages.clear();
448 m_printPages.clear();
449 m_printManager = nullptr;
450 m_docSource = nullptr;
451 m_printDoc = nullptr;
452
453 if( m_xamlSource )
454 {
455 m_xamlSource.Close();
456 m_xamlSource = nullptr;
457 }
458
459 if( m_host )
460 {
461 ::DestroyWindow( m_host );
462 m_host = nullptr;
463 }
464 }
465
466 HWND m_owner;
467 wdp::PdfDocument m_pdf;
468 winrt::hstring m_jobName;
469 uint32_t m_pageCount;
470 int m_currentPage;
471 std::shared_ptr<JOB_STATE> m_job;
472
473 HWND m_host = nullptr;
474 bool m_reenableOwner = false;
475 wux::Hosting::DesktopWindowXamlSource m_xamlSource{ nullptr };
476 wux::Printing::PrintDocument m_printDoc{ nullptr };
477 wgp::IPrintDocumentSource m_docSource{ nullptr };
478 wgp::PrintManager m_printManager{ nullptr };
479 wgp::PrintPageDescription m_previewPaper{};
480 std::vector<wux::UIElement> m_previewPages;
481 std::vector<wux::UIElement> m_printPages;
482
483 winrt::event_token m_taskRequestedToken{};
484 winrt::event_token m_paginateToken{};
485 winrt::event_token m_previewToken{};
486 winrt::event_token m_addPagesToken{};
487};
488} // namespace
489
490
491namespace KIPLATFORM
492{
493namespace PRINTING
494{
495 PRINT_RESULT PrintPDF( const std::string& aFile, int aCurrentPage )
496 {
497 wxFileName fn( wxString::FromUTF8( aFile ) );
498 winrt::hstring path( fn.GetFullPath().ToStdWstring() );
499
500 if( !fn.FileExists() )
502
503 wdp::PdfDocument pdf{ nullptr };
504
505 try
506 {
507 pdf = runInMta(
508 [&]()
509 {
510 auto file = winrt::Windows::Storage::StorageFile::GetFileFromPathAsync( path ).get();
511 return wdp::PdfDocument::LoadFromFileAsync( file ).get();
512 } );
513 }
514 catch( const winrt::hresult_error& e )
515 {
516 wxLogTrace( PRINTING_TRACE, "Failed to load %s: %s", aFile, winrt::to_string( e.message() ) );
518 }
519
520 if( !pdf || pdf.PageCount() == 0 )
522
523 HWND owner = ::GetActiveWindow();
524
525 if( !owner )
526 owner = ::GetForegroundWindow();
527
528 if( !owner )
530
532
533 try
534 {
535 WIN_PDF_PRINTER printer( owner, pdf, winrt::hstring( fn.GetName().ToStdWstring() ), aCurrentPage );
536 result = printer.Run();
537 }
538 catch( const winrt::hresult_error& e )
539 {
540 wxLogTrace( PRINTING_TRACE, "Print failed: %s", winrt::to_string( e.message() ) );
541 }
542 catch( const std::exception& e )
543 {
544 wxLogTrace( PRINTING_TRACE, "Print failed: %s", e.what() );
545 }
546
547 return result;
548 }
549} // namespace PRINTING
550} // namespace KIPLATFORM
551
552#else
553
554namespace KIPLATFORM
555{
556namespace PRINTING
557{
558 PRINT_RESULT PrintPDF( std::string const&, int )
559 {
561 }
562} // namespace PRINTING
563} // namespace KIPLATFORM
564
565#endif
566
567namespace KIPLATFORM
568{
569namespace PRINTING
570{
571 // Windows spools through the driver rather than a scratch file, so the wx-level filename
572 // only ever holds the destination the user asked for
573 void ResetPrintToFilePath( wxPrintData& )
574 {
575 }
576} // namespace PRINTING
577} // namespace KIPLATFORM
int index
std::string source
PRINT_RESULT PrintPDF(const std::string &aFile, int aCurrentPage=0)
Show the platform print dialog for the PDF aFile and print it.
void ResetPrintToFilePath(wxPrintData &aData)
Discard a "print to file" destination in aData that the platform print backend generated for its own ...
#define PRINTING_TRACE
Definition printing.h:28
const int scale
std::string path
wxString result
Test unit parsing edge cases and error handling.