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