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