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