66838dd307172943d0a59fd26097013192d8e6c4
[pspp] / src / ui / gui / psppire-syntax-window.c
1 /* PSPPIRE - a graphical user interface for PSPP.
2    Copyright (C) 2008, 2009, 2010, 2011, 2012, 2014  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 <gtk/gtk.h>
20 #include <stdlib.h>
21
22 #include <gtksourceview/gtksourcebuffer.h>
23 #include <gtksourceview/gtksourcelanguage.h>
24 #include <gtksourceview/gtksourcelanguagemanager.h>
25 #include <gtksourceview/gtksourceprintcompositor.h>
26
27 #include "language/lexer/lexer.h"
28 #include "libpspp/encoding-guesser.h"
29 #include "libpspp/i18n.h"
30 #include "libpspp/message.h"
31 #include "ui/gui/executor.h"
32 #include "ui/gui/help-menu.h"
33 #include "ui/gui/helper.h"
34 #include "ui/gui/builder-wrapper.h"
35 #include "ui/gui/psppire-data-window.h"
36 #include "ui/gui/psppire-encoding-selector.h"
37 #include "ui/gui/psppire-lex-reader.h"
38 #include "ui/gui/psppire-syntax-window.h"
39 #include "ui/gui/psppire-window-register.h"
40 #include "ui/gui/psppire.h"
41
42 #include "gl/localcharset.h"
43 #include "gl/xalloc.h"
44 #include "gl/xvasprintf.h"
45
46 #include <gettext.h>
47 #define _(msgid) gettext (msgid)
48 #define N_(msgid) msgid
49
50 static void psppire_syntax_window_base_finalize (PsppireSyntaxWindowClass *, gpointer);
51 static void psppire_syntax_window_base_init     (PsppireSyntaxWindowClass *class);
52 static void psppire_syntax_window_class_init    (PsppireSyntaxWindowClass *class);
53 static void psppire_syntax_window_init          (PsppireSyntaxWindow      *syntax_editor);
54
55
56 static void psppire_syntax_window_iface_init (PsppireWindowIface *iface);
57
58
59 /* Properties */
60 enum
61 {
62   PROP_0,
63   PROP_ENCODING
64 };
65
66 static void
67 psppire_syntax_window_set_property (GObject         *object,
68                                     guint            prop_id,
69                                     const GValue    *value,
70                                     GParamSpec      *pspec)
71 {
72   PsppireSyntaxWindow *window = PSPPIRE_SYNTAX_WINDOW (object);
73
74   switch (prop_id)
75     {
76     case PROP_ENCODING:
77       g_free (window->encoding);
78       window->encoding = g_value_dup_string (value);
79       break;
80     default:
81       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
82       break;
83     };
84 }
85
86
87 static void
88 psppire_syntax_window_get_property (GObject         *object,
89                                     guint            prop_id,
90                                     GValue          *value,
91                                     GParamSpec      *pspec)
92 {
93   PsppireSyntaxWindow *window = PSPPIRE_SYNTAX_WINDOW (object);
94
95   switch (prop_id)
96     {
97     case PROP_ENCODING:
98       g_value_set_string (value, window->encoding);
99       break;
100     default:
101       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
102       break;
103     };
104 }
105
106 GType
107 psppire_syntax_window_get_type (void)
108 {
109   static GType psppire_syntax_window_type = 0;
110
111   if (!psppire_syntax_window_type)
112     {
113       static const GTypeInfo psppire_syntax_window_info =
114       {
115         sizeof (PsppireSyntaxWindowClass),
116         (GBaseInitFunc) psppire_syntax_window_base_init,
117         (GBaseFinalizeFunc) psppire_syntax_window_base_finalize,
118         (GClassInitFunc)psppire_syntax_window_class_init,
119         (GClassFinalizeFunc) NULL,
120         NULL,
121         sizeof (PsppireSyntaxWindow),
122         0,
123         (GInstanceInitFunc) psppire_syntax_window_init,
124       };
125
126       static const GInterfaceInfo window_interface_info =
127         {
128           (GInterfaceInitFunc) psppire_syntax_window_iface_init,
129           NULL,
130           NULL
131         };
132
133       psppire_syntax_window_type =
134         g_type_register_static (PSPPIRE_TYPE_WINDOW, "PsppireSyntaxWindow",
135                                 &psppire_syntax_window_info, 0);
136
137       g_type_add_interface_static (psppire_syntax_window_type,
138                                    PSPPIRE_TYPE_WINDOW_MODEL,
139                                    &window_interface_info);
140     }
141
142   return psppire_syntax_window_type;
143 }
144
145 static GObjectClass *parent_class ;
146
147 static void
148 psppire_syntax_window_finalize (GObject *object)
149 {
150   if (G_OBJECT_CLASS (parent_class)->finalize)
151     (*G_OBJECT_CLASS (parent_class)->finalize) (object);
152 }
153
154
155 static void
156 psppire_syntax_window_dispose (GObject *obj)
157 {
158   PsppireSyntaxWindow *sw = (PsppireSyntaxWindow *)obj;
159
160   GtkClipboard *clip_selection;
161   GtkClipboard *clip_primary;
162
163   if (sw->dispose_has_run)
164     return;
165
166   g_free (sw->encoding);
167   sw->encoding = NULL;
168
169   clip_selection = gtk_widget_get_clipboard (GTK_WIDGET (sw), GDK_SELECTION_CLIPBOARD);
170   clip_primary =   gtk_widget_get_clipboard (GTK_WIDGET (sw), GDK_SELECTION_PRIMARY);
171
172   g_signal_handler_disconnect (clip_primary, sw->sel_handler);
173
174   g_signal_handler_disconnect (clip_selection, sw->ps_handler);
175
176   /* Make sure dispose does not run twice. */
177   sw->dispose_has_run = TRUE;
178
179   /* Chain up to the parent class */
180   G_OBJECT_CLASS (parent_class)->dispose (obj);
181 }
182
183
184
185 static void
186 psppire_syntax_window_class_init (PsppireSyntaxWindowClass *class)
187 {
188   GParamSpec *encoding_spec;
189   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
190
191   GtkSourceLanguageManager *lm = gtk_source_language_manager_get_default ();
192
193   const gchar * const *existing_paths =  gtk_source_language_manager_get_search_path (lm);
194   gchar **new_paths = g_strdupv ((gchar **)existing_paths);
195   int n = g_strv_length ((gchar **) existing_paths);
196
197   new_paths = g_realloc (new_paths, (n + 2) * sizeof (*new_paths));
198   new_paths[n] = g_strdup (relocate (PKGDATADIR));
199   new_paths[n+1] = NULL;
200
201   lm = gtk_source_language_manager_new ();
202   gtk_source_language_manager_set_search_path (lm, new_paths);
203
204   class->lan = gtk_source_language_manager_get_language (lm, "pspp");
205
206   if (class->lan == NULL)
207     g_warning ("pspp.lang file not found.  Syntax highlighting will not be available.");
208
209   parent_class = g_type_class_peek_parent (class);
210
211   g_strfreev (new_paths);
212
213   encoding_spec =
214     null_if_empty_param ("encoding",
215                          "Character encoding",
216                          "IANA character encoding in this syntax file",
217                          NULL,
218                          G_PARAM_CONSTRUCT | G_PARAM_READWRITE);
219
220   parent_class = g_type_class_peek_parent (class);
221
222   gobject_class->set_property = psppire_syntax_window_set_property;
223   gobject_class->get_property = psppire_syntax_window_get_property;
224   gobject_class->dispose = psppire_syntax_window_dispose;
225
226   g_object_class_install_property (gobject_class,
227                                    PROP_ENCODING,
228                                    encoding_spec);
229 }
230
231
232 static void
233 psppire_syntax_window_base_init (PsppireSyntaxWindowClass *class)
234 {
235   GObjectClass *object_class = G_OBJECT_CLASS (class);
236   object_class->finalize = psppire_syntax_window_finalize;
237 }
238
239
240
241 static void
242 psppire_syntax_window_base_finalize (PsppireSyntaxWindowClass *class,
243                                      gpointer class_data)
244 {
245 }
246
247
248 static void
249 editor_execute_syntax (const PsppireSyntaxWindow *sw, GtkTextIter start,
250                        GtkTextIter stop)
251 {
252   PsppireWindow *win = PSPPIRE_WINDOW (sw);
253   struct lex_reader *reader = lex_reader_for_gtk_text_buffer (GTK_TEXT_BUFFER (sw->buffer), start, stop);
254
255   lex_reader_set_file_name (reader, psppire_window_get_filename (win));
256
257   execute_syntax (psppire_default_data_window (), reader);
258 }
259 \f
260 /* Delete the currently selected text */
261 static void
262 on_edit_delete (PsppireSyntaxWindow *sw)
263 {
264   GtkTextIter begin, end;
265   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (sw->buffer);
266   
267   if ( gtk_text_buffer_get_selection_bounds (buffer, &begin, &end) )
268     gtk_text_buffer_delete (buffer, &begin, &end);
269 }
270
271
272 /* The syntax editor's clipboard deals only with text */
273 enum {
274   SELECT_FMT_NULL,
275   SELECT_FMT_TEXT,
276 };
277
278
279 static void
280 selection_changed (PsppireSyntaxWindow *sw)
281 {
282   gboolean sel = gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (sw->buffer));
283
284   gtk_action_set_sensitive (sw->edit_copy, sel);
285   gtk_action_set_sensitive (sw->edit_cut, sel);
286   gtk_action_set_sensitive (sw->edit_delete, sel);
287 }
288
289 /* The callback which runs when something request clipboard data */
290 static void
291 clipboard_get_cb (GtkClipboard     *clipboard,
292                   GtkSelectionData *selection_data,
293                   guint             info,
294                   gpointer          data)
295 {
296   PsppireSyntaxWindow *sw = data;
297   g_assert (info == SELECT_FMT_TEXT);
298
299   gtk_selection_data_set (selection_data, gtk_selection_data_get_target (selection_data),
300                           8,
301                           (const guchar *) sw->cliptext, strlen (sw->cliptext));
302
303 }
304
305 static void
306 clipboard_clear_cb (GtkClipboard *clipboard,
307                     gpointer data)
308 {
309   PsppireSyntaxWindow *sw = data;
310   g_free (sw->cliptext);
311   sw->cliptext = NULL;
312 }
313
314
315 static const GtkTargetEntry targets[] = {
316   { "UTF8_STRING",   0, SELECT_FMT_TEXT },
317   { "STRING",        0, SELECT_FMT_TEXT },
318   { "TEXT",          0, SELECT_FMT_TEXT },
319   { "COMPOUND_TEXT", 0, SELECT_FMT_TEXT },
320   { "text/plain;charset=utf-8", 0, SELECT_FMT_TEXT },
321   { "text/plain",    0, SELECT_FMT_TEXT },
322 };
323
324
325 /*
326   Store a clip containing the currently selected text.
327   Returns true iff something was set.
328   As a side effect, begin and end will be set to indicate
329   the limits of the selected text.
330 */
331 static gboolean
332 set_clip (PsppireSyntaxWindow *sw, GtkTextIter *begin, GtkTextIter *end)
333 {
334   GtkClipboard *clipboard ;
335   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (sw->buffer);
336
337   if ( ! gtk_text_buffer_get_selection_bounds (buffer, begin, end) )
338     return FALSE;
339
340   g_free (sw->cliptext);
341   sw->cliptext = gtk_text_buffer_get_text  (buffer, begin, end, FALSE);
342
343   clipboard =
344     gtk_widget_get_clipboard (GTK_WIDGET (sw), GDK_SELECTION_CLIPBOARD);
345
346   if (!gtk_clipboard_set_with_owner (clipboard, targets,
347                                      G_N_ELEMENTS (targets),
348                                      clipboard_get_cb, clipboard_clear_cb,
349                                      G_OBJECT (sw)))
350     clipboard_clear_cb (clipboard, sw);
351
352   return TRUE;
353 }
354
355 static void
356 on_edit_cut (PsppireSyntaxWindow *sw)
357 {
358   GtkTextIter begin, end;
359   
360   if ( set_clip (sw, &begin, &end))
361     gtk_text_buffer_delete (GTK_TEXT_BUFFER (sw->buffer), &begin, &end);
362 }
363
364 static void
365 on_edit_copy (PsppireSyntaxWindow *sw)
366 {
367   GtkTextIter begin, end;
368
369   set_clip (sw, &begin, &end);
370 }
371
372 static void
373 on_edit_paste (PsppireSyntaxWindow *sw)
374 {
375   GdkDisplay *display = gtk_widget_get_display (GTK_WIDGET (sw));
376   GtkClipboard *clipboard =
377     gtk_clipboard_get_for_display (display, GDK_SELECTION_CLIPBOARD);
378
379   gtk_text_buffer_paste_clipboard (GTK_TEXT_BUFFER (sw->buffer), clipboard, NULL, TRUE);
380 }
381
382
383 /* Check to see if CLIP holds a target which we know how to paste,
384    and set the sensitivity of the Paste action accordingly.
385  */
386 static void
387 set_paste_sensitivity (GtkClipboard *clip, GdkEventOwnerChange *event, gpointer data)
388 {
389   gint i;
390   gboolean compatible_target = FALSE;
391   PsppireSyntaxWindow *sw = PSPPIRE_SYNTAX_WINDOW (data);
392
393   for (i = 0 ; i < sizeof (targets) / sizeof (targets[0]) ; ++i)
394     {
395       GdkAtom atom = gdk_atom_intern (targets[i].target, TRUE);
396       if ( gtk_clipboard_wait_is_target_available (clip, atom))
397         {
398           compatible_target = TRUE;
399           break;
400         }
401     }
402
403   gtk_action_set_sensitive (sw->edit_paste, compatible_target);
404 }
405
406
407 \f
408
409 /* Parse and execute all the text in the buffer */
410 static void
411 on_run_all (GtkMenuItem *menuitem, gpointer user_data)
412 {
413   GtkTextIter begin, end;
414   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
415
416   gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (se->buffer), &begin, 0);
417   gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (se->buffer), &end, -1);
418
419   editor_execute_syntax (se, begin, end);
420 }
421
422 /* Parse and execute the currently selected text */
423 static void
424 on_run_selection (GtkMenuItem *menuitem, gpointer user_data)
425 {
426   GtkTextIter begin, end;
427   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
428
429   if ( gtk_text_buffer_get_selection_bounds (GTK_TEXT_BUFFER (se->buffer), &begin, &end) )
430     editor_execute_syntax (se, begin, end);
431 }
432
433
434 /* Parse and execute the from the current line, to the end of the
435    buffer */
436 static void
437 on_run_to_end (GtkMenuItem *menuitem, gpointer user_data)
438 {
439   GtkTextIter begin, end;
440   GtkTextIter here;
441   gint line;
442
443   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
444
445   /* Get the current line */
446   gtk_text_buffer_get_iter_at_mark (GTK_TEXT_BUFFER (se->buffer),
447                                     &here,
448                                     gtk_text_buffer_get_insert (GTK_TEXT_BUFFER (se->buffer))
449                                     );
450
451   line = gtk_text_iter_get_line (&here) ;
452
453   /* Now set begin and end to the start of this line, and end of buffer
454      respectively */
455   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &begin, line);
456   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &end, -1);
457
458   editor_execute_syntax (se, begin, end);
459 }
460
461
462
463 /* Parse and execute the current line */
464 static void
465 on_run_current_line (GtkMenuItem *menuitem, gpointer user_data)
466 {
467   GtkTextIter begin, end;
468   GtkTextIter here;
469   gint line;
470
471   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
472
473   /* Get the current line */
474   gtk_text_buffer_get_iter_at_mark (GTK_TEXT_BUFFER (se->buffer),
475                                     &here,
476                                     gtk_text_buffer_get_insert (GTK_TEXT_BUFFER (se->buffer))
477                                     );
478
479   line = gtk_text_iter_get_line (&here) ;
480
481   /* Now set begin and end to the start of this line, and start of
482      following line respectively */
483   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &begin, line);
484   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &end, line + 1);
485
486   editor_execute_syntax (se, begin, end);
487 }
488
489
490
491 /* Append ".sps" to FILENAME if necessary.
492    The returned result must be freed when no longer required.
493  */
494 static gchar *
495 append_suffix (const gchar *filename)
496 {
497   if ( ! g_str_has_suffix (filename, ".sps" ) &&
498        ! g_str_has_suffix (filename, ".SPS" ) )
499     {
500       return g_strdup_printf ("%s.sps", filename);
501     }
502
503   return xstrdup (filename);
504 }
505
506 /*
507   Save BUFFER to the file called FILENAME.
508   FILENAME must be encoded in Glib filename encoding.
509   If successful, clears the buffer's modified flag.
510 */
511 static gboolean
512 save_editor_to_file (PsppireSyntaxWindow *se,
513                      const gchar *filename,
514                      GError **err)
515 {
516   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (se->buffer);
517   struct substring text_locale;
518   gboolean result ;
519   GtkTextIter start, stop;
520   gchar *text;
521
522   gchar *suffixedname;
523   g_assert (filename);
524
525   suffixedname = append_suffix (filename);
526
527   gtk_text_buffer_get_iter_at_line (buffer, &start, 0);
528   gtk_text_buffer_get_iter_at_offset (buffer, &stop, -1);
529
530   text = gtk_text_buffer_get_text (buffer, &start, &stop, FALSE);
531
532   text_locale = recode_substring_pool (se->encoding, "UTF-8", ss_cstr (text),
533                                        NULL);
534
535   result =  g_file_set_contents (suffixedname, ss_data (text_locale),
536                                  ss_length (text_locale), err);
537
538   ss_dealloc (&text_locale);
539   g_free (suffixedname);
540
541   if ( result )
542     {
543       char *fn = g_filename_display_name (filename);
544       gchar *msg = g_strdup_printf (_("Saved file `%s'"), fn);
545       g_free (fn);
546       gtk_statusbar_push (GTK_STATUSBAR (se->sb), se->text_context, msg);
547       gtk_text_buffer_set_modified (buffer, FALSE);
548       g_free (msg);
549     }
550
551   return result;
552 }
553
554
555 /* PsppireWindow 'pick_Filename' callback. */
556 static void
557 syntax_pick_filename (PsppireWindow *window)
558 {
559   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (window);
560   const char *default_encoding;
561   GtkFileFilter *filter;
562   gint response;
563
564   GtkWidget *dialog =
565     gtk_file_chooser_dialog_new (_("Save Syntax"),
566                                  GTK_WINDOW (se),
567                                  GTK_FILE_CHOOSER_ACTION_SAVE,
568                                  _("Cancel"), GTK_RESPONSE_CANCEL,
569                                  _("Save"),   GTK_RESPONSE_ACCEPT,
570                                  NULL);
571
572   g_object_set (dialog, "local-only", FALSE, NULL);
573
574   filter = gtk_file_filter_new ();
575   gtk_file_filter_set_name (filter, _("Syntax Files (*.sps) "));
576   gtk_file_filter_add_pattern (filter, "*.sps");
577   gtk_file_filter_add_pattern (filter, "*.SPS");
578   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
579
580   filter = gtk_file_filter_new ();
581   gtk_file_filter_set_name (filter, _("All Files"));
582   gtk_file_filter_add_pattern (filter, "*");
583   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
584
585   gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog),
586                                                   TRUE);
587
588   default_encoding = se->encoding != NULL ? se->encoding : locale_charset ();
589   gtk_file_chooser_set_extra_widget (
590     GTK_FILE_CHOOSER (dialog),
591     psppire_encoding_selector_new (default_encoding, false));
592
593   response = gtk_dialog_run (GTK_DIALOG (dialog));
594
595   if ( response == GTK_RESPONSE_ACCEPT )
596     {
597       gchar *encoding;
598       char *filename;
599
600       filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog) );
601       psppire_window_set_filename (window, filename);
602       free (filename);
603
604       encoding = psppire_encoding_selector_get_encoding (
605         gtk_file_chooser_get_extra_widget (GTK_FILE_CHOOSER (dialog)));
606       if (encoding != NULL)
607         {
608           g_free (se->encoding);
609           se->encoding = encoding;
610         }
611     }
612
613   gtk_widget_destroy (dialog);
614 }
615
616
617 /* PsppireWindow 'save' callback. */
618 static void
619 syntax_save (PsppireWindow *se)
620 {
621   const gchar *filename = psppire_window_get_filename (se);
622   GError *err = NULL;
623   save_editor_to_file (PSPPIRE_SYNTAX_WINDOW (se), filename, &err);
624   if ( err )
625     {
626       msg (ME, "%s", err->message);
627       g_error_free (err);
628     }
629 }
630
631
632 /* Callback for the File->Quit menuitem */
633 static gboolean
634 on_quit (GtkMenuItem *menuitem, gpointer    user_data)
635 {
636   psppire_quit ();
637
638   return FALSE;
639 }
640
641
642 static void
643 load_and_show_syntax_window (GtkWidget *se, const gchar *filename,
644                              const gchar *encoding)
645 {
646   gboolean ok;
647
648   gtk_source_buffer_begin_not_undoable_action (PSPPIRE_SYNTAX_WINDOW (se)->buffer);
649   ok = psppire_window_load (PSPPIRE_WINDOW (se), filename, encoding, NULL);
650   gtk_source_buffer_end_not_undoable_action (PSPPIRE_SYNTAX_WINDOW (se)->buffer);
651
652   if (ok )
653     gtk_widget_show (se);
654   else
655     gtk_widget_destroy (se);
656 }
657
658 void
659 create_syntax_window (void)
660 {
661   GtkWidget *w = psppire_syntax_window_new (NULL);
662   gtk_widget_show (w);
663 }
664
665 void
666 open_syntax_window (const char *file_name, const gchar *encoding)
667 {
668   GtkWidget *se = psppire_syntax_window_new (NULL);
669
670   if ( file_name)
671     load_and_show_syntax_window (se, file_name, encoding);
672 }
673
674
675
676 static void psppire_syntax_window_print (PsppireSyntaxWindow *window);
677
678 static void
679 on_modified_changed (GtkTextBuffer *buffer, PsppireWindow *window)
680 {
681   if (gtk_text_buffer_get_modified (buffer))
682     psppire_window_set_unsaved (window);
683 }
684
685 static void undo_redo_update (PsppireSyntaxWindow *window);
686 static void undo_last_edit (PsppireSyntaxWindow *window);
687 static void redo_last_edit (PsppireSyntaxWindow *window);
688
689 static void
690 on_text_changed (GtkTextBuffer *buffer, PsppireSyntaxWindow *window)
691 {
692   gtk_statusbar_pop (GTK_STATUSBAR (window->sb), window->text_context);
693   undo_redo_update (window);
694 }
695
696 static void
697 psppire_syntax_window_init (PsppireSyntaxWindow *window)
698 {
699   GtkBuilder *xml = builder_new ("syntax-editor.ui");
700   GtkWidget *box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
701
702   GtkWidget *menubar = get_widget_assert (xml, "menubar");
703   GtkWidget *sw = get_widget_assert (xml, "scrolledwindow8");
704
705   GtkWidget *text_view = get_widget_assert (xml, "syntax_text_view");
706
707   PsppireSyntaxWindowClass *class
708     = PSPPIRE_SYNTAX_WINDOW_CLASS (G_OBJECT_GET_CLASS (window));
709
710   GtkClipboard *clip_selection = gtk_widget_get_clipboard (GTK_WIDGET (window), GDK_SELECTION_CLIPBOARD);
711   GtkClipboard *clip_primary =   gtk_widget_get_clipboard (GTK_WIDGET (window), GDK_SELECTION_PRIMARY);
712
713   window->print_settings = NULL;
714   window->undo_menuitem = get_action_assert (xml, "edit_undo");
715   window->redo_menuitem = get_action_assert (xml, "edit_redo");
716
717   if (class->lan)
718     window->buffer = gtk_source_buffer_new_with_language (class->lan);
719   else
720     window->buffer = gtk_source_buffer_new (NULL);
721
722   gtk_text_view_set_buffer (GTK_TEXT_VIEW (text_view), GTK_TEXT_BUFFER (window->buffer));
723
724   g_object_set (window->buffer,
725                 "highlight-matching-brackets", TRUE,
726                 NULL);
727
728   g_object_set (text_view,
729                 "show-line-numbers", TRUE,
730                 "show-line-marks", TRUE,
731                 "auto-indent", TRUE,
732                 "indent-width", 4,
733                 "highlight-current-line", TRUE,
734                 NULL);
735
736   window->encoding = NULL;
737
738   window->cliptext = NULL;
739   window->dispose_has_run = FALSE;
740
741   window->edit_delete = get_action_assert (xml, "edit_delete");
742   window->edit_copy = get_action_assert (xml, "edit_copy");
743   window->edit_cut = get_action_assert (xml, "edit_cut");
744   window->edit_paste = get_action_assert (xml, "edit_paste");
745
746   window->buffer = GTK_SOURCE_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW (text_view)));
747
748   window->sb = get_widget_assert (xml, "statusbar2");
749   window->text_context = gtk_statusbar_get_context_id (GTK_STATUSBAR (window->sb), "Text Context");
750
751   g_signal_connect (window->buffer, "changed", 
752                     G_CALLBACK (on_text_changed), window);
753
754   g_signal_connect (window->buffer, "modified-changed", 
755                     G_CALLBACK (on_modified_changed), window);
756
757   g_signal_connect_swapped (get_action_assert (xml, "file_print"), "activate",
758                             G_CALLBACK (psppire_syntax_window_print), window);
759
760
761   g_signal_connect_swapped (window->undo_menuitem,
762                             "activate",
763                             G_CALLBACK (undo_last_edit),
764                             window);
765
766   g_signal_connect_swapped (window->redo_menuitem,
767                             "activate",
768                             G_CALLBACK (redo_last_edit),
769                             window);
770
771   undo_redo_update (window);
772
773   window->sel_handler = g_signal_connect_swapped (clip_primary, "owner-change", 
774                                                    G_CALLBACK (selection_changed), window);
775
776   window->ps_handler = g_signal_connect (clip_selection, "owner-change", 
777                                           G_CALLBACK (set_paste_sensitivity), window);
778
779   connect_help (xml);
780
781   gtk_container_add (GTK_CONTAINER (window), box);
782
783   g_object_ref (menubar);
784
785   g_object_ref (sw);
786
787   g_object_ref (window->sb);
788
789   gtk_box_pack_start (GTK_BOX (box), menubar, FALSE, TRUE, 0);
790   gtk_box_pack_start (GTK_BOX (box), sw, TRUE, TRUE, 0);
791   gtk_box_pack_start (GTK_BOX (box), window->sb, FALSE, TRUE, 0);
792
793   gtk_widget_show_all (box);
794
795   g_signal_connect_swapped (get_action_assert (xml,"file_new_syntax"), "activate", G_CALLBACK (create_syntax_window), NULL);
796
797   g_signal_connect (get_action_assert (xml,"file_new_data"),
798                     "activate",
799                     G_CALLBACK (create_data_window),
800                     window);
801
802   g_signal_connect_swapped (get_action_assert (xml, "file_open"),
803                     "activate",
804                     G_CALLBACK (psppire_window_open),
805                     window);
806
807   g_signal_connect_swapped (get_action_assert (xml, "file_save"),
808                     "activate",
809                     G_CALLBACK (psppire_window_save),
810                     window);
811
812   g_signal_connect_swapped (get_action_assert (xml, "file_save_as"),
813                     "activate",
814                     G_CALLBACK (psppire_window_save_as),
815                     window);
816
817   g_signal_connect (get_action_assert (xml,"file_quit"),
818                     "activate",
819                     G_CALLBACK (on_quit),
820                     window);
821
822   g_signal_connect_swapped (window->edit_delete,
823                     "activate",
824                     G_CALLBACK (on_edit_delete),
825                     window);
826
827   g_signal_connect_swapped (window->edit_copy,
828                     "activate",
829                     G_CALLBACK (on_edit_copy),
830                     window);
831
832   g_signal_connect_swapped (window->edit_cut,
833                     "activate",
834                     G_CALLBACK (on_edit_cut),
835                     window);
836
837   g_signal_connect_swapped (window->edit_paste,
838                     "activate",
839                     G_CALLBACK (on_edit_paste),
840                     window);
841
842   g_signal_connect (get_action_assert (xml,"run_all"),
843                     "activate",
844                     G_CALLBACK (on_run_all),
845                     window);
846
847   g_signal_connect (get_action_assert (xml,"run_selection"),
848                     "activate",
849                     G_CALLBACK (on_run_selection),
850                     window);
851
852   g_signal_connect (get_action_assert (xml,"run_current_line"),
853                     "activate",
854                     G_CALLBACK (on_run_current_line),
855                     window);
856
857   g_signal_connect (get_action_assert (xml,"run_to_end"),
858                     "activate",
859                     G_CALLBACK (on_run_to_end),
860                     window);
861
862   g_signal_connect (get_action_assert (xml,"windows_minimise_all"),
863                     "activate",
864                     G_CALLBACK (psppire_window_minimise_all), NULL);
865
866
867   {
868     GtkUIManager *uim = GTK_UI_MANAGER (get_object_assert (xml, "uimanager1", GTK_TYPE_UI_MANAGER));
869     GtkWidget *w = gtk_ui_manager_get_widget (uim,"/ui/menubar/windows/windows_minimise_all");
870
871     gtk_menu_shell_append (GTK_MENU_SHELL (menubar),  create_help_menu (GTK_WINDOW (window)));
872
873     PSPPIRE_WINDOW (window)->menu = GTK_MENU_SHELL (gtk_widget_get_parent (w));
874   }
875
876   g_object_unref (xml);
877 }
878
879
880
881
882
883 GtkWidget*
884 psppire_syntax_window_new (const char *encoding)
885 {
886   return GTK_WIDGET (g_object_new (psppire_syntax_window_get_type (),
887                                    "description", _("Syntax Editor"),
888                                    "encoding", encoding,
889                                    NULL));
890 }
891
892 static void
893 error_dialog (GtkWindow *w, const gchar *filename,  GError *err)
894 {
895   gchar *fn = g_filename_display_basename (filename);
896
897   GtkWidget *dialog =
898     gtk_message_dialog_new (w,
899                             GTK_DIALOG_DESTROY_WITH_PARENT,
900                             GTK_MESSAGE_ERROR,
901                             GTK_BUTTONS_CLOSE,
902                             _("Cannot load syntax file `%s'"),
903                             fn);
904
905   g_free (fn);
906
907   g_object_set (dialog, "icon-name", "pspp", NULL);
908
909   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
910                                             "%s", err->message);
911
912   gtk_dialog_run (GTK_DIALOG (dialog));
913
914   gtk_widget_destroy (dialog);
915 }
916
917 /*
918   Loads the buffer from the file called FILENAME
919 */
920 gboolean
921 syntax_load (PsppireWindow *window, const gchar *filename,
922              const gchar *encoding, gpointer not_used)
923 {
924   GError *err = NULL;
925   gchar *text_locale = NULL;
926   gchar *text_utf8 = NULL;
927   gsize len_locale = -1;
928   gsize len_utf8 = -1;
929   GtkTextIter iter;
930   PsppireSyntaxWindow *sw = PSPPIRE_SYNTAX_WINDOW (window);
931   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (sw->buffer);
932
933   /* FIXME: What if it's a very big file ? */
934   if ( ! g_file_get_contents (filename, &text_locale, &len_locale, &err) )
935     {
936       error_dialog (GTK_WINDOW (window), filename, err);
937       g_clear_error (&err);
938       return FALSE;
939     }
940
941   if (!encoding || !encoding[0])
942     {
943       /* Determine the file's encoding and update sw->encoding.  (The ordering
944          is important here because encoding_guess_whole_file() often returns
945          its argument instead of a copy of it.) */
946       char *guessed_encoding;
947
948       guessed_encoding = g_strdup (encoding_guess_whole_file (sw->encoding,
949                                                               text_locale,
950                                                               len_locale));
951       g_free (sw->encoding);
952       sw->encoding = guessed_encoding;
953     }
954   else
955     {
956       g_free (sw->encoding);
957       sw->encoding = g_strdup (encoding);
958     }
959
960   text_utf8 = recode_substring_pool ("UTF-8", sw->encoding,
961                                      ss_buffer (text_locale, len_locale),
962                                      NULL).string;
963   free (text_locale);
964
965   if ( text_utf8 == NULL )
966     {
967       error_dialog (GTK_WINDOW (window), filename, err);
968       g_clear_error (&err);
969       return FALSE;
970     }
971
972   gtk_text_buffer_get_iter_at_line (buffer, &iter, 0);
973
974   gtk_text_buffer_insert (buffer, &iter, text_utf8, len_utf8);
975
976   gtk_text_buffer_set_modified (buffer, FALSE);
977
978   free (text_utf8);
979
980   add_most_recent (filename, "text/x-spss-syntax", sw->encoding);
981
982   return TRUE;
983 }
984
985 \f
986
987 static void
988 psppire_syntax_window_iface_init (PsppireWindowIface *iface)
989 {
990   iface->save = syntax_save;
991   iface->pick_filename = syntax_pick_filename;
992   iface->load = syntax_load;
993 }
994
995
996 \f
997
998 static void
999 undo_redo_update (PsppireSyntaxWindow *window)
1000 {
1001   gtk_action_set_sensitive (window->undo_menuitem,
1002                             gtk_source_buffer_can_undo (window->buffer));
1003
1004   gtk_action_set_sensitive (window->redo_menuitem,
1005                             gtk_source_buffer_can_redo (window->buffer));
1006 }
1007
1008 static void
1009 undo_last_edit (PsppireSyntaxWindow *window)
1010 {
1011   gtk_source_buffer_undo (window->buffer);
1012   undo_redo_update (window);
1013 }
1014
1015 static void
1016 redo_last_edit (PsppireSyntaxWindow *window)
1017 {
1018   gtk_source_buffer_redo (window->buffer);
1019   undo_redo_update (window);
1020 }
1021
1022
1023 \f
1024 /* Printing related stuff */
1025
1026
1027 static void
1028 begin_print (GtkPrintOperation *operation,
1029           GtkPrintContext   *context,
1030           PsppireSyntaxWindow *window)
1031 {
1032   window->compositor =
1033     gtk_source_print_compositor_new (window->buffer);
1034 }
1035
1036
1037 static void
1038 end_print (GtkPrintOperation *operation,
1039           GtkPrintContext   *context,
1040           PsppireSyntaxWindow *window)
1041 {
1042   g_object_unref (window->compositor);
1043   window->compositor = NULL;
1044 }
1045
1046
1047
1048 static gboolean
1049 paginate (GtkPrintOperation *operation,
1050           GtkPrintContext   *context,
1051           PsppireSyntaxWindow *window)
1052 {
1053   if (gtk_source_print_compositor_paginate (window->compositor, context))
1054     {
1055       gint n_pages = gtk_source_print_compositor_get_n_pages (window->compositor);
1056       gtk_print_operation_set_n_pages (operation, n_pages);
1057         
1058       return TRUE;
1059     }
1060
1061   return FALSE;
1062 }
1063
1064 static void
1065 draw_page (GtkPrintOperation *operation,
1066            GtkPrintContext   *context,
1067            gint               page_nr,
1068           PsppireSyntaxWindow *window)
1069 {
1070   gtk_source_print_compositor_draw_page (window->compositor, 
1071                                          context,
1072                                          page_nr);
1073 }
1074
1075
1076
1077 static void
1078 psppire_syntax_window_print (PsppireSyntaxWindow *window)
1079 {
1080   GtkPrintOperationResult res;
1081
1082   GtkPrintOperation *print = gtk_print_operation_new ();
1083
1084   if (window->print_settings != NULL) 
1085     gtk_print_operation_set_print_settings (print, window->print_settings);
1086
1087
1088   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), window);
1089   g_signal_connect (print, "end_print", G_CALLBACK (end_print),     window);
1090   g_signal_connect (print, "draw_page", G_CALLBACK (draw_page),     window);
1091   g_signal_connect (print, "paginate", G_CALLBACK (paginate),       window);
1092
1093   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1094                                  GTK_WINDOW (window), NULL);
1095
1096   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1097     {
1098       if (window->print_settings != NULL)
1099         g_object_unref (window->print_settings);
1100       window->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1101     }
1102
1103   g_object_unref (print);
1104 }