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