2011-10-07 [colin] 3.7.10cvs21
[claws.git] / src / printing.c
1 /* Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
2  * Copyright (C) 2007-2011 Holger Berndt <hb@claws-mail.org>,
3  * Colin Leroy <colin@colino.net>, and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include "printing.h"
27 #include "image_viewer.h"
28
29 #include "gtkutils.h"
30 #include "toolbar.h"
31 #include "prefs_common.h"
32
33 #include <glib/gi18n.h>
34 #include <gdk/gdkkeysyms.h>
35 #include <gtk/gtk.h>
36 #include <pango/pango.h>
37 #include <string.h>
38 #include <math.h>
39
40 struct _PrintData {
41         PrintRenderer *renderer;
42         gpointer renderer_data;
43         PangoLayout *layout;
44         PangoContext *pango_context;
45         gpointer to_print;
46         GList *page_breaks;
47         guint npages;
48         gint sel_start;
49         gint sel_end;
50         GHashTable *images;
51         gint img_cnt;
52         gdouble zoom;
53         gdouble ypos_line;
54 };
55
56 typedef struct {
57         GtkPrintOperation *op;
58         GtkPrintOperationPreview *preview;
59         GtkWidget         *dialog;
60         GtkWidget         *scrolled_window;
61         GtkWidget         *area;
62         PrintData         *print_data;
63         GtkWidget         *page_nr_label;
64         GList             *pages_to_print;
65         GList             *current_page;
66         GtkWidget *first;
67         GtkWidget *next;
68         GtkWidget *previous;
69         GtkWidget *last;
70         GtkWidget *close;
71         GtkWidget *zoom_100;
72         GtkWidget *zoom_fit;
73         GtkWidget *zoom_in;
74         GtkWidget *zoom_out;
75         gboolean rendering;
76         gint page_width;
77         gint page_height;
78         GtkPrintContext *context;
79 } PreviewData;
80
81 /* callbacks */
82 static void     printing_textview_cb_begin_print(GtkPrintOperation*,
83                                                  GtkPrintContext*, gpointer);
84 static void     printing_textview_cb_draw_page(GtkPrintOperation*, 
85                                                GtkPrintContext*, gint,
86                                                gpointer);
87 static gboolean cb_preview(GtkPrintOperation*, GtkPrintOperationPreview*,
88                            GtkPrintContext*, GtkWindow*, gpointer);
89 static void     cb_preview_destroy(GtkWindow*, gpointer);
90 static gboolean cb_preview_close(GtkWidget*, GdkEventAny*, gpointer);
91 static void     cb_preview_size_allocate(GtkWidget*, GtkAllocation*);
92 static void     cb_preview_ready(GtkPrintOperationPreview*,
93                                  GtkPrintContext*, gpointer);
94 #if !GTK_CHECK_VERSION(3, 0, 0)
95 static gboolean cb_preview_expose(GtkWidget*, GdkEventExpose*, gpointer);
96 #else
97 static gboolean cb_preview_expose(GtkWidget*, cairo_t*, gpointer);
98 #endif
99 static void     cb_preview_got_page_size(GtkPrintOperationPreview*,
100                                          GtkPrintContext*,
101                                          GtkPageSetup*, gpointer);
102 static void     cb_preview_go_first(GtkButton*, gpointer);
103 static void     cb_preview_go_previous(GtkButton*, gpointer);
104 static void     cb_preview_go_next(GtkButton*, gpointer);
105 static void     cb_preview_go_last(GtkButton*, gpointer);
106 static void     cb_preview_btn_close(GtkButton*, gpointer);
107 static void     cb_preview_zoom_100(GtkButton*, gpointer);
108 static void     cb_preview_zoom_fit(GtkButton*, gpointer);
109 static void     cb_preview_zoom_in(GtkButton*, gpointer);
110 static void     cb_preview_zoom_out(GtkButton*, gpointer);
111 static void     cb_preview_request_page_setup(GtkPrintOperation*,
112                                               GtkPrintContext*,
113                                               gint,GtkPageSetup*,gpointer);
114
115 static void     printing_preview_update_zoom_sensitivity(PreviewData*);
116
117 /* variables */
118 static GtkPrintSettings *settings   = NULL;
119 static GtkPageSetup     *page_setup = NULL;
120
121 /* other static functions */
122 static void     printing_layout_set_text_attributes(PrintData*, GtkPrintContext *, gboolean *);
123 static gboolean printing_is_pango_gdk_color_equal(PangoColor*, GdkColor*); 
124 static gint     printing_text_iter_get_offset_bytes(PrintData *, const GtkTextIter*);
125
126 #define PAGE_MARGIN_STORAGE_UNIT GTK_UNIT_MM
127 #define PREVIEW_SCALE 72
128 #define PREVIEW_SHADOW_OFFSET 3
129 #define PREVIEW_ZOOM_FAC 1.41
130 #define PREVIEW_ZOOM_MAX 10.
131 #define PREVIEW_ZOOM_MIN 0.2
132
133 static void free_pixbuf(gpointer key, gpointer value, gpointer data)
134 {
135         PangoAttrShape *attr = (PangoAttrShape *) value;
136         g_object_unref(G_OBJECT(attr->data));
137 }
138
139 gpointer printing_get_renderer_data(PrintData *print_data)
140 {
141         if (!print_data)
142                 return NULL;
143         return print_data->renderer_data;
144 }
145
146 gdouble printing_get_zoom(PrintData *print_data)
147 {
148         if (!print_data)
149                 return 1.0;
150         return print_data->zoom;
151 }
152
153 void printing_set_n_pages(PrintData *print_data, gint n_pages)
154 {
155         if (!print_data)
156                 return;
157         print_data->npages = n_pages;
158 }
159
160 GtkPrintSettings *printing_get_settings(void)
161 {
162         if (settings == NULL) {
163                 settings = gtk_print_settings_new();
164                 gtk_print_settings_set_use_color(settings, prefs_common.print_use_color);
165                 gtk_print_settings_set_collate(settings, prefs_common.print_use_collate);
166                 gtk_print_settings_set_reverse(settings, prefs_common.print_use_reverse);
167                 gtk_print_settings_set_duplex(settings, prefs_common.print_use_duplex);
168         }
169         return settings;
170 }
171
172 void printing_store_settings(GtkPrintSettings *new_settings)
173 {
174         if (settings != NULL)
175                 g_object_unref(settings);
176
177         settings = g_object_ref(new_settings);
178         prefs_common.print_use_color = gtk_print_settings_get_use_color(settings);
179         prefs_common.print_use_collate = gtk_print_settings_get_collate(settings);
180         prefs_common.print_use_reverse = gtk_print_settings_get_reverse(settings);
181         prefs_common.print_use_duplex = gtk_print_settings_get_duplex(settings);
182 }
183
184 GtkPageSetup *printing_get_page_setup(void)
185 {
186         if (page_setup == NULL) {
187                 gboolean read_from_file;
188                 char *page_setup_filename;
189                 GKeyFile *keyfile;
190                 gboolean key_file_read;
191
192                 page_setup = gtk_page_setup_new();
193
194                 read_from_file = FALSE;
195
196 #if GTK_CHECK_VERSION(2,14,0)
197                 /* try reading the page setup from file */
198                 page_setup_filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, 
199                                                   PRINTING_PAGE_SETUP_STORAGE_FILE, NULL);
200                 keyfile = g_key_file_new();
201                 key_file_read = g_key_file_load_from_file(keyfile, page_setup_filename,
202                                                           0, NULL);
203                 g_free(page_setup_filename);
204
205                 if (key_file_read)
206                         read_from_file = gtk_page_setup_load_key_file(page_setup, keyfile,
207                                                                       NULL, NULL);
208                 g_key_file_free(keyfile);
209
210                 if (read_from_file) {
211                         debug_print("Printing: Read page setup from key file\n");
212                 } else {
213                         debug_print("Printing: Could not read page setup from key file\n");
214                 }
215 #else
216                 key_file_read = FALSE;
217                 keyfile = NULL;
218                 page_setup_filename = NULL;
219 #endif
220
221                 /* if reading from file did not work, or has not been tried (GTK+ < 2.14), use prefs */
222                 if (!read_from_file) {
223                         /* paper size */
224                         if (prefs_common.print_paper_type &&
225                             *prefs_common.print_paper_type) {
226                                 GtkPaperSize *paper = gtk_paper_size_new(prefs_common.print_paper_type);
227                                 gtk_page_setup_set_paper_size(page_setup, paper);
228                                 gtk_paper_size_free(paper);
229                         }
230                         /* orientation */
231                         gtk_page_setup_set_orientation(page_setup,
232                                                        prefs_common.print_paper_orientation);
233                         /* margins */
234                         if (prefs_common.print_margin_top != -1)
235                                 gtk_page_setup_set_top_margin(page_setup,
236                                                               0.01*prefs_common.print_margin_top,
237                                                               PAGE_MARGIN_STORAGE_UNIT);
238                         if (prefs_common.print_margin_bottom != -1)
239                                 gtk_page_setup_set_bottom_margin(page_setup,
240                                                                  0.01*prefs_common.print_margin_bottom,
241                                                                  PAGE_MARGIN_STORAGE_UNIT);
242                         if (prefs_common.print_margin_left != -1)
243                                 gtk_page_setup_set_left_margin(page_setup,
244                                                                0.01*prefs_common.print_margin_left,
245                                                                PAGE_MARGIN_STORAGE_UNIT);
246                         if (prefs_common.print_margin_right != -1)
247                                 gtk_page_setup_set_right_margin(page_setup,
248                                                                 0.01*prefs_common.print_margin_right,
249                                                                 PAGE_MARGIN_STORAGE_UNIT);
250                 }
251         }
252         return page_setup;
253 }
254
255 void printing_print_full(GtkWindow *parent, PrintRenderer *renderer, gpointer renderer_data, 
256                          gint sel_start, gint sel_end)
257 {                        
258         GtkPrintOperation *op;
259         GtkPrintOperationResult res;
260         PrintData *print_data;
261
262         op = gtk_print_operation_new();
263
264         print_data = g_new0(PrintData,1);
265
266         print_data->renderer = renderer;
267         print_data->renderer_data = renderer_data;
268         print_data->sel_start = sel_start;
269         print_data->sel_end = sel_end;
270
271         print_data->zoom = 1.;
272
273         print_data->images = g_hash_table_new(g_direct_hash, g_direct_equal);
274
275         print_data->pango_context = renderer->get_pango_context(renderer_data);
276
277         print_data->to_print = renderer->get_data_to_print(renderer_data, sel_start, sel_end);
278
279         printing_get_settings();
280         printing_get_page_setup();
281
282         /* Config for printing */
283         gtk_print_operation_set_print_settings(op, settings);
284         gtk_print_operation_set_default_page_setup(op, page_setup);
285 #if GTK_CHECK_VERSION(2, 18, 0)
286         /* enable Page Size and Orientation in the print dialog */
287         gtk_print_operation_set_embed_page_setup(op, TRUE);
288 #endif
289
290         /* signals */
291         g_signal_connect(op, "begin_print", G_CALLBACK(renderer->cb_begin_print), print_data);
292         g_signal_connect(op, "draw_page", G_CALLBACK(renderer->cb_draw_page), print_data);
293         g_signal_connect(op, "preview", G_CALLBACK(cb_preview), print_data);
294
295         /* Start printing process */
296         res = gtk_print_operation_run(op, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
297                                       parent, NULL);
298
299         if (res == GTK_PRINT_OPERATION_RESULT_ERROR) {
300                 GError *error = NULL;
301                 gtk_print_operation_get_error(op, &error);
302                 debug_print("Error printing message: %s\n",
303                             error ? error->message : "no details");
304         } else if (res == GTK_PRINT_OPERATION_RESULT_APPLY) {
305                 /* store settings for next printing session */
306                 printing_store_settings(gtk_print_operation_get_print_settings(op));
307         }
308
309         g_hash_table_foreach(print_data->images, free_pixbuf, NULL);
310         g_hash_table_destroy(print_data->images);
311         if (print_data->to_print)
312                 g_free(print_data->to_print);
313         g_list_free(print_data->page_breaks);
314         if (print_data->layout)
315                 g_object_unref(print_data->layout);
316
317         g_free(print_data);
318
319         g_object_unref(op);
320         debug_print("printing_print finished\n");
321 }
322
323 static PangoContext *printing_textview_get_pango_context(gpointer data)
324 {
325         return gtk_widget_get_pango_context(GTK_WIDGET(data));
326 }
327
328 static gpointer printing_textview_get_data_to_print(gpointer data, gint sel_start, gint sel_end)
329 {
330         GtkTextView *text_view = GTK_TEXT_VIEW(data);
331         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text_view);
332         GtkTextIter start, end;
333
334         if (sel_start < 0 || sel_end <= sel_start) {
335                 gtk_text_buffer_get_start_iter(buffer, &start);
336                 gtk_text_buffer_get_end_iter(buffer, &end);
337         } else {
338                 gtk_text_buffer_get_iter_at_offset(buffer, &start, sel_start);
339                 gtk_text_buffer_get_iter_at_offset(buffer, &end, sel_end);
340         }
341
342         return gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
343 }
344
345 void printing_print(GtkTextView *text_view, GtkWindow *parent, gint sel_start, gint sel_end)
346 {
347         PrintRenderer *textview_renderer = g_new0(PrintRenderer, 1);
348         
349         textview_renderer->get_pango_context = printing_textview_get_pango_context;
350         textview_renderer->get_data_to_print = printing_textview_get_data_to_print;
351         textview_renderer->cb_begin_print    = printing_textview_cb_begin_print;
352         textview_renderer->cb_draw_page      = printing_textview_cb_draw_page;
353
354         printing_print_full(parent, textview_renderer, text_view, sel_start, sel_end);
355         
356         g_free(textview_renderer);
357 }
358
359 void printing_page_setup(GtkWindow *parent)
360 {
361         GtkPageSetup *new_page_setup;
362         char *keyfile;
363
364         keyfile = NULL;
365
366         printing_get_settings();
367         printing_get_page_setup();
368
369         new_page_setup = gtk_print_run_page_setup_dialog(parent,page_setup,settings);
370
371         if (page_setup)
372                 g_object_unref(page_setup);
373
374         page_setup = new_page_setup;
375
376         g_free(prefs_common.print_paper_type);
377         prefs_common.print_paper_type = g_strdup(gtk_paper_size_get_name(
378                                                 gtk_page_setup_get_paper_size(page_setup)));
379         prefs_common.print_paper_orientation = gtk_page_setup_get_orientation(page_setup);
380         /* store 100th millimeters */
381         prefs_common.print_margin_top    = (int) (100*gtk_page_setup_get_top_margin(page_setup, 
382                                                                 PAGE_MARGIN_STORAGE_UNIT));
383         prefs_common.print_margin_bottom = (int) (100*gtk_page_setup_get_bottom_margin(page_setup,
384                                                                 PAGE_MARGIN_STORAGE_UNIT));
385         prefs_common.print_margin_left   = (int) (100*gtk_page_setup_get_left_margin(page_setup,
386                                                                 PAGE_MARGIN_STORAGE_UNIT));
387         prefs_common.print_margin_right  = (int) (100*gtk_page_setup_get_right_margin(page_setup,
388                                                                 PAGE_MARGIN_STORAGE_UNIT));
389
390 #if GTK_CHECK_VERSION(2,14,0)
391         /* save to file */
392         keyfile = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
393                               PRINTING_PAGE_SETUP_STORAGE_FILE, NULL);
394         if (!gtk_page_setup_to_file(page_setup, keyfile, NULL)) {
395                 debug_print("Printing: Could not store page setup in file `%s'\n", keyfile);
396         }
397         g_free(keyfile);
398 #endif
399 }
400
401 static gboolean cb_preview(GtkPrintOperation        *operation,
402                            GtkPrintOperationPreview *preview,
403                            GtkPrintContext          *context,
404                            GtkWindow                *parent,
405                            gpointer                 data)
406 {
407         PrintData *print_data;
408         cairo_t *cr;
409         PreviewData *preview_data;
410         GtkWidget *vbox;
411         GtkWidget *toolbar;
412         GtkWidget *da;
413         GtkWidget *sw;
414         GtkWidget *page;
415         GtkToolItem *separator;
416         static GdkGeometry geometry;
417         GtkWidget *dialog = NULL;
418         GtkWidget *statusbar = gtk_hbox_new(2, FALSE);
419         CLAWS_TIP_DECL();
420
421         debug_print("Creating internal print preview\n");
422
423         print_data = (PrintData*) data;
424
425         preview_data = g_new0(PreviewData,1);
426         preview_data->print_data = print_data;
427         preview_data->op = g_object_ref(operation);
428         preview_data->preview = preview;
429
430         /* Window */
431         dialog = gtkut_window_new(GTK_WINDOW_TOPLEVEL, "print_preview");
432         preview_data->dialog = dialog;
433         if (!geometry.min_height) {
434                 geometry.min_width = 600;
435                 geometry.min_height = 400;
436         }
437         gtk_window_set_geometry_hints(GTK_WINDOW(dialog), NULL, &geometry,
438                                       GDK_HINT_MIN_SIZE);
439         gtk_widget_set_size_request(dialog, prefs_common.print_previewwin_width,
440                                     prefs_common.print_previewwin_height);
441         gtk_window_set_title(GTK_WINDOW(dialog), _("Print preview"));
442
443         /* vbox */
444         vbox = gtk_vbox_new(FALSE, 0);
445         gtk_container_add(GTK_CONTAINER(dialog), vbox);
446   
447         /* toolbar */
448         toolbar = gtk_toolbar_new();
449 #if (GTK_CHECK_VERSION(2,16,0))
450         gtk_orientable_set_orientation(GTK_ORIENTABLE(toolbar), GTK_ORIENTATION_HORIZONTAL);
451 #else
452         gtk_toolbar_set_orientation(GTK_TOOLBAR(toolbar), GTK_ORIENTATION_HORIZONTAL);
453 #endif
454         switch (prefs_common.toolbar_style) {
455                 case TOOLBAR_ICON:
456                         gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);
457                         break;
458                 case TOOLBAR_TEXT:
459                         gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_TEXT);
460                         break;
461                 case TOOLBAR_BOTH_HORIZ:
462                         gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_BOTH_HORIZ);
463                         break;
464                 case TOOLBAR_BOTH:
465                         default:          
466                         gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_BOTH);
467         }
468         gtk_toolbar_set_show_arrow(GTK_TOOLBAR(toolbar), TRUE);
469
470         gtk_box_pack_start(GTK_BOX(vbox), toolbar, FALSE, FALSE, 0);
471
472 #if !(GTK_CHECK_VERSION(2,12,0))
473 #define CLAWS_SET_TOOL_ITEM_TIP(widget,tip) { \
474         gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(widget), GTK_TOOLTIPS(tips),                    \
475                         tip, NULL);                                                             \
476 }
477 #else
478 #define CLAWS_SET_TOOL_ITEM_TIP(widget,tip) { \
479         gtk_tool_item_set_tooltip_text(GTK_TOOL_ITEM(widget), tip);                             \
480 }
481 #endif  
482
483 #define TOOLBAR_ITEM(item,text,tooltip,cb,cbdata) {                                                             \
484         item = GTK_WIDGET(gtk_tool_button_new_from_stock(text));                                        \
485         gtk_tool_item_set_homogeneous(GTK_TOOL_ITEM(item), FALSE);                                      \
486         gtk_tool_item_set_is_important(GTK_TOOL_ITEM(item), TRUE);                                      \
487         gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(item), -1);                              \
488         g_signal_connect (G_OBJECT(item), "clicked", G_CALLBACK(cb), cbdata);                           \
489         CLAWS_SET_TOOL_ITEM_TIP(GTK_TOOL_ITEM(item),            \
490                         tooltip);                                                                       \
491 }
492
493         TOOLBAR_ITEM(preview_data->first, GTK_STOCK_GOTO_FIRST,
494                      _("First page"), cb_preview_go_first, preview_data);
495         TOOLBAR_ITEM(preview_data->previous, GTK_STOCK_GO_BACK,
496                      _("Previous page"), cb_preview_go_previous, preview_data);
497
498         page = gtk_label_new("");
499         gtk_widget_set_size_request(page, 100, -1);
500         preview_data->page_nr_label = page;
501
502         TOOLBAR_ITEM(preview_data->next, GTK_STOCK_GO_FORWARD,
503                      _("Next page"), cb_preview_go_next, preview_data);
504         TOOLBAR_ITEM(preview_data->last, GTK_STOCK_GOTO_LAST,
505                      _("Last page"), cb_preview_go_last, preview_data);
506
507         separator = gtk_separator_tool_item_new();
508         gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(separator), -1);
509
510         TOOLBAR_ITEM(preview_data->zoom_100, GTK_STOCK_ZOOM_100,
511                      _("Zoom 100%"), cb_preview_zoom_100, preview_data);
512         TOOLBAR_ITEM(preview_data->zoom_fit, GTK_STOCK_ZOOM_FIT,
513                      _("Zoom fit"), cb_preview_zoom_fit, preview_data);
514         TOOLBAR_ITEM(preview_data->zoom_in, GTK_STOCK_ZOOM_IN,
515                      _("Zoom in"), cb_preview_zoom_in, preview_data);
516         TOOLBAR_ITEM(preview_data->zoom_out, GTK_STOCK_ZOOM_OUT,
517                      _("Zoom out"), cb_preview_zoom_out, preview_data);
518
519         separator = gtk_separator_tool_item_new();
520         gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(separator), -1);
521
522         /* tooltip has to be NULL else it triggers an expose_event */
523         TOOLBAR_ITEM(preview_data->close, GTK_STOCK_CLOSE, NULL,
524                      cb_preview_btn_close, preview_data);
525
526         gtk_widget_show(statusbar);
527         gtk_box_pack_start(GTK_BOX(vbox), statusbar, FALSE, FALSE, 0);
528         gtk_box_pack_start(GTK_BOX(statusbar), page, FALSE, FALSE, 0);
529         /* Drawing area */
530         sw = gtk_scrolled_window_new(NULL, NULL);
531         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
532                                        GTK_POLICY_AUTOMATIC,
533                                        GTK_POLICY_AUTOMATIC);
534         gtk_box_pack_start(GTK_BOX(vbox), sw, TRUE, TRUE, 0);
535         da = gtk_drawing_area_new();
536         gtk_widget_set_double_buffered(da, FALSE);
537         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(sw),
538                                               da);
539         gtk_widget_realize(da);
540         preview_data->scrolled_window = sw;
541         preview_data->area = da;
542
543         /* cairo context */
544         cr = gdk_cairo_create(gtk_widget_get_window(da));
545         gtk_print_context_set_cairo_context(context, cr, PREVIEW_SCALE, PREVIEW_SCALE);
546         cairo_destroy(cr);
547
548         /* signals */
549         g_signal_connect(dialog, "key_press_event",
550                          G_CALLBACK(cb_preview_close), preview_data);
551         g_signal_connect(dialog, "size_allocate",
552                          G_CALLBACK(cb_preview_size_allocate), NULL);
553         g_signal_connect(dialog, "destroy",G_CALLBACK(cb_preview_destroy),
554                          preview_data);
555         g_signal_connect(preview, "ready", G_CALLBACK(cb_preview_ready),
556                          preview_data);
557         g_signal_connect(preview, "got-page-size",
558                          G_CALLBACK(cb_preview_got_page_size), preview_data);
559
560         g_signal_connect(operation, "request-page-setup",
561                          G_CALLBACK(cb_preview_request_page_setup), preview_data);
562
563         gtk_widget_show_all(dialog);
564         return TRUE;
565 }
566
567 static void cb_preview_destroy(GtkWindow *window, gpointer data)
568 {
569         PreviewData *preview_data;
570         preview_data = (PreviewData*) data;
571
572         if (preview_data->rendering)
573                 return;
574         debug_print("Preview window destroyed\n");
575
576         gtk_print_operation_preview_end_preview(preview_data->preview);
577         g_object_unref(preview_data->op);
578         g_list_free(preview_data->pages_to_print);
579
580         g_free(preview_data);
581 }
582
583 static gboolean cb_preview_close(GtkWidget *widget, GdkEventAny *event,
584                                  gpointer data)
585 {
586         PreviewData *preview_data = (PreviewData *)data;
587         if (event->type == GDK_KEY_PRESS)
588                  if (((GdkEventKey *)event)->keyval != GDK_KEY_Escape)
589                         return FALSE;
590         if (preview_data->rendering)
591                 return FALSE; 
592         gtk_widget_destroy(widget);
593         return FALSE;
594 }
595
596 static void cb_preview_size_allocate(GtkWidget *widget,
597                                      GtkAllocation *allocation)
598 {
599         cm_return_if_fail(allocation != NULL);
600
601         prefs_common.print_previewwin_width = allocation->width;
602         prefs_common.print_previewwin_height = allocation->height;
603 }
604
605 static void cb_preview_ready(GtkPrintOperationPreview *preview,
606                              GtkPrintContext          *context,
607                              gpointer                  data)
608 {
609         PreviewData *preview_data;
610         gint iPage;
611         preview_data = (PreviewData*) data;
612         debug_print("preview_ready %d\n", preview_data->print_data->npages);
613
614         for (iPage = 0; iPage < (preview_data->print_data->npages); iPage++) {
615                 if (gtk_print_operation_preview_is_selected(preview_data->preview, iPage)) {
616                         preview_data->pages_to_print = 
617                                 g_list_prepend(preview_data->pages_to_print,
618                                                GINT_TO_POINTER(iPage));
619                         debug_print("want to print page %d\n",iPage+1);
620                 }
621         }
622
623         preview_data->pages_to_print = g_list_reverse(preview_data->pages_to_print);
624         preview_data->current_page = preview_data->pages_to_print;
625         preview_data->context = context;
626
627 #if !GTK_CHECK_VERSION(3, 0, 0)
628         g_signal_connect(preview_data->area, "expose_event",
629                          G_CALLBACK(cb_preview_expose),
630                          preview_data);
631 #else
632         g_signal_connect(preview_data->area, "draw",
633                          G_CALLBACK(cb_preview_expose),
634                          preview_data);
635 #endif
636
637         gtk_widget_queue_draw(preview_data->area);
638 }
639
640 static void cb_preview_got_page_size(GtkPrintOperationPreview *preview,
641                                      GtkPrintContext          *context,
642                                      GtkPageSetup             *page_setup,
643                                      gpointer                  data)
644 {
645         PreviewData *preview_data;
646         GtkPageOrientation orientation;
647         GtkPaperSize *paper_size;
648         gint paper_width;
649         gint paper_height;
650
651         preview_data = (PreviewData*) data;
652         debug_print("got_page_size\n");
653         orientation  = gtk_page_setup_get_orientation(page_setup);
654         paper_size   = gtk_page_setup_get_paper_size(page_setup);
655         paper_width  = (gint)(gtk_paper_size_get_width(paper_size, GTK_UNIT_INCH)  
656                               * PREVIEW_SCALE);
657         paper_height = (gint)(gtk_paper_size_get_height(paper_size,  GTK_UNIT_INCH)
658                               * PREVIEW_SCALE);
659
660         preview_data->page_width  = paper_width;
661         preview_data->page_height = paper_height;
662
663         debug_print("w/h %d/%d\n", paper_width, paper_height);
664         gtk_widget_set_size_request(GTK_WIDGET(preview_data->area), 
665                                     paper_width, paper_height);
666 }
667
668 #if !GTK_CHECK_VERSION(3, 0, 0)
669 static gboolean cb_preview_expose(GtkWidget *widget, GdkEventExpose *event,
670                                   gpointer data)
671 #else
672 static gboolean cb_preview_expose(GtkWidget *widget, cairo_t *event,
673                                   gpointer data)
674 #endif
675 {
676         PreviewData *preview_data = data;
677 #if !GTK_CHECK_VERSION(3, 0, 0)
678         cairo_t *cr;
679 #endif
680
681         debug_print("preview_expose (current %p)\n", preview_data->current_page);
682
683 #if !GTK_CHECK_VERSION(3, 0, 0)
684         cr = gdk_cairo_create(gtk_widget_get_window(preview_data->area));
685 #endif
686
687         /* background */
688         cairo_set_source_rgb(cr, 0.5, 0.5, 0.5);
689 #if !GTK_CHECK_VERSION(3, 0, 0)
690         cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height);
691 #else
692         cairo_rectangle(cr, 0, 0, event->area.width, event->area.height);
693 #endif
694         cairo_fill(cr);
695
696         /* shadow */
697         cairo_set_source_rgb(cr, 0., 0., 0.);
698         cairo_rectangle(cr, PREVIEW_SHADOW_OFFSET, PREVIEW_SHADOW_OFFSET,
699             preview_data->page_width+PREVIEW_SHADOW_OFFSET,
700             preview_data->page_height+PREVIEW_SHADOW_OFFSET);
701         cairo_fill(cr);
702
703         /* paper */
704         cairo_set_source_rgb(cr, 1., 1., 1.);
705         cairo_rectangle(cr, 0, 0,
706             preview_data->page_width,
707             preview_data->page_height);
708         cairo_fill(cr);
709
710         gtk_print_context_set_cairo_context(preview_data->context, cr, PREVIEW_SCALE, PREVIEW_SCALE);
711 #if !GTK_CHECK_VERSION(3, 0, 0)
712         cairo_destroy(cr);
713 #endif
714
715         if (preview_data->current_page) {
716                 preview_data->rendering = TRUE;
717                 gtk_widget_set_sensitive(preview_data->close, FALSE);
718                 int cur = GPOINTER_TO_INT(preview_data->current_page->data);
719                 gchar *str;
720                 str = g_strdup_printf(_("Page %d"), cur+1);
721                 gtk_label_set_text(GTK_LABEL(preview_data->page_nr_label), str);
722                 g_free(str);
723                 gtk_print_operation_preview_render_page(preview_data->preview,
724                                                         GPOINTER_TO_INT
725                                                         (preview_data->current_page->data));
726
727                 gtk_widget_set_sensitive(preview_data->first,
728                                          preview_data->current_page->prev != NULL);
729                 gtk_widget_set_sensitive(preview_data->previous,
730                                          preview_data->current_page->prev != NULL);
731                 gtk_widget_set_sensitive(preview_data->next,
732                                          preview_data->current_page->next != NULL);
733                 gtk_widget_set_sensitive(preview_data->last,
734                                          preview_data->current_page->next != NULL);
735                 gtk_widget_set_sensitive(preview_data->close, TRUE);
736                 preview_data->rendering = FALSE;
737         }
738         return TRUE;
739 }
740
741 static void cb_preview_go_first(GtkButton *button, gpointer data)
742 {
743         PreviewData *preview_data = (PreviewData*) data;
744         preview_data->current_page = preview_data->pages_to_print;
745         gtk_widget_queue_draw(preview_data->area);
746 }
747
748 static void cb_preview_go_previous(GtkButton *button, gpointer data)
749 {
750         GList *next;
751         PreviewData *preview_data = (PreviewData*) data;
752         next = g_list_previous(preview_data->current_page);
753         if (next)
754                 preview_data->current_page = next;
755         gtk_widget_queue_draw(preview_data->area);
756 }
757
758 static void cb_preview_go_next(GtkButton *button, gpointer data)
759 {
760         GList *next;
761         PreviewData *preview_data = (PreviewData*) data;
762         next = g_list_next(preview_data->current_page);
763         if (next)
764                 preview_data->current_page = next;
765         gtk_widget_queue_draw(preview_data->area);
766 }
767
768 static void cb_preview_go_last(GtkButton *button, gpointer data)
769 {
770         PreviewData *preview_data = (PreviewData*) data;
771         preview_data->current_page = g_list_last(preview_data->current_page);
772         gtk_widget_queue_draw(preview_data->area);
773 }
774
775 static void cb_preview_btn_close(GtkButton *button, gpointer data)
776 {
777         PreviewData *preview_data = (PreviewData *)data;
778         if (preview_data->rendering)
779                 return; 
780         gtk_widget_destroy(preview_data->dialog);
781 }
782
783 static void cb_preview_zoom_100(GtkButton *button, gpointer data)
784 {
785         PreviewData *preview_data = (PreviewData*) data;
786         if (preview_data->print_data->zoom != 1.) {
787                 preview_data->print_data->zoom = 1.;
788                 gtk_widget_queue_draw(preview_data->area);
789                 printing_preview_update_zoom_sensitivity(preview_data);
790         }
791 }
792
793 static void cb_preview_zoom_fit(GtkButton *button, gpointer data)
794 {
795         PreviewData *preview_data = (PreviewData*) data;
796         GtkAllocation allocation;
797         gdouble zoom_w;
798         gdouble zoom_h;
799
800         gtk_widget_get_allocation(preview_data->scrolled_window, &allocation);
801         zoom_w = ((gdouble)allocation.width) /
802                  ((gdouble)preview_data->page_width/preview_data->print_data->zoom +
803                   PREVIEW_SHADOW_OFFSET);
804         zoom_h = ((gdouble)allocation.height) /
805                  ((gdouble)preview_data->page_height/preview_data->print_data->zoom +
806                   PREVIEW_SHADOW_OFFSET);
807
808         preview_data->print_data->zoom = MIN(zoom_w,zoom_h) - 0.01;
809
810         if (preview_data->print_data->zoom > PREVIEW_ZOOM_MAX)
811                 preview_data->print_data->zoom = PREVIEW_ZOOM_MAX;
812         else if (preview_data->print_data->zoom < PREVIEW_ZOOM_MIN)
813                 preview_data->print_data->zoom = PREVIEW_ZOOM_MIN;
814
815         printing_preview_update_zoom_sensitivity(preview_data);
816         gtk_widget_queue_draw(preview_data->area);
817 }
818
819 static void cb_preview_zoom_in(GtkButton *button, gpointer data)
820 {
821         PreviewData *preview_data = (PreviewData*) data;
822         gdouble new_zoom;
823         new_zoom =  preview_data->print_data->zoom * PREVIEW_ZOOM_FAC;
824         if (new_zoom <= PREVIEW_ZOOM_MAX) {
825                 preview_data->print_data->zoom = new_zoom;
826                 printing_preview_update_zoom_sensitivity(preview_data);
827                 gtk_widget_queue_draw(preview_data->area);
828         }
829 }
830
831 static void cb_preview_zoom_out(GtkButton *button, gpointer data)
832 {
833         PreviewData *preview_data = (PreviewData*) data;
834         gdouble new_zoom;
835         new_zoom =  preview_data->print_data->zoom / PREVIEW_ZOOM_FAC;
836         if (new_zoom >= PREVIEW_ZOOM_MIN) {
837                 preview_data->print_data->zoom = new_zoom;
838                 printing_preview_update_zoom_sensitivity(preview_data);
839                 gtk_widget_queue_draw(preview_data->area);
840         }
841 }
842
843 static void cb_preview_request_page_setup(GtkPrintOperation *op,
844                                           GtkPrintContext *context,
845                                           gint page_nr,
846                                           GtkPageSetup *setup,gpointer data)
847 {
848         GtkPaperSize *paper_size;
849         GtkPaperSize *old_size;
850         gdouble width;
851         gdouble height;
852         gdouble top_margin;
853         gdouble bottom_margin;
854         gdouble left_margin;
855         gdouble right_margin;
856
857         PreviewData *preview_data = (PreviewData*) data;
858
859         old_size = gtk_page_setup_get_paper_size(setup);
860         width  = gtk_paper_size_get_width(old_size,GTK_UNIT_INCH);
861         height = gtk_paper_size_get_height(old_size,GTK_UNIT_INCH);
862
863         top_margin    = gtk_page_setup_get_top_margin(setup,GTK_UNIT_INCH);
864         bottom_margin = gtk_page_setup_get_bottom_margin(setup,GTK_UNIT_INCH);
865         left_margin   = gtk_page_setup_get_left_margin(setup,GTK_UNIT_INCH);
866         right_margin  = gtk_page_setup_get_right_margin(setup,GTK_UNIT_INCH);
867
868         paper_size = gtk_paper_size_new_custom("preview paper", "preview_paper",
869                                                width*preview_data->print_data->zoom,
870                                                height*preview_data->print_data->zoom,
871                                                GTK_UNIT_INCH);
872         gtk_page_setup_set_paper_size(setup, paper_size);
873         gtk_paper_size_free(paper_size);
874
875         gtk_page_setup_set_top_margin(setup,top_margin*preview_data->print_data->zoom,
876                                       GTK_UNIT_INCH);
877         gtk_page_setup_set_bottom_margin(setup,bottom_margin*preview_data->print_data->zoom,
878                                          GTK_UNIT_INCH);
879         gtk_page_setup_set_left_margin(setup,left_margin*preview_data->print_data->zoom,
880                                        GTK_UNIT_INCH);
881         gtk_page_setup_set_right_margin(setup,right_margin*preview_data->print_data->zoom,
882                                         GTK_UNIT_INCH);
883 }
884
885 static void printing_textview_cb_begin_print(GtkPrintOperation *op, GtkPrintContext *context,
886                            gpointer user_data)
887 {
888         double width, height;
889         int num_lines;
890         double page_height;
891         GList *page_breaks;
892         PrintData *print_data;
893         PangoFontDescription *desc;
894         int start, ii;
895         PangoLayoutIter *iter;
896         double start_pos;
897         gint header_end_pos;
898         gint num_header_lines;
899         gint dummy;
900         gboolean header_done;
901         gboolean has_headers = FALSE;
902         const gchar *text;
903         double line_height =0.;
904
905         print_data = (PrintData*) user_data;
906
907         debug_print("Preparing print job...\n");
908
909         width  = gtk_print_context_get_width(context);
910         height = gtk_print_context_get_height(context);
911
912         if (print_data->layout == NULL)
913                 print_data->layout = gtk_print_context_create_pango_layout(context);
914
915         if (prefs_common.use_different_print_font)
916                 desc = pango_font_description_from_string(prefs_common.printfont);
917         else
918                 desc = pango_font_description_copy(
919         pango_context_get_font_description(print_data->pango_context));
920
921         pango_layout_set_font_description(print_data->layout, desc);
922         pango_font_description_free(desc);
923
924         pango_layout_set_width(print_data->layout, width * PANGO_SCALE);
925         pango_layout_set_text(print_data->layout, (char *)print_data->to_print, -1);
926
927         printing_layout_set_text_attributes(print_data, context, &has_headers);
928
929         num_lines = pango_layout_get_line_count(print_data->layout);
930
931         page_breaks = NULL;
932         page_height = 0;
933         start = 0;
934         ii = 0;
935         start_pos = 0.;
936         iter = pango_layout_get_iter(print_data->layout);
937
938         /* find the last character of the header */
939         header_end_pos = 0;
940         header_done = FALSE;
941         text = pango_layout_get_text(print_data->layout);
942
943         if (has_headers) {
944                 if (text && *text && *text != '\n') {
945                         do {
946                                 if (text[0] == '\n' && (text[1] != '\0') && (text[1] == '\n'))
947                                         header_done = TRUE;
948                                 else
949                                         header_end_pos++;
950                                 text++;
951                         } while(*text && !header_done);
952                 }
953                 /* find line number for header end */
954                 pango_layout_index_to_line_x(print_data->layout, header_end_pos, 1,
955                                              &num_header_lines, &dummy);
956                 /* line count is zero-based */
957                 num_header_lines++;
958         } else {
959                 print_data->ypos_line = -1.0;
960         }
961
962         do {
963                 PangoRectangle logical_rect;
964                 PangoLayoutLine *line;
965                 PangoAttrShape *attr = NULL;
966                 int baseline;
967
968                 if (ii >= start) {
969                         line = pango_layout_iter_get_line(iter);
970
971                         pango_layout_iter_get_line_extents(iter, NULL, &logical_rect);
972                         baseline = pango_layout_iter_get_baseline(iter);
973
974                         if ((attr = g_hash_table_lookup(print_data->images,
975                                                 GINT_TO_POINTER(pango_layout_iter_get_index(iter)))) != NULL) {
976                                 line_height = (double)gdk_pixbuf_get_height(GDK_PIXBUF(attr->data));
977                         } else {
978                                 line_height = ((double)logical_rect.height) / PANGO_SCALE;
979                         }
980                 }
981                 if ((page_height + line_height) > height) {
982                         page_breaks = g_list_prepend(page_breaks, GINT_TO_POINTER(ii));
983                         page_height = 0;
984                 }
985
986                 if (has_headers && ii == num_header_lines) {
987                         int y0, y1;
988                         pango_layout_iter_get_line_yrange(iter,&y0,&y1);
989                         print_data->ypos_line = (double)y0 + 1./3.*((double)(y1 - y0))/2.;
990                 }
991
992                 page_height += line_height;
993                 ii++;
994         } while(ii < num_lines && pango_layout_iter_next_line(iter));
995         pango_layout_iter_free(iter);
996
997         page_breaks = g_list_reverse(page_breaks);
998         print_data->npages = g_list_length(page_breaks) + 1;    
999         print_data->page_breaks = page_breaks;
1000
1001         gtk_print_operation_set_n_pages(op, print_data->npages);
1002
1003         debug_print("Starting print job...\n");
1004 }
1005
1006 static cairo_surface_t *pixbuf_to_surface(GdkPixbuf *pixbuf)
1007 {
1008           cairo_surface_t *surface;
1009           cairo_format_t format;
1010           static const cairo_user_data_key_t key;
1011           guchar *pixels = g_malloc(
1012                                 4*
1013                                 gdk_pixbuf_get_width(pixbuf)*
1014                                 gdk_pixbuf_get_height(pixbuf));
1015           guchar *src_pixels = gdk_pixbuf_get_pixels (pixbuf);
1016           gint width = gdk_pixbuf_get_width(pixbuf);
1017           gint height = gdk_pixbuf_get_height(pixbuf);
1018           gint nchans = gdk_pixbuf_get_n_channels (pixbuf);
1019           gint stride = gdk_pixbuf_get_rowstride (pixbuf);
1020           gint j;
1021
1022           if (nchans == 3)
1023             format = CAIRO_FORMAT_RGB24;
1024           else
1025             format = CAIRO_FORMAT_ARGB32;
1026           surface = cairo_image_surface_create_for_data (pixels,         
1027                                                 format, width, height, 4*width);
1028           cairo_surface_set_user_data (surface, &key, 
1029                 pixels, (cairo_destroy_func_t)g_free);
1030
1031           for (j = height; j; j--) {
1032                 guchar *p = src_pixels;
1033                 guchar *q = pixels;
1034
1035                 if (nchans == 3) {
1036                         guchar *end = p + 3 * width;
1037
1038                         while (p < end) {
1039 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
1040                                 q[0] = p[2];
1041                                 q[1] = p[1];
1042                                 q[2] = p[0];
1043 #else
1044                                 q[1] = p[0];
1045                                 q[2] = p[1];
1046                                 q[3] = p[2];
1047 #endif
1048                                 p += 3;
1049                                 q += 4;
1050                         }
1051                 } else {
1052                         guchar *end = p + 4 * width;
1053                         guint t1,t2,t3;
1054
1055 #define MULT(d,c,a,t) G_STMT_START { t = c * a + 0x7f; d = ((t >> 8) + t) >> 8; } G_STMT_END
1056
1057                         while (p < end) {
1058 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
1059                                 MULT(q[0], p[2], p[3], t1);
1060                                 MULT(q[1], p[1], p[3], t2);
1061                                 MULT(q[2], p[0], p[3], t3);
1062                                 q[3] = p[3];
1063 #else
1064                                 q[0] = p[3];
1065                                 MULT(q[1], p[0], p[3], t1);
1066                                 MULT(q[2], p[1], p[3], t2);
1067                                 MULT(q[3], p[2], p[3], t3);
1068 #endif
1069
1070                                 p += 4;
1071                                 q += 4;
1072                         }
1073
1074 #undef MULT
1075                 }
1076
1077                 src_pixels += stride;
1078                 pixels += 4 * width;
1079         }
1080                 
1081         return surface;
1082 }
1083
1084 static void printing_textview_cb_draw_page(GtkPrintOperation *op, GtkPrintContext *context,
1085                          int page_nr, gpointer user_data)
1086 {
1087         cairo_t *cr;
1088         PrintData *print_data;
1089         int start, end, ii;
1090         GList *pagebreak;
1091         PangoLayoutIter *iter;
1092         double start_pos;
1093         gboolean notlast = TRUE;
1094
1095         print_data = (PrintData*) user_data;
1096
1097         if (page_nr == 0) {
1098                 start = 0;
1099         } else {
1100                 pagebreak = g_list_nth(print_data->page_breaks, page_nr - 1);
1101                 start = GPOINTER_TO_INT(pagebreak->data);
1102         }
1103
1104         pagebreak = g_list_nth(print_data->page_breaks, page_nr);
1105         if (pagebreak == NULL)
1106                 end = pango_layout_get_line_count(print_data->layout);
1107         else
1108                 end = GPOINTER_TO_INT(pagebreak->data);
1109
1110         cr = gtk_print_context_get_cairo_context(context);
1111         cairo_scale(cr, print_data->zoom, print_data->zoom);
1112         cairo_set_source_rgb(cr, 0., 0., 0.);
1113
1114         ii = 0;
1115         start_pos = 0.;
1116         iter = pango_layout_get_iter(print_data->layout);
1117         do {
1118                 PangoRectangle logical_rect;
1119                 PangoLayoutLine *line;
1120                 PangoAttrShape *attr = NULL;
1121                 int baseline;
1122
1123                 if (ii >= start) {
1124                         line = pango_layout_iter_get_line(iter);
1125
1126                         pango_layout_iter_get_line_extents(iter, NULL, &logical_rect);
1127                         baseline = pango_layout_iter_get_baseline(iter);
1128
1129                         if (ii == start)
1130                                 start_pos = ((double)logical_rect.y) / PANGO_SCALE;
1131
1132                         /* Draw header separator line */
1133                         if (ii == 0 && print_data->ypos_line >= 0) {
1134                                 cairo_surface_t *surface;
1135                                 surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
1136                                                 gtk_print_context_get_width(context)/print_data->zoom,
1137                                                 gtk_print_context_get_height(context)/print_data->zoom);
1138                                 cairo_set_line_width(cr, .5);
1139                                 cairo_set_source_surface(cr, surface,
1140                                                          ((double)logical_rect.x) / PANGO_SCALE, 
1141                                                          ((double)baseline) / PANGO_SCALE - start_pos);
1142                                 cairo_move_to(cr, ((double)logical_rect.x) / PANGO_SCALE,
1143                                               (double)print_data->ypos_line / PANGO_SCALE);
1144                                 cairo_rel_line_to(cr, gtk_print_context_get_width(context)/print_data->zoom, 0);
1145                                 cairo_set_source_rgb(cr, 0., 0., 0.);
1146                                 cairo_stroke(cr);
1147                                 cairo_surface_destroy(surface);
1148                         }
1149
1150                         cairo_move_to(cr,
1151                                       ((double)logical_rect.x) / PANGO_SCALE,
1152                                       ((double)baseline) / PANGO_SCALE - start_pos);
1153
1154                         if ((attr = g_hash_table_lookup(print_data->images,
1155                              GINT_TO_POINTER(pango_layout_iter_get_index(iter)))) != NULL) {
1156                                 cairo_surface_t *surface;
1157
1158                                 surface = pixbuf_to_surface(GDK_PIXBUF(attr->data));
1159                                 cairo_set_source_surface (cr, surface, 
1160                                                           ((double)logical_rect.x) / PANGO_SCALE, 
1161                                                           ((double)baseline) / PANGO_SCALE - start_pos);
1162                                 cairo_paint (cr);
1163                                 cairo_surface_destroy (surface);
1164                         } else {
1165                                 pango_cairo_show_layout_line(cr, line);
1166                         }
1167                 }
1168                 ii++;
1169         } while(ii < end && (notlast = pango_layout_iter_next_line(iter)));
1170         pango_layout_iter_free(iter);
1171         debug_print("Sent page %d to printer\n", page_nr+1);
1172 }
1173
1174 static void printing_layout_set_text_attributes(PrintData *print_data,
1175                                                 GtkPrintContext *context,
1176                                                 gboolean *has_headers)
1177 {
1178         GtkTextIter iter;
1179         PangoAttrList *attr_list;
1180         PangoAttribute *attr;
1181         GSList *open_attrs, *attr_walk;
1182         GtkTextView *text_view = GTK_TEXT_VIEW(print_data->renderer_data);
1183         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text_view);
1184
1185         *has_headers = FALSE;
1186
1187         attr_list = pango_attr_list_new();
1188         if (print_data->sel_start < 0 || print_data->sel_end <= print_data->sel_start) {
1189                 gtk_text_buffer_get_start_iter(buffer, &iter);
1190         } else {
1191                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, print_data->sel_start);
1192         }
1193
1194         open_attrs = NULL;
1195         do {
1196                 gboolean fg_set, bg_set, under_set, strike_set, weight_set;
1197                 GSList *tags, *tag_walk;
1198                 GtkTextTag *tag;
1199                 GdkColor *color = NULL;
1200                 PangoUnderline underline;
1201                 gboolean strikethrough;
1202                 gint weight;
1203                 GdkPixbuf *image;
1204
1205                 if (prefs_common.print_imgs && (image = gtk_text_iter_get_pixbuf(&iter)) != NULL) {
1206                         PangoRectangle rect = {0, 0, 0, 0};
1207                         gint startpos = printing_text_iter_get_offset_bytes(print_data, &iter);
1208                         gint h = gdk_pixbuf_get_height(image);
1209                         gint w = gdk_pixbuf_get_width(image);
1210                         gint a_h = gtk_print_context_get_height(context);
1211                         gint a_w = gtk_print_context_get_width(context);
1212                         gint r_h, r_w;
1213                         GdkPixbuf *scaled = NULL;
1214                         image_viewer_get_resized_size(w, h, a_w, a_h, &r_w, &r_h);
1215                         rect.x = 0;
1216                         rect.y = 0;
1217                         rect.width = r_w * PANGO_SCALE;
1218                         rect.height = r_h * PANGO_SCALE;
1219       
1220                         scaled = gdk_pixbuf_scale_simple(image, r_w, r_h, GDK_INTERP_BILINEAR);
1221                         attr = pango_attr_shape_new_with_data (&rect, &rect,
1222                                                                scaled, NULL, NULL);
1223                         attr->start_index = startpos;
1224                         attr->end_index = startpos+1;
1225                         pango_attr_list_insert(attr_list, attr);
1226                         g_hash_table_insert(print_data->images, GINT_TO_POINTER(startpos), attr);
1227                         print_data->img_cnt++;
1228                 }
1229
1230                 if (gtk_text_iter_ends_tag(&iter, NULL)) {
1231                         PangoAttrColor *attr_color;
1232                         PangoAttrInt   *attr_int;
1233
1234                         tags = gtk_text_iter_get_toggled_tags(&iter, FALSE);
1235                         for (tag_walk = tags; tag_walk != NULL; tag_walk = tag_walk->next) {
1236                                 gboolean found;
1237
1238                                 tag = GTK_TEXT_TAG(tag_walk->data);
1239                                 g_object_get(G_OBJECT(tag),
1240                                              "background-set", &bg_set,
1241                                              "foreground-set", &fg_set,
1242                                              "underline-set",&under_set,
1243                                              "strikethrough-set", &strike_set,
1244                                              "weight-set", &weight_set,
1245                                              NULL);
1246
1247                                 if (fg_set) {
1248                                         found = FALSE;
1249                                         for (attr_walk = open_attrs; attr_walk != NULL;
1250                                              attr_walk = attr_walk->next) {
1251                                                 attr = (PangoAttribute*)attr_walk->data;
1252                                                 if (attr->klass->type == PANGO_ATTR_FOREGROUND) {
1253                                                         attr_color = (PangoAttrColor*) attr;
1254                                                         g_object_get(G_OBJECT(tag), "foreground_gdk",
1255                                                                      &color, NULL);
1256                                                         if (color && 
1257                                                             printing_is_pango_gdk_color_equal(&(attr_color->color),
1258                                                             color)) {
1259                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1260                                                                 pango_attr_list_insert(attr_list, attr);
1261                                                                 found = TRUE;
1262                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1263                                                                 break;
1264                                                         }
1265                                                         if (color)
1266                                                                 gdk_color_free(color);
1267                                                 }
1268                                         }
1269                                         if (!found)
1270                                                 debug_print("Error generating attribute list.\n");
1271                                 }
1272
1273                                 if (bg_set) {
1274                                         found = FALSE;
1275                                         for (attr_walk = open_attrs; attr_walk != NULL;
1276                                              attr_walk = attr_walk->next) {
1277                                                 attr = (PangoAttribute*)attr_walk->data;
1278                                                 if (attr->klass->type == PANGO_ATTR_BACKGROUND) {
1279                                                         attr_color = (PangoAttrColor*) attr;
1280                                                         g_object_get(G_OBJECT(tag), "background-gdk",
1281                                                                      &color, NULL);
1282                                                         if (printing_is_pango_gdk_color_equal(&(attr_color->color),
1283                                                             color)) {
1284                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1285                                                                 pango_attr_list_insert(attr_list, attr);
1286                                                                 found = TRUE;
1287                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1288                                                                 break;
1289                                                         }
1290                                                         if (color)
1291                                                                 gdk_color_free(color);
1292                                                 }
1293                                         }
1294                                         if (!found)
1295                                                 debug_print("Error generating attribute list.\n");
1296                                 }
1297
1298                                 if (under_set) {
1299                                         found = FALSE;
1300                                         for (attr_walk = open_attrs; attr_walk != NULL;
1301                                              attr_walk = attr_walk->next) {
1302                                                 attr = (PangoAttribute*)attr_walk->data;
1303                                                 if (attr->klass->type == PANGO_ATTR_UNDERLINE) {
1304                                                         attr_int = (PangoAttrInt*)attr;
1305                                                         g_object_get(G_OBJECT(tag), "underline",
1306                                                                      &underline, NULL);
1307                                                         if (attr_int->value == underline) {
1308                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1309                                                                 pango_attr_list_insert(attr_list, attr);
1310                                                                 found = TRUE;
1311                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1312                                                                 break;
1313                                                         }
1314                                                 }
1315                                         }
1316                                         if (!found)
1317                                                 debug_print("Error generating attribute list.\n");
1318                                 }
1319
1320                                 if (strike_set) {
1321                                         found = FALSE;
1322                                         for (attr_walk = open_attrs; attr_walk != NULL;
1323                                              attr_walk = attr_walk->next) {
1324                                                 attr = (PangoAttribute*)attr_walk->data;
1325                                                 if (attr->klass->type == PANGO_ATTR_STRIKETHROUGH) {
1326                                                         attr_int = (PangoAttrInt*)attr;
1327                                                         g_object_get(G_OBJECT(tag), "strikethrough",
1328                                                                      &strikethrough, NULL);
1329                                                         if (attr_int->value == strikethrough) {
1330                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1331                                                                 pango_attr_list_insert(attr_list, attr);
1332                                                                 found = TRUE;
1333                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1334                                                                 break;
1335                                                         }
1336                                                 }
1337                                         }
1338                                         if (!found)
1339                                                 debug_print("Error generating attribute list.\n");
1340                                 }
1341
1342                                 if (weight_set) {
1343                                         found = FALSE;
1344                                         for (attr_walk = open_attrs; attr_walk != NULL;
1345                                             attr_walk = attr_walk->next) {
1346                                                 attr = (PangoAttribute*)attr_walk->data;
1347                                                 if (attr->klass->type == PANGO_ATTR_WEIGHT) {
1348                                                                 attr_int = (PangoAttrInt*)attr;
1349                                                         g_object_get(G_OBJECT(tag), "weight", &weight, NULL);
1350                                                         if (attr_int->value == weight) {
1351                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1352                                                                 pango_attr_list_insert(attr_list, attr);
1353                                                                 found = TRUE;
1354                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1355                                                                 break;
1356                                                         }
1357                                                 }
1358                                         }
1359                                         if (!found)
1360                                                 debug_print("Error generating attribute list.\n");
1361                                 }
1362                         }
1363                         g_slist_free(tags);
1364                 }
1365
1366                 if (gtk_text_iter_begins_tag(&iter, NULL)) {
1367                         tags = gtk_text_iter_get_toggled_tags(&iter, TRUE);
1368                         /* Sometimes, an iter has several weights. Use only the first in this case */
1369                         gboolean weight_set_for_this_iter;
1370                         weight_set_for_this_iter = FALSE;
1371                         for (tag_walk = tags; tag_walk != NULL; tag_walk = tag_walk->next) {
1372                                 tag = GTK_TEXT_TAG(tag_walk->data);
1373                                 g_object_get(G_OBJECT(tag),
1374                                              "background-set", &bg_set,
1375                                              "foreground-set", &fg_set,
1376                                              "underline-set", &under_set,
1377                                              "strikethrough-set", &strike_set,
1378                                              "weight-set", &weight_set,
1379                                              NULL);
1380                                 if (fg_set) {
1381                                         g_object_get(G_OBJECT(tag), "foreground-gdk", &color, NULL);
1382                                         attr = pango_attr_foreground_new(color->red,color->green,color->blue);
1383                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1384                                         open_attrs = g_slist_prepend(open_attrs, attr);
1385                                 }
1386                                 if (bg_set) {
1387                                         g_object_get(G_OBJECT(tag), "background-gdk", &color, NULL);
1388                                         attr = pango_attr_background_new(color->red,color->green,color->blue);
1389                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1390                                         open_attrs = g_slist_prepend(open_attrs, attr);
1391                                 }
1392                                 if (under_set) {
1393                                         g_object_get(G_OBJECT(tag), "underline", &underline, NULL);
1394                                         attr = pango_attr_underline_new(underline);
1395                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1396                                         open_attrs = g_slist_prepend(open_attrs, attr);   
1397                                 }
1398                                 if (strike_set) {
1399                                         g_object_get(G_OBJECT(tag), "strikethrough", &strikethrough, NULL);
1400                                         attr = pango_attr_strikethrough_new(strikethrough);
1401                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1402                                         open_attrs = g_slist_prepend(open_attrs, attr);   
1403                                 }
1404                                 if (weight_set && !weight_set_for_this_iter) {
1405                                         weight_set_for_this_iter = TRUE;
1406                                         g_object_get(G_OBJECT(tag), "weight", &weight, NULL);
1407                                         attr = pango_attr_weight_new(weight);
1408                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1409                                         open_attrs = g_slist_prepend(open_attrs, attr); 
1410                                         /* Hack to see if the first char is bold -- indicates header */
1411                                         if (attr->start_index == 0 && weight == PANGO_WEIGHT_BOLD) {
1412                                                 *has_headers = TRUE;
1413                                         }
1414                                 }
1415                         }
1416                         g_slist_free(tags);
1417                 }
1418     
1419         } while(!gtk_text_iter_is_end(&iter) && gtk_text_iter_forward_to_tag_toggle(&iter, NULL));
1420           
1421         /* close all open attributes */
1422         for (attr_walk = open_attrs; attr_walk != NULL; attr_walk = attr_walk->next) {
1423                 attr = (PangoAttribute*) attr_walk->data;
1424                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1425                 pango_attr_list_insert(attr_list, attr);
1426         }
1427         g_slist_free(open_attrs);
1428
1429         pango_layout_set_attributes(print_data->layout, attr_list);
1430         pango_attr_list_unref(attr_list);
1431 }
1432
1433 static gboolean printing_is_pango_gdk_color_equal(PangoColor *p, GdkColor *g)
1434 {
1435         return ((p->red == g->red) && (p->green == g->green) && (p->blue == g->blue));
1436 }
1437
1438 /* Pango has it's attribute in bytes, but GtkTextIter gets only an offset
1439  * in characters, so here we're returning an offset in bytes. 
1440  */
1441 static gint printing_text_iter_get_offset_bytes(PrintData *print_data, const GtkTextIter *iter)
1442 {
1443         gint off_chars;
1444         gint off_bytes;
1445         gchar *text;
1446         GtkTextIter start;
1447
1448         off_chars = gtk_text_iter_get_offset(iter);
1449         if (print_data->sel_start < 0 || print_data->sel_end <= print_data->sel_start) {
1450                 gtk_text_buffer_get_start_iter(gtk_text_iter_get_buffer(iter), &start);
1451         } else {
1452                 gtk_text_buffer_get_iter_at_offset(gtk_text_iter_get_buffer(iter), &start, print_data->sel_start);
1453         }
1454         text = gtk_text_iter_get_text(&start, iter);
1455         off_bytes = strlen(text);
1456         g_free(text);
1457         return off_bytes;
1458 }
1459
1460 static void printing_preview_update_zoom_sensitivity(PreviewData *preview_data)
1461 {
1462         if((preview_data->print_data->zoom * PREVIEW_ZOOM_FAC) > PREVIEW_ZOOM_MAX)
1463                 gtk_widget_set_sensitive(preview_data->zoom_in, FALSE);
1464         else
1465                 gtk_widget_set_sensitive(preview_data->zoom_in, TRUE);
1466
1467         if ((preview_data->print_data->zoom / PREVIEW_ZOOM_FAC) < PREVIEW_ZOOM_MIN)
1468                 gtk_widget_set_sensitive(preview_data->zoom_out, FALSE);
1469         else
1470                 gtk_widget_set_sensitive(preview_data->zoom_out, TRUE);
1471 }