746f3b942be099ff7c650fdd19105773b14fed6e
[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       char *text = text_item_get_plain_text (text_item);
423       bool text_is_empty = text[0] == '\0';
424       free (text);
425       if (text_is_empty)
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_for_scrolling (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       /* Create a new node in the tree and puts a reference to it in 'iter'. */
475       GtkTreeIter iter;
476       GtkTreeIter parent;
477       if (view->cur_group
478           && gtk_tree_path_get_depth (view->cur_group) > 0
479           && gtk_tree_model_get_iter (GTK_TREE_MODEL (store),
480                                       &parent, view->cur_group))
481         gtk_tree_store_append (store, &iter, &parent);
482       else
483         gtk_tree_store_append (store, &iter, NULL);
484
485       if (is_group_open_item (item))
486         {
487           gtk_tree_path_free (view->cur_group);
488           view->cur_group = gtk_tree_model_get_path (GTK_TREE_MODEL (store),
489                                                      &iter);
490         }
491
492       gtk_tree_store_set (store, &iter,
493                           COL_LABEL, output_item_get_label (item),
494                           COL_ADDR, item,
495                           COL_Y, view->y,
496                           -1);
497
498       GtkTreePath *path = gtk_tree_model_get_path (
499         GTK_TREE_MODEL (store), &iter);
500       gtk_tree_view_expand_row (view->overview, path, TRUE);
501       gtk_tree_path_free (path);
502     }
503
504   if (view->max_width < tw)
505     view->max_width = tw;
506   view->y += th;
507
508   gtk_layout_set_size (view->output, view->max_width, view->y);
509 }
510
511 static void
512 on_row_activate (GtkTreeView *overview,
513                  GtkTreePath *path,
514                  GtkTreeViewColumn *column,
515                  struct psppire_output_view *view)
516 {
517   GtkTreeModel *model;
518   GtkTreeIter iter;
519   GtkAdjustment *vadj;
520   GValue value = {0};
521   double y, min, max;
522
523   model = gtk_tree_view_get_model (overview);
524   if (!gtk_tree_model_get_iter (model, &iter, path))
525     return;
526
527   gtk_tree_model_get_value (model, &iter, COL_Y, &value);
528   y = g_value_get_long (&value);
529   g_value_unset (&value);
530
531   vadj = gtk_scrollable_get_vadjustment (GTK_SCROLLABLE (view->output));
532   min = gtk_adjustment_get_lower (vadj);
533   max = gtk_adjustment_get_upper (vadj) - gtk_adjustment_get_page_size (vadj);
534   if (y < min)
535     y = min;
536   else if (y > max)
537     y = max;
538   gtk_adjustment_set_value (vadj, y);
539 }
540
541 static void
542 on_style_updated (GtkWidget *toplevel, struct psppire_output_view *view)
543 {
544   if (!view->n_items || !gtk_widget_get_window (GTK_WIDGET (view->output)))
545     return;
546
547   /* GTK+ fires this signal for trivial changes like the mouse moving in or out
548      of the window.  Check whether the actual fsm options changed and
549      re-render only if they did. */
550   struct xr_fsm_style *style = get_xr_fsm_style (view);
551   if (!view->style || !xr_fsm_style_equals (style, view->style))
552     {
553       xr_fsm_style_unref (view->style);
554       view->style = xr_fsm_style_ref (style);
555       rerender (view);
556     }
557   xr_fsm_style_unref (style);
558 }
559
560 enum {
561   SELECT_FMT_NULL,
562   SELECT_FMT_TEXT,
563   SELECT_FMT_UTF8,
564   SELECT_FMT_HTML,
565   SELECT_FMT_SVG,
566   SELECT_FMT_IMG,
567   SELECT_FMT_ODT
568 };
569
570 static void
571 clear_rectangle (cairo_surface_t *surface,
572                  double x0, double y0, double x1, double y1)
573 {
574   cairo_t *cr = cairo_create (surface);
575   cairo_set_source_rgb (cr, 1, 1, 1);
576   cairo_new_path (cr);
577   cairo_rectangle (cr, x0, y0, x1 - x0, y1 - y0);
578   cairo_fill (cr);
579   cairo_destroy (cr);
580 }
581
582 static void
583 clipboard_get_cb (GtkClipboard     *clipboard,
584                   GtkSelectionData *selection_data,
585                   guint             info,
586                   gpointer          data)
587 {
588   struct psppire_output_view *view = data;
589
590   gsize length;
591   gchar *text = NULL;
592   struct output_driver *driver = NULL;
593   char *filename;
594   struct string_map options;
595   struct temp_dir *td = NULL;
596
597   if (view->selected_item == NULL)
598     return;
599
600   td = create_temp_dir ("pspp", NULL, false);
601   if (td == NULL)
602     {
603       msg_error (errno, _("failed to create temporary directory during clipboard operation"));
604       return;
605     }
606   filename = xasprintf ("%s/clip.tmp", td->dir_name);
607
608   string_map_init (&options);
609   string_map_insert (&options, "output-file", filename);
610
611   switch (info)
612     {
613     case SELECT_FMT_UTF8:
614       string_map_insert (&options, "box", "unicode");
615       /* fall-through */
616
617     case SELECT_FMT_TEXT:
618       string_map_insert (&options, "format", "txt");
619       string_map_insert (&options, "width", "1000");
620       break;
621
622     case SELECT_FMT_HTML:
623       string_map_insert (&options, "format", "html");
624       string_map_insert (&options, "borders", "false");
625       string_map_insert (&options, "css", "false");
626       break;
627
628     case SELECT_FMT_SVG:
629     case SELECT_FMT_IMG:
630       /* see below */
631       break;
632
633     case SELECT_FMT_ODT:
634       string_map_insert (&options, "format", "odt");
635       break;
636
637     default:
638       g_warning ("unsupported clip target\n");
639       goto finish;
640       break;
641     }
642
643   if ((info == SELECT_FMT_IMG) ||
644       (info == SELECT_FMT_SVG) )
645     {
646       GtkWidget *widget = view->selected_item->drawing_area;
647       struct xr_fsm *fsm = g_object_get_data (G_OBJECT (widget), "fsm");
648
649       GdkWindow *win = gtk_layout_get_bin_window (view->output);
650       cairo_region_t *region = gdk_window_get_visible_region (win);
651       GdkDrawingContext *ctx =  gdk_window_begin_draw_frame (win, region);
652       cairo_t *cr = gdk_drawing_context_get_cairo_context (ctx);
653
654       int w, h;
655       xr_fsm_measure (fsm, cr, &w, &h);
656
657       gdk_window_end_draw_frame (win, ctx);
658       cairo_region_destroy (region);
659
660       cairo_surface_t *surface
661         = (info == SELECT_FMT_SVG
662            ? cairo_svg_surface_create (filename, w, h)
663            : cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h));
664       clear_rectangle (surface, 0, 0, w, h);
665       cairo_t *cr2 = cairo_create (surface);
666       xr_fsm_draw_all (fsm, cr2);
667       cairo_destroy (cr2);
668       if (info == SELECT_FMT_IMG)
669         {
670           GdkPixbuf *pixbuf = gdk_pixbuf_get_from_surface (surface,
671                                                            0, 0, w, h);
672           if (pixbuf)
673             {
674               gtk_selection_data_set_pixbuf (selection_data, pixbuf);
675               g_object_unref (pixbuf);
676             }
677         }
678       cairo_surface_destroy (surface);
679     }
680   else
681     {
682       driver = output_driver_create (&options);
683       if (driver == NULL)
684         goto finish;
685
686       driver->class->submit (driver, view->selected_item->item);
687
688       if (driver->class->flush)
689         driver->class->flush (driver);
690
691       /* Some drivers (eg: the odt one) don't write anything until they
692          are closed */
693       output_driver_destroy (driver);
694       driver = NULL;
695     }
696
697   if (info != SELECT_FMT_IMG
698       && g_file_get_contents (filename, &text, &length, NULL))
699     gtk_selection_data_set (selection_data,
700                             gtk_selection_data_get_target (selection_data),
701                             8, (const guchar *) text, length);
702
703  finish:
704
705   if (driver != NULL)
706     output_driver_destroy (driver);
707
708   g_free (text);
709
710   unlink (filename);
711   free (filename);
712   cleanup_temp_dir (td);
713 }
714
715 static void
716 clipboard_clear_cb (GtkClipboard *clipboard,
717                     gpointer data)
718 {
719 }
720
721 #define CBTARGETS                                           \
722 CT ( ctn1, "STRING",        0, SELECT_FMT_TEXT )            \
723 CT ( ctn2, "TEXT",          0, SELECT_FMT_TEXT )            \
724 CT ( ctn3, "COMPOUND_TEXT", 0, SELECT_FMT_TEXT )            \
725 CT ( ctn4, "text/plain",    0, SELECT_FMT_TEXT )            \
726 CT ( ctn5, "UTF8_STRING",   0, SELECT_FMT_UTF8 )            \
727 CT ( ctn6, "text/plain;charset=utf-8", 0, SELECT_FMT_UTF8 ) \
728 CT ( ctn7, "text/html",     0, SELECT_FMT_HTML )            \
729 CT ( ctn8, "image/svg+xml", 0, SELECT_FMT_SVG )
730
731 #define CT(ID, TARGET, FLAGS, INFO) static gchar ID[] = TARGET;
732 CBTARGETS
733 #undef CT
734 static gchar ctnlast[] = "application/vnd.oasis.opendocument.text";
735
736 static const GtkTargetEntry targets[] = {
737 #define CT(ID, TARGET, FLAGS, INFO) { ID, FLAGS, INFO },
738   CBTARGETS
739 #undef CT
740   { ctnlast, 0, SELECT_FMT_ODT }
741 };
742
743 static GtkTargetList *
744 build_target_list (const struct output_item *item)
745 {
746   GtkTargetList *tl = gtk_target_list_new (targets, G_N_ELEMENTS (targets));
747   g_return_val_if_fail (tl, NULL);
748   if (is_table_item (item) ||
749       is_chart_item (item))
750     gtk_target_list_add_image_targets (tl, SELECT_FMT_IMG, TRUE);
751   return tl;
752 }
753
754 static void
755 on_copy (struct psppire_output_view *view)
756 {
757   GtkWidget *widget = GTK_WIDGET (view->overview);
758   GtkClipboard *cb = gtk_widget_get_clipboard (widget, GDK_SELECTION_CLIPBOARD);
759
760   struct output_view_item *ov_item = find_selected_item (view);
761   if (ov_item == NULL)
762     return;
763   view->selected_item = ov_item;
764   GtkTargetList *tl = build_target_list (ov_item->item);
765   g_return_if_fail (tl);
766   gint no_of_targets = 0;
767   GtkTargetEntry *ta = gtk_target_table_new_from_list (tl, &no_of_targets);
768   g_return_if_fail (ta);
769   if (!gtk_clipboard_set_with_data (cb, ta, no_of_targets,
770                                     clipboard_get_cb, clipboard_clear_cb,
771                                     view))
772     clipboard_clear_cb (cb, view);
773
774   gtk_target_list_unref (tl);
775   gtk_target_table_free (ta,no_of_targets);
776 }
777
778 static void
779 on_size_allocate (GtkWidget    *widget,
780                   GdkRectangle *allocation,
781                   struct psppire_output_view *view)
782 {
783   view->render_width = MAX (300, allocation->width);
784   rerender (view);
785 }
786
787 static void
788 on_realize (GtkWidget *overview, GObject *view)
789 {
790   GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (overview));
791
792   GAction *copy_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
793                                                      "copy");
794
795   GAction *select_all_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
796                                                            "select-all");
797
798   g_object_set (copy_action, "enabled", FALSE, NULL);
799   g_object_set (select_all_action, "enabled", FALSE, NULL);
800
801   g_signal_connect_swapped (copy_action, "activate",
802                             G_CALLBACK (on_copy), view);
803
804 }
805
806 struct psppire_output_view *
807 psppire_output_view_new (GtkLayout *output, GtkTreeView *overview)
808 {
809   struct psppire_output_view *view;
810   GtkTreeViewColumn *column;
811   GtkCellRenderer *renderer;
812
813   GtkTreeModel *model;
814
815   view = xmalloc (sizeof *view);
816   *view = (struct psppire_output_view) {
817     .object_spacing = 10,
818     .output = output,
819     .overview = overview,
820     .toplevel = gtk_widget_get_toplevel (GTK_WIDGET (output)),
821   };
822
823   g_signal_connect (output, "draw", G_CALLBACK (layout_draw_callback), NULL);
824
825   g_signal_connect (output, "style-updated", G_CALLBACK (on_style_updated), view);
826
827   g_signal_connect (output, "size-allocate", G_CALLBACK (on_size_allocate), view);
828
829   gtk_widget_add_events (GTK_WIDGET (output), GDK_BUTTON_PRESS_MASK);
830   g_signal_connect (output, "button-press-event",
831                     G_CALLBACK (off_item_button_press_event_cb), view);
832
833   gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (output)),
834                                GTK_STYLE_CLASS_VIEW);
835
836   if (overview)
837     {
838       g_signal_connect (overview, "realize", G_CALLBACK (on_realize), view);
839
840       model = GTK_TREE_MODEL (gtk_tree_store_new (
841                                 N_COLS,
842                                 G_TYPE_STRING,  /* COL_LABEL */
843                                 G_TYPE_POINTER, /* COL_ADDR */
844                                 G_TYPE_LONG));  /* COL_Y */
845       gtk_tree_view_set_model (overview, model);
846       g_object_unref (model);
847
848       column = gtk_tree_view_column_new ();
849       gtk_tree_view_append_column (GTK_TREE_VIEW (overview), column);
850       renderer = gtk_cell_renderer_text_new ();
851       gtk_tree_view_column_pack_start (column, renderer, TRUE);
852       gtk_tree_view_column_add_attribute (column, renderer, "text", COL_LABEL);
853
854       g_signal_connect (GTK_TREE_VIEW (overview),
855                         "row-activated", G_CALLBACK (on_row_activate), view);
856     }
857
858   return view;
859 }
860
861 void
862 psppire_output_view_destroy (struct psppire_output_view *view)
863 {
864   size_t i;
865
866   if (!view)
867     return;
868
869   g_signal_handlers_disconnect_by_func (view->output,
870                                         G_CALLBACK (on_style_updated), view);
871
872   xr_fsm_style_unref (view->style);
873
874   for (i = 0; i < view->n_items; i++)
875     output_item_unref (view->items[i].item);
876   free (view->items);
877   view->items = NULL;
878   view->n_items = view->allocated_items = 0;
879
880   if (view->print_settings != NULL)
881     g_object_unref (view->print_settings);
882
883   if (view->cur_group)
884     gtk_tree_path_free (view->cur_group);
885
886   free (view);
887 }
888
889 void
890 psppire_output_view_clear (struct psppire_output_view *view)
891 {
892   size_t i;
893
894   view->max_width = 0;
895   view->y = 0;
896
897   for (i = 0; i < view->n_items; i++)
898     {
899       gtk_container_remove (GTK_CONTAINER (view->output),
900                             view->items[i].drawing_area);
901       output_item_unref (view->items[i].item);
902     }
903   free (view->items);
904   view->items = NULL;
905   view->n_items = view->allocated_items = 0;
906 }
907
908 /* Export. */
909
910 void
911 psppire_output_view_export (struct psppire_output_view *view,
912                             struct string_map *options)
913 {
914   struct output_driver *driver;
915
916   driver = output_driver_create (options);
917   if (driver)
918     {
919       size_t i;
920
921       for (i = 0; i < view->n_items; i++)
922         driver->class->submit (driver, view->items[i].item);
923       output_driver_destroy (driver);
924     }
925 }
926 \f
927 /* Print. */
928
929 static cairo_t *
930 get_cairo_context_from_print_context (GtkPrintContext *context)
931 {
932   cairo_t *cr = gtk_print_context_get_cairo_context (context);
933   return cairo_reference (cr);
934 }
935
936 static void
937 create_xr_print_driver (GtkPrintContext *context, struct psppire_output_view *view)
938 {
939   GtkPageSetup *ps = gtk_print_context_get_page_setup (context);
940
941   enum { H = TABLE_HORZ, V = TABLE_VERT };
942   int paper[TABLE_N_AXES] = {
943     [H] = gtk_page_setup_get_paper_width (ps, GTK_UNIT_POINTS) * XR_POINT,
944     [V] = gtk_page_setup_get_paper_height (ps, GTK_UNIT_POINTS) * XR_POINT,
945   };
946
947   /* These are all 1/2 inch.  The "margins" that GTK+ gives us are useless:
948      they are the printer's imagable area. */
949   int margins[TABLE_N_AXES][2] = {
950     [H][0] = XR_POINT * 36,
951     [H][1] = XR_POINT * 36,
952     [V][0] = XR_POINT * 36,
953     [V][1] = XR_POINT * 36,
954   };
955
956   double size[TABLE_N_AXES];
957   for (int a = 0; a < TABLE_N_AXES; a++)
958     size[a] = paper[a] - margins[a][0] - margins[a][1];
959
960   view->page_style = xmalloc (sizeof *view->page_style);
961   *view->page_style = (struct xr_page_style) {
962     .ref_cnt = 1,
963
964     .margins = {
965       [H] = { margins[H][0], margins[H][1] },
966       [V] = { margins[V][0], margins[V][1] },
967     },
968     .initial_page_number = 1,
969   };
970
971   view->fsm_style = xmalloc (sizeof *view->fsm_style);
972   *view->fsm_style = (struct xr_fsm_style) {
973     .ref_cnt = 1,
974
975     .size = { [H] = size[H], [V] = size[V] },
976     .min_break = { [H] = size[H] / 2, [V] = size[V] / 2 },
977     .font = pango_font_description_from_string ("Sans Serif 10"),
978     .fg = CELL_COLOR_BLACK,
979     .use_system_colors = false,
980     .object_spacing = 12 * XR_POINT,
981     .font_resolution = 72.0
982   };
983
984   view->pager = xr_pager_create (view->page_style, view->fsm_style);
985 }
986
987 static gboolean
988 paginate (GtkPrintOperation *operation,
989           GtkPrintContext   *context,
990           struct psppire_output_view *view)
991 {
992   if (view->paginated)
993     {
994       /* Sometimes GTK+ emits this signal again even after pagination is
995          complete.  Don't let that screw up printing. */
996       return TRUE;
997     }
998   else if (view->print_item < view->n_items)
999     {
1000       xr_pager_add_item (view->pager, view->items[view->print_item++].item);
1001       while (xr_pager_needs_new_page (view->pager))
1002         {
1003           xr_pager_add_page (view->pager,
1004                              get_cairo_context_from_print_context (context));
1005           view->print_n_pages ++;
1006         }
1007       return FALSE;
1008     }
1009   else
1010     {
1011       gtk_print_operation_set_n_pages (operation, MAX (1, view->print_n_pages));
1012
1013       /* Re-create the driver to do the real printing. */
1014       xr_pager_destroy (view->pager);
1015       view->pager = xr_pager_create (view->page_style, view->fsm_style);
1016       view->print_item = 0;
1017       view->paginated = TRUE;
1018
1019       return TRUE;
1020     }
1021 }
1022
1023 static void
1024 begin_print (GtkPrintOperation *operation,
1025              GtkPrintContext   *context,
1026              struct psppire_output_view *view)
1027 {
1028   create_xr_print_driver (context, view);
1029
1030   view->print_item = 0;
1031   view->print_n_pages = 0;
1032   view->paginated = FALSE;
1033 }
1034
1035 static void
1036 end_print (GtkPrintOperation *operation,
1037            GtkPrintContext   *context,
1038            struct psppire_output_view *view)
1039 {
1040   xr_pager_destroy (view->pager);
1041   view->pager = NULL;
1042 }
1043
1044
1045 static void
1046 draw_page (GtkPrintOperation *operation,
1047            GtkPrintContext   *context,
1048            gint               page_number,
1049            struct psppire_output_view *view)
1050 {
1051   xr_pager_add_page (view->pager,
1052                      get_cairo_context_from_print_context (context));
1053   while (!xr_pager_needs_new_page (view->pager)
1054          && view->print_item < view->n_items)
1055     xr_pager_add_item (view->pager, view->items [view->print_item++].item);
1056 }
1057
1058
1059 void
1060 psppire_output_view_print (struct psppire_output_view *view,
1061                            GtkWindow *parent_window)
1062 {
1063   GtkPrintOperationResult res;
1064
1065   GtkPrintOperation *print = gtk_print_operation_new ();
1066
1067   if (view->print_settings != NULL)
1068     gtk_print_operation_set_print_settings (print, view->print_settings);
1069
1070   gtk_print_operation_set_use_full_page (print, TRUE);
1071   gtk_print_operation_set_unit (print, GTK_UNIT_POINTS);
1072
1073   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), view);
1074   g_signal_connect (print, "end_print",   G_CALLBACK (end_print),   view);
1075   g_signal_connect (print, "paginate",    G_CALLBACK (paginate),    view);
1076   g_signal_connect (print, "draw_page",   G_CALLBACK (draw_page),   view);
1077
1078   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1079                                  parent_window, NULL);
1080
1081   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1082     {
1083       if (view->print_settings != NULL)
1084         g_object_unref (view->print_settings);
1085       view->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1086     }
1087
1088   g_object_unref (print);
1089 }
1090 \f
1091 struct psppire_output_view_driver
1092   {
1093     struct output_driver driver;
1094     struct psppire_output_view *view;
1095   };
1096
1097 static struct psppire_output_view_driver *
1098 psppire_output_view_driver_cast (struct output_driver *driver)
1099 {
1100   return UP_CAST (driver, struct psppire_output_view_driver, driver);
1101 }
1102
1103 static void
1104 psppire_output_view_submit (struct output_driver *this,
1105                             const struct output_item *item)
1106 {
1107   struct psppire_output_view_driver *povd = psppire_output_view_driver_cast (this);
1108
1109   if (is_table_item (item))
1110     psppire_output_view_put (povd->view, item);
1111 }
1112
1113 static struct output_driver_class psppire_output_view_driver_class =
1114   {
1115     "PSPPIRE Output View",      /* name */
1116     NULL,                       /* destroy */
1117     psppire_output_view_submit, /* submit */
1118     NULL,                       /* flush */
1119   };
1120
1121 void
1122 psppire_output_view_register_driver (struct psppire_output_view *view)
1123 {
1124   struct psppire_output_view_driver *povd;
1125   struct output_driver *d;
1126
1127   povd = xzalloc (sizeof *povd);
1128   povd->view = view;
1129   d = &povd->driver;
1130   output_driver_init (d, &psppire_output_view_driver_class, "PSPPIRE Output View",
1131                       SETTINGS_DEVICE_UNFILTERED);
1132   output_driver_register (d);
1133 }