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