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