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