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