Prevent critical when closing output viewer
[pspp] / src / ui / gui / psppire-output-window.c
1 /* PSPPIRE - a graphical user interface for PSPP.
2    Copyright (C) 2008, 2009, 2010  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 <errno.h>
20 #include <gtk/gtk.h>
21 #include <stdlib.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25
26 #include "libpspp/cast.h"
27 #include "libpspp/message.h"
28 #include "libpspp/string-map.h"
29 #include "output/cairo.h"
30 #include "output/chart-item.h"
31 #include "output/driver-provider.h"
32 #include "output/output-item.h"
33 #include "output/tab.h"
34 #include "output/table-item.h"
35 #include "output/text-item.h"
36 #include "ui/gui/help-menu.h"
37 #include "ui/gui/helper.h"
38 #include "ui/gui/psppire-output-window.h"
39
40 #include "gl/error.h"
41 #include "gl/tmpdir.h"
42 #include "gl/xalloc.h"
43
44 #include <gettext.h>
45 #define _(msgid) gettext (msgid)
46 #define N_(msgid) msgid
47
48 enum
49   {
50     COL_TITLE,                  /* Table title. */
51     COL_ADDR,                   /* Pointer to the table */
52     COL_Y,                      /* Y position of top of title. */
53     N_COLS
54   };
55
56 static void psppire_output_window_base_finalize (PsppireOutputWindowClass *, gpointer);
57 static void psppire_output_window_base_init     (PsppireOutputWindowClass *class);
58 static void psppire_output_window_class_init    (PsppireOutputWindowClass *class);
59 static void psppire_output_window_init          (PsppireOutputWindow      *window);
60
61
62 GType
63 psppire_output_window_get_type (void)
64 {
65   static GType psppire_output_window_type = 0;
66
67   if (!psppire_output_window_type)
68     {
69       static const GTypeInfo psppire_output_window_info =
70       {
71         sizeof (PsppireOutputWindowClass),
72         (GBaseInitFunc) psppire_output_window_base_init,
73         (GBaseFinalizeFunc) psppire_output_window_base_finalize,
74         (GClassInitFunc)psppire_output_window_class_init,
75         (GClassFinalizeFunc) NULL,
76         NULL,
77         sizeof (PsppireOutputWindow),
78         0,
79         (GInstanceInitFunc) psppire_output_window_init,
80       };
81
82       psppire_output_window_type =
83         g_type_register_static (PSPPIRE_TYPE_WINDOW, "PsppireOutputWindow",
84                                 &psppire_output_window_info, 0);
85     }
86
87   return psppire_output_window_type;
88 }
89
90 static GObjectClass *parent_class;
91
92 static void
93 psppire_output_window_finalize (GObject *object)
94 {
95   if (G_OBJECT_CLASS (parent_class)->finalize)
96     (*G_OBJECT_CLASS (parent_class)->finalize) (object);
97 }
98
99
100 static void
101 psppire_output_window_dispose (GObject *obj)
102 {
103   PsppireOutputWindow *viewer = PSPPIRE_OUTPUT_WINDOW (obj);
104   size_t i;
105
106   for (i = 0; i < viewer->n_items; i++)
107     output_item_unref (viewer->items[i]);
108   free (viewer->items);
109   viewer->items = NULL;
110   viewer->n_items = viewer->allocated_items = 0;
111
112   if (viewer->print_settings != NULL)
113     g_object_unref (viewer->print_settings);
114
115   /* Chain up to the parent class */
116   G_OBJECT_CLASS (parent_class)->dispose (obj);
117 }
118
119 static void
120 psppire_output_window_class_init (PsppireOutputWindowClass *class)
121 {
122   GObjectClass *object_class = G_OBJECT_CLASS (class);
123
124   parent_class = g_type_class_peek_parent (class);
125   object_class->dispose = psppire_output_window_dispose;
126 }
127
128
129 static void
130 psppire_output_window_base_init (PsppireOutputWindowClass *class)
131 {
132   GObjectClass *object_class = G_OBJECT_CLASS (class);
133
134   object_class->finalize = psppire_output_window_finalize;
135 }
136
137
138
139 static void
140 psppire_output_window_base_finalize (PsppireOutputWindowClass *class,
141                                      gpointer class_data)
142 {
143 }
144 \f
145 /* Output driver class. */
146
147 struct psppire_output_driver
148   {
149     struct output_driver driver;
150     PsppireOutputWindow *viewer;
151     struct xr_driver *xr;
152   };
153
154 static struct output_driver_class psppire_output_class;
155
156 static struct psppire_output_driver *
157 psppire_output_cast (struct output_driver *driver)
158 {
159   assert (driver->class == &psppire_output_class);
160   return UP_CAST (driver, struct psppire_output_driver, driver);
161 }
162
163 static gboolean
164 expose_event_callback (GtkWidget *widget, GdkEventExpose *event, gpointer data)
165 {
166   struct xr_rendering *r = g_object_get_data (G_OBJECT (widget), "rendering");
167   cairo_t *cr;
168
169   cr = gdk_cairo_create (widget->window);
170   xr_rendering_draw (r, cr, event->area.x, event->area.y,
171                      event->area.width, event->area.height);
172   cairo_destroy (cr);
173
174   return TRUE;
175 }
176
177 static void
178 psppire_output_submit (struct output_driver *this,
179                        const struct output_item *item)
180 {
181   struct psppire_output_driver *pod = psppire_output_cast (this);
182   PsppireOutputWindow *viewer;
183   GtkWidget *drawing_area;
184   struct xr_rendering *r;
185   struct string title;
186   GtkTreeStore *store;
187   GtkTreePath *path;
188   GtkTreeIter iter;
189   cairo_t *cr;
190   int tw, th;
191
192   if (pod->viewer == NULL)
193     {
194       pod->viewer = PSPPIRE_OUTPUT_WINDOW (psppire_output_window_new ());
195       gtk_widget_show_all (GTK_WIDGET (pod->viewer));
196       pod->viewer->driver = pod;
197     }
198   viewer = pod->viewer;
199
200   if (viewer->n_items >= viewer->allocated_items)
201     viewer->items = x2nrealloc (viewer->items, &viewer->allocated_items,
202                                 sizeof *viewer->items);
203   viewer->items[viewer->n_items++] = output_item_ref (item);
204
205   if (is_text_item (item))
206     {
207       const struct text_item *text_item = to_text_item (item);
208       enum text_item_type type = text_item_get_type (text_item);
209       const char *text = text_item_get_text (text_item);
210
211       if (type == TEXT_ITEM_COMMAND_CLOSE)
212         {
213           viewer->in_command = false;
214           return;
215         }
216       else if (text[0] == '\0')
217         return;
218     }
219
220   cr = gdk_cairo_create (GTK_WIDGET (pod->viewer)->window);
221   if (pod->xr == NULL)
222     {
223       const GtkStyle *style = gtk_widget_get_style (GTK_WIDGET (viewer));
224       struct string_map options = STRING_MAP_INITIALIZER (options);
225       PangoFontDescription *font_desc;
226       char *font_name;
227
228       /* Use GTK+ default font as proportional font. */
229       font_name = pango_font_description_to_string (style->font_desc);
230       string_map_insert (&options, "prop-font", font_name);
231       g_free (font_name);
232
233       /* Derived emphasized font from proportional font. */
234       font_desc = pango_font_description_copy (style->font_desc);
235       pango_font_description_set_style (font_desc, PANGO_STYLE_ITALIC);
236       font_name = pango_font_description_to_string (font_desc);
237       string_map_insert (&options, "emph-font", font_name);
238       g_free (font_name);
239       pango_font_description_free (font_desc);
240
241       /* Pretend that the "page" has a reasonable width and a very big length,
242          so that most tables can be conveniently viewed on-screen with vertical
243          scrolling only.  (The length should not be increased very much because
244          it is already close enough to INT_MAX when expressed as thousands of a
245          point.) */
246       string_map_insert (&options, "paper-size", "300x200000mm");
247       string_map_insert (&options, "left-margin", "0");
248       string_map_insert (&options, "right-margin", "0");
249       string_map_insert (&options, "top-margin", "0");
250       string_map_insert (&options, "bottom-margin", "0");
251
252       pod->xr = xr_driver_create (cr, &options);
253
254       string_map_destroy (&options);
255     }
256
257   r = xr_rendering_create (pod->xr, item, cr);
258   if (r == NULL)
259     goto done;
260
261   xr_rendering_measure (r, &tw, &th);
262
263   drawing_area = gtk_drawing_area_new ();
264   gtk_widget_modify_bg (
265     GTK_WIDGET (drawing_area), GTK_STATE_NORMAL,
266     &gtk_widget_get_style (drawing_area)->base[GTK_STATE_NORMAL]);
267   g_object_set_data (G_OBJECT (drawing_area), "rendering", r);
268   gtk_widget_set_size_request (drawing_area, tw, th);
269   gtk_layout_put (pod->viewer->output, drawing_area, 0, pod->viewer->y);
270   gtk_widget_show (drawing_area);
271   g_signal_connect (G_OBJECT (drawing_area), "expose_event",
272                      G_CALLBACK (expose_event_callback), NULL);
273
274   if (!is_text_item (item)
275       || text_item_get_type (to_text_item (item)) != TEXT_ITEM_SYNTAX
276       || !viewer->in_command)
277     {
278       store = GTK_TREE_STORE (gtk_tree_view_get_model (viewer->overview));
279
280       ds_init_empty (&title);
281       if (is_text_item (item)
282           && text_item_get_type (to_text_item (item)) == TEXT_ITEM_COMMAND_OPEN)
283         {
284           gtk_tree_store_append (store, &iter, NULL);
285           viewer->cur_command = iter; /* XXX shouldn't save a GtkTreeIter */
286           viewer->in_command = true;
287         }
288       else
289         {
290           GtkTreeIter *p = viewer->in_command ? &viewer->cur_command : NULL;
291           gtk_tree_store_append (store, &iter, p);
292         }
293
294       ds_clear (&title);
295       if (is_text_item (item))
296         ds_put_cstr (&title, text_item_get_text (to_text_item (item)));
297       else if (is_table_item (item))
298         {
299           const char *caption = table_item_get_caption (to_table_item (item));
300           if (caption != NULL)
301             ds_put_format (&title, "Table: %s", caption);
302           else
303             ds_put_cstr (&title, "Table");
304         }
305       else if (is_chart_item (item))
306         {
307           const char *s = chart_item_get_title (to_chart_item (item));
308           if (s != NULL)
309             ds_put_format (&title, "Chart: %s", s);
310           else
311             ds_put_cstr (&title, "Chart");
312         }
313       gtk_tree_store_set (store, &iter,
314                           COL_TITLE, ds_cstr (&title),
315                           COL_ADDR, item, 
316                           COL_Y, viewer->y,
317                           -1);
318       ds_destroy (&title);
319
320       path = gtk_tree_model_get_path (GTK_TREE_MODEL (store), &iter);
321       gtk_tree_view_expand_row (viewer->overview, path, TRUE);
322       gtk_tree_path_free (path);
323     }
324
325   if (pod->viewer->max_width < tw)
326     pod->viewer->max_width = tw;
327   pod->viewer->y += th;
328
329   gtk_layout_set_size (pod->viewer->output,
330                        pod->viewer->max_width, pod->viewer->y);
331
332   gtk_window_set_urgency_hint (GTK_WINDOW (pod->viewer), TRUE);
333
334 done:
335   cairo_destroy (cr);
336 }
337
338 static struct output_driver_class psppire_output_class =
339   {
340     "PSPPIRE",                  /* name */
341     NULL,                       /* destroy */
342     psppire_output_submit,      /* submit */
343     NULL,                       /* flush */
344   };
345
346 void
347 psppire_output_window_setup (void)
348 {
349   struct psppire_output_driver *pod;
350   struct output_driver *d;
351
352   pod = xzalloc (sizeof *pod);
353   d = &pod->driver;
354   output_driver_init (d, &psppire_output_class, "PSPPIRE",
355                       SETTINGS_DEVICE_UNFILTERED);
356   output_driver_register (d);
357 }
358 \f
359 int viewer_length = 16;
360 int viewer_width = 59;
361
362 /* Callback for the "delete" action (clicking the x on the top right
363    hand corner of the window) */
364 static gboolean
365 on_delete (GtkWidget *w, GdkEvent *event, gpointer user_data)
366 {
367   PsppireOutputWindow *ow = PSPPIRE_OUTPUT_WINDOW (user_data);
368
369   gtk_widget_destroy (GTK_WIDGET (ow));
370
371   ow->driver->viewer = NULL;
372
373   return FALSE;
374 }
375
376
377
378 static void
379 cancel_urgency (GtkWindow *window,  gpointer data)
380 {
381   gtk_window_set_urgency_hint (window, FALSE);
382 }
383
384 static void
385 on_row_activate (GtkTreeView *overview,
386                  GtkTreePath *path,
387                  GtkTreeViewColumn *column,
388                  PsppireOutputWindow *window)
389 {
390   GtkTreeModel *model;
391   GtkTreeIter iter;
392   GtkAdjustment *vadj;
393   GValue value = {0};
394   double y, min, max;
395
396   model = gtk_tree_view_get_model (overview);
397   if (!gtk_tree_model_get_iter (model, &iter, path))
398     return;
399
400   gtk_tree_model_get_value (model, &iter, COL_Y, &value);
401   y = g_value_get_long (&value);
402   g_value_unset (&value);
403
404   vadj = gtk_layout_get_vadjustment (window->output);
405   min = vadj->lower;
406   max = vadj->upper - vadj->page_size;
407   if (y < min)
408     y = min;
409   else if (y > max)
410     y = max;
411   gtk_adjustment_set_value (vadj, y);
412 }
413
414 static void psppire_output_window_print (PsppireOutputWindow *window);
415
416
417 static void
418 export_output (PsppireOutputWindow *window, struct string_map *options,
419                const char *format)
420 {
421   struct output_driver *driver;
422   size_t i;
423
424   string_map_insert (options, "format", format);
425   driver = output_driver_create (options);
426   if (driver == NULL)
427     return;
428
429   for (i = 0; i < window->n_items; i++)
430     driver->class->submit (driver, window->items[i]);
431   output_driver_destroy (driver);
432 }
433
434
435 struct file_types
436 {
437   const gchar *label;
438   const gchar *ext;
439 };
440
441 enum 
442   {
443     FT_AUTO = 0,
444     FT_PDF,
445     FT_HTML,
446     FT_ODT,
447     FT_TXT,
448     FT_PS,
449     FT_CSV,
450     n_FT
451   };
452
453 #define N_EXTENTIONS (n_FT - 1)
454
455 struct file_types ft[n_FT] = {
456   {N_("Infer file type from extension"),  NULL},
457   {N_("PDF (*.pdf)"),                     ".pdf"},
458   {N_("HTML (*.html)"),                   ".html"},
459   {N_("OpenDocument (*.odt)"),            ".odt"},
460   {N_("Text (*.txt)"),                    ".txt"},
461   {N_("PostScript (*.ps)"),               ".ps"},
462   {N_("Comma-Separated Values (*.csv)"),  ".csv"}
463 };
464
465
466 static void
467 on_combo_change (GtkFileChooser *chooser)
468 {
469   gboolean sensitive = FALSE;
470   GtkWidget *combo = gtk_file_chooser_get_extra_widget (chooser);
471
472   int x = 0; 
473   gchar *fn = gtk_file_chooser_get_filename (chooser);
474
475   if (combo &&  GTK_WIDGET_REALIZED (combo))
476     x = gtk_combo_box_get_active (GTK_COMBO_BOX (combo));
477
478   if (fn == NULL)
479     {
480       sensitive = FALSE;
481     }
482   else
483     {
484       gint i;
485       if ( x != 0 )
486         sensitive = TRUE;
487
488       for (i = 1 ; i < N_EXTENTIONS ; ++i)
489         {
490           if ( g_str_has_suffix (fn, ft[i].ext))
491             {
492               sensitive = TRUE;
493               break;
494             }
495         }
496     }
497
498   g_free (fn);
499
500   gtk_dialog_set_response_sensitive (GTK_DIALOG (chooser), GTK_RESPONSE_ACCEPT, sensitive);
501 }
502
503
504 static void
505 on_file_chooser_change (GObject *w, GParamSpec *pspec, gpointer data)
506 {
507
508   GtkFileChooser *chooser = data;
509   const gchar *name = g_param_spec_get_name (pspec);
510
511   if ( ! GTK_WIDGET_REALIZED (chooser))
512     return;
513
514   /* Ignore this one.  It causes recursion. */
515   if ( 0 == strcmp ("tooltip-text", name))
516     return;
517
518   on_combo_change (chooser);
519 }
520
521
522 /* Recursively descend all the children of W, connecting
523    to their "notify" signal */
524 static void
525 iterate_widgets (GtkWidget *w, gpointer data)
526 {
527   if ( GTK_IS_CONTAINER (w))
528     gtk_container_forall (GTK_CONTAINER (w), iterate_widgets, data);
529   else
530     g_signal_connect (w, "notify",  G_CALLBACK (on_file_chooser_change), data);
531 }
532
533
534
535 static GtkListStore *
536 create_file_type_list (void)
537 {
538   int i;
539   GtkTreeIter iter;
540   GtkListStore *list = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_STRING);
541   
542   for (i = 0 ; i < 6 ; ++i)
543     {
544       gtk_list_store_append (list, &iter);
545       gtk_list_store_set (list, &iter,
546                           0,  gettext (ft[i].label),
547                           1,  ft[i].ext,
548                           -1);
549     }
550   
551   return list;
552 }
553
554 static void
555 psppire_output_window_export (PsppireOutputWindow *window)
556 {
557   gint response;
558   GtkWidget *combo;
559   GtkListStore *list;
560
561   GtkFileChooser *chooser;
562   
563   GtkWidget *dialog = gtk_file_chooser_dialog_new (_("Export Output"),
564                                         GTK_WINDOW (window),
565                                         GTK_FILE_CHOOSER_ACTION_SAVE,
566                                         GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
567                                         GTK_STOCK_SAVE,   GTK_RESPONSE_ACCEPT,
568                                         NULL);
569
570   chooser = GTK_FILE_CHOOSER (dialog);
571
572   list = create_file_type_list ();
573
574   combo = gtk_combo_box_new_with_model (GTK_TREE_MODEL (list));
575
576
577   {
578     /* Create text cell renderer */
579     GtkCellRenderer *cell = gtk_cell_renderer_text_new();
580     gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), cell, FALSE );
581
582     gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (combo), cell,  "text", 0);
583   }
584
585   g_signal_connect_swapped (combo, "changed", G_CALLBACK (on_combo_change), chooser);
586
587   gtk_combo_box_set_active (GTK_COMBO_BOX (combo), 0);
588
589   gtk_file_chooser_set_extra_widget (chooser, combo);
590
591   /* This kludge is necessary because there is no signal to tell us
592      when the candidate filename of a GtkFileChooser has changed */
593   gtk_container_forall (GTK_CONTAINER (dialog), iterate_widgets, dialog);
594
595
596   gtk_file_chooser_set_do_overwrite_confirmation (chooser, TRUE);
597
598   response = gtk_dialog_run (GTK_DIALOG (dialog));
599
600   if ( response == GTK_RESPONSE_ACCEPT )
601     {
602       int file_type = gtk_combo_box_get_active (GTK_COMBO_BOX (combo));
603       char *filename = gtk_file_chooser_get_filename (chooser);
604       struct string_map options;
605
606       g_return_if_fail (filename);
607
608       if (file_type == FT_AUTO)
609         {
610           gint i;
611           for (i = 1 ; i < N_EXTENTIONS ; ++i)
612             {
613               if ( g_str_has_suffix (filename, ft[i].ext))
614                 {
615                   file_type = i;
616                   break;
617                 }
618             }
619         }
620
621       
622       string_map_init (&options);
623       string_map_insert (&options, "output-file", filename);
624
625       switch (file_type)
626         {
627         case FT_PDF:
628           export_output (window, &options, "pdf");
629           break;
630         case FT_HTML:
631           export_output (window, &options, "html");
632           break;
633         case FT_ODT:
634           export_output (window, &options, "odt");
635           break;
636         case FT_PS:
637           export_output (window, &options, "ps");
638           break;
639         case FT_CSV:
640           export_output (window, &options, "csv");
641           break;
642
643         case FT_TXT:
644           string_map_insert (&options, "headers", "false");
645           string_map_insert (&options, "paginate", "false");
646           string_map_insert (&options, "squeeze", "true");
647           string_map_insert (&options, "emphasis", "none");
648           string_map_insert (&options, "charts", "none");
649           string_map_insert (&options, "top-margin", "0");
650           string_map_insert (&options, "bottom-margin", "0");
651           export_output (window, &options, "txt");
652           break;
653         default:
654           g_assert_not_reached ();
655         }
656
657       string_map_destroy (&options);
658
659       free (filename);
660     }
661
662   gtk_widget_destroy (dialog);
663 }
664
665
666 enum {
667   SELECT_FMT_NULL,
668   SELECT_FMT_TEXT,
669   SELECT_FMT_UTF8,
670   SELECT_FMT_HTML,
671   SELECT_FMT_ODT
672 };
673
674
675 static void
676 insert_glyph (struct string_map *map, const char *opt, gunichar glyph)
677 {
678   char s[6] = {0,0,0,0,0,0};
679
680   g_unichar_to_utf8 (glyph, s);
681   string_map_insert (map, opt, s);
682 }
683
684 struct glyph_pair
685 {
686   gunichar glyph;
687   char opt[10];
688 };
689
690 /* See the table at 
691    http://en.wikipedia.org/wiki/Box-drawing_characters */
692 struct glyph_pair table[] = {
693   {0x2500, "box[1010]"},
694   {0x2501, "box[2020]"},
695   {0x2502, "box[0101]"},
696   {0x2503, "box[0202]"},
697
698   {0x250C, "box[1100]"},
699   {0x250D, "box[2100]"},
700   {0x250E, "box[1200]"},
701   {0x250F, "box[2200]"},
702   {0x2510, "box[0110]"},
703   {0x2511, "box[0110]"},
704   {0x2512, "box[0210]"},
705   {0x2513, "box[0220]"},
706   {0x2514, "box[1001]"},
707   {0x2515, "box[2001]"},
708   {0x2516, "box[1002]"},
709   {0x2517, "box[2002]"},
710   {0x2518, "box[0011]"},
711   {0x2519, "box[0021]"},
712   {0x251A, "box[0012]"},
713   {0x251B, "box[0022]"},
714   {0x251C, "box[1101]"},
715   {0x251D, "box[2101]"},
716   {0x251E, "box[1102]"},
717   {0x251F, "box[1201]"},
718   {0x2520, "box[1202]"},
719   {0x2521, "box[2102]"},
720   {0x2522, "box[2201]"},
721   {0x2523, "box[2202]"},
722   {0x2524, "box[0111]"},
723   {0x2525, "box[0121]"},
724   {0x2526, "box[0112]"},
725   {0x2527, "box[0211]"},
726   {0x2528, "box[0212]"},
727   {0x2529, "box[0122]"},
728   {0x252A, "box[0221]"},
729   {0x252B, "box[0222]"},
730   {0x252C, "box[1110]"},
731   {0x252D, "box[1120]"},
732   {0x252E, "box[2110]"},
733   {0x252F, "box[2120]"},
734   {0x2530, "box[1210]"},
735   {0x2531, "box[1220]"},
736   {0x2532, "box[2210]"},
737   {0x2533, "box[2220]"},
738   {0x2534, "box[1011]"},
739   {0x2535, "box[1021]"},
740   {0x2536, "box[2011]"},
741   {0x2537, "box[2021]"},
742   {0x2538, "box[1012]"},
743   {0x2539, "box[1022]"},
744   {0x253A, "box[2012]"},
745   {0x253B, "box[2022]"},
746   {0x253C, "box[1111]"},
747   {0x253D, "box[1121]"},
748   {0x253E, "box[2111]"},
749   {0x253F, "box[2121]"},
750   {0x2540, "box[1112]"},
751   {0x2541, "box[1211]"},
752   {0x2542, "box[1212]"},
753   {0x2543, "box[1122]"},
754   {0x2544, "box[2112]"},
755   {0x2545, "box[1221]"},
756   {0x2546, "box[2211]"},
757   {0x2547, "box[2122]"},
758   {0x2548, "box[2221]"},
759   {0x2549, "box[1222]"},
760   {0x254A, "box[2212]"},
761   {0x254B, "box[2222]"},
762
763   {0x2574, "box[0010]"},
764   {0x2575, "box[0001]"},
765   {0x2576, "box[1000]"},
766   {0x2577, "box[0100]"},
767   {0x2578, "box[0020]"},
768   {0x2579, "box[0002]"},
769   {0x257A, "box[2000]"},
770   {0x257B, "box[0200]"},
771   {0x257C, "box[2010]"},
772   {0x257D, "box[0201]"},
773   {0x257E, "box[1020]"},
774   {0x257F, "box[0102]"},
775 };
776
777
778 static void
779 utf8_box_chars (struct string_map *map)
780 {
781   int i;
782   for (i = 0; i < sizeof (table) / sizeof (table[0]); ++i)
783     {
784       const struct glyph_pair *p = &table[i];
785       insert_glyph (map, p->opt, p->glyph);
786     }
787 }
788
789
790
791 static void
792 clipboard_get_cb (GtkClipboard     *clipboard,
793                   GtkSelectionData *selection_data,
794                   guint             info,
795                   gpointer          data)
796 {
797   PsppireOutputWindow *window = data;
798
799   gsize length;
800   gchar *text = NULL;
801   struct output_driver *driver = NULL;
802   char dirname[PATH_MAX], *filename;
803   struct string_map options;
804
805   GtkTreeSelection *sel = gtk_tree_view_get_selection (window->overview);
806   GtkTreeModel *model = gtk_tree_view_get_model (window->overview);
807
808   GList *rows = gtk_tree_selection_get_selected_rows (sel, &model);
809   GList *n = rows;
810
811   if ( n == NULL)
812     return;
813
814   if (path_search (dirname, sizeof dirname, NULL, NULL, true)
815       || mkdtemp (dirname) == NULL)
816     {
817       error (0, errno, _("failed to create temporary directory"));
818       return;
819     }
820   filename = xasprintf ("%s/clip.tmp", dirname);
821
822   string_map_init (&options);
823   string_map_insert (&options, "output-file", filename);
824
825   switch (info)
826     {
827     case SELECT_FMT_UTF8:
828       utf8_box_chars (&options);
829       /* fall-through */
830
831     case SELECT_FMT_TEXT:
832       string_map_insert (&options, "format", "txt");
833       break;
834
835     case SELECT_FMT_HTML:
836       string_map_insert (&options, "format", "html");
837       break;
838
839     case SELECT_FMT_ODT:
840       string_map_insert (&options, "format", "odt");
841       break;
842
843     default:
844       g_warning ("unsupported clip target\n");
845       goto finish;
846       break;
847     }
848
849   driver = output_driver_create (&options);
850   if (driver == NULL)
851     goto finish;
852
853   while (n)
854     {
855       GtkTreePath *path = n->data ; 
856       GtkTreeIter iter;
857       struct output_item *item ;
858
859       gtk_tree_model_get_iter (model, &iter, path);
860       gtk_tree_model_get (model, &iter, COL_ADDR, &item, -1);
861
862       driver->class->submit (driver, item);
863
864       n = n->next;
865     }
866
867   if ( driver->class->flush)
868     driver->class->flush (driver);
869
870
871   /* Some drivers (eg: the odt one) don't write anything until they
872      are closed */
873   output_driver_destroy (driver);
874   driver = NULL;
875
876   if ( g_file_get_contents (filename, &text, &length, NULL) )
877     {
878       gtk_selection_data_set (selection_data, selection_data->target,
879                               8,
880                               (const guchar *) text, length);
881     }
882
883  finish:
884
885   if (driver != NULL)
886     output_driver_destroy (driver);
887
888   g_free (text);
889
890   unlink (filename);
891   free (filename);
892   rmdir (dirname);
893
894   g_list_free (rows);
895 }
896
897 static void
898 clipboard_clear_cb (GtkClipboard *clipboard,
899                     gpointer data)
900 {
901 }
902
903 static const GtkTargetEntry targets[] = {
904
905   { "STRING",        0, SELECT_FMT_TEXT },
906   { "TEXT",          0, SELECT_FMT_TEXT },
907   { "COMPOUND_TEXT", 0, SELECT_FMT_TEXT },
908   { "text/plain",    0, SELECT_FMT_TEXT },
909
910   { "UTF8_STRING",   0, SELECT_FMT_UTF8 },
911   { "text/plain;charset=utf-8", 0, SELECT_FMT_UTF8 },
912
913   { "text/html",     0, SELECT_FMT_HTML },
914
915   { "application/vnd.oasis.opendocument.text", 0, SELECT_FMT_ODT }
916 };
917
918 static void
919 on_copy (PsppireOutputWindow *window)
920 {
921   {
922     GtkClipboard *clipboard =
923       gtk_widget_get_clipboard (GTK_WIDGET (window),
924                                 GDK_SELECTION_CLIPBOARD);
925
926     if (!gtk_clipboard_set_with_data (clipboard, targets,
927                                        G_N_ELEMENTS (targets),
928                                        clipboard_get_cb, clipboard_clear_cb,
929                                       window))
930
931       clipboard_clear_cb (clipboard, window);
932   }
933 }
934
935 static void
936 on_selection_change (GtkTreeSelection *sel, GtkAction *copy_action)
937 {
938   /* The Copy action is available only if there is something selected */
939   gtk_action_set_sensitive (copy_action, gtk_tree_selection_count_selected_rows (sel) > 0);
940 }
941
942 static void
943 on_select_all (PsppireOutputWindow *window)
944 {
945   GtkTreeSelection *sel = gtk_tree_view_get_selection (window->overview);
946   gtk_tree_view_expand_all (window->overview);
947   gtk_tree_selection_select_all (sel);
948 }
949
950
951 static void
952 psppire_output_window_init (PsppireOutputWindow *window)
953 {
954   GtkTreeViewColumn *column;
955   GtkCellRenderer *renderer;
956   GtkBuilder *xml;
957   GtkAction *copy_action;
958   GtkAction *select_all_action;
959   GtkTreeSelection *sel;
960
961   xml = builder_new ("output-viewer.ui");
962
963   copy_action = get_action_assert (xml, "edit_copy");
964   select_all_action = get_action_assert (xml, "edit_select-all");
965
966   gtk_action_set_sensitive (copy_action, FALSE);
967
968   g_signal_connect_swapped (copy_action, "activate", G_CALLBACK (on_copy), window);
969
970   g_signal_connect_swapped (select_all_action, "activate", G_CALLBACK (on_select_all), window);
971
972   gtk_widget_reparent (get_widget_assert (xml, "vbox1"), GTK_WIDGET (window));
973
974   window->output = GTK_LAYOUT (get_widget_assert (xml, "output"));
975   window->y = 0;
976
977   window->overview = GTK_TREE_VIEW (get_widget_assert (xml, "overview"));
978
979   sel = gtk_tree_view_get_selection (window->overview);
980
981   gtk_tree_selection_set_mode (sel, GTK_SELECTION_MULTIPLE);
982
983   g_signal_connect (sel, "changed", G_CALLBACK (on_selection_change), copy_action);
984
985   gtk_tree_view_set_model (window->overview,
986                            GTK_TREE_MODEL (gtk_tree_store_new (
987                                              N_COLS,
988                                              G_TYPE_STRING,  /* COL_TITLE */
989                                              G_TYPE_POINTER, /* COL_ADDR */
990                                              G_TYPE_LONG))); /* COL_Y */
991
992   window->in_command = false;
993
994   window->items = NULL;
995   window->n_items = window->allocated_items = 0;
996
997   column = gtk_tree_view_column_new ();
998   gtk_tree_view_append_column (GTK_TREE_VIEW (window->overview), column);
999   renderer = gtk_cell_renderer_text_new ();
1000   gtk_tree_view_column_pack_start (column, renderer, TRUE);
1001   gtk_tree_view_column_add_attribute (column, renderer, "text", COL_TITLE);
1002
1003   g_signal_connect (GTK_TREE_VIEW (window->overview),
1004                     "row-activated", G_CALLBACK (on_row_activate), window);
1005
1006   gtk_widget_modify_bg (GTK_WIDGET (window->output), GTK_STATE_NORMAL,
1007                         &gtk_widget_get_style (GTK_WIDGET (window->output))->base[GTK_STATE_NORMAL]);
1008
1009   connect_help (xml);
1010
1011   g_signal_connect (window,
1012                     "focus-in-event",
1013                     G_CALLBACK (cancel_urgency),
1014                     NULL);
1015
1016   g_signal_connect (get_action_assert (xml,"windows_minimise-all"),
1017                     "activate",
1018                     G_CALLBACK (psppire_window_minimise_all),
1019                     NULL);
1020
1021   {
1022     GtkUIManager *uim = GTK_UI_MANAGER (get_object_assert (xml, "uimanager1", GTK_TYPE_UI_MANAGER));
1023     merge_help_menu (uim);
1024
1025     PSPPIRE_WINDOW (window)->menu =
1026       GTK_MENU_SHELL (gtk_ui_manager_get_widget (uim,"/ui/menubar/windows_menuitem/windows_minimise-all")->parent);
1027   }
1028
1029   g_signal_connect_swapped (get_action_assert (xml, "file_export"), "activate",
1030                             G_CALLBACK (psppire_output_window_export), window);
1031
1032
1033   g_signal_connect_swapped (get_action_assert (xml, "file_print"), "activate",
1034                             G_CALLBACK (psppire_output_window_print), window);
1035
1036   g_object_unref (xml);
1037
1038   g_signal_connect (window, "delete-event",
1039                     G_CALLBACK (on_delete), window);
1040 }
1041
1042
1043 GtkWidget*
1044 psppire_output_window_new (void)
1045 {
1046   return GTK_WIDGET (g_object_new (psppire_output_window_get_type (),
1047                                    /* TRANSLATORS: This will form a filename.  Please avoid whitespace. */
1048                                    "filename", _("Output"),
1049                                    "description", _("Output Viewer"),
1050                                    NULL));
1051 }
1052
1053
1054 \f
1055 static void
1056 create_xr_print_driver (GtkPrintContext *context, PsppireOutputWindow *window)
1057 {
1058   struct string_map options;
1059   GtkPageSetup *page_setup;
1060   double width, height;
1061   double left_margin;
1062   double right_margin;
1063   double top_margin;
1064   double bottom_margin;
1065
1066   page_setup = gtk_print_context_get_page_setup (context);
1067   width = gtk_page_setup_get_paper_width (page_setup, GTK_UNIT_MM);
1068   height = gtk_page_setup_get_paper_height (page_setup, GTK_UNIT_MM);
1069   left_margin = gtk_page_setup_get_left_margin (page_setup, GTK_UNIT_MM);
1070   right_margin = gtk_page_setup_get_right_margin (page_setup, GTK_UNIT_MM);
1071   top_margin = gtk_page_setup_get_top_margin (page_setup, GTK_UNIT_MM);
1072   bottom_margin = gtk_page_setup_get_bottom_margin (page_setup, GTK_UNIT_MM);
1073
1074   string_map_init (&options);
1075   string_map_insert_nocopy (&options, xstrdup ("paper-size"),
1076                             xasprintf("%.2fx%.2fmm", width, height));
1077   string_map_insert_nocopy (&options, xstrdup ("left-margin"),
1078                             xasprintf ("%.2fmm", left_margin));
1079   string_map_insert_nocopy (&options, xstrdup ("right-margin"),
1080                             xasprintf ("%.2fmm", right_margin));
1081   string_map_insert_nocopy (&options, xstrdup ("top-margin"),
1082                             xasprintf ("%.2fmm", top_margin));
1083   string_map_insert_nocopy (&options, xstrdup ("bottom-margin"),
1084                             xasprintf ("%.2fmm", bottom_margin));
1085
1086   window->print_xrd =
1087     xr_driver_create (gtk_print_context_get_cairo_context (context), &options);
1088
1089   string_map_destroy (&options);
1090 }
1091
1092 static gboolean
1093 paginate (GtkPrintOperation *operation,
1094           GtkPrintContext   *context,
1095           PsppireOutputWindow *window)
1096 {
1097   if ( window->print_item < window->n_items )
1098     {
1099       xr_driver_output_item (window->print_xrd, window->items[window->print_item++]);
1100       if (xr_driver_need_new_page (window->print_xrd))
1101         {
1102           xr_driver_next_page (window->print_xrd, NULL);
1103           window->print_n_pages ++;
1104         }
1105       return FALSE;
1106     }
1107   else
1108     {
1109       gtk_print_operation_set_n_pages (operation, window->print_n_pages);
1110       window->print_item = 0;
1111       create_xr_print_driver (context, window);
1112       return TRUE;
1113     }
1114 }
1115
1116 static void
1117 begin_print (GtkPrintOperation *operation,
1118              GtkPrintContext   *context,
1119              PsppireOutputWindow *window)
1120 {
1121   create_xr_print_driver (context, window);
1122
1123   window->print_item = 0;
1124   window->print_n_pages = 1;
1125 }
1126
1127 static void
1128 end_print (GtkPrintOperation *operation,
1129            GtkPrintContext   *context,
1130            PsppireOutputWindow *window)
1131 {
1132   xr_driver_destroy (window->print_xrd);
1133 }
1134
1135
1136 static void
1137 draw_page (GtkPrintOperation *operation,
1138            GtkPrintContext   *context,
1139            gint               page_number,
1140            PsppireOutputWindow *window)
1141 {
1142   xr_driver_next_page (window->print_xrd, gtk_print_context_get_cairo_context (context));
1143   while ( window->print_item < window->n_items)
1144     {
1145       xr_driver_output_item (window->print_xrd, window->items [window->print_item++]);
1146       if ( xr_driver_need_new_page (window->print_xrd) )
1147           break;          
1148     }
1149 }
1150
1151
1152 static void
1153 psppire_output_window_print (PsppireOutputWindow *window)
1154 {
1155   GtkPrintOperationResult res;
1156
1157   GtkPrintOperation *print = gtk_print_operation_new ();
1158
1159   if (window->print_settings != NULL) 
1160     gtk_print_operation_set_print_settings (print, window->print_settings);
1161
1162   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), window);
1163   g_signal_connect (print, "end_print", G_CALLBACK (end_print),     window);
1164   g_signal_connect (print, "paginate", G_CALLBACK (paginate),       window);
1165   g_signal_connect (print, "draw_page", G_CALLBACK (draw_page),     window);
1166
1167   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1168                                  GTK_WINDOW (window), NULL);
1169
1170   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1171     {
1172       if (window->print_settings != NULL)
1173         g_object_unref (window->print_settings);
1174       window->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1175       
1176     }
1177
1178   g_object_unref (print);
1179 }