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