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