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