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