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