fc660896d155a98437143ca5d74f961e6097fac7
[pspp] / src / ui / gui / psppire-output-view.c
1 /* PSPPIRE - a graphical user interface for PSPP.
2    Copyright (C) 2008-2015, 2016 Free Software Foundation.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "ui/gui/psppire-output-view.h"
20
21 #include <errno.h>
22 #include <stdbool.h>
23
24 #include "libpspp/assertion.h"
25 #include "libpspp/string-map.h"
26 #include "output/cairo.h"
27 #include "output/driver-provider.h"
28 #include "output/driver.h"
29 #include "output/chart-item.h"
30 #include "output/group-item.h"
31 #include "output/message-item.h"
32 #include "output/output-item.h"
33 #include "output/table-item.h"
34 #include "output/text-item.h"
35
36 #include "gl/c-xvasprintf.h"
37 #include "gl/minmax.h"
38 #include "gl/tmpdir.h"
39 #include "gl/xalloc.h"
40
41 #include <gettext.h>
42 #define _(msgid) gettext (msgid)
43
44 struct output_view_item
45   {
46     struct output_item *item;
47     GtkWidget *drawing_area;
48   };
49
50 struct psppire_output_view
51   {
52     struct xr_driver *xr;
53     int font_height;
54
55     GtkLayout *output;
56     int render_width;
57     int max_width;
58     glong y;
59
60     struct string_map render_opts;
61     GtkTreeView *overview;
62     GtkTreeIter cur_command;
63     bool in_command;
64
65     GtkWidget *toplevel;
66
67     struct output_view_item *items;
68     size_t n_items, allocated_items;
69
70     /* Variables pertaining to printing */
71     GtkPrintSettings *print_settings;
72     struct xr_driver *print_xrd;
73     int print_item;
74     int print_n_pages;
75     gboolean paginated;
76   };
77
78 enum
79   {
80     COL_NAME,                   /* Table name. */
81     COL_ADDR,                   /* Pointer to the table */
82     COL_Y,                      /* Y position of top of name. */
83     N_COLS
84   };
85
86 /* Draws a white background on the GtkLayout to match the white background of
87    each of the output items. */
88 static gboolean
89 layout_draw_callback (GtkWidget *widget, cairo_t *cr, gpointer data)
90 {
91   cairo_save (cr);
92
93   int width = gtk_widget_get_allocated_width (widget);
94   int height = gtk_widget_get_allocated_height (widget);
95   cairo_rectangle (cr, 0, 0, width, height);
96   cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
97   cairo_fill (cr);
98
99   cairo_restore (cr);
100
101   return FALSE;                 /* Continue drawing the GtkDrawingAreas. */
102 }
103
104 static gboolean
105 draw_callback (GtkWidget *widget, cairo_t *cr, gpointer data)
106 {
107   GdkRectangle clip;
108   if (!gdk_cairo_get_clip_rectangle (cr, &clip))
109     return TRUE;
110
111   struct xr_rendering *r = g_object_get_data (G_OBJECT (widget), "rendering");
112   xr_rendering_draw (r, cr, clip.x, clip.y,
113                      clip.x + clip.width, clip.y + clip.height);
114   return TRUE;
115 }
116
117 static void
118 free_rendering (gpointer rendering_)
119 {
120   struct xr_rendering *rendering = rendering_;
121   xr_rendering_destroy (rendering);
122 }
123
124 static void
125 create_xr (struct psppire_output_view *view)
126 {
127   struct text_item *text_item;
128   PangoFontDescription *font_desc;
129   struct xr_rendering *r;
130   char *font_name;
131   int font_width;
132   cairo_t *cr;
133   gchar *fgc;
134
135   GtkStyleContext *context = gtk_widget_get_style_context (GTK_WIDGET (view->output));
136   GtkStateFlags state = gtk_widget_get_state_flags (GTK_WIDGET (view->output));
137   GdkRGBA *fg_color;
138
139   gtk_style_context_get (context, state,
140     "font", &font_desc, "color", &fg_color, NULL);
141
142   cr = gdk_cairo_create (gtk_widget_get_window (GTK_WIDGET (view->output)));
143
144   /* Set the widget's text color as the foreground color for the output driver */
145   /* gdk_rgba_to_string() would be perfect, but xr's parse_color does not      */
146   /* understand the rgb(255,128,33) format. Therefore we do it ourself.        */
147   fgc = xasprintf("#%4x%4x%4x",(int)(fg_color->red*0xffff),
148     (int)(fg_color->green*0xffff),(int)(fg_color->blue*0xffff));
149   string_map_insert (&view->render_opts, "foreground-color", fgc);
150   g_free (fgc);
151   gdk_rgba_free (fg_color);
152
153   /* Use GTK+ default font as proportional font. */
154   font_name = pango_font_description_to_string (font_desc);
155   string_map_insert (&view->render_opts, "prop-font", font_name);
156   g_free (font_name);
157
158   /* Derived emphasized font from proportional font. */
159   pango_font_description_set_style (font_desc, PANGO_STYLE_ITALIC);
160   font_name = pango_font_description_to_string (font_desc);
161   string_map_insert (&view->render_opts, "emph-font", font_name);
162   g_free (font_name);
163   pango_font_description_free (font_desc);
164
165   /* Pretend that the "page" has a reasonable width and a very big length,
166      so that most tables can be conveniently viewed on-screen with vertical
167      scrolling only.  (The length should not be increased very much because
168      it is already close enough to INT_MAX when expressed as thousands of a
169      point.) */
170   string_map_insert_nocopy (&view->render_opts, xstrdup ("paper-size"),
171                             xasprintf ("%dx1000000pt", view->render_width));
172   string_map_insert (&view->render_opts, "left-margin", "0");
173   string_map_insert (&view->render_opts, "right-margin", "0");
174   string_map_insert (&view->render_opts, "top-margin", "0");
175   string_map_insert (&view->render_opts, "bottom-margin", "0");
176
177   view->xr = xr_driver_create (cr, &view->render_opts);
178
179   text_item = text_item_create (TEXT_ITEM_PARAGRAPH, "X");
180   r = xr_rendering_create (view->xr, text_item_super (text_item), cr);
181   xr_rendering_measure (r, &font_width, &view->font_height);
182   text_item_unref (text_item);
183
184   cairo_destroy (cr);
185 }
186
187 /* Return the horizontal position to place a widget whose
188    width is CHILD_WIDTH */
189 static gint
190 get_xpos (const struct psppire_output_view *view, gint child_width)
191 {
192   GdkWindow *gdkw = gtk_widget_get_window (GTK_WIDGET (view->output));
193   guint w = gdk_window_get_width (gdkw);
194   int gutter = 0;
195   g_object_get (view->output, "border-width", &gutter, NULL);
196   return (gtk_widget_get_direction (GTK_WIDGET (view->output)) ==  GTK_TEXT_DIR_RTL) ? w - child_width - gutter: gutter;
197 }
198
199 static void
200 create_drawing_area (struct psppire_output_view *view,
201                      GtkWidget *drawing_area, struct xr_rendering *r,
202                      int tw, int th)
203 {
204   /* Enable this to help with debugging.  It shows you which widgets are being
205      put where. */
206   if (0)
207     {
208       GdkRGBA green = {0, 1, 0, 1};
209       gtk_widget_override_background_color (GTK_WIDGET (view->output),
210                                             GTK_STATE_FLAG_NORMAL, &green);
211       GdkRGBA red = {1, 0, 0, 1};
212       gtk_widget_override_background_color (drawing_area,
213                                             GTK_STATE_FLAG_NORMAL, &red);
214     }
215
216   g_object_set_data_full (G_OBJECT (drawing_area),
217                           "rendering", r, free_rendering);
218
219   g_signal_connect (drawing_area, "draw",
220                     G_CALLBACK (draw_callback), view);
221
222   gtk_widget_set_size_request (drawing_area, tw, th);
223   gint xpos = get_xpos (view, tw);
224
225   gtk_layout_put (view->output, drawing_area, xpos, view->y);
226
227   gtk_widget_show (drawing_area);
228 }
229
230 static void
231 rerender (struct psppire_output_view *view)
232 {
233   struct output_view_item *item;
234   GdkWindow *gdkw = gtk_widget_get_window (GTK_WIDGET (view->output));
235   cairo_t *cr;
236
237   if (!view->n_items || ! gdkw)
238     return;
239
240   cr = gdk_cairo_create (gdkw);
241   if (view->xr == NULL)
242     create_xr (view);
243   view->y = 0;
244   view->max_width = 0;
245   for (item = view->items; item < &view->items[view->n_items]; item++)
246     {
247       struct xr_rendering *r;
248       GtkAllocation alloc;
249       int tw, th;
250
251       if (view->y > 0)
252         view->y += view->font_height / 2;
253
254       r = xr_rendering_create (view->xr, item->item, cr);
255       if (r == NULL)
256         {
257           g_warn_if_reached ();
258           continue;
259         }
260
261       xr_rendering_measure (r, &tw, &th);
262
263       gint xpos = get_xpos (view, tw);
264
265       if (!item->drawing_area)
266         {
267           item->drawing_area = gtk_drawing_area_new ();
268           create_drawing_area (view, item->drawing_area, r, tw, th);
269         }
270       else
271         {
272           g_object_set_data_full (G_OBJECT (item->drawing_area),
273                                   "rendering", r, free_rendering);
274           gtk_widget_set_size_request (item->drawing_area, tw, th);
275           gtk_layout_move (view->output, item->drawing_area, xpos, view->y);
276         }
277
278       {
279         gint minw;
280         gint minh;
281         /* This code probably doesn't bring us anthing, but Gtk
282            shows warnings if get_preferred_width/height is not
283            called before the size_allocate below is called. */
284         gtk_widget_get_preferred_width (item->drawing_area, &minw, NULL);
285         gtk_widget_get_preferred_height (item->drawing_area, &minh, NULL);
286         if (th > minh) th = minh;
287         if (tw > minw) tw = minw;
288       }
289       alloc.x = xpos;
290       alloc.y = view->y;
291       alloc.width = tw;
292       alloc.height = th;
293
294       gtk_widget_size_allocate (item->drawing_area, &alloc);
295
296       if (view->max_width < tw)
297         view->max_width = tw;
298       view->y += th;
299     }
300
301   gtk_layout_set_size (view->output, view->max_width, view->y);
302   cairo_destroy (cr);
303 }
304
305 void
306 psppire_output_view_put (struct psppire_output_view *view,
307                          const struct output_item *item)
308 {
309   struct output_view_item *view_item;
310   GtkWidget *drawing_area;
311   struct xr_rendering *r;
312   struct string name;
313   GtkTreeStore *store;
314   cairo_t *cr = NULL;
315   GtkTreePath *path;
316   GtkTreeIter iter;
317   int tw, th;
318
319   if (is_group_close_item (item))
320     {
321       if (output_get_group_level () == 0)
322         {
323           view->in_command = false;
324           return;
325         }
326     }
327   else if (is_text_item (item))
328     {
329       const struct text_item *text_item = to_text_item (item);
330       const char *text = text_item_get_text (text_item);
331       if (text[0] == '\0')
332         return;
333     }
334
335   if (view->n_items >= view->allocated_items)
336     view->items = x2nrealloc (view->items, &view->allocated_items,
337                                 sizeof *view->items);
338   view_item = &view->items[view->n_items++];
339   view_item->item = output_item_ref (item);
340   view_item->drawing_area = NULL;
341
342   if (gtk_widget_get_window (GTK_WIDGET (view->output)))
343     {
344       view_item->drawing_area = drawing_area = gtk_drawing_area_new ();
345
346       cr = gdk_cairo_create (gtk_widget_get_window (GTK_WIDGET (view->output)));
347       if (view->xr == NULL)
348         create_xr (view);
349
350       if (view->y > 0)
351         view->y += view->font_height / 2;
352
353       r = xr_rendering_create (view->xr, item, cr);
354       if (r == NULL)
355         goto done;
356
357       xr_rendering_measure (r, &tw, &th);
358
359       create_drawing_area (view, drawing_area, r, tw, th);
360     }
361   else
362     tw = th = 0;
363
364   if (view->overview
365       && (!is_text_item (item)
366           || text_item_get_type (to_text_item (item)) != TEXT_ITEM_SYNTAX
367           || !view->in_command))
368     {
369       store = GTK_TREE_STORE (gtk_tree_view_get_model (view->overview));
370
371       ds_init_empty (&name);
372       if (is_group_open_item (item) && output_get_group_level () == 1)
373         {
374           gtk_tree_store_append (store, &iter, NULL);
375           view->cur_command = iter; /* XXX shouldn't save a GtkTreeIter */
376           view->in_command = true;
377         }
378       else
379         {
380           GtkTreeIter *p = view->in_command ? &view->cur_command : NULL;
381           gtk_tree_store_append (store, &iter, p);
382         }
383
384       ds_clear (&name);
385       if (is_text_item (item))
386         ds_put_cstr (&name, text_item_get_text (to_text_item (item)));
387       else if (is_message_item (item))
388         {
389           const struct message_item *msg_item = to_message_item (item);
390           const struct msg *msg = message_item_get_msg (msg_item);
391           ds_put_format (&name, "%s: %s", _("Message"),
392                          msg_severity_to_string (msg->severity));
393         }
394       else if (is_table_item (item))
395         {
396           const struct table_item_text *title
397             = table_item_get_title (to_table_item (item));
398           if (title != NULL)
399             ds_put_format (&name, "Table: %s", title->content);
400           else
401             ds_put_cstr (&name, "Table");
402         }
403       else if (is_chart_item (item))
404         {
405           const char *s = chart_item_get_title (to_chart_item (item));
406           if (s != NULL)
407             ds_put_format (&name, "Chart: %s", s);
408           else
409             ds_put_cstr (&name, "Chart");
410         }
411       else if (is_group_open_item (item))
412         ds_put_cstr (&name, to_group_open_item (item)->command_name);
413       gtk_tree_store_set (store, &iter,
414                           COL_NAME, ds_cstr (&name),
415                           COL_ADDR, item,
416                           COL_Y, (view->y),
417                           -1);
418       ds_destroy (&name);
419
420       path = gtk_tree_model_get_path (GTK_TREE_MODEL (store), &iter);
421       gtk_tree_view_expand_row (view->overview, path, TRUE);
422       gtk_tree_path_free (path);
423     }
424
425   if (view->max_width < tw)
426     view->max_width = tw;
427   view->y += th;
428
429   gtk_layout_set_size (view->output, view->max_width, view->y);
430
431 done:
432   cairo_destroy (cr);
433 }
434
435 static void
436 on_row_activate (GtkTreeView *overview,
437                  GtkTreePath *path,
438                  GtkTreeViewColumn *column,
439                  struct psppire_output_view *view)
440 {
441   GtkTreeModel *model;
442   GtkTreeIter iter;
443   GtkAdjustment *vadj;
444   GValue value = {0};
445   double y, min, max;
446
447   model = gtk_tree_view_get_model (overview);
448   if (!gtk_tree_model_get_iter (model, &iter, path))
449     return;
450
451   gtk_tree_model_get_value (model, &iter, COL_Y, &value);
452   y = g_value_get_long (&value);
453   g_value_unset (&value);
454
455   vadj = gtk_scrollable_get_vadjustment (GTK_SCROLLABLE (view->output));
456   min = gtk_adjustment_get_lower (vadj);
457   max = gtk_adjustment_get_upper (vadj) - gtk_adjustment_get_page_size (vadj);
458   if (y < min)
459     y = min;
460   else if (y > max)
461     y = max;
462   gtk_adjustment_set_value (vadj, y);
463 }
464
465 static void
466 on_style_updated (GtkWidget *toplevel, struct psppire_output_view *view)
467 {
468   if (!view->n_items || !gtk_widget_get_window (GTK_WIDGET (view->output)))
469     return;
470   string_map_clear (&view->render_opts);
471   xr_driver_destroy (view->xr);
472   create_xr (view);
473   rerender (view);
474 }
475
476 enum {
477   SELECT_FMT_NULL,
478   SELECT_FMT_TEXT,
479   SELECT_FMT_UTF8,
480   SELECT_FMT_HTML,
481   SELECT_FMT_ODT
482 };
483
484 /* GNU Hurd doesn't have PATH_MAX.  Use a fallback.
485    Temporary directory names are usually not that long.  */
486 #ifndef PATH_MAX
487 # define PATH_MAX 1024
488 #endif
489
490 static void
491 clipboard_get_cb (GtkClipboard     *clipboard,
492                   GtkSelectionData *selection_data,
493                   guint             info,
494                   gpointer          data)
495 {
496   struct psppire_output_view *view = data;
497
498   gsize length;
499   gchar *text = NULL;
500   struct output_driver *driver = NULL;
501   char dirname[PATH_MAX], *filename;
502   struct string_map options;
503
504   GtkTreeSelection *sel = gtk_tree_view_get_selection (view->overview);
505   GtkTreeModel *model = gtk_tree_view_get_model (view->overview);
506
507   GList *rows = gtk_tree_selection_get_selected_rows (sel, &model);
508   GList *n = rows;
509
510   if ( n == NULL)
511     return;
512
513   if (path_search (dirname, sizeof dirname, NULL, NULL, true)
514       || mkdtemp (dirname) == NULL)
515     {
516       msg_error (errno, _("failed to create temporary directory during clipboard operation"));
517       return;
518     }
519   filename = xasprintf ("%s/clip.tmp", dirname);
520
521   string_map_init (&options);
522   string_map_insert (&options, "output-file", filename);
523
524   switch (info)
525     {
526     case SELECT_FMT_UTF8:
527       string_map_insert (&options, "box", "unicode");
528       /* fall-through */
529
530     case SELECT_FMT_TEXT:
531       string_map_insert (&options, "format", "txt");
532       break;
533
534     case SELECT_FMT_HTML:
535       string_map_insert (&options, "format", "html");
536       string_map_insert (&options, "borders", "false");
537       string_map_insert (&options, "css", "false");
538       break;
539
540     case SELECT_FMT_ODT:
541       string_map_insert (&options, "format", "odt");
542       break;
543
544     default:
545       g_warning ("unsupported clip target\n");
546       goto finish;
547       break;
548     }
549
550   driver = output_driver_create (&options);
551   if (driver == NULL)
552     goto finish;
553
554   while (n)
555     {
556       GtkTreePath *path = n->data ;
557       GtkTreeIter iter;
558       struct output_item *item ;
559
560       gtk_tree_model_get_iter (model, &iter, path);
561       gtk_tree_model_get (model, &iter, COL_ADDR, &item, -1);
562
563       driver->class->submit (driver, item);
564
565       n = n->next;
566     }
567
568   if ( driver->class->flush)
569     driver->class->flush (driver);
570
571
572   /* Some drivers (eg: the odt one) don't write anything until they
573      are closed */
574   output_driver_destroy (driver);
575   driver = NULL;
576
577   if ( g_file_get_contents (filename, &text, &length, NULL) )
578     {
579       gtk_selection_data_set (selection_data, gtk_selection_data_get_target (selection_data),
580                               8,
581                               (const guchar *) text, length);
582     }
583
584  finish:
585
586   if (driver != NULL)
587     output_driver_destroy (driver);
588
589   g_free (text);
590
591   unlink (filename);
592   free (filename);
593   rmdir (dirname);
594
595   g_list_free (rows);
596 }
597
598 static void
599 clipboard_clear_cb (GtkClipboard *clipboard,
600                     gpointer data)
601 {
602 }
603
604 static const GtkTargetEntry targets[] = {
605
606   { "STRING",        0, SELECT_FMT_TEXT },
607   { "TEXT",          0, SELECT_FMT_TEXT },
608   { "COMPOUND_TEXT", 0, SELECT_FMT_TEXT },
609   { "text/plain",    0, SELECT_FMT_TEXT },
610
611   { "UTF8_STRING",   0, SELECT_FMT_UTF8 },
612   { "text/plain;charset=utf-8", 0, SELECT_FMT_UTF8 },
613
614   { "text/html",     0, SELECT_FMT_HTML },
615
616   { "application/vnd.oasis.opendocument.text", 0, SELECT_FMT_ODT }
617 };
618
619 static void
620 on_copy (struct psppire_output_view *view)
621 {
622   GtkWidget *widget = GTK_WIDGET (view->overview);
623   GtkClipboard *cb = gtk_widget_get_clipboard (widget, GDK_SELECTION_CLIPBOARD);
624
625   if (!gtk_clipboard_set_with_data (cb, targets, G_N_ELEMENTS (targets),
626                                     clipboard_get_cb, clipboard_clear_cb,
627                                     view))
628     clipboard_clear_cb (cb, view);
629 }
630
631 static void
632 on_selection_change (GtkTreeSelection *sel, GAction *copy_action)
633 {
634   /* The Copy action is available only if there is something selected */
635   g_object_set (copy_action,
636                 "enabled", gtk_tree_selection_count_selected_rows (sel) > 0,
637                 NULL);
638 }
639
640 static void
641 on_select_all (struct psppire_output_view *view)
642 {
643   GtkTreeSelection *sel = gtk_tree_view_get_selection (view->overview);
644   gtk_tree_view_expand_all (view->overview);
645   gtk_tree_selection_select_all (sel);
646 }
647
648 static void
649 on_size_allocate (GtkWidget    *widget,
650                   GdkRectangle *allocation,
651                   struct psppire_output_view *view)
652 {
653   view->render_width = MAX (300, allocation->width);
654   rerender (view);
655 }
656
657 static void
658 on_realize (GtkWidget *overview, GObject *view)
659 {
660   GtkTreeSelection *sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (overview));
661   gtk_tree_selection_set_mode (sel, GTK_SELECTION_MULTIPLE);
662
663   GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (overview));
664
665   GAction *copy_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
666                                                      "copy");
667
668   GAction *select_all_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
669                                                            "select-all");
670
671   g_object_set (copy_action, "enabled", FALSE, NULL);
672
673   g_signal_connect_swapped (select_all_action, "activate",
674                             G_CALLBACK (on_select_all), view);
675
676   g_signal_connect_swapped (copy_action, "activate",
677                             G_CALLBACK (on_copy), view);
678
679   g_signal_connect (sel, "changed", G_CALLBACK (on_selection_change),
680                     copy_action);
681 }
682
683 struct psppire_output_view *
684 psppire_output_view_new (GtkLayout *output, GtkTreeView *overview)
685 {
686   struct psppire_output_view *view;
687   GtkTreeViewColumn *column;
688   GtkCellRenderer *renderer;
689
690   GtkTreeModel *model;
691
692   view = xmalloc (sizeof *view);
693   view->xr = NULL;
694   view->font_height = 0;
695   view->output = output;
696   view->render_width = 0;
697   view->max_width = 0;
698   view->y = 0;
699   string_map_init (&view->render_opts);
700   view->overview = overview;
701   memset (&view->cur_command, 0, sizeof view->cur_command);
702   view->in_command = false;
703   view->toplevel = gtk_widget_get_toplevel (GTK_WIDGET (output));
704   view->items = NULL;
705   view->n_items = view->allocated_items = 0;
706   view->print_settings = NULL;
707   view->print_xrd = NULL;
708   view->print_item = 0;
709   view->print_n_pages = 0;
710   view->paginated = FALSE;
711
712   g_signal_connect (output, "draw", G_CALLBACK (layout_draw_callback), NULL);
713
714   g_signal_connect (output, "style-updated", G_CALLBACK (on_style_updated), view);
715
716   g_signal_connect (output, "size-allocate", G_CALLBACK (on_size_allocate), view);
717
718   gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (output)),
719                                GTK_STYLE_CLASS_VIEW);
720
721   if (overview)
722     {
723       g_signal_connect (overview, "realize", G_CALLBACK (on_realize), view);
724
725       model = GTK_TREE_MODEL (gtk_tree_store_new (
726                                 N_COLS,
727                                 G_TYPE_STRING,  /* COL_NAME */
728                                 G_TYPE_POINTER, /* COL_ADDR */
729                                 G_TYPE_LONG));  /* COL_Y */
730       gtk_tree_view_set_model (overview, model);
731       g_object_unref (model);
732
733       column = gtk_tree_view_column_new ();
734       gtk_tree_view_append_column (GTK_TREE_VIEW (overview), column);
735       renderer = gtk_cell_renderer_text_new ();
736       gtk_tree_view_column_pack_start (column, renderer, TRUE);
737       gtk_tree_view_column_add_attribute (column, renderer, "text", COL_NAME);
738
739       g_signal_connect (GTK_TREE_VIEW (overview),
740                         "row-activated", G_CALLBACK (on_row_activate), view);
741     }
742
743   return view;
744 }
745
746 void
747 psppire_output_view_destroy (struct psppire_output_view *view)
748 {
749   size_t i;
750
751   if (!view)
752     return;
753
754   g_signal_handlers_disconnect_by_func (view->output,
755                                         G_CALLBACK (on_style_updated), view);
756
757   string_map_destroy (&view->render_opts);
758
759   for (i = 0; i < view->n_items; i++)
760     output_item_unref (view->items[i].item);
761   free (view->items);
762   view->items = NULL;
763   view->n_items = view->allocated_items = 0;
764
765   if (view->print_settings != NULL)
766     g_object_unref (view->print_settings);
767
768   xr_driver_destroy (view->xr);
769
770   free (view);
771 }
772
773 void
774 psppire_output_view_clear (struct psppire_output_view *view)
775 {
776   size_t i;
777
778   view->max_width = 0;
779   view->y = 0;
780
781   for (i = 0; i < view->n_items; i++)
782     {
783       gtk_container_remove (GTK_CONTAINER (view->output),
784                             view->items[i].drawing_area);
785       output_item_unref (view->items[i].item);
786     }
787   free (view->items);
788   view->items = NULL;
789   view->n_items = view->allocated_items = 0;
790 }
791
792 /* Export. */
793
794 void
795 psppire_output_view_export (struct psppire_output_view *view,
796                             struct string_map *options)
797 {
798   struct output_driver *driver;
799
800   driver = output_driver_create (options);
801   if (driver)
802     {
803       size_t i;
804
805       for (i = 0; i < view->n_items; i++)
806         driver->class->submit (driver, view->items[i].item);
807       output_driver_destroy (driver);
808     }
809 }
810 \f
811 /* Print. */
812
813 static cairo_t *
814 get_cairo_context_from_print_context (GtkPrintContext *context)
815 {
816   cairo_t *cr = gtk_print_context_get_cairo_context (context);
817
818   /*
819     For all platforms except windows, gtk_print_context_get_dpi_[xy] returns 72.
820     Windows returns 600.
821   */
822   double xres = gtk_print_context_get_dpi_x (context);
823   double yres = gtk_print_context_get_dpi_y (context);
824
825   /* This means that the cairo context now has its dimensions in Points */
826   cairo_scale (cr, xres / 72.0, yres / 72.0);
827
828   return cr;
829 }
830
831
832 static void
833 create_xr_print_driver (GtkPrintContext *context, struct psppire_output_view *view)
834 {
835   struct string_map options;
836   GtkPageSetup *page_setup;
837   double width, height;
838   double left_margin;
839   double right_margin;
840   double top_margin;
841   double bottom_margin;
842
843   page_setup = gtk_print_context_get_page_setup (context);
844   width = gtk_page_setup_get_paper_width (page_setup, GTK_UNIT_MM);
845   height = gtk_page_setup_get_paper_height (page_setup, GTK_UNIT_MM);
846   left_margin = gtk_page_setup_get_left_margin (page_setup, GTK_UNIT_MM);
847   right_margin = gtk_page_setup_get_right_margin (page_setup, GTK_UNIT_MM);
848   top_margin = gtk_page_setup_get_top_margin (page_setup, GTK_UNIT_MM);
849   bottom_margin = gtk_page_setup_get_bottom_margin (page_setup, GTK_UNIT_MM);
850
851   string_map_init (&options);
852   string_map_insert_nocopy (&options, xstrdup ("paper-size"),
853                             c_xasprintf("%.2fx%.2fmm", width, height));
854   string_map_insert_nocopy (&options, xstrdup ("left-margin"),
855                             c_xasprintf ("%.2fmm", left_margin));
856   string_map_insert_nocopy (&options, xstrdup ("right-margin"),
857                             c_xasprintf ("%.2fmm", right_margin));
858   string_map_insert_nocopy (&options, xstrdup ("top-margin"),
859                             c_xasprintf ("%.2fmm", top_margin));
860   string_map_insert_nocopy (&options, xstrdup ("bottom-margin"),
861                             c_xasprintf ("%.2fmm", bottom_margin));
862
863   view->print_xrd = xr_driver_create (get_cairo_context_from_print_context (context), &options);
864
865   string_map_destroy (&options);
866 }
867
868 static gboolean
869 paginate (GtkPrintOperation *operation,
870           GtkPrintContext   *context,
871           struct psppire_output_view *view)
872 {
873   if (view->paginated)
874     {
875       /* Sometimes GTK+ emits this signal again even after pagination is
876          complete.  Don't let that screw up printing. */
877       return TRUE;
878     }
879   else if ( view->print_item < view->n_items )
880     {
881       xr_driver_output_item (view->print_xrd,
882                              view->items[view->print_item++].item);
883       while (xr_driver_need_new_page (view->print_xrd))
884         {
885           xr_driver_next_page (view->print_xrd, get_cairo_context_from_print_context (context));
886           view->print_n_pages ++;
887         }
888       return FALSE;
889     }
890   else
891     {
892       gtk_print_operation_set_n_pages (operation, view->print_n_pages);
893
894       /* Re-create the driver to do the real printing. */
895       xr_driver_destroy (view->print_xrd);
896       create_xr_print_driver (context, view);
897       view->print_item = 0;
898       view->paginated = TRUE;
899
900       return TRUE;
901     }
902 }
903
904 static void
905 begin_print (GtkPrintOperation *operation,
906              GtkPrintContext   *context,
907              struct psppire_output_view *view)
908 {
909   create_xr_print_driver (context, view);
910
911   view->print_item = 0;
912   view->print_n_pages = 1;
913   view->paginated = FALSE;
914 }
915
916 static void
917 end_print (GtkPrintOperation *operation,
918            GtkPrintContext   *context,
919            struct psppire_output_view *view)
920 {
921   xr_driver_destroy (view->print_xrd);
922 }
923
924
925 static void
926 draw_page (GtkPrintOperation *operation,
927            GtkPrintContext   *context,
928            gint               page_number,
929            struct psppire_output_view *view)
930 {
931   xr_driver_next_page (view->print_xrd, get_cairo_context_from_print_context (context));
932   while (!xr_driver_need_new_page (view->print_xrd)
933          && view->print_item < view->n_items)
934     xr_driver_output_item (view->print_xrd, view->items [view->print_item++].item);
935 }
936
937
938 void
939 psppire_output_view_print (struct psppire_output_view *view,
940                            GtkWindow *parent_window)
941 {
942   GtkPrintOperationResult res;
943
944   GtkPrintOperation *print = gtk_print_operation_new ();
945
946   if (view->print_settings != NULL)
947     gtk_print_operation_set_print_settings (print, view->print_settings);
948
949   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), view);
950   g_signal_connect (print, "end_print",   G_CALLBACK (end_print),   view);
951   g_signal_connect (print, "paginate",    G_CALLBACK (paginate),    view);
952   g_signal_connect (print, "draw_page",   G_CALLBACK (draw_page),   view);
953
954   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
955                                  parent_window, NULL);
956
957   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
958     {
959       if (view->print_settings != NULL)
960         g_object_unref (view->print_settings);
961       view->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
962     }
963
964   g_object_unref (print);
965 }
966 \f
967 struct psppire_output_view_driver
968   {
969     struct output_driver driver;
970     struct psppire_output_view *view;
971   };
972
973 static struct psppire_output_view_driver *
974 psppire_output_view_driver_cast (struct output_driver *driver)
975 {
976   return UP_CAST (driver, struct psppire_output_view_driver, driver);
977 }
978
979 static void
980 psppire_output_view_submit (struct output_driver *this,
981                             const struct output_item *item)
982 {
983   struct psppire_output_view_driver *povd = psppire_output_view_driver_cast (this);
984
985   if (is_table_item (item))
986     psppire_output_view_put (povd->view, item);
987 }
988
989 static struct output_driver_class psppire_output_view_driver_class =
990   {
991     "PSPPIRE Output View",      /* name */
992     NULL,                       /* destroy */
993     psppire_output_view_submit, /* submit */
994     NULL,                       /* flush */
995   };
996
997 void
998 psppire_output_view_register_driver (struct psppire_output_view *view)
999 {
1000   struct psppire_output_view_driver *povd;
1001   struct output_driver *d;
1002
1003   povd = xzalloc (sizeof *povd);
1004   povd->view = view;
1005   d = &povd->driver;
1006   output_driver_init (d, &psppire_output_view_driver_class, "PSPPIRE Output View",
1007                       SETTINGS_DEVICE_UNFILTERED);
1008   output_driver_register (d);
1009 }