Put the pages as pointers
[pspp] / src / ui / gui / page-separators.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 <errno.h>
22 #include <fcntl.h>
23 #include <gtk-contrib/psppire-sheet.h>
24 #include <gtk/gtk.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <sys/stat.h>
28
29 #include "data/data-in.h"
30 #include "data/data-out.h"
31 #include "data/format-guesser.h"
32 #include "data/value-labels.h"
33 #include "language/data-io/data-parser.h"
34 #include "language/lexer/lexer.h"
35 #include "libpspp/assertion.h"
36 #include "libpspp/i18n.h"
37 #include "libpspp/line-reader.h"
38 #include "libpspp/message.h"
39 #include "ui/gui/checkbox-treeview.h"
40 #include "ui/gui/dialog-common.h"
41 #include "ui/gui/executor.h"
42 #include "ui/gui/helper.h"
43 #include "ui/gui/builder-wrapper.h"
44 #include "ui/gui/psppire-data-window.h"
45 #include "ui/gui/psppire-dialog.h"
46 #include "ui/gui/psppire-encoding-selector.h"
47 #include "ui/gui/psppire-empty-list-store.h"
48 #include "ui/gui/psppire-var-sheet.h"
49 #include "ui/gui/psppire-var-store.h"
50 #include "ui/gui/psppire-scanf.h"
51 #include "ui/syntax-gen.h"
52
53 #include "gl/error.h"
54 #include "gl/intprops.h"
55 #include "gl/xalloc.h"
56
57 #include "gettext.h"
58 #define _(msgid) gettext (msgid)
59 #define N_(msgid) msgid
60
61 \f
62 /* The "separators" page of the assistant. */
63
64 static void revise_fields_preview (struct import_assistant *ia);
65 static void choose_likely_separators (struct import_assistant *ia);
66 static void find_commonest_chars (unsigned long int histogram[UCHAR_MAX + 1],
67                                   const char *targets, const char *def,
68                                   struct string *result);
69 static void clear_fields (struct import_assistant *ia);
70 static void revise_fields_preview (struct import_assistant *);
71 static void set_separators (struct import_assistant *);
72 static void get_separators (struct import_assistant *);
73 static void on_separators_custom_entry_notify (GObject *UNUSED,
74                                                GParamSpec *UNUSED,
75                                                struct import_assistant *);
76 static void on_separators_custom_cb_toggle (GtkToggleButton *custom_cb,
77                                             struct import_assistant *);
78 static void on_quote_combo_change (GtkComboBox *combo,
79                                    struct import_assistant *);
80 static void on_quote_cb_toggle (GtkToggleButton *quote_cb,
81                                 struct import_assistant *);
82 static void on_separator_toggle (GtkToggleButton *, struct import_assistant *);
83
84 /* A common field separator and its identifying name. */
85 struct separator
86   {
87     const char *name;           /* Name (for use with get_widget_assert). */
88     int c;                      /* Separator character. */
89   };
90
91 /* All the separators in the dialog box. */
92 static const struct separator separators[] =
93   {
94     {"space", ' '},
95     {"tab", '\t'},
96     {"bang", '!'},
97     {"colon", ':'},
98     {"comma", ','},
99     {"hyphen", '-'},
100     {"pipe", '|'},
101     {"semicolon", ';'},
102     {"slash", '/'},
103   };
104 #define SEPARATOR_CNT (sizeof separators / sizeof *separators)
105
106 static void
107 set_quote_list (GtkComboBoxEntry *cb)
108 {
109   GtkListStore *list =  gtk_list_store_new (1, G_TYPE_STRING);
110   GtkTreeIter iter;
111   gint i;
112   const gchar *seperator[3] = {"'\"", "\'", "\""};
113
114   for (i = 0; i < 3; i++)
115     {
116       const gchar *s = seperator[i];
117
118       /* Add a new row to the model */
119       gtk_list_store_append (list, &iter);
120       gtk_list_store_set (list, &iter,
121                           0, s,
122                           -1);
123
124     }
125
126   gtk_combo_box_set_model (GTK_COMBO_BOX (cb), GTK_TREE_MODEL (list));
127   g_object_unref (list);
128
129   gtk_combo_box_entry_set_text_column (cb, 0);
130 }
131
132 /* Initializes IA's separators substructure. */
133 void
134 init_separators_page (struct import_assistant *ia)
135 {
136   GtkBuilder *builder = ia->asst.builder;
137   struct separators_page *p = ia->separators;
138   size_t i;
139
140   choose_likely_separators (ia);
141
142   p->page = add_page_to_assistant (ia, get_widget_assert (builder, "Separators"),
143                                    GTK_ASSISTANT_PAGE_CONTENT);
144   p->custom_cb = get_widget_assert (builder, "custom-cb");
145   p->custom_entry = get_widget_assert (builder, "custom-entry");
146   p->quote_combo = get_widget_assert (builder, "quote-combo");
147   p->quote_entry = GTK_ENTRY (gtk_bin_get_child (GTK_BIN (p->quote_combo)));
148   p->quote_cb = get_widget_assert (builder, "quote-cb");
149   p->escape_cb = get_widget_assert (builder, "escape");
150
151   set_separators (ia);
152   set_quote_list (GTK_COMBO_BOX_ENTRY (p->quote_combo));
153   p->fields_tree_view = GTK_TREE_VIEW (get_widget_assert (builder, "fields"));
154   g_signal_connect (p->quote_combo, "changed",
155                     G_CALLBACK (on_quote_combo_change), ia);
156   g_signal_connect (p->quote_cb, "toggled",
157                     G_CALLBACK (on_quote_cb_toggle), ia);
158   g_signal_connect (p->custom_entry, "notify::text",
159                     G_CALLBACK (on_separators_custom_entry_notify), ia);
160   g_signal_connect (p->custom_cb, "toggled",
161                     G_CALLBACK (on_separators_custom_cb_toggle), ia);
162   for (i = 0; i < SEPARATOR_CNT; i++)
163     g_signal_connect (get_widget_assert (builder, separators[i].name),
164                       "toggled", G_CALLBACK (on_separator_toggle), ia);
165   g_signal_connect (p->escape_cb, "toggled",
166                     G_CALLBACK (on_separator_toggle), ia);
167 }
168
169 /* Frees IA's separators substructure. */
170 void
171 destroy_separators_page (struct import_assistant *ia)
172 {
173   struct separators_page *s = ia->separators;
174
175   ds_destroy (&s->separators);
176   ds_destroy (&s->quotes);
177   clear_fields (ia);
178 }
179
180 /* Called just before the separators page becomes visible in the
181    assistant. */
182 void
183 prepare_separators_page (struct import_assistant *ia)
184 {
185   revise_fields_preview (ia);
186 }
187
188 /* Called when the Reset button is clicked on the separators
189    page, resets the separators to the defaults. */
190 void
191 reset_separators_page (struct import_assistant *ia)
192 {
193   choose_likely_separators (ia);
194   set_separators (ia);
195 }
196
197 /* Frees and clears the column data in IA's separators
198    substructure. */
199 static void
200 clear_fields (struct import_assistant *ia)
201 {
202   struct separators_page *s = ia->separators;
203
204   if (s->column_cnt > 0)
205     {
206       struct column *col;
207       size_t row;
208
209       for (row = 0; row < ia->file.line_cnt; row++)
210         {
211           const struct string *line = &ia->file.lines[row];
212           const char *line_start = ds_data (line);
213           const char *line_end = ds_end (line);
214
215           for (col = s->columns; col < &s->columns[s->column_cnt]; col++)
216             {
217               char *s = ss_data (col->contents[row]);
218               if (!(s >= line_start && s <= line_end))
219                 ss_dealloc (&col->contents[row]);
220             }
221         }
222
223       for (col = s->columns; col < &s->columns[s->column_cnt]; col++)
224         {
225           free (col->name);
226           free (col->contents);
227         }
228
229       free (s->columns);
230       s->columns = NULL;
231       s->column_cnt = 0;
232     }
233 }
234
235 /* Breaks the file data in IA into columns based on the
236    separators set in IA's separators substructure. */
237 static void
238 split_fields (struct import_assistant *ia)
239 {
240   struct separators_page *s = ia->separators;
241   size_t columns_allocated;
242   bool space_sep;
243   size_t row;
244
245   clear_fields (ia);
246
247   /* Is space in the set of separators? */
248   space_sep = ss_find_byte (ds_ss (&s->separators), ' ') != SIZE_MAX;
249
250   /* Split all the lines, not just those from
251      ia->first_line.skip_lines on, so that we split the line that
252      contains variables names if ia->first_line.variable_names is
253      true. */
254   columns_allocated = 0;
255   for (row = 0; row < ia->file.line_cnt; row++)
256     {
257       struct string *line = &ia->file.lines[row];
258       struct substring text = ds_ss (line);
259       size_t column_idx;
260
261       for (column_idx = 0; ; column_idx++)
262         {
263           struct substring field;
264           struct column *column;
265
266           if (space_sep)
267             ss_ltrim (&text, ss_cstr (" "));
268           if (ss_is_empty (text))
269             {
270               if (column_idx != 0)
271                 break;
272               field = text;
273             }
274           else if (!ds_is_empty (&s->quotes)
275                    && ds_find_byte (&s->quotes, text.string[0]) != SIZE_MAX)
276             {
277               int quote = ss_get_byte (&text);
278               if (!s->escape)
279                 ss_get_until (&text, quote, &field);
280               else
281                 {
282                   struct string s;
283                   int c;
284
285                   ds_init_empty (&s);
286                   while ((c = ss_get_byte (&text)) != EOF)
287                     if (c != quote)
288                       ds_put_byte (&s, c);
289                     else if (ss_match_byte (&text, quote))
290                       ds_put_byte (&s, quote);
291                     else
292                       break;
293                   field = ds_ss (&s);
294                 }
295             }
296           else
297             ss_get_bytes (&text, ss_cspan (text, ds_ss (&s->separators)),
298                           &field);
299
300           if (column_idx >= s->column_cnt)
301             {
302               struct column *column;
303
304               if (s->column_cnt >= columns_allocated)
305                 s->columns = x2nrealloc (s->columns, &columns_allocated,
306                                          sizeof *s->columns);
307               column = &s->columns[s->column_cnt++];
308               column->name = NULL;
309               column->width = 0;
310               column->contents = xcalloc (ia->file.line_cnt,
311                                           sizeof *column->contents);
312             }
313           column = &s->columns[column_idx];
314           column->contents[row] = field;
315           if (ss_length (field) > column->width)
316             column->width = ss_length (field);
317
318           if (space_sep)
319             ss_ltrim (&text, ss_cstr (" "));
320           if (ss_is_empty (text))
321             break;
322           if (ss_find_byte (ds_ss (&s->separators), ss_first (text))
323               != SIZE_MAX)
324             ss_advance (&text, 1);
325         }
326     }
327 }
328
329 /* Chooses a name for each column on the separators page */
330 static void
331 choose_column_names (struct import_assistant *ia)
332 {
333   const struct first_line_page *f = ia->first_line;
334   struct separators_page *s = ia->separators;
335   struct dictionary *dict;
336   unsigned long int generated_name_count = 0;
337   struct column *col;
338   size_t name_row;
339
340   dict = dict_create (get_default_encoding ());
341   name_row = f->variable_names && f->skip_lines ? f->skip_lines : 0;
342   for (col = s->columns; col < &s->columns[s->column_cnt]; col++)
343     {
344       char *hint, *name;
345
346       hint = name_row ? ss_xstrdup (col->contents[name_row - 1]) : NULL;
347       name = dict_make_unique_var_name (dict, hint, &generated_name_count);
348       free (hint);
349
350       col->name = name;
351       dict_create_var_assert (dict, name, 0);
352     }
353   dict_destroy (dict);
354 }
355
356 /* Picks the most likely separator and quote characters based on
357    IA's file data. */
358 static void
359 choose_likely_separators (struct import_assistant *ia)
360 {
361   unsigned long int histogram[UCHAR_MAX + 1] = { 0 };
362   size_t row;
363
364   /* Construct a histogram of all the characters used in the
365      file. */
366   for (row = 0; row < ia->file.line_cnt; row++)
367     {
368       struct substring line = ds_ss (&ia->file.lines[row]);
369       size_t length = ss_length (line);
370       size_t i;
371       for (i = 0; i < length; i++)
372         histogram[(unsigned char) line.string[i]]++;
373     }
374
375   find_commonest_chars (histogram, "\"'", "", &ia->separators->quotes);
376   find_commonest_chars (histogram, ",;:/|!\t-", ",", &ia->separators->separators);
377   ia->separators->escape = true;
378 }
379
380 /* Chooses the most common character among those in TARGETS,
381    based on the frequency data in HISTOGRAM, and stores it in
382    RESULT.  If there is a tie for the most common character among
383    those in TARGETS, the earliest character is chosen.  If none
384    of the TARGETS appear at all, then DEF is used as a
385    fallback. */
386 static void
387 find_commonest_chars (unsigned long int histogram[UCHAR_MAX + 1],
388                       const char *targets, const char *def,
389                       struct string *result)
390 {
391   unsigned char max = 0;
392   unsigned long int max_count = 0;
393
394   for (; *targets != '\0'; targets++)
395     {
396       unsigned char c = *targets;
397       unsigned long int count = histogram[c];
398       if (count > max_count)
399         {
400           max = c;
401           max_count = count;
402         }
403     }
404   if (max_count > 0)
405     {
406       ds_clear (result);
407       ds_put_byte (result, max);
408     }
409   else
410     ds_assign_cstr (result, def);
411 }
412
413 /* Revises the contents of the fields tree view based on the
414    currently chosen set of separators. */
415 static void
416 revise_fields_preview (struct import_assistant *ia)
417 {
418   GtkWidget *w;
419
420   push_watch_cursor (ia);
421
422   w = GTK_WIDGET (ia->separators->fields_tree_view);
423   gtk_widget_destroy (w);
424   get_separators (ia);
425   split_fields (ia);
426   choose_column_names (ia);
427   ia->separators->fields_tree_view = create_data_tree_view (
428     true,
429     GTK_CONTAINER (get_widget_assert (ia->asst.builder, "fields-scroller")),
430     ia);
431
432   pop_watch_cursor (ia);
433 }
434
435 /* Sets the widgets to match IA's separators substructure. */
436 static void
437 set_separators (struct import_assistant *ia)
438 {
439   struct separators_page *s = ia->separators;
440   unsigned int seps;
441   struct string custom;
442   bool any_custom;
443   bool any_quotes;
444   size_t i;
445
446   ds_init_empty (&custom);
447   seps = 0;
448   for (i = 0; i < ds_length (&s->separators); i++)
449     {
450       unsigned char c = ds_at (&s->separators, i);
451       int j;
452
453       for (j = 0; j < SEPARATOR_CNT; j++)
454         {
455           const struct separator *s = &separators[j];
456           if (s->c == c)
457             {
458               seps += 1u << j;
459               goto next;
460             }
461         }
462
463       ds_put_byte (&custom, c);
464     next:;
465     }
466
467   for (i = 0; i < SEPARATOR_CNT; i++)
468     {
469       const struct separator *s = &separators[i];
470       GtkWidget *button = get_widget_assert (ia->asst.builder, s->name);
471       gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button),
472                                     (seps & (1u << i)) != 0);
473     }
474   any_custom = !ds_is_empty (&custom);
475   gtk_entry_set_text (GTK_ENTRY (s->custom_entry), ds_cstr (&custom));
476   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (s->custom_cb),
477                                 any_custom);
478   gtk_widget_set_sensitive (s->custom_entry, any_custom);
479   ds_destroy (&custom);
480
481   any_quotes = !ds_is_empty (&s->quotes);
482
483   gtk_entry_set_text (s->quote_entry,
484                       any_quotes ? ds_cstr (&s->quotes) : "\"");
485   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (s->quote_cb),
486                                 any_quotes);
487   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (s->escape_cb),
488                                 s->escape);
489   gtk_widget_set_sensitive (s->quote_combo, any_quotes);
490   gtk_widget_set_sensitive (s->escape_cb, any_quotes);
491 }
492
493 /* Sets IA's separators substructure to match the widgets. */
494 static void
495 get_separators (struct import_assistant *ia)
496 {
497   struct separators_page *s = ia->separators;
498   int i;
499
500   ds_clear (&s->separators);
501   for (i = 0; i < SEPARATOR_CNT; i++)
502     {
503       const struct separator *sep = &separators[i];
504       GtkWidget *button = get_widget_assert (ia->asst.builder, sep->name);
505       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
506         ds_put_byte (&s->separators, sep->c);
507     }
508
509   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (s->custom_cb)))
510     ds_put_cstr (&s->separators,
511                  gtk_entry_get_text (GTK_ENTRY (s->custom_entry)));
512
513   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (s->quote_cb)))
514     {
515       gchar *text = gtk_combo_box_get_active_text (
516                       GTK_COMBO_BOX (s->quote_combo));
517       ds_assign_cstr (&s->quotes, text);
518       g_free (text);
519     }
520   else
521     ds_clear (&s->quotes);
522   s->escape = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (s->escape_cb));
523 }
524
525 /* Called when the user changes the entry field for custom
526    separators. */
527 static void
528 on_separators_custom_entry_notify (GObject *gobject UNUSED,
529                                    GParamSpec *arg1 UNUSED,
530                                    struct import_assistant *ia)
531 {
532   revise_fields_preview (ia);
533 }
534
535 /* Called when the user toggles the checkbox that enables custom
536    separators. */
537 static void
538 on_separators_custom_cb_toggle (GtkToggleButton *custom_cb,
539                                 struct import_assistant *ia)
540 {
541   bool is_active = gtk_toggle_button_get_active (custom_cb);
542   gtk_widget_set_sensitive (ia->separators->custom_entry, is_active);
543   revise_fields_preview (ia);
544 }
545
546 /* Called when the user changes the selection in the combo box
547    that selects a quote character. */
548 static void
549 on_quote_combo_change (GtkComboBox *combo, struct import_assistant *ia)
550 {
551   revise_fields_preview (ia);
552 }
553
554 /* Called when the user toggles the checkbox that enables
555    quoting. */
556 static void
557 on_quote_cb_toggle (GtkToggleButton *quote_cb, struct import_assistant *ia)
558 {
559   bool is_active = gtk_toggle_button_get_active (quote_cb);
560   gtk_widget_set_sensitive (ia->separators->quote_combo, is_active);
561   gtk_widget_set_sensitive (ia->separators->escape_cb, is_active);
562   revise_fields_preview (ia);
563 }
564
565 /* Called when the user toggles one of the separators
566    checkboxes. */
567 static void
568 on_separator_toggle (GtkToggleButton *toggle UNUSED,
569                      struct import_assistant *ia)
570 {
571   revise_fields_preview (ia);
572 }
573