Remove unused global variables
[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
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
378 \f
379
380 /* Callback for the "delete" action (clicking the x on the top right
381    hand corner of the window) */
382 static gboolean
383 on_delete (GtkWidget *w, GdkEvent *event, gpointer user_data)
384 {
385   PsppireOutputWindow *ow = PSPPIRE_OUTPUT_WINDOW (user_data);
386
387   gtk_widget_destroy (GTK_WIDGET (ow));
388
389   ow->driver->viewer = NULL;
390
391   return FALSE;
392 }
393
394
395
396 static void
397 cancel_urgency (GtkWindow *window,  gpointer data)
398 {
399   gtk_window_set_urgency_hint (window, FALSE);
400 }
401
402 static void
403 on_row_activate (GtkTreeView *overview,
404                  GtkTreePath *path,
405                  GtkTreeViewColumn *column,
406                  PsppireOutputWindow *window)
407 {
408   GtkTreeModel *model;
409   GtkTreeIter iter;
410   GtkAdjustment *vadj;
411   GValue value = {0};
412   double y, min, max;
413
414   model = gtk_tree_view_get_model (overview);
415   if (!gtk_tree_model_get_iter (model, &iter, path))
416     return;
417
418   gtk_tree_model_get_value (model, &iter, COL_Y, &value);
419   y = g_value_get_long (&value);
420   g_value_unset (&value);
421
422   vadj = gtk_layout_get_vadjustment (window->output);
423   min = vadj->lower;
424   max = vadj->upper - vadj->page_size;
425   if (y < min)
426     y = min;
427   else if (y > max)
428     y = max;
429   gtk_adjustment_set_value (vadj, y);
430 }
431
432 static void psppire_output_window_print (PsppireOutputWindow *window);
433
434
435 static void
436 export_output (PsppireOutputWindow *window, struct string_map *options,
437                const char *format)
438 {
439   struct output_driver *driver;
440   size_t i;
441
442   string_map_insert (options, "format", format);
443   driver = output_driver_create (options);
444   if (driver == NULL)
445     return;
446
447   for (i = 0; i < window->n_items; i++)
448     driver->class->submit (driver, window->items[i]);
449   output_driver_destroy (driver);
450 }
451
452
453 struct file_types
454 {
455   const gchar *label;
456   const gchar *ext;
457 };
458
459 enum 
460   {
461     FT_AUTO = 0,
462     FT_PDF,
463     FT_HTML,
464     FT_ODT,
465     FT_TXT,
466     FT_PS,
467     FT_CSV,
468     n_FT
469   };
470
471 #define N_EXTENSIONS (n_FT - 1)
472
473 struct file_types ft[n_FT] = {
474   {N_("Infer file type from extension"),  NULL},
475   {N_("PDF (*.pdf)"),                     ".pdf"},
476   {N_("HTML (*.html)"),                   ".html"},
477   {N_("OpenDocument (*.odt)"),            ".odt"},
478   {N_("Text (*.txt)"),                    ".txt"},
479   {N_("PostScript (*.ps)"),               ".ps"},
480   {N_("Comma-Separated Values (*.csv)"),  ".csv"}
481 };
482
483
484 static void
485 on_combo_change (GtkFileChooser *chooser)
486 {
487   gboolean sensitive = FALSE;
488   GtkWidget *combo = gtk_file_chooser_get_extra_widget (chooser);
489
490   int x = 0; 
491   gchar *fn = gtk_file_chooser_get_filename (chooser);
492
493   if (combo &&  gtk_widget_get_realized (combo))
494     x = gtk_combo_box_get_active (GTK_COMBO_BOX (combo));
495
496   if (fn == NULL)
497     {
498       sensitive = FALSE;
499     }
500   else
501     {
502       gint i;
503       if ( x != 0 )
504         sensitive = TRUE;
505
506       for (i = 1 ; i < N_EXTENSIONS ; ++i)
507         {
508           if ( g_str_has_suffix (fn, ft[i].ext))
509             {
510               sensitive = TRUE;
511               break;
512             }
513         }
514     }
515
516   g_free (fn);
517
518   gtk_dialog_set_response_sensitive (GTK_DIALOG (chooser), GTK_RESPONSE_ACCEPT, sensitive);
519 }
520
521
522 static void
523 on_file_chooser_change (GObject *w, GParamSpec *pspec, gpointer data)
524 {
525
526   GtkFileChooser *chooser = data;
527   const gchar *name = g_param_spec_get_name (pspec);
528
529   if ( ! gtk_widget_get_realized (GTK_WIDGET (chooser)))
530     return;
531
532   /* Ignore this one.  It causes recursion. */
533   if ( 0 == strcmp ("tooltip-text", name))
534     return;
535
536   on_combo_change (chooser);
537 }
538
539
540 /* Recursively descend all the children of W, connecting
541    to their "notify" signal */
542 static void
543 iterate_widgets (GtkWidget *w, gpointer data)
544 {
545   if ( GTK_IS_CONTAINER (w))
546     gtk_container_forall (GTK_CONTAINER (w), iterate_widgets, data);
547   else
548     g_signal_connect (w, "notify",  G_CALLBACK (on_file_chooser_change), data);
549 }
550
551
552
553 static GtkListStore *
554 create_file_type_list (void)
555 {
556   int i;
557   GtkTreeIter iter;
558   GtkListStore *list = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_STRING);
559   
560   for (i = 0 ; i < n_FT ; ++i)
561     {
562       gtk_list_store_append (list, &iter);
563       gtk_list_store_set (list, &iter,
564                           0,  gettext (ft[i].label),
565                           1,  ft[i].ext,
566                           -1);
567     }
568   
569   return list;
570 }
571
572 static void
573 psppire_output_window_export (PsppireOutputWindow *window)
574 {
575   gint response;
576   GtkWidget *combo;
577   GtkListStore *list;
578
579   GtkFileChooser *chooser;
580   
581   GtkWidget *dialog = gtk_file_chooser_dialog_new (_("Export Output"),
582                                         GTK_WINDOW (window),
583                                         GTK_FILE_CHOOSER_ACTION_SAVE,
584                                         GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
585                                         GTK_STOCK_SAVE,   GTK_RESPONSE_ACCEPT,
586                                         NULL);
587
588   g_object_set (dialog, "local-only", FALSE, NULL);
589
590   chooser = GTK_FILE_CHOOSER (dialog);
591
592   list = create_file_type_list ();
593
594   combo = gtk_combo_box_new_with_model (GTK_TREE_MODEL (list));
595
596
597   {
598     /* Create text cell renderer */
599     GtkCellRenderer *cell = gtk_cell_renderer_text_new();
600     gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), cell, FALSE );
601
602     gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (combo), cell,  "text", 0);
603   }
604
605   g_signal_connect_swapped (combo, "changed", G_CALLBACK (on_combo_change), chooser);
606
607   gtk_combo_box_set_active (GTK_COMBO_BOX (combo), 0);
608
609   gtk_file_chooser_set_extra_widget (chooser, combo);
610
611   /* This kludge is necessary because there is no signal to tell us
612      when the candidate filename of a GtkFileChooser has changed */
613   gtk_container_forall (GTK_CONTAINER (dialog), iterate_widgets, dialog);
614
615
616   gtk_file_chooser_set_do_overwrite_confirmation (chooser, TRUE);
617
618   response = gtk_dialog_run (GTK_DIALOG (dialog));
619
620   if ( response == GTK_RESPONSE_ACCEPT )
621     {
622       int file_type = gtk_combo_box_get_active (GTK_COMBO_BOX (combo));
623       char *filename = gtk_file_chooser_get_filename (chooser);
624       struct string_map options;
625
626       g_return_if_fail (filename);
627
628       if (file_type == FT_AUTO)
629         {
630           gint i;
631           for (i = 1 ; i < N_EXTENSIONS ; ++i)
632             {
633               if ( g_str_has_suffix (filename, ft[i].ext))
634                 {
635                   file_type = i;
636                   break;
637                 }
638             }
639         }
640
641       
642       string_map_init (&options);
643       string_map_insert (&options, "output-file", filename);
644
645       switch (file_type)
646         {
647         case FT_PDF:
648           export_output (window, &options, "pdf");
649           break;
650         case FT_HTML:
651           export_output (window, &options, "html");
652           break;
653         case FT_ODT:
654           export_output (window, &options, "odt");
655           break;
656         case FT_PS:
657           export_output (window, &options, "ps");
658           break;
659         case FT_CSV:
660           export_output (window, &options, "csv");
661           break;
662
663         case FT_TXT:
664           string_map_insert (&options, "headers", "false");
665           string_map_insert (&options, "paginate", "false");
666           string_map_insert (&options, "squeeze", "true");
667           string_map_insert (&options, "emphasis", "none");
668           string_map_insert (&options, "charts", "none");
669           string_map_insert (&options, "top-margin", "0");
670           string_map_insert (&options, "bottom-margin", "0");
671           export_output (window, &options, "txt");
672           break;
673         default:
674           g_assert_not_reached ();
675         }
676
677       string_map_destroy (&options);
678
679       free (filename);
680     }
681
682   gtk_widget_destroy (dialog);
683 }
684
685
686 enum {
687   SELECT_FMT_NULL,
688   SELECT_FMT_TEXT,
689   SELECT_FMT_UTF8,
690   SELECT_FMT_HTML,
691   SELECT_FMT_ODT
692 };
693
694 static void
695 clipboard_get_cb (GtkClipboard     *clipboard,
696                   GtkSelectionData *selection_data,
697                   guint             info,
698                   gpointer          data)
699 {
700   PsppireOutputWindow *window = data;
701
702   gsize length;
703   gchar *text = NULL;
704   struct output_driver *driver = NULL;
705   char dirname[PATH_MAX], *filename;
706   struct string_map options;
707
708   GtkTreeSelection *sel = gtk_tree_view_get_selection (window->overview);
709   GtkTreeModel *model = gtk_tree_view_get_model (window->overview);
710
711   GList *rows = gtk_tree_selection_get_selected_rows (sel, &model);
712   GList *n = rows;
713
714   if ( n == NULL)
715     return;
716
717   if (path_search (dirname, sizeof dirname, NULL, NULL, true)
718       || mkdtemp (dirname) == NULL)
719     {
720       error (0, errno, _("failed to create temporary directory"));
721       return;
722     }
723   filename = xasprintf ("%s/clip.tmp", dirname);
724
725   string_map_init (&options);
726   string_map_insert (&options, "output-file", filename);
727
728   switch (info)
729     {
730     case SELECT_FMT_UTF8:
731       string_map_insert (&options, "box", "unicode");
732       /* fall-through */
733
734     case SELECT_FMT_TEXT:
735       string_map_insert (&options, "format", "txt");
736       break;
737
738     case SELECT_FMT_HTML:
739       string_map_insert (&options, "format", "html");
740       string_map_insert (&options, "borders", "false");
741       string_map_insert (&options, "css", "false");
742       break;
743
744     case SELECT_FMT_ODT:
745       string_map_insert (&options, "format", "odt");
746       break;
747
748     default:
749       g_warning ("unsupported clip target\n");
750       goto finish;
751       break;
752     }
753
754   driver = output_driver_create (&options);
755   if (driver == NULL)
756     goto finish;
757
758   while (n)
759     {
760       GtkTreePath *path = n->data ; 
761       GtkTreeIter iter;
762       struct output_item *item ;
763
764       gtk_tree_model_get_iter (model, &iter, path);
765       gtk_tree_model_get (model, &iter, COL_ADDR, &item, -1);
766
767       driver->class->submit (driver, item);
768
769       n = n->next;
770     }
771
772   if ( driver->class->flush)
773     driver->class->flush (driver);
774
775
776   /* Some drivers (eg: the odt one) don't write anything until they
777      are closed */
778   output_driver_destroy (driver);
779   driver = NULL;
780
781   if ( g_file_get_contents (filename, &text, &length, NULL) )
782     {
783       gtk_selection_data_set (selection_data, selection_data->target,
784                               8,
785                               (const guchar *) text, length);
786     }
787
788  finish:
789
790   if (driver != NULL)
791     output_driver_destroy (driver);
792
793   g_free (text);
794
795   unlink (filename);
796   free (filename);
797   rmdir (dirname);
798
799   g_list_free (rows);
800 }
801
802 static void
803 clipboard_clear_cb (GtkClipboard *clipboard,
804                     gpointer data)
805 {
806 }
807
808 static const GtkTargetEntry targets[] = {
809
810   { "STRING",        0, SELECT_FMT_TEXT },
811   { "TEXT",          0, SELECT_FMT_TEXT },
812   { "COMPOUND_TEXT", 0, SELECT_FMT_TEXT },
813   { "text/plain",    0, SELECT_FMT_TEXT },
814
815   { "UTF8_STRING",   0, SELECT_FMT_UTF8 },
816   { "text/plain;charset=utf-8", 0, SELECT_FMT_UTF8 },
817
818   { "text/html",     0, SELECT_FMT_HTML },
819
820   { "application/vnd.oasis.opendocument.text", 0, SELECT_FMT_ODT }
821 };
822
823 static void
824 on_copy (PsppireOutputWindow *window)
825 {
826   {
827     GtkClipboard *clipboard =
828       gtk_widget_get_clipboard (GTK_WIDGET (window),
829                                 GDK_SELECTION_CLIPBOARD);
830
831     if (!gtk_clipboard_set_with_data (clipboard, targets,
832                                        G_N_ELEMENTS (targets),
833                                        clipboard_get_cb, clipboard_clear_cb,
834                                       window))
835
836       clipboard_clear_cb (clipboard, window);
837   }
838 }
839
840 static void
841 on_selection_change (GtkTreeSelection *sel, GtkAction *copy_action)
842 {
843   /* The Copy action is available only if there is something selected */
844   gtk_action_set_sensitive (copy_action, gtk_tree_selection_count_selected_rows (sel) > 0);
845 }
846
847 static void
848 on_select_all (PsppireOutputWindow *window)
849 {
850   GtkTreeSelection *sel = gtk_tree_view_get_selection (window->overview);
851   gtk_tree_view_expand_all (window->overview);
852   gtk_tree_selection_select_all (sel);
853 }
854
855
856 static void
857 psppire_output_window_init (PsppireOutputWindow *window)
858 {
859   GtkTreeViewColumn *column;
860   GtkCellRenderer *renderer;
861   GtkBuilder *xml;
862   GtkAction *copy_action;
863   GtkAction *select_all_action;
864   GtkTreeSelection *sel;
865
866   xml = builder_new ("output-viewer.ui");
867
868   copy_action = get_action_assert (xml, "edit_copy");
869   select_all_action = get_action_assert (xml, "edit_select-all");
870
871   gtk_action_set_sensitive (copy_action, FALSE);
872
873   g_signal_connect_swapped (copy_action, "activate", G_CALLBACK (on_copy), window);
874
875   g_signal_connect_swapped (select_all_action, "activate", G_CALLBACK (on_select_all), window);
876
877   gtk_widget_reparent (get_widget_assert (xml, "vbox1"), GTK_WIDGET (window));
878
879   window->output = GTK_LAYOUT (get_widget_assert (xml, "output"));
880   window->y = 0;
881
882   window->overview = GTK_TREE_VIEW (get_widget_assert (xml, "overview"));
883
884   sel = gtk_tree_view_get_selection (window->overview);
885
886   gtk_tree_selection_set_mode (sel, GTK_SELECTION_MULTIPLE);
887
888   g_signal_connect (sel, "changed", G_CALLBACK (on_selection_change), copy_action);
889
890   gtk_tree_view_set_model (window->overview,
891                            GTK_TREE_MODEL (gtk_tree_store_new (
892                                              N_COLS,
893                                              G_TYPE_STRING,  /* COL_TITLE */
894                                              G_TYPE_POINTER, /* COL_ADDR */
895                                              G_TYPE_LONG))); /* COL_Y */
896
897   window->in_command = false;
898
899   window->items = NULL;
900   window->n_items = window->allocated_items = 0;
901
902   column = gtk_tree_view_column_new ();
903   gtk_tree_view_append_column (GTK_TREE_VIEW (window->overview), column);
904   renderer = gtk_cell_renderer_text_new ();
905   gtk_tree_view_column_pack_start (column, renderer, TRUE);
906   gtk_tree_view_column_add_attribute (column, renderer, "text", COL_TITLE);
907
908   g_signal_connect (GTK_TREE_VIEW (window->overview),
909                     "row-activated", G_CALLBACK (on_row_activate), window);
910
911   gtk_widget_modify_bg (GTK_WIDGET (window->output), GTK_STATE_NORMAL,
912                         &gtk_widget_get_style (GTK_WIDGET (window->output))->base[GTK_STATE_NORMAL]);
913
914   connect_help (xml);
915
916   g_signal_connect (window,
917                     "focus-in-event",
918                     G_CALLBACK (cancel_urgency),
919                     NULL);
920
921   g_signal_connect (get_action_assert (xml,"windows_minimise-all"),
922                     "activate",
923                     G_CALLBACK (psppire_window_minimise_all),
924                     NULL);
925
926   {
927     GtkUIManager *uim = GTK_UI_MANAGER (get_object_assert (xml, "uimanager1", GTK_TYPE_UI_MANAGER));
928     merge_help_menu (uim);
929
930     PSPPIRE_WINDOW (window)->menu =
931       GTK_MENU_SHELL (gtk_ui_manager_get_widget (uim,"/ui/menubar/windows_menuitem/windows_minimise-all")->parent);
932   }
933
934   g_signal_connect_swapped (get_action_assert (xml, "file_export"), "activate",
935                             G_CALLBACK (psppire_output_window_export), window);
936
937
938   g_signal_connect_swapped (get_action_assert (xml, "file_print"), "activate",
939                             G_CALLBACK (psppire_output_window_print), window);
940
941   g_object_unref (xml);
942
943   g_signal_connect (window, "delete-event",
944                     G_CALLBACK (on_delete), window);
945 }
946
947
948 GtkWidget*
949 psppire_output_window_new (void)
950 {
951   return GTK_WIDGET (g_object_new (psppire_output_window_get_type (),
952                                    /* TRANSLATORS: This will form a filename.  Please avoid whitespace. */
953                                    "filename", _("Output"),
954                                    "description", _("Output Viewer"),
955                                    NULL));
956 }
957
958
959 \f
960 static void
961 create_xr_print_driver (GtkPrintContext *context, PsppireOutputWindow *window)
962 {
963   struct string_map options;
964   GtkPageSetup *page_setup;
965   double width, height;
966   double left_margin;
967   double right_margin;
968   double top_margin;
969   double bottom_margin;
970
971   page_setup = gtk_print_context_get_page_setup (context);
972   width = gtk_page_setup_get_paper_width (page_setup, GTK_UNIT_MM);
973   height = gtk_page_setup_get_paper_height (page_setup, GTK_UNIT_MM);
974   left_margin = gtk_page_setup_get_left_margin (page_setup, GTK_UNIT_MM);
975   right_margin = gtk_page_setup_get_right_margin (page_setup, GTK_UNIT_MM);
976   top_margin = gtk_page_setup_get_top_margin (page_setup, GTK_UNIT_MM);
977   bottom_margin = gtk_page_setup_get_bottom_margin (page_setup, GTK_UNIT_MM);
978
979   string_map_init (&options);
980   string_map_insert_nocopy (&options, xstrdup ("paper-size"),
981                             xasprintf("%.2fx%.2fmm", width, height));
982   string_map_insert_nocopy (&options, xstrdup ("left-margin"),
983                             xasprintf ("%.2fmm", left_margin));
984   string_map_insert_nocopy (&options, xstrdup ("right-margin"),
985                             xasprintf ("%.2fmm", right_margin));
986   string_map_insert_nocopy (&options, xstrdup ("top-margin"),
987                             xasprintf ("%.2fmm", top_margin));
988   string_map_insert_nocopy (&options, xstrdup ("bottom-margin"),
989                             xasprintf ("%.2fmm", bottom_margin));
990
991   window->print_xrd =
992     xr_driver_create (gtk_print_context_get_cairo_context (context), &options);
993
994   string_map_destroy (&options);
995 }
996
997 static gboolean
998 paginate (GtkPrintOperation *operation,
999           GtkPrintContext   *context,
1000           PsppireOutputWindow *window)
1001 {
1002   if ( window->print_item < window->n_items )
1003     {
1004       xr_driver_output_item (window->print_xrd, window->items[window->print_item++]);
1005       while (xr_driver_need_new_page (window->print_xrd))
1006         {
1007           xr_driver_next_page (window->print_xrd, NULL);
1008           window->print_n_pages ++;
1009         }
1010       return FALSE;
1011     }
1012   else
1013     {
1014       gtk_print_operation_set_n_pages (operation, window->print_n_pages);
1015       window->print_item = 0;
1016       create_xr_print_driver (context, window);
1017       return TRUE;
1018     }
1019 }
1020
1021 static void
1022 begin_print (GtkPrintOperation *operation,
1023              GtkPrintContext   *context,
1024              PsppireOutputWindow *window)
1025 {
1026   create_xr_print_driver (context, window);
1027
1028   window->print_item = 0;
1029   window->print_n_pages = 1;
1030 }
1031
1032 static void
1033 end_print (GtkPrintOperation *operation,
1034            GtkPrintContext   *context,
1035            PsppireOutputWindow *window)
1036 {
1037   xr_driver_destroy (window->print_xrd);
1038 }
1039
1040
1041 static void
1042 draw_page (GtkPrintOperation *operation,
1043            GtkPrintContext   *context,
1044            gint               page_number,
1045            PsppireOutputWindow *window)
1046 {
1047   xr_driver_next_page (window->print_xrd, gtk_print_context_get_cairo_context (context));
1048   while (!xr_driver_need_new_page (window->print_xrd)
1049          && window->print_item < window->n_items)
1050     xr_driver_output_item (window->print_xrd, window->items [window->print_item++]);
1051 }
1052
1053
1054 static void
1055 psppire_output_window_print (PsppireOutputWindow *window)
1056 {
1057   GtkPrintOperationResult res;
1058
1059   GtkPrintOperation *print = gtk_print_operation_new ();
1060
1061   if (window->print_settings != NULL) 
1062     gtk_print_operation_set_print_settings (print, window->print_settings);
1063
1064   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), window);
1065   g_signal_connect (print, "end_print", G_CALLBACK (end_print),     window);
1066   g_signal_connect (print, "paginate", G_CALLBACK (paginate),       window);
1067   g_signal_connect (print, "draw_page", G_CALLBACK (draw_page),     window);
1068
1069   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1070                                  GTK_WINDOW (window), NULL);
1071
1072   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1073     {
1074       if (window->print_settings != NULL)
1075         g_object_unref (window->print_settings);
1076       window->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1077       
1078     }
1079
1080   g_object_unref (print);
1081 }