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