Use the msg function to report errors wherever possible.
[pspp] / src / ui / gui / text-data-import-dialog.c
1 /* PSPPIRE - a graphical user interface for PSPP.
2    Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013  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 "ui/gui/text-data-import-dialog.h"
20
21 #include "page-intro.h"
22 #include "page-sheet-spec.h"
23 #include "page-first-line.h"
24 #include "page-separators.h"
25 #include "page-formats.h"
26
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <gtk/gtk.h>
30 #include <limits.h>
31 #include <stdlib.h>
32 #include <sys/stat.h>
33
34 #include "data/data-in.h"
35 #include "data/data-out.h"
36 #include "data/format-guesser.h"
37 #include "data/value-labels.h"
38 #include "language/data-io/data-parser.h"
39 #include "language/lexer/lexer.h"
40 #include "libpspp/assertion.h"
41 #include "libpspp/i18n.h"
42 #include "libpspp/line-reader.h"
43 #include "libpspp/message.h"
44 #include "ui/gui/checkbox-treeview.h"
45 #include "ui/gui/dialog-common.h"
46 #include "ui/gui/executor.h"
47 #include "ui/gui/helper.h"
48 #include "ui/gui/builder-wrapper.h"
49 #include "ui/gui/pspp-sheet-selection.h"
50 #include "ui/gui/pspp-sheet-view.h"
51 #include "ui/gui/psppire-data-window.h"
52 #include "ui/gui/psppire-dialog.h"
53 #include "ui/gui/psppire-encoding-selector.h"
54 #include "ui/gui/psppire-empty-list-store.h"
55 #include "ui/gui/psppire-var-sheet.h"
56 #include "ui/gui/psppire-scanf.h"
57 #include "ui/syntax-gen.h"
58
59 #include "gl/intprops.h"
60 #include "gl/xalloc.h"
61
62 #include "gettext.h"
63 #define _(msgid) gettext (msgid)
64 #define N_(msgid) msgid
65
66 struct import_assistant;
67
68 static void apply_dict (const struct dictionary *, struct string *);
69 static char *generate_syntax (const struct import_assistant *);
70
71 static void add_line_number_column (const struct import_assistant *,
72                                     PsppSheetView *);
73
74 /* Pops up the Text Data Import assistant. */
75 void
76 text_data_import_assistant (PsppireDataWindow *dw)
77 {
78   GtkWindow *parent_window = GTK_WINDOW (dw);
79   struct import_assistant *ia = init_assistant (parent_window);
80   struct sheet_spec_page *ssp ;
81
82   if (!init_file (ia, parent_window))
83     {
84       free (ia);
85       return;
86     }
87
88   ssp = ia->sheet_spec;
89
90   if (ia->spreadsheet)
91     {
92       ia->sheet_spec = sheet_spec_page_create (ia);
93     }
94   else
95     {
96       ia->intro = intro_page_create (ia);
97       ia->first_line = first_line_page_create (ia);
98       ia->separators = separators_page_create (ia);
99     }
100   ia->formats = formats_page_create (ia);
101
102   gtk_widget_show_all (GTK_WIDGET (ia->asst.assistant));
103
104   ia->asst.main_loop = g_main_loop_new (NULL, false);
105
106   {  
107   /*
108     Instead of this block,
109     A simple     g_main_loop_run (ia->asst.main_loop);  should work here.  But it seems to crash.
110     I have no idea why.
111   */
112     GMainContext *ctx = g_main_loop_get_context (ia->asst.main_loop);
113     ia->asst.loop_done = false;
114     while (! ia->asst.loop_done)
115       {
116         g_main_context_iteration (ctx, TRUE);
117       }
118   }
119   g_main_loop_unref (ia->asst.main_loop);
120
121   switch (ia->asst.response)
122     {
123     case GTK_RESPONSE_APPLY:
124       {
125         gchar *fn = g_path_get_basename (ia->file.file_name);
126         open_data_window (PSPPIRE_WINDOW (dw), fn, generate_syntax (ia));
127         g_free (fn);
128       }
129       break;
130     case PSPPIRE_RESPONSE_PASTE:
131       free (paste_syntax_to_window (generate_syntax (ia)));
132       break;
133     default:
134       break;
135     }
136
137   if (ssp) 
138     {
139       destroy_formats_page (ia);
140       destroy_separators_page (ia);
141     }
142
143   destroy_assistant (ia);
144   destroy_file (ia);
145   free (ia);
146 }
147
148 /* Emits PSPP syntax to S that applies the dictionary attributes
149    (such as missing values and value labels) of the variables in
150    DICT.  */
151 static void
152 apply_dict (const struct dictionary *dict, struct string *s)
153 {
154   size_t var_cnt = dict_get_var_cnt (dict);
155   size_t i;
156
157   for (i = 0; i < var_cnt; i++)
158     {
159       struct variable *var = dict_get_var (dict, i);
160       const char *name = var_get_name (var);
161       enum val_type type = var_get_type (var);
162       int width = var_get_width (var);
163       enum measure measure = var_get_measure (var);
164       enum var_role role = var_get_role (var);
165       enum alignment alignment = var_get_alignment (var);
166       const struct fmt_spec *format = var_get_print_format (var);
167
168       if (var_has_missing_values (var))
169         {
170           const struct missing_values *mv = var_get_missing_values (var);
171           size_t j;
172
173           syntax_gen_pspp (s, "MISSING VALUES %ss (", name);
174           for (j = 0; j < mv_n_values (mv); j++)
175             {
176               if (j)
177                 ds_put_cstr (s, ", ");
178               syntax_gen_value (s, mv_get_value (mv, j), width, format);
179             }
180
181           if (mv_has_range (mv))
182             {
183               double low, high;
184               if (mv_has_value (mv))
185                 ds_put_cstr (s, ", ");
186               mv_get_range (mv, &low, &high);
187               syntax_gen_num_range (s, low, high, format);
188             }
189           ds_put_cstr (s, ").\n");
190         }
191       if (var_has_value_labels (var))
192         {
193           const struct val_labs *vls = var_get_value_labels (var);
194           const struct val_lab **labels = val_labs_sorted (vls);
195           size_t n_labels = val_labs_count (vls);
196           size_t i;
197
198           syntax_gen_pspp (s, "VALUE LABELS %ss", name);
199           for (i = 0; i < n_labels; i++)
200             {
201               const struct val_lab *vl = labels[i];
202               ds_put_cstr (s, "\n  ");
203               syntax_gen_value (s, &vl->value, width, format);
204               ds_put_byte (s, ' ');
205               syntax_gen_string (s, ss_cstr (val_lab_get_escaped_label (vl)));
206             }
207           free (labels);
208           ds_put_cstr (s, ".\n");
209         }
210       if (var_has_label (var))
211         syntax_gen_pspp (s, "VARIABLE LABELS %ss %sq.\n",
212                          name, var_get_label (var));
213       if (measure != var_default_measure (type))
214         syntax_gen_pspp (s, "VARIABLE LEVEL %ss (%ss).\n",
215                          name, measure_to_syntax (measure));
216       if (role != ROLE_INPUT)
217         syntax_gen_pspp (s, "VARIABLE ROLE /%ss %ss.\n",
218                          var_role_to_syntax (role), name);
219       if (alignment != var_default_alignment (type))
220         syntax_gen_pspp (s, "VARIABLE ALIGNMENT %ss (%ss).\n",
221                          name, alignment_to_syntax (alignment));
222       if (var_get_display_width (var) != var_default_display_width (width))
223         syntax_gen_pspp (s, "VARIABLE WIDTH %ss (%d).\n",
224                          name, var_get_display_width (var));
225     }
226 }
227
228 /* Generates and returns PSPP syntax to execute the import
229    operation described by IA.  The caller must free the syntax
230    with free(). */
231 static char *
232 generate_syntax (const struct import_assistant *ia)
233 {
234   struct string s = DS_EMPTY_INITIALIZER;
235
236   if (ia->spreadsheet == NULL)
237     {
238       syntax_gen_pspp (&s,
239                        "GET DATA"
240                        "\n  /TYPE=TXT"
241                        "\n  /FILE=%sq\n",
242                        ia->file.file_name);
243       if (ia->file.encoding && strcmp (ia->file.encoding, "Auto"))
244         syntax_gen_pspp (&s, "  /ENCODING=%sq\n", ia->file.encoding);
245
246       intro_append_syntax (ia->intro, &s);
247
248
249       ds_put_cstr (&s,
250                    "  /ARRANGEMENT=DELIMITED\n"
251                    "  /DELCASE=LINE\n");
252
253       first_line_append_syntax (ia, &s);
254       separators_append_syntax (ia, &s);
255       formats_append_syntax (ia, &s);
256       apply_dict (ia->dict, &s);
257     }
258   else
259     {
260       return sheet_spec_gen_syntax (ia);
261     }
262   
263   return ds_cstr (&s);
264 }
265
266
267
268 static void render_input_cell (PsppSheetViewColumn *tree_column,
269                                GtkCellRenderer *cell,
270                                GtkTreeModel *model, GtkTreeIter *iter,
271                                gpointer ia);
272
273 static gboolean on_query_input_tooltip (GtkWidget *widget, gint wx, gint wy,
274                                         gboolean keyboard_mode UNUSED,
275                                         GtkTooltip *tooltip,
276                                         struct import_assistant *);
277
278
279
280 /* Called to render one of the cells in the fields preview tree
281    view. */
282 static void
283 render_input_cell (PsppSheetViewColumn *tree_column, GtkCellRenderer *cell,
284                    GtkTreeModel *model, GtkTreeIter *iter,
285                    gpointer ia_)
286 {
287   struct import_assistant *ia = ia_;
288   struct substring field;
289   size_t row;
290   gint column;
291
292   column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
293                                                "column-number"));
294   row = empty_list_store_iter_to_row (iter) + ia->skip_lines;
295   field = ia->columns[column].contents[row];
296   if (field.string != NULL)
297     {
298       GValue text = {0, };
299       g_value_init (&text, G_TYPE_STRING);
300       g_value_take_string (&text, ss_xstrdup (field));
301       g_object_set_property (G_OBJECT (cell), "text", &text);
302       g_value_unset (&text);
303       g_object_set (cell, "background-set", FALSE, (void *) NULL);
304     }
305   else
306     g_object_set (cell,
307                   "text", "",
308                   "background", "red",
309                   "background-set", TRUE,
310                   (void *) NULL);
311 }
312
313 static gboolean
314 get_tooltip_location (GtkWidget *widget, gint wx, gint wy,
315                       const struct import_assistant *ia,
316                       size_t *row, size_t *column);
317
318
319 /* Called to render a tooltip on one of the cells in the fields
320    preview tree view. */
321 static gboolean
322 on_query_input_tooltip (GtkWidget *widget, gint wx, gint wy,
323                         gboolean keyboard_mode UNUSED,
324                         GtkTooltip *tooltip, struct import_assistant *ia)
325 {
326   size_t row, column;
327
328   if (!get_tooltip_location (widget, wx, wy, ia, &row, &column))
329     return FALSE;
330
331   if (ia->columns[column].contents[row].string != NULL)
332     return FALSE;
333
334   gtk_tooltip_set_text (tooltip,
335                         _("This input line has too few separators "
336                           "to fill in this field."));
337   return TRUE;
338 }
339
340
341 /* Parses the contents of the field at (ROW,COLUMN) according to
342    its variable format.  If OUTPUTP is non-null, then *OUTPUTP
343    receives the formatted output for that field (which must be
344    freed with free).  If TOOLTIPP is non-null, then *TOOLTIPP
345    receives a message suitable for use in a tooltip, if one is
346    needed, or a null pointer otherwise.  Returns true if a
347    tooltip message is needed, otherwise false. */
348 static bool
349 parse_field (struct import_assistant *ia,
350              size_t row, size_t column,
351              char **outputp, char **tooltipp)
352 {
353   const struct fmt_spec *in;
354   struct fmt_spec out;
355   char *tooltip;
356   bool ok;
357
358   struct substring field = ia->columns[column].contents[row];
359   struct variable *var = dict_get_var (ia->dict, column);
360   union value val;
361
362   value_init (&val, var_get_width (var));
363   in = var_get_print_format (var);
364   out = fmt_for_output_from_input (in);
365   tooltip = NULL;
366   if (field.string != NULL)
367     {
368       char *error;
369
370       error = data_in (field, "UTF-8", in->type, &val, var_get_width (var),
371                        dict_get_encoding (ia->dict));
372       if (error != NULL)
373         {
374           tooltip = xasprintf (_("Cannot parse field content `%.*s' as "
375                                  "format %s: %s"),
376                                (int) field.length, field.string,
377                                fmt_name (in->type), error);
378           free (error);
379         }
380     }
381   else
382     {
383       tooltip = xstrdup (_("This input line has too few separators "
384                            "to fill in this field."));
385       value_set_missing (&val, var_get_width (var));
386     }
387   if (outputp != NULL)
388     {
389       *outputp = data_out (&val, dict_get_encoding (ia->dict),  &out);
390     }
391   value_destroy (&val, var_get_width (var));
392
393   ok = tooltip == NULL;
394   if (tooltipp != NULL)
395     *tooltipp = tooltip;
396   else
397     free (tooltip);
398   return ok;
399 }
400
401 /* Called to render one of the cells in the data preview tree
402    view. */
403 static void
404 render_output_cell (PsppSheetViewColumn *tree_column,
405                     GtkCellRenderer *cell,
406                     GtkTreeModel *model,
407                     GtkTreeIter *iter,
408                     gpointer ia_)
409 {
410   struct import_assistant *ia = ia_;
411   char *output;
412   GValue gvalue = { 0, };
413   bool ok;
414
415   ok = parse_field (ia,
416                     (empty_list_store_iter_to_row (iter)
417                      + ia->skip_lines),
418                     GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
419                                                         "column-number")),
420                     &output, NULL);
421
422   g_value_init (&gvalue, G_TYPE_STRING);
423   g_value_take_string (&gvalue, output);
424   g_object_set_property (G_OBJECT (cell), "text", &gvalue);
425   g_value_unset (&gvalue);
426
427   if (ok)
428     g_object_set (cell, "background-set", FALSE, (void *) NULL);
429   else
430     g_object_set (cell,
431                   "background", "red",
432                   "background-set", TRUE,
433                   (void *) NULL);
434 }
435
436 /* Called to render a tooltip for one of the cells in the data
437    preview tree view. */
438 static gboolean
439 on_query_output_tooltip (GtkWidget *widget, gint wx, gint wy,
440                          gboolean keyboard_mode UNUSED,
441                          GtkTooltip *tooltip, struct import_assistant *ia)
442 {
443   size_t row, column;
444   char *text;
445
446   if (!get_tooltip_location (widget, wx, wy, ia, &row, &column))
447     return FALSE;
448
449   if (parse_field (ia, row, column, NULL, &text))
450     return FALSE;
451
452   gtk_tooltip_set_text (tooltip, text);
453   free (text);
454   return TRUE;
455 }
456 \f
457 /* Utility functions used by multiple pages of the assistant. */
458
459 static gboolean
460 get_tooltip_location (GtkWidget *widget, gint wx, gint wy,
461                       const struct import_assistant *ia,
462                       size_t *row, size_t *column)
463 {
464   PsppSheetView *tree_view = PSPP_SHEET_VIEW (widget);
465   gint bx, by;
466   GtkTreePath *path;
467   GtkTreeIter iter;
468   PsppSheetViewColumn *tree_column;
469   GtkTreeModel *tree_model;
470   bool ok;
471
472   /* Check that WIDGET is really visible on the screen before we
473      do anything else.  This is a bug fix for a sticky situation:
474      when text_data_import_assistant() returns, it frees the data
475      necessary to compose the tool tip message, but there may be
476      a tool tip under preparation at that point (even if there is
477      no visible tool tip) that will call back into us a little
478      bit later.  Perhaps the correct solution to this problem is
479      to make the data related to the tool tips part of a GObject
480      that only gets destroyed when all references are released,
481      but this solution appears to be effective too. */
482   if (!gtk_widget_get_mapped (widget))
483     return FALSE;
484
485   pspp_sheet_view_convert_widget_to_bin_window_coords (tree_view,
486                                                        wx, wy, &bx, &by);
487   if (!pspp_sheet_view_get_path_at_pos (tree_view, bx, by,
488                                       &path, &tree_column, NULL, NULL))
489     return FALSE;
490
491   *column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
492                                                 "column-number"));
493
494   tree_model = pspp_sheet_view_get_model (tree_view);
495   ok = gtk_tree_model_get_iter (tree_model, &iter, path);
496   gtk_tree_path_free (path);
497   if (!ok)
498     return FALSE;
499
500   *row = empty_list_store_iter_to_row (&iter) + ia->skip_lines;
501   return TRUE;
502 }
503
504 void
505 make_tree_view (const struct import_assistant *ia,
506                 size_t first_line,
507                 PsppSheetView **tree_view)
508 {
509   GtkTreeModel *model;
510
511   *tree_view = PSPP_SHEET_VIEW (pspp_sheet_view_new ());
512   pspp_sheet_view_set_grid_lines (*tree_view, PSPP_SHEET_VIEW_GRID_LINES_BOTH);
513   model = GTK_TREE_MODEL (psppire_empty_list_store_new (
514                                                         ia->file.line_cnt - first_line));
515   g_object_set_data (G_OBJECT (model), "lines", ia->file.lines + first_line);
516   g_object_set_data (G_OBJECT (model), "first-line",
517                      GINT_TO_POINTER (first_line));
518   pspp_sheet_view_set_model (*tree_view, model);
519   g_object_unref (model);
520
521   add_line_number_column (ia, *tree_view);
522 }
523
524 static void
525 render_line_number (PsppSheetViewColumn *tree_column,
526                     GtkCellRenderer *cell,
527                     GtkTreeModel *tree_model,
528                     GtkTreeIter *iter,
529                     gpointer data)
530 {
531   gint row = empty_list_store_iter_to_row (iter);
532   char s[INT_BUFSIZE_BOUND (int)];
533   int first_line;
534
535   first_line = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_model),
536                                                    "first-line"));
537   sprintf (s, "%d", first_line + row);
538   g_object_set (cell, "text", s, NULL);
539 }
540
541 static void
542 add_line_number_column (const struct import_assistant *ia,
543                         PsppSheetView *treeview)
544 {
545   PsppSheetViewColumn *column;
546
547   column = pspp_sheet_view_column_new_with_attributes (
548     _("Line"), ia->asst.prop_renderer, (void *) NULL);
549   pspp_sheet_view_column_set_fixed_width (
550     column, get_monospace_width (treeview, ia->asst.prop_renderer, 5));
551   pspp_sheet_view_column_set_resizable (column, TRUE);
552   pspp_sheet_view_column_set_cell_data_func (column, ia->asst.prop_renderer,
553                                              render_line_number, NULL, NULL);
554   pspp_sheet_view_append_column (treeview, column);
555 }
556
557 gint
558 get_monospace_width (PsppSheetView *treeview, GtkCellRenderer *renderer,
559                      size_t char_cnt)
560 {
561   struct string s;
562   gint width;
563
564   ds_init_empty (&s);
565   ds_put_byte_multiple (&s, '0', char_cnt);
566   ds_put_byte (&s, ' ');
567   width = get_string_width (treeview, renderer, ds_cstr (&s));
568   ds_destroy (&s);
569
570   return width;
571 }
572
573 gint
574 get_string_width (PsppSheetView *treeview, GtkCellRenderer *renderer,
575                   const char *string)
576 {
577   gint width;
578   g_object_set (G_OBJECT (renderer), "text", string, (void *) NULL);
579   gtk_cell_renderer_get_size (renderer, GTK_WIDGET (treeview),
580                               NULL, NULL, NULL, &width, NULL);
581   return width;
582 }
583
584 PsppSheetViewColumn *
585 make_data_column (struct import_assistant *ia, PsppSheetView *tree_view,
586                   bool input, gint dict_idx)
587 {
588   struct variable *var = NULL;
589   struct column *column = NULL;
590   size_t char_cnt;
591   gint content_width, header_width;
592   PsppSheetViewColumn *tree_column;
593   char *name;
594
595   if (input)
596     column = &ia->columns[dict_idx];
597   else
598     var = dict_get_var (ia->dict, dict_idx);
599
600   name = escape_underscores (input ? column->name : var_get_name (var));
601   char_cnt = input ? column->width : var_get_print_format (var)->w;
602   content_width = get_monospace_width (tree_view, ia->asst.fixed_renderer,
603                                        char_cnt);
604   header_width = get_string_width (tree_view, ia->asst.prop_renderer,
605                                    name);
606
607   tree_column = pspp_sheet_view_column_new ();
608   g_object_set_data (G_OBJECT (tree_column), "column-number",
609                      GINT_TO_POINTER (dict_idx));
610   pspp_sheet_view_column_set_title (tree_column, name);
611   pspp_sheet_view_column_pack_start (tree_column, ia->asst.fixed_renderer,
612                                      FALSE);
613   pspp_sheet_view_column_set_cell_data_func (
614     tree_column, ia->asst.fixed_renderer,
615     input ? render_input_cell : render_output_cell, ia, NULL);
616   pspp_sheet_view_column_set_fixed_width (tree_column, MAX (content_width,
617                                                             header_width));
618
619   free (name);
620
621   return tree_column;
622 }
623
624 PsppSheetView *
625 create_data_tree_view (bool input, GtkContainer *parent,
626                        struct import_assistant *ia)
627 {
628   PsppSheetView *tree_view;
629   gint i;
630
631   make_tree_view (ia, ia->skip_lines, &tree_view);
632   pspp_sheet_selection_set_mode (pspp_sheet_view_get_selection (tree_view),
633                                  PSPP_SHEET_SELECTION_NONE);
634
635   for (i = 0; i < ia->column_cnt; i++)
636     pspp_sheet_view_append_column (tree_view,
637                                    make_data_column (ia, tree_view, input, i));
638
639   g_object_set (G_OBJECT (tree_view), "has-tooltip", TRUE, (void *) NULL);
640   g_signal_connect (tree_view, "query-tooltip",
641                     G_CALLBACK (input ? on_query_input_tooltip
642                                 : on_query_output_tooltip), ia);
643
644
645   gtk_container_add (parent, GTK_WIDGET (tree_view));
646   gtk_widget_show (GTK_WIDGET (tree_view));
647
648   return tree_view;
649 }
650
651 /* Increments the "watch cursor" level, setting the cursor for
652    the assistant window to a watch face to indicate to the user
653    that the ongoing operation may take some time. */
654 void
655 push_watch_cursor (struct import_assistant *ia)
656 {
657   if (++ia->asst.watch_cursor == 1)
658     {
659       GtkWidget *widget = GTK_WIDGET (ia->asst.assistant);
660       GdkDisplay *display = gtk_widget_get_display (widget);
661       GdkCursor *cursor = gdk_cursor_new_for_display (display, GDK_WATCH);
662       gdk_window_set_cursor (widget->window, cursor);
663       gdk_cursor_unref (cursor);
664       gdk_display_flush (display);
665     }
666 }
667
668 /* Decrements the "watch cursor" level.  If the level reaches
669    zero, the cursor is reset to its default shape. */
670 void
671 pop_watch_cursor (struct import_assistant *ia)
672 {
673   if (--ia->asst.watch_cursor == 0)
674     {
675       GtkWidget *widget = GTK_WIDGET (ia->asst.assistant);
676       gdk_window_set_cursor (widget->window, NULL);
677     }
678 }