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