ccf23e8c4ca9b222bc2d9f866a1a45850d546091
[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/tmpdir.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_scale = 1.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 /* GNU Hurd doesn't have PATH_MAX.  Use a fallback.
604    Temporary directory names are usually not that long.  */
605 #ifndef PATH_MAX
606 # define PATH_MAX 1024
607 #endif
608
609 /* Returns a pixbuf from a svg file      */
610 /* You must unref the pixbuf after usage */
611 static GdkPixbuf *
612 derive_pixbuf_from_svg (const char *filename)
613 {
614   GError *err = NULL;
615   GdkPixbuf *pixbuf = NULL;
616 #if HAVE_RSVG
617   RsvgHandle *handle = rsvg_handle_new_from_file (filename, &err);
618   if (err == NULL)
619     {
620       rsvg_handle_set_dpi (handle, 300.0);
621       pixbuf = rsvg_handle_get_pixbuf (handle);
622       g_object_unref (handle);
623     }
624 #else
625   pixbuf = gdk_pixbuf_new_from_file (filename, &err);
626 #endif
627   if (err != NULL)
628     {
629       msg (ME, _("Could not open file %s during copy operation: %s"),
630            filename, err->message);
631       g_error_free (err);
632       return NULL;
633     }
634   return pixbuf;
635 }
636
637 static void
638 clipboard_get_cb (GtkClipboard     *clipboard,
639                   GtkSelectionData *selection_data,
640                   guint             info,
641                   gpointer          data)
642 {
643   struct psppire_output_view *view = data;
644
645   gsize length;
646   gchar *text = NULL;
647   struct output_driver *driver = NULL;
648   char dirname[PATH_MAX], *filename;
649   struct string_map options;
650
651   if (view->selected_item == NULL)
652     return;
653
654   if (path_search (dirname, sizeof dirname, NULL, NULL, true)
655       || mkdtemp (dirname) == NULL)
656     {
657       msg_error (errno, _("failed to create temporary directory during clipboard operation"));
658       return;
659     }
660   filename = xasprintf ("%s/clip.tmp", dirname);
661
662   string_map_init (&options);
663   string_map_insert (&options, "output-file", filename);
664
665   switch (info)
666     {
667     case SELECT_FMT_UTF8:
668       string_map_insert (&options, "box", "unicode");
669       /* fall-through */
670
671     case SELECT_FMT_TEXT:
672       string_map_insert (&options, "format", "txt");
673       break;
674
675     case SELECT_FMT_HTML:
676       string_map_insert (&options, "format", "html");
677       string_map_insert (&options, "borders", "false");
678       string_map_insert (&options, "css", "false");
679       break;
680
681     case SELECT_FMT_SVG:
682     case SELECT_FMT_IMG:
683       /* see below */
684       break;
685
686     case SELECT_FMT_ODT:
687       string_map_insert (&options, "format", "odt");
688       break;
689
690     default:
691       g_warning ("unsupported clip target\n");
692       goto finish;
693       break;
694     }
695
696   if ((info == SELECT_FMT_IMG) ||
697       (info == SELECT_FMT_SVG) )
698     {
699       GtkWidget *widget = view->selected_item->drawing_area;
700       struct xr_fsm *fsm = g_object_get_data (G_OBJECT (widget), "fsm");
701
702       GdkWindow *win = gtk_layout_get_bin_window (view->output);
703       cairo_region_t *region = gdk_window_get_visible_region (win);
704       GdkDrawingContext *ctx =  gdk_window_begin_draw_frame (win, region);
705       cairo_t *cr = gdk_drawing_context_get_cairo_context (ctx);
706
707       int w, h;
708       xr_fsm_measure (fsm, cr, &w, &h);
709
710       gdk_window_end_draw_frame (win, ctx);
711       cairo_region_destroy (region);
712
713       cairo_surface_t *surface = cairo_svg_surface_create (filename, w, h);
714       if (surface)
715         {
716           cairo_t *cr = cairo_create (surface);
717           xr_fsm_draw_all (fsm, cr);
718           cairo_destroy (cr);
719           cairo_surface_destroy (surface);
720         }
721       else
722         g_error ("Could not create cairo svg surface with file %s", filename);
723     }
724   else
725     {
726       driver = output_driver_create (&options);
727       if (driver == NULL)
728         goto finish;
729
730       driver->class->submit (driver, view->selected_item->item);
731
732       if (driver->class->flush)
733         driver->class->flush (driver);
734
735       /* Some drivers (eg: the odt one) don't write anything until they
736          are closed */
737       output_driver_destroy (driver);
738       driver = NULL;
739     }
740
741   if (info == SELECT_FMT_IMG)
742     {
743       GdkPixbuf *pixbuf = derive_pixbuf_from_svg (filename);
744       if (pixbuf)
745         {
746           gtk_selection_data_set_pixbuf (selection_data, pixbuf);
747           g_object_unref (pixbuf);
748         }
749     }
750   else if (g_file_get_contents (filename, &text, &length, NULL))
751     gtk_selection_data_set (selection_data, gtk_selection_data_get_target (selection_data),
752                             8,
753                             (const guchar *) text, length);
754
755  finish:
756
757   if (driver != NULL)
758     output_driver_destroy (driver);
759
760   g_free (text);
761
762   unlink (filename);
763   free (filename);
764   rmdir (dirname);
765 }
766
767 static void
768 clipboard_clear_cb (GtkClipboard *clipboard,
769                     gpointer data)
770 {
771 }
772
773 #define CBTARGETS                                           \
774 CT ( ctn1, "STRING",        0, SELECT_FMT_TEXT )            \
775 CT ( ctn2, "TEXT",          0, SELECT_FMT_TEXT )            \
776 CT ( ctn3, "COMPOUND_TEXT", 0, SELECT_FMT_TEXT )            \
777 CT ( ctn4, "text/plain",    0, SELECT_FMT_TEXT )            \
778 CT ( ctn5, "UTF8_STRING",   0, SELECT_FMT_UTF8 )            \
779 CT ( ctn6, "text/plain;charset=utf-8", 0, SELECT_FMT_UTF8 ) \
780 CT ( ctn7, "text/html",     0, SELECT_FMT_HTML )            \
781 CT ( ctn8, "image/svg+xml", 0, SELECT_FMT_SVG )
782
783 #define CT(ID, TARGET, FLAGS, INFO) static gchar ID[] = TARGET;
784 CBTARGETS
785 #undef CT
786 static gchar ctnlast[] = "application/vnd.oasis.opendocument.text";
787
788 static const GtkTargetEntry targets[] = {
789 #define CT(ID, TARGET, FLAGS, INFO) { ID, FLAGS, INFO },
790   CBTARGETS
791 #undef CT
792   { ctnlast, 0, SELECT_FMT_ODT }
793 };
794
795 static GtkTargetList *
796 build_target_list (const struct output_item *item)
797 {
798   GtkTargetList *tl = gtk_target_list_new (targets, G_N_ELEMENTS (targets));
799   g_return_val_if_fail (tl, NULL);
800   if (is_table_item (item) ||
801       is_chart_item (item))
802     gtk_target_list_add_image_targets (tl, SELECT_FMT_IMG, TRUE);
803   return tl;
804 }
805
806 static void
807 on_copy (struct psppire_output_view *view)
808 {
809   GtkWidget *widget = GTK_WIDGET (view->overview);
810   GtkClipboard *cb = gtk_widget_get_clipboard (widget, GDK_SELECTION_CLIPBOARD);
811
812   struct output_view_item *ov_item = find_selected_item (view);
813   if (ov_item == NULL)
814     return;
815   view->selected_item = ov_item;
816   GtkTargetList *tl = build_target_list (ov_item->item);
817   g_return_if_fail (tl);
818   gint no_of_targets = 0;
819   GtkTargetEntry *ta = gtk_target_table_new_from_list (tl, &no_of_targets);
820   g_return_if_fail (ta);
821   if (!gtk_clipboard_set_with_data (cb, ta, no_of_targets,
822                                     clipboard_get_cb, clipboard_clear_cb,
823                                     view))
824     clipboard_clear_cb (cb, view);
825
826   gtk_target_list_unref (tl);
827   gtk_target_table_free (ta,no_of_targets);
828 }
829
830 static void
831 on_size_allocate (GtkWidget    *widget,
832                   GdkRectangle *allocation,
833                   struct psppire_output_view *view)
834 {
835   view->render_width = MAX (300, allocation->width);
836   rerender (view);
837 }
838
839 static void
840 on_realize (GtkWidget *overview, GObject *view)
841 {
842   GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (overview));
843
844   GAction *copy_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
845                                                      "copy");
846
847   GAction *select_all_action = g_action_map_lookup_action (G_ACTION_MAP (toplevel),
848                                                            "select-all");
849
850   g_object_set (copy_action, "enabled", FALSE, NULL);
851   g_object_set (select_all_action, "enabled", FALSE, NULL);
852
853   g_signal_connect_swapped (copy_action, "activate",
854                             G_CALLBACK (on_copy), view);
855
856 }
857
858 struct psppire_output_view *
859 psppire_output_view_new (GtkLayout *output, GtkTreeView *overview)
860 {
861   struct psppire_output_view *view;
862   GtkTreeViewColumn *column;
863   GtkCellRenderer *renderer;
864
865   GtkTreeModel *model;
866
867   view = xmalloc (sizeof *view);
868   view->style = NULL;
869   view->object_spacing = 10;
870   view->output = output;
871   view->render_width = 0;
872   view->max_width = 0;
873   view->y = 0;
874   view->overview = overview;
875   view->cur_group = NULL;
876   view->toplevel = gtk_widget_get_toplevel (GTK_WIDGET (output));
877   view->buttontime = 0;
878   view->items = NULL;
879   view->n_items = view->allocated_items = 0;
880   view->selected_item = NULL;
881   view->print_settings = NULL;
882   view->print_xrd = NULL;
883   view->print_item = 0;
884   view->print_n_pages = 0;
885   view->paginated = FALSE;
886
887   g_signal_connect (output, "draw", G_CALLBACK (layout_draw_callback), NULL);
888
889   g_signal_connect (output, "style-updated", G_CALLBACK (on_style_updated), view);
890
891   g_signal_connect (output, "size-allocate", G_CALLBACK (on_size_allocate), view);
892
893   gtk_widget_add_events (GTK_WIDGET (output), GDK_BUTTON_PRESS_MASK);
894   g_signal_connect (output, "button-press-event",
895                     G_CALLBACK (off_item_button_press_event_cb), view);
896
897   gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (output)),
898                                GTK_STYLE_CLASS_VIEW);
899
900   if (overview)
901     {
902       g_signal_connect (overview, "realize", G_CALLBACK (on_realize), view);
903
904       model = GTK_TREE_MODEL (gtk_tree_store_new (
905                                 N_COLS,
906                                 G_TYPE_STRING,  /* COL_NAME */
907                                 G_TYPE_POINTER, /* COL_ADDR */
908                                 G_TYPE_LONG));  /* COL_Y */
909       gtk_tree_view_set_model (overview, model);
910       g_object_unref (model);
911
912       column = gtk_tree_view_column_new ();
913       gtk_tree_view_append_column (GTK_TREE_VIEW (overview), column);
914       renderer = gtk_cell_renderer_text_new ();
915       gtk_tree_view_column_pack_start (column, renderer, TRUE);
916       gtk_tree_view_column_add_attribute (column, renderer, "text", COL_NAME);
917
918       g_signal_connect (GTK_TREE_VIEW (overview),
919                         "row-activated", G_CALLBACK (on_row_activate), view);
920     }
921
922   return view;
923 }
924
925 void
926 psppire_output_view_destroy (struct psppire_output_view *view)
927 {
928   size_t i;
929
930   if (!view)
931     return;
932
933   g_signal_handlers_disconnect_by_func (view->output,
934                                         G_CALLBACK (on_style_updated), view);
935
936   xr_fsm_style_unref (view->style);
937
938   for (i = 0; i < view->n_items; i++)
939     output_item_unref (view->items[i].item);
940   free (view->items);
941   view->items = NULL;
942   view->n_items = view->allocated_items = 0;
943
944   if (view->print_settings != NULL)
945     g_object_unref (view->print_settings);
946
947   if (view->cur_group)
948     gtk_tree_path_free (view->cur_group);
949
950   free (view);
951 }
952
953 void
954 psppire_output_view_clear (struct psppire_output_view *view)
955 {
956   size_t i;
957
958   view->max_width = 0;
959   view->y = 0;
960
961   for (i = 0; i < view->n_items; i++)
962     {
963       gtk_container_remove (GTK_CONTAINER (view->output),
964                             view->items[i].drawing_area);
965       output_item_unref (view->items[i].item);
966     }
967   free (view->items);
968   view->items = NULL;
969   view->n_items = view->allocated_items = 0;
970 }
971
972 /* Export. */
973
974 void
975 psppire_output_view_export (struct psppire_output_view *view,
976                             struct string_map *options)
977 {
978   struct output_driver *driver;
979
980   driver = output_driver_create (options);
981   if (driver)
982     {
983       size_t i;
984
985       for (i = 0; i < view->n_items; i++)
986         driver->class->submit (driver, view->items[i].item);
987       output_driver_destroy (driver);
988     }
989 }
990 \f
991 /* Print. */
992
993 static cairo_t *
994 get_cairo_context_from_print_context (GtkPrintContext *context)
995 {
996   cairo_t *cr = gtk_print_context_get_cairo_context (context);
997
998   /*
999     For all platforms except windows, gtk_print_context_get_dpi_[xy] returns 72.
1000     Windows returns 600.
1001   */
1002   double xres = gtk_print_context_get_dpi_x (context);
1003   double yres = gtk_print_context_get_dpi_y (context);
1004
1005   /* This means that the cairo context now has its dimensions in Points */
1006   cairo_scale (cr, xres / 72.0, yres / 72.0);
1007
1008   return cr;
1009 }
1010
1011
1012 static void
1013 create_xr_print_driver (GtkPrintContext *context, struct psppire_output_view *view)
1014 {
1015   struct string_map options;
1016   GtkPageSetup *page_setup;
1017   double width, height;
1018   double left_margin;
1019   double right_margin;
1020   double top_margin;
1021   double bottom_margin;
1022
1023   page_setup = gtk_print_context_get_page_setup (context);
1024   width = gtk_page_setup_get_paper_width (page_setup, GTK_UNIT_MM);
1025   height = gtk_page_setup_get_paper_height (page_setup, GTK_UNIT_MM);
1026   left_margin = gtk_page_setup_get_left_margin (page_setup, GTK_UNIT_MM);
1027   right_margin = gtk_page_setup_get_right_margin (page_setup, GTK_UNIT_MM);
1028   top_margin = gtk_page_setup_get_top_margin (page_setup, GTK_UNIT_MM);
1029   bottom_margin = gtk_page_setup_get_bottom_margin (page_setup, GTK_UNIT_MM);
1030
1031   string_map_init (&options);
1032   string_map_insert_nocopy (&options, xstrdup ("paper-size"),
1033                             c_xasprintf("%.2fx%.2fmm", width, height));
1034   string_map_insert_nocopy (&options, xstrdup ("left-margin"),
1035                             c_xasprintf ("%.2fmm", left_margin));
1036   string_map_insert_nocopy (&options, xstrdup ("right-margin"),
1037                             c_xasprintf ("%.2fmm", right_margin));
1038   string_map_insert_nocopy (&options, xstrdup ("top-margin"),
1039                             c_xasprintf ("%.2fmm", top_margin));
1040   string_map_insert_nocopy (&options, xstrdup ("bottom-margin"),
1041                             c_xasprintf ("%.2fmm", bottom_margin));
1042
1043   view->print_xrd = xr_driver_create (get_cairo_context_from_print_context (context), &options);
1044
1045   string_map_destroy (&options);
1046 }
1047
1048 static gboolean
1049 paginate (GtkPrintOperation *operation,
1050           GtkPrintContext   *context,
1051           struct psppire_output_view *view)
1052 {
1053   if (view->paginated)
1054     {
1055       /* Sometimes GTK+ emits this signal again even after pagination is
1056          complete.  Don't let that screw up printing. */
1057       return TRUE;
1058     }
1059   else if (view->print_item < view->n_items)
1060     {
1061       xr_driver_output_item (view->print_xrd,
1062                              view->items[view->print_item++].item);
1063       while (xr_driver_need_new_page (view->print_xrd))
1064         {
1065           xr_driver_next_page (view->print_xrd, get_cairo_context_from_print_context (context));
1066           view->print_n_pages ++;
1067         }
1068       return FALSE;
1069     }
1070   else
1071     {
1072       gtk_print_operation_set_n_pages (operation, view->print_n_pages);
1073
1074       /* Re-create the driver to do the real printing. */
1075       xr_driver_destroy (view->print_xrd);
1076       create_xr_print_driver (context, view);
1077       view->print_item = 0;
1078       view->paginated = TRUE;
1079
1080       return TRUE;
1081     }
1082 }
1083
1084 static void
1085 begin_print (GtkPrintOperation *operation,
1086              GtkPrintContext   *context,
1087              struct psppire_output_view *view)
1088 {
1089   create_xr_print_driver (context, view);
1090
1091   view->print_item = 0;
1092   view->print_n_pages = 1;
1093   view->paginated = FALSE;
1094 }
1095
1096 static void
1097 end_print (GtkPrintOperation *operation,
1098            GtkPrintContext   *context,
1099            struct psppire_output_view *view)
1100 {
1101   xr_driver_destroy (view->print_xrd);
1102 }
1103
1104
1105 static void
1106 draw_page (GtkPrintOperation *operation,
1107            GtkPrintContext   *context,
1108            gint               page_number,
1109            struct psppire_output_view *view)
1110 {
1111   xr_driver_next_page (view->print_xrd, get_cairo_context_from_print_context (context));
1112   while (!xr_driver_need_new_page (view->print_xrd)
1113          && view->print_item < view->n_items)
1114     xr_driver_output_item (view->print_xrd, view->items [view->print_item++].item);
1115 }
1116
1117
1118 void
1119 psppire_output_view_print (struct psppire_output_view *view,
1120                            GtkWindow *parent_window)
1121 {
1122   GtkPrintOperationResult res;
1123
1124   GtkPrintOperation *print = gtk_print_operation_new ();
1125
1126   if (view->print_settings != NULL)
1127     gtk_print_operation_set_print_settings (print, view->print_settings);
1128
1129   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), view);
1130   g_signal_connect (print, "end_print",   G_CALLBACK (end_print),   view);
1131   g_signal_connect (print, "paginate",    G_CALLBACK (paginate),    view);
1132   g_signal_connect (print, "draw_page",   G_CALLBACK (draw_page),   view);
1133
1134   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1135                                  parent_window, NULL);
1136
1137   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1138     {
1139       if (view->print_settings != NULL)
1140         g_object_unref (view->print_settings);
1141       view->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1142     }
1143
1144   g_object_unref (print);
1145 }
1146 \f
1147 struct psppire_output_view_driver
1148   {
1149     struct output_driver driver;
1150     struct psppire_output_view *view;
1151   };
1152
1153 static struct psppire_output_view_driver *
1154 psppire_output_view_driver_cast (struct output_driver *driver)
1155 {
1156   return UP_CAST (driver, struct psppire_output_view_driver, driver);
1157 }
1158
1159 static void
1160 psppire_output_view_submit (struct output_driver *this,
1161                             const struct output_item *item)
1162 {
1163   struct psppire_output_view_driver *povd = psppire_output_view_driver_cast (this);
1164
1165   if (is_table_item (item))
1166     psppire_output_view_put (povd->view, item);
1167 }
1168
1169 static struct output_driver_class psppire_output_view_driver_class =
1170   {
1171     "PSPPIRE Output View",      /* name */
1172     NULL,                       /* destroy */
1173     psppire_output_view_submit, /* submit */
1174     NULL,                       /* flush */
1175   };
1176
1177 void
1178 psppire_output_view_register_driver (struct psppire_output_view *view)
1179 {
1180   struct psppire_output_view_driver *povd;
1181   struct output_driver *d;
1182
1183   povd = xzalloc (sizeof *povd);
1184   povd->view = view;
1185   d = &povd->driver;
1186   output_driver_init (d, &psppire_output_view_driver_class, "PSPPIRE Output View",
1187                       SETTINGS_DEVICE_UNFILTERED);
1188   output_driver_register (d);
1189 }