Remove deprecated objects GtkAction and GtkUIManager
[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, 2016  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.h"
40 #include "ui/gui/windows-menu.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   g_object_set (sw->edit_copy,    "enabled", sel, NULL);
285   g_object_set (sw->edit_cut,     "enabled", sel, NULL);
286   g_object_set (sw->edit_delete,  "enabled", sel, NULL);
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   g_object_set (sw->edit_paste, "enabled", compatible_target, NULL);
404 }
405
406
407 \f
408
409 /* Parse and execute all the text in the buffer */
410 static void
411 on_run_all (PsppireSyntaxWindow *se)
412 {
413   GtkTextIter begin, end;
414
415   gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (se->buffer), &begin, 0);
416   gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (se->buffer), &end, -1);
417
418   editor_execute_syntax (se, begin, end);
419 }
420
421 /* Parse and execute the currently selected text */
422 static void
423 on_run_selection (PsppireSyntaxWindow *se)
424 {
425   GtkTextIter begin, end;
426
427   if ( gtk_text_buffer_get_selection_bounds (GTK_TEXT_BUFFER (se->buffer), &begin, &end) )
428     editor_execute_syntax (se, begin, end);
429 }
430
431
432 /* Parse and execute the from the current line, to the end of the
433    buffer */
434 static void
435 on_run_to_end (PsppireSyntaxWindow *se)
436 {
437   GtkTextIter begin, end;
438   GtkTextIter here;
439   gint line;
440
441   /* Get the current line */
442   gtk_text_buffer_get_iter_at_mark (GTK_TEXT_BUFFER (se->buffer),
443                                     &here,
444                                     gtk_text_buffer_get_insert (GTK_TEXT_BUFFER (se->buffer))
445                                     );
446
447   line = gtk_text_iter_get_line (&here) ;
448
449   /* Now set begin and end to the start of this line, and end of buffer
450      respectively */
451   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &begin, line);
452   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &end, -1);
453
454   editor_execute_syntax (se, begin, end);
455 }
456
457
458
459 /* Parse and execute the current line */
460 static void
461 on_run_current_line (PsppireSyntaxWindow *se)
462 {
463   GtkTextIter begin, end;
464   GtkTextIter here;
465   gint line;
466
467   /* Get the current line */
468   gtk_text_buffer_get_iter_at_mark (GTK_TEXT_BUFFER (se->buffer),
469                                     &here,
470                                     gtk_text_buffer_get_insert (GTK_TEXT_BUFFER (se->buffer))
471                                     );
472
473   line = gtk_text_iter_get_line (&here) ;
474
475   /* Now set begin and end to the start of this line, and start of
476      following line respectively */
477   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &begin, line);
478   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &end, line + 1);
479
480   editor_execute_syntax (se, begin, end);
481 }
482
483
484
485 /* Append ".sps" to FILENAME if necessary.
486    The returned result must be freed when no longer required.
487  */
488 static gchar *
489 append_suffix (const gchar *filename)
490 {
491   if ( ! g_str_has_suffix (filename, ".sps" ) &&
492        ! g_str_has_suffix (filename, ".SPS" ) )
493     {
494       return g_strdup_printf ("%s.sps", filename);
495     }
496
497   return xstrdup (filename);
498 }
499
500 /*
501   Save BUFFER to the file called FILENAME.
502   FILENAME must be encoded in Glib filename encoding.
503   If successful, clears the buffer's modified flag.
504 */
505 static gboolean
506 save_editor_to_file (PsppireSyntaxWindow *se,
507                      const gchar *filename,
508                      GError **err)
509 {
510   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (se->buffer);
511   struct substring text_locale;
512   gboolean result ;
513   GtkTextIter start, stop;
514   gchar *text;
515
516   gchar *suffixedname;
517   g_assert (filename);
518
519   suffixedname = append_suffix (filename);
520
521   gtk_text_buffer_get_iter_at_line (buffer, &start, 0);
522   gtk_text_buffer_get_iter_at_offset (buffer, &stop, -1);
523
524   text = gtk_text_buffer_get_text (buffer, &start, &stop, FALSE);
525
526   text_locale = recode_substring_pool (se->encoding, "UTF-8", ss_cstr (text),
527                                        NULL);
528
529   result =  g_file_set_contents (suffixedname, ss_data (text_locale),
530                                  ss_length (text_locale), err);
531
532   ss_dealloc (&text_locale);
533   g_free (suffixedname);
534
535   if ( result )
536     {
537       char *fn = g_filename_display_name (filename);
538       gchar *msg = g_strdup_printf (_("Saved file `%s'"), fn);
539       g_free (fn);
540       gtk_statusbar_push (GTK_STATUSBAR (se->sb), se->text_context, msg);
541       gtk_text_buffer_set_modified (buffer, FALSE);
542       g_free (msg);
543     }
544
545   return result;
546 }
547
548
549 /* PsppireWindow 'pick_Filename' callback. */
550 static void
551 syntax_pick_filename (PsppireWindow *window)
552 {
553   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (window);
554   const char *default_encoding;
555   GtkFileFilter *filter;
556   gint response;
557
558   GtkWidget *dialog =
559     gtk_file_chooser_dialog_new (_("Save Syntax"),
560                                  GTK_WINDOW (se),
561                                  GTK_FILE_CHOOSER_ACTION_SAVE,
562                                  _("Cancel"), GTK_RESPONSE_CANCEL,
563                                  _("Save"),   GTK_RESPONSE_ACCEPT,
564                                  NULL);
565
566   g_object_set (dialog, "local-only", FALSE, NULL);
567
568   filter = gtk_file_filter_new ();
569   gtk_file_filter_set_name (filter, _("Syntax Files (*.sps) "));
570   gtk_file_filter_add_pattern (filter, "*.sps");
571   gtk_file_filter_add_pattern (filter, "*.SPS");
572   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
573
574   filter = gtk_file_filter_new ();
575   gtk_file_filter_set_name (filter, _("All Files"));
576   gtk_file_filter_add_pattern (filter, "*");
577   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
578
579   gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog),
580                                                   TRUE);
581
582   default_encoding = se->encoding != NULL ? se->encoding : locale_charset ();
583   gtk_file_chooser_set_extra_widget (
584     GTK_FILE_CHOOSER (dialog),
585     psppire_encoding_selector_new (default_encoding, false));
586
587   response = gtk_dialog_run (GTK_DIALOG (dialog));
588
589   if ( response == GTK_RESPONSE_ACCEPT )
590     {
591       gchar *encoding;
592       char *filename;
593
594       filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog) );
595       psppire_window_set_filename (window, filename);
596       free (filename);
597
598       encoding = psppire_encoding_selector_get_encoding (
599         gtk_file_chooser_get_extra_widget (GTK_FILE_CHOOSER (dialog)));
600       if (encoding != NULL)
601         {
602           g_free (se->encoding);
603           se->encoding = encoding;
604         }
605     }
606
607   gtk_widget_destroy (dialog);
608 }
609
610
611 /* PsppireWindow 'save' callback. */
612 static void
613 syntax_save (PsppireWindow *se)
614 {
615   const gchar *filename = psppire_window_get_filename (se);
616   GError *err = NULL;
617   save_editor_to_file (PSPPIRE_SYNTAX_WINDOW (se), filename, &err);
618   if ( err )
619     {
620       msg (ME, "%s", err->message);
621       g_error_free (err);
622     }
623 }
624
625
626 static void
627 load_and_show_syntax_window (GtkWidget *se, const gchar *filename,
628                              const gchar *encoding)
629 {
630   gboolean ok;
631
632   gtk_source_buffer_begin_not_undoable_action (PSPPIRE_SYNTAX_WINDOW (se)->buffer);
633   ok = psppire_window_load (PSPPIRE_WINDOW (se), filename, encoding, NULL);
634   gtk_source_buffer_end_not_undoable_action (PSPPIRE_SYNTAX_WINDOW (se)->buffer);
635
636   if (ok )
637     gtk_widget_show (se);
638   else
639     gtk_widget_destroy (se);
640 }
641
642 void
643 create_syntax_window (void)
644 {
645   GtkWidget *w = psppire_syntax_window_new (NULL);
646
647   gtk_widget_show (w);
648 }
649
650 void
651 open_syntax_window (const char *file_name, const gchar *encoding)
652 {
653   GtkWidget *se = psppire_syntax_window_new (NULL);
654
655   if ( file_name)
656     load_and_show_syntax_window (se, file_name, encoding);
657 }
658
659
660
661 static void psppire_syntax_window_print (PsppireSyntaxWindow *window);
662
663 static void
664 on_modified_changed (GtkTextBuffer *buffer, PsppireWindow *window)
665 {
666   if (gtk_text_buffer_get_modified (buffer))
667     psppire_window_set_unsaved (window);
668 }
669
670 static void undo_redo_update (PsppireSyntaxWindow *window);
671 static void undo_last_edit (PsppireSyntaxWindow *window);
672 static void redo_last_edit (PsppireSyntaxWindow *window);
673
674 static void
675 on_text_changed (GtkTextBuffer *buffer, PsppireSyntaxWindow *window)
676 {
677   gtk_statusbar_pop (GTK_STATUSBAR (window->sb), window->text_context);
678   undo_redo_update (window);
679 }
680
681 static void
682 psppire_syntax_window_init (PsppireSyntaxWindow *window)
683 {
684   GtkBuilder *xml = builder_new ("syntax-editor.ui");
685   GtkWidget *box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
686
687   GObject *menu = get_object_assert (xml, "syntax-window-menu", G_TYPE_MENU);
688   GtkWidget *menubar = gtk_menu_bar_new_from_model (G_MENU_MODEL (menu));
689
690   GtkWidget *sw = get_widget_assert (xml, "scrolledwindow8");
691
692   GtkWidget *text_view = get_widget_assert (xml, "syntax_text_view");
693
694   PsppireSyntaxWindowClass *class
695     = PSPPIRE_SYNTAX_WINDOW_CLASS (G_OBJECT_GET_CLASS (window));
696
697   GtkClipboard *clip_selection = gtk_widget_get_clipboard (GTK_WIDGET (window), GDK_SELECTION_CLIPBOARD);
698   GtkClipboard *clip_primary =   gtk_widget_get_clipboard (GTK_WIDGET (window), GDK_SELECTION_PRIMARY);
699
700   window->print_settings = NULL;
701
702   window->undo_menuitem = g_simple_action_new ("undo", NULL);
703   window->redo_menuitem = g_simple_action_new ("redo", NULL);
704
705   g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (window->undo_menuitem));
706   g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (window->redo_menuitem));
707
708   
709   if (class->lan)
710     window->buffer = gtk_source_buffer_new_with_language (class->lan);
711   else
712     window->buffer = gtk_source_buffer_new (NULL);
713
714   gtk_text_view_set_buffer (GTK_TEXT_VIEW (text_view), GTK_TEXT_BUFFER (window->buffer));
715
716   g_object_set (window->buffer,
717                 "highlight-matching-brackets", TRUE,
718                 NULL);
719
720   g_object_set (text_view,
721                 "show-line-numbers", TRUE,
722                 "show-line-marks", TRUE,
723                 "auto-indent", TRUE,
724                 "indent-width", 4,
725                 "highlight-current-line", TRUE,
726                 NULL);
727
728   window->encoding = NULL;
729
730   window->cliptext = NULL;
731   window->dispose_has_run = FALSE;
732
733
734   window->edit_delete = g_simple_action_new ("delete", NULL);
735   g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (window->edit_delete));
736
737   window->edit_copy = g_simple_action_new ("copy", NULL);
738   g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (window->edit_copy));
739
740   window->edit_cut = g_simple_action_new ("cut", NULL);
741   g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (window->edit_cut));
742
743   window->edit_paste = g_simple_action_new ("paste", NULL);
744   g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (window->edit_paste));
745
746
747   window->buffer = GTK_SOURCE_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW (text_view)));
748
749   window->sb = get_widget_assert (xml, "statusbar2");
750   window->text_context = gtk_statusbar_get_context_id (GTK_STATUSBAR (window->sb), "Text Context");
751
752   g_signal_connect (window->buffer, "changed", 
753                     G_CALLBACK (on_text_changed), window);
754
755   g_signal_connect (window->buffer, "modified-changed", 
756                     G_CALLBACK (on_modified_changed), window);
757
758
759   {
760     GSimpleAction *print = g_simple_action_new ("print", NULL);
761     
762     g_signal_connect_swapped (print, "activate",
763                               G_CALLBACK (psppire_syntax_window_print), window);
764     
765     g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (print));
766   }
767
768   g_signal_connect_swapped (window->undo_menuitem,
769                             "activate",
770                             G_CALLBACK (undo_last_edit),
771                             window);
772
773   g_signal_connect_swapped (window->redo_menuitem,
774                             "activate",
775                             G_CALLBACK (redo_last_edit),
776                             window);
777
778   undo_redo_update (window);
779
780
781   window->sel_handler = g_signal_connect_swapped (clip_primary, "owner-change", 
782                                                    G_CALLBACK (selection_changed), window);
783
784   window->ps_handler = g_signal_connect (clip_selection, "owner-change", 
785                                           G_CALLBACK (set_paste_sensitivity), window);
786
787   connect_help (xml);
788
789   gtk_container_add (GTK_CONTAINER (window), box);
790
791   g_object_ref (sw);
792
793   g_object_ref (window->sb);
794
795   gtk_box_pack_start (GTK_BOX (box), menubar, FALSE, TRUE, 0);
796   gtk_box_pack_start (GTK_BOX (box), sw, TRUE, TRUE, 0);
797   gtk_box_pack_start (GTK_BOX (box), window->sb, FALSE, TRUE, 0);
798
799   gtk_widget_show_all (box);
800
801   GApplication *app = g_application_get_default ();
802
803   {
804     GSimpleAction *open = g_simple_action_new ("open", NULL);
805     
806     g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (open));
807
808     g_signal_connect_swapped (open,
809                               "activate",
810                               G_CALLBACK (psppire_window_open),
811                               window);
812   }
813
814   {
815     GSimpleAction *save = g_simple_action_new ("save", NULL);
816     
817     g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (save));
818     
819     g_signal_connect_swapped (save,
820                               "activate",
821                               G_CALLBACK (psppire_window_save),
822                               window);
823
824     const gchar *accels[2] = { "<Ctrl>S", NULL};
825     gtk_application_set_accels_for_action (app,
826                                            "win.save",
827                                            accels);
828   
829   }
830
831   {
832     GSimpleAction *save_as = g_simple_action_new ("save_as", NULL);
833     
834     g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (save_as));
835     
836     g_signal_connect_swapped (save_as,
837                               "activate",
838                               G_CALLBACK (psppire_window_save_as),
839                               window);
840
841
842     const gchar *accels[2] = { "<Shift><Ctrl>S", NULL};
843     gtk_application_set_accels_for_action (app,
844                                            "win.save_as",
845                                            accels);
846     
847     
848   }
849
850
851   g_signal_connect_swapped (window->edit_delete,
852                     "activate",
853                     G_CALLBACK (on_edit_delete),
854                     window);
855
856   g_signal_connect_swapped (window->edit_copy,
857                     "activate",
858                     G_CALLBACK (on_edit_copy),
859                     window);
860
861   g_signal_connect_swapped (window->edit_cut,
862                     "activate",
863                     G_CALLBACK (on_edit_cut),
864                     window);
865
866   g_signal_connect_swapped (window->edit_paste,
867                     "activate",
868                     G_CALLBACK (on_edit_paste),
869                     window);
870
871   {
872     GSimpleAction *run_all = g_simple_action_new ("run-all", NULL);
873
874     g_signal_connect_swapped (run_all, "activate",
875                               G_CALLBACK (on_run_all), window);
876
877     g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (run_all));
878   }
879
880   {
881     GSimpleAction *run_current_line = g_simple_action_new ("run-current-line", NULL);
882
883     g_signal_connect_swapped (run_current_line, "activate",
884                               G_CALLBACK (on_run_current_line), window);
885
886     g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (run_current_line));
887
888     GApplication *app = g_application_get_default ();
889     const gchar *accels[2] = { "<Ctrl>R", NULL};
890     gtk_application_set_accels_for_action (app,
891                                            "win.run-current-line",
892                                            accels);
893   }
894
895   {
896     GSimpleAction *run_selection = g_simple_action_new ("run-selection", NULL);
897       
898     g_signal_connect_swapped (run_selection, "activate",
899                               G_CALLBACK (on_run_selection), window);
900
901     g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (run_selection));
902   }
903
904   {
905     GSimpleAction *run_to_end = g_simple_action_new ("run-to-end", NULL);
906     
907     g_signal_connect_swapped (run_to_end, "activate",
908                               G_CALLBACK (on_run_to_end), window);
909     
910     g_action_map_add_action (G_ACTION_MAP (window), G_ACTION (run_to_end));
911   }
912
913   gtk_menu_shell_append (GTK_MENU_SHELL (menubar),
914                          create_windows_menu (GTK_WINDOW (window)));
915
916   gtk_menu_shell_append (GTK_MENU_SHELL (menubar),
917                          create_help_menu (GTK_WINDOW (window)));
918
919   g_object_unref (xml);
920 }
921
922
923
924
925
926 GtkWidget *
927 psppire_syntax_window_new (const char *encoding)
928 {
929   GObject *sw = g_object_new (psppire_syntax_window_get_type (),
930                               "description", _("Syntax Editor"),
931                               "encoding", encoding,
932                               NULL);
933   
934   GApplication *app = g_application_get_default ();
935   gtk_application_add_window (GTK_APPLICATION (app), GTK_WINDOW (sw));
936
937   return GTK_WIDGET (sw);
938 }
939
940 static void
941 error_dialog (GtkWindow *w, const gchar *filename,  GError *err)
942 {
943   gchar *fn = g_filename_display_basename (filename);
944
945   GtkWidget *dialog =
946     gtk_message_dialog_new (w,
947                             GTK_DIALOG_DESTROY_WITH_PARENT,
948                             GTK_MESSAGE_ERROR,
949                             GTK_BUTTONS_CLOSE,
950                             _("Cannot load syntax file `%s'"),
951                             fn);
952
953   g_free (fn);
954
955   g_object_set (dialog, "icon-name", "pspp", NULL);
956
957   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
958                                             "%s", err->message);
959
960   gtk_dialog_run (GTK_DIALOG (dialog));
961
962   gtk_widget_destroy (dialog);
963 }
964
965 /*
966   Loads the buffer from the file called FILENAME
967 */
968 gboolean
969 syntax_load (PsppireWindow *window, const gchar *filename,
970              const gchar *encoding, gpointer not_used)
971 {
972   GError *err = NULL;
973   gchar *text_locale = NULL;
974   gchar *text_utf8 = NULL;
975   gsize len_locale = -1;
976   gsize len_utf8 = -1;
977   GtkTextIter iter;
978   PsppireSyntaxWindow *sw = PSPPIRE_SYNTAX_WINDOW (window);
979   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (sw->buffer);
980
981   /* FIXME: What if it's a very big file ? */
982   if ( ! g_file_get_contents (filename, &text_locale, &len_locale, &err) )
983     {
984       error_dialog (GTK_WINDOW (window), filename, err);
985       g_clear_error (&err);
986       return FALSE;
987     }
988
989   if (!encoding || !encoding[0])
990     {
991       /* Determine the file's encoding and update sw->encoding.  (The ordering
992          is important here because encoding_guess_whole_file() often returns
993          its argument instead of a copy of it.) */
994       char *guessed_encoding;
995
996       guessed_encoding = g_strdup (encoding_guess_whole_file (sw->encoding,
997                                                               text_locale,
998                                                               len_locale));
999       g_free (sw->encoding);
1000       sw->encoding = guessed_encoding;
1001     }
1002   else
1003     {
1004       g_free (sw->encoding);
1005       sw->encoding = g_strdup (encoding);
1006     }
1007
1008   text_utf8 = recode_substring_pool ("UTF-8", sw->encoding,
1009                                      ss_buffer (text_locale, len_locale),
1010                                      NULL).string;
1011   free (text_locale);
1012
1013   if ( text_utf8 == NULL )
1014     {
1015       error_dialog (GTK_WINDOW (window), filename, err);
1016       g_clear_error (&err);
1017       return FALSE;
1018     }
1019
1020   gtk_text_buffer_get_iter_at_line (buffer, &iter, 0);
1021
1022   gtk_text_buffer_insert (buffer, &iter, text_utf8, len_utf8);
1023
1024   gtk_text_buffer_set_modified (buffer, FALSE);
1025
1026   free (text_utf8);
1027
1028   add_most_recent (filename, "text/x-spss-syntax", sw->encoding);
1029
1030   return TRUE;
1031 }
1032
1033 \f
1034
1035 static void
1036 psppire_syntax_window_iface_init (PsppireWindowIface *iface)
1037 {
1038   iface->save = syntax_save;
1039   iface->pick_filename = syntax_pick_filename;
1040   iface->load = syntax_load;
1041 }
1042
1043
1044 \f
1045
1046 static void
1047 undo_redo_update (PsppireSyntaxWindow *window)
1048 {
1049   g_object_set (window->undo_menuitem, "enabled",
1050                 gtk_source_buffer_can_undo (window->buffer), NULL);
1051
1052   g_object_set  (window->redo_menuitem, "enabled",
1053                  gtk_source_buffer_can_redo (window->buffer), NULL);
1054 }
1055
1056 static void
1057 undo_last_edit (PsppireSyntaxWindow *window)
1058 {
1059   gtk_source_buffer_undo (window->buffer);
1060   undo_redo_update (window);
1061 }
1062
1063 static void
1064 redo_last_edit (PsppireSyntaxWindow *window)
1065 {
1066   gtk_source_buffer_redo (window->buffer);
1067   undo_redo_update (window);
1068 }
1069
1070
1071 \f
1072 /* Printing related stuff */
1073
1074
1075 static void
1076 begin_print (GtkPrintOperation *operation,
1077           GtkPrintContext   *context,
1078           PsppireSyntaxWindow *window)
1079 {
1080   window->compositor =
1081     gtk_source_print_compositor_new (window->buffer);
1082 }
1083
1084
1085 static void
1086 end_print (GtkPrintOperation *operation,
1087           GtkPrintContext   *context,
1088           PsppireSyntaxWindow *window)
1089 {
1090   g_object_unref (window->compositor);
1091   window->compositor = NULL;
1092 }
1093
1094
1095
1096 static gboolean
1097 paginate (GtkPrintOperation *operation,
1098           GtkPrintContext   *context,
1099           PsppireSyntaxWindow *window)
1100 {
1101   if (gtk_source_print_compositor_paginate (window->compositor, context))
1102     {
1103       gint n_pages = gtk_source_print_compositor_get_n_pages (window->compositor);
1104       gtk_print_operation_set_n_pages (operation, n_pages);
1105         
1106       return TRUE;
1107     }
1108
1109   return FALSE;
1110 }
1111
1112 static void
1113 draw_page (GtkPrintOperation *operation,
1114            GtkPrintContext   *context,
1115            gint               page_nr,
1116           PsppireSyntaxWindow *window)
1117 {
1118   gtk_source_print_compositor_draw_page (window->compositor, 
1119                                          context,
1120                                          page_nr);
1121 }
1122
1123
1124
1125 static void
1126 psppire_syntax_window_print (PsppireSyntaxWindow *window)
1127 {
1128   GtkPrintOperationResult res;
1129
1130   GtkPrintOperation *print = gtk_print_operation_new ();
1131
1132   if (window->print_settings != NULL) 
1133     gtk_print_operation_set_print_settings (print, window->print_settings);
1134
1135
1136   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), window);
1137   g_signal_connect (print, "end_print", G_CALLBACK (end_print),     window);
1138   g_signal_connect (print, "draw_page", G_CALLBACK (draw_page),     window);
1139   g_signal_connect (print, "paginate", G_CALLBACK (paginate),       window);
1140
1141   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1142                                  GTK_WINDOW (window), NULL);
1143
1144   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1145     {
1146       if (window->print_settings != NULL)
1147         g_object_unref (window->print_settings);
1148       window->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1149     }
1150
1151   g_object_unref (print);
1152 }