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