cd4b62da32ed04ea0aac369f44864e0424e8bef4
[pspp-builds.git] / src / ui / gui / psppire-syntax-window.c
1 /* PSPPIRE - a graphical user interface for PSPP.
2    Copyright (C) 2008, 2009, 2010, 2011  Free Software Foundation
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <gtk/gtk.h>
20 #include <stdlib.h>
21
22 #include <gtksourceview/gtksourcebuffer.h>
23 #include <gtksourceview/gtksourcelanguage.h>
24 #include <gtksourceview/gtksourcelanguagemanager.h>
25 #include <gtksourceview/gtksourceprintcompositor.h>
26
27 #include "language/lexer/lexer.h"
28 #include "libpspp/encoding-guesser.h"
29 #include "libpspp/i18n.h"
30 #include "libpspp/message.h"
31 #include "ui/gui/executor.h"
32 #include "ui/gui/help-menu.h"
33 #include "ui/gui/helper.h"
34 #include "ui/gui/psppire-data-window.h"
35 #include "ui/gui/psppire-encoding-selector.h"
36 #include "ui/gui/psppire-syntax-window.h"
37 #include "ui/gui/psppire-window-register.h"
38 #include "ui/gui/psppire.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_free (sw->encoding);
165   sw->encoding = NULL;
166
167   clip_selection = gtk_widget_get_clipboard (GTK_WIDGET (sw), GDK_SELECTION_CLIPBOARD);
168   clip_primary =   gtk_widget_get_clipboard (GTK_WIDGET (sw), GDK_SELECTION_PRIMARY);
169
170   g_signal_handler_disconnect (clip_primary, sw->sel_handler);
171
172   g_signal_handler_disconnect (clip_selection, sw->ps_handler);
173
174   /* Make sure dispose does not run twice. */
175   sw->dispose_has_run = TRUE;
176
177   /* Chain up to the parent class */
178   G_OBJECT_CLASS (parent_class)->dispose (obj);
179 }
180
181
182
183 static void
184 psppire_syntax_window_class_init (PsppireSyntaxWindowClass *class)
185 {
186   GParamSpec *encoding_spec;
187   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
188
189   GtkSourceLanguageManager *lm = gtk_source_language_manager_get_default ();
190
191   const gchar * const *existing_paths =  gtk_source_language_manager_get_search_path (lm);
192   gchar **new_paths = g_strdupv ((gchar **)existing_paths);
193   int n = g_strv_length ((gchar **) existing_paths);
194
195   new_paths = g_realloc (new_paths, (n + 2) * sizeof (*new_paths));
196   new_paths[n] = g_strdup (relocate (PKGDATADIR));
197   new_paths[n+1] = NULL;
198
199   lm = gtk_source_language_manager_new ();
200   gtk_source_language_manager_set_search_path (lm, new_paths);
201
202   class->lan = gtk_source_language_manager_get_language (lm, "pspp");
203
204   if (class->lan == NULL)
205     g_warning ("pspp.lang file not found.  Syntax highlighting will not be available.");
206
207   parent_class = g_type_class_peek_parent (class);
208
209   g_strfreev (new_paths);
210
211   encoding_spec =
212     null_if_empty_param ("encoding",
213                          "Character encoding",
214                          "IANA character encoding in this syntax file",
215                          NULL,
216                          G_PARAM_CONSTRUCT | G_PARAM_READWRITE);
217
218   parent_class = g_type_class_peek_parent (class);
219
220   gobject_class->set_property = psppire_syntax_window_set_property;
221   gobject_class->get_property = psppire_syntax_window_get_property;
222   gobject_class->dispose = psppire_syntax_window_dispose;
223
224   g_object_class_install_property (gobject_class,
225                                    PROP_ENCODING,
226                                    encoding_spec);
227 }
228
229
230 static void
231 psppire_syntax_window_base_init (PsppireSyntaxWindowClass *class)
232 {
233   GObjectClass *object_class = G_OBJECT_CLASS (class);
234   object_class->finalize = psppire_syntax_window_finalize;
235 }
236
237
238
239 static void
240 psppire_syntax_window_base_finalize (PsppireSyntaxWindowClass *class,
241                                      gpointer class_data)
242 {
243 }
244
245
246 static void
247 editor_execute_syntax (const PsppireSyntaxWindow *sw, GtkTextIter start,
248                        GtkTextIter stop)
249 {
250   PsppireWindow *win = PSPPIRE_WINDOW (sw);
251   struct lex_reader *reader;
252   gchar *text = gtk_text_buffer_get_text (GTK_TEXT_BUFFER (sw->buffer), &start, &stop, FALSE);
253   reader = lex_reader_for_string (text);
254   g_free (text);
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
273 /* The syntax editor's clipboard deals only with text */
274 enum {
275   SELECT_FMT_NULL,
276   SELECT_FMT_TEXT,
277 };
278
279
280 static void
281 selection_changed (PsppireSyntaxWindow *sw)
282 {
283   gboolean sel = gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (sw->buffer));
284
285   gtk_action_set_sensitive (sw->edit_copy, sel);
286   gtk_action_set_sensitive (sw->edit_cut, sel);
287   gtk_action_set_sensitive (sw->edit_delete, sel);
288 }
289
290 /* The callback which runs when something request clipboard data */
291 static void
292 clipboard_get_cb (GtkClipboard     *clipboard,
293                   GtkSelectionData *selection_data,
294                   guint             info,
295                   gpointer          data)
296 {
297   PsppireSyntaxWindow *sw = data;
298   g_assert (info == SELECT_FMT_TEXT);
299
300   gtk_selection_data_set (selection_data, selection_data->target,
301                           8,
302                           (const guchar *) sw->cliptext, strlen (sw->cliptext));
303
304 }
305
306 static void
307 clipboard_clear_cb (GtkClipboard *clipboard,
308                     gpointer data)
309 {
310   PsppireSyntaxWindow *sw = data;
311   g_free (sw->cliptext);
312   sw->cliptext = NULL;
313 }
314
315
316 static const GtkTargetEntry targets[] = {
317   { "UTF8_STRING",   0, SELECT_FMT_TEXT },
318   { "STRING",        0, SELECT_FMT_TEXT },
319   { "TEXT",          0, SELECT_FMT_TEXT },
320   { "COMPOUND_TEXT", 0, SELECT_FMT_TEXT },
321   { "text/plain;charset=utf-8", 0, SELECT_FMT_TEXT },
322   { "text/plain",    0, SELECT_FMT_TEXT },
323 };
324
325
326 /*
327   Store a clip containing the currently selected text.
328   Returns true iff something was set.
329   As a side effect, begin and end will be set to indicate
330   the limits of the selected text.
331 */
332 static gboolean
333 set_clip (PsppireSyntaxWindow *sw, GtkTextIter *begin, GtkTextIter *end)
334 {
335   GtkClipboard *clipboard ;
336   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (sw->buffer);
337
338   if ( ! gtk_text_buffer_get_selection_bounds (buffer, begin, end) )
339     return FALSE;
340
341   g_free (sw->cliptext);
342   sw->cliptext = gtk_text_buffer_get_text  (buffer, begin, end, FALSE);
343
344   clipboard =
345     gtk_widget_get_clipboard (GTK_WIDGET (sw), GDK_SELECTION_CLIPBOARD);
346
347   if (!gtk_clipboard_set_with_owner (clipboard, targets,
348                                      G_N_ELEMENTS (targets),
349                                      clipboard_get_cb, clipboard_clear_cb,
350                                      G_OBJECT (sw)))
351     clipboard_clear_cb (clipboard, sw);
352
353   return TRUE;
354 }
355
356 static void
357 on_edit_cut (PsppireSyntaxWindow *sw)
358 {
359   GtkTextIter begin, end;
360   
361   if ( set_clip (sw, &begin, &end))
362     gtk_text_buffer_delete (GTK_TEXT_BUFFER (sw->buffer), &begin, &end);
363 }
364
365 static void
366 on_edit_copy (PsppireSyntaxWindow *sw)
367 {
368   GtkTextIter begin, end;
369
370   set_clip (sw, &begin, &end);
371 }
372
373
374 /* A callback for when the clipboard contents have been received */
375 static void
376 contents_received_callback (GtkClipboard *clipboard,
377                             GtkSelectionData *sd,
378                             gpointer data)
379 {
380   gchar *c;
381   PsppireSyntaxWindow *syntax_window = data;
382
383   if ( sd->length < 0 )
384     return;
385
386   if ( sd->type != gdk_atom_intern ("UTF8_STRING", FALSE))
387     return;
388
389   c = (gchar *) sd->data;
390
391   gtk_text_buffer_insert_at_cursor (GTK_TEXT_BUFFER (syntax_window->buffer),
392                                     (gchar *) sd->data,
393                                     sd->length);
394
395 }
396
397 static void
398 on_edit_paste (PsppireSyntaxWindow *sw)
399 {
400   GdkDisplay *display = gtk_widget_get_display (GTK_WIDGET (sw));
401   GtkClipboard *clipboard =
402     gtk_clipboard_get_for_display (display, GDK_SELECTION_CLIPBOARD);
403
404   gtk_clipboard_request_contents (clipboard,
405                                   gdk_atom_intern ("UTF8_STRING", TRUE),
406                                   contents_received_callback,
407                                   sw);
408 }
409
410
411 /* Check to see if CLIP holds a target which we know how to paste,
412    and set the sensitivity of the Paste action accordingly.
413  */
414 static void
415 set_paste_sensitivity (GtkClipboard *clip, GdkEventOwnerChange *event, gpointer data)
416 {
417   gint i;
418   gboolean compatible_target = FALSE;
419   PsppireSyntaxWindow *sw = PSPPIRE_SYNTAX_WINDOW (data);
420
421   for (i = 0 ; i < sizeof (targets) / sizeof (targets[0]) ; ++i)
422     {
423       GdkAtom atom = gdk_atom_intern (targets[i].target, TRUE);
424       if ( gtk_clipboard_wait_is_target_available (clip, atom))
425         {
426           compatible_target = TRUE;
427           break;
428         }
429     }
430
431   gtk_action_set_sensitive (sw->edit_paste, compatible_target);
432 }
433
434
435 \f
436
437 /* Parse and execute all the text in the buffer */
438 static void
439 on_run_all (GtkMenuItem *menuitem, gpointer user_data)
440 {
441   GtkTextIter begin, end;
442   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
443
444   gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (se->buffer), &begin, 0);
445   gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (se->buffer), &end, -1);
446
447   editor_execute_syntax (se, begin, end);
448 }
449
450 /* Parse and execute the currently selected text */
451 static void
452 on_run_selection (GtkMenuItem *menuitem, gpointer user_data)
453 {
454   GtkTextIter begin, end;
455   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
456
457   if ( gtk_text_buffer_get_selection_bounds (GTK_TEXT_BUFFER (se->buffer), &begin, &end) )
458     editor_execute_syntax (se, begin, end);
459 }
460
461
462 /* Parse and execute the from the current line, to the end of the
463    buffer */
464 static void
465 on_run_to_end (GtkMenuItem *menuitem, gpointer user_data)
466 {
467   GtkTextIter begin, end;
468   GtkTextIter here;
469   gint line;
470
471   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
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 (GtkMenuItem *menuitem, gpointer user_data)
494 {
495   GtkTextIter begin, end;
496   GtkTextIter here;
497   gint line;
498
499   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
500
501   /* Get the current line */
502   gtk_text_buffer_get_iter_at_mark (GTK_TEXT_BUFFER (se->buffer),
503                                     &here,
504                                     gtk_text_buffer_get_insert (GTK_TEXT_BUFFER (se->buffer))
505                                     );
506
507   line = gtk_text_iter_get_line (&here) ;
508
509   /* Now set begin and end to the start of this line, and start of
510      following line respectively */
511   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &begin, line);
512   gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (se->buffer), &end, line + 1);
513
514   editor_execute_syntax (se, begin, end);
515 }
516
517
518
519 /* Append ".sps" to FILENAME if necessary.
520    The returned result must be freed when no longer required.
521  */
522 static gchar *
523 append_suffix (const gchar *filename)
524 {
525   if ( ! g_str_has_suffix (filename, ".sps" ) &&
526        ! g_str_has_suffix (filename, ".SPS" ) )
527     {
528       return g_strdup_printf ("%s.sps", filename);
529     }
530
531   return xstrdup (filename);
532 }
533
534 /*
535   Save BUFFER to the file called FILENAME.
536   FILENAME must be encoded in Glib filename encoding.
537   If successful, clears the buffer's modified flag.
538 */
539 static gboolean
540 save_editor_to_file (PsppireSyntaxWindow *se,
541                      const gchar *filename,
542                      GError **err)
543 {
544   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (se->buffer);
545   struct substring text_locale;
546   gboolean result ;
547   GtkTextIter start, stop;
548   gchar *text;
549
550   gchar *suffixedname;
551   g_assert (filename);
552
553   suffixedname = append_suffix (filename);
554
555   gtk_text_buffer_get_iter_at_line (buffer, &start, 0);
556   gtk_text_buffer_get_iter_at_offset (buffer, &stop, -1);
557
558   text = gtk_text_buffer_get_text (buffer, &start, &stop, FALSE);
559
560   text_locale = recode_substring_pool (se->encoding, "UTF-8", ss_cstr (text),
561                                        NULL);
562
563   result =  g_file_set_contents (suffixedname, ss_data (text_locale),
564                                  ss_length (text_locale), err);
565
566   ss_dealloc (&text_locale);
567   g_free (suffixedname);
568
569   if ( result )
570     {
571       char *fn = g_filename_display_name (filename);
572       gchar *msg = g_strdup_printf (_("Saved file `%s'"), fn);
573       g_free (fn);
574       gtk_statusbar_push (GTK_STATUSBAR (se->sb), se->text_context, msg);
575       gtk_text_buffer_set_modified (buffer, FALSE);
576       g_free (msg);
577     }
578
579   return result;
580 }
581
582
583 /* PsppireWindow 'pick_Filename' callback. */
584 static void
585 syntax_pick_filename (PsppireWindow *window)
586 {
587   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (window);
588   const char *default_encoding;
589   GtkFileFilter *filter;
590   gint response;
591
592   GtkWidget *dialog =
593     gtk_file_chooser_dialog_new (_("Save Syntax"),
594                                  GTK_WINDOW (se),
595                                  GTK_FILE_CHOOSER_ACTION_SAVE,
596                                  GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
597                                  GTK_STOCK_SAVE,   GTK_RESPONSE_ACCEPT,
598                                  NULL);
599
600   g_object_set (dialog, "local-only", FALSE, NULL);
601
602   filter = gtk_file_filter_new ();
603   gtk_file_filter_set_name (filter, _("Syntax Files (*.sps) "));
604   gtk_file_filter_add_pattern (filter, "*.sps");
605   gtk_file_filter_add_pattern (filter, "*.SPS");
606   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
607
608   filter = gtk_file_filter_new ();
609   gtk_file_filter_set_name (filter, _("All Files"));
610   gtk_file_filter_add_pattern (filter, "*");
611   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
612
613   gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog),
614                                                   TRUE);
615
616   default_encoding = se->encoding != NULL ? se->encoding : locale_charset ();
617   gtk_file_chooser_set_extra_widget (
618     GTK_FILE_CHOOSER (dialog),
619     psppire_encoding_selector_new (default_encoding, false));
620
621   response = gtk_dialog_run (GTK_DIALOG (dialog));
622
623   if ( response == GTK_RESPONSE_ACCEPT )
624     {
625       gchar *encoding;
626       char *filename;
627
628       filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog) );
629       psppire_window_set_filename (window, filename);
630       free (filename);
631
632       encoding = psppire_encoding_selector_get_encoding (
633         gtk_file_chooser_get_extra_widget (GTK_FILE_CHOOSER (dialog)));
634       if (encoding != NULL)
635         {
636           g_free (se->encoding);
637           se->encoding = encoding;
638         }
639     }
640
641   gtk_widget_destroy (dialog);
642 }
643
644
645 /* PsppireWindow 'save' callback. */
646 static void
647 syntax_save (PsppireWindow *se)
648 {
649   const gchar *filename = psppire_window_get_filename (se);
650   GError *err = NULL;
651   save_editor_to_file (PSPPIRE_SYNTAX_WINDOW (se), filename, &err);
652   if ( err )
653     {
654       msg (ME, "%s", err->message);
655       g_error_free (err);
656     }
657 }
658
659
660 /* Callback for the File->Quit menuitem */
661 static gboolean
662 on_quit (GtkMenuItem *menuitem, gpointer    user_data)
663 {
664   psppire_quit ();
665
666   return FALSE;
667 }
668
669
670 static void
671 load_and_show_syntax_window (GtkWidget *se, const gchar *filename)
672 {
673   gboolean ok;
674
675   gtk_source_buffer_begin_not_undoable_action (PSPPIRE_SYNTAX_WINDOW (se)->buffer);
676   ok = psppire_window_load (PSPPIRE_WINDOW (se), filename);
677   gtk_source_buffer_end_not_undoable_action (PSPPIRE_SYNTAX_WINDOW (se)->buffer);
678
679   if (ok )
680     gtk_widget_show (se);
681   else
682     gtk_widget_destroy (se);
683 }
684
685 void
686 create_syntax_window (void)
687 {
688   GtkWidget *w = psppire_syntax_window_new (NULL);
689   gtk_widget_show (w);
690 }
691
692 void
693 open_syntax_window (const char *file_name, const gchar *encoding)
694 {
695   GtkWidget *se = psppire_syntax_window_new (encoding);
696
697   if ( file_name)
698     load_and_show_syntax_window (se, file_name);
699 }
700
701
702
703 static void psppire_syntax_window_print (PsppireSyntaxWindow *window);
704
705 static void
706 on_modified_changed (GtkTextBuffer *buffer, PsppireWindow *window)
707 {
708   if (gtk_text_buffer_get_modified (buffer))
709     psppire_window_set_unsaved (window);
710 }
711
712 static void undo_redo_update (PsppireSyntaxWindow *window);
713 static void undo_last_edit (PsppireSyntaxWindow *window);
714 static void redo_last_edit (PsppireSyntaxWindow *window);
715
716 static void
717 on_text_changed (GtkTextBuffer *buffer, PsppireSyntaxWindow *window)
718 {
719   gtk_statusbar_pop (GTK_STATUSBAR (window->sb), window->text_context);
720   undo_redo_update (window);
721 }
722
723 static void
724 psppire_syntax_window_init (PsppireSyntaxWindow *window)
725 {
726   GtkBuilder *xml = builder_new ("syntax-editor.ui");
727   GtkWidget *box = gtk_vbox_new (FALSE, 0);
728
729   GtkWidget *menubar = get_widget_assert (xml, "menubar");
730   GtkWidget *sw = get_widget_assert (xml, "scrolledwindow8");
731
732   GtkWidget *text_view = get_widget_assert (xml, "syntax_text_view");
733
734   PsppireSyntaxWindowClass *class
735     = PSPPIRE_SYNTAX_WINDOW_CLASS (G_OBJECT_GET_CLASS (window));
736
737   GtkClipboard *clip_selection = gtk_widget_get_clipboard (GTK_WIDGET (window), GDK_SELECTION_CLIPBOARD);
738   GtkClipboard *clip_primary =   gtk_widget_get_clipboard (GTK_WIDGET (window), GDK_SELECTION_PRIMARY);
739
740   window->print_settings = NULL;
741   window->undo_menuitem = get_action_assert (xml, "edit_undo");
742   window->redo_menuitem = get_action_assert (xml, "edit_redo");
743
744   if (class->lan)
745     window->buffer = gtk_source_buffer_new_with_language (class->lan);
746   else
747     window->buffer = gtk_source_buffer_new (NULL);
748
749   gtk_text_view_set_buffer (GTK_TEXT_VIEW (text_view), GTK_TEXT_BUFFER (window->buffer));
750
751   g_object_set (window->buffer,
752                 "highlight-matching-brackets", TRUE,
753                 NULL);
754
755   g_object_set (text_view,
756                 "show-line-numbers", TRUE,
757                 "show-line-marks", TRUE,
758                 "auto-indent", TRUE,
759                 "indent-width", 4,
760                 "highlight-current-line", TRUE,
761                 NULL);
762
763   window->encoding = NULL;
764
765   window->cliptext = NULL;
766   window->dispose_has_run = FALSE;
767
768   window->edit_delete = get_action_assert (xml, "edit_delete");
769   window->edit_copy = get_action_assert (xml, "edit_copy");
770   window->edit_cut = get_action_assert (xml, "edit_cut");
771   window->edit_paste = get_action_assert (xml, "edit_paste");
772
773   window->buffer = GTK_SOURCE_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW (text_view)));
774
775   window->sb = get_widget_assert (xml, "statusbar2");
776   window->text_context = gtk_statusbar_get_context_id (GTK_STATUSBAR (window->sb), "Text Context");
777
778   g_signal_connect (window->buffer, "changed", 
779                     G_CALLBACK (on_text_changed), window);
780
781   g_signal_connect (window->buffer, "modified-changed", 
782                     G_CALLBACK (on_modified_changed), window);
783
784   g_signal_connect_swapped (get_action_assert (xml, "file_print"), "activate",
785                             G_CALLBACK (psppire_syntax_window_print), window);
786
787
788   g_signal_connect_swapped (window->undo_menuitem,
789                             "activate",
790                             G_CALLBACK (undo_last_edit),
791                             window);
792
793   g_signal_connect_swapped (window->redo_menuitem,
794                             "activate",
795                             G_CALLBACK (redo_last_edit),
796                             window);
797
798   undo_redo_update (window);
799
800   window->sel_handler = g_signal_connect_swapped (clip_primary, "owner-change", 
801                                                    G_CALLBACK (selection_changed), window);
802
803   window->ps_handler = g_signal_connect (clip_selection, "owner-change", 
804                                           G_CALLBACK (set_paste_sensitivity), window);
805
806   connect_help (xml);
807
808   gtk_container_add (GTK_CONTAINER (window), box);
809
810   g_object_ref (menubar);
811
812   g_object_ref (sw);
813
814   g_object_ref (window->sb);
815
816   gtk_box_pack_start (GTK_BOX (box), menubar, FALSE, TRUE, 0);
817   gtk_box_pack_start (GTK_BOX (box), sw, TRUE, TRUE, 0);
818   gtk_box_pack_start (GTK_BOX (box), window->sb, FALSE, TRUE, 0);
819
820   gtk_widget_show_all (box);
821
822   g_signal_connect_swapped (get_action_assert (xml,"file_new_syntax"), "activate", G_CALLBACK (create_syntax_window), NULL);
823
824   g_signal_connect (get_action_assert (xml,"file_new_data"),
825                     "activate",
826                     G_CALLBACK (create_data_window),
827                     window);
828
829   g_signal_connect_swapped (get_action_assert (xml, "file_open"),
830                     "activate",
831                     G_CALLBACK (psppire_window_open),
832                     window);
833
834   g_signal_connect_swapped (get_action_assert (xml, "file_save"),
835                     "activate",
836                     G_CALLBACK (psppire_window_save),
837                     window);
838
839   g_signal_connect_swapped (get_action_assert (xml, "file_save_as"),
840                     "activate",
841                     G_CALLBACK (psppire_window_save_as),
842                     window);
843
844   g_signal_connect (get_action_assert (xml,"file_quit"),
845                     "activate",
846                     G_CALLBACK (on_quit),
847                     window);
848
849   g_signal_connect_swapped (window->edit_delete,
850                     "activate",
851                     G_CALLBACK (on_edit_delete),
852                     window);
853
854   g_signal_connect_swapped (window->edit_copy,
855                     "activate",
856                     G_CALLBACK (on_edit_copy),
857                     window);
858
859   g_signal_connect_swapped (window->edit_cut,
860                     "activate",
861                     G_CALLBACK (on_edit_cut),
862                     window);
863
864   g_signal_connect_swapped (window->edit_paste,
865                     "activate",
866                     G_CALLBACK (on_edit_paste),
867                     window);
868
869   g_signal_connect (get_action_assert (xml,"run_all"),
870                     "activate",
871                     G_CALLBACK (on_run_all),
872                     window);
873
874   g_signal_connect (get_action_assert (xml,"run_selection"),
875                     "activate",
876                     G_CALLBACK (on_run_selection),
877                     window);
878
879   g_signal_connect (get_action_assert (xml,"run_current_line"),
880                     "activate",
881                     G_CALLBACK (on_run_current_line),
882                     window);
883
884   g_signal_connect (get_action_assert (xml,"run_to_end"),
885                     "activate",
886                     G_CALLBACK (on_run_to_end),
887                     window);
888
889   g_signal_connect (get_action_assert (xml,"windows_minimise_all"),
890                     "activate",
891                     G_CALLBACK (psppire_window_minimise_all), NULL);
892
893
894
895
896
897   {
898   GtkUIManager *uim = GTK_UI_MANAGER (get_object_assert (xml, "uimanager1", GTK_TYPE_UI_MANAGER));
899
900   merge_help_menu (uim);
901
902   PSPPIRE_WINDOW (window)->menu =
903     GTK_MENU_SHELL (gtk_ui_manager_get_widget (uim,"/ui/menubar/windows/windows_minimise_all")->parent);
904   }
905
906   g_object_unref (xml);
907 }
908
909
910
911
912
913 GtkWidget*
914 psppire_syntax_window_new (const char *encoding)
915 {
916   return GTK_WIDGET (g_object_new (psppire_syntax_window_get_type (),
917                                    "description", _("Syntax Editor"),
918                                    "encoding", encoding,
919                                    NULL));
920 }
921
922 static void
923 error_dialog (GtkWindow *w, const gchar *filename,  GError *err)
924 {
925   gchar *fn = g_filename_display_basename (filename);
926
927   GtkWidget *dialog =
928     gtk_message_dialog_new (w,
929                             GTK_DIALOG_DESTROY_WITH_PARENT,
930                             GTK_MESSAGE_ERROR,
931                             GTK_BUTTONS_CLOSE,
932                             _("Cannot load syntax file `%s'"),
933                             fn);
934
935   g_free (fn);
936
937   g_object_set (dialog, "icon-name", "pspp", NULL);
938
939   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
940                                             "%s", err->message);
941
942   gtk_dialog_run (GTK_DIALOG (dialog));
943
944   gtk_widget_destroy (dialog);
945 }
946
947 /*
948   Loads the buffer from the file called FILENAME
949 */
950 gboolean
951 syntax_load (PsppireWindow *window, const gchar *filename)
952 {
953   GError *err = NULL;
954   gchar *text_locale = NULL;
955   gchar *text_utf8 = NULL;
956   gsize len_locale = -1;
957   gsize len_utf8 = -1;
958   GtkTextIter iter;
959   PsppireSyntaxWindow *sw = PSPPIRE_SYNTAX_WINDOW (window);
960   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (sw->buffer);
961   gchar *encoding;
962   char *mime_type;
963
964   /* FIXME: What if it's a very big file ? */
965   if ( ! g_file_get_contents (filename, &text_locale, &len_locale, &err) )
966     {
967       error_dialog (GTK_WINDOW (window), filename, err);
968       g_clear_error (&err);
969       return FALSE;
970     }
971
972   /* Determine the file's encoding and update sw->encoding.  (The ordering is
973      important here because encoding_guess_whole_file() often returns its
974      argument instead of a copy of it.) */
975   encoding = g_strdup (encoding_guess_whole_file (sw->encoding, text_locale,
976                                                   len_locale));
977   g_free (sw->encoding);
978   sw->encoding = encoding;
979
980   text_utf8 = recode_substring_pool ("UTF-8", encoding,
981                                      ss_buffer (text_locale, len_locale),
982                                      NULL).string;
983   free (text_locale);
984
985   if ( text_utf8 == NULL )
986     {
987       error_dialog (GTK_WINDOW (window), filename, err);
988       g_clear_error (&err);
989       return FALSE;
990     }
991
992   gtk_text_buffer_get_iter_at_line (buffer, &iter, 0);
993
994   gtk_text_buffer_insert (buffer, &iter, text_utf8, len_utf8);
995
996   gtk_text_buffer_set_modified (buffer, FALSE);
997
998   free (text_utf8);
999
1000   mime_type = xasprintf ("text/x-spss-syntax; charset=%s", sw->encoding);
1001   add_most_recent (filename, mime_type);
1002   free (mime_type);
1003
1004   return TRUE;
1005 }
1006
1007 \f
1008
1009 static void
1010 psppire_syntax_window_iface_init (PsppireWindowIface *iface)
1011 {
1012   iface->save = syntax_save;
1013   iface->pick_filename = syntax_pick_filename;
1014   iface->load = syntax_load;
1015 }
1016
1017
1018 \f
1019
1020 static void
1021 undo_redo_update (PsppireSyntaxWindow *window)
1022 {
1023   gtk_action_set_sensitive (window->undo_menuitem,
1024                             gtk_source_buffer_can_undo (window->buffer));
1025
1026   gtk_action_set_sensitive (window->redo_menuitem,
1027                             gtk_source_buffer_can_redo (window->buffer));
1028 }
1029
1030 static void
1031 undo_last_edit (PsppireSyntaxWindow *window)
1032 {
1033   gtk_source_buffer_undo (window->buffer);
1034   undo_redo_update (window);
1035 }
1036
1037 static void
1038 redo_last_edit (PsppireSyntaxWindow *window)
1039 {
1040   gtk_source_buffer_redo (window->buffer);
1041   undo_redo_update (window);
1042 }
1043
1044
1045 \f
1046 /* Printing related stuff */
1047
1048
1049 static void
1050 begin_print (GtkPrintOperation *operation,
1051           GtkPrintContext   *context,
1052           PsppireSyntaxWindow *window)
1053 {
1054   window->compositor =
1055     gtk_source_print_compositor_new (window->buffer);
1056 }
1057
1058
1059 static void
1060 end_print (GtkPrintOperation *operation,
1061           GtkPrintContext   *context,
1062           PsppireSyntaxWindow *window)
1063 {
1064   g_object_unref (window->compositor);
1065   window->compositor = NULL;
1066 }
1067
1068
1069
1070 static gboolean
1071 paginate (GtkPrintOperation *operation,
1072           GtkPrintContext   *context,
1073           PsppireSyntaxWindow *window)
1074 {
1075   if (gtk_source_print_compositor_paginate (window->compositor, context))
1076     {
1077       gint n_pages = gtk_source_print_compositor_get_n_pages (window->compositor);
1078       gtk_print_operation_set_n_pages (operation, n_pages);
1079         
1080       return TRUE;
1081     }
1082
1083   return FALSE;
1084 }
1085
1086 static void
1087 draw_page (GtkPrintOperation *operation,
1088            GtkPrintContext   *context,
1089            gint               page_nr,
1090           PsppireSyntaxWindow *window)
1091 {
1092   gtk_source_print_compositor_draw_page (window->compositor, 
1093                                          context,
1094                                          page_nr);
1095 }
1096
1097
1098
1099 static void
1100 psppire_syntax_window_print (PsppireSyntaxWindow *window)
1101 {
1102   GtkPrintOperationResult res;
1103
1104   GtkPrintOperation *print = gtk_print_operation_new ();
1105
1106   if (window->print_settings != NULL) 
1107     gtk_print_operation_set_print_settings (print, window->print_settings);
1108
1109
1110   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), window);
1111   g_signal_connect (print, "end_print", G_CALLBACK (end_print),     window);
1112   g_signal_connect (print, "draw_page", G_CALLBACK (draw_page),     window);
1113   g_signal_connect (print, "paginate", G_CALLBACK (paginate),       window);
1114
1115   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1116                                  GTK_WINDOW (window), NULL);
1117
1118   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1119     {
1120       if (window->print_settings != NULL)
1121         g_object_unref (window->print_settings);
1122       window->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1123     }
1124
1125   g_object_unref (print);
1126 }