2006-01-28 [colin] 1.9.100cvs194
[claws.git] / src / gtk / gtksourceprintjob.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; coding: utf-8 -*- */
2 /*
3  * gtksourceprintjob.c
4  * This file is part of GtkSourceView
5  *
6  * Derived from gedit-print.c
7  *
8  * Copyright (C) 2000, 2001 Chema Celorio, Paolo Maggi
9  * Copyright (C) 2002  Paolo Maggi  
10  * Copyright (C) 2003  Gustavo Giráldez
11  * Copyright (C) 2004  Red Hat, Inc.
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, 
26  * Boston, MA 02111-1307, USA. 
27  */
28  
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32
33 #ifdef USE_GNOMEPRINT
34
35 #include <string.h>
36 #include <time.h>
37
38 #include "gtksourceprintjob.h"
39 #include "image_viewer.h"
40
41 #include <glib/gi18n.h>
42 #include <gtk/gtkmain.h>
43 #include <gtk/gtktextview.h>
44 #include <libgnomeprint/gnome-print-pango.h>
45
46 #ifdef ENABLE_PROFILE
47 #define PROFILE(x) x
48 #else
49 #define PROFILE(x)
50 #endif
51
52 #ifdef ENABLE_DEBUG
53 #define DEBUG(x) x
54 #else
55 #define DEBUG(x)
56 #endif
57
58
59 #define DEFAULT_FONT_NAME   "Monospace 10"
60 #define DEFAULT_COLOR       0x000000ff
61
62 #define CM(v) ((v) * 72.0 / 2.54)
63 #define A4_WIDTH (210.0 * 72 / 25.4)
64 #define A4_HEIGHT (297.0 * 72 / 25.4)
65
66 #define NUMBERS_TEXT_SEPARATION CM(0.5)
67
68 #define HEADER_FOOTER_SIZE      2.5
69 #define SEPARATOR_SPACING       1.5
70 #define SEPARATOR_LINE_WIDTH    1.0
71
72
73 typedef struct _TextSegment TextSegment;
74 typedef struct _Paragraph   Paragraph;
75 typedef struct _TextStyle   TextStyle;
76
77 /* a piece of text (within a paragraph) of the same style */
78 struct _TextSegment
79 {
80         TextSegment             *next;
81         TextStyle               *style;
82         gchar                   *text;
83         GdkPixbuf               *image;
84 };
85
86 /* a printable line */
87 struct _Paragraph
88 {
89         guint                    line_number;
90         TextSegment             *segment;
91 };
92
93 /* the style of a TextSegment */
94 struct _TextStyle
95 {
96         PangoFontDescription    *font_desc;
97         GdkColor                *foreground;
98         GdkColor                *background;
99         gdouble                  scale;
100         gboolean                 strikethrough;
101         PangoUnderline           underline;
102 };
103
104
105 struct _GtkSourcePrintJobPrivate
106 {
107         /* General job configuration */
108         GnomePrintConfig        *config;
109         GtkTextBuffer           *buffer;
110         guint                    tabs_width;
111         GtkWrapMode              wrap_mode;
112         gboolean                 highlight;
113         PangoLanguage           *language;
114         PangoFontDescription    *font;
115         PangoFontDescription    *numbers_font;
116         guint                    print_numbers;
117         gdouble                  margin_top;
118         gdouble                  margin_bottom;
119         gdouble                  margin_left;
120         gdouble                  margin_right;
121
122         /* Default header and footer configuration */
123         gboolean                 print_header;
124         gboolean                 print_footer;
125         PangoFontDescription    *header_footer_font;
126         gchar                   *header_format_left;
127         gchar                   *header_format_center;
128         gchar                   *header_format_right;
129         gboolean                 header_separator;
130         gchar                   *footer_format_left;
131         gchar                   *footer_format_center;
132         gchar                   *footer_format_right;
133         gboolean                 footer_separator;
134
135         /* Job data */
136         guint                    first_line_number;
137         guint                    last_line_number;
138         GSList                  *paragraphs;
139
140         /* Job state */
141         gboolean                 printing;
142         guint                    idle_printing_tag;
143         GnomePrintContext       *print_ctxt;
144         GnomePrintJob           *print_job;
145         PangoContext            *pango_context;
146         PangoTabArray           *tab_array;
147         gint                     page;
148         gint                     page_count;
149         gdouble                  available_height;
150         GSList                  *current_paragraph;
151         gint                     current_paragraph_line;
152         guint                    printed_lines;
153
154         /* Cached information - all this information is obtained from
155          * other fields in the configuration */
156         GHashTable              *tag_styles;
157
158         gdouble                  page_width;
159         gdouble                  page_height;
160         /* outer margins */
161         gdouble                  doc_margin_top;
162         gdouble                  doc_margin_left;
163         gdouble                  doc_margin_right;
164         gdouble                  doc_margin_bottom;
165
166         gdouble                  header_height;
167         gdouble                  footer_height;
168         gdouble                  numbers_width;
169
170         /* printable (for the document itself) size */
171         gdouble                  text_width;
172         gdouble                  text_height;
173 };
174
175
176 enum
177 {
178         PROP_0,
179         PROP_CONFIG,
180         PROP_BUFFER,
181         PROP_TABS_WIDTH,
182         PROP_WRAP_MODE,
183         PROP_HIGHLIGHT,
184         PROP_FONT,
185         PROP_FONT_DESC,
186         PROP_NUMBERS_FONT,
187         PROP_NUMBERS_FONT_DESC,
188         PROP_PRINT_NUMBERS,
189         PROP_PRINT_HEADER,
190         PROP_PRINT_FOOTER,
191         PROP_HEADER_FOOTER_FONT,
192         PROP_HEADER_FOOTER_FONT_DESC
193 };
194
195 enum
196 {
197         BEGIN_PAGE = 0,
198         FINISHED,
199         LAST_SIGNAL
200 };
201
202 static GObjectClass *parent_class = NULL;
203 static guint         print_job_signals [LAST_SIGNAL] = { 0 };
204
205 static void     gtk_source_print_job_class_init    (GtkSourcePrintJobClass *klass);
206 static void     gtk_source_print_job_instance_init (GtkSourcePrintJob      *job);
207 static void     gtk_source_print_job_finalize      (GObject                *object);
208 static void     gtk_source_print_job_get_property  (GObject                *object,
209                                                     guint                   property_id,
210                                                     GValue                 *value,
211                                                     GParamSpec             *pspec);
212 static void     gtk_source_print_job_set_property  (GObject                *object,
213                                                     guint                   property_id,
214                                                     const GValue           *value,
215                                                     GParamSpec             *pspec);
216 static void     gtk_source_print_job_begin_page    (GtkSourcePrintJob      *job);
217
218 static void     default_print_header               (GtkSourcePrintJob      *job,
219                                                     gdouble                 x,
220                                                     gdouble                 y);
221 static void     default_print_footer               (GtkSourcePrintJob      *job,
222                                                     gdouble                 x,
223                                                     gdouble                 y);
224
225
226 GType
227 gtk_source_print_job_get_type (void)
228 {
229         static GType our_type = 0;
230
231         if (our_type == 0)
232         {
233                 static const GTypeInfo our_info = {
234                         sizeof (GtkSourcePrintJobClass),
235                         NULL,   /* base_init */
236                         NULL,   /* base_finalize */
237                         (GClassInitFunc) gtk_source_print_job_class_init,
238                         NULL,   /* class_finalize */
239                         NULL,   /* class_data */
240                         sizeof (GtkSourcePrintJob),
241                         0,      /* n_preallocs */
242                         (GInstanceInitFunc) gtk_source_print_job_instance_init
243                 };
244
245                 our_type = g_type_register_static (G_TYPE_OBJECT,
246                                                    "GtkSourcePrintJob",
247                                                    &our_info, 
248                                                    0);
249         }
250         
251         return our_type;
252 }
253         
254 static void
255 gtk_source_print_job_class_init (GtkSourcePrintJobClass *klass)
256 {
257         GObjectClass *object_class;
258
259         object_class = G_OBJECT_CLASS (klass);
260         parent_class = g_type_class_peek_parent (klass);
261                 
262         object_class->finalize     = gtk_source_print_job_finalize;
263         object_class->get_property = gtk_source_print_job_get_property;
264         object_class->set_property = gtk_source_print_job_set_property;
265
266         klass->begin_page = gtk_source_print_job_begin_page;
267         klass->finished = NULL;
268         
269         g_object_class_install_property (object_class,
270                                          PROP_CONFIG,
271                                          g_param_spec_object ("config",
272                                                               _("Configuration"),
273                                                               _("Configuration options for "
274                                                                 "the print job"),
275                                                               GNOME_TYPE_PRINT_CONFIG,
276                                                               G_PARAM_READWRITE));
277         g_object_class_install_property (object_class,
278                                          PROP_BUFFER,
279                                          g_param_spec_object ("buffer",
280                                                               _("Source Buffer"),
281                                                               _("GtkTextBuffer object to print"),
282                                                               GTK_TYPE_TEXT_BUFFER,
283                                                               G_PARAM_READWRITE));
284         g_object_class_install_property (object_class,
285                                          PROP_TABS_WIDTH,
286                                          g_param_spec_uint ("tabs_width",
287                                                             _("Tabs Width"),
288                                                             _("Width in equivalent space "
289                                                               "characters of tabs"),
290                                                             0, 100, 8,
291                                                             G_PARAM_READWRITE));
292         g_object_class_install_property (object_class,
293                                          PROP_WRAP_MODE,
294                                          g_param_spec_enum ("wrap_mode",
295                                                             _("Wrap Mode"),
296                                                             _("Word wrapping mode"),
297                                                             GTK_TYPE_WRAP_MODE,
298                                                             GTK_WRAP_NONE,
299                                                             G_PARAM_READWRITE));
300         g_object_class_install_property (object_class,
301                                          PROP_HIGHLIGHT,
302                                          g_param_spec_boolean ("highlight",
303                                                                _("Highlight"),
304                                                                _("Whether to print the "
305                                                                  "document with highlighted "
306                                                                  "syntax"),
307                                                                TRUE,
308                                                                G_PARAM_READWRITE));
309         g_object_class_install_property (object_class,
310                                          PROP_FONT,
311                                          g_param_spec_string ("font",
312                                                               _("Font"),
313                                                               _("GnomeFont name to use for the "
314                                                                 "document text (deprecated)"),
315                                                               NULL,
316                                                               G_PARAM_READWRITE));
317         g_object_class_install_property (object_class,
318                                          PROP_FONT_DESC,
319                                          g_param_spec_boxed ("font_desc",
320                                                              _("Font Description"),
321                                                              _("Font to use for the document text "
322                                                                "(e.g. \"Monospace 10\")"),
323                                                              PANGO_TYPE_FONT_DESCRIPTION,
324                                                               G_PARAM_READWRITE));
325         g_object_class_install_property (object_class,
326                                          PROP_NUMBERS_FONT,
327                                          g_param_spec_string ("numbers_font",
328                                                               _("Numbers Font"),
329                                                               _("GnomeFont name to use for the "
330                                                                 "line numbers (deprecated)"),
331                                                               NULL,
332                                                               G_PARAM_READWRITE));
333         g_object_class_install_property (object_class,
334                                          PROP_NUMBERS_FONT_DESC,
335                                          g_param_spec_boxed ("numbers_font_desc",
336                                                              _("Numbers Font"),
337                                                              _("Font description to use for the "
338                                                                "line numbers"),
339                                                              PANGO_TYPE_FONT_DESCRIPTION,
340                                                               G_PARAM_READWRITE));
341         g_object_class_install_property (object_class,
342                                          PROP_PRINT_NUMBERS,
343                                          g_param_spec_uint ("print_numbers",
344                                                             _("Print Line Numbers"),
345                                                             _("Interval of printed line numbers "
346                                                               "(0 means no numbers)"),
347                                                             0, 100, 1,
348                                                             G_PARAM_READWRITE));
349         g_object_class_install_property (object_class,
350                                          PROP_PRINT_HEADER,
351                                          g_param_spec_boolean ("print_header",
352                                                                _("Print Header"),
353                                                                _("Whether to print a header "
354                                                                  "in each page"),
355                                                                FALSE,
356                                                                G_PARAM_READWRITE));
357         g_object_class_install_property (object_class,
358                                          PROP_PRINT_FOOTER,
359                                          g_param_spec_boolean ("print_footer",
360                                                                _("Print Footer"),
361                                                                _("Whether to print a footer "
362                                                                  "in each page"),
363                                                                FALSE,
364                                                                G_PARAM_READWRITE));
365         g_object_class_install_property (object_class,
366                                          PROP_HEADER_FOOTER_FONT,
367                                          g_param_spec_string ("header_footer_font",
368                                                               _("Header and Footer Font"),
369                                                               _("GnomeFont name to use for the header "
370                                                                 "and footer (deprecated)"),
371                                                               NULL,
372                                                               G_PARAM_READWRITE));
373         g_object_class_install_property (object_class,
374                                          PROP_HEADER_FOOTER_FONT_DESC,
375                                          g_param_spec_boxed ("header_footer_font_desc",
376                                                              _("Header and Footer Font Description"),
377                                                              _("Font to use for headers and footers "
378                                                                "(e.g. \"Monospace 10\")"),
379                                                              PANGO_TYPE_FONT_DESCRIPTION,
380                                                              G_PARAM_READWRITE));
381         
382         print_job_signals [BEGIN_PAGE] =
383             g_signal_new ("begin_page",
384                           G_OBJECT_CLASS_TYPE (object_class),
385                           G_SIGNAL_RUN_LAST,
386                           G_STRUCT_OFFSET (GtkSourcePrintJobClass, begin_page),
387                           NULL, NULL,
388                           g_cclosure_marshal_VOID__VOID,
389                           G_TYPE_NONE, 
390                           0);
391         print_job_signals [FINISHED] =
392             g_signal_new ("finished",
393                           G_OBJECT_CLASS_TYPE (object_class),
394                           G_SIGNAL_RUN_FIRST,
395                           G_STRUCT_OFFSET (GtkSourcePrintJobClass, finished),
396                           NULL, NULL,
397                           g_cclosure_marshal_VOID__VOID,
398                           G_TYPE_NONE, 
399                           0);
400 }
401
402 static void
403 gtk_source_print_job_instance_init (GtkSourcePrintJob *job)
404 {
405         GtkSourcePrintJobPrivate *priv;
406
407         priv = g_new0 (GtkSourcePrintJobPrivate, 1);
408         job->priv = priv;
409
410         /* default job configuration */
411         priv->config = NULL;
412         priv->buffer = NULL;
413
414         priv->tabs_width = 8;
415         priv->wrap_mode = GTK_WRAP_NONE;
416         priv->highlight = TRUE;
417         priv->language = gtk_get_default_language ();
418         priv->font = NULL;
419         priv->numbers_font = NULL;
420         priv->print_numbers = 1;
421         priv->margin_top = 0.0;
422         priv->margin_bottom = 0.0;
423         priv->margin_left = 0.0;
424         priv->margin_right = 0.0;
425
426         priv->print_header = FALSE;
427         priv->print_footer = FALSE;
428         priv->header_footer_font = NULL;
429         priv->header_format_left = NULL;
430         priv->header_format_center = NULL;
431         priv->header_format_right = NULL;
432         priv->header_separator = FALSE;
433         priv->footer_format_left = NULL;
434         priv->footer_format_center = NULL;
435         priv->footer_format_right = NULL;
436         priv->footer_separator = FALSE;
437
438         /* initial state */
439         priv->printing = FALSE;
440         priv->print_ctxt = NULL;
441         priv->print_job = NULL;
442         priv->page = 0;
443         priv->page_count = 0;
444
445         priv->first_line_number = 0;
446         priv->paragraphs = NULL;
447         priv->tag_styles = NULL;
448
449         /* some default, sane values */
450         priv->page_width = A4_WIDTH;
451         priv->page_height = A4_HEIGHT;
452         priv->doc_margin_top = CM (1);
453         priv->doc_margin_left = CM (1);
454         priv->doc_margin_right = CM (1);
455         priv->doc_margin_bottom = CM (1);
456 }
457
458 static void
459 free_paragraphs (GSList *paras)
460 {
461         while (paras != NULL)
462         {
463                 Paragraph *para = paras->data;
464                 TextSegment *seg =  para->segment;
465                 while (seg != NULL)
466                 {
467                         TextSegment *next = seg->next;
468                         g_free (seg->text);
469                         g_free (seg);
470                         seg = next;
471                 }
472                 g_free (para);
473                 paras = g_slist_delete_link (paras, paras);
474         }
475 }
476
477 static void
478 gtk_source_print_job_finalize (GObject *object)
479 {
480         GtkSourcePrintJob *job;
481         GtkSourcePrintJobPrivate *priv;
482         
483         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (object));
484         
485         job = GTK_SOURCE_PRINT_JOB (object);
486         priv = job->priv;
487         
488         if (priv != NULL)
489         {
490                 if (priv->config != NULL)
491                         gnome_print_config_unref (priv->config);
492                 if (priv->buffer != NULL)
493                         g_object_unref (priv->buffer);
494                 if (priv->font != NULL)
495                         pango_font_description_free (priv->font);
496                 if (priv->numbers_font != NULL)
497                         pango_font_description_free (priv->numbers_font);
498                 if (priv->header_footer_font != NULL)
499                         pango_font_description_free (priv->header_footer_font);
500                 g_free (priv->header_format_left);
501                 g_free (priv->header_format_right);
502                 g_free (priv->header_format_center);
503                 g_free (priv->footer_format_left);
504                 g_free (priv->footer_format_right);
505                 g_free (priv->footer_format_center);
506                 
507                 if (priv->print_ctxt != NULL)
508                         g_object_unref (priv->print_ctxt);
509                 if (priv->print_job != NULL)
510                         g_object_unref (priv->print_job);
511                 if (priv->pango_context != NULL)
512                         g_object_unref (priv->pango_context);
513                 if (priv->tab_array != NULL)
514                         pango_tab_array_free (priv->tab_array);
515
516                 if (priv->paragraphs != NULL)
517                         free_paragraphs (priv->paragraphs);
518                 if (priv->tag_styles != NULL)
519                         g_hash_table_destroy (priv->tag_styles);
520                 
521                 g_free (priv);
522                 job->priv = NULL;
523         }
524         
525         G_OBJECT_CLASS (parent_class)->finalize (object);
526 }
527
528 static void 
529 gtk_source_print_job_get_property (GObject    *object,
530                                    guint       prop_id,
531                                    GValue     *value,
532                                    GParamSpec *pspec)
533 {
534         GtkSourcePrintJob *job = GTK_SOURCE_PRINT_JOB (object);
535
536         switch (prop_id)
537         {
538                 case PROP_CONFIG:
539                         g_value_set_object (value, job->priv->config);
540                         break;
541                         
542                 case PROP_BUFFER:
543                         g_value_set_object (value, job->priv->buffer);
544                         break;
545
546                 case PROP_TABS_WIDTH:
547                         g_value_set_uint (value, job->priv->tabs_width);
548                         break;
549                         
550                 case PROP_WRAP_MODE:
551                         g_value_set_enum (value, job->priv->wrap_mode);
552                         break;
553
554                 case PROP_HIGHLIGHT:
555                         g_value_set_boolean (value, job->priv->highlight);
556                         break;
557                         
558                 case PROP_FONT:
559                         g_value_take_string (value, gtk_source_print_job_get_font (job));
560                         break;
561                         
562                 case PROP_FONT_DESC:
563                         g_value_set_boxed (value, gtk_source_print_job_get_font_desc (job));
564                         break;
565                         
566                 case PROP_NUMBERS_FONT:
567                         g_value_take_string (value, gtk_source_print_job_get_numbers_font (job));
568                         break;
569                         
570                 case PROP_NUMBERS_FONT_DESC:
571                         g_value_set_boxed (value, gtk_source_print_job_get_numbers_font_desc (job));
572                         break;
573                         
574                 case PROP_PRINT_NUMBERS:
575                         g_value_set_uint (value, job->priv->print_numbers);
576                         break;
577                         
578                 case PROP_PRINT_HEADER:
579                         g_value_set_boolean (value, job->priv->print_header);
580                         break;
581                         
582                 case PROP_PRINT_FOOTER:
583                         g_value_set_boolean (value, job->priv->print_footer);
584                         break;
585                         
586                 case PROP_HEADER_FOOTER_FONT:
587                         g_value_take_string (value,
588                                              gtk_source_print_job_get_header_footer_font (job));
589                         break;
590                         
591                 case PROP_HEADER_FOOTER_FONT_DESC:
592                         g_value_set_boxed (value,
593                                            gtk_source_print_job_get_header_footer_font_desc (job));
594                         break;
595                         
596                 default:
597                         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
598                         break;
599         }
600 }
601
602 static void 
603 gtk_source_print_job_set_property (GObject      *object,
604                                    guint         prop_id,
605                                    const GValue *value,
606                                    GParamSpec   *pspec)
607 {
608         GtkSourcePrintJob *job = GTK_SOURCE_PRINT_JOB (object);
609
610         switch (prop_id)
611         {
612                 case PROP_CONFIG:
613                         gtk_source_print_job_set_config (job, g_value_get_object (value));
614                         break;
615                         
616                 case PROP_BUFFER:
617                         gtk_source_print_job_set_buffer (job, g_value_get_object (value));
618                         break;
619                         
620                 case PROP_TABS_WIDTH:
621                         gtk_source_print_job_set_tabs_width (job, g_value_get_uint (value));
622                         break;
623                         
624                 case PROP_WRAP_MODE:
625                         gtk_source_print_job_set_wrap_mode (job, g_value_get_enum (value));
626                         break;
627
628                 case PROP_HIGHLIGHT:
629                         gtk_source_print_job_set_highlight (job, g_value_get_boolean (value));
630                         break;
631
632                 case PROP_FONT:
633                         gtk_source_print_job_set_font (job, g_value_get_string (value));
634                         break;
635
636                 case PROP_FONT_DESC:
637                         gtk_source_print_job_set_font_desc (job, g_value_get_boxed (value));
638                         break;
639                         
640                 case PROP_NUMBERS_FONT:
641                         gtk_source_print_job_set_numbers_font (job, g_value_get_string (value));
642                         break;
643                         
644                 case PROP_NUMBERS_FONT_DESC:
645                         gtk_source_print_job_set_numbers_font_desc (job, g_value_get_boxed (value));
646                         break;
647
648                 case PROP_PRINT_NUMBERS:
649                         gtk_source_print_job_set_print_numbers (job, g_value_get_uint (value));
650                         break;
651                         
652                 case PROP_PRINT_HEADER:
653                         gtk_source_print_job_set_print_header (job, g_value_get_boolean (value));
654                         break;
655
656                 case PROP_PRINT_FOOTER:
657                         gtk_source_print_job_set_print_footer (job, g_value_get_boolean (value));
658                         break;
659
660                 case PROP_HEADER_FOOTER_FONT:
661                         gtk_source_print_job_set_header_footer_font (job,
662                                                                      g_value_get_string (value));
663                         break;
664                         
665                 case PROP_HEADER_FOOTER_FONT_DESC:
666                         gtk_source_print_job_set_header_footer_font_desc (job,
667                                                                           g_value_get_boxed (value));
668                         break;
669
670                 default:
671                         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
672                         break;
673         }
674 }
675
676 static void 
677 gtk_source_print_job_begin_page (GtkSourcePrintJob *job)
678 {
679         g_return_if_fail (job->priv->printing);
680         
681         if (job->priv->print_header && job->priv->header_height > 0)
682         {
683                 gdouble x, y;
684
685                 x = job->priv->doc_margin_left + job->priv->margin_left;
686                 y = job->priv->page_height - job->priv->doc_margin_top - job->priv->margin_top;
687                 default_print_header (job, x, y);
688         }
689
690         if (job->priv->print_footer && job->priv->footer_height > 0)
691         {
692                 gdouble x, y;
693
694                 x = job->priv->doc_margin_left + job->priv->margin_left;
695                 y = job->priv->doc_margin_bottom +
696                         job->priv->margin_bottom +
697                         job->priv->footer_height;
698                 default_print_footer (job, x, y);
699         }
700 }
701
702 /* ---- gnome-print / Pango convenience functions */
703
704 /* Gets the width of a layout in gnome-print coordinates */
705 static gdouble
706 get_layout_width (PangoLayout *layout)
707 {
708         gint layout_width;
709
710         pango_layout_get_size (layout, &layout_width, NULL);
711         return (gdouble) layout_width / PANGO_SCALE;
712 }
713
714 /* Gets the ascent/descent of a font in gnome-print coordinates */
715 static void
716 get_font_ascent_descent (GtkSourcePrintJob    *job,
717                          PangoFontDescription *desc,
718                          gdouble              *ascent,
719                          gdouble              *descent)
720 {
721         PangoFontMetrics *metrics;
722         
723         metrics = pango_context_get_metrics (job->priv->pango_context,
724                                              desc,
725                                              job->priv->language);
726
727         if (ascent)
728                 *ascent = (gdouble) pango_font_metrics_get_ascent (metrics) / PANGO_SCALE;
729         if (descent)
730                 *descent = (gdouble) pango_font_metrics_get_descent (metrics) / PANGO_SCALE;
731
732         pango_font_metrics_unref (metrics);
733 }
734
735 /* Draws the first line in a layout; we use this for one-line layouts
736  * to get baseline alignment */
737 static void
738 show_first_layout_line (GnomePrintContext *print_ctxt,
739                         PangoLayout       *layout)
740 {
741         PangoLayoutLine *line;
742
743         line = pango_layout_get_lines (layout)->data;
744         gnome_print_pango_layout_line (print_ctxt, line);
745 }
746
747 static PangoLayout *
748 get_line_number_layout (GtkSourcePrintJob *job,
749                         guint              line_number)
750 {
751         PangoLayout *layout;
752         gchar *num_str;
753
754         num_str = g_strdup_printf ("%d", line_number);
755         layout = pango_layout_new (job->priv->pango_context);
756         pango_layout_set_font_description (layout, job->priv->numbers_font);
757         pango_layout_set_text (layout, num_str, -1);
758         g_free (num_str);
759
760         return layout;
761 }
762
763 /* ---- Configuration functions */
764
765 static void
766 ensure_print_config (GtkSourcePrintJob *job)
767 {
768         if (job->priv->config == NULL)
769                 job->priv->config = gnome_print_config_default ();
770         if (job->priv->font == NULL)
771                 job->priv->font = pango_font_description_from_string (DEFAULT_FONT_NAME);
772 }
773
774 static gboolean
775 update_page_size_and_margins (GtkSourcePrintJob *job)
776 {
777         PangoLayout *layout;
778         gdouble ascent, descent;
779         
780         gnome_print_job_get_page_size_from_config (job->priv->config, 
781                                                    &job->priv->page_width,
782                                                    &job->priv->page_height);
783
784         gnome_print_config_get_length (job->priv->config, GNOME_PRINT_KEY_PAGE_MARGIN_TOP,
785                                        &job->priv->doc_margin_top, NULL);
786         gnome_print_config_get_length (job->priv->config, GNOME_PRINT_KEY_PAGE_MARGIN_BOTTOM,
787                                        &job->priv->doc_margin_bottom, NULL);
788         gnome_print_config_get_length (job->priv->config, GNOME_PRINT_KEY_PAGE_MARGIN_LEFT,
789                                        &job->priv->doc_margin_left, NULL);
790         gnome_print_config_get_length (job->priv->config, GNOME_PRINT_KEY_PAGE_MARGIN_RIGHT,
791                                        &job->priv->doc_margin_right, NULL);
792
793         /* set default fonts for numbers and header/footer */
794         if (job->priv->numbers_font == NULL)
795                 job->priv->numbers_font = pango_font_description_copy (job->priv->font);
796         
797         if (job->priv->header_footer_font == NULL)
798                 job->priv->header_footer_font = pango_font_description_copy (job->priv->font);
799         
800         /* calculate numbers width */
801         if (job->priv->print_numbers > 0)
802         {
803                 layout = get_line_number_layout (job, job->priv->last_line_number);
804                 job->priv->numbers_width = get_layout_width (layout) + NUMBERS_TEXT_SEPARATION;
805                 g_object_unref (layout);
806         }
807         else
808                 job->priv->numbers_width = 0.0;
809
810         get_font_ascent_descent (job, job->priv->header_footer_font, &ascent, &descent);
811
812         /* calculate header/footer height */
813         if (job->priv->print_header &&
814             (job->priv->header_format_left != NULL ||
815              job->priv->header_format_center != NULL ||
816              job->priv->header_format_right != NULL))
817                 job->priv->header_height = HEADER_FOOTER_SIZE * (ascent + descent);
818         else
819                 job->priv->header_height = 0.0;
820
821         if (job->priv->print_footer &&
822             (job->priv->footer_format_left != NULL ||
823              job->priv->footer_format_center != NULL ||
824              job->priv->footer_format_right != NULL))
825                 job->priv->footer_height = HEADER_FOOTER_SIZE * (ascent + descent);
826         else
827                 job->priv->footer_height = 0.0;
828
829         /* verify that the user provided margins are not too excesive
830          * and that we still have room for the text */
831         job->priv->text_width = (job->priv->page_width -
832                                  job->priv->doc_margin_left - job->priv->doc_margin_right -
833                                  job->priv->margin_left - job->priv->margin_right -
834                                  job->priv->numbers_width);
835         
836         job->priv->text_height = (job->priv->page_height -
837                                   job->priv->doc_margin_top - job->priv->doc_margin_bottom -
838                                   job->priv->margin_top - job->priv->margin_bottom -
839                                   job->priv->header_height - job->priv->footer_height);
840
841         /* FIXME: put some saner values than 5cm - Gustavo */
842         g_return_val_if_fail (job->priv->text_width > CM(5.0), FALSE);
843         g_return_val_if_fail (job->priv->text_height > CM(5.0), FALSE);
844
845         return TRUE;
846 }
847
848 /* We want a uniform tab width for the entire job without regard to style
849  * See comments in gtksourceview.c:calculate_real_tab_width
850  */
851 static gint
852 calculate_real_tab_width (GtkSourcePrintJob *job, guint tab_size, gchar c)
853 {
854         PangoLayout *layout;
855         gchar *tab_string;
856         gint tab_width = 0;
857
858         if (tab_size == 0)
859                 return -1;
860
861         tab_string = g_strnfill (tab_size, c);
862         layout = pango_layout_new (job->priv->pango_context);
863         pango_layout_set_text (layout, tab_string, -1);
864         g_free (tab_string);
865
866         pango_layout_get_size (layout, &tab_width, NULL);
867         g_object_unref (G_OBJECT (layout));
868         
869         return tab_width;
870 }
871
872 static gboolean
873 setup_pango_context (GtkSourcePrintJob *job)
874 {
875         PangoFontMap *font_map;
876         gint real_tab_width;
877
878         if (!job->priv->pango_context)
879         {
880                 font_map = gnome_print_pango_get_default_font_map ();
881                 job->priv->pango_context = gnome_print_pango_create_context (font_map);
882         }
883
884         pango_context_set_language (job->priv->pango_context, job->priv->language);
885         pango_context_set_font_description (job->priv->pango_context, job->priv->font);
886
887         if (job->priv->tab_array)
888         {
889                 pango_tab_array_free (job->priv->tab_array);
890                 job->priv->tab_array = NULL;
891         }
892         
893         real_tab_width = calculate_real_tab_width (job, job->priv->tabs_width, ' ');
894         if (real_tab_width > 0)
895         {
896                 job->priv->tab_array = pango_tab_array_new (1, FALSE);
897                 pango_tab_array_set_tab (job->priv->tab_array, 0, PANGO_TAB_LEFT, real_tab_width);
898         }
899         
900         return TRUE;
901 }
902
903 /* ----- Helper functions */
904
905 static gchar * 
906 font_description_to_gnome_font_name (PangoFontDescription *desc)
907 {
908         GnomeFontFace *font_face;
909         gchar *retval;
910
911         /* Will always return some font */
912         font_face = gnome_font_face_find_closest_from_pango_description (desc);
913
914         retval = g_strdup_printf("%s %f",
915                                  gnome_font_face_get_name (font_face),
916                                  (double) pango_font_description_get_size (desc) / PANGO_SCALE);
917         g_object_unref (font_face);
918
919         return retval;
920 }
921
922 /*
923  * The following routines are duplicated in gedit/gedit/gedit-prefs-manager.c
924  */
925
926 /* Do this ourselves since gnome_font_find_closest() doesn't call
927  * gnome_font_face_find_closest() (probably a gnome-print bug)
928  */
929 static void
930 face_and_size_from_full_name (const guchar   *name,
931                               GnomeFontFace **face,
932                               gdouble        *size)
933 {
934         char *copy;
935         char *str_size;
936
937         copy = g_strdup (name);
938         str_size = strrchr (copy, ' ');
939         if (str_size)
940         {
941                 *str_size = 0;
942                 str_size ++;
943                 *size = atof (str_size);
944         }
945         else
946         {
947                 *size = 12;
948         }
949
950         *face = gnome_font_face_find_closest (copy);
951         g_free (copy);
952 }
953
954 static PangoFontDescription *
955 font_description_from_gnome_font_name (const char *font_name)
956 {
957         GnomeFontFace *face;
958         PangoFontDescription *desc;
959         PangoStyle style;
960         PangoWeight weight;
961         gdouble size;
962
963         face_and_size_from_full_name (font_name, &face, &size);
964
965         /* Pango and GnomePrint have basically the same numeric weight values */
966         weight = (PangoWeight) gnome_font_face_get_weight_code (face);
967         style = gnome_font_face_is_italic (face) ? PANGO_STYLE_ITALIC : PANGO_STYLE_NORMAL;
968
969         desc = pango_font_description_new ();
970         pango_font_description_set_family (desc, gnome_font_face_get_family_name (face));
971         pango_font_description_set_weight (desc, weight);
972         pango_font_description_set_style (desc, style);
973         pango_font_description_set_size (desc, size * PANGO_SCALE);
974
975         g_object_unref (face);
976
977         return desc;
978 }
979
980 /* ---- TextStyle functions */
981
982 static TextStyle * 
983 text_style_new (GtkSourcePrintJob *job, GtkTextTag *tag)
984 {
985         TextStyle *style;
986         gboolean bg_set, fg_set;
987         
988         g_return_val_if_fail (tag != NULL && GTK_IS_TEXT_TAG (tag), NULL);
989
990         style = g_new0 (TextStyle, 1);
991
992         g_object_get (G_OBJECT (tag),
993                       "background_set", &bg_set,
994                       "foreground_set", &fg_set,
995                       "font_desc", &style->font_desc,
996                       "scale", &style->scale,
997                       "underline", &style->underline,
998                       "strikethrough", &style->strikethrough,
999                       NULL);
1000
1001         if (fg_set)
1002                 g_object_get (G_OBJECT (tag), "foreground_gdk", &style->foreground, NULL);
1003
1004         if (bg_set)
1005                 g_object_get (G_OBJECT (tag), "background_gdk", &style->background, NULL);
1006         
1007         return style;
1008 }
1009
1010 static void
1011 text_style_free (TextStyle *style)
1012 {
1013         pango_font_description_free (style->font_desc);
1014         if (style->foreground)
1015                 gdk_color_free (style->foreground);
1016         if (style->background)
1017                 gdk_color_free (style->background);
1018         g_free (style);
1019 }
1020
1021 static TextStyle * 
1022 get_style (GtkSourcePrintJob *job, const GtkTextIter *iter)
1023 {
1024         GSList *tags, *t;
1025         GtkTextTag *tag = NULL;
1026         TextStyle *style = NULL;
1027         
1028         if (job->priv->tag_styles == NULL)
1029         {
1030                 job->priv->tag_styles = g_hash_table_new_full (
1031                         g_direct_hash, g_direct_equal,
1032                         NULL, (GDestroyNotify) text_style_free);
1033         }
1034         
1035         /* get the tags at iter */
1036         tags = gtk_text_iter_get_tags (iter);
1037
1038         /* now find the GtkSourceTag (if any) which applies at iter */
1039         /* FIXME: this makes the assumption that the style at a given
1040          * iter is only determined by one GtkSourceTag (the one with
1041          * highest priority).  This is true for now, but could change
1042          * in the future - Gustavo */
1043         t = tags;
1044         while (t != NULL)
1045         {
1046                 if (GTK_IS_TEXT_TAG (t->data))
1047                         tag = t->data;
1048                 t = g_slist_next (t);
1049         }
1050         g_slist_free (tags);
1051
1052         /* now we lookup the tag style in the cache */
1053         if (tag != NULL)
1054         {
1055                 style = g_hash_table_lookup (job->priv->tag_styles, tag);
1056                 if (style == NULL)
1057                 {
1058                         /* create a style for the tag and cache it */
1059                         style = text_style_new (job, tag);
1060                         g_hash_table_insert (job->priv->tag_styles, tag, style);
1061                 }
1062         }
1063
1064         return style;
1065 }
1066
1067 /* ----- Text fetching functions */
1068
1069 static gboolean 
1070 get_text_simple (GtkSourcePrintJob *job,
1071                  GtkTextIter       *start,
1072                  GtkTextIter       *end)
1073 {
1074         GtkTextIter iter;
1075
1076         while (gtk_text_iter_compare (start, end) < 0)
1077         {
1078                 Paragraph *para;
1079                 TextSegment *seg;
1080                 
1081                 /* get a line of text */
1082                 iter = *start;
1083                 if (!gtk_text_iter_ends_line (&iter))
1084                         gtk_text_iter_forward_to_line_end (&iter);
1085                 
1086                 if (gtk_text_iter_compare (&iter, end) > 0)
1087                         iter = *end;
1088
1089                 
1090                 seg = g_new0 (TextSegment, 1);
1091                 seg->next = NULL;  /* only one segment per line, since there's no style change */
1092                 seg->style = NULL; /* use default style */
1093                 /* FIXME: handle invisible text properly.  This also
1094                  * assumes the text has no embedded images and
1095                  * stuff */
1096                 seg->text = gtk_text_iter_get_slice (start, &iter);
1097
1098                 para = g_new0 (Paragraph, 1);
1099                 para->segment = seg;
1100
1101                 /* add the line of text to the job */
1102                 job->priv->paragraphs = g_slist_prepend (job->priv->paragraphs, para);
1103
1104                 gtk_text_iter_forward_line (&iter);
1105                 
1106                 /* advance to next line */
1107                 *start = iter;
1108         }
1109         job->priv->paragraphs = g_slist_reverse (job->priv->paragraphs);
1110
1111         return TRUE;
1112 }
1113
1114 static gboolean 
1115 get_text_with_style (GtkSourcePrintJob *job,
1116                      GtkTextIter       *start,
1117                      GtkTextIter       *end)
1118 {
1119         GtkTextIter limit, next_toggle;
1120         gboolean have_toggle;
1121         GdkPixbuf *image = NULL;
1122         
1123         /* make sure the region to print is highlighted */
1124         /*_gtk_source_buffer_highlight_region (job->priv->buffer, start, end, TRUE); */
1125
1126         next_toggle = *start;
1127         have_toggle = gtk_text_iter_forward_to_tag_toggle (&next_toggle, NULL);
1128         
1129         /* FIXME: handle invisible text properly.  This also assumes
1130          * the text has no embedded images and stuff */
1131         while (gtk_text_iter_compare (start, end) < 0)
1132         {
1133                 TextStyle *style;
1134                 TextSegment *seg;
1135                 Paragraph *para;
1136                 
1137                 para = g_new0 (Paragraph, 1);
1138
1139                 /* get the style at the start of the line */
1140                 style = get_style (job, start);
1141
1142                 /* get a line of text - limit points to the end of the line */
1143                 limit = *start;
1144                 if (!gtk_text_iter_ends_line (&limit))
1145                         gtk_text_iter_forward_to_line_end (&limit);
1146                 
1147                 if (gtk_text_iter_compare (&limit, end) > 0)
1148                         limit = *end;
1149
1150                 /* create the first segment for the line */
1151                 para->segment = seg = g_new0 (TextSegment, 1);
1152                 seg->style = style;
1153
1154                 /* while the next tag toggle is within the line, we check to see
1155                  * if the style has changed at each tag toggle position, and if so,
1156                  * create new segments */
1157                 while (have_toggle && gtk_text_iter_compare (&next_toggle, &limit) < 0)
1158                 {
1159                         /* check style changes */
1160                         style = get_style (job, &next_toggle);
1161                         if (style != seg->style)
1162                         {
1163                                 TextSegment *new_seg;
1164                                 /* style has changed, thus we need to
1165                                  * create a new segment */
1166                                 /* close the current segment */
1167                                 seg->text = gtk_text_iter_get_slice (start, &next_toggle);
1168                                 if ((image = gtk_text_iter_get_pixbuf(start)) != NULL)
1169                                         seg->image = image;
1170                                 
1171                                 *start = next_toggle;
1172                                 
1173                                 new_seg = g_new0 (TextSegment, 1);
1174                                 seg->next = new_seg;
1175                                 seg = new_seg;
1176                                 seg->style = style;
1177                         }
1178
1179                         have_toggle = gtk_text_iter_forward_to_tag_toggle (&next_toggle, NULL);                 
1180                 }
1181                 
1182                 /* close the line */
1183                 seg->next = NULL;
1184                 seg->text = gtk_text_iter_get_slice (start, &limit);
1185                 if ((image = gtk_text_iter_get_pixbuf(start)) != NULL)
1186                         seg->image = image;
1187
1188                 /* add the line of text to the job */
1189                 job->priv->paragraphs = g_slist_prepend (job->priv->paragraphs, para);
1190
1191                 /* advance to next line */
1192                 *start = limit;
1193                 gtk_text_iter_forward_line (start);
1194
1195                 if (gtk_text_iter_compare (&next_toggle, start) < 0) {
1196                         next_toggle = *start;
1197                         have_toggle = gtk_text_iter_forward_to_tag_toggle (&next_toggle, NULL);
1198                 }
1199         }
1200         job->priv->paragraphs = g_slist_reverse (job->priv->paragraphs);
1201
1202         return TRUE;
1203 }
1204
1205 static gboolean 
1206 get_text_to_print (GtkSourcePrintJob *job,
1207                    const GtkTextIter *start,
1208                    const GtkTextIter *end)
1209 {
1210         GtkTextIter _start, _end;
1211         gboolean retval;
1212         
1213         g_return_val_if_fail (start != NULL && end != NULL, FALSE);
1214         g_return_val_if_fail (job->priv->buffer != NULL, FALSE);
1215
1216         _start = *start;
1217         _end = *end;
1218
1219         /* erase any previous data */
1220         if (job->priv->paragraphs != NULL)
1221         {
1222                 free_paragraphs (job->priv->paragraphs);
1223                 job->priv->paragraphs = NULL;
1224         }
1225         if (job->priv->tag_styles != NULL)
1226         {
1227                 g_hash_table_destroy (job->priv->tag_styles);
1228                 job->priv->tag_styles = NULL;
1229         }
1230
1231         /* provide ordered iters */
1232         gtk_text_iter_order (&_start, &_end);
1233
1234         /* save the first and last line numbers for future reference */
1235         job->priv->first_line_number = gtk_text_iter_get_line (&_start) + 1;
1236         job->priv->last_line_number = gtk_text_iter_get_line (&_end) + 1;
1237
1238         if (!job->priv->highlight)
1239                 retval = get_text_simple (job, &_start, &_end);
1240         else
1241                 retval = get_text_with_style (job, &_start, &_end);
1242
1243         if (retval && job->priv->paragraphs == NULL)
1244         {
1245                 Paragraph *para;
1246                 TextSegment *seg;
1247                 
1248                 /* add an empty line to allow printing empty documents */
1249                 seg = g_new0 (TextSegment, 1);
1250                 seg->next = NULL;
1251                 seg->style = NULL; /* use default style */
1252                 seg->text = g_strdup ("");
1253
1254                 para = g_new0 (Paragraph, 1);
1255                 para->segment = seg;
1256
1257                 job->priv->paragraphs = g_slist_prepend (job->priv->paragraphs, para);
1258         }
1259
1260         return retval;
1261 }
1262
1263 /* ----- Pagination functions */
1264
1265 static void
1266 add_attribute_to_list (PangoAttribute *attr, 
1267                        PangoAttrList  *list,
1268                        guint           index,
1269                        gsize           len)
1270 {
1271         attr->start_index = index;
1272         attr->end_index = index + len;
1273         pango_attr_list_insert (list, attr);
1274 }
1275
1276 static void *
1277 create_layout_for_para (GtkSourcePrintJob *job,
1278                         Paragraph         *para,
1279                         gboolean          *is_image)
1280 {
1281         GString *text;
1282         PangoLayout *layout;
1283         PangoAttrList *attrs;
1284         TextSegment *seg;
1285         gint index;
1286         GdkPixbuf *image = NULL;
1287         text = g_string_new (NULL);
1288         attrs = pango_attr_list_new ();
1289         
1290         seg = para->segment;
1291         index = 0;
1292
1293         while (seg != NULL)
1294         {
1295                 gsize seg_len = strlen (seg->text);
1296                 g_string_append (text, seg->text);
1297
1298                 if (seg->style)
1299                 {
1300                         PangoAttribute *attr;
1301
1302                         attr = pango_attr_font_desc_new (seg->style->font_desc);
1303                         add_attribute_to_list (attr, attrs, index, seg_len);
1304
1305                         if (seg->style->scale != PANGO_SCALE_MEDIUM) 
1306                         {
1307                                 attr = pango_attr_scale_new (seg->style->scale);
1308                                 add_attribute_to_list (attr, attrs, index, seg_len);
1309                         }
1310
1311                         if (seg->style->foreground)
1312                         {
1313                                 attr = pango_attr_foreground_new (seg->style->foreground->red,
1314                                                                   seg->style->foreground->green,
1315                                                                   seg->style->foreground->blue);
1316                                 add_attribute_to_list (attr, attrs, index, seg_len);
1317                         }
1318
1319                         if (seg->style->background)
1320                         {
1321                                 attr = pango_attr_background_new (seg->style->background->red,
1322                                                                   seg->style->background->green,
1323                                                                   seg->style->background->blue);
1324                                 add_attribute_to_list (attr, attrs, index, seg_len);
1325                         }
1326
1327                         if (seg->style->strikethrough)
1328                         {
1329                                 attr = pango_attr_strikethrough_new (TRUE);
1330                                 add_attribute_to_list (attr, attrs, index, seg_len);
1331                         }
1332
1333                         if (seg->style->underline != PANGO_UNDERLINE_NONE)
1334                         {
1335                                 attr = pango_attr_underline_new (seg->style->underline);
1336                                 add_attribute_to_list (attr, attrs, index, seg_len);
1337                         }
1338                 }
1339
1340                 if (seg->image) {
1341                         image = seg->image;
1342                 }
1343
1344                 index += seg_len;
1345                 seg = seg->next;
1346         }
1347
1348         if (image != NULL) {
1349                 *is_image = TRUE;
1350                 return image;
1351         }
1352
1353         layout = pango_layout_new (job->priv->pango_context);
1354         
1355         pango_layout_set_width (layout, job->priv->text_width * PANGO_SCALE);
1356         
1357         switch (job->priv->wrap_mode)   {
1358         case GTK_WRAP_CHAR:
1359                 pango_layout_set_wrap (layout, PANGO_WRAP_CHAR);
1360                 break;
1361         case GTK_WRAP_WORD:
1362                 pango_layout_set_wrap (layout, PANGO_WRAP_WORD);
1363                 break;
1364         case GTK_WRAP_WORD_CHAR:
1365                 pango_layout_set_wrap (layout, PANGO_WRAP_WORD_CHAR);
1366                 break;
1367         case GTK_WRAP_NONE:
1368                 /* FIXME: hack 
1369                  * Ellipsize the paragraph when text wrapping is disabled.
1370                  * Another possibility would be to set the width so the text 
1371                  * breaks into multiple lines, and paginate/render just the 
1372                  * first one.
1373                  * See also Comment #23 by Owen on bug #143874.
1374                  */
1375
1376                 /* orph says to comment this out and commit it.
1377                    PANGO_ELLIPSIZE_END is not available in pango
1378                    1.4.1, at least, and he says this code is never
1379                    used. */
1380                 /*pango_layout_set_ellipsize (layout, PANGO_ELLIPSIZE_END);*/
1381
1382                 break;
1383         }
1384
1385         if (job->priv->tab_array)
1386                 pango_layout_set_tabs (layout, job->priv->tab_array);
1387         
1388         pango_layout_set_text (layout, text->str, text->len);
1389         pango_layout_set_attributes (layout, attrs);
1390         *is_image = FALSE;
1391
1392         /* FIXME: <horrible-hack> 
1393          * For empty paragraphs, pango_layout_iter_get_baseline() returns 0,
1394          * so I check this condition and add a space character to force 
1395          * the calculation of the baseline. I don't like that, but I
1396          * didn't find a better way to do it. Note that a paragraph is 
1397          * considered empty either when it has no characters, or when 
1398          * it only has tabs.
1399          * See comment #22 and #23 on bug #143874.
1400          */
1401         if (job->priv->print_numbers > 0)
1402         {
1403                 PangoLayoutIter *iter;
1404                 iter = pango_layout_get_iter (layout);
1405                 if (pango_layout_iter_get_baseline (iter) == 0)
1406                 {
1407                         g_string_append_c (text, ' ');
1408                         pango_layout_set_text (layout, text->str, text->len);
1409                 }
1410                 pango_layout_iter_free (iter);
1411         }
1412         /* FIXME: </horrible-hack> */
1413         
1414         g_string_free (text, TRUE);
1415         pango_attr_list_unref (attrs);
1416
1417         return layout;
1418 }
1419
1420 /* The break logic in this function needs to match that in print_paragraph */
1421 static void
1422 paginate_paragraph (GtkSourcePrintJob *job,
1423                     Paragraph         *para)
1424 {
1425         PangoLayout *layout;
1426         PangoLayoutIter *iter;
1427         PangoRectangle logical_rect;
1428         gdouble max;
1429         gdouble page_skip;
1430         GdkPixbuf *image;
1431         void *tmp;
1432         gboolean is_image = FALSE;
1433         
1434         tmp = create_layout_for_para (job, para, &is_image);
1435         if (!is_image) {
1436                 layout = (PangoLayout *)tmp;
1437                 image  = NULL;
1438         } else {
1439                 image  = (GdkPixbuf *)tmp;
1440                 layout = NULL;
1441         }
1442
1443         if (image == NULL) {
1444                 iter = pango_layout_get_iter (layout);
1445
1446                 max = 0;
1447                 page_skip = 0;
1448
1449                 do
1450                 {
1451                         pango_layout_iter_get_line_extents (iter, NULL, &logical_rect);
1452                         max = (gdouble) (logical_rect.y + logical_rect.height) / PANGO_SCALE;
1453
1454                         if (max - page_skip > job->priv->available_height)
1455                         {
1456                                 /* "create" a new page */
1457                                 job->priv->page_count++;
1458                                 job->priv->available_height = job->priv->text_height;
1459                                 page_skip = (gdouble) logical_rect.y / PANGO_SCALE;
1460                         }
1461
1462                 }
1463                 while (pango_layout_iter_next_line (iter));
1464
1465                 job->priv->available_height -= max - page_skip;
1466
1467                 pango_layout_iter_free (iter);
1468                 g_object_unref (layout);
1469         } else {
1470                 gint max_height = job->priv->available_height;
1471                 gint image_height = gdk_pixbuf_get_height(image);
1472                 gint image_width = gdk_pixbuf_get_width(image);
1473                 gint scaled_height = 0, scaled_width = 0;
1474                 image_viewer_get_resized_size(image_width,
1475                                          image_height,
1476                                          job->priv->text_width, 
1477                                          job->priv->text_height,
1478                                          &scaled_width, &scaled_height);
1479
1480                 if (scaled_height > max_height) {
1481                         job->priv->page_count++;
1482                         job->priv->available_height = job->priv->text_height;
1483                 } else {
1484                         job->priv->available_height -= scaled_height;
1485                 }
1486         }
1487
1488 }
1489
1490 static gboolean 
1491 paginate_text (GtkSourcePrintJob *job)
1492 {
1493         GSList *l;
1494         guint line_number;
1495         
1496         /* set these to zero so the first break_line creates a new page */
1497         job->priv->page_count = 0;
1498         job->priv->available_height = 0;
1499         line_number = job->priv->first_line_number;
1500         l = job->priv->paragraphs;
1501         while (l != NULL)
1502         {
1503                 Paragraph *para = l->data;
1504
1505                 para->line_number = line_number;
1506                 paginate_paragraph (job, para);
1507                 
1508                 line_number++;
1509                 l = g_slist_next (l);
1510         }
1511
1512         /* FIXME: do we have any error condition which can force us to
1513          * return %FALSE? - Gustavo */
1514         return TRUE;
1515 }
1516
1517 /* ---- Printing functions */
1518
1519 static void
1520 begin_page (GtkSourcePrintJob *job)
1521 {
1522         gnome_print_beginpage (job->priv->print_ctxt, NULL);
1523
1524         g_signal_emit (job, print_job_signals [BEGIN_PAGE], 0);
1525 }
1526
1527 static void
1528 end_page (GtkSourcePrintJob *job)
1529 {
1530         gnome_print_showpage (job->priv->print_ctxt);
1531 }
1532
1533 static void 
1534 print_line_number (GtkSourcePrintJob *job,
1535                    guint              line_number,
1536                    gdouble            x,
1537                    gdouble            y)
1538 {
1539         PangoLayout *layout;
1540
1541         layout = get_line_number_layout (job, line_number);
1542
1543         x = x + job->priv->numbers_width - get_layout_width (layout) - NUMBERS_TEXT_SEPARATION;
1544         gnome_print_moveto (job->priv->print_ctxt, x, y);
1545         
1546         show_first_layout_line (job->priv->print_ctxt, layout);
1547         
1548         g_object_unref (layout);
1549 }       
1550
1551 /* The break logic in this function needs to match that in paginate_paragraph
1552  *
1553  * @start_line is the first line in the paragraph to print
1554  * @y is updated to the position after the portion of the paragraph we printed
1555  * @baseline_out is set to the baseline of the first line of the paragraph
1556  *   if we printed it. (And not set otherwise)
1557  * 
1558  * Returns the first unprinted line in the paragraph (unprinted because it
1559  * flowed onto the next page) or -1 if the entire paragraph was printed.
1560  */
1561 static gint
1562 print_paragraph (GtkSourcePrintJob *job,
1563                  Paragraph         *para,
1564                  gint               start_line,
1565                  gdouble            x,
1566                  gdouble           *y,
1567                  gdouble           *baseline_out,
1568                  gboolean           force_fit)
1569 {
1570         PangoLayout *layout;
1571         PangoLayoutIter *iter;
1572         PangoRectangle logical_rect;
1573         int current_line;
1574         gdouble max;
1575         gdouble page_skip;
1576         gdouble baseline;
1577         int result = -1;
1578         GdkPixbuf *image;
1579         void *tmp;
1580         gboolean is_image;
1581
1582         tmp = create_layout_for_para (job, para, &is_image);
1583         if (!is_image) {
1584                 layout = (PangoLayout *)tmp;
1585                 image  = NULL;
1586         } else {
1587                 image  = (GdkPixbuf *)tmp;
1588                 layout = NULL;
1589         }
1590
1591         if (!is_image) {
1592                 iter = pango_layout_get_iter (layout);
1593
1594                 /* Skip over lines already printed on previous page(s) */
1595                 for (current_line = 0; current_line < start_line; current_line++)
1596                         pango_layout_iter_next_line (iter);
1597
1598                 max = 0;
1599                 page_skip = 0;
1600
1601                 do
1602                 {
1603                         pango_layout_iter_get_line_extents (iter, NULL, &logical_rect);
1604                         max = (gdouble) (logical_rect.y + logical_rect.height) / PANGO_SCALE;
1605
1606                         if (current_line == start_line)
1607                                 page_skip = (gdouble) logical_rect.y / PANGO_SCALE;
1608
1609                         if (max - page_skip > job->priv->available_height)
1610                         {
1611                                 result = current_line; /* Save position for next page */
1612                                 break;
1613                         }
1614
1615                         baseline = (gdouble) pango_layout_iter_get_baseline (iter) / PANGO_SCALE;
1616                         baseline = *y + page_skip - baseline; /* Adjust to global coordinates */
1617                         if (current_line == 0)
1618                                 *baseline_out = baseline;
1619
1620                         gnome_print_moveto (job->priv->print_ctxt,
1621                                             x + (gdouble) logical_rect.x / PANGO_SCALE,
1622                                             baseline);
1623                         gnome_print_pango_layout_line (job->priv->print_ctxt,
1624                                                        pango_layout_iter_get_line (iter));
1625
1626                         current_line++;
1627                 }
1628                 while (pango_layout_iter_next_line (iter));
1629
1630                 job->priv->available_height -= max - page_skip;
1631                 *y -= max - page_skip;
1632
1633                 pango_layout_iter_free (iter);
1634                 g_object_unref (layout);
1635         } else {
1636                 gint max_height = job->priv->available_height;
1637                 gint image_height = gdk_pixbuf_get_height(image);
1638                 gint image_width = gdk_pixbuf_get_width(image);
1639                 gint scaled_height = 0, scaled_width = 0;
1640                 GdkPixbuf *scaled_image = NULL;
1641                 image_viewer_get_resized_size(image_width,
1642                                          image_height,
1643                                          job->priv->text_width, 
1644                                          job->priv->text_height,
1645                                          &scaled_width, &scaled_height);
1646
1647                 if (scaled_height > max_height) {
1648                         /* next page */
1649                         return 0;
1650                 } else {
1651                         scaled_image = gdk_pixbuf_scale_simple
1652                                         (image, scaled_width, scaled_height, 
1653                                          GDK_INTERP_BILINEAR);
1654
1655                         gnome_print_moveto(job->priv->print_ctxt,
1656                                             x, (gdouble)*y);
1657                         gnome_print_gsave(job->priv->print_ctxt);
1658                         gnome_print_translate(job->priv->print_ctxt, 
1659                                               x, *y - scaled_height);
1660                         gnome_print_scale(job->priv->print_ctxt, 
1661                                           scaled_width,
1662                                           scaled_height);
1663
1664                         if (gdk_pixbuf_get_has_alpha(image))
1665                                 gnome_print_rgbaimage  (job->priv->print_ctxt,
1666                                                         gdk_pixbuf_get_pixels    (scaled_image),
1667                                                         gdk_pixbuf_get_width     (scaled_image),
1668                                                         gdk_pixbuf_get_height    (scaled_image),
1669                                                         gdk_pixbuf_get_rowstride (scaled_image));
1670                         else
1671                                 gnome_print_rgbimage  (job->priv->print_ctxt,
1672                                                        gdk_pixbuf_get_pixels    (scaled_image),
1673                                                        gdk_pixbuf_get_width     (scaled_image),
1674                                                        gdk_pixbuf_get_height    (scaled_image),
1675                                                        gdk_pixbuf_get_rowstride (scaled_image));
1676                         g_object_unref(scaled_image);
1677                         gnome_print_grestore(job->priv->print_ctxt);
1678
1679                         job->priv->available_height -= scaled_height;
1680                         *y -= scaled_height;
1681                         return -1;
1682
1683                 }
1684         }
1685         return result;
1686 }
1687
1688 static void
1689 print_page (GtkSourcePrintJob *job)
1690 {
1691         GSList *l;
1692         gdouble x, y;
1693         gint line;
1694         gboolean force_fit = TRUE;
1695         
1696         job->priv->page++;
1697         
1698         
1699         begin_page (job);
1700         job->priv->available_height = job->priv->text_height;
1701
1702         y = job->priv->page_height -
1703                 job->priv->doc_margin_top - job->priv->margin_top -
1704                 job->priv->header_height;
1705         x = job->priv->doc_margin_left + job->priv->margin_left +
1706                 job->priv->numbers_width;
1707         l = job->priv->current_paragraph;
1708         line = job->priv->current_paragraph_line;
1709
1710         while (l != NULL)
1711         {
1712                 Paragraph *para = l->data;
1713                 gdouble baseline;
1714                 gint last_line = line;
1715                 
1716                 line = print_paragraph (job, para, line, x, &y, &baseline, force_fit);
1717
1718                 if (last_line == 0 && line != 0)
1719                 {
1720                         /* We printed the first line of a paragraph */
1721                         if (job->priv->print_numbers > 0 &&
1722                             ((para->line_number % job->priv->print_numbers) == 0))
1723                                 print_line_number (job,
1724                                                    para->line_number,
1725                                                    job->priv->doc_margin_left +
1726                                                    job->priv->margin_left,
1727                                                    baseline);
1728
1729                         job->priv->printed_lines++;
1730                 }
1731
1732                 if (line >= 0)
1733                         break;  /* Didn't all fit on this page */
1734                 
1735                 l = l->next;
1736                 line = 0;
1737                 force_fit = FALSE;
1738         }
1739         end_page (job);
1740         job->priv->current_paragraph = l;
1741         job->priv->current_paragraph_line = line;
1742 }
1743
1744 static void
1745 setup_for_print (GtkSourcePrintJob *job)
1746 {
1747         job->priv->current_paragraph = job->priv->paragraphs;
1748         job->priv->page = 0;
1749         job->priv->printed_lines = 0;
1750
1751         if (job->priv->print_job != NULL)
1752                 g_object_unref (job->priv->print_job);
1753         if (job->priv->print_ctxt != NULL)
1754                 g_object_unref (job->priv->print_ctxt);
1755         
1756         job->priv->print_job = gnome_print_job_new (job->priv->config);
1757         job->priv->print_ctxt = gnome_print_job_get_context (job->priv->print_job);
1758
1759         gnome_print_pango_update_context (job->priv->pango_context, job->priv->print_ctxt);
1760 }
1761
1762 static void
1763 print_job (GtkSourcePrintJob *job)
1764 {
1765         while (job->priv->current_paragraph != NULL)
1766                 print_page (job);
1767
1768         gnome_print_job_close (job->priv->print_job);
1769 }
1770
1771 static gboolean
1772 idle_printing_handler (GtkSourcePrintJob *job)
1773 {
1774         g_assert (job->priv->current_paragraph != NULL);
1775
1776         print_page (job);
1777
1778         if (job->priv->current_paragraph == NULL)
1779         {
1780                 gnome_print_job_close (job->priv->print_job);
1781                 job->priv->printing = FALSE;
1782                 job->priv->idle_printing_tag = 0;
1783
1784                 g_signal_emit (job, print_job_signals [FINISHED], 0);
1785                 /* after this the print job object is possibly
1786                  * destroyed (common use case) */
1787                 
1788                 return FALSE;
1789         }
1790         return TRUE;
1791 }
1792
1793
1794 /* Public API ------------------- */
1795
1796 /**
1797  * gtk_source_print_job_new:
1798  * @config: an optional #GnomePrintConfig object.
1799  * 
1800  * Creates a new print job object, initially setting the print configuration.
1801  * 
1802  * Return value: the new print job object.
1803  **/
1804 GtkSourcePrintJob *
1805 gtk_source_print_job_new (GnomePrintConfig  *config)
1806 {
1807         GtkSourcePrintJob *job;
1808
1809         g_return_val_if_fail (config == NULL || GNOME_IS_PRINT_CONFIG (config), NULL);
1810
1811         job = GTK_SOURCE_PRINT_JOB (g_object_new (GTK_TYPE_SOURCE_PRINT_JOB, NULL));
1812         if (config != NULL)
1813                 gtk_source_print_job_set_config (job, config);
1814
1815         return job;
1816 }
1817
1818 /**
1819  * gtk_source_print_job_new_with_buffer:
1820  * @config: an optional #GnomePrintConfig.
1821  * @buffer: the #GtkTextBuffer to print (might be %NULL).
1822  * 
1823  * Creates a new print job to print @buffer.
1824  * 
1825  * Return value: a new print job object.
1826  **/
1827 GtkSourcePrintJob *
1828 gtk_source_print_job_new_with_buffer (GnomePrintConfig  *config,
1829                                       GtkTextBuffer   *buffer)
1830 {
1831         GtkSourcePrintJob *job;
1832
1833         g_return_val_if_fail (config == NULL || GNOME_IS_PRINT_CONFIG (config), NULL);
1834         g_return_val_if_fail (buffer == NULL || GTK_IS_TEXT_BUFFER (buffer), NULL);
1835
1836         job = gtk_source_print_job_new (config);
1837         if (buffer != NULL)
1838                 gtk_source_print_job_set_buffer (job, buffer);
1839
1840         return job;
1841 }
1842
1843 /* --- print job basic configuration */
1844
1845 /**
1846  * gtk_source_print_job_set_config:
1847  * @job: a #GtkSourcePrintJob.
1848  * @config: a #GnomePrintConfig object to get printing configuration from.
1849  * 
1850  * Sets the print configuration for the job.  If you don't set a
1851  * configuration object for the print job, when needed one will be
1852  * created with gnome_print_config_default().
1853  **/
1854 void
1855 gtk_source_print_job_set_config (GtkSourcePrintJob *job,
1856                                  GnomePrintConfig  *config)
1857 {
1858         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
1859         g_return_if_fail (GNOME_IS_PRINT_CONFIG (config));
1860         g_return_if_fail (!job->priv->printing);
1861         
1862         if (config == job->priv->config)
1863                 return;
1864         
1865         if (job->priv->config != NULL)
1866                 gnome_print_config_unref (job->priv->config);
1867
1868         job->priv->config = config;
1869         gnome_print_config_ref (config);
1870
1871         g_object_notify (G_OBJECT (job), "config");
1872 }
1873
1874 /**
1875  * gtk_source_print_job_get_config:
1876  * @job: a #GtkSourcePrintJob.
1877  * 
1878  * Gets the current #GnomePrintConfig the print job will use.  If not
1879  * previously set, this will create a default configuration and return
1880  * it.  The returned object reference is owned by the print job.
1881  * 
1882  * Return value: the #GnomePrintConfig for the print job.
1883  **/
1884 GnomePrintConfig * 
1885 gtk_source_print_job_get_config (GtkSourcePrintJob *job)
1886 {
1887         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
1888
1889         ensure_print_config (job);
1890         
1891         return job->priv->config;
1892 }
1893
1894 /**
1895  * gtk_source_print_job_set_buffer:
1896  * @job: a #GtkSourcePrintJob.
1897  * @buffer: a #GtkTextBuffer.
1898  * 
1899  * Sets the #GtkTextBuffer the print job will print.  You need to
1900  * specify a buffer to print, either by the use of this function or by
1901  * creating the print job with gtk_source_print_job_new_with_buffer().
1902  **/
1903 void 
1904 gtk_source_print_job_set_buffer (GtkSourcePrintJob *job,
1905                                  GtkTextBuffer   *buffer)
1906 {
1907         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
1908         g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1909         g_return_if_fail (!job->priv->printing);
1910
1911         if (buffer == job->priv->buffer)
1912                 return;
1913         
1914         if (job->priv->buffer != NULL)
1915                 g_object_unref (job->priv->buffer);
1916
1917         job->priv->buffer = buffer;
1918         g_object_ref (buffer);
1919
1920         g_object_notify (G_OBJECT (job), "buffer");
1921 }
1922
1923 /**
1924  * gtk_source_print_job_get_buffer:
1925  * @job: a #GtkSourcePrintJob.
1926  * 
1927  * Gets the #GtkTextBuffer the print job would print.  The returned
1928  * object reference (if non %NULL) is owned by the job object and
1929  * should not be unreferenced.
1930  * 
1931  * Return value: the #GtkTextBuffer to print.
1932  **/
1933 GtkTextBuffer *
1934 gtk_source_print_job_get_buffer (GtkSourcePrintJob *job)
1935 {
1936         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
1937
1938         return job->priv->buffer;
1939 }
1940
1941 /* --- print job layout and style configuration */
1942
1943 /**
1944  * gtk_source_print_job_set_tabs_width:
1945  * @job: a #GtkSourcePrintJob.
1946  * @tabs_width: the number of equivalent spaces for a tabulation.
1947  * 
1948  * Sets the width (in equivalent spaces) of tabulations for the
1949  * printed text.  The width in printing units will be calculated as
1950  * the width of a string containing @tabs_width spaces of the default
1951  * font.  Tabulation stops are set for the full width of printed text.
1952  **/
1953 void 
1954 gtk_source_print_job_set_tabs_width (GtkSourcePrintJob *job,
1955                                      guint              tabs_width)
1956 {
1957         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
1958         g_return_if_fail (!job->priv->printing);
1959
1960         if (tabs_width == job->priv->tabs_width)
1961                 return;
1962         
1963         job->priv->tabs_width = tabs_width;
1964
1965         g_object_notify (G_OBJECT (job), "tabs_width");
1966 }
1967
1968 /**
1969  * gtk_source_print_job_get_tabs_width:
1970  * @job: a #GtkSourcePrintJob.
1971  * 
1972  * Determines the configured width (in equivalent spaces) of
1973  * tabulations.  The default value is 8.
1974  * 
1975  * Return value: the width (in equivalent spaces) of a tabulation.
1976  **/
1977 guint 
1978 gtk_source_print_job_get_tabs_width (GtkSourcePrintJob *job)
1979 {
1980         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), 0);
1981
1982         return job->priv->tabs_width;
1983 }
1984
1985 /**
1986  * gtk_source_print_job_set_wrap_mode:
1987  * @job: a #GtkSourcePrintJob.
1988  * @wrap: the wrap mode.
1989  * 
1990  * Sets the wrap mode for lines of text larger than the printable
1991  * width.  See #GtkWrapMode for a definition of the possible values.
1992  **/
1993 void 
1994 gtk_source_print_job_set_wrap_mode (GtkSourcePrintJob *job,
1995                                     GtkWrapMode        wrap)
1996 {
1997         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
1998         g_return_if_fail (!job->priv->printing);
1999
2000         if (wrap == job->priv->wrap_mode)
2001                 return;
2002         
2003         job->priv->wrap_mode = wrap;
2004
2005         g_object_notify (G_OBJECT (job), "wrap_mode");
2006 }
2007
2008 /**
2009  * gtk_source_print_job_get_wrap_mode:
2010  * @job: a #GtkSourcePrintJob.
2011  * 
2012  * Determines the wrapping style for text lines wider than the
2013  * printable width.  The default is no wrapping.
2014  * 
2015  * Return value: the current wrapping mode for the print job.
2016  **/
2017 GtkWrapMode 
2018 gtk_source_print_job_get_wrap_mode (GtkSourcePrintJob *job)
2019 {
2020         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), GTK_WRAP_NONE);
2021
2022         return job->priv->wrap_mode;
2023 }
2024
2025 /**
2026  * gtk_source_print_job_set_highlight:
2027  * @job: a #GtkSourcePrintJob.
2028  * @highlight: %TRUE if the printed text should be highlighted.
2029  * 
2030  * Sets whether the printed text will be highlighted according to the
2031  * buffer rules.  Both color and font style are applied.
2032  **/
2033 void 
2034 gtk_source_print_job_set_highlight (GtkSourcePrintJob *job,
2035                                     gboolean           highlight)
2036 {
2037         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2038         g_return_if_fail (!job->priv->printing);
2039
2040         highlight = (highlight != FALSE);
2041         
2042         if (highlight == job->priv->highlight)
2043                 return;
2044         
2045         job->priv->highlight = highlight;
2046
2047         g_object_notify (G_OBJECT (job), "highlight");
2048 }
2049
2050 /**
2051  * gtk_source_print_job_get_highlight:
2052  * @job: a #GtkSourcePrintJob.
2053  * 
2054  * Determines if the job is configured to print the text highlighted
2055  * with colors and font styles.  Note that highlighting will happen
2056  * only if the buffer to print has highlighting activated.
2057  * 
2058  * Return value: %TRUE if the printed output will be highlighted.
2059  **/
2060 gboolean 
2061 gtk_source_print_job_get_highlight (GtkSourcePrintJob *job)
2062 {
2063         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), FALSE);
2064
2065         return job->priv->highlight;
2066 }
2067
2068 /**
2069  * gtk_source_print_job_set_font_desc:
2070  * @job: a #GtkSourcePrintJob.
2071  * @desc: the #PangoFontDescription for the default font
2072  * 
2073  * Sets the default font for the printed text.
2074  **/
2075 void 
2076 gtk_source_print_job_set_font_desc (GtkSourcePrintJob    *job,
2077                                     PangoFontDescription *desc)
2078 {
2079         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2080         g_return_if_fail (desc != NULL);
2081         g_return_if_fail (!job->priv->printing);
2082
2083         desc = pango_font_description_copy (desc);
2084         if (job->priv->font != NULL)
2085                 pango_font_description_free (job->priv->font);
2086         job->priv->font = desc;
2087         g_object_freeze_notify (G_OBJECT (job));
2088         g_object_notify (G_OBJECT (job), "font");
2089         g_object_notify (G_OBJECT (job), "font_desc");
2090         g_object_thaw_notify (G_OBJECT (job));
2091 }
2092
2093 /**
2094  * gtk_source_print_job_set_font:
2095  * @job: a #GtkSourcePrintJob.
2096  * @font_name: the name of the default font.
2097  * 
2098  * Sets the default font for the printed text.  @font_name should be a
2099  * <emphasis>full font name</emphasis> GnomePrint can understand
2100  * (e.g. &quot;Monospace Regular 10.0&quot;).
2101  *
2102  * Note that @font_name is a #GnomeFont name not a Pango font
2103  * description string. This function is deprecated since #GnomeFont is
2104  * no longer used when implementing printing for GtkSourceView; you
2105  * should use gtk_source_print_job_set_font_desc() instead.
2106  **/
2107 void 
2108 gtk_source_print_job_set_font (GtkSourcePrintJob *job,
2109                                const gchar       *font_name)
2110 {
2111         PangoFontDescription *desc;
2112         
2113         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2114         g_return_if_fail (font_name != NULL);
2115         g_return_if_fail (!job->priv->printing);
2116
2117         desc = font_description_from_gnome_font_name (font_name);
2118         if (desc)
2119         {
2120                 gtk_source_print_job_set_font_desc (job, desc);
2121                 pango_font_description_free (desc);
2122         }
2123 }
2124
2125 /**
2126  * gtk_source_print_job_get_font_desc:
2127  * @job: a #GtkSourcePrintJob.
2128  * 
2129  * Determines the default font to be used for the printed text.  The
2130  * returned string is of the form &quot;Fontfamily Style Size&quot;,
2131  * for example &quot;Monospace Regular 10.0&quot;.  The returned value
2132  * should be freed when no longer needed.
2133  * 
2134  * Return value: the current text font description. This value is
2135  *  owned by the job and must not be modified or freed.
2136  **/
2137 PangoFontDescription *
2138 gtk_source_print_job_get_font_desc (GtkSourcePrintJob *job)
2139 {
2140         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
2141
2142         ensure_print_config (job);
2143         
2144         return job->priv->font;
2145 }
2146
2147 /**
2148  * gtk_source_print_job_get_font:
2149  * @job: a #GtkSourcePrintJob.
2150  * 
2151  * Determines the default font to be used for the printed text.  The
2152  * returned string is of the form &quot;Fontfamily Style Size&quot;,
2153  * for example &quot;Monospace Regular 10.0&quot;.  The returned value
2154  * should be freed when no longer needed.
2155  * 
2156  * Note that the result is a #GnomeFont name not a Pango font
2157  * description string. This function is deprecated since #GnomeFont is
2158  * no longer used when implementing printing for GtkSourceView; you
2159  * should use gtk_source_print_job_get_font_desc() instead.
2160  *
2161  * Return value: a newly allocated string with the name of the current
2162  * text font.
2163  **/
2164 gchar *
2165 gtk_source_print_job_get_font (GtkSourcePrintJob *job)
2166 {
2167         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
2168
2169         ensure_print_config (job);
2170         
2171         return font_description_to_gnome_font_name (job->priv->font);
2172 }
2173
2174 /**
2175  * gtk_source_print_job_setup_from_view:
2176  * @job: a #GtkSourcePrintJob.
2177  * @view: a #GtkSourceView to get configuration from.
2178  * 
2179  * Convenience function to set several configuration options at once,
2180  * so that the printed output matches @view.  The options set are
2181  * buffer (if not set already), tabs width, highlighting, wrap mode
2182  * and default font.
2183  **/
2184 void 
2185 gtk_source_print_job_setup_from_view (GtkSourcePrintJob *job,
2186                                       GtkTextView       *view)
2187 {
2188         GtkTextBuffer *buffer = NULL;
2189         PangoContext *pango_context;
2190         
2191         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2192         g_return_if_fail (!job->priv->printing);
2193
2194         buffer = gtk_text_view_get_buffer (view);
2195         
2196         if (job->priv->buffer == NULL && buffer != NULL)
2197                 gtk_source_print_job_set_buffer (job, buffer);
2198
2199         /* gtk_source_print_job_set_tabs_width (job, gtk_source_view_get_tabs_width (view)); */
2200         gtk_source_print_job_set_highlight (job, TRUE);
2201         gtk_source_print_job_set_wrap_mode (job, gtk_text_view_get_wrap_mode (view));
2202
2203         pango_context = gtk_widget_get_pango_context (GTK_WIDGET (view));
2204         gtk_source_print_job_set_font_desc (job, 
2205                                             pango_context_get_font_description (pango_context));
2206 }
2207
2208 /**
2209  * gtk_source_print_job_set_numbers_font_desc:
2210  * @job: a #GtkSourcePrintJob.
2211  * @desc: the #PangoFontDescription for the font for line numbers, or %NULL
2212  * 
2213  * Sets the font for printing line numbers on the left margin.  If
2214  * NULL is supplied, the default font (i.e. the one being used for the
2215  * text) will be used instead.
2216  **/
2217 void 
2218 gtk_source_print_job_set_numbers_font_desc (GtkSourcePrintJob    *job,
2219                                             PangoFontDescription *desc)
2220 {
2221         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2222         g_return_if_fail (!job->priv->printing);
2223         
2224         if (desc)
2225                 desc = pango_font_description_copy (desc);
2226         if (job->priv->numbers_font != NULL)
2227                 pango_font_description_free (job->priv->numbers_font);
2228         job->priv->numbers_font = desc;
2229         g_object_freeze_notify (G_OBJECT (job));
2230         g_object_notify (G_OBJECT (job), "numbers_font");
2231         g_object_notify (G_OBJECT (job), "numbers_font_desc");
2232         g_object_thaw_notify (G_OBJECT (job));
2233 }
2234
2235 /**
2236  * gtk_source_print_job_set_numbers_font:
2237  * @job: a #GtkSourcePrintJob.
2238  * @font_name: the full name of the font for line numbers, or %NULL.
2239  * 
2240  * Sets the font for printing line numbers on the left margin.  If
2241  * %NULL is supplied, the default font (i.e. the one being used for the
2242  * text) will be used instead.
2243  *
2244  * Note that @font_name is a #GnomeFont name not a Pango font
2245  * description string. This function is deprecated since #GnomeFont is
2246  * no longer used when implementing printing for GtkSourceView; you
2247  * should use gtk_source_print_job_set_numbers_font_desc() instead.
2248  **/
2249 void 
2250 gtk_source_print_job_set_numbers_font (GtkSourcePrintJob *job,
2251                                        const gchar       *font_name)
2252 {
2253         PangoFontDescription *desc;
2254         
2255         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2256         g_return_if_fail (!job->priv->printing);
2257
2258         if (font_name != NULL)
2259         {
2260                 desc = font_description_from_gnome_font_name (font_name);
2261                 if (desc)
2262                 {
2263                         gtk_source_print_job_set_numbers_font_desc (job, desc);
2264                         pango_font_description_free (desc);
2265                 }
2266         }
2267         else
2268                 gtk_source_print_job_set_numbers_font (job, NULL);
2269 }
2270
2271 /**
2272  * gtk_source_print_job_get_numbers_font_desc:
2273  * @job: a #GtkSourcePrintJob.
2274  * 
2275  * Determines the font to be used for the line numbers. This function
2276  * might return %NULL if a specific font for numbers has not been set.
2277  * 
2278  * Return value: the line numbers font description or %NULL. This value is
2279  * owned by the job and must not be modified or freed.
2280  **/
2281 PangoFontDescription *
2282 gtk_source_print_job_get_numbers_font_desc (GtkSourcePrintJob *job)
2283 {
2284         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
2285
2286         return job->priv->numbers_font;
2287 }
2288
2289 /**
2290  * gtk_source_print_job_get_numbers_font:
2291  * @job: a #GtkSourcePrintJob.
2292  * 
2293  * Determines the font to be used for the line numbers.  The returned
2294  * string is of the form &quot;Fontfamily Style Size&quot;, for
2295  * example &quot;Monospace Regular 10.0&quot;.  The returned value
2296  * should be freed when no longer needed.  This function might return
2297  * %NULL if a specific font for numbers has not been set.
2298  * 
2299  * Note that the result is a #GnomeFont name not a Pango font
2300  * description string. This function is deprecated since #GnomeFont is
2301  * no longer used when implementing printing for GtkSourceView; you
2302  * should use gtk_source_print_job_get_numbers_font_desc() instead.
2303  *
2304  * Return value: a newly allocated string with the name of the current
2305  * line numbers font, or %NULL.
2306  **/
2307 gchar *
2308 gtk_source_print_job_get_numbers_font (GtkSourcePrintJob *job)
2309 {
2310         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
2311
2312         if (job->priv->numbers_font != NULL)
2313                 return font_description_to_gnome_font_name (job->priv->numbers_font);
2314         else
2315                 return NULL;
2316 }
2317
2318 /**
2319  * gtk_source_print_job_set_print_numbers:
2320  * @job: a #GtkSourcePrintJob.
2321  * @interval: interval for printed line numbers.
2322  * 
2323  * Sets the interval for printed line numbers.  If @interval is 0 no
2324  * numbers will be printed.  If greater than 0, a number will be
2325  * printed every @interval lines (i.e. 1 will print all line numbers).
2326  **/
2327 void 
2328 gtk_source_print_job_set_print_numbers (GtkSourcePrintJob *job,
2329                                         guint              interval)
2330 {
2331         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2332         g_return_if_fail (!job->priv->printing);
2333
2334         if (interval == job->priv->print_numbers)
2335                 return;
2336         
2337         job->priv->print_numbers = interval;
2338
2339         g_object_notify (G_OBJECT (job), "print_numbers");
2340 }
2341
2342 /**
2343  * gtk_source_print_job_get_print_numbers:
2344  * @job: a #GtkSourcePrintJob.
2345  * 
2346  * Determines the interval used for line number printing.  If the
2347  * value is 0, no line numbers will be printed.  The default value is
2348  * 1 (i.e. numbers printed in all lines).
2349  * 
2350  * Return value: the interval of printed line numbers.
2351  **/
2352 guint 
2353 gtk_source_print_job_get_print_numbers (GtkSourcePrintJob *job)
2354 {
2355         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), 0);
2356
2357         return job->priv->print_numbers;
2358 }
2359
2360 /**
2361  * gtk_source_print_job_set_text_margins:
2362  * @job: a #GtkSourcePrintJob.
2363  * @top: the top user margin.
2364  * @bottom: the bottom user margin.
2365  * @left: the left user margin.
2366  * @right: the right user margin.
2367  * 
2368  * Sets the four user margins for the print job.  These margins are in
2369  * addition to the document margins provided in the #GnomePrintConfig
2370  * and will not be used for headers, footers or line numbers (those
2371  * are calculated separatedly).  You can print in the space allocated
2372  * by these margins by connecting to the <link
2373  * linkend="GtkSourcePrintJob-begin-page">&quot;begin_page&quot;</link> signal.  The
2374  * space is around the printed text, and inside the margins specified
2375  * in the #GnomePrintConfig.
2376  *
2377  * The margin numbers are given in device units.  If any of the given
2378  * values is less than 0, that particular margin is not altered by
2379  * this function.
2380  **/
2381 void 
2382 gtk_source_print_job_set_text_margins (GtkSourcePrintJob *job,
2383                                        gdouble            top,
2384                                        gdouble            bottom,
2385                                        gdouble            left,
2386                                        gdouble            right)
2387 {
2388         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2389         g_return_if_fail (!job->priv->printing);
2390
2391         if (top >= 0)
2392                 job->priv->margin_top = top;
2393         if (bottom >= 0)
2394                 job->priv->margin_bottom = bottom;
2395         if (left >= 0)
2396                 job->priv->margin_left = left;
2397         if (right >= 0)
2398                 job->priv->margin_right = right;
2399 }
2400
2401 /**
2402  * gtk_source_print_job_get_text_margins:
2403  * @job: a #GtkSourcePrintJob.
2404  * @top: a pointer to a #gdouble to return the top margin.
2405  * @bottom: a pointer to a #gdouble to return the bottom margin.
2406  * @left: a pointer to a #gdouble to return the left margin.
2407  * @right: a pointer to a #gdouble to return the right margin.
2408  * 
2409  * Determines the user set margins for the job.  This function
2410  * retrieves the values previously set by
2411  * gtk_source_print_job_set_text_margins().  The default for all four
2412  * margins is 0.  Any of the pointers can be %NULL if you want to
2413  * ignore that value.
2414  **/
2415 void 
2416 gtk_source_print_job_get_text_margins (GtkSourcePrintJob *job,
2417                                        gdouble           *top,
2418                                        gdouble           *bottom,
2419                                        gdouble           *left,
2420                                        gdouble           *right)
2421 {
2422         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2423
2424         if (top != NULL)
2425                 *top = job->priv->margin_top;
2426         if (bottom != NULL)
2427                 *bottom = job->priv->margin_bottom;
2428         if (left != NULL)
2429                 *left = job->priv->margin_left;
2430         if (right != NULL)
2431                 *right = job->priv->margin_right;
2432 }
2433
2434 /* --- printing operations */
2435
2436 static gboolean
2437 gtk_source_print_job_prepare (GtkSourcePrintJob *job,
2438                               const GtkTextIter *start,
2439                               const GtkTextIter *end)
2440 {
2441         PROFILE (GTimer *timer);
2442         
2443         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), FALSE);
2444         g_return_val_if_fail (!job->priv->printing, FALSE);
2445         g_return_val_if_fail (job->priv->buffer != NULL, FALSE);
2446         g_return_val_if_fail (start != NULL && end != NULL, FALSE);
2447
2448         /* make sure we have a sane configuration to start printing */
2449         ensure_print_config (job);
2450
2451         PROFILE (timer = g_timer_new ());
2452
2453         /* get the text to print */
2454         if (!get_text_to_print (job, start, end))
2455                 return FALSE;
2456
2457         PROFILE (g_message ("get_text_to_print: %.2f", g_timer_elapsed (timer, NULL)));
2458
2459         if (!setup_pango_context (job))
2460                 return FALSE;
2461
2462         /* check margins */
2463         if (!update_page_size_and_margins (job))
2464                 return FALSE;
2465
2466         /* split the document in pages */
2467         if (!paginate_text (job))
2468                 return FALSE;
2469
2470         PROFILE ({
2471                 g_message ("paginate_text: %.2f", g_timer_elapsed (timer, NULL));
2472                 g_timer_destroy (timer);
2473         });
2474
2475         return TRUE;
2476 }
2477
2478 /**
2479  * gtk_source_print_job_print:
2480  * @job: a configured #GtkSourcePrintJob.
2481  * 
2482  * Produces a #GnomePrintJob with the printed document.  The whole
2483  * contents of the configured #GtkTextBuffer are printed.  The
2484  * returned job is already closed and ready to be previewed (using
2485  * gnome_print_job_preview_new()) or printed directly.  The caller of
2486  * this function owns a reference to the returned object, so @job can
2487  * be destroyed and the output will still be valid, or the document
2488  * can be printed again with different settings.
2489  * 
2490  * Return value: a closed #GnomePrintJob with the printed document, or
2491  * %NULL if printing could not be completed.
2492  **/
2493 GnomePrintJob *
2494 gtk_source_print_job_print (GtkSourcePrintJob *job)
2495 {
2496         GtkTextIter start, end;
2497
2498         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
2499         g_return_val_if_fail (!job->priv->printing, NULL);
2500         g_return_val_if_fail (job->priv->buffer != NULL, NULL);
2501
2502         gtk_text_buffer_get_bounds (GTK_TEXT_BUFFER (job->priv->buffer), &start, &end);
2503
2504         return gtk_source_print_job_print_range (job, &start, &end);
2505 }
2506
2507 /**
2508  * gtk_source_print_job_print_range:
2509  * @job: a configured #GtkSourcePrintJob.
2510  * @start: the start of the region of text to print.
2511  * @end: the end of the region of text to print.
2512  * 
2513  * Similar to gtk_source_print_job_print(), except you can specify a
2514  * range of text to print.  The passed #GtkTextIter values might be
2515  * out of order.
2516  * 
2517  * Return value: a closed #GnomePrintJob with the text from @start to
2518  * @end printed, or %NULL if @job could not print.
2519  **/
2520 GnomePrintJob *
2521 gtk_source_print_job_print_range (GtkSourcePrintJob *job,
2522                                   const GtkTextIter *start,
2523                                   const GtkTextIter *end)
2524 {
2525         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
2526         g_return_val_if_fail (!job->priv->printing, NULL);
2527         g_return_val_if_fail (job->priv->buffer != NULL, NULL);
2528         g_return_val_if_fail (start != NULL && end != NULL, NULL);
2529         g_return_val_if_fail (gtk_text_iter_get_buffer (start) ==
2530                               GTK_TEXT_BUFFER (job->priv->buffer) &&
2531                               gtk_text_iter_get_buffer (end) ==
2532                               GTK_TEXT_BUFFER (job->priv->buffer), NULL);
2533
2534         if (!gtk_source_print_job_prepare (job, start, end))
2535                 return NULL;
2536
2537         /* real work starts here */
2538         setup_for_print (job);
2539
2540         job->priv->printing = TRUE;
2541         print_job (job);
2542         job->priv->printing = FALSE;
2543
2544         g_object_ref (job->priv->print_job);
2545         return job->priv->print_job;
2546 }
2547
2548 /* --- asynchronous printing */
2549
2550 /**
2551  * gtk_source_print_job_print_range_async:
2552  * @job: a configured #GtkSourcePrintJob.
2553  * @start: the start of the region of text to print.
2554  * @end: the end of the region of text to print.
2555  * 
2556  * Starts to print @job asynchronously.  This function will ready the
2557  * @job for printing and install an idle handler that will render one
2558  * page at a time.
2559  *
2560  * This function will not return immediatly, as only page rendering is
2561  * done asynchronously.  Text retrieval and paginating happens within
2562  * this function.  Also, if highlighting is enabled, the whole buffer
2563  * needs to be highlighted first.
2564  *
2565  * To get notification when the job has finished, you must connect to
2566  * the <link
2567  * linkend="GtkSourcePrintJob-finished">&quot;finished&quot;</link>
2568  * signal.  After this signal is emitted you can retrieve the
2569  * resulting #GnomePrintJob with gtk_source_print_job_get_print_job().
2570  * You may cancel the job with gtk_source_print_job_cancel().
2571  *
2572  * Return value: %TRUE if the print started.
2573  **/
2574 gboolean 
2575 gtk_source_print_job_print_range_async (GtkSourcePrintJob *job,
2576                                         const GtkTextIter *start,
2577                                         const GtkTextIter *end)
2578 {
2579         GSource *idle_source;
2580
2581         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), FALSE);
2582         g_return_val_if_fail (!job->priv->printing, FALSE);
2583         g_return_val_if_fail (job->priv->buffer != NULL, FALSE);
2584         g_return_val_if_fail (start != NULL && end != NULL, FALSE);
2585         g_return_val_if_fail (gtk_text_iter_get_buffer (start) ==
2586                               GTK_TEXT_BUFFER (job->priv->buffer) &&
2587                               gtk_text_iter_get_buffer (end) ==
2588                               GTK_TEXT_BUFFER (job->priv->buffer), FALSE);
2589
2590         if (!gtk_source_print_job_prepare (job, start, end))
2591                 return FALSE;
2592
2593         /* real work starts here */
2594         setup_for_print (job);
2595         if (job->priv->current_paragraph == NULL)
2596                 return FALSE;
2597         
2598         /* setup the idle handler to print each page at a time */
2599         idle_source = g_idle_source_new ();
2600         g_source_set_priority (idle_source, GTK_SOURCE_PRINT_JOB_PRIORITY);
2601         g_source_set_closure (idle_source,
2602                               g_cclosure_new_object ((GCallback) idle_printing_handler,
2603                                                      G_OBJECT (job)));
2604         job->priv->idle_printing_tag = g_source_attach (idle_source, NULL);
2605         g_source_unref (idle_source);
2606
2607         job->priv->printing = TRUE;
2608
2609         return TRUE;
2610 }
2611
2612 /**
2613  * gtk_source_print_job_cancel:
2614  * @job: a #GtkSourcePrintJob.
2615  * 
2616  * Cancels an asynchronous printing operation.  This will remove any
2617  * pending print idle handler and unref the current #GnomePrintJob.
2618  *
2619  * Note that if you got a reference to the job's #GnomePrintJob (using
2620  * gtk_source_print_job_get_print_job()) it will not be destroyed
2621  * (since you hold a reference to it), but it will not be closed
2622  * either.  If you wish to show or print the partially printed
2623  * document you need to close it yourself.
2624  *
2625  * This function has no effect when called from a non-asynchronous
2626  * print operation.
2627  **/
2628 void 
2629 gtk_source_print_job_cancel (GtkSourcePrintJob *job)
2630 {
2631         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2632         g_return_if_fail (job->priv->printing);
2633
2634         if (job->priv->idle_printing_tag > 0)
2635         {
2636                 g_source_remove (job->priv->idle_printing_tag);
2637                 job->priv->current_paragraph = NULL;
2638                 job->priv->idle_printing_tag = 0;
2639                 job->priv->printing = FALSE;
2640                 g_object_unref (job->priv->print_job);
2641                 g_object_unref (job->priv->print_ctxt);
2642                 job->priv->print_job = NULL;
2643                 job->priv->print_ctxt = NULL;
2644         }
2645 }
2646
2647 /**
2648  * gtk_source_print_job_get_print_job:
2649  * @job: a #GtkSourcePrintJob.
2650  * 
2651  * Gets a reference to the #GnomePrintJob which the @job is printing
2652  * or has recently finished printing.  You need to unref the returned
2653  * object.
2654  *
2655  * You may call this function in the middle of an asynchronous
2656  * printing operation, but the returned #GnomePrintJob will not be
2657  * closed until the last page is printed and the <link
2658  * linkend="GtkSourcePrintJob-finished">&quot;finished&quot;</link>
2659  * signal is emitted.
2660  * 
2661  * Return value: a new reference to the @job's #GnomePrintJob, or
2662  * %NULL.
2663  **/
2664 GnomePrintJob *
2665 gtk_source_print_job_get_print_job (GtkSourcePrintJob *job)
2666 {
2667         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
2668
2669         if (job->priv->print_job)
2670                 g_object_ref (job->priv->print_job);
2671         
2672         return job->priv->print_job;
2673 }
2674
2675 /* --- information for asynchronous ops and headers and footers callback */
2676
2677 /**
2678  * gtk_source_print_job_get_page:
2679  * @job: a #GtkSourcePrintJob.
2680  * 
2681  * Determines the currently printing page number.  This function is
2682  * only valid while printing (either synchronously or asynchronously).
2683  * 
2684  * Return value: the current page number.
2685  **/
2686 guint 
2687 gtk_source_print_job_get_page (GtkSourcePrintJob *job)
2688 {
2689         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), 0);
2690         g_return_val_if_fail (job->priv->printing, 0);
2691
2692         return job->priv->page;
2693 }
2694
2695 /**
2696  * gtk_source_print_job_get_page_count:
2697  * @job: a #GtkSourcePrintJob.
2698  * 
2699  * Determines the total number of pages the job will print.  The
2700  * returned value is only meaninful after pagination has finished.  In
2701  * practice, for synchronous printing this means when <link
2702  * linkend="GtkSourcePrintJob-begin-page">&quot;begin_page&quot;</link>
2703  * is emitted, or after gtk_source_print_job_print_range_async() has
2704  * returned.
2705  * 
2706  * Return value: the number of pages of the printed job.
2707  **/
2708 guint 
2709 gtk_source_print_job_get_page_count (GtkSourcePrintJob *job)
2710 {
2711         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), 0);
2712
2713         return job->priv->page_count;
2714 }
2715
2716 /**
2717  * gtk_source_print_job_get_print_context:
2718  * @job: a printing #GtkSourcePrintJob.
2719  * 
2720  * Determines the #GnomePrintContext of the current job.  This
2721  * function is only valid while printing.  Normally you would use this
2722  * function to print in the margins set by
2723  * gtk_source_print_job_set_margins() in a handler for the <link
2724  * linkend="GtkSourcePrintJob-begin-page">&quot;begin_page&quot;</link>
2725  * signal.
2726  * 
2727  * Return value: the current #GnomePrintContext.  The returned object
2728  * is owned by @job.
2729  **/
2730 GnomePrintContext *
2731 gtk_source_print_job_get_print_context (GtkSourcePrintJob *job)
2732 {
2733         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
2734         g_return_val_if_fail (job->priv->printing, NULL);
2735
2736         return job->priv->print_ctxt;
2737 }
2738
2739 /* ---- Header and footer (default implementation) */
2740
2741 /* Most of this code taken from GLib's g_date_strftime() in gdate.c
2742  * GLIB - Library of useful routines for C programming
2743  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald */
2744
2745 static gchar *
2746 strdup_strftime (const gchar *format, const struct tm *tm)
2747 {
2748         gsize locale_format_len = 0;
2749         gchar *locale_format;
2750         gsize tmplen;
2751         gchar *tmpbuf;
2752         gsize tmpbufsize;
2753         gchar *convbuf;
2754         gsize convlen = 0;
2755         GError *error = NULL;
2756
2757         g_return_val_if_fail (format != NULL, NULL);
2758         g_return_val_if_fail (tm != NULL, NULL);
2759
2760         locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
2761
2762         if (error)
2763         {
2764                 g_warning (G_STRLOC "Error converting format to locale encoding: %s",
2765                            error->message);
2766                 g_error_free (error);
2767                 
2768                 return NULL;
2769         }
2770
2771         tmpbufsize = MAX (128, locale_format_len * 2);
2772         while (TRUE)
2773         {
2774                 tmpbuf = g_malloc (tmpbufsize);
2775                 
2776                 /* Set the first byte to something other than '\0', to be able to
2777                  * recognize whether strftime actually failed or just returned "".
2778                  */
2779                 tmpbuf[0] = '\1';
2780                 tmplen = strftime (tmpbuf, tmpbufsize, locale_format, tm);
2781                 
2782                 if (tmplen == 0 && tmpbuf[0] != '\0')
2783                 {
2784                         g_free (tmpbuf);
2785                         tmpbufsize *= 2;
2786                         
2787                         if (tmpbufsize > 65536)
2788                         {
2789                                 g_warning (G_STRLOC "Maximum buffer size for strdup_strftime "
2790                                            "exceeded: giving up");
2791                                 g_free (locale_format);
2792                                 return NULL;
2793                         }
2794                 }
2795                 else
2796                         break;
2797         }
2798         g_free (locale_format);
2799
2800         convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
2801         g_free (tmpbuf);
2802
2803         if (error)
2804         {
2805                 g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s",
2806                            error->message);
2807                 g_error_free (error);
2808                 
2809                 return NULL;
2810         }
2811
2812         return convbuf;
2813 }
2814
2815 static gchar *
2816 evaluate_format_string (GtkSourcePrintJob *job, const gchar *format)
2817 {
2818         GString *eval;
2819         gchar *eval_str, *retval;
2820         const struct tm *tm;
2821         time_t now;
2822         gunichar ch;
2823         
2824         /* get time */
2825         time (&now);
2826         tm = localtime (&now);
2827
2828         /* analyze format string and replace the codes we know */
2829         eval = g_string_new_len (NULL, strlen (format));
2830         ch = g_utf8_get_char (format);
2831         while (ch != 0)
2832         {
2833                 if (ch == '%')
2834                 {
2835                         format = g_utf8_next_char (format);
2836                         ch = g_utf8_get_char (format);
2837                         if (ch == 'N')
2838                                 g_string_append_printf (eval, "%d", job->priv->page);
2839                         else if (ch == 'Q')
2840                                 g_string_append_printf (eval, "%d", job->priv->page_count);
2841                         else
2842                         {
2843                                 g_string_append_c (eval, '%');
2844                                 g_string_append_unichar (eval, ch);
2845                         }
2846                 }
2847                 else
2848                         g_string_append_unichar (eval, ch);
2849
2850                 format = g_utf8_next_char (format);
2851                 ch = g_utf8_get_char (format);
2852         }
2853
2854         eval_str = g_string_free (eval, FALSE);
2855         retval = strdup_strftime (eval_str, tm);
2856         g_free (eval_str);
2857
2858         return retval;
2859 }
2860
2861 static void
2862 print_header_footer_string (GtkSourcePrintJob *job,
2863                             const gchar       *format,
2864                             gdouble            x_align,
2865                             gdouble            x,
2866                             gdouble            y)
2867 {
2868         PangoLayout *layout;
2869         gchar *text;
2870         gdouble width;
2871         gdouble xx;
2872         
2873         width = job->priv->text_width + job->priv->numbers_width;
2874         
2875         text = evaluate_format_string (job, format);
2876         if (text != NULL)
2877         {
2878                 layout = pango_layout_new (job->priv->pango_context);
2879                 pango_layout_set_font_description (layout, job->priv->header_footer_font);
2880                 pango_layout_set_text (layout, text, -1);
2881                 
2882                 xx = x + x_align * (width - get_layout_width (layout));
2883                 gnome_print_moveto (job->priv->print_ctxt, xx, y);
2884                 show_first_layout_line (job->priv->print_ctxt, layout);
2885                 
2886                 g_free (text);
2887                 g_object_unref (layout);
2888         }
2889 }
2890
2891 static void 
2892 default_print_header (GtkSourcePrintJob *job,
2893                       gdouble            x,
2894                       gdouble            y)
2895 {
2896         gdouble width;
2897         gdouble yy;
2898         gdouble ascent, descent;
2899         
2900         width = job->priv->text_width + job->priv->numbers_width;
2901
2902         get_font_ascent_descent (job, job->priv->header_footer_font, &ascent, &descent);
2903
2904         yy = y - ascent;
2905
2906         /* left format */
2907         if (job->priv->header_format_left != NULL)
2908                 print_header_footer_string (job, job->priv->header_format_left, 0.0, x, yy);
2909         
2910         /* right format */
2911         if (job->priv->header_format_right != NULL)
2912                 print_header_footer_string (job, job->priv->header_format_right, 1.0, x, yy);
2913
2914         /* center format */
2915         if (job->priv->header_format_center != NULL)
2916                 print_header_footer_string (job, job->priv->header_format_center, 0.5, x, yy);
2917
2918         /* separator */
2919         if (job->priv->header_separator)
2920         {
2921                 yy = y - (SEPARATOR_SPACING * (ascent + descent));
2922                 gnome_print_setlinewidth (job->priv->print_ctxt, SEPARATOR_LINE_WIDTH);
2923                 gnome_print_moveto (job->priv->print_ctxt, x, yy);
2924                 gnome_print_lineto (job->priv->print_ctxt, x + width, yy);
2925                 gnome_print_stroke (job->priv->print_ctxt);
2926         }
2927 }
2928
2929 static void 
2930 default_print_footer (GtkSourcePrintJob *job,
2931                       gdouble            x,
2932                       gdouble            y)
2933 {
2934         gdouble width;
2935         gdouble yy;
2936         gdouble ascent, descent;
2937         
2938         width = job->priv->text_width + job->priv->numbers_width;
2939
2940         get_font_ascent_descent (job, job->priv->header_footer_font, &ascent, &descent);
2941
2942         yy = y - job->priv->footer_height + descent;
2943
2944         /* left format */
2945         if (job->priv->footer_format_left != NULL)
2946                 print_header_footer_string (job, job->priv->footer_format_left, 0.0, x, yy);
2947         
2948         /* right format */
2949         if (job->priv->footer_format_right != NULL)
2950                 print_header_footer_string (job, job->priv->footer_format_right, 1.0, x, yy);
2951
2952         /* center format */
2953         if (job->priv->footer_format_center != NULL)
2954                 print_header_footer_string (job, job->priv->footer_format_center, 0.5, x, yy);
2955
2956         /* separator */
2957         if (job->priv->footer_separator)
2958         {
2959                 yy = y - job->priv->footer_height +
2960                         (SEPARATOR_SPACING * (ascent + descent));
2961                 gnome_print_setlinewidth (job->priv->print_ctxt, SEPARATOR_LINE_WIDTH);
2962                 gnome_print_moveto (job->priv->print_ctxt, x, yy);
2963                 gnome_print_lineto (job->priv->print_ctxt, x + width, yy);
2964                 gnome_print_stroke (job->priv->print_ctxt);
2965         }
2966 }
2967
2968 /**
2969  * gtk_source_print_job_set_print_header:
2970  * @job: a #GtkSourcePrintJob.
2971  * @setting: %TRUE if you want the header to be printed.
2972  * 
2973  * Sets whether you want to print a header in each page.  The default
2974  * header consists of three pieces of text and an optional line
2975  * separator, configurable with
2976  * gtk_source_print_job_set_header_format().
2977  *
2978  * Note that by default the header format is unspecified, and if it's
2979  * empty it will not be printed, regardless of this setting.
2980  **/
2981 void 
2982 gtk_source_print_job_set_print_header (GtkSourcePrintJob *job,
2983                                        gboolean           setting)
2984 {
2985         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
2986         g_return_if_fail (!job->priv->printing);
2987
2988         setting = (setting != FALSE);
2989         
2990         if (setting == job->priv->print_header)
2991                 return;
2992         
2993         job->priv->print_header = setting;
2994
2995         g_object_notify (G_OBJECT (job), "print_header");
2996 }
2997
2998 /**
2999  * gtk_source_print_job_get_print_header:
3000  * @job: a #GtkSourcePrintJob.
3001  * 
3002  * Determines if a header is set to be printed for each page.  A
3003  * header will be printed if this function returns %TRUE
3004  * <emphasis>and</emphasis> some format strings have been specified
3005  * with gtk_source_print_job_set_header_format().
3006  * 
3007  * Return value: %TRUE if the header is set to be printed.
3008  **/
3009 gboolean 
3010 gtk_source_print_job_get_print_header (GtkSourcePrintJob *job)
3011 {
3012         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), FALSE);
3013
3014         return job->priv->print_header;
3015 }
3016
3017 /**
3018  * gtk_source_print_job_set_print_footer:
3019  * @job: a #GtkSourcePrintJob.
3020  * @setting: %TRUE if you want the footer to be printed.
3021  * 
3022  * Sets whether you want to print a footer in each page.  The default
3023  * footer consists of three pieces of text and an optional line
3024  * separator, configurable with
3025  * gtk_source_print_job_set_footer_format().
3026  *
3027  * Note that by default the footer format is unspecified, and if it's
3028  * empty it will not be printed, regardless of this setting.
3029  **/
3030 void 
3031 gtk_source_print_job_set_print_footer (GtkSourcePrintJob *job,
3032                                        gboolean           setting)
3033 {
3034         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
3035         g_return_if_fail (!job->priv->printing);
3036
3037         setting = (setting != FALSE);
3038         
3039         if (setting == job->priv->print_footer)
3040                 return;
3041         
3042         job->priv->print_footer = setting;
3043
3044         g_object_notify (G_OBJECT (job), "print_footer");
3045 }
3046
3047 /**
3048  * gtk_source_print_job_get_print_footer:
3049  * @job: a #GtkSourcePrintJob.
3050  * 
3051  * Determines if a footer is set to be printed for each page.  A
3052  * footer will be printed if this function returns %TRUE
3053  * <emphasis>and</emphasis> some format strings have been specified
3054  * with gtk_source_print_job_set_footer_format().
3055  * 
3056  * Return value: %TRUE if the footer is set to be printed.
3057  **/
3058 gboolean 
3059 gtk_source_print_job_get_print_footer (GtkSourcePrintJob *job)
3060 {
3061         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), FALSE);
3062
3063         return job->priv->print_footer;
3064 }
3065
3066 /**
3067  * gtk_source_print_job_set_header_footer_font_desc:
3068  * @job: a #GtkSourcePrintJob.
3069  * @desc: the #PangoFontDescription for the font to be used in headers and footers, or %NULL.
3070  * 
3071  * Sets the font for printing headers and footers.  If %NULL is
3072  * supplied, the default font (i.e. the one being used for the text)
3073  * will be used instead.
3074  **/
3075 void 
3076 gtk_source_print_job_set_header_footer_font_desc (GtkSourcePrintJob    *job,
3077                                                   PangoFontDescription *desc)
3078 {
3079         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
3080         g_return_if_fail (!job->priv->printing);
3081         
3082         if (desc)
3083                 desc = pango_font_description_copy (desc);
3084         if (job->priv->header_footer_font != NULL)
3085                 pango_font_description_free (job->priv->header_footer_font);
3086         job->priv->header_footer_font = desc;
3087         g_object_freeze_notify (G_OBJECT (job));
3088         g_object_notify (G_OBJECT (job), "header_footer_font");
3089         g_object_notify (G_OBJECT (job), "header_footer_font_desc");
3090         g_object_thaw_notify (G_OBJECT (job));
3091 }
3092
3093 /**
3094  * gtk_source_print_job_set_header_footer_font:
3095  * @job: a #GtkSourcePrintJob.
3096  * @font_name: the full name of the font to be used in headers and footers, or %NULL.
3097  * 
3098  * Sets the font for printing headers and footers.  If %NULL is
3099  * supplied, the default font (i.e. the one being used for the text)
3100  * will be used instead.
3101  *
3102  * Note that @font_name is a #GnomeFont name not a Pango font
3103  * description string. This function is deprecated since #GnomeFont is
3104  * no longer used when implementing printing for GtkSourceView; you
3105  * should use gtk_source_print_job_set_header_footer_font_desc() instead.
3106  **/
3107 void 
3108 gtk_source_print_job_set_header_footer_font (GtkSourcePrintJob *job,
3109                                              const gchar       *font_name)
3110 {
3111         PangoFontDescription *desc;
3112         
3113         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
3114         g_return_if_fail (!job->priv->printing);
3115
3116         if (font_name != NULL)
3117         {
3118                 desc = font_description_from_gnome_font_name (font_name);
3119                 if (desc)
3120                 {
3121                         gtk_source_print_job_set_header_footer_font_desc (job, desc);
3122                         pango_font_description_free (desc);
3123                 }
3124         }
3125         else
3126                 gtk_source_print_job_set_header_footer_font_desc (job, NULL);
3127 }
3128
3129 /**
3130  * gtk_source_print_job_get_header_footer_font_desc:
3131  * @job: a #GtkSourcePrintJob.
3132  * 
3133  * Determines the font to be used for the header and footer.  This function
3134  * might return %NULL if a specific font has not been set.
3135  * 
3136  * Return value: the header and footer font description or %NULL. This value is
3137  * owned by the job and must not be modified or freed.
3138  **/
3139 PangoFontDescription *
3140 gtk_source_print_job_get_header_footer_font_desc (GtkSourcePrintJob *job)
3141 {
3142         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
3143
3144         return job->priv->header_footer_font;
3145 }
3146
3147 /**
3148  * gtk_source_print_job_get_header_footer_font:
3149  * @job: a #GtkSourcePrintJob.
3150  * 
3151  * Determines the font to be used for the header and footer.  The
3152  * returned string is of the form &quot;Fontfamily Style Size&quot;,
3153  * for example &quot;Monospace Regular 10.0&quot;.  The returned value
3154  * should be freed when no longer needed.  This function might return
3155  * %NULL if a specific font has not been set.
3156  * 
3157  * Note that the result is a #GnomeFont name not a Pango font
3158  * description string. This function is deprecated since #GnomeFont is
3159  * no longer used when implementing printing for GtkSourceView; you
3160  * should use gtk_source_print_job_get_header_footer_font_desc() instead.
3161  *
3162  * Return value: a newly allocated string with the name of the current
3163  * header and footer font, or %NULL.
3164  **/
3165 gchar *
3166 gtk_source_print_job_get_header_footer_font (GtkSourcePrintJob *job)
3167 {
3168         g_return_val_if_fail (GTK_IS_SOURCE_PRINT_JOB (job), NULL);
3169
3170         if (job->priv->header_footer_font != NULL)
3171                 return font_description_to_gnome_font_name (job->priv->header_footer_font);
3172         else
3173                 return NULL;
3174 }
3175
3176 /**
3177  * gtk_source_print_job_set_header_format:
3178  * @job: a #GtkSourcePrintJob.
3179  * @left: a format string to print on the left of the header.
3180  * @center: a format string to print on the center of the header.
3181  * @right: a format string to print on the right of the header.
3182  * @separator: %TRUE if you want a separator line to be printed.
3183  * 
3184  * Sets strftime like header format strings, to be printed on the
3185  * left, center and right of the top of each page.  The strings may
3186  * include strftime(3) codes which will be expanded at print time.
3187  * All strftime() codes are accepted, with the addition of %N for the
3188  * page number and %Q for the page count.
3189  *
3190  * @separator specifies if a solid line should be drawn to separate
3191  * the header from the document text.
3192  *
3193  * If %NULL is given for any of the three arguments, that particular
3194  * string will not be printed.  For the header to be printed, in
3195  * addition to specifying format strings, you need to enable header
3196  * printing with gtk_source_print_job_set_print_header().
3197  **/
3198 void 
3199 gtk_source_print_job_set_header_format (GtkSourcePrintJob *job,
3200                                         const gchar       *left,
3201                                         const gchar       *center,
3202                                         const gchar       *right,
3203                                         gboolean           separator)
3204 {
3205         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
3206         g_return_if_fail (!job->priv->printing);
3207
3208         /* FIXME: validate given strings? */
3209         g_free (job->priv->header_format_left);
3210         g_free (job->priv->header_format_center);
3211         g_free (job->priv->header_format_right);
3212         job->priv->header_format_left = g_strdup (left);
3213         job->priv->header_format_center = g_strdup (center);
3214         job->priv->header_format_right = g_strdup (right);
3215         job->priv->header_separator = separator;
3216 }
3217
3218 /**
3219  * gtk_source_print_job_set_footer_format:
3220  * @job: a #GtkSourcePrintJob.
3221  * @left: a format string to print on the left of the footer.
3222  * @center: a format string to print on the center of the footer.
3223  * @right: a format string to print on the right of the footer.
3224  * @separator: %TRUE if you want a separator line to be printed.
3225  * 
3226  * Like gtk_source_print_job_set_header_format(), but for the footer.
3227  **/
3228 void 
3229 gtk_source_print_job_set_footer_format (GtkSourcePrintJob *job,
3230                                         const gchar       *left,
3231                                         const gchar       *center,
3232                                         const gchar       *right,
3233                                         gboolean           separator)
3234 {
3235         g_return_if_fail (GTK_IS_SOURCE_PRINT_JOB (job));
3236         g_return_if_fail (!job->priv->printing);
3237
3238         /* FIXME: validate given strings? */
3239         g_free (job->priv->footer_format_left);
3240         g_free (job->priv->footer_format_center);
3241         g_free (job->priv->footer_format_right);
3242         job->priv->footer_format_left = g_strdup (left);
3243         job->priv->footer_format_center = g_strdup (center);
3244         job->priv->footer_format_right = g_strdup (right);
3245         job->priv->footer_separator = separator;
3246 }
3247 #endif