Implemented Cut, Copy and Delete in the syntax editor
[pspp] / src / ui / gui / psppire-syntax-window.c
1 /* PSPPIRE - a graphical user interface for PSPP.
2    Copyright (C) 2008, 2009, 2010  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/gtksignal.h>
20 #include <gtk/gtkbox.h>
21 #include "executor.h"
22 #include "helper.h"
23
24 #include <libpspp/message.h>
25 #include <stdlib.h>
26
27 #include "psppire.h"
28 #include "psppire-syntax-window.h"
29
30 #include "psppire-data-window.h"
31 #include "psppire-window-register.h"
32 #include "psppire.h"
33 #include "help-menu.h"
34 #include "psppire-syntax-window.h"
35 #include "syntax-editor-source.h"
36 #include <language/lexer/lexer.h>
37
38 #include "xalloc.h"
39
40 #include <gettext.h>
41 #define _(msgid) gettext (msgid)
42 #define N_(msgid) msgid
43
44 static void psppire_syntax_window_base_finalize (PsppireSyntaxWindowClass *, gpointer);
45 static void psppire_syntax_window_base_init     (PsppireSyntaxWindowClass *class);
46 static void psppire_syntax_window_class_init    (PsppireSyntaxWindowClass *class);
47 static void psppire_syntax_window_init          (PsppireSyntaxWindow      *syntax_editor);
48
49
50 static void psppire_syntax_window_iface_init (PsppireWindowIface *iface);
51
52
53 GType
54 psppire_syntax_window_get_type (void)
55 {
56   static GType psppire_syntax_window_type = 0;
57
58   if (!psppire_syntax_window_type)
59     {
60       static const GTypeInfo psppire_syntax_window_info =
61       {
62         sizeof (PsppireSyntaxWindowClass),
63         (GBaseInitFunc) psppire_syntax_window_base_init,
64         (GBaseFinalizeFunc) psppire_syntax_window_base_finalize,
65         (GClassInitFunc)psppire_syntax_window_class_init,
66         (GClassFinalizeFunc) NULL,
67         NULL,
68         sizeof (PsppireSyntaxWindow),
69         0,
70         (GInstanceInitFunc) psppire_syntax_window_init,
71       };
72
73       static const GInterfaceInfo window_interface_info =
74         {
75           (GInterfaceInitFunc) psppire_syntax_window_iface_init,
76           NULL,
77           NULL
78         };
79
80       psppire_syntax_window_type =
81         g_type_register_static (PSPPIRE_TYPE_WINDOW, "PsppireSyntaxWindow",
82                                 &psppire_syntax_window_info, 0);
83
84       g_type_add_interface_static (psppire_syntax_window_type,
85                                    PSPPIRE_TYPE_WINDOW_MODEL,
86                                    &window_interface_info);
87     }
88
89   return psppire_syntax_window_type;
90 }
91
92 static GObjectClass *parent_class ;
93
94 static void
95 psppire_syntax_window_finalize (GObject *object)
96 {
97   if (G_OBJECT_CLASS (parent_class)->finalize)
98     (*G_OBJECT_CLASS (parent_class)->finalize) (object);
99 }
100
101
102 static void
103 psppire_syntax_window_class_init (PsppireSyntaxWindowClass *class)
104 {
105   parent_class = g_type_class_peek_parent (class);
106 }
107
108
109 static void
110 psppire_syntax_window_base_init (PsppireSyntaxWindowClass *class)
111 {
112   GObjectClass *object_class = G_OBJECT_CLASS (class);
113
114   object_class->finalize = psppire_syntax_window_finalize;
115 }
116
117
118
119 static void
120 psppire_syntax_window_base_finalize (PsppireSyntaxWindowClass *class,
121                                      gpointer class_data)
122 {
123 }
124
125
126 static void
127 editor_execute_syntax (const PsppireSyntaxWindow *sw, GtkTextIter start,
128                        GtkTextIter stop)
129 {
130   PsppireWindow *win = PSPPIRE_WINDOW (sw);
131   const gchar *name = psppire_window_get_filename (win);
132   execute_syntax (create_syntax_editor_source (sw->buffer, start, stop, name));
133 }
134
135
136 \f
137
138 /* Delete the currently selected text */
139 static void
140 on_edit_delete (PsppireSyntaxWindow *sw)
141 {
142   GtkTextIter begin, end;
143   
144   if ( gtk_text_buffer_get_selection_bounds (sw->buffer, &begin, &end) )
145     gtk_text_buffer_delete (sw->buffer, &begin, &end);
146 }
147
148 /* The syntax editor's clipboard deals only with text */
149 enum {
150   SELECT_FMT_NULL,
151   SELECT_FMT_TEXT,
152 };
153
154
155 /* The callback which runs when something request clipboard data */
156 static void
157 clipboard_get_cb (GtkClipboard     *clipboard,
158                   GtkSelectionData *selection_data,
159                   guint             info,
160                   gpointer          data)
161 {
162   PsppireSyntaxWindow *sw = data;
163   g_assert (info == SELECT_FMT_TEXT);
164
165   gtk_selection_data_set (selection_data, selection_data->target,
166                           8,
167                           (const guchar *) sw->cliptext, strlen (sw->cliptext));
168
169 }
170
171 static void
172 clipboard_clear_cb (GtkClipboard *clipboard,
173                     gpointer data)
174 {
175   PsppireSyntaxWindow *sw = data;
176   g_free (sw->cliptext);
177   sw->cliptext = NULL;
178 }
179
180
181 static const GtkTargetEntry targets[] = {
182   { "UTF8_STRING",   0, SELECT_FMT_TEXT },
183   { "STRING",        0, SELECT_FMT_TEXT },
184   { "TEXT",          0, SELECT_FMT_TEXT },
185   { "COMPOUND_TEXT", 0, SELECT_FMT_TEXT },
186   { "text/plain;charset=utf-8", 0, SELECT_FMT_TEXT },
187   { "text/plain",    0, SELECT_FMT_TEXT },
188 };
189
190
191 /*
192   Store a clip containing the currently selected text.
193   Returns true iff something was set.
194   As a side effect, begin and end will be set to indicate
195   the limits of the selected text.
196 */
197 static gboolean
198 set_clip (PsppireSyntaxWindow *sw, GtkTextIter *begin, GtkTextIter *end)
199 {
200   GtkClipboard *clipboard ;
201
202   if ( ! gtk_text_buffer_get_selection_bounds (sw->buffer, begin, end) )
203     return FALSE;
204
205   g_free (sw->cliptext);
206   sw->cliptext = gtk_text_buffer_get_text  (sw->buffer, begin, end, FALSE);
207
208   clipboard =
209     gtk_widget_get_clipboard (GTK_WIDGET (sw), GDK_SELECTION_CLIPBOARD);
210
211   if (!gtk_clipboard_set_with_owner (clipboard, targets,
212                                      G_N_ELEMENTS (targets),
213                                      clipboard_get_cb, clipboard_clear_cb,
214                                      G_OBJECT (sw)))
215     clipboard_clear_cb (clipboard, sw);
216
217   return TRUE;
218 }
219
220 static void
221 on_edit_cut (PsppireSyntaxWindow *sw)
222 {
223   GtkTextIter begin, end;
224   
225   if ( set_clip (sw, &begin, &end))
226     gtk_text_buffer_delete (sw->buffer, &begin, &end);
227 }
228
229 static void
230 on_edit_copy (PsppireSyntaxWindow *sw)
231 {
232   GtkTextIter begin, end;
233
234   if ( ! set_clip (sw, &begin, &end))
235     return;
236 }
237
238 \f
239
240 /* Parse and execute all the text in the buffer */
241 static void
242 on_run_all (GtkMenuItem *menuitem, gpointer user_data)
243 {
244   GtkTextIter begin, end;
245   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
246
247   gtk_text_buffer_get_iter_at_offset (se->buffer, &begin, 0);
248   gtk_text_buffer_get_iter_at_offset (se->buffer, &end, -1);
249
250   editor_execute_syntax (se, begin, end);
251 }
252
253 /* Parse and execute the currently selected text */
254 static void
255 on_run_selection (GtkMenuItem *menuitem, gpointer user_data)
256 {
257   GtkTextIter begin, end;
258   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
259
260   if ( gtk_text_buffer_get_selection_bounds (se->buffer, &begin, &end) )
261     editor_execute_syntax (se, begin, end);
262 }
263
264
265 /* Parse and execute the from the current line, to the end of the
266    buffer */
267 static void
268 on_run_to_end (GtkMenuItem *menuitem, gpointer user_data)
269 {
270   GtkTextIter begin, end;
271   GtkTextIter here;
272   gint line;
273
274   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
275
276   /* Get the current line */
277   gtk_text_buffer_get_iter_at_mark (se->buffer,
278                                     &here,
279                                     gtk_text_buffer_get_insert (se->buffer)
280                                     );
281
282   line = gtk_text_iter_get_line (&here) ;
283
284   /* Now set begin and end to the start of this line, and end of buffer
285      respectively */
286   gtk_text_buffer_get_iter_at_line (se->buffer, &begin, line);
287   gtk_text_buffer_get_iter_at_line (se->buffer, &end, -1);
288
289   editor_execute_syntax (se, begin, end);
290 }
291
292
293
294 /* Parse and execute the current line */
295 static void
296 on_run_current_line (GtkMenuItem *menuitem, gpointer user_data)
297 {
298   GtkTextIter begin, end;
299   GtkTextIter here;
300   gint line;
301
302   PsppireSyntaxWindow *se = PSPPIRE_SYNTAX_WINDOW (user_data);
303
304   /* Get the current line */
305   gtk_text_buffer_get_iter_at_mark (se->buffer,
306                                     &here,
307                                     gtk_text_buffer_get_insert (se->buffer)
308                                     );
309
310   line = gtk_text_iter_get_line (&here) ;
311
312   /* Now set begin and end to the start of this line, and start of
313      following line respectively */
314   gtk_text_buffer_get_iter_at_line (se->buffer, &begin, line);
315   gtk_text_buffer_get_iter_at_line (se->buffer, &end, line + 1);
316
317   editor_execute_syntax (se, begin, end);
318 }
319
320
321
322 /* Append ".sps" to FILENAME if necessary.
323    The returned result must be freed when no longer required.
324  */
325 static gchar *
326 append_suffix (const gchar *filename)
327 {
328   if ( ! g_str_has_suffix (filename, ".sps" ) &&
329        ! g_str_has_suffix (filename, ".SPS" ) )
330     {
331       return g_strdup_printf ("%s.sps", filename);
332     }
333
334   return xstrdup (filename);
335 }
336
337 /*
338   Save BUFFER to the file called FILENAME.
339   FILENAME must be encoded in Glib filename encoding.
340   If successful, clears the buffer's modified flag.
341 */
342 static gboolean
343 save_editor_to_file (PsppireSyntaxWindow *se,
344                      const gchar *filename,
345                      GError **err)
346 {
347   GtkTextBuffer *buffer = se->buffer;
348   gboolean result ;
349   GtkTextIter start, stop;
350   gchar *text;
351
352   gchar *suffixedname;
353   g_assert (filename);
354
355   suffixedname = append_suffix (filename);
356
357   gtk_text_buffer_get_iter_at_line (buffer, &start, 0);
358   gtk_text_buffer_get_iter_at_offset (buffer, &stop, -1);
359
360   text = gtk_text_buffer_get_text (buffer, &start, &stop, FALSE);
361
362   result =  g_file_set_contents (suffixedname, text, -1, err);
363
364   g_free (suffixedname);
365
366   if ( result )
367     {
368       char *fn = g_filename_display_name (filename);
369       gchar *msg = g_strdup_printf (_("Saved file \"%s\""), fn);
370       g_free (fn);
371       gtk_statusbar_push (GTK_STATUSBAR (se->sb), se->text_context, msg);
372       gtk_text_buffer_set_modified (buffer, FALSE);
373       g_free (msg);
374     }
375
376   return result;
377 }
378
379
380 /* Callback for the File->SaveAs menuitem */
381 static void
382 syntax_save_as (PsppireWindow *se)
383 {
384   GtkFileFilter *filter;
385   gint response;
386
387   GtkWidget *dialog =
388     gtk_file_chooser_dialog_new (_("Save Syntax"),
389                                  GTK_WINDOW (se),
390                                  GTK_FILE_CHOOSER_ACTION_SAVE,
391                                  GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
392                                  GTK_STOCK_SAVE,   GTK_RESPONSE_ACCEPT,
393                                  NULL);
394
395   filter = gtk_file_filter_new ();
396   gtk_file_filter_set_name (filter, _("Syntax Files (*.sps) "));
397   gtk_file_filter_add_pattern (filter, "*.sps");
398   gtk_file_filter_add_pattern (filter, "*.SPS");
399   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
400
401   filter = gtk_file_filter_new ();
402   gtk_file_filter_set_name (filter, _("All Files"));
403   gtk_file_filter_add_pattern (filter, "*");
404   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter);
405
406   gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog),
407                                                   TRUE);
408   response = gtk_dialog_run (GTK_DIALOG (dialog));
409
410   if ( response == GTK_RESPONSE_ACCEPT )
411     {
412       GError *err = NULL;
413       char *filename =
414         gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog) );
415
416       if ( ! save_editor_to_file (PSPPIRE_SYNTAX_WINDOW (se), filename, &err) )
417         {
418           msg ( ME, "%s", err->message );
419           g_error_free (err);
420         }
421
422       free (filename);
423     }
424
425   gtk_widget_destroy (dialog);
426 }
427
428
429 /* Callback for the File->Save menuitem */
430 static void
431 syntax_save (PsppireWindow *se)
432 {
433   const gchar *filename = psppire_window_get_filename (se);
434
435   if ( filename == NULL )
436     syntax_save_as (se);
437   else
438     {
439       GError *err = NULL;
440       save_editor_to_file (PSPPIRE_SYNTAX_WINDOW (se), filename, &err);
441       if ( err )
442         {
443           msg (ME, "%s", err->message);
444           g_error_free (err);
445         }
446     }
447 }
448
449
450 /* Callback for the File->Quit menuitem */
451 static gboolean
452 on_quit (GtkMenuItem *menuitem, gpointer    user_data)
453 {
454   psppire_quit ();
455
456   return FALSE;
457 }
458
459
460 void
461 create_syntax_window (void)
462 {
463   GtkWidget *w = psppire_syntax_window_new ();
464   gtk_widget_show (w);
465 }
466
467 void
468 open_syntax_window (const char *file_name)
469 {
470   GtkWidget *se = psppire_syntax_window_new ();
471
472   if ( psppire_window_load (PSPPIRE_WINDOW (se), file_name) )
473     gtk_widget_show (se);
474   else
475     gtk_widget_destroy (se);
476 }
477
478 static void
479 on_text_changed (GtkTextBuffer *buffer, PsppireSyntaxWindow *window)
480 {
481   gtk_statusbar_pop (GTK_STATUSBAR (window->sb), window->text_context);
482 }
483
484 static void
485 on_modified_changed (GtkTextBuffer *buffer, PsppireWindow *window)
486 {
487   if (gtk_text_buffer_get_modified (buffer))
488     psppire_window_set_unsaved (window);
489 }
490
491 extern struct source_stream *the_source_stream ;
492
493 static void
494 psppire_syntax_window_init (PsppireSyntaxWindow *window)
495 {
496   GtkBuilder *xml = builder_new ("syntax-editor.ui");
497   GtkWidget *box = gtk_vbox_new (FALSE, 0);
498
499   GtkWidget *menubar = get_widget_assert (xml, "menubar");
500   GtkWidget *sw = get_widget_assert (xml, "scrolledwindow8");
501
502
503   GtkWidget *text_view = get_widget_assert (xml, "syntax_text_view");
504
505   window->cliptext = NULL;
506
507   window->buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (text_view));
508   window->lexer = lex_create (the_source_stream);
509
510   window->sb = get_widget_assert (xml, "statusbar2");
511   window->text_context = gtk_statusbar_get_context_id (GTK_STATUSBAR (window->sb), "Text Context");
512
513   g_signal_connect (window->buffer, "changed", G_CALLBACK (on_text_changed), window);
514
515   g_signal_connect (window->buffer, "modified-changed",
516                     G_CALLBACK (on_modified_changed), window);
517
518   connect_help (xml);
519
520   gtk_container_add (GTK_CONTAINER (window), box);
521
522   g_object_ref (menubar);
523
524   g_object_ref (sw);
525
526   g_object_ref (window->sb);
527
528
529   gtk_box_pack_start (GTK_BOX (box), menubar, FALSE, TRUE, 0);
530   gtk_box_pack_start (GTK_BOX (box), sw, TRUE, TRUE, 0);
531   gtk_box_pack_start (GTK_BOX (box), window->sb, FALSE, TRUE, 0);
532
533   gtk_widget_show_all (box);
534
535   g_signal_connect_swapped (get_action_assert (xml,"file_new_syntax"), "activate", G_CALLBACK (create_syntax_window), NULL);
536
537 #if 0
538   g_signal_connect (get_action_assert (xml,"file_new_data"),
539                     "activate",
540                     G_CALLBACK (create_data_window),
541                     window);
542 #endif
543
544   g_signal_connect_swapped (get_action_assert (xml, "file_save"),
545                     "activate",
546                     G_CALLBACK (syntax_save),
547                     window);
548
549   g_signal_connect_swapped (get_action_assert (xml, "file_save_as"),
550                     "activate",
551                     G_CALLBACK (syntax_save_as),
552                     window);
553
554   g_signal_connect (get_action_assert (xml,"file_quit"),
555                     "activate",
556                     G_CALLBACK (on_quit),
557                     window);
558
559
560   g_signal_connect_swapped (get_action_assert (xml, "edit_delete"),
561                     "activate",
562                     G_CALLBACK (on_edit_delete),
563                     window);
564
565   g_signal_connect_swapped (get_action_assert (xml, "edit_copy"),
566                     "activate",
567                     G_CALLBACK (on_edit_copy),
568                     window);
569
570   g_signal_connect_swapped (get_action_assert (xml, "edit_cut"),
571                     "activate",
572                     G_CALLBACK (on_edit_cut),
573                     window);
574
575   g_signal_connect (get_action_assert (xml,"run_all"),
576                     "activate",
577                     G_CALLBACK (on_run_all),
578                     window);
579
580
581   g_signal_connect (get_action_assert (xml,"run_selection"),
582                     "activate",
583                     G_CALLBACK (on_run_selection),
584                     window);
585
586   g_signal_connect (get_action_assert (xml,"run_current_line"),
587                     "activate",
588                     G_CALLBACK (on_run_current_line),
589                     window);
590
591   g_signal_connect (get_action_assert (xml,"run_to_end"),
592                     "activate",
593                     G_CALLBACK (on_run_to_end),
594                     window);
595
596   g_signal_connect (get_action_assert (xml,"windows_minimise_all"),
597                     "activate",
598                     G_CALLBACK (psppire_window_minimise_all), NULL);
599
600
601   {
602   GtkUIManager *uim = GTK_UI_MANAGER (get_object_assert (xml, "uimanager1", GTK_TYPE_UI_MANAGER));
603
604   merge_help_menu (uim);
605
606   PSPPIRE_WINDOW (window)->menu =
607     GTK_MENU_SHELL (gtk_ui_manager_get_widget (uim,"/ui/menubar/windows/windows_minimise_all")->parent);
608   }
609
610   g_object_unref (xml);
611 }
612
613
614 GtkWidget*
615 psppire_syntax_window_new (void)
616 {
617   return GTK_WIDGET (g_object_new (psppire_syntax_window_get_type (),
618                                    "filename", "Syntax",
619                                    "description", _("Syntax Editor"),
620                                    NULL));
621 }
622
623 static void
624 error_dialog (GtkWindow *w, const gchar *filename,  GError *err)
625 {
626   gchar *fn = g_filename_display_basename (filename);
627
628   GtkWidget *dialog =
629     gtk_message_dialog_new (w,
630                             GTK_DIALOG_DESTROY_WITH_PARENT,
631                             GTK_MESSAGE_ERROR,
632                             GTK_BUTTONS_CLOSE,
633                             _("Cannot load syntax file '%s'"),
634                             fn);
635
636   g_free (fn);
637
638   g_object_set (dialog, "icon-name", "psppicon", NULL);
639
640   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
641                                             "%s", err->message);
642
643   gtk_dialog_run (GTK_DIALOG (dialog));
644
645   gtk_widget_destroy (dialog);
646 }
647
648 /*
649   Loads the buffer from the file called FILENAME
650 */
651 gboolean
652 syntax_load (PsppireWindow *window, const gchar *filename)
653 {
654   GError *err = NULL;
655   gchar *text_locale = NULL;
656   gchar *text_utf8 = NULL;
657   gsize len_locale = -1;
658   gsize len_utf8 = -1;
659   GtkTextIter iter;
660   PsppireSyntaxWindow *sw = PSPPIRE_SYNTAX_WINDOW (window);
661
662   /* FIXME: What if it's a very big file ? */
663   if ( ! g_file_get_contents (filename, &text_locale, &len_locale, &err) )
664     {
665       error_dialog (GTK_WINDOW (window), filename, err);
666       g_clear_error (&err);
667       return FALSE;
668     }
669
670   text_utf8 = g_locale_to_utf8 (text_locale, len_locale, NULL, &len_utf8, &err);
671
672   free (text_locale);
673
674   if ( text_utf8 == NULL )
675     {
676       error_dialog (GTK_WINDOW (window), filename, err);
677       g_clear_error (&err);
678       return FALSE;
679     }
680
681   gtk_text_buffer_get_iter_at_line (sw->buffer, &iter, 0);
682
683   gtk_text_buffer_insert (sw->buffer, &iter, text_utf8, len_utf8);
684
685   gtk_text_buffer_set_modified (sw->buffer, FALSE);
686
687   free (text_utf8);
688
689   return TRUE;
690 }
691
692 \f
693
694 static void
695 psppire_syntax_window_iface_init (PsppireWindowIface *iface)
696 {
697   iface->save = syntax_save;
698   iface->load = syntax_load;
699 }