printing works; font sizes are weird
[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 <cairo/cairo-svg.h>
22 #include <errno.h>
23 #include <stdbool.h>
24
25 #if HAVE_RSVG
26 #include "librsvg/rsvg.h"
27 #endif
28 #include "libpspp/assertion.h"
29 #include "libpspp/string-map.h"
30 #include "output/cairo-fsm.h"
31 #include "output/cairo-pager.h"
32 #include "output/driver-provider.h"
33 #include "output/driver.h"
34 #include "output/chart-item.h"
35 #include "output/group-item.h"
36 #include "output/message-item.h"
37 #include "output/output-item.h"
38 #include "output/output-item-provider.h"
39 #include "output/table-item.h"
40 #include "output/text-item.h"
41
42 #include "gl/c-xvasprintf.h"
43 #include "gl/minmax.h"
44 #include "gl/tmpdir.h"
45 #include "gl/xalloc.h"
46
47 #include <gettext.h>
48 #define _(msgid) gettext (msgid)
49
50 struct output_view_item
51   {
52     struct output_item *item;
53     GtkWidget *drawing_area;
54   };
55
56 struct psppire_output_view
57   {
58     struct xr_fsm_style *style;
59     int object_spacing;
60
61     GtkLayout *output;
62     int render_width;
63     int max_width;
64     glong y;
65
66     GtkTreeView *overview;
67     GtkTreePath *cur_group;
68
69     GtkWidget *toplevel;
70
71     guint buttontime; /* Time of the button event */
72
73     struct output_view_item *items;
74     size_t n_items, allocated_items;
75     struct output_view_item *selected_item;
76
77     /* Variables pertaining to printing */
78     GtkPrintSettings *print_settings;
79
80     struct xr_fsm_style *fsm_style;
81     struct xr_page_style *page_style;
82     struct xr_pager *pager;
83     int print_item;
84     int print_n_pages;
85     gboolean paginated;
86   };
87
88 enum
89   {
90     COL_NAME,                   /* Table name. */
91     COL_ADDR,                   /* Pointer to the table */
92     COL_Y,                      /* Y position of top of name. */
93     N_COLS
94   };
95
96 static GtkTargetList *build_target_list (const struct output_item *item);
97 static void clipboard_get_cb (GtkClipboard     *clipboard,
98                               GtkSelectionData *selection_data,
99                               guint             info,
100                               gpointer          data);
101
102 /* Draws a white background on the GtkLayout to match the white background of
103    each of the output items. */
104 static gboolean
105 layout_draw_callback (GtkWidget *widget, cairo_t *cr, gpointer data)
106 {
107   int width = gtk_widget_get_allocated_width (widget);
108   int height = gtk_widget_get_allocated_height (widget);
109   GtkStyleContext *context = gtk_widget_get_style_context (widget);
110   gtk_render_background (context, cr, 0, 0, width, height);
111   return FALSE;                 /* Continue drawing the GtkDrawingAreas. */
112 }
113
114 static gboolean
115 draw_callback (GtkWidget *widget, cairo_t *cr, gpointer data)
116 {
117   GdkRectangle clip;
118   if (!gdk_cairo_get_clip_rectangle (cr, &clip))
119     return TRUE;
120
121   struct xr_fsm *fsm = g_object_get_data (G_OBJECT (widget), "fsm");
122
123   /* Draw the background based on the state of the widget
124      which can be selected or not selected */
125   GtkStyleContext *context = gtk_widget_get_style_context (widget);
126   gtk_render_background (context, cr, clip.x, clip.y,
127                          clip.x + clip.width, clip.y + clip.height);
128   /* Select the default foreground color based on current style
129      and state of the widget */
130   GtkStateFlags state = gtk_widget_get_state_flags (widget);
131   GdkRGBA color;
132   gtk_style_context_get_color (context, state, &color);
133   cairo_set_source_rgba (cr, color.red, color.green, color.blue, color.alpha);
134   xr_fsm_draw_region (fsm, cr, clip.x, clip.y, clip.width, clip.height);
135
136   return TRUE;
137 }
138
139 static void
140 free_fsm (gpointer fsm_)
141 {
142   struct xr_fsm *fsm = fsm_;
143   xr_fsm_destroy (fsm);
144 }
145
146 static struct xr_fsm_style *
147 get_xr_fsm_style (struct psppire_output_view *view)
148 {
149   GtkStyleContext *context
150     = gtk_widget_get_style_context (GTK_WIDGET (view->output));
151   GtkStateFlags state = gtk_widget_get_state_flags (GTK_WIDGET (view->output));
152
153   int xr_width = view->render_width * 1000;
154
155   PangoFontDescription *pf;
156   gtk_style_context_get (context, state, "font", &pf, NULL);
157   PangoFontDescription *ff = pango_font_description_from_string ("Monospace");
158   pango_font_description_set_size (ff, pango_font_description_get_size (pf));
159
160   struct xr_fsm_style *style = xmalloc (sizeof *style);
161   *style = (struct xr_fsm_style) {
162     .ref_cnt = 1,
163     .size = { [TABLE_HORZ] = xr_width, [TABLE_VERT] = INT_MAX },
164     .min_break = { [TABLE_HORZ] = xr_width / 2, [TABLE_VERT] = 0 },
165     .fonts = {
166       [XR_FONT_PROPORTIONAL] = pf,
167       [XR_FONT_FIXED] = ff,
168     },
169     .use_system_colors = true,
170     .transparent = true,
171     .font_scale = 1.0,
172   };
173
174   return style;
175 }
176
177 /* Return the horizontal position to place a widget whose
178    width is CHILD_WIDTH */
179 static gint
180 get_xpos (const struct psppire_output_view *view, gint child_width)
181 {
182   GdkWindow *gdkw = gtk_widget_get_window (GTK_WIDGET (view->output));
183   guint w = gdk_window_get_width (gdkw);
184   int gutter = 0;
185   g_object_get (view->output, "border-width", &gutter, NULL);
186   return (gtk_widget_get_direction (GTK_WIDGET (view->output)) ==  GTK_TEXT_DIR_RTL) ? w - child_width - gutter: gutter;
187 }
188
189 static struct output_view_item *
190 find_selected_item (struct psppire_output_view *view)
191 {
192   struct output_view_item *item = NULL;
193   if (view == NULL)
194     return NULL;
195   if (view->items == NULL)
196     return NULL;
197
198   for (item = view->items; item < &view->items[view->n_items]; item++)
199     {
200       GtkWidget *widget = GTK_WIDGET (item->drawing_area);
201       if GTK_IS_WIDGET (widget)
202         {
203           GtkStateFlags state = gtk_widget_get_state_flags (widget);
204           if (state & GTK_STATE_FLAG_SELECTED)
205             return item;
206         }
207     }
208   return NULL;
209 }
210
211
212 static void
213 set_copy_action (struct psppire_output_view *view,
214                  gboolean state)
215 {
216   GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (view->output));
217   GAction *copy_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
218                                                      "copy");
219   g_object_set (copy_action,
220                 "enabled", state,
221                 NULL);
222 }
223
224 static void
225 clear_selection (struct psppire_output_view *view)
226 {
227   if (view == NULL)
228     return;
229   struct output_view_item *item = find_selected_item (view);
230   if (item == NULL)
231     return;
232   set_copy_action (view, FALSE);
233   GtkWidget *widget = GTK_WIDGET (item->drawing_area);
234   if (GTK_IS_WIDGET (widget))
235     {
236       gtk_widget_unset_state_flags (widget, GTK_STATE_FLAG_SELECTED);
237       gtk_widget_queue_draw (widget);
238     }
239 }
240
241 static gboolean
242 off_item_button_press_event_cb (GtkWidget      *widget,
243                                 GdkEventButton *event,
244                                 struct psppire_output_view *view)
245 {
246   /* buttontime is set by button_press_event_cb
247      If our event->time is equal to the time from the
248      button_press_event_cb, then we handle the same event.
249      In that case we must not clear the selection because
250      it was just set by button_press_event_cb from the item */
251   if (event->time != view->buttontime)
252     clear_selection (view);
253   return FALSE; /* Forward the event -> DragNDrop */
254 }
255
256 static gboolean
257 button_press_event_cb (GtkWidget      *widget,
258                        GdkEventButton *event,
259                        struct psppire_output_view *view)
260 {
261   view->buttontime = event->time;
262   clear_selection (view);
263   set_copy_action (view, TRUE);
264   gtk_widget_set_state_flags (widget, GTK_STATE_FLAG_SELECTED, FALSE);
265   gtk_widget_queue_draw (widget);
266   return FALSE; /* Forward Event -> off_item will trigger */
267 }
268
269 static void
270 drag_data_get_cb (GtkWidget *widget, GdkDragContext *context,
271                   GtkSelectionData *selection_data,
272                   guint target_type, guint time,
273                   struct psppire_output_view *view)
274 {
275   view->selected_item = find_selected_item (view);
276   clipboard_get_cb (NULL, selection_data, target_type, view);
277 }
278
279 static void
280 create_drawing_area (struct psppire_output_view *view,
281                      GtkWidget *drawing_area, struct xr_fsm *r,
282                      int tw, int th, const struct output_item *item)
283 {
284   g_object_set_data_full (G_OBJECT (drawing_area),
285                           "fsm", r, free_fsm);
286   g_signal_connect (drawing_area, "button-press-event",
287                     G_CALLBACK (button_press_event_cb), view);
288   gtk_widget_add_events (drawing_area, GDK_BUTTON_PRESS_MASK);
289
290   { /* Drag and Drop */
291     GtkTargetList *tl = build_target_list (item);
292     g_assert (tl);
293     gtk_drag_source_set (drawing_area, GDK_BUTTON1_MASK, NULL, 0, GDK_ACTION_COPY);
294     gtk_drag_source_set_target_list (drawing_area, tl);
295     gtk_target_list_unref (tl);
296     g_signal_connect (drawing_area, "drag-data-get",
297                       G_CALLBACK (drag_data_get_cb), view);
298   }
299   GtkStyleContext *context = gtk_widget_get_style_context (drawing_area);
300   gtk_style_context_add_class (context,
301                                GTK_STYLE_CLASS_VIEW);
302   g_signal_connect (drawing_area, "draw",
303                     G_CALLBACK (draw_callback), view);
304
305   gtk_widget_set_size_request (drawing_area, tw, th);
306   gint xpos = get_xpos (view, tw);
307
308   gtk_layout_put (view->output, drawing_area, xpos, view->y);
309
310   gtk_widget_show (drawing_area);
311 }
312
313 static void
314 rerender (struct psppire_output_view *view)
315 {
316   struct output_view_item *item;
317   GdkWindow *gdkw = gtk_widget_get_window (GTK_WIDGET (view->output));
318
319   if (!view->n_items || ! gdkw)
320     return;
321
322   if (!view->style)
323     view->style = get_xr_fsm_style (view);
324
325   GdkWindow *win = gtk_layout_get_bin_window (view->output);
326   cairo_region_t *region = gdk_window_get_visible_region (win);
327   GdkDrawingContext *ctx =  gdk_window_begin_draw_frame (win, region);
328   cairo_t *cr = gdk_drawing_context_get_cairo_context (ctx);
329
330   view->y = 0;
331   view->max_width = 0;
332   for (item = view->items; item < &view->items[view->n_items]; item++)
333     {
334       struct xr_fsm *r;
335       GtkAllocation alloc;
336       int tw, th;
337
338       if (view->y > 0)
339         view->y += view->object_spacing;
340
341       if (is_group_open_item (item->item))
342         continue;
343
344       r = xr_fsm_create (item->item, view->style, cr);
345       if (r == NULL)
346         {
347           g_warn_if_reached ();
348           continue;
349         }
350
351       xr_fsm_measure (r, cr, &tw, &th);
352
353       gint xpos = get_xpos (view, tw);
354
355       if (!item->drawing_area)
356         {
357           item->drawing_area = gtk_drawing_area_new ();
358           create_drawing_area (view, item->drawing_area, r, tw, th, item->item);
359         }
360       else
361         {
362           g_object_set_data_full (G_OBJECT (item->drawing_area),
363                                   "fsm", r, free_fsm);
364           gtk_widget_set_size_request (item->drawing_area, tw, th);
365           gtk_layout_move (view->output, item->drawing_area, xpos, view->y);
366         }
367
368       {
369         gint minw;
370         gint minh;
371         /* This code probably doesn't bring us anthing, but Gtk
372            shows warnings if get_preferred_width/height is not
373            called before the size_allocate below is called. */
374         gtk_widget_get_preferred_width (item->drawing_area, &minw, NULL);
375         gtk_widget_get_preferred_height (item->drawing_area, &minh, NULL);
376         if (th > minh) th = minh;
377         if (tw > minw) tw = minw;
378       }
379       alloc.x = xpos;
380       alloc.y = view->y;
381       alloc.width = tw;
382       alloc.height = th;
383
384       gtk_widget_size_allocate (item->drawing_area, &alloc);
385
386       if (view->max_width < tw)
387         view->max_width = tw;
388       view->y += th;
389     }
390
391   gtk_layout_set_size (view->output,
392                        view->max_width + view->object_spacing,
393                        view->y + view->object_spacing);
394
395   gdk_window_end_draw_frame (win, ctx);
396   cairo_region_destroy (region);
397 }
398
399
400 void
401 psppire_output_view_put (struct psppire_output_view *view,
402                          const struct output_item *item)
403 {
404   struct output_view_item *view_item;
405   GtkWidget *drawing_area;
406   struct string name;
407   int tw, th;
408
409   if (is_group_close_item (item))
410     {
411       if (view->cur_group)
412         {
413           if (!gtk_tree_path_up (view->cur_group))
414             {
415               gtk_tree_path_free (view->cur_group);
416               view->cur_group = NULL;
417             }
418         }
419       return;
420     }
421   else if (is_text_item (item))
422     {
423       const struct text_item *text_item = to_text_item (item);
424       const char *text = text_item_get_text (text_item);
425       if (text[0] == '\0')
426         return;
427     }
428
429   if (view->n_items >= view->allocated_items)
430     view->items = x2nrealloc (view->items, &view->allocated_items,
431                                 sizeof *view->items);
432   view_item = &view->items[view->n_items++];
433   view_item->item = output_item_ref (item);
434   view_item->drawing_area = NULL;
435
436   GdkWindow *win = gtk_widget_get_window (GTK_WIDGET (view->output));
437   if (is_group_open_item (item))
438     tw = th = 0;
439   else if (win)
440     {
441       view_item->drawing_area = drawing_area = gtk_drawing_area_new ();
442
443       if (!view->style)
444         view->style = get_xr_fsm_style (view);
445
446       cairo_region_t *region = gdk_window_get_visible_region (win);
447       GdkDrawingContext *ctx = gdk_window_begin_draw_frame (win, region);
448       cairo_t *cr = gdk_drawing_context_get_cairo_context (ctx);
449
450       if (view->y > 0)
451         view->y += view->object_spacing;
452
453       struct xr_fsm *r = xr_fsm_create (item, view->style, cr);
454       if (r == NULL)
455         {
456           gdk_window_end_draw_frame (win, ctx);
457           cairo_region_destroy (region);
458           return;
459         }
460
461       xr_fsm_measure (r, cr, &tw, &th);
462       create_drawing_area (view, drawing_area, r, tw, th, item);
463       gdk_window_end_draw_frame (win, ctx);
464       cairo_region_destroy (region);
465     }
466   else
467     tw = th = 0;
468
469   if (view->overview)
470     {
471       GtkTreeStore *store = GTK_TREE_STORE (
472         gtk_tree_view_get_model (view->overview));
473
474       ds_init_empty (&name);
475
476       /* Create a new node in the tree and puts a reference to it in 'iter'. */
477       GtkTreeIter iter;
478       GtkTreeIter parent;
479       if (view->cur_group
480           && gtk_tree_path_get_depth (view->cur_group) > 0
481           && gtk_tree_model_get_iter (GTK_TREE_MODEL (store),
482                                       &parent, view->cur_group))
483         gtk_tree_store_append (store, &iter, &parent);
484       else
485         gtk_tree_store_append (store, &iter, NULL);
486
487       if (is_group_open_item (item))
488         {
489           gtk_tree_path_free (view->cur_group);
490           view->cur_group = gtk_tree_model_get_path (GTK_TREE_MODEL (store),
491                                                      &iter);
492         }
493
494       ds_clear (&name);
495       if (is_text_item (item))
496         {
497           const struct text_item *text_item = to_text_item (item);
498           ds_put_cstr (&name, text_item_type_to_string (
499                          text_item_get_type (text_item)));
500         }
501       else if (is_message_item (item))
502         {
503           const struct message_item *msg_item = to_message_item (item);
504           const struct msg *msg = message_item_get_msg (msg_item);
505           ds_put_format (&name, "%s: %s", _("Message"),
506                          msg_severity_to_string (msg->severity));
507         }
508       else if (is_table_item (item))
509         {
510           const struct table_item_text *title
511             = table_item_get_title (to_table_item (item));
512           if (title != NULL)
513             ds_put_format (&name, "Table: %s", title->content);
514           else
515             ds_put_cstr (&name, "Table");
516         }
517       else if (is_chart_item (item))
518         {
519           const char *s = chart_item_get_title (to_chart_item (item));
520           if (s != NULL)
521             ds_put_format (&name, "Chart: %s", s);
522           else
523             ds_put_cstr (&name, "Chart");
524         }
525       else if (is_group_open_item (item))
526         ds_put_cstr (&name, to_group_open_item (item)->command_name);
527       gtk_tree_store_set (store, &iter,
528                           COL_NAME, ds_cstr (&name),
529                           COL_ADDR, item,
530                           COL_Y, (view->y),
531                           -1);
532       ds_destroy (&name);
533
534       GtkTreePath *path = gtk_tree_model_get_path (
535         GTK_TREE_MODEL (store), &iter);
536       gtk_tree_view_expand_row (view->overview, path, TRUE);
537       gtk_tree_path_free (path);
538     }
539
540   if (view->max_width < tw)
541     view->max_width = tw;
542   view->y += th;
543
544   gtk_layout_set_size (view->output, view->max_width, view->y);
545 }
546
547 static void
548 on_row_activate (GtkTreeView *overview,
549                  GtkTreePath *path,
550                  GtkTreeViewColumn *column,
551                  struct psppire_output_view *view)
552 {
553   GtkTreeModel *model;
554   GtkTreeIter iter;
555   GtkAdjustment *vadj;
556   GValue value = {0};
557   double y, min, max;
558
559   model = gtk_tree_view_get_model (overview);
560   if (!gtk_tree_model_get_iter (model, &iter, path))
561     return;
562
563   gtk_tree_model_get_value (model, &iter, COL_Y, &value);
564   y = g_value_get_long (&value);
565   g_value_unset (&value);
566
567   vadj = gtk_scrollable_get_vadjustment (GTK_SCROLLABLE (view->output));
568   min = gtk_adjustment_get_lower (vadj);
569   max = gtk_adjustment_get_upper (vadj) - gtk_adjustment_get_page_size (vadj);
570   if (y < min)
571     y = min;
572   else if (y > max)
573     y = max;
574   gtk_adjustment_set_value (vadj, y);
575 }
576
577 static void
578 on_style_updated (GtkWidget *toplevel, struct psppire_output_view *view)
579 {
580   if (!view->n_items || !gtk_widget_get_window (GTK_WIDGET (view->output)))
581     return;
582
583   /* GTK+ fires this signal for trivial changes like the mouse moving in or out
584      of the window.  Check whether the actual fsm options changed and
585      re-render only if they did. */
586   struct xr_fsm_style *style = get_xr_fsm_style (view);
587   if (!view->style || !xr_fsm_style_equals (style, view->style))
588     {
589       xr_fsm_style_unref (view->style);
590       view->style = xr_fsm_style_ref (style);
591       rerender (view);
592     }
593   xr_fsm_style_unref (style);
594 }
595
596 enum {
597   SELECT_FMT_NULL,
598   SELECT_FMT_TEXT,
599   SELECT_FMT_UTF8,
600   SELECT_FMT_HTML,
601   SELECT_FMT_SVG,
602   SELECT_FMT_IMG,
603   SELECT_FMT_ODT
604 };
605
606 /* GNU Hurd doesn't have PATH_MAX.  Use a fallback.
607    Temporary directory names are usually not that long.  */
608 #ifndef PATH_MAX
609 # define PATH_MAX 1024
610 #endif
611
612 /* Returns a pixbuf from a svg file      */
613 /* You must unref the pixbuf after usage */
614 static GdkPixbuf *
615 derive_pixbuf_from_svg (const char *filename)
616 {
617   GError *err = NULL;
618   GdkPixbuf *pixbuf = NULL;
619 #if HAVE_RSVG
620   RsvgHandle *handle = rsvg_handle_new_from_file (filename, &err);
621   if (err == NULL)
622     {
623       rsvg_handle_set_dpi (handle, 300.0);
624       pixbuf = rsvg_handle_get_pixbuf (handle);
625       g_object_unref (handle);
626     }
627 #else
628   pixbuf = gdk_pixbuf_new_from_file (filename, &err);
629 #endif
630   if (err != NULL)
631     {
632       msg (ME, _("Could not open file %s during copy operation: %s"),
633            filename, err->message);
634       g_error_free (err);
635       return NULL;
636     }
637   return pixbuf;
638 }
639
640 static void
641 clipboard_get_cb (GtkClipboard     *clipboard,
642                   GtkSelectionData *selection_data,
643                   guint             info,
644                   gpointer          data)
645 {
646   struct psppire_output_view *view = data;
647
648   gsize length;
649   gchar *text = NULL;
650   struct output_driver *driver = NULL;
651   char dirname[PATH_MAX], *filename;
652   struct string_map options;
653
654   if (view->selected_item == NULL)
655     return;
656
657   if (path_search (dirname, sizeof dirname, NULL, NULL, true)
658       || mkdtemp (dirname) == NULL)
659     {
660       msg_error (errno, _("failed to create temporary directory during clipboard operation"));
661       return;
662     }
663   filename = xasprintf ("%s/clip.tmp", dirname);
664
665   string_map_init (&options);
666   string_map_insert (&options, "output-file", filename);
667
668   switch (info)
669     {
670     case SELECT_FMT_UTF8:
671       string_map_insert (&options, "box", "unicode");
672       /* fall-through */
673
674     case SELECT_FMT_TEXT:
675       string_map_insert (&options, "format", "txt");
676       break;
677
678     case SELECT_FMT_HTML:
679       string_map_insert (&options, "format", "html");
680       string_map_insert (&options, "borders", "false");
681       string_map_insert (&options, "css", "false");
682       break;
683
684     case SELECT_FMT_SVG:
685     case SELECT_FMT_IMG:
686       /* see below */
687       break;
688
689     case SELECT_FMT_ODT:
690       string_map_insert (&options, "format", "odt");
691       break;
692
693     default:
694       g_warning ("unsupported clip target\n");
695       goto finish;
696       break;
697     }
698
699   if ((info == SELECT_FMT_IMG) ||
700       (info == SELECT_FMT_SVG) )
701     {
702       GtkWidget *widget = view->selected_item->drawing_area;
703       struct xr_fsm *fsm = g_object_get_data (G_OBJECT (widget), "fsm");
704
705       GdkWindow *win = gtk_layout_get_bin_window (view->output);
706       cairo_region_t *region = gdk_window_get_visible_region (win);
707       GdkDrawingContext *ctx =  gdk_window_begin_draw_frame (win, region);
708       cairo_t *cr = gdk_drawing_context_get_cairo_context (ctx);
709
710       int w, h;
711       xr_fsm_measure (fsm, cr, &w, &h);
712
713       gdk_window_end_draw_frame (win, ctx);
714       cairo_region_destroy (region);
715
716       cairo_surface_t *surface = cairo_svg_surface_create (filename, w, h);
717       if (surface)
718         {
719           cairo_t *cr = cairo_create (surface);
720           xr_fsm_draw_all (fsm, cr);
721           cairo_destroy (cr);
722           cairo_surface_destroy (surface);
723         }
724       else
725         g_error ("Could not create cairo svg surface with file %s", filename);
726     }
727   else
728     {
729       driver = output_driver_create (&options);
730       if (driver == NULL)
731         goto finish;
732
733       driver->class->submit (driver, view->selected_item->item);
734
735       if (driver->class->flush)
736         driver->class->flush (driver);
737
738       /* Some drivers (eg: the odt one) don't write anything until they
739          are closed */
740       output_driver_destroy (driver);
741       driver = NULL;
742     }
743
744   if (info == SELECT_FMT_IMG)
745     {
746       GdkPixbuf *pixbuf = derive_pixbuf_from_svg (filename);
747       if (pixbuf)
748         {
749           gtk_selection_data_set_pixbuf (selection_data, pixbuf);
750           g_object_unref (pixbuf);
751         }
752     }
753   else if (g_file_get_contents (filename, &text, &length, NULL))
754     gtk_selection_data_set (selection_data, gtk_selection_data_get_target (selection_data),
755                             8,
756                             (const guchar *) text, length);
757
758  finish:
759
760   if (driver != NULL)
761     output_driver_destroy (driver);
762
763   g_free (text);
764
765   unlink (filename);
766   free (filename);
767   rmdir (dirname);
768 }
769
770 static void
771 clipboard_clear_cb (GtkClipboard *clipboard,
772                     gpointer data)
773 {
774 }
775
776 #define CBTARGETS                                           \
777 CT ( ctn1, "STRING",        0, SELECT_FMT_TEXT )            \
778 CT ( ctn2, "TEXT",          0, SELECT_FMT_TEXT )            \
779 CT ( ctn3, "COMPOUND_TEXT", 0, SELECT_FMT_TEXT )            \
780 CT ( ctn4, "text/plain",    0, SELECT_FMT_TEXT )            \
781 CT ( ctn5, "UTF8_STRING",   0, SELECT_FMT_UTF8 )            \
782 CT ( ctn6, "text/plain;charset=utf-8", 0, SELECT_FMT_UTF8 ) \
783 CT ( ctn7, "text/html",     0, SELECT_FMT_HTML )            \
784 CT ( ctn8, "image/svg+xml", 0, SELECT_FMT_SVG )
785
786 #define CT(ID, TARGET, FLAGS, INFO) static gchar ID[] = TARGET;
787 CBTARGETS
788 #undef CT
789 static gchar ctnlast[] = "application/vnd.oasis.opendocument.text";
790
791 static const GtkTargetEntry targets[] = {
792 #define CT(ID, TARGET, FLAGS, INFO) { ID, FLAGS, INFO },
793   CBTARGETS
794 #undef CT
795   { ctnlast, 0, SELECT_FMT_ODT }
796 };
797
798 static GtkTargetList *
799 build_target_list (const struct output_item *item)
800 {
801   GtkTargetList *tl = gtk_target_list_new (targets, G_N_ELEMENTS (targets));
802   g_return_val_if_fail (tl, NULL);
803   if (is_table_item (item) ||
804       is_chart_item (item))
805     gtk_target_list_add_image_targets (tl, SELECT_FMT_IMG, TRUE);
806   return tl;
807 }
808
809 static void
810 on_copy (struct psppire_output_view *view)
811 {
812   GtkWidget *widget = GTK_WIDGET (view->overview);
813   GtkClipboard *cb = gtk_widget_get_clipboard (widget, GDK_SELECTION_CLIPBOARD);
814
815   struct output_view_item *ov_item = find_selected_item (view);
816   if (ov_item == NULL)
817     return;
818   view->selected_item = ov_item;
819   GtkTargetList *tl = build_target_list (ov_item->item);
820   g_return_if_fail (tl);
821   gint no_of_targets = 0;
822   GtkTargetEntry *ta = gtk_target_table_new_from_list (tl, &no_of_targets);
823   g_return_if_fail (ta);
824   if (!gtk_clipboard_set_with_data (cb, ta, no_of_targets,
825                                     clipboard_get_cb, clipboard_clear_cb,
826                                     view))
827     clipboard_clear_cb (cb, view);
828
829   gtk_target_list_unref (tl);
830   gtk_target_table_free (ta,no_of_targets);
831 }
832
833 static void
834 on_size_allocate (GtkWidget    *widget,
835                   GdkRectangle *allocation,
836                   struct psppire_output_view *view)
837 {
838   view->render_width = MAX (300, allocation->width);
839   rerender (view);
840 }
841
842 static void
843 on_realize (GtkWidget *overview, GObject *view)
844 {
845   GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (overview));
846
847   GAction *copy_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
848                                                      "copy");
849
850   GAction *select_all_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
851                                                            "select-all");
852
853   g_object_set (copy_action, "enabled", FALSE, NULL);
854   g_object_set (select_all_action, "enabled", FALSE, NULL);
855
856   g_signal_connect_swapped (copy_action, "activate",
857                             G_CALLBACK (on_copy), view);
858
859 }
860
861 struct psppire_output_view *
862 psppire_output_view_new (GtkLayout *output, GtkTreeView *overview)
863 {
864   struct psppire_output_view *view;
865   GtkTreeViewColumn *column;
866   GtkCellRenderer *renderer;
867
868   GtkTreeModel *model;
869
870   view = xmalloc (sizeof *view);
871   *view = (struct psppire_output_view) {
872     .object_spacing = 10,
873     .output = output,
874     .overview = overview,
875     .toplevel = gtk_widget_get_toplevel (GTK_WIDGET (output)),
876   };
877
878   g_signal_connect (output, "draw", G_CALLBACK (layout_draw_callback), NULL);
879
880   g_signal_connect (output, "style-updated", G_CALLBACK (on_style_updated), view);
881
882   g_signal_connect (output, "size-allocate", G_CALLBACK (on_size_allocate), view);
883
884   gtk_widget_add_events (GTK_WIDGET (output), GDK_BUTTON_PRESS_MASK);
885   g_signal_connect (output, "button-press-event",
886                     G_CALLBACK (off_item_button_press_event_cb), view);
887
888   gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (output)),
889                                GTK_STYLE_CLASS_VIEW);
890
891   if (overview)
892     {
893       g_signal_connect (overview, "realize", G_CALLBACK (on_realize), view);
894
895       model = GTK_TREE_MODEL (gtk_tree_store_new (
896                                 N_COLS,
897                                 G_TYPE_STRING,  /* COL_NAME */
898                                 G_TYPE_POINTER, /* COL_ADDR */
899                                 G_TYPE_LONG));  /* COL_Y */
900       gtk_tree_view_set_model (overview, model);
901       g_object_unref (model);
902
903       column = gtk_tree_view_column_new ();
904       gtk_tree_view_append_column (GTK_TREE_VIEW (overview), column);
905       renderer = gtk_cell_renderer_text_new ();
906       gtk_tree_view_column_pack_start (column, renderer, TRUE);
907       gtk_tree_view_column_add_attribute (column, renderer, "text", COL_NAME);
908
909       g_signal_connect (GTK_TREE_VIEW (overview),
910                         "row-activated", G_CALLBACK (on_row_activate), view);
911     }
912
913   return view;
914 }
915
916 void
917 psppire_output_view_destroy (struct psppire_output_view *view)
918 {
919   size_t i;
920
921   if (!view)
922     return;
923
924   g_signal_handlers_disconnect_by_func (view->output,
925                                         G_CALLBACK (on_style_updated), view);
926
927   xr_fsm_style_unref (view->style);
928
929   for (i = 0; i < view->n_items; i++)
930     output_item_unref (view->items[i].item);
931   free (view->items);
932   view->items = NULL;
933   view->n_items = view->allocated_items = 0;
934
935   if (view->print_settings != NULL)
936     g_object_unref (view->print_settings);
937
938   if (view->cur_group)
939     gtk_tree_path_free (view->cur_group);
940
941   free (view);
942 }
943
944 void
945 psppire_output_view_clear (struct psppire_output_view *view)
946 {
947   size_t i;
948
949   view->max_width = 0;
950   view->y = 0;
951
952   for (i = 0; i < view->n_items; i++)
953     {
954       gtk_container_remove (GTK_CONTAINER (view->output),
955                             view->items[i].drawing_area);
956       output_item_unref (view->items[i].item);
957     }
958   free (view->items);
959   view->items = NULL;
960   view->n_items = view->allocated_items = 0;
961 }
962
963 /* Export. */
964
965 void
966 psppire_output_view_export (struct psppire_output_view *view,
967                             struct string_map *options)
968 {
969   struct output_driver *driver;
970
971   driver = output_driver_create (options);
972   if (driver)
973     {
974       size_t i;
975
976       for (i = 0; i < view->n_items; i++)
977         driver->class->submit (driver, view->items[i].item);
978       output_driver_destroy (driver);
979     }
980 }
981 \f
982 /* Print. */
983
984 static cairo_t *
985 get_cairo_context_from_print_context (GtkPrintContext *context)
986 {
987   cairo_t *cr = gtk_print_context_get_cairo_context (context);
988   return cairo_reference (cr);
989 }
990
991 static void
992 create_xr_print_driver (GtkPrintContext *context, struct psppire_output_view *view)
993 {
994   GtkPageSetup *ps = gtk_print_context_get_page_setup (context);
995
996   enum { H = TABLE_HORZ, V = TABLE_VERT };
997   int paper[TABLE_N_AXES] = {
998     [H] = gtk_page_setup_get_paper_width (ps, GTK_UNIT_POINTS) * XR_POINT,
999     [V] = gtk_page_setup_get_paper_height (ps, GTK_UNIT_POINTS) * XR_POINT,
1000   };
1001
1002   /* These are all 1/2 inch.  The "margins" that GTK+ gives us are useless:
1003      they are the printer's imagable area. */
1004   int margins[TABLE_N_AXES][2] = {
1005     [H][0] = XR_POINT * 36,
1006     [H][1] = XR_POINT * 36,
1007     [V][0] = XR_POINT * 36,
1008     [V][1] = XR_POINT * 36,
1009   };
1010
1011   double size[TABLE_N_AXES];
1012   for (int a = 0; a < TABLE_N_AXES; a++)
1013     size[a] = paper[a] - margins[a][0] - margins[a][1];
1014
1015   PangoFontDescription *proportional_font
1016     = pango_font_description_from_string ("Sans Serif 10");
1017   PangoFontDescription *fixed_font
1018     = pango_font_description_from_string ("Monospace 10");
1019
1020   view->page_style = xmalloc (sizeof *view->page_style);
1021   *view->page_style = (struct xr_page_style) {
1022     .ref_cnt = 1,
1023
1024     .margins = {
1025       [H] = { margins[H][0], margins[H][1] },
1026       [V] = { margins[V][0], margins[V][1] },
1027     },
1028     .bg = { .alpha = 0 },
1029     .initial_page_number = 1,
1030     .object_spacing = 12 * XR_POINT,
1031   };
1032
1033   view->fsm_style = xmalloc (sizeof *view->fsm_style);
1034   *view->fsm_style = (struct xr_fsm_style) {
1035     .ref_cnt = 1,
1036
1037     .size = { [H] = size[H], [V] = size[V] },
1038     .min_break = { [H] = size[H] / 2, [V] = size[V] / 2 },
1039     .fonts = {
1040       [XR_FONT_PROPORTIONAL] = proportional_font,
1041       [XR_FONT_FIXED] = fixed_font,
1042     },
1043     .fg = CELL_COLOR_BLACK,
1044     .use_system_colors = false,
1045     .transparent = false,
1046     .font_scale = 72.0 / 128.0
1047   };
1048
1049   view->pager = xr_pager_create (view->page_style, view->fsm_style);
1050 }
1051
1052 static gboolean
1053 paginate (GtkPrintOperation *operation,
1054           GtkPrintContext   *context,
1055           struct psppire_output_view *view)
1056 {
1057   if (view->paginated)
1058     {
1059       /* Sometimes GTK+ emits this signal again even after pagination is
1060          complete.  Don't let that screw up printing. */
1061       return TRUE;
1062     }
1063   else if (view->print_item < view->n_items)
1064     {
1065       xr_pager_add_item (view->pager, view->items[view->print_item++].item);
1066       while (xr_pager_needs_new_page (view->pager))
1067         {
1068           xr_pager_add_page (view->pager,
1069                              get_cairo_context_from_print_context (context));
1070           view->print_n_pages ++;
1071         }
1072       return FALSE;
1073     }
1074   else
1075     {
1076       gtk_print_operation_set_n_pages (operation, MAX (1, view->print_n_pages));
1077
1078       /* Re-create the driver to do the real printing. */
1079       xr_pager_destroy (view->pager);
1080       view->pager = xr_pager_create (view->page_style, view->fsm_style);
1081       view->print_item = 0;
1082       view->paginated = TRUE;
1083
1084       return TRUE;
1085     }
1086 }
1087
1088 static void
1089 begin_print (GtkPrintOperation *operation,
1090              GtkPrintContext   *context,
1091              struct psppire_output_view *view)
1092 {
1093   create_xr_print_driver (context, view);
1094
1095   view->print_item = 0;
1096   view->print_n_pages = 0;
1097   view->paginated = FALSE;
1098 }
1099
1100 static void
1101 end_print (GtkPrintOperation *operation,
1102            GtkPrintContext   *context,
1103            struct psppire_output_view *view)
1104 {
1105   xr_pager_destroy (view->pager);
1106   view->pager = NULL;
1107 }
1108
1109
1110 static void
1111 draw_page (GtkPrintOperation *operation,
1112            GtkPrintContext   *context,
1113            gint               page_number,
1114            struct psppire_output_view *view)
1115 {
1116   xr_pager_add_page (view->pager,
1117                      get_cairo_context_from_print_context (context));
1118   while (!xr_pager_needs_new_page (view->pager)
1119          && view->print_item < view->n_items)
1120     xr_pager_add_item (view->pager, view->items [view->print_item++].item);
1121 }
1122
1123
1124 void
1125 psppire_output_view_print (struct psppire_output_view *view,
1126                            GtkWindow *parent_window)
1127 {
1128   GtkPrintOperationResult res;
1129
1130   GtkPrintOperation *print = gtk_print_operation_new ();
1131
1132   if (view->print_settings != NULL)
1133     gtk_print_operation_set_print_settings (print, view->print_settings);
1134
1135   gtk_print_operation_set_use_full_page (print, TRUE);
1136   gtk_print_operation_set_unit (print, GTK_UNIT_POINTS);
1137
1138   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), view);
1139   g_signal_connect (print, "end_print",   G_CALLBACK (end_print),   view);
1140   g_signal_connect (print, "paginate",    G_CALLBACK (paginate),    view);
1141   g_signal_connect (print, "draw_page",   G_CALLBACK (draw_page),   view);
1142
1143   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1144                                  parent_window, NULL);
1145
1146   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1147     {
1148       if (view->print_settings != NULL)
1149         g_object_unref (view->print_settings);
1150       view->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1151     }
1152
1153   g_object_unref (print);
1154 }
1155 \f
1156 struct psppire_output_view_driver
1157   {
1158     struct output_driver driver;
1159     struct psppire_output_view *view;
1160   };
1161
1162 static struct psppire_output_view_driver *
1163 psppire_output_view_driver_cast (struct output_driver *driver)
1164 {
1165   return UP_CAST (driver, struct psppire_output_view_driver, driver);
1166 }
1167
1168 static void
1169 psppire_output_view_submit (struct output_driver *this,
1170                             const struct output_item *item)
1171 {
1172   struct psppire_output_view_driver *povd = psppire_output_view_driver_cast (this);
1173
1174   if (is_table_item (item))
1175     psppire_output_view_put (povd->view, item);
1176 }
1177
1178 static struct output_driver_class psppire_output_view_driver_class =
1179   {
1180     "PSPPIRE Output View",      /* name */
1181     NULL,                       /* destroy */
1182     psppire_output_view_submit, /* submit */
1183     NULL,                       /* flush */
1184   };
1185
1186 void
1187 psppire_output_view_register_driver (struct psppire_output_view *view)
1188 {
1189   struct psppire_output_view_driver *povd;
1190   struct output_driver *d;
1191
1192   povd = xzalloc (sizeof *povd);
1193   povd->view = view;
1194   d = &povd->driver;
1195   output_driver_init (d, &psppire_output_view_driver_class, "PSPPIRE Output View",
1196                       SETTINGS_DEVICE_UNFILTERED);
1197   output_driver_register (d);
1198 }