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