8a969ad452d2b3bdc5f1b111ddbaae5c121e5424
[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         GtkPageOrientation orientation;
638         GtkPaperSize *paper_size;
639         gint paper_width;
640         gint paper_height;
641
642         preview_data = (PreviewData*) data;
643         debug_print("got_page_size\n");
644         orientation  = gtk_page_setup_get_orientation(page_setup);
645         paper_size   = gtk_page_setup_get_paper_size(page_setup);
646         paper_width  = (gint)(gtk_paper_size_get_width(paper_size, GTK_UNIT_INCH)  
647                               * PREVIEW_SCALE);
648         paper_height = (gint)(gtk_paper_size_get_height(paper_size,  GTK_UNIT_INCH)
649                               * PREVIEW_SCALE);
650
651         preview_data->page_width  = paper_width;
652         preview_data->page_height = paper_height;
653
654         debug_print("w/h %d/%d\n", paper_width, paper_height);
655         gtk_widget_set_size_request(GTK_WIDGET(preview_data->area), 
656                                     paper_width, paper_height);
657 }
658
659 #if !GTK_CHECK_VERSION(3, 0, 0)
660 static gboolean cb_preview_expose(GtkWidget *widget, GdkEventExpose *event,
661                                   gpointer data)
662 #else
663 static gboolean cb_preview_expose(GtkWidget *widget, cairo_t *event,
664                                   gpointer data)
665 #endif
666 {
667         PreviewData *preview_data = data;
668 #if !GTK_CHECK_VERSION(3, 0, 0)
669         cairo_t *cr;
670 #endif
671
672         debug_print("preview_expose (current %p)\n", preview_data->current_page);
673
674 #if !GTK_CHECK_VERSION(3, 0, 0)
675         cr = gdk_cairo_create(gtk_widget_get_window(preview_data->area));
676 #endif
677
678         /* background */
679         cairo_set_source_rgb(cr, 0.5, 0.5, 0.5);
680 #if !GTK_CHECK_VERSION(3, 0, 0)
681         cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height);
682 #else
683         cairo_rectangle(cr, 0, 0, event->area.width, event->area.height);
684 #endif
685         cairo_fill(cr);
686
687         /* shadow */
688         cairo_set_source_rgb(cr, 0., 0., 0.);
689         cairo_rectangle(cr, PREVIEW_SHADOW_OFFSET, PREVIEW_SHADOW_OFFSET,
690             preview_data->page_width+PREVIEW_SHADOW_OFFSET,
691             preview_data->page_height+PREVIEW_SHADOW_OFFSET);
692         cairo_fill(cr);
693
694         /* paper */
695         cairo_set_source_rgb(cr, 1., 1., 1.);
696         cairo_rectangle(cr, 0, 0,
697             preview_data->page_width,
698             preview_data->page_height);
699         cairo_fill(cr);
700
701         gtk_print_context_set_cairo_context(preview_data->context, cr, PREVIEW_SCALE, PREVIEW_SCALE);
702 #if !GTK_CHECK_VERSION(3, 0, 0)
703         cairo_destroy(cr);
704 #endif
705
706         if (preview_data->current_page) {
707                 preview_data->rendering = TRUE;
708                 gtk_widget_set_sensitive(preview_data->close, FALSE);
709                 int cur = GPOINTER_TO_INT(preview_data->current_page->data);
710                 gchar *str;
711                 str = g_strdup_printf(_("Page %d"), cur+1);
712                 gtk_label_set_text(GTK_LABEL(preview_data->page_nr_label), str);
713                 g_free(str);
714                 gtk_print_operation_preview_render_page(preview_data->preview,
715                                                         GPOINTER_TO_INT
716                                                         (preview_data->current_page->data));
717
718                 gtk_widget_set_sensitive(preview_data->first,
719                                          preview_data->current_page->prev != NULL);
720                 gtk_widget_set_sensitive(preview_data->previous,
721                                          preview_data->current_page->prev != NULL);
722                 gtk_widget_set_sensitive(preview_data->next,
723                                          preview_data->current_page->next != NULL);
724                 gtk_widget_set_sensitive(preview_data->last,
725                                          preview_data->current_page->next != NULL);
726                 gtk_widget_set_sensitive(preview_data->close, TRUE);
727                 preview_data->rendering = FALSE;
728         }
729         return TRUE;
730 }
731
732 static void cb_preview_go_first(GtkButton *button, gpointer data)
733 {
734         PreviewData *preview_data = (PreviewData*) data;
735         preview_data->current_page = preview_data->pages_to_print;
736         gtk_widget_queue_draw(preview_data->area);
737 }
738
739 static void cb_preview_go_previous(GtkButton *button, gpointer data)
740 {
741         GList *next;
742         PreviewData *preview_data = (PreviewData*) data;
743         next = g_list_previous(preview_data->current_page);
744         if (next)
745                 preview_data->current_page = next;
746         gtk_widget_queue_draw(preview_data->area);
747 }
748
749 static void cb_preview_go_next(GtkButton *button, gpointer data)
750 {
751         GList *next;
752         PreviewData *preview_data = (PreviewData*) data;
753         next = g_list_next(preview_data->current_page);
754         if (next)
755                 preview_data->current_page = next;
756         gtk_widget_queue_draw(preview_data->area);
757 }
758
759 static void cb_preview_go_last(GtkButton *button, gpointer data)
760 {
761         PreviewData *preview_data = (PreviewData*) data;
762         preview_data->current_page = g_list_last(preview_data->current_page);
763         gtk_widget_queue_draw(preview_data->area);
764 }
765
766 static void cb_preview_btn_close(GtkButton *button, gpointer data)
767 {
768         PreviewData *preview_data = (PreviewData *)data;
769         if (preview_data->rendering)
770                 return; 
771         gtk_widget_destroy(preview_data->dialog);
772 }
773
774 static void cb_preview_zoom_100(GtkButton *button, gpointer data)
775 {
776         PreviewData *preview_data = (PreviewData*) data;
777         if (preview_data->print_data->zoom != 1.) {
778                 preview_data->print_data->zoom = 1.;
779                 gtk_widget_queue_draw(preview_data->area);
780                 printing_preview_update_zoom_sensitivity(preview_data);
781         }
782 }
783
784 static void cb_preview_zoom_fit(GtkButton *button, gpointer data)
785 {
786         PreviewData *preview_data = (PreviewData*) data;
787         GtkAllocation allocation;
788         gdouble zoom_w;
789         gdouble zoom_h;
790
791         gtk_widget_get_allocation(preview_data->scrolled_window, &allocation);
792         zoom_w = ((gdouble)allocation.width) /
793                  ((gdouble)preview_data->page_width/preview_data->print_data->zoom +
794                   PREVIEW_SHADOW_OFFSET);
795         zoom_h = ((gdouble)allocation.height) /
796                  ((gdouble)preview_data->page_height/preview_data->print_data->zoom +
797                   PREVIEW_SHADOW_OFFSET);
798
799         preview_data->print_data->zoom = MIN(zoom_w,zoom_h) - 0.01;
800
801         if (preview_data->print_data->zoom > PREVIEW_ZOOM_MAX)
802                 preview_data->print_data->zoom = PREVIEW_ZOOM_MAX;
803         else if (preview_data->print_data->zoom < PREVIEW_ZOOM_MIN)
804                 preview_data->print_data->zoom = PREVIEW_ZOOM_MIN;
805
806         printing_preview_update_zoom_sensitivity(preview_data);
807         gtk_widget_queue_draw(preview_data->area);
808 }
809
810 static void cb_preview_zoom_in(GtkButton *button, gpointer data)
811 {
812         PreviewData *preview_data = (PreviewData*) data;
813         gdouble new_zoom;
814         new_zoom =  preview_data->print_data->zoom * PREVIEW_ZOOM_FAC;
815         if (new_zoom <= PREVIEW_ZOOM_MAX) {
816                 preview_data->print_data->zoom = new_zoom;
817                 printing_preview_update_zoom_sensitivity(preview_data);
818                 gtk_widget_queue_draw(preview_data->area);
819         }
820 }
821
822 static void cb_preview_zoom_out(GtkButton *button, gpointer data)
823 {
824         PreviewData *preview_data = (PreviewData*) data;
825         gdouble new_zoom;
826         new_zoom =  preview_data->print_data->zoom / PREVIEW_ZOOM_FAC;
827         if (new_zoom >= PREVIEW_ZOOM_MIN) {
828                 preview_data->print_data->zoom = new_zoom;
829                 printing_preview_update_zoom_sensitivity(preview_data);
830                 gtk_widget_queue_draw(preview_data->area);
831         }
832 }
833
834 static void cb_preview_request_page_setup(GtkPrintOperation *op,
835                                           GtkPrintContext *context,
836                                           gint page_nr,
837                                           GtkPageSetup *setup,gpointer data)
838 {
839         GtkPaperSize *paper_size;
840         GtkPaperSize *old_size;
841         gdouble width;
842         gdouble height;
843         gdouble top_margin;
844         gdouble bottom_margin;
845         gdouble left_margin;
846         gdouble right_margin;
847
848         PreviewData *preview_data = (PreviewData*) data;
849
850         old_size = gtk_page_setup_get_paper_size(setup);
851         width  = gtk_paper_size_get_width(old_size,GTK_UNIT_INCH);
852         height = gtk_paper_size_get_height(old_size,GTK_UNIT_INCH);
853
854         top_margin    = gtk_page_setup_get_top_margin(setup,GTK_UNIT_INCH);
855         bottom_margin = gtk_page_setup_get_bottom_margin(setup,GTK_UNIT_INCH);
856         left_margin   = gtk_page_setup_get_left_margin(setup,GTK_UNIT_INCH);
857         right_margin  = gtk_page_setup_get_right_margin(setup,GTK_UNIT_INCH);
858
859         paper_size = gtk_paper_size_new_custom("preview paper", "preview_paper",
860                                                width*preview_data->print_data->zoom,
861                                                height*preview_data->print_data->zoom,
862                                                GTK_UNIT_INCH);
863         gtk_page_setup_set_paper_size(setup, paper_size);
864         gtk_paper_size_free(paper_size);
865
866         gtk_page_setup_set_top_margin(setup,top_margin*preview_data->print_data->zoom,
867                                       GTK_UNIT_INCH);
868         gtk_page_setup_set_bottom_margin(setup,bottom_margin*preview_data->print_data->zoom,
869                                          GTK_UNIT_INCH);
870         gtk_page_setup_set_left_margin(setup,left_margin*preview_data->print_data->zoom,
871                                        GTK_UNIT_INCH);
872         gtk_page_setup_set_right_margin(setup,right_margin*preview_data->print_data->zoom,
873                                         GTK_UNIT_INCH);
874 }
875
876 static void printing_textview_cb_begin_print(GtkPrintOperation *op, GtkPrintContext *context,
877                            gpointer user_data)
878 {
879         double width, height;
880         int num_lines;
881         double page_height;
882         GList *page_breaks;
883         PrintData *print_data;
884         PangoFontDescription *desc;
885         int start, ii;
886         PangoLayoutIter *iter;
887         gint header_end_pos;
888         gint num_header_lines;
889         gint dummy;
890         gboolean header_done;
891         gboolean has_headers = FALSE;
892         const gchar *text;
893         double line_height =0.;
894
895         print_data = (PrintData*) user_data;
896
897         debug_print("Preparing print job...\n");
898
899         width  = gtk_print_context_get_width(context);
900         height = gtk_print_context_get_height(context);
901
902         if (print_data->layout == NULL)
903                 print_data->layout = gtk_print_context_create_pango_layout(context);
904
905         if (prefs_common.use_different_print_font)
906                 desc = pango_font_description_from_string(prefs_common.printfont);
907         else
908                 desc = pango_font_description_copy(
909         pango_context_get_font_description(print_data->pango_context));
910
911         pango_layout_set_font_description(print_data->layout, desc);
912         pango_font_description_free(desc);
913
914         pango_layout_set_width(print_data->layout, width * PANGO_SCALE);
915         pango_layout_set_text(print_data->layout, (char *)print_data->to_print, -1);
916
917         printing_layout_set_text_attributes(print_data, context, &has_headers);
918
919         num_lines = pango_layout_get_line_count(print_data->layout);
920
921         page_breaks = NULL;
922         page_height = 0;
923         start = 0;
924         ii = 0;
925         iter = pango_layout_get_iter(print_data->layout);
926
927         /* find the last character of the header */
928         header_end_pos = 0;
929         header_done = FALSE;
930         text = pango_layout_get_text(print_data->layout);
931
932         if (has_headers) {
933                 if (text && *text && *text != '\n') {
934                         do {
935                                 if (text[0] == '\n' && (text[1] != '\0') && (text[1] == '\n'))
936                                         header_done = TRUE;
937                                 else
938                                         header_end_pos++;
939                                 text++;
940                         } while(*text && !header_done);
941                 }
942                 /* find line number for header end */
943                 pango_layout_index_to_line_x(print_data->layout, header_end_pos, 1,
944                                              &num_header_lines, &dummy);
945                 /* line count is zero-based */
946                 num_header_lines++;
947         } else {
948                 print_data->ypos_line = -1.0;
949         }
950
951         do {
952                 PangoRectangle logical_rect;
953                 PangoLayoutLine *line;
954                 PangoAttrShape *attr = NULL;
955                 int baseline;
956
957                 if (ii >= start) {
958                         line = pango_layout_iter_get_line(iter);
959
960                         pango_layout_iter_get_line_extents(iter, NULL, &logical_rect);
961                         baseline = pango_layout_iter_get_baseline(iter);
962
963                         if ((attr = g_hash_table_lookup(print_data->images,
964                                                 GINT_TO_POINTER(pango_layout_iter_get_index(iter)))) != NULL) {
965                                 line_height = (double)gdk_pixbuf_get_height(GDK_PIXBUF(attr->data));
966                         } else {
967                                 line_height = ((double)logical_rect.height) / PANGO_SCALE;
968                         }
969                 }
970                 if ((page_height + line_height) > height) {
971                         page_breaks = g_list_prepend(page_breaks, GINT_TO_POINTER(ii));
972                         page_height = 0;
973                 }
974
975                 if (has_headers && ii == num_header_lines) {
976                         int y0, y1;
977                         pango_layout_iter_get_line_yrange(iter,&y0,&y1);
978                         print_data->ypos_line = (double)y0 + 1./3.*((double)(y1 - y0))/2.;
979                 }
980
981                 page_height += line_height;
982                 ii++;
983         } while(ii < num_lines && pango_layout_iter_next_line(iter));
984         pango_layout_iter_free(iter);
985
986         page_breaks = g_list_reverse(page_breaks);
987         print_data->npages = g_list_length(page_breaks) + 1;    
988         print_data->page_breaks = page_breaks;
989
990         gtk_print_operation_set_n_pages(op, print_data->npages);
991
992         debug_print("Starting print job...\n");
993 }
994
995 static cairo_surface_t *pixbuf_to_surface(GdkPixbuf *pixbuf)
996 {
997           cairo_surface_t *surface;
998           cairo_format_t format;
999           static const cairo_user_data_key_t key;
1000           guchar *pixels = g_malloc(
1001                                 4*
1002                                 gdk_pixbuf_get_width(pixbuf)*
1003                                 gdk_pixbuf_get_height(pixbuf));
1004           guchar *src_pixels = gdk_pixbuf_get_pixels (pixbuf);
1005           gint width = gdk_pixbuf_get_width(pixbuf);
1006           gint height = gdk_pixbuf_get_height(pixbuf);
1007           gint nchans = gdk_pixbuf_get_n_channels (pixbuf);
1008           gint stride = gdk_pixbuf_get_rowstride (pixbuf);
1009           gint j;
1010
1011           if (nchans == 3)
1012             format = CAIRO_FORMAT_RGB24;
1013           else
1014             format = CAIRO_FORMAT_ARGB32;
1015           surface = cairo_image_surface_create_for_data (pixels,         
1016                                                 format, width, height, 4*width);
1017           cairo_surface_set_user_data (surface, &key, 
1018                 pixels, (cairo_destroy_func_t)g_free);
1019
1020           for (j = height; j; j--) {
1021                 guchar *p = src_pixels;
1022                 guchar *q = pixels;
1023
1024                 if (nchans == 3) {
1025                         guchar *end = p + 3 * width;
1026
1027                         while (p < end) {
1028 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
1029                                 q[0] = p[2];
1030                                 q[1] = p[1];
1031                                 q[2] = p[0];
1032 #else
1033                                 q[1] = p[0];
1034                                 q[2] = p[1];
1035                                 q[3] = p[2];
1036 #endif
1037                                 p += 3;
1038                                 q += 4;
1039                         }
1040                 } else {
1041                         guchar *end = p + 4 * width;
1042                         guint t1,t2,t3;
1043
1044 #define MULT(d,c,a,t) G_STMT_START { t = c * a + 0x7f; d = ((t >> 8) + t) >> 8; } G_STMT_END
1045
1046                         while (p < end) {
1047 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
1048                                 MULT(q[0], p[2], p[3], t1);
1049                                 MULT(q[1], p[1], p[3], t2);
1050                                 MULT(q[2], p[0], p[3], t3);
1051                                 q[3] = p[3];
1052 #else
1053                                 q[0] = p[3];
1054                                 MULT(q[1], p[0], p[3], t1);
1055                                 MULT(q[2], p[1], p[3], t2);
1056                                 MULT(q[3], p[2], p[3], t3);
1057 #endif
1058
1059                                 p += 4;
1060                                 q += 4;
1061                         }
1062
1063 #undef MULT
1064                 }
1065
1066                 src_pixels += stride;
1067                 pixels += 4 * width;
1068         }
1069                 
1070         return surface;
1071 }
1072
1073 static void printing_textview_cb_draw_page(GtkPrintOperation *op, GtkPrintContext *context,
1074                          int page_nr, gpointer user_data)
1075 {
1076         cairo_t *cr;
1077         PrintData *print_data;
1078         int start, end, ii;
1079         GList *pagebreak;
1080         PangoLayoutIter *iter;
1081         double start_pos;
1082         gboolean notlast = TRUE;
1083
1084         print_data = (PrintData*) user_data;
1085
1086         if (page_nr == 0) {
1087                 start = 0;
1088         } else {
1089                 pagebreak = g_list_nth(print_data->page_breaks, page_nr - 1);
1090                 start = GPOINTER_TO_INT(pagebreak->data);
1091         }
1092
1093         pagebreak = g_list_nth(print_data->page_breaks, page_nr);
1094         if (pagebreak == NULL)
1095                 end = pango_layout_get_line_count(print_data->layout);
1096         else
1097                 end = GPOINTER_TO_INT(pagebreak->data);
1098
1099         cr = gtk_print_context_get_cairo_context(context);
1100         cairo_scale(cr, print_data->zoom, print_data->zoom);
1101         cairo_set_source_rgb(cr, 0., 0., 0.);
1102
1103         ii = 0;
1104         start_pos = 0.;
1105         iter = pango_layout_get_iter(print_data->layout);
1106         do {
1107                 PangoRectangle logical_rect;
1108                 PangoLayoutLine *line;
1109                 PangoAttrShape *attr = NULL;
1110                 int baseline;
1111
1112                 if (ii >= start) {
1113                         line = pango_layout_iter_get_line(iter);
1114
1115                         pango_layout_iter_get_line_extents(iter, NULL, &logical_rect);
1116                         baseline = pango_layout_iter_get_baseline(iter);
1117
1118                         if (ii == start)
1119                                 start_pos = ((double)logical_rect.y) / PANGO_SCALE;
1120
1121                         /* Draw header separator line */
1122                         if (ii == 0 && print_data->ypos_line >= 0) {
1123                                 cairo_surface_t *surface;
1124                                 surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
1125                                                 gtk_print_context_get_width(context)/print_data->zoom,
1126                                                 gtk_print_context_get_height(context)/print_data->zoom);
1127                                 cairo_set_line_width(cr, .5);
1128                                 cairo_set_source_surface(cr, surface,
1129                                                          ((double)logical_rect.x) / PANGO_SCALE, 
1130                                                          ((double)baseline) / PANGO_SCALE - start_pos);
1131                                 cairo_move_to(cr, ((double)logical_rect.x) / PANGO_SCALE,
1132                                               (double)print_data->ypos_line / PANGO_SCALE);
1133                                 cairo_rel_line_to(cr, gtk_print_context_get_width(context)/print_data->zoom, 0);
1134                                 cairo_set_source_rgb(cr, 0., 0., 0.);
1135                                 cairo_stroke(cr);
1136                                 cairo_surface_destroy(surface);
1137                         }
1138
1139                         cairo_move_to(cr,
1140                                       ((double)logical_rect.x) / PANGO_SCALE,
1141                                       ((double)baseline) / PANGO_SCALE - start_pos);
1142
1143                         if ((attr = g_hash_table_lookup(print_data->images,
1144                              GINT_TO_POINTER(pango_layout_iter_get_index(iter)))) != NULL) {
1145                                 cairo_surface_t *surface;
1146
1147                                 surface = pixbuf_to_surface(GDK_PIXBUF(attr->data));
1148                                 cairo_set_source_surface (cr, surface, 
1149                                                           ((double)logical_rect.x) / PANGO_SCALE, 
1150                                                           ((double)baseline) / PANGO_SCALE - start_pos);
1151                                 cairo_paint (cr);
1152                                 cairo_surface_destroy (surface);
1153                         } else {
1154                                 pango_cairo_show_layout_line(cr, line);
1155                         }
1156                 }
1157                 ii++;
1158         } while(ii < end && (notlast = pango_layout_iter_next_line(iter)));
1159         pango_layout_iter_free(iter);
1160         debug_print("Sent page %d to printer\n", page_nr+1);
1161 }
1162
1163 static void printing_layout_set_text_attributes(PrintData *print_data,
1164                                                 GtkPrintContext *context,
1165                                                 gboolean *has_headers)
1166 {
1167         GtkTextIter iter;
1168         PangoAttrList *attr_list;
1169         PangoAttribute *attr;
1170         GSList *open_attrs, *attr_walk;
1171         GtkTextView *text_view = GTK_TEXT_VIEW(print_data->renderer_data);
1172         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text_view);
1173
1174         *has_headers = FALSE;
1175
1176         attr_list = pango_attr_list_new();
1177         if (print_data->sel_start < 0 || print_data->sel_end <= print_data->sel_start) {
1178                 gtk_text_buffer_get_start_iter(buffer, &iter);
1179         } else {
1180                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, print_data->sel_start);
1181         }
1182
1183         open_attrs = NULL;
1184         do {
1185                 gboolean fg_set, bg_set, under_set, strike_set, weight_set;
1186                 GSList *tags, *tag_walk;
1187                 GtkTextTag *tag;
1188                 GdkColor *color = NULL;
1189                 PangoUnderline underline;
1190                 gboolean strikethrough;
1191                 gint weight;
1192                 GdkPixbuf *image;
1193
1194                 if (prefs_common.print_imgs && (image = gtk_text_iter_get_pixbuf(&iter)) != NULL) {
1195                         PangoRectangle rect = {0, 0, 0, 0};
1196                         gint startpos = printing_text_iter_get_offset_bytes(print_data, &iter);
1197                         gint h = gdk_pixbuf_get_height(image);
1198                         gint w = gdk_pixbuf_get_width(image);
1199                         gint a_h = gtk_print_context_get_height(context);
1200                         gint a_w = gtk_print_context_get_width(context);
1201                         gint r_h, r_w;
1202                         GdkPixbuf *scaled = NULL;
1203                         image_viewer_get_resized_size(w, h, a_w, a_h, &r_w, &r_h);
1204                         rect.x = 0;
1205                         rect.y = 0;
1206                         rect.width = r_w * PANGO_SCALE;
1207                         rect.height = r_h * PANGO_SCALE;
1208       
1209                         scaled = gdk_pixbuf_scale_simple(image, r_w, r_h, GDK_INTERP_BILINEAR);
1210                         attr = pango_attr_shape_new_with_data (&rect, &rect,
1211                                                                scaled, NULL, NULL);
1212                         attr->start_index = startpos;
1213                         attr->end_index = startpos+1;
1214                         pango_attr_list_insert(attr_list, attr);
1215                         g_hash_table_insert(print_data->images, GINT_TO_POINTER(startpos), attr);
1216                         print_data->img_cnt++;
1217                 }
1218
1219                 if (gtk_text_iter_ends_tag(&iter, NULL)) {
1220                         PangoAttrColor *attr_color;
1221                         PangoAttrInt   *attr_int;
1222
1223                         tags = gtk_text_iter_get_toggled_tags(&iter, FALSE);
1224                         for (tag_walk = tags; tag_walk != NULL; tag_walk = tag_walk->next) {
1225                                 gboolean found;
1226
1227                                 tag = GTK_TEXT_TAG(tag_walk->data);
1228                                 g_object_get(G_OBJECT(tag),
1229                                              "background-set", &bg_set,
1230                                              "foreground-set", &fg_set,
1231                                              "underline-set",&under_set,
1232                                              "strikethrough-set", &strike_set,
1233                                              "weight-set", &weight_set,
1234                                              NULL);
1235
1236                                 if (fg_set) {
1237                                         found = FALSE;
1238                                         for (attr_walk = open_attrs; attr_walk != NULL;
1239                                              attr_walk = attr_walk->next) {
1240                                                 attr = (PangoAttribute*)attr_walk->data;
1241                                                 if (attr->klass->type == PANGO_ATTR_FOREGROUND) {
1242                                                         attr_color = (PangoAttrColor*) attr;
1243                                                         g_object_get(G_OBJECT(tag), "foreground_gdk",
1244                                                                      &color, NULL);
1245                                                         if (color && 
1246                                                             printing_is_pango_gdk_color_equal(&(attr_color->color),
1247                                                             color)) {
1248                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1249                                                                 pango_attr_list_insert(attr_list, attr);
1250                                                                 found = TRUE;
1251                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1252                                                                 break;
1253                                                         }
1254                                                         if (color)
1255                                                                 gdk_color_free(color);
1256                                                 }
1257                                         }
1258                                         if (!found)
1259                                                 debug_print("Error generating attribute list.\n");
1260                                 }
1261
1262                                 if (bg_set) {
1263                                         found = FALSE;
1264                                         for (attr_walk = open_attrs; attr_walk != NULL;
1265                                              attr_walk = attr_walk->next) {
1266                                                 attr = (PangoAttribute*)attr_walk->data;
1267                                                 if (attr->klass->type == PANGO_ATTR_BACKGROUND) {
1268                                                         attr_color = (PangoAttrColor*) attr;
1269                                                         g_object_get(G_OBJECT(tag), "background-gdk",
1270                                                                      &color, NULL);
1271                                                         if (printing_is_pango_gdk_color_equal(&(attr_color->color),
1272                                                             color)) {
1273                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1274                                                                 pango_attr_list_insert(attr_list, attr);
1275                                                                 found = TRUE;
1276                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1277                                                                 break;
1278                                                         }
1279                                                         if (color)
1280                                                                 gdk_color_free(color);
1281                                                 }
1282                                         }
1283                                         if (!found)
1284                                                 debug_print("Error generating attribute list.\n");
1285                                 }
1286
1287                                 if (under_set) {
1288                                         found = FALSE;
1289                                         for (attr_walk = open_attrs; attr_walk != NULL;
1290                                              attr_walk = attr_walk->next) {
1291                                                 attr = (PangoAttribute*)attr_walk->data;
1292                                                 if (attr->klass->type == PANGO_ATTR_UNDERLINE) {
1293                                                         attr_int = (PangoAttrInt*)attr;
1294                                                         g_object_get(G_OBJECT(tag), "underline",
1295                                                                      &underline, NULL);
1296                                                         if (attr_int->value == underline) {
1297                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1298                                                                 pango_attr_list_insert(attr_list, attr);
1299                                                                 found = TRUE;
1300                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1301                                                                 break;
1302                                                         }
1303                                                 }
1304                                         }
1305                                         if (!found)
1306                                                 debug_print("Error generating attribute list.\n");
1307                                 }
1308
1309                                 if (strike_set) {
1310                                         found = FALSE;
1311                                         for (attr_walk = open_attrs; attr_walk != NULL;
1312                                              attr_walk = attr_walk->next) {
1313                                                 attr = (PangoAttribute*)attr_walk->data;
1314                                                 if (attr->klass->type == PANGO_ATTR_STRIKETHROUGH) {
1315                                                         attr_int = (PangoAttrInt*)attr;
1316                                                         g_object_get(G_OBJECT(tag), "strikethrough",
1317                                                                      &strikethrough, NULL);
1318                                                         if (attr_int->value == strikethrough) {
1319                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1320                                                                 pango_attr_list_insert(attr_list, attr);
1321                                                                 found = TRUE;
1322                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1323                                                                 break;
1324                                                         }
1325                                                 }
1326                                         }
1327                                         if (!found)
1328                                                 debug_print("Error generating attribute list.\n");
1329                                 }
1330
1331                                 if (weight_set) {
1332                                         found = FALSE;
1333                                         for (attr_walk = open_attrs; attr_walk != NULL;
1334                                             attr_walk = attr_walk->next) {
1335                                                 attr = (PangoAttribute*)attr_walk->data;
1336                                                 if (attr->klass->type == PANGO_ATTR_WEIGHT) {
1337                                                                 attr_int = (PangoAttrInt*)attr;
1338                                                         g_object_get(G_OBJECT(tag), "weight", &weight, NULL);
1339                                                         if (attr_int->value == weight) {
1340                                                                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1341                                                                 pango_attr_list_insert(attr_list, attr);
1342                                                                 found = TRUE;
1343                                                                 open_attrs = g_slist_delete_link(open_attrs, attr_walk);
1344                                                                 break;
1345                                                         }
1346                                                 }
1347                                         }
1348                                         if (!found)
1349                                                 debug_print("Error generating attribute list.\n");
1350                                 }
1351                         }
1352                         g_slist_free(tags);
1353                 }
1354
1355                 if (gtk_text_iter_begins_tag(&iter, NULL)) {
1356                         tags = gtk_text_iter_get_toggled_tags(&iter, TRUE);
1357                         /* Sometimes, an iter has several weights. Use only the first in this case */
1358                         gboolean weight_set_for_this_iter;
1359                         weight_set_for_this_iter = FALSE;
1360                         for (tag_walk = tags; tag_walk != NULL; tag_walk = tag_walk->next) {
1361                                 tag = GTK_TEXT_TAG(tag_walk->data);
1362                                 g_object_get(G_OBJECT(tag),
1363                                              "background-set", &bg_set,
1364                                              "foreground-set", &fg_set,
1365                                              "underline-set", &under_set,
1366                                              "strikethrough-set", &strike_set,
1367                                              "weight-set", &weight_set,
1368                                              NULL);
1369                                 if (fg_set) {
1370                                         g_object_get(G_OBJECT(tag), "foreground-gdk", &color, NULL);
1371                                         attr = pango_attr_foreground_new(color->red,color->green,color->blue);
1372                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1373                                         open_attrs = g_slist_prepend(open_attrs, attr);
1374                                 }
1375                                 if (bg_set) {
1376                                         g_object_get(G_OBJECT(tag), "background-gdk", &color, NULL);
1377                                         attr = pango_attr_background_new(color->red,color->green,color->blue);
1378                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1379                                         open_attrs = g_slist_prepend(open_attrs, attr);
1380                                 }
1381                                 if (under_set) {
1382                                         g_object_get(G_OBJECT(tag), "underline", &underline, NULL);
1383                                         attr = pango_attr_underline_new(underline);
1384                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1385                                         open_attrs = g_slist_prepend(open_attrs, attr);   
1386                                 }
1387                                 if (strike_set) {
1388                                         g_object_get(G_OBJECT(tag), "strikethrough", &strikethrough, NULL);
1389                                         attr = pango_attr_strikethrough_new(strikethrough);
1390                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1391                                         open_attrs = g_slist_prepend(open_attrs, attr);   
1392                                 }
1393                                 if (weight_set && !weight_set_for_this_iter) {
1394                                         weight_set_for_this_iter = TRUE;
1395                                         g_object_get(G_OBJECT(tag), "weight", &weight, NULL);
1396                                         attr = pango_attr_weight_new(weight);
1397                                         attr->start_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1398                                         open_attrs = g_slist_prepend(open_attrs, attr); 
1399                                         /* Hack to see if the first char is bold -- indicates header */
1400                                         if (attr->start_index == 0 && weight == PANGO_WEIGHT_BOLD) {
1401                                                 *has_headers = TRUE;
1402                                         }
1403                                 }
1404                         }
1405                         g_slist_free(tags);
1406                 }
1407     
1408         } while(!gtk_text_iter_is_end(&iter) && gtk_text_iter_forward_to_tag_toggle(&iter, NULL));
1409           
1410         /* close all open attributes */
1411         for (attr_walk = open_attrs; attr_walk != NULL; attr_walk = attr_walk->next) {
1412                 attr = (PangoAttribute*) attr_walk->data;
1413                 attr->end_index = printing_text_iter_get_offset_bytes(print_data, &iter);
1414                 pango_attr_list_insert(attr_list, attr);
1415         }
1416         g_slist_free(open_attrs);
1417
1418         pango_layout_set_attributes(print_data->layout, attr_list);
1419         pango_attr_list_unref(attr_list);
1420 }
1421
1422 static gboolean printing_is_pango_gdk_color_equal(PangoColor *p, GdkColor *g)
1423 {
1424         return ((p->red == g->red) && (p->green == g->green) && (p->blue == g->blue));
1425 }
1426
1427 /* Pango has it's attribute in bytes, but GtkTextIter gets only an offset
1428  * in characters, so here we're returning an offset in bytes. 
1429  */
1430 static gint printing_text_iter_get_offset_bytes(PrintData *print_data, const GtkTextIter *iter)
1431 {
1432         gint off_chars;
1433         gint off_bytes;
1434         gchar *text;
1435         GtkTextIter start;
1436
1437         off_chars = gtk_text_iter_get_offset(iter);
1438         if (print_data->sel_start < 0 || print_data->sel_end <= print_data->sel_start) {
1439                 gtk_text_buffer_get_start_iter(gtk_text_iter_get_buffer(iter), &start);
1440         } else {
1441                 gtk_text_buffer_get_iter_at_offset(gtk_text_iter_get_buffer(iter), &start, print_data->sel_start);
1442         }
1443         text = gtk_text_iter_get_text(&start, iter);
1444         off_bytes = strlen(text);
1445         g_free(text);
1446         return off_bytes;
1447 }
1448
1449 static void printing_preview_update_zoom_sensitivity(PreviewData *preview_data)
1450 {
1451         if((preview_data->print_data->zoom * PREVIEW_ZOOM_FAC) > PREVIEW_ZOOM_MAX)
1452                 gtk_widget_set_sensitive(preview_data->zoom_in, FALSE);
1453         else
1454                 gtk_widget_set_sensitive(preview_data->zoom_in, TRUE);
1455
1456         if ((preview_data->print_data->zoom / PREVIEW_ZOOM_FAC) < PREVIEW_ZOOM_MIN)
1457                 gtk_widget_set_sensitive(preview_data->zoom_out, FALSE);
1458         else
1459                 gtk_widget_set_sensitive(preview_data->zoom_out, TRUE);
1460 }