Move column count from seperators into assist
[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   if (ia->column_cnt > 0)
203     {
204       struct column *col;
205       size_t row;
206
207       for (row = 0; row < ia->file.line_cnt; row++)
208         {
209           const struct string *line = &ia->file.lines[row];
210           const char *line_start = ds_data (line);
211           const char *line_end = ds_end (line);
212
213           for (col = ia->columns; col < &ia->columns[ia->column_cnt]; col++)
214             {
215               char *s = ss_data (col->contents[row]);
216               if (!(s >= line_start && s <= line_end))
217                 ss_dealloc (&col->contents[row]);
218             }
219         }
220
221       for (col = ia->columns; col < &ia->columns[ia->column_cnt]; col++)
222         {
223           free (col->name);
224           free (col->contents);
225         }
226
227       free (ia->columns);
228       ia->columns = NULL;
229       ia->column_cnt = 0;
230     }
231 }
232
233 /* Breaks the file data in IA into columns based on the
234    separators set in IA's separators substructure. */
235 static void
236 split_fields (struct import_assistant *ia)
237 {
238   struct separators_page *s = ia->separators;
239   size_t columns_allocated;
240   bool space_sep;
241   size_t row;
242
243   clear_fields (ia);
244
245   /* Is space in the set of separators? */
246   space_sep = ss_find_byte (ds_ss (&s->separators), ' ') != SIZE_MAX;
247
248   /* Split all the lines, not just those from
249      ia->first_line.skip_lines on, so that we split the line that
250      contains variables names if ia->first_line.variable_names is
251      true. */
252   columns_allocated = 0;
253   for (row = 0; row < ia->file.line_cnt; row++)
254     {
255       struct string *line = &ia->file.lines[row];
256       struct substring text = ds_ss (line);
257       size_t column_idx;
258
259       for (column_idx = 0; ; column_idx++)
260         {
261           struct substring field;
262           struct column *column;
263
264           if (space_sep)
265             ss_ltrim (&text, ss_cstr (" "));
266           if (ss_is_empty (text))
267             {
268               if (column_idx != 0)
269                 break;
270               field = text;
271             }
272           else if (!ds_is_empty (&s->quotes)
273                    && ds_find_byte (&s->quotes, text.string[0]) != SIZE_MAX)
274             {
275               int quote = ss_get_byte (&text);
276               if (!s->escape)
277                 ss_get_until (&text, quote, &field);
278               else
279                 {
280                   struct string s;
281                   int c;
282
283                   ds_init_empty (&s);
284                   while ((c = ss_get_byte (&text)) != EOF)
285                     if (c != quote)
286                       ds_put_byte (&s, c);
287                     else if (ss_match_byte (&text, quote))
288                       ds_put_byte (&s, quote);
289                     else
290                       break;
291                   field = ds_ss (&s);
292                 }
293             }
294           else
295             ss_get_bytes (&text, ss_cspan (text, ds_ss (&s->separators)),
296                           &field);
297
298           if (column_idx >= ia->column_cnt)
299             {
300               struct column *column;
301
302               if (ia->column_cnt >= columns_allocated)
303                 ia->columns = x2nrealloc (ia->columns, &columns_allocated,
304                                          sizeof *ia->columns);
305               column = &ia->columns[ia->column_cnt++];
306               column->name = NULL;
307               column->width = 0;
308               column->contents = xcalloc (ia->file.line_cnt,
309                                           sizeof *column->contents);
310             }
311           column = &ia->columns[column_idx];
312           column->contents[row] = field;
313           if (ss_length (field) > column->width)
314             column->width = ss_length (field);
315
316           if (space_sep)
317             ss_ltrim (&text, ss_cstr (" "));
318           if (ss_is_empty (text))
319             break;
320           if (ss_find_byte (ds_ss (&s->separators), ss_first (text))
321               != SIZE_MAX)
322             ss_advance (&text, 1);
323         }
324     }
325 }
326
327 /* Chooses a name for each column on the separators page */
328 static void
329 choose_column_names (struct import_assistant *ia)
330 {
331   const struct first_line_page *f = ia->first_line;
332   struct separators_page *s = ia->separators;
333   struct dictionary *dict;
334   unsigned long int generated_name_count = 0;
335   struct column *col;
336   size_t name_row;
337
338   dict = dict_create (get_default_encoding ());
339   name_row = f->variable_names && f->skip_lines ? f->skip_lines : 0;
340   for (col = ia->columns; col < &ia->columns[ia->column_cnt]; col++)
341     {
342       char *hint, *name;
343
344       hint = name_row ? ss_xstrdup (col->contents[name_row - 1]) : NULL;
345       name = dict_make_unique_var_name (dict, hint, &generated_name_count);
346       free (hint);
347
348       col->name = name;
349       dict_create_var_assert (dict, name, 0);
350     }
351   dict_destroy (dict);
352 }
353
354 /* Picks the most likely separator and quote characters based on
355    IA's file data. */
356 static void
357 choose_likely_separators (struct import_assistant *ia)
358 {
359   unsigned long int histogram[UCHAR_MAX + 1] = { 0 };
360   size_t row;
361
362   /* Construct a histogram of all the characters used in the
363      file. */
364   for (row = 0; row < ia->file.line_cnt; row++)
365     {
366       struct substring line = ds_ss (&ia->file.lines[row]);
367       size_t length = ss_length (line);
368       size_t i;
369       for (i = 0; i < length; i++)
370         histogram[(unsigned char) line.string[i]]++;
371     }
372
373   find_commonest_chars (histogram, "\"'", "", &ia->separators->quotes);
374   find_commonest_chars (histogram, ",;:/|!\t-", ",", &ia->separators->separators);
375   ia->separators->escape = true;
376 }
377
378 /* Chooses the most common character among those in TARGETS,
379    based on the frequency data in HISTOGRAM, and stores it in
380    RESULT.  If there is a tie for the most common character among
381    those in TARGETS, the earliest character is chosen.  If none
382    of the TARGETS appear at all, then DEF is used as a
383    fallback. */
384 static void
385 find_commonest_chars (unsigned long int histogram[UCHAR_MAX + 1],
386                       const char *targets, const char *def,
387                       struct string *result)
388 {
389   unsigned char max = 0;
390   unsigned long int max_count = 0;
391
392   for (; *targets != '\0'; targets++)
393     {
394       unsigned char c = *targets;
395       unsigned long int count = histogram[c];
396       if (count > max_count)
397         {
398           max = c;
399           max_count = count;
400         }
401     }
402   if (max_count > 0)
403     {
404       ds_clear (result);
405       ds_put_byte (result, max);
406     }
407   else
408     ds_assign_cstr (result, def);
409 }
410
411 /* Revises the contents of the fields tree view based on the
412    currently chosen set of separators. */
413 static void
414 revise_fields_preview (struct import_assistant *ia)
415 {
416   GtkWidget *w;
417
418   push_watch_cursor (ia);
419
420   w = GTK_WIDGET (ia->separators->fields_tree_view);
421   gtk_widget_destroy (w);
422   get_separators (ia);
423   split_fields (ia);
424   choose_column_names (ia);
425   ia->separators->fields_tree_view = create_data_tree_view (
426     true,
427     GTK_CONTAINER (get_widget_assert (ia->asst.builder, "fields-scroller")),
428     ia);
429
430   pop_watch_cursor (ia);
431 }
432
433 /* Sets the widgets to match IA's separators substructure. */
434 static void
435 set_separators (struct import_assistant *ia)
436 {
437   struct separators_page *s = ia->separators;
438   unsigned int seps;
439   struct string custom;
440   bool any_custom;
441   bool any_quotes;
442   size_t i;
443
444   ds_init_empty (&custom);
445   seps = 0;
446   for (i = 0; i < ds_length (&s->separators); i++)
447     {
448       unsigned char c = ds_at (&s->separators, i);
449       int j;
450
451       for (j = 0; j < SEPARATOR_CNT; j++)
452         {
453           const struct separator *s = &separators[j];
454           if (s->c == c)
455             {
456               seps += 1u << j;
457               goto next;
458             }
459         }
460
461       ds_put_byte (&custom, c);
462     next:;
463     }
464
465   for (i = 0; i < SEPARATOR_CNT; i++)
466     {
467       const struct separator *s = &separators[i];
468       GtkWidget *button = get_widget_assert (ia->asst.builder, s->name);
469       gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button),
470                                     (seps & (1u << i)) != 0);
471     }
472   any_custom = !ds_is_empty (&custom);
473   gtk_entry_set_text (GTK_ENTRY (s->custom_entry), ds_cstr (&custom));
474   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (s->custom_cb),
475                                 any_custom);
476   gtk_widget_set_sensitive (s->custom_entry, any_custom);
477   ds_destroy (&custom);
478
479   any_quotes = !ds_is_empty (&s->quotes);
480
481   gtk_entry_set_text (s->quote_entry,
482                       any_quotes ? ds_cstr (&s->quotes) : "\"");
483   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (s->quote_cb),
484                                 any_quotes);
485   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (s->escape_cb),
486                                 s->escape);
487   gtk_widget_set_sensitive (s->quote_combo, any_quotes);
488   gtk_widget_set_sensitive (s->escape_cb, any_quotes);
489 }
490
491 /* Sets IA's separators substructure to match the widgets. */
492 static void
493 get_separators (struct import_assistant *ia)
494 {
495   struct separators_page *s = ia->separators;
496   int i;
497
498   ds_clear (&s->separators);
499   for (i = 0; i < SEPARATOR_CNT; i++)
500     {
501       const struct separator *sep = &separators[i];
502       GtkWidget *button = get_widget_assert (ia->asst.builder, sep->name);
503       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
504         ds_put_byte (&s->separators, sep->c);
505     }
506
507   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (s->custom_cb)))
508     ds_put_cstr (&s->separators,
509                  gtk_entry_get_text (GTK_ENTRY (s->custom_entry)));
510
511   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (s->quote_cb)))
512     {
513       gchar *text = gtk_combo_box_get_active_text (
514                       GTK_COMBO_BOX (s->quote_combo));
515       ds_assign_cstr (&s->quotes, text);
516       g_free (text);
517     }
518   else
519     ds_clear (&s->quotes);
520   s->escape = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (s->escape_cb));
521 }
522
523 /* Called when the user changes the entry field for custom
524    separators. */
525 static void
526 on_separators_custom_entry_notify (GObject *gobject UNUSED,
527                                    GParamSpec *arg1 UNUSED,
528                                    struct import_assistant *ia)
529 {
530   revise_fields_preview (ia);
531 }
532
533 /* Called when the user toggles the checkbox that enables custom
534    separators. */
535 static void
536 on_separators_custom_cb_toggle (GtkToggleButton *custom_cb,
537                                 struct import_assistant *ia)
538 {
539   bool is_active = gtk_toggle_button_get_active (custom_cb);
540   gtk_widget_set_sensitive (ia->separators->custom_entry, is_active);
541   revise_fields_preview (ia);
542 }
543
544 /* Called when the user changes the selection in the combo box
545    that selects a quote character. */
546 static void
547 on_quote_combo_change (GtkComboBox *combo, struct import_assistant *ia)
548 {
549   revise_fields_preview (ia);
550 }
551
552 /* Called when the user toggles the checkbox that enables
553    quoting. */
554 static void
555 on_quote_cb_toggle (GtkToggleButton *quote_cb, struct import_assistant *ia)
556 {
557   bool is_active = gtk_toggle_button_get_active (quote_cb);
558   gtk_widget_set_sensitive (ia->separators->quote_combo, is_active);
559   gtk_widget_set_sensitive (ia->separators->escape_cb, is_active);
560   revise_fields_preview (ia);
561 }
562
563 /* Called when the user toggles one of the separators
564    checkboxes. */
565 static void
566 on_separator_toggle (GtkToggleButton *toggle UNUSED,
567                      struct import_assistant *ia)
568 {
569   revise_fields_preview (ia);
570 }
571