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