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