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