5ccbca5cb5660635a982b09ae4965a925ca59ae0
[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   g_object_set (dialog, "local-only", FALSE, NULL);
604
605   filter = gtk_file_filter_new ();
606   gtk_file_filter_set_name (filter, _("Syntax Files (*.sps) "));
607   gtk_file_filter_add_pattern (filter, "*.sps");
608   gtk_file_filter_add_pattern (filter, "*.SPS");
609   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
610
611   filter = gtk_file_filter_new ();
612   gtk_file_filter_set_name (filter, _("All Files"));
613   gtk_file_filter_add_pattern (filter, "*");
614   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
615
616   gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog),
617                                                   TRUE);
618
619   default_encoding = se->encoding != NULL ? se->encoding : locale_charset ();
620   gtk_file_chooser_set_extra_widget (
621     GTK_FILE_CHOOSER (dialog),
622     psppire_encoding_selector_new (default_encoding, false));
623
624   response = gtk_dialog_run (GTK_DIALOG (dialog));
625
626   if ( response == GTK_RESPONSE_ACCEPT )
627     {
628       gchar *encoding;
629       char *filename;
630
631       filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog) );
632       psppire_window_set_filename (window, filename);
633       free (filename);
634
635       encoding = psppire_encoding_selector_get_encoding (
636         gtk_file_chooser_get_extra_widget (GTK_FILE_CHOOSER (dialog)));
637       if (encoding != NULL)
638         {
639           g_free (se->encoding);
640           se->encoding = encoding;
641         }
642     }
643
644   gtk_widget_destroy (dialog);
645 }
646
647
648 /* PsppireWindow 'save' callback. */
649 static void
650 syntax_save (PsppireWindow *se)
651 {
652   const gchar *filename = psppire_window_get_filename (se);
653   GError *err = NULL;
654   save_editor_to_file (PSPPIRE_SYNTAX_WINDOW (se), filename, &err);
655   if ( err )
656     {
657       msg (ME, "%s", err->message);
658       g_error_free (err);
659     }
660 }
661
662
663 /* Callback for the File->Quit menuitem */
664 static gboolean
665 on_quit (GtkMenuItem *menuitem, gpointer    user_data)
666 {
667   psppire_quit ();
668
669   return FALSE;
670 }
671
672
673 static void
674 load_and_show_syntax_window (GtkWidget *se, const gchar *filename)
675 {
676   gboolean ok;
677
678   gtk_source_buffer_begin_not_undoable_action (PSPPIRE_SYNTAX_WINDOW (se)->buffer);
679   ok = psppire_window_load (PSPPIRE_WINDOW (se), filename);
680   gtk_source_buffer_end_not_undoable_action (PSPPIRE_SYNTAX_WINDOW (se)->buffer);
681
682   if (ok )
683     gtk_widget_show (se);
684   else
685     gtk_widget_destroy (se);
686 }
687
688 void
689 create_syntax_window (void)
690 {
691   GtkWidget *w = psppire_syntax_window_new (NULL);
692   gtk_widget_show (w);
693 }
694
695 void
696 open_syntax_window (const char *file_name, const gchar *encoding)
697 {
698   GtkWidget *se = psppire_syntax_window_new (encoding);
699
700   if ( file_name)
701     load_and_show_syntax_window (se, file_name);
702 }
703
704
705
706 static void psppire_syntax_window_print (PsppireSyntaxWindow *window);
707
708 static void
709 on_modified_changed (GtkTextBuffer *buffer, PsppireWindow *window)
710 {
711   if (gtk_text_buffer_get_modified (buffer))
712     psppire_window_set_unsaved (window);
713 }
714
715 static void undo_redo_update (PsppireSyntaxWindow *window);
716 static void undo_last_edit (PsppireSyntaxWindow *window);
717 static void redo_last_edit (PsppireSyntaxWindow *window);
718
719 static void
720 on_text_changed (GtkTextBuffer *buffer, PsppireSyntaxWindow *window)
721 {
722   gtk_statusbar_pop (GTK_STATUSBAR (window->sb), window->text_context);
723   undo_redo_update (window);
724 }
725
726 static void
727 psppire_syntax_window_init (PsppireSyntaxWindow *window)
728 {
729   GtkBuilder *xml = builder_new ("syntax-editor.ui");
730   GtkWidget *box = gtk_vbox_new (FALSE, 0);
731
732   GtkWidget *menubar = get_widget_assert (xml, "menubar");
733   GtkWidget *sw = get_widget_assert (xml, "scrolledwindow8");
734
735   GtkWidget *text_view = get_widget_assert (xml, "syntax_text_view");
736
737   PsppireSyntaxWindowClass *class
738     = PSPPIRE_SYNTAX_WINDOW_CLASS (G_OBJECT_GET_CLASS (window));
739
740   GtkClipboard *clip_selection = gtk_widget_get_clipboard (GTK_WIDGET (window), GDK_SELECTION_CLIPBOARD);
741   GtkClipboard *clip_primary =   gtk_widget_get_clipboard (GTK_WIDGET (window), GDK_SELECTION_PRIMARY);
742
743   window->print_settings = NULL;
744   window->undo_menuitem = get_action_assert (xml, "edit_undo");
745   window->redo_menuitem = get_action_assert (xml, "edit_redo");
746
747   if (class->lan)
748     window->buffer = gtk_source_buffer_new_with_language (class->lan);
749   else
750     window->buffer = gtk_source_buffer_new (NULL);
751
752   gtk_text_view_set_buffer (GTK_TEXT_VIEW (text_view), GTK_TEXT_BUFFER (window->buffer));
753
754   g_object_set (window->buffer,
755                 "highlight-matching-brackets", TRUE,
756                 NULL);
757
758   g_object_set (text_view,
759                 "show-line-numbers", TRUE,
760                 "show-line-marks", TRUE,
761                 "auto-indent", TRUE,
762                 "indent-width", 4,
763                 "highlight-current-line", TRUE,
764                 NULL);
765
766   window->encoding = NULL;
767
768   window->cliptext = NULL;
769   window->dispose_has_run = FALSE;
770
771   window->edit_delete = get_action_assert (xml, "edit_delete");
772   window->edit_copy = get_action_assert (xml, "edit_copy");
773   window->edit_cut = get_action_assert (xml, "edit_cut");
774   window->edit_paste = get_action_assert (xml, "edit_paste");
775
776   window->buffer = GTK_SOURCE_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW (text_view)));
777
778   window->sb = get_widget_assert (xml, "statusbar2");
779   window->text_context = gtk_statusbar_get_context_id (GTK_STATUSBAR (window->sb), "Text Context");
780
781   g_signal_connect (window->buffer, "changed", 
782                     G_CALLBACK (on_text_changed), window);
783
784   g_signal_connect (window->buffer, "modified-changed", 
785                     G_CALLBACK (on_modified_changed), window);
786
787   g_signal_connect_swapped (get_action_assert (xml, "file_print"), "activate",
788                             G_CALLBACK (psppire_syntax_window_print), window);
789
790
791   g_signal_connect_swapped (window->undo_menuitem,
792                             "activate",
793                             G_CALLBACK (undo_last_edit),
794                             window);
795
796   g_signal_connect_swapped (window->redo_menuitem,
797                             "activate",
798                             G_CALLBACK (redo_last_edit),
799                             window);
800
801   undo_redo_update (window);
802
803   window->sel_handler = g_signal_connect_swapped (clip_primary, "owner-change", 
804                                                    G_CALLBACK (selection_changed), window);
805
806   window->ps_handler = g_signal_connect (clip_selection, "owner-change", 
807                                           G_CALLBACK (set_paste_sensitivity), window);
808
809   connect_help (xml);
810
811   gtk_container_add (GTK_CONTAINER (window), box);
812
813   g_object_ref (menubar);
814
815   g_object_ref (sw);
816
817   g_object_ref (window->sb);
818
819   gtk_box_pack_start (GTK_BOX (box), menubar, FALSE, TRUE, 0);
820   gtk_box_pack_start (GTK_BOX (box), sw, TRUE, TRUE, 0);
821   gtk_box_pack_start (GTK_BOX (box), window->sb, FALSE, TRUE, 0);
822
823   gtk_widget_show_all (box);
824
825   g_signal_connect_swapped (get_action_assert (xml,"file_new_syntax"), "activate", G_CALLBACK (create_syntax_window), NULL);
826
827   g_signal_connect (get_action_assert (xml,"file_new_data"),
828                     "activate",
829                     G_CALLBACK (create_data_window),
830                     window);
831
832   g_signal_connect_swapped (get_action_assert (xml, "file_open"),
833                     "activate",
834                     G_CALLBACK (psppire_window_open),
835                     window);
836
837   g_signal_connect_swapped (get_action_assert (xml, "file_save"),
838                     "activate",
839                     G_CALLBACK (psppire_window_save),
840                     window);
841
842   g_signal_connect_swapped (get_action_assert (xml, "file_save_as"),
843                     "activate",
844                     G_CALLBACK (psppire_window_save_as),
845                     window);
846
847   g_signal_connect (get_action_assert (xml,"file_quit"),
848                     "activate",
849                     G_CALLBACK (on_quit),
850                     window);
851
852   g_signal_connect_swapped (window->edit_delete,
853                     "activate",
854                     G_CALLBACK (on_edit_delete),
855                     window);
856
857   g_signal_connect_swapped (window->edit_copy,
858                     "activate",
859                     G_CALLBACK (on_edit_copy),
860                     window);
861
862   g_signal_connect_swapped (window->edit_cut,
863                     "activate",
864                     G_CALLBACK (on_edit_cut),
865                     window);
866
867   g_signal_connect_swapped (window->edit_paste,
868                     "activate",
869                     G_CALLBACK (on_edit_paste),
870                     window);
871
872   g_signal_connect (get_action_assert (xml,"run_all"),
873                     "activate",
874                     G_CALLBACK (on_run_all),
875                     window);
876
877   g_signal_connect (get_action_assert (xml,"run_selection"),
878                     "activate",
879                     G_CALLBACK (on_run_selection),
880                     window);
881
882   g_signal_connect (get_action_assert (xml,"run_current_line"),
883                     "activate",
884                     G_CALLBACK (on_run_current_line),
885                     window);
886
887   g_signal_connect (get_action_assert (xml,"run_to_end"),
888                     "activate",
889                     G_CALLBACK (on_run_to_end),
890                     window);
891
892   g_signal_connect (get_action_assert (xml,"windows_minimise_all"),
893                     "activate",
894                     G_CALLBACK (psppire_window_minimise_all), NULL);
895
896
897
898
899
900   {
901   GtkUIManager *uim = GTK_UI_MANAGER (get_object_assert (xml, "uimanager1", GTK_TYPE_UI_MANAGER));
902
903   merge_help_menu (uim);
904
905   PSPPIRE_WINDOW (window)->menu =
906     GTK_MENU_SHELL (gtk_ui_manager_get_widget (uim,"/ui/menubar/windows/windows_minimise_all")->parent);
907   }
908
909   g_object_unref (xml);
910 }
911
912
913
914
915
916 GtkWidget*
917 psppire_syntax_window_new (const char *encoding)
918 {
919   return GTK_WIDGET (g_object_new (psppire_syntax_window_get_type (),
920                                    "description", _("Syntax Editor"),
921                                    "encoding", encoding,
922                                    NULL));
923 }
924
925 static void
926 error_dialog (GtkWindow *w, const gchar *filename,  GError *err)
927 {
928   gchar *fn = g_filename_display_basename (filename);
929
930   GtkWidget *dialog =
931     gtk_message_dialog_new (w,
932                             GTK_DIALOG_DESTROY_WITH_PARENT,
933                             GTK_MESSAGE_ERROR,
934                             GTK_BUTTONS_CLOSE,
935                             _("Cannot load syntax file `%s'"),
936                             fn);
937
938   g_free (fn);
939
940   g_object_set (dialog, "icon-name", "psppicon", NULL);
941
942   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
943                                             "%s", err->message);
944
945   gtk_dialog_run (GTK_DIALOG (dialog));
946
947   gtk_widget_destroy (dialog);
948 }
949
950 /*
951   Loads the buffer from the file called FILENAME
952 */
953 gboolean
954 syntax_load (PsppireWindow *window, const gchar *filename)
955 {
956   GError *err = NULL;
957   gchar *text_locale = NULL;
958   gchar *text_utf8 = NULL;
959   gsize len_locale = -1;
960   gsize len_utf8 = -1;
961   GtkTextIter iter;
962   PsppireSyntaxWindow *sw = PSPPIRE_SYNTAX_WINDOW (window);
963   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (sw->buffer);
964   gchar *encoding;
965   char *mime_type;
966
967   /* FIXME: What if it's a very big file ? */
968   if ( ! g_file_get_contents (filename, &text_locale, &len_locale, &err) )
969     {
970       error_dialog (GTK_WINDOW (window), filename, err);
971       g_clear_error (&err);
972       return FALSE;
973     }
974
975   /* Determine the file's encoding and update sw->encoding.  (The ordering is
976      important here because encoding_guess_whole_file() often returns its
977      argument instead of a copy of it.) */
978   encoding = g_strdup (encoding_guess_whole_file (sw->encoding, text_locale,
979                                                   len_locale));
980   g_free (sw->encoding);
981   sw->encoding = encoding;
982
983   text_utf8 = recode_substring_pool ("UTF-8", encoding,
984                                      ss_buffer (text_locale, len_locale),
985                                      NULL).string;
986   free (text_locale);
987
988   if ( text_utf8 == NULL )
989     {
990       error_dialog (GTK_WINDOW (window), filename, err);
991       g_clear_error (&err);
992       return FALSE;
993     }
994
995   gtk_text_buffer_get_iter_at_line (buffer, &iter, 0);
996
997   gtk_text_buffer_insert (buffer, &iter, text_utf8, len_utf8);
998
999   gtk_text_buffer_set_modified (buffer, FALSE);
1000
1001   free (text_utf8);
1002
1003   mime_type = xasprintf ("text/x-spss-syntax; charset=%s", sw->encoding);
1004   add_most_recent (filename, mime_type);
1005   free (mime_type);
1006
1007   return TRUE;
1008 }
1009
1010 \f
1011
1012 static void
1013 psppire_syntax_window_iface_init (PsppireWindowIface *iface)
1014 {
1015   iface->save = syntax_save;
1016   iface->pick_filename = syntax_pick_filename;
1017   iface->load = syntax_load;
1018 }
1019
1020
1021 \f
1022
1023 static void
1024 undo_redo_update (PsppireSyntaxWindow *window)
1025 {
1026   gtk_action_set_sensitive (window->undo_menuitem,
1027                             gtk_source_buffer_can_undo (window->buffer));
1028
1029   gtk_action_set_sensitive (window->redo_menuitem,
1030                             gtk_source_buffer_can_redo (window->buffer));
1031 }
1032
1033 static void
1034 undo_last_edit (PsppireSyntaxWindow *window)
1035 {
1036   gtk_source_buffer_undo (window->buffer);
1037   undo_redo_update (window);
1038 }
1039
1040 static void
1041 redo_last_edit (PsppireSyntaxWindow *window)
1042 {
1043   gtk_source_buffer_redo (window->buffer);
1044   undo_redo_update (window);
1045 }
1046
1047
1048 \f
1049 /* Printing related stuff */
1050
1051
1052 static void
1053 begin_print (GtkPrintOperation *operation,
1054           GtkPrintContext   *context,
1055           PsppireSyntaxWindow *window)
1056 {
1057   window->compositor =
1058     gtk_source_print_compositor_new (window->buffer);
1059 }
1060
1061
1062 static void
1063 end_print (GtkPrintOperation *operation,
1064           GtkPrintContext   *context,
1065           PsppireSyntaxWindow *window)
1066 {
1067   g_object_unref (window->compositor);
1068   window->compositor = NULL;
1069 }
1070
1071
1072
1073 static gboolean
1074 paginate (GtkPrintOperation *operation,
1075           GtkPrintContext   *context,
1076           PsppireSyntaxWindow *window)
1077 {
1078   if (gtk_source_print_compositor_paginate (window->compositor, context))
1079     {
1080       gint n_pages = gtk_source_print_compositor_get_n_pages (window->compositor);
1081       gtk_print_operation_set_n_pages (operation, n_pages);
1082         
1083       return TRUE;
1084     }
1085
1086   return FALSE;
1087 }
1088
1089 static void
1090 draw_page (GtkPrintOperation *operation,
1091            GtkPrintContext   *context,
1092            gint               page_nr,
1093           PsppireSyntaxWindow *window)
1094 {
1095   gtk_source_print_compositor_draw_page (window->compositor, 
1096                                          context,
1097                                          page_nr);
1098 }
1099
1100
1101
1102 static void
1103 psppire_syntax_window_print (PsppireSyntaxWindow *window)
1104 {
1105   GtkPrintOperationResult res;
1106
1107   GtkPrintOperation *print = gtk_print_operation_new ();
1108
1109   if (window->print_settings != NULL) 
1110     gtk_print_operation_set_print_settings (print, window->print_settings);
1111
1112
1113   g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), window);
1114   g_signal_connect (print, "end_print", G_CALLBACK (end_print),     window);
1115   g_signal_connect (print, "draw_page", G_CALLBACK (draw_page),     window);
1116   g_signal_connect (print, "paginate", G_CALLBACK (paginate),       window);
1117
1118   res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
1119                                  GTK_WINDOW (window), NULL);
1120
1121   if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
1122     {
1123       if (window->print_settings != NULL)
1124         g_object_unref (window->print_settings);
1125       window->print_settings = g_object_ref (gtk_print_operation_get_print_settings (print));
1126     }
1127
1128   g_object_unref (print);
1129 }