KiCad PCB EDA Suite
Loading...
Searching...
No Matches
unix/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#include <printing.h>
20
21#include <poppler/glib/poppler.h>
22#include <gtk/gtk.h>
23#include <unistd.h>
24#include <algorithm>
25#include <memory>
26
27#include <wx/filename.h>
28#include <wx/filesys.h>
29#include <wx/print.h>
30#include <wx/cmndata.h>
31#include <wx/regex.h>
32#include <wx/toplevel.h>
33#include <wx/log.h>
34
35#if wxUSE_GTKPRINT
36#include <wx/gtk/print.h>
37#endif
38
39namespace
40{
41struct PrintData
42{
43 PopplerDocument* doc;
44 bool fit_to_page;
45
46 PrintData( PopplerDocument* d ) :
47 doc( d ),
48 fit_to_page( true )
49 {
50 }
51};
52
53void draw_page( GtkPrintOperation* operation, GtkPrintContext* context, gint page_nr, gpointer user_data )
54{
55 PrintData* print_data = static_cast<PrintData*>( user_data );
56
57 if( !print_data || !print_data->doc )
58 return;
59
60 PopplerPage* page = poppler_document_get_page( print_data->doc, page_nr );
61
62 if( !page ) return;
63
64 auto cleanup_page = std::unique_ptr<PopplerPage, decltype( &g_object_unref )>( page, &g_object_unref );
65
66 cairo_t* cr = gtk_print_context_get_cairo_context( context );
67
68 if( !cr ) return;
69
70 // Get page dimensions
71 double page_width, page_height;
72 poppler_page_get_size( page, &page_width, &page_height );
73
74 // Get print context dimensions
75 double print_width = gtk_print_context_get_width( context );
76 double print_height = gtk_print_context_get_height( context );
77
78 cairo_save( cr );
79 auto cleanup_cairo = std::unique_ptr<cairo_t, decltype( &cairo_restore )>( cr, &cairo_restore );
80
81 if( print_data->fit_to_page )
82 {
83 // Calculate scaling to fit page while maintaining aspect ratio
84 double scale_x = print_width / page_width;
85 double scale_y = print_height / page_height;
86 double scale = std::min( scale_x, scale_y );
87
88 // Center the page
89 double scaled_width = page_width * scale;
90 double scaled_height = page_height * scale;
91 double offset_x = ( print_width - scaled_width ) / 2.0;
92 double offset_y = ( print_height - scaled_height ) / 2.0;
93
94 // Apply transformations
95 cairo_translate( cr, offset_x, offset_y );
96 cairo_scale( cr, scale, scale );
97 }
98
99 // Set white background
100 cairo_set_source_rgb( cr, 1.0, 1.0, 1.0 );
101 cairo_paint( cr );
102
103 // Render the page
104 poppler_page_render( page, cr );
105}
106
107void begin_print_callback( GtkPrintOperation* operation, GtkPrintContext* context, gpointer user_data )
108{
109 PrintData* print_data = static_cast<PrintData*>( user_data );
110 if( !print_data || !print_data->doc )
111 {
112 gtk_print_operation_cancel( operation );
113 return;
114 }
115
116 int num_pages = poppler_document_get_n_pages( print_data->doc );
117 if( num_pages <= 0 )
118 {
119 gtk_print_operation_cancel( operation );
120 return;
121 }
122
123 gtk_print_operation_set_n_pages( operation, num_pages );
124}
125
126void request_page_setup_callback( GtkPrintOperation* operation, GtkPrintContext* context, gint page_nr,
127 GtkPageSetup* setup, gpointer user_data )
128{
129 PrintData* print_data = static_cast<PrintData*>( user_data );
130
131 if( !print_data || !print_data->doc )
132 return;
133
134 PopplerPage* page = poppler_document_get_page( print_data->doc, page_nr );
135
136 if( !page )
137 return;
138
139 // Get page dimensions to determine orientation
140 double page_width, page_height;
141 poppler_page_get_size( page, &page_width, &page_height );
142
143 // Set orientation based on page dimensions
144 GtkPageOrientation orientation =
145 ( page_width > page_height ) ? GTK_PAGE_ORIENTATION_LANDSCAPE : GTK_PAGE_ORIENTATION_PORTRAIT;
146 gtk_page_setup_set_orientation( setup, orientation );
147
148 g_object_unref( page );
149}
150
151
152// GTK's scratch files use the g_mkstemp() templates "gtkprintXXXXXX" and "gtkprint_XXXXXX", so match
153// the whole template to keep a destination the user named gtkprint-something
154bool isSpoolName( const wxString& aFileName )
155{
156 static wxRegEx spoolTemplate( wxS( "^gtkprint_?[A-Z0-9]{6}$" ) );
157
158 return spoolTemplate.Matches( aFileName );
159}
160
161
162// Settings from the last accepted dialog, so the next print reopens on the same printer and paper
163GtkPrintSettings* s_lastSettings = nullptr;
164
165
166// Keep the print-to-file folder but not the file, so the next document is offered under its own name
167void rememberSettings( GtkPrintSettings* aSettings )
168{
169 GtkPrintSettings* settings = gtk_print_settings_copy( aSettings );
170 const gchar* uri = gtk_print_settings_get( settings, GTK_PRINT_SETTINGS_OUTPUT_URI );
171
172 if( uri )
173 {
174 GFile* file = g_file_new_for_uri( uri );
175 GFile* dir = g_file_get_parent( file );
176 gchar* name = g_file_get_basename( file );
177
178 // The file backend joins output-dir to the basename as a local path, so a URI there breaks it
179 gchar* dirPath = dir ? g_file_get_path( dir ) : nullptr;
180
181 if( dirPath && name && !isSpoolName( wxFileName( wxString::FromUTF8( name ) ).GetName() ) )
182 gtk_print_settings_set( settings, GTK_PRINT_SETTINGS_OUTPUT_DIR, dirPath );
183
184 g_free( dirPath );
185
186 g_free( name );
187
188 if( dir )
189 g_object_unref( dir );
190
191 g_object_unref( file );
192 gtk_print_settings_unset( settings, GTK_PRINT_SETTINGS_OUTPUT_URI );
193 }
194
195 // A page selection only fits the document it was made for, so the next print starts from all pages
196 gtk_print_settings_set_print_pages( settings, GTK_PRINT_PAGES_ALL );
197 gtk_print_settings_unset( settings, GTK_PRINT_SETTINGS_PAGE_RANGES );
198
199 if( s_lastSettings )
200 g_object_unref( s_lastSettings );
201
202 s_lastSettings = settings;
203}
204
205
206GtkWindow* activeToplevel()
207{
208 wxWindow* active = wxGetTopLevelParent( wxGetActiveWindow() );
209
210 if( !active || !active->GetHandle() )
211 return nullptr;
212
213 GtkWidget* toplevel = gtk_widget_get_toplevel( active->GetHandle() );
214
215 return gtk_widget_is_toplevel( toplevel ) ? GTK_WINDOW( toplevel ) : nullptr;
216}
217} // namespace
218
219namespace KIPLATFORM
220{
221namespace PRINTING
222{
223 PRINT_RESULT PrintPDF( const std::string& aFile, bool fit_to_page, int aCurrentPage )
224 {
225 // Check file accessibility
226 if( access( aFile.c_str(), R_OK ) != 0 )
228
229 // Create file URI
230 gchar* uri = g_filename_to_uri( aFile.c_str(), NULL, NULL );
231 if( !uri )
233
234 // Load the PDF document
235 GError* error = NULL;
236 PopplerDocument* doc = poppler_document_new_from_file( uri, NULL, &error );
237 g_free( uri );
238
239 if( error )
240 {
241 wxLogTrace( PRINTING_TRACE, "Poppler could not load %s: %s", aFile, error->message );
242 g_error_free( error );
244 }
245
246 if( !doc )
248
249 auto cleanup_doc = std::unique_ptr<PopplerDocument, decltype(&g_object_unref)>(doc, &g_object_unref);
250
251 // Check if document has pages
252 int num_pages = poppler_document_get_n_pages( doc );
253
254 if( num_pages <= 0 )
256
257 // Create print data
258 PrintData print_data( doc );
259 print_data.fit_to_page = fit_to_page;
260
261 // Create print operation
262 GtkPrintOperation* op = gtk_print_operation_new();
263
264 if( !op )
266
267 auto cleanup_op = std::unique_ptr<GtkPrintOperation, decltype( &g_object_unref )>( op, &g_object_unref );
268
269 // Set up print operation properties
270 gtk_print_operation_set_use_full_page( op, FALSE );
271 gtk_print_operation_set_unit( op, GTK_UNIT_POINTS );
272
273 // GTK names both the spooled job and the print-to-file output after these
274 std::string jobName = wxFileName( wxString::FromUTF8( aFile ) ).GetName().ToStdString( wxConvUTF8 );
275 GtkPrintSettings* settings =
276 s_lastSettings ? gtk_print_settings_copy( s_lastSettings ) : gtk_print_settings_new();
277
278 gtk_print_settings_set( settings, GTK_PRINT_SETTINGS_OUTPUT_BASENAME, jobName.c_str() );
279 gtk_print_operation_set_print_settings( op, settings );
280 g_object_unref( settings );
281 gtk_print_operation_set_job_name( op, jobName.c_str() );
282
283 if( aCurrentPage > 0 && aCurrentPage <= num_pages )
284 gtk_print_operation_set_current_page( op, aCurrentPage - 1 );
285
286 // Connect callbacks
287 g_signal_connect( op, "begin-print", G_CALLBACK( begin_print_callback ), &print_data );
288 g_signal_connect( op, "draw-page", G_CALLBACK( draw_page ), &print_data );
289 g_signal_connect( op, "request-page-setup", G_CALLBACK( request_page_setup_callback ), &print_data );
290
291 // Run the print operation
292 error = NULL;
293 GtkPrintOperationResult result =
294 gtk_print_operation_run( op, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG, activeToplevel(), &error );
295
296 // Handle errors and determine result
297 PRINT_RESULT return_result;
298
299 if( error )
300 {
301 wxLogTrace( PRINTING_TRACE, "GTK print failed: %s", error->message );
302 g_error_free( error );
303 return_result = PRINT_RESULT::FAILED_TO_PRINT;
304 }
305 else
306 {
307 switch( result )
308 {
309 case GTK_PRINT_OPERATION_RESULT_APPLY:
310 rememberSettings( gtk_print_operation_get_print_settings( op ) );
311 return_result = PRINT_RESULT::OK;
312 break;
313 case GTK_PRINT_OPERATION_RESULT_CANCEL: return_result = PRINT_RESULT::CANCELLED; break;
314 case GTK_PRINT_OPERATION_RESULT_ERROR:
315 default: return_result = PRINT_RESULT::FAILED_TO_PRINT; break;
316 }
317 }
318
319 return return_result;
320 }
321
322 PRINT_RESULT PrintPDF( const std::string& aFile, int aCurrentPage )
323 {
324 return PrintPDF( aFile, true, aCurrentPage );
325 }
326
327 void ResetPrintToFilePath( wxPrintData& aData )
328 {
329 if( isSpoolName( wxFileName( aData.GetFilename() ).GetFullName() ) )
330 aData.SetFilename( wxEmptyString );
331
332#if wxUSE_GTKPRINT
333 wxGtkPrintNativeData* nativeData = dynamic_cast<wxGtkPrintNativeData*>( aData.GetNativeData() );
334
335 if( !nativeData || !nativeData->GetPrintConfig() )
336 return;
337
338 const gchar* uri = gtk_print_settings_get( nativeData->GetPrintConfig(),
339 GTK_PRINT_SETTINGS_OUTPUT_URI );
340
341 if( !uri )
342 return;
343
344 wxFileName destination = wxFileSystem::URLToFileName( wxString::FromUTF8( uri ) );
345
346 if( isSpoolName( destination.GetFullName() ) )
347 gtk_print_settings_unset( nativeData->GetPrintConfig(), GTK_PRINT_SETTINGS_OUTPUT_URI );
348#endif
349 }
350
351} // namespace PRINTING
352} // namespace KIPLATFORM
const char * name
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
static EDA_ORIENTATION orientation(double d)
wxString result
Test unit parsing edge cases and error handling.