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