]> Pileus Git - ~andy/gtk/blob - modules/printbackends/file/gtkprintbackendfile.c
Bug 549810 – Memory leaks in printing code
[~andy/gtk] / modules / printbackends / file / gtkprintbackendfile.c
1 /* GTK - The GIMP Toolkit
2  * gtkprintbackendfile.c: Default implementation of GtkPrintBackend 
3  * for printing to a file
4  * Copyright (C) 2003, Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #include "config.h"
23
24 #include <unistd.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include <errno.h>
32 #include <cairo.h>
33 #include <cairo-pdf.h>
34 #include <cairo-ps.h>
35
36 #include <glib/gi18n-lib.h>
37
38 #include "gtk/gtk.h"
39 #include "gtk/gtkprinter-private.h"
40
41 #include "gtkprintbackendfile.h"
42
43 typedef struct _GtkPrintBackendFileClass GtkPrintBackendFileClass;
44
45 #define GTK_PRINT_BACKEND_FILE_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_PRINT_BACKEND_FILE, GtkPrintBackendFileClass))
46 #define GTK_IS_PRINT_BACKEND_FILE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_PRINT_BACKEND_FILE))
47 #define GTK_PRINT_BACKEND_FILE_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_PRINT_BACKEND_FILE, GtkPrintBackendFileClass))
48
49 #define _STREAM_MAX_CHUNK_SIZE 8192
50
51 static GType print_backend_file_type = 0;
52
53 struct _GtkPrintBackendFileClass
54 {
55   GtkPrintBackendClass parent_class;
56 };
57
58 struct _GtkPrintBackendFile
59 {
60   GtkPrintBackend parent_instance;
61 };
62
63 typedef enum
64 {
65   FORMAT_PDF,
66   FORMAT_PS,
67   N_FORMATS
68 } OutputFormat;
69
70 static const gchar* formats[N_FORMATS] =
71 {
72   "pdf",
73   "ps"
74 };
75
76 static GObjectClass *backend_parent_class;
77
78 static void                 gtk_print_backend_file_class_init      (GtkPrintBackendFileClass *class);
79 static void                 gtk_print_backend_file_init            (GtkPrintBackendFile      *impl);
80 static void                 file_printer_get_settings_from_options (GtkPrinter              *printer,
81                                                                     GtkPrinterOptionSet     *options,
82                                                                     GtkPrintSettings        *settings);
83 static GtkPrinterOptionSet *file_printer_get_options               (GtkPrinter              *printer,
84                                                                     GtkPrintSettings        *settings,
85                                                                     GtkPageSetup            *page_setup,
86                                                                     GtkPrintCapabilities     capabilities);
87 static void                 file_printer_prepare_for_print         (GtkPrinter              *printer,
88                                                                     GtkPrintJob             *print_job,
89                                                                     GtkPrintSettings        *settings,
90                                                                     GtkPageSetup            *page_setup);
91 static void                 gtk_print_backend_file_print_stream    (GtkPrintBackend         *print_backend,
92                                                                     GtkPrintJob             *job,
93                                                                     GIOChannel              *data_io,
94                                                                     GtkPrintJobCompleteFunc  callback,
95                                                                     gpointer                 user_data,
96                                                                     GDestroyNotify           dnotify);
97 static cairo_surface_t *    file_printer_create_cairo_surface      (GtkPrinter              *printer,
98                                                                     GtkPrintSettings        *settings,
99                                                                     gdouble                  width,
100                                                                     gdouble                  height,
101                                                                     GIOChannel              *cache_io);
102
103 static GList *              file_printer_list_papers               (GtkPrinter              *printer);
104 static GtkPageSetup *       file_printer_get_default_page_size     (GtkPrinter              *printer);
105
106 static void
107 gtk_print_backend_file_register_type (GTypeModule *module)
108 {
109   static const GTypeInfo print_backend_file_info =
110   {
111     sizeof (GtkPrintBackendFileClass),
112     NULL,               /* base_init */
113     NULL,               /* base_finalize */
114     (GClassInitFunc) gtk_print_backend_file_class_init,
115     NULL,               /* class_finalize */
116     NULL,               /* class_data */
117     sizeof (GtkPrintBackendFile),
118     0,          /* n_preallocs */
119     (GInstanceInitFunc) gtk_print_backend_file_init,
120   };
121
122   print_backend_file_type = g_type_module_register_type (module,
123                                                          GTK_TYPE_PRINT_BACKEND,
124                                                          "GtkPrintBackendFile",
125                                                          &print_backend_file_info, 0);
126 }
127
128 G_MODULE_EXPORT void 
129 pb_module_init (GTypeModule *module)
130 {
131   gtk_print_backend_file_register_type (module);
132 }
133
134 G_MODULE_EXPORT void 
135 pb_module_exit (void)
136 {
137
138 }
139   
140 G_MODULE_EXPORT GtkPrintBackend * 
141 pb_module_create (void)
142 {
143   return gtk_print_backend_file_new ();
144 }
145
146 /*
147  * GtkPrintBackendFile
148  */
149 GType
150 gtk_print_backend_file_get_type (void)
151 {
152   return print_backend_file_type;
153 }
154
155 /**
156  * gtk_print_backend_file_new:
157  *
158  * Creates a new #GtkPrintBackendFile object. #GtkPrintBackendFile
159  * implements the #GtkPrintBackend interface with direct access to
160  * the filesystem using Unix/Linux API calls
161  *
162  * Return value: the new #GtkPrintBackendFile object
163  **/
164 GtkPrintBackend *
165 gtk_print_backend_file_new (void)
166 {
167   return g_object_new (GTK_TYPE_PRINT_BACKEND_FILE, NULL);
168 }
169
170 static void
171 gtk_print_backend_file_class_init (GtkPrintBackendFileClass *class)
172 {
173   GtkPrintBackendClass *backend_class = GTK_PRINT_BACKEND_CLASS (class);
174
175   backend_parent_class = g_type_class_peek_parent (class);
176
177   backend_class->print_stream = gtk_print_backend_file_print_stream;
178   backend_class->printer_create_cairo_surface = file_printer_create_cairo_surface;
179   backend_class->printer_get_options = file_printer_get_options;
180   backend_class->printer_get_settings_from_options = file_printer_get_settings_from_options;
181   backend_class->printer_prepare_for_print = file_printer_prepare_for_print;
182   backend_class->printer_list_papers = file_printer_list_papers;
183   backend_class->printer_get_default_page_size = file_printer_get_default_page_size;
184 }
185
186 /* return N_FORMATS if no explicit format in the settings */
187 static OutputFormat
188 format_from_settings (GtkPrintSettings *settings)
189 {
190   const gchar *value;
191   gint i;
192
193   if (settings == NULL)
194     return N_FORMATS;
195
196   value = gtk_print_settings_get (settings,
197                                   GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT);
198   if (value == NULL)
199     return N_FORMATS;
200
201   for (i = 0; i < N_FORMATS; ++i)
202     if (strcmp (value, formats[i]) == 0)
203       break;
204
205   g_assert (i < N_FORMATS);
206
207   return (OutputFormat) i;
208 }
209
210 static gchar *
211 output_file_from_settings (GtkPrintSettings *settings,
212                            const gchar      *default_format)
213 {
214   gchar *uri = NULL;
215   
216   if (settings)
217     uri = g_strdup (gtk_print_settings_get (settings, GTK_PRINT_SETTINGS_OUTPUT_URI));
218
219   if (uri == NULL)
220     { 
221       const gchar *extension;
222       gchar *name, *locale_name, *path;
223
224       if (default_format)
225         extension = default_format;
226       else
227         {
228           OutputFormat format;
229
230           format = format_from_settings (settings);
231           extension = format == FORMAT_PS ? "ps" : "pdf";
232         }
233  
234       /* default filename used for print-to-file */ 
235       name = g_strdup_printf (_("output.%s"), extension);
236       locale_name = g_filename_from_utf8 (name, -1, NULL, NULL, NULL);
237       g_free (name);
238
239       if (locale_name != NULL)
240         {
241           gchar *current_dir = g_get_current_dir ();
242           path = g_build_filename (current_dir, locale_name, NULL);
243           g_free (locale_name);
244
245           uri = g_filename_to_uri (path, NULL, NULL);
246           g_free (path);
247           g_free (current_dir);
248         }
249     }
250
251   return uri;
252 }
253
254 static cairo_status_t
255 _cairo_write (void                *closure,
256               const unsigned char *data,
257               unsigned int         length)
258 {
259   GIOChannel *io = (GIOChannel *)closure;
260   gsize written;
261   GError *error;
262
263   error = NULL;
264
265   GTK_NOTE (PRINTING,
266             g_print ("FILE Backend: Writting %i byte chunk to temp file\n", length));
267
268   while (length > 0) 
269     {
270       g_io_channel_write_chars (io, (const gchar *) data, length, &written, &error);
271
272       if (error != NULL)
273         {
274           GTK_NOTE (PRINTING,
275                      g_print ("FILE Backend: Error writting to temp file, %s\n", error->message));
276
277           g_error_free (error);
278           return CAIRO_STATUS_WRITE_ERROR;
279         }    
280
281       GTK_NOTE (PRINTING,
282                 g_print ("FILE Backend: Wrote %i bytes to temp file\n", written));
283       
284       data += written;
285       length -= written;
286     }
287
288   return CAIRO_STATUS_SUCCESS;
289 }
290
291
292 static cairo_surface_t *
293 file_printer_create_cairo_surface (GtkPrinter       *printer,
294                                    GtkPrintSettings *settings,
295                                    gdouble           width, 
296                                    gdouble           height,
297                                    GIOChannel       *cache_io)
298 {
299   cairo_surface_t *surface;
300   OutputFormat format;
301
302   format = format_from_settings (settings);
303
304   if (format == FORMAT_PS)
305     surface = cairo_ps_surface_create_for_stream (_cairo_write, cache_io, width, height);
306   else
307     surface = cairo_pdf_surface_create_for_stream (_cairo_write, cache_io, width, height);
308
309   /* TODO: DPI from settings object? */
310   cairo_surface_set_fallback_resolution (surface, 300, 300);
311
312   return surface;
313 }
314
315 typedef struct {
316   GtkPrintBackend *backend;
317   GtkPrintJobCompleteFunc callback;
318   GtkPrintJob *job;
319   GIOChannel *target_io;
320   gpointer user_data;
321   GDestroyNotify dnotify;
322 } _PrintStreamData;
323
324 static void
325 file_print_cb (GtkPrintBackendFile *print_backend,
326                GError              *error,
327                gpointer            user_data)
328 {
329   _PrintStreamData *ps = (_PrintStreamData *) user_data;
330
331   GDK_THREADS_ENTER ();
332
333   if (ps->target_io != NULL)
334     g_io_channel_unref (ps->target_io);
335
336   if (ps->callback)
337     ps->callback (ps->job, ps->user_data, error);
338
339   if (ps->dnotify)
340     ps->dnotify (ps->user_data);
341
342   gtk_print_job_set_status (ps->job,
343                             (error != NULL)?GTK_PRINT_STATUS_FINISHED_ABORTED:GTK_PRINT_STATUS_FINISHED);
344
345   if (ps->job)
346     g_object_unref (ps->job);
347  
348   g_free (ps);
349
350   GDK_THREADS_LEAVE ();
351 }
352
353 static gboolean
354 file_write (GIOChannel   *source,
355             GIOCondition  con,
356             gpointer      user_data)
357 {
358   gchar buf[_STREAM_MAX_CHUNK_SIZE];
359   gsize bytes_read;
360   GError *error;
361   GIOStatus read_status;
362   _PrintStreamData *ps = (_PrintStreamData *) user_data;
363
364   error = NULL;
365
366   read_status = 
367     g_io_channel_read_chars (source,
368                              buf,
369                              _STREAM_MAX_CHUNK_SIZE,
370                              &bytes_read,
371                              &error);
372
373   if (read_status != G_IO_STATUS_ERROR)
374     {
375       gsize bytes_written;
376
377       g_io_channel_write_chars (ps->target_io, 
378                                 buf, 
379                                 bytes_read, 
380                                 &bytes_written, 
381                                 &error);
382     }
383
384   if (error != NULL || read_status == G_IO_STATUS_EOF)
385     {
386       file_print_cb (GTK_PRINT_BACKEND_FILE (ps->backend), error, user_data);
387
388       if (error != NULL)
389         {
390           GTK_NOTE (PRINTING,
391                     g_print ("FILE Backend: %s\n", error->message));
392
393           g_error_free (error);
394         }
395
396       return FALSE;
397     }
398
399   GTK_NOTE (PRINTING,
400             g_print ("FILE Backend: Writting %i byte chunk to target file\n", bytes_read));
401
402   return TRUE;
403 }
404
405 static void
406 gtk_print_backend_file_print_stream (GtkPrintBackend        *print_backend,
407                                      GtkPrintJob            *job,
408                                      GIOChannel             *data_io,
409                                      GtkPrintJobCompleteFunc callback,
410                                      gpointer                user_data,
411                                      GDestroyNotify          dnotify)
412 {
413   GError *internal_error = NULL;
414   GtkPrinter *printer;
415   _PrintStreamData *ps;
416   GtkPrintSettings *settings;
417   gchar *uri, *filename;
418
419   printer = gtk_print_job_get_printer (job);
420   settings = gtk_print_job_get_settings (job);
421
422   ps = g_new0 (_PrintStreamData, 1);
423   ps->callback = callback;
424   ps->user_data = user_data;
425   ps->dnotify = dnotify;
426   ps->job = g_object_ref (job);
427   ps->backend = print_backend;
428
429   internal_error = NULL;
430   uri = output_file_from_settings (settings, NULL);
431   filename = g_filename_from_uri (uri, NULL, &internal_error);
432   g_free (uri);
433
434   if (filename == NULL)
435     goto error;
436
437   ps->target_io = g_io_channel_new_file (filename, "w", &internal_error);
438
439   g_free (filename);
440
441   if (internal_error == NULL)
442     g_io_channel_set_encoding (ps->target_io, NULL, &internal_error);
443
444 error:
445   if (internal_error != NULL)
446     {
447       file_print_cb (GTK_PRINT_BACKEND_FILE (print_backend),
448                     internal_error, ps);
449
450       g_error_free (internal_error);
451       return;
452     }
453
454   g_io_add_watch (data_io, 
455                   G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP,
456                   (GIOFunc) file_write,
457                   ps);
458 }
459
460 static void
461 gtk_print_backend_file_init (GtkPrintBackendFile *backend)
462 {
463   GtkPrinter *printer;
464   
465   printer = g_object_new (GTK_TYPE_PRINTER,
466                           "name", _("Print to File"),
467                           "backend", backend,
468                           "is-virtual", TRUE,
469                           NULL); 
470
471   gtk_printer_set_has_details (printer, TRUE);
472   gtk_printer_set_icon_name (printer, "gtk-floppy");
473   gtk_printer_set_is_active (printer, TRUE);
474
475   gtk_print_backend_add_printer (GTK_PRINT_BACKEND (backend), printer);
476   g_object_unref (printer);
477
478   gtk_print_backend_set_list_done (GTK_PRINT_BACKEND (backend));
479 }
480
481 static void
482 file_printer_output_file_format_changed (GtkPrinterOption    *format_option,
483                                          GtkPrinterOptionSet *set)
484 {
485   GtkPrinterOption *uri_option;
486   gchar            *base = NULL;
487
488   if (! format_option->value)
489     return;
490
491   uri_option = gtk_printer_option_set_lookup (set,
492                                               "gtk-main-page-custom-input");
493
494   if (uri_option && uri_option->value)
495     {
496       const gchar *uri = uri_option->value;
497       const gchar *dot = strrchr (uri, '.');
498
499       if (dot)
500         {
501           gint i;
502
503           /*  check if the file extension matches one of the known ones  */
504           for (i = 0; i < N_FORMATS; i++)
505             if (strcmp (dot + 1, formats[i]) == 0)
506               break;
507
508           if (i < N_FORMATS && strcmp (formats[i], format_option->value))
509             {
510               /*  the file extension is known but doesn't match the
511                *  selected one, strip it away
512                */
513               base = g_strndup (uri, dot - uri);
514             }
515         }
516       else
517         {
518           /*  there's no file extension  */
519           base = g_strdup (uri);
520         }
521     }
522
523   if (base)
524     {
525       gchar *tmp = g_strdup_printf ("%s.%s", base, format_option->value);
526
527       gtk_printer_option_set (uri_option, tmp);
528       g_free (tmp);
529       g_free (base);
530     }
531 }
532
533 static GtkPrinterOptionSet *
534 file_printer_get_options (GtkPrinter           *printer,
535                           GtkPrintSettings     *settings,
536                           GtkPageSetup         *page_setup,
537                           GtkPrintCapabilities  capabilities)
538 {
539   GtkPrinterOptionSet *set;
540   GtkPrinterOption *option;
541   const gchar *n_up[] = {"1", "2", "4", "6", "9", "16" };
542   const gchar *pages_per_sheet = NULL;
543   const gchar *format_names[N_FORMATS] = { N_("PDF"), N_("Postscript") };
544   const gchar *supported_formats[N_FORMATS];
545   gchar *display_format_names[N_FORMATS];
546   gint n_formats = 0;
547   OutputFormat format;
548   gchar *uri;
549   gint current_format = 0;
550
551   format = format_from_settings (settings);
552
553   set = gtk_printer_option_set_new ();
554
555   option = gtk_printer_option_new ("gtk-n-up", _("Pages per _sheet:"), GTK_PRINTER_OPTION_TYPE_PICKONE);
556   gtk_printer_option_choices_from_array (option, G_N_ELEMENTS (n_up),
557                                          (char **) n_up, (char **) n_up /* FIXME i18n (localised digits)! */);
558   if (settings)
559     pages_per_sheet = gtk_print_settings_get (settings, GTK_PRINT_SETTINGS_NUMBER_UP);
560   if (pages_per_sheet)
561     gtk_printer_option_set (option, pages_per_sheet);
562   else
563     gtk_printer_option_set (option, "1");
564   gtk_printer_option_set_add (set, option);
565   g_object_unref (option);
566
567   if (capabilities & (GTK_PRINT_CAPABILITY_GENERATE_PDF | GTK_PRINT_CAPABILITY_GENERATE_PS))
568     {
569       if (capabilities & GTK_PRINT_CAPABILITY_GENERATE_PDF)
570         {
571           if (format == FORMAT_PDF || format == N_FORMATS)
572             {
573               format = FORMAT_PDF;
574               current_format = n_formats;
575             }
576           supported_formats[n_formats] = formats[FORMAT_PDF];
577           display_format_names[n_formats] = _(format_names[FORMAT_PDF]);
578           n_formats++;
579         }
580       if (capabilities & GTK_PRINT_CAPABILITY_GENERATE_PS)
581         {
582           if (format == FORMAT_PS || format == N_FORMATS)
583             current_format = n_formats;
584           supported_formats[n_formats] = formats[FORMAT_PS];
585           display_format_names[n_formats] = _(format_names[FORMAT_PS]);
586           n_formats++;
587         }
588     }
589   else
590     {
591       current_format = format == FORMAT_PS ? FORMAT_PS : FORMAT_PDF;
592       for (n_formats = 0; n_formats < N_FORMATS; ++n_formats)
593         {
594           supported_formats[n_formats] = formats[n_formats];
595           display_format_names[n_formats] = _(format_names[n_formats]);
596         }
597     }
598
599   uri = output_file_from_settings (settings, supported_formats[current_format]);
600
601   option = gtk_printer_option_new ("gtk-main-page-custom-input", _("File"), 
602                                    GTK_PRINTER_OPTION_TYPE_FILESAVE);
603   gtk_printer_option_set (option, uri);
604   g_free (uri);
605   option->group = g_strdup ("GtkPrintDialogExtension");
606   gtk_printer_option_set_add (set, option);
607
608   if (n_formats > 1)
609     {
610       option = gtk_printer_option_new ("output-file-format", _("_Output format"), 
611                                        GTK_PRINTER_OPTION_TYPE_ALTERNATIVE);
612       option->group = g_strdup ("GtkPrintDialogExtension");
613
614       gtk_printer_option_choices_from_array (option, n_formats,
615                                              (char **) supported_formats,
616                                              display_format_names);
617       gtk_printer_option_set (option, supported_formats[current_format]);
618       gtk_printer_option_set_add (set, option);
619
620       g_signal_connect (option, "changed",
621                         G_CALLBACK (file_printer_output_file_format_changed),
622                         set);
623
624       g_object_unref (option);
625     }
626
627   return set;
628 }
629
630 static void
631 file_printer_get_settings_from_options (GtkPrinter          *printer,
632                                         GtkPrinterOptionSet *options,
633                                         GtkPrintSettings    *settings)
634 {
635   GtkPrinterOption *option;
636
637   option = gtk_printer_option_set_lookup (options, "gtk-main-page-custom-input");
638   gtk_print_settings_set (settings, GTK_PRINT_SETTINGS_OUTPUT_URI, option->value);
639
640   option = gtk_printer_option_set_lookup (options, "output-file-format");
641   if (option)
642     gtk_print_settings_set (settings, GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT, option->value);
643
644   option = gtk_printer_option_set_lookup (options, "gtk-n-up");
645   if (option)
646     gtk_print_settings_set (settings, GTK_PRINT_SETTINGS_NUMBER_UP, option->value);
647 }
648
649 static void
650 file_printer_prepare_for_print (GtkPrinter       *printer,
651                                 GtkPrintJob      *print_job,
652                                 GtkPrintSettings *settings,
653                                 GtkPageSetup     *page_setup)
654 {
655   gdouble scale;
656
657   print_job->print_pages = gtk_print_settings_get_print_pages (settings);
658   print_job->page_ranges = NULL;
659   print_job->num_page_ranges = 0;
660   
661   if (print_job->print_pages == GTK_PRINT_PAGES_RANGES)
662     print_job->page_ranges =
663       gtk_print_settings_get_page_ranges (settings,
664                                           &print_job->num_page_ranges);
665   
666   print_job->collate = gtk_print_settings_get_collate (settings);
667   print_job->reverse = gtk_print_settings_get_reverse (settings);
668   print_job->num_copies = gtk_print_settings_get_n_copies (settings);
669
670   scale = gtk_print_settings_get_scale (settings);
671   if (scale != 100.0)
672     print_job->scale = scale/100.0;
673
674   print_job->page_set = gtk_print_settings_get_page_set (settings);
675   print_job->rotate_to_orientation = TRUE;
676 }
677
678 static GList *
679 file_printer_list_papers (GtkPrinter *printer)
680 {
681   GList *result = NULL;
682   GList *papers, *p;
683   GtkPageSetup *page_setup;
684
685   papers = gtk_paper_size_get_paper_sizes (TRUE);
686
687   for (p = papers; p; p = p->next)
688     {
689       GtkPaperSize *paper_size = p->data;
690
691       page_setup = gtk_page_setup_new ();
692       gtk_page_setup_set_paper_size (page_setup, paper_size);
693       gtk_paper_size_free (paper_size);
694       result = g_list_prepend (result, page_setup);
695     }
696
697   g_list_free (papers);
698
699   return g_list_reverse (result);
700 }
701
702 static GtkPageSetup *
703 file_printer_get_default_page_size (GtkPrinter *printer)
704 {
705   GtkPageSetup *result = NULL;
706
707   return result;
708 }