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