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