Import assistant: Re-enable automatic inference of the separators
[pspp] / src / ui / gui / psppire-import-assistant.c
1 /* PSPPIRE - a graphical user interface for PSPP.
2    Copyright (C) 2015, 2016, 2017  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 <errno.h>
20 #include <fcntl.h>
21 #include <gtk/gtk.h>
22 #include <sys/stat.h>
23
24 #include "data/casereader.h"
25 #include "data/data-in.h"
26 #include "data/data-out.h"
27 #include "data/dictionary.h"
28 #include "data/format-guesser.h"
29 #include "data/format.h"
30 #include "data/gnumeric-reader.h"
31 #include "data/ods-reader.h"
32 #include "data/spreadsheet-reader.h"
33 #include "data/value-labels.h"
34 #include "data/casereader-provider.h"
35
36 #include "gl/intprops.h"
37
38 #include "libpspp/i18n.h"
39 #include "libpspp/line-reader.h"
40 #include "libpspp/message.h"
41 #include "libpspp/hmap.h"
42 #include "libpspp/hash-functions.h"
43 #include "libpspp/str.h"
44
45 #include "builder-wrapper.h"
46 #include "helper.h"
47 #include "psppire-import-assistant.h"
48 #include "psppire-scanf.h"
49 #include "psppire-dialog.h"
50 #include "psppire-empty-list-store.h"
51 #include "psppire-encoding-selector.h"
52 #include "psppire-spreadsheet-model.h"
53 #include "psppire-text-file.h"
54 #include "psppire-delimited-text.h"
55 #include "psppire-data-sheet.h"
56 #include "psppire-data-store.h"
57 #include "psppire-dict.h"
58 #include "psppire-variable-sheet.h"
59
60 #include "ui/syntax-gen.h"
61
62 #include <gettext.h>
63 #define _(msgid) gettext (msgid)
64 #define N_(msgid) msgid
65
66 enum { MAX_LINE_LEN = 16384 }; /* Max length of an acceptable line. */
67
68
69 /* Sets IA's separators substructure to match the widgets. */
70 static void split_fields (PsppireImportAssistant *ia);
71
72 /* Chooses a name for each column on the separators page */
73 static void choose_column_names (PsppireImportAssistant *ia);
74
75
76
77 static void intro_page_create (PsppireImportAssistant *ia);
78 static void first_line_page_create (PsppireImportAssistant *ia);
79
80 static void separators_page_create (PsppireImportAssistant *ia);
81 static void formats_page_create (PsppireImportAssistant *ia);
82
83 static void push_watch_cursor (PsppireImportAssistant *ia);
84 static void pop_watch_cursor (PsppireImportAssistant *ia);
85
86
87
88 static void psppire_import_assistant_init            (PsppireImportAssistant      *act);
89 static void psppire_import_assistant_class_init      (PsppireImportAssistantClass *class);
90
91 G_DEFINE_TYPE (PsppireImportAssistant, psppire_import_assistant, GTK_TYPE_ASSISTANT);
92
93
94 /* Properties */
95 enum
96   {
97     PROP_0,
98   };
99
100 static void
101 psppire_import_assistant_set_property (GObject         *object,
102                                        guint            prop_id,
103                                        const GValue    *value,
104                                        GParamSpec      *pspec)
105 {
106   //   PsppireImportAssistant *act = PSPPIRE_IMPORT_ASSISTANT (object);
107
108   switch (prop_id)
109     {
110     default:
111       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
112       break;
113     };
114 }
115
116
117 static void
118 psppire_import_assistant_get_property (GObject    *object,
119                                        guint            prop_id,
120                                        GValue          *value,
121                                        GParamSpec      *pspec)
122 {
123   //  PsppireImportAssistant *assistant = PSPPIRE_IMPORT_ASSISTANT (object);
124
125   switch (prop_id)
126     {
127     default:
128       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
129       break;
130     };
131 }
132
133 static GObjectClass * parent_class = NULL;
134
135
136 static void
137 psppire_import_assistant_finalize (GObject *object)
138 {
139   PsppireImportAssistant *ia = PSPPIRE_IMPORT_ASSISTANT (object);
140
141
142   if (ia->spreadsheet)
143     spreadsheet_unref (ia->spreadsheet);
144
145   ds_destroy (&ia->quotes);
146
147   g_object_unref (ia->builder);
148
149   g_object_unref (ia->prop_renderer);
150   g_object_unref (ia->fixed_renderer);
151
152   if (G_OBJECT_CLASS (parent_class)->finalize)
153     G_OBJECT_CLASS (parent_class)->finalize (object);
154 }
155
156
157 static void
158 psppire_import_assistant_class_init (PsppireImportAssistantClass *class)
159 {
160   GObjectClass *object_class = G_OBJECT_CLASS (class);
161
162   parent_class = g_type_class_peek_parent (class);
163
164   object_class->set_property = psppire_import_assistant_set_property;
165   object_class->get_property = psppire_import_assistant_get_property;
166
167   object_class->finalize = psppire_import_assistant_finalize;
168 }
169
170
171 /* Causes the assistant to close, returning RESPONSE for
172    interpretation by text_data_import_assistant. */
173 static void
174 close_assistant (PsppireImportAssistant *ia, int response)
175 {
176   ia->response = response;
177   g_main_loop_quit (ia->main_loop);
178   gtk_widget_hide (GTK_WIDGET (ia));
179 }
180
181
182 /* Called when the Paste button on the last page of the assistant
183    is clicked. */
184 static void
185 on_paste (GtkButton *button, PsppireImportAssistant *ia)
186 {
187   close_assistant (ia, PSPPIRE_RESPONSE_PASTE);
188 }
189
190
191 /* Revises the contents of the fields tree view based on the
192    currently chosen set of separators. */
193 static void
194 revise_fields_preview (PsppireImportAssistant *ia)
195 {
196   push_watch_cursor (ia);
197
198   //  split_fields (ia);
199   choose_column_names (ia);
200
201   pop_watch_cursor (ia);
202 }
203
204
205 #if SHEET_MERGE
206
207 /* Chooses the most common character among those in TARGETS,
208    based on the frequency data in HISTOGRAM, and stores it in
209    RESULT.  If there is a tie for the most common character among
210    those in TARGETS, the earliest character is chosen.  If none
211    of the TARGETS appear at all, then DEF is used as a
212    fallback. */
213 static void
214 find_commonest_chars (unsigned long int histogram[UCHAR_MAX + 1],
215                       const char *targets, const char *def,
216                       struct string *result)
217 {
218   unsigned char max = 0;
219   unsigned long int max_count = 0;
220
221   for (; *targets != '\0'; targets++)
222     {
223       unsigned char c = *targets;
224       unsigned long int count = histogram[c];
225       if (count > max_count)
226         {
227           max = c;
228           max_count = count;
229         }
230     }
231   if (max_count > 0)
232     {
233       ds_clear (result);
234       ds_put_byte (result, max);
235     }
236   else
237     ds_assign_cstr (result, def);
238 }
239
240 #endif
241
242 struct separator
243 {
244   const char *name;           /* Name (for use with get_widget_assert). */
245   gunichar c;                 /* Separator character. */
246 };
247
248 /* All the separators in the dialog box. */
249 static const struct separator separators[] =
250   {
251     {"space", ' '},
252     {"tab", '\t'},
253     {"bang", '!'},
254     {"colon", ':'},
255     {"comma", ','},
256     {"hyphen", '-'},
257     {"pipe", '|'},
258     {"semicolon", ';'},
259     {"slash", '/'},
260   };
261 #define SEPARATOR_CNT (sizeof separators / sizeof *separators)
262
263 struct separator_count_node
264 {
265   struct hmap_node node;
266   int occurance; /* The number of times the separator occurs in a line */
267   int quantity;  /* The number of lines with this occurance */
268 };
269
270
271 /* Picks the most likely separator and quote characters based on
272    IA's file data. */
273 static void
274 choose_likely_separators (PsppireImportAssistant *ia)
275 {
276   gint first_line = 0;
277   g_object_get (ia->delimiters_model, "first-line", &first_line, NULL);
278
279   gboolean valid;
280   GtkTreeIter iter;
281   int i = 0;
282
283   int j;
284
285   struct hmap count_map[SEPARATOR_CNT];
286   for (j = 0; j < SEPARATOR_CNT; ++j)
287     hmap_init (count_map + j);
288
289   GtkTreePath *p = gtk_tree_path_new_from_indices (first_line, -1);
290
291   for (valid = gtk_tree_model_get_iter (GTK_TREE_MODEL (ia->text_file), &iter, p);
292        valid;
293        valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (ia->text_file), &iter))
294     {
295       int j;
296
297       gchar *line_text = NULL;
298       gtk_tree_model_get (GTK_TREE_MODEL (ia->text_file), &iter, 1, &line_text, -1);
299
300       gint *counts = xzalloc (sizeof *counts * SEPARATOR_CNT);
301       for (j = 0; j < strlen (line_text); ++j)
302         {
303           int s;
304           for (s = 0; s < SEPARATOR_CNT; ++s)
305             {
306               // FIXME do this in UTF8 encoding
307               if (line_text[j] == separators[s].c)
308                 counts[s]++;
309             }
310         }
311
312       for (j = 0; j < SEPARATOR_CNT; ++j)
313         {
314           if (counts[j] > 0)
315             {
316               struct separator_count_node *cn = NULL;
317               unsigned int hash = hash_int (counts[j], 0);
318               HMAP_FOR_EACH_WITH_HASH (cn, struct separator_count_node, node, hash, &count_map[j])
319                 {
320                   if (cn->occurance == counts[j])
321                     break;
322                 }
323
324               if (cn == NULL)
325                 {
326                   struct separator_count_node *new_cn = xzalloc (sizeof *new_cn);
327                   new_cn->occurance = counts[j];
328                   new_cn->quantity = 1;
329                   hmap_insert (&count_map[j], &new_cn->node, hash);
330                 }
331               else
332                 cn->quantity++;
333             }
334         }
335
336       free (line_text);
337       free (counts);
338     }
339   gtk_tree_path_free (p);
340
341   int most_frequent = -1;
342   int largest = 0;
343   for (j = 0; j < SEPARATOR_CNT; ++j)
344     {
345       struct separator_count_node *cn;
346       HMAP_FOR_EACH (cn, struct separator_count_node, node, &count_map[j])
347         {
348           if (largest < cn->quantity)
349             {
350               largest = cn->quantity;
351               most_frequent = j;
352             }
353         }
354       hmap_destroy (&count_map[j]);
355     }
356
357   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (get_widget_assert (ia->builder, separators[most_frequent].name)), TRUE);
358 }
359
360 static void
361 repopulate_delimiter_columns (PsppireImportAssistant *ia)
362 {
363   /* Remove all the columns */
364   while (gtk_tree_view_get_n_columns (GTK_TREE_VIEW (ia->fields_tree_view)) > 0)
365     {
366       GtkTreeViewColumn *tvc = gtk_tree_view_get_column (GTK_TREE_VIEW (ia->fields_tree_view), 0);
367       gtk_tree_view_remove_column (GTK_TREE_VIEW (ia->fields_tree_view), tvc);
368     }
369
370   gint n_fields = gtk_tree_model_get_n_columns (ia->delimiters_model);
371
372   /* ... and put them back again. */
373   gint f;
374   for (f = gtk_tree_view_get_n_columns (GTK_TREE_VIEW (ia->fields_tree_view));
375        f < n_fields; f++)
376     {
377       GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
378
379       const gchar *title = NULL;
380
381       if (f == 0)
382         title = _("line");
383       else
384         {
385           if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)))
386             {
387               title =
388                 psppire_delimited_text_get_header_title
389                 (PSPPIRE_DELIMITED_TEXT (ia->delimiters_model), f - 1);
390             }
391           if (title == NULL)
392             title = _("var");
393         }
394
395       GtkTreeViewColumn *column =
396         gtk_tree_view_column_new_with_attributes (title,
397                                                   renderer,
398                                                   "text", f,
399                                                   NULL);
400       g_object_set (column,
401                     "resizable", TRUE,
402                     "sizing", GTK_TREE_VIEW_COLUMN_AUTOSIZE,
403                     NULL);
404
405       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->fields_tree_view), column);
406     }
407 }
408
409 static void
410 reset_tree_view_model (PsppireImportAssistant *ia)
411 {
412   GtkTreeModel *tm = gtk_tree_view_get_model (GTK_TREE_VIEW (ia->fields_tree_view));
413   g_object_ref (tm);
414   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), NULL);
415
416
417   repopulate_delimiter_columns (ia);
418
419   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), tm);
420   //  gtk_tree_view_columns_autosize (GTK_TREE_VIEW (ia->fields_tree_view));
421
422   g_object_unref (tm);
423 }
424
425 /* Called just before the separators page becomes visible in the
426    assistant, and when the Reset button is clicked. */
427 static void
428 prepare_separators_page (PsppireImportAssistant *ia, GtkWidget *page)
429 {
430   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), ia->delimiters_model);
431
432   g_signal_connect_swapped (ia->delimiters_model, "notify::delimiters",
433                         G_CALLBACK (reset_tree_view_model), ia);
434
435
436   repopulate_delimiter_columns (ia);
437
438   revise_fields_preview (ia);
439   choose_likely_separators (ia);
440 }
441
442 /* Resets IA's intro page to its initial state. */
443 static void
444 reset_intro_page (PsppireImportAssistant *ia)
445 {
446   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ia->all_cases_button),
447                                 TRUE);
448 }
449
450
451
452 /* Clears the set of user-modified variables from IA's formats
453    substructure.  This discards user modifications to variable
454    formats, thereby causing formats to revert to their
455    defaults.  */
456 static void
457 reset_formats_page (PsppireImportAssistant *ia, GtkWidget *page)
458 {
459   size_t i;
460
461   for (i = 0; i < ia->modified_var_cnt; i++)
462     var_destroy (ia->modified_vars[i]);
463   free (ia->modified_vars);
464   ia->modified_vars = NULL;
465   ia->modified_var_cnt = 0;
466 }
467
468 static void prepare_formats_page (PsppireImportAssistant *ia);
469
470 /* Called when the Reset button is clicked. */
471 static void
472 on_reset (GtkButton *button, PsppireImportAssistant *ia)
473 {
474   gint pn = gtk_assistant_get_current_page (GTK_ASSISTANT (ia));
475   {
476     GtkWidget *page =  gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), pn);
477
478     page_func *on_reset = g_object_get_data (G_OBJECT (page), "on-reset");
479
480     if (on_reset)
481       on_reset (ia, page);
482   }
483 }
484
485
486 static gint
487 next_page_func (gint old_page, gpointer data)
488 {
489   return old_page + 1;
490 }
491
492
493 /* Called just before PAGE is displayed as the current page of
494    IMPORT_ASSISTANT, this updates IA content according to the new
495    page. */
496 static void
497 on_prepare (GtkAssistant *assistant, GtkWidget *page, PsppireImportAssistant *ia)
498 {
499   gtk_widget_show (ia->reset_button);
500   gtk_widget_hide (ia->paste_button);
501
502   gint pn = gtk_assistant_get_current_page (assistant);
503   gint previous_page_index = ia->current_page;
504
505   if (previous_page_index >= 0)
506     {
507       GtkWidget *closing_page = gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), previous_page_index);
508
509       if (pn > previous_page_index)
510         {
511           page_func *on_forward = g_object_get_data (G_OBJECT (closing_page), "on-forward");
512
513           if (on_forward)
514             on_forward (ia, closing_page);
515         }
516       else
517         {
518           page_func *on_back = g_object_get_data (G_OBJECT (closing_page), "on-back");
519
520           if (on_back)
521             on_back (ia, closing_page);
522         }
523     }
524
525   {
526     GtkWidget *new_page = gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), pn);
527
528     page_func *on_entering = g_object_get_data (G_OBJECT (new_page), "on-entering");
529
530     if (on_entering)
531       on_entering (ia, new_page);
532   }
533
534   ia->current_page = pn;
535 }
536
537 /* Called when the Cancel button in the assistant is clicked. */
538 static void
539 on_cancel (GtkAssistant *assistant, PsppireImportAssistant *ia)
540 {
541   close_assistant (ia, GTK_RESPONSE_CANCEL);
542 }
543
544 /* Called when the Apply button on the last page of the assistant
545    is clicked. */
546 static void
547 on_close (GtkAssistant *assistant, PsppireImportAssistant *ia)
548 {
549   close_assistant (ia, GTK_RESPONSE_APPLY);
550 }
551
552
553 /* Increments the "watch cursor" level, setting the cursor for
554    the assistant window to a watch face to indicate to the user
555    that the ongoing operation may take some time. */
556 static void
557 push_watch_cursor (PsppireImportAssistant *ia)
558 {
559   if (++ia->watch_cursor == 1)
560     {
561       GtkWidget *widget = GTK_WIDGET (ia);
562       GdkDisplay *display = gtk_widget_get_display (widget);
563       GdkCursor *cursor = gdk_cursor_new_for_display (display, GDK_WATCH);
564       gdk_window_set_cursor (gtk_widget_get_window (widget), cursor);
565       g_object_unref (cursor);
566       gdk_display_flush (display);
567     }
568 }
569
570 /* Decrements the "watch cursor" level.  If the level reaches
571    zero, the cursor is reset to its default shape. */
572 static void
573 pop_watch_cursor (PsppireImportAssistant *ia)
574 {
575   if (--ia->watch_cursor == 0)
576     {
577       GtkWidget *widget = GTK_WIDGET (ia);
578       gdk_window_set_cursor (gtk_widget_get_window (widget), NULL);
579     }
580 }
581
582 #if SHEET_MERGE
583 static gint
584 get_string_width (GtkWidget *treeview, GtkCellRenderer *renderer,
585                   const char *string)
586 {
587   gint width;
588   g_object_set (G_OBJECT (renderer), "text", string, (void *) NULL);
589   gtk_cell_renderer_get_preferred_width (renderer, treeview,
590                                          NULL, &width);
591   return width;
592 }
593
594 static gint
595 get_monospace_width (GtkWidget *treeview, GtkCellRenderer *renderer,
596                      size_t char_cnt)
597 {
598   struct string s;
599   gint width;
600
601   ds_init_empty (&s);
602   ds_put_byte_multiple (&s, '0', char_cnt);
603   ds_put_byte (&s, ' ');
604   width = get_string_width (treeview, renderer, ds_cstr (&s));
605   ds_destroy (&s);
606
607   return width;
608 }
609
610 static GtkWidget *
611 make_tree_view (const PsppireImportAssistant *ia)
612 {
613   GtkWidget *tree_view = pspp_sheet_view_new ();
614   pspp_sheet_view_set_grid_lines (PSPP_SHEET_VIEW (tree_view), PSPP_SHEET_VIEW_GRID_LINES_BOTH);
615
616   add_line_number_column (ia, tree_view);
617
618   return tree_view;
619 }
620 #endif
621
622 static GtkWidget *
623 add_page_to_assistant (PsppireImportAssistant *ia,
624                        GtkWidget *page, GtkAssistantPageType type, const gchar *);
625
626
627 static void
628 on_sheet_combo_changed (GtkComboBox *cb, PsppireImportAssistant *ia)
629 {
630   GtkTreeIter iter;
631   gchar *range = NULL;
632   GtkTreeModel *model = gtk_combo_box_get_model (cb);
633   GtkBuilder *builder = ia->builder;
634   GtkWidget *range_entry = get_widget_assert (builder, "cell-range-entry");
635
636   gtk_combo_box_get_active_iter (cb, &iter);
637   gtk_tree_model_get (model, &iter, PSPPIRE_SPREADSHEET_MODEL_COL_RANGE, &range, -1);
638   gtk_entry_set_text (GTK_ENTRY (range_entry), range ?  range : "");
639   g_free (range);
640 }
641
642 /* Prepares IA's sheet_spec page. */
643 static void
644 prepare_sheet_spec_page (PsppireImportAssistant *ia)
645 {
646   GtkBuilder *builder = ia->builder;
647   GtkWidget *sheet_entry = get_widget_assert (builder, "sheet-entry");
648   GtkWidget *readnames_checkbox = get_widget_assert (builder, "readnames-checkbox");
649
650   gtk_combo_box_set_model (GTK_COMBO_BOX (sheet_entry),
651                            psppire_spreadsheet_model_new (ia->spreadsheet));
652
653   gtk_combo_box_set_active (GTK_COMBO_BOX (sheet_entry), 0);
654
655   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (readnames_checkbox), FALSE);
656 }
657
658
659 /* Initializes IA's sheet_spec substructure. */
660 static void
661 sheet_spec_page_create (PsppireImportAssistant *ia)
662 {
663   GtkBuilder *builder = ia->builder;
664   GtkWidget *page = get_widget_assert (builder, "Spreadsheet-Importer");
665
666   GtkWidget *combo_box = get_widget_assert (builder, "sheet-entry");
667   GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
668   gtk_cell_layout_clear (GTK_CELL_LAYOUT (combo_box));
669   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), renderer, TRUE);
670   gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), renderer,
671                                   "text", 0,
672                                   NULL);
673
674   g_signal_connect (combo_box, "changed", G_CALLBACK (on_sheet_combo_changed), ia);
675
676   add_page_to_assistant (ia, page,
677                          GTK_ASSISTANT_PAGE_CONTENT, _("Importing Spreadsheet Data"));
678
679   g_object_set_data (G_OBJECT (page), "on-entering", prepare_sheet_spec_page);
680 }
681
682 static void
683 on_chosen (PsppireImportAssistant *ia, GtkWidget *page)
684 {
685   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
686   gchar *f = gtk_file_chooser_get_filename (fc);
687   int i;
688
689   for(i = gtk_assistant_get_n_pages (GTK_ASSISTANT (ia)); i > 0; --i)
690     gtk_assistant_remove_page (GTK_ASSISTANT (ia), i);
691
692   gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), GTK_WIDGET (fc), FALSE);
693
694   if (f && !g_file_test (f, G_FILE_TEST_IS_DIR))
695     {
696       gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), GTK_WIDGET (fc), TRUE);
697
698       if (ia->spreadsheet)
699         spreadsheet_unref (ia->spreadsheet);
700
701       ia->spreadsheet = gnumeric_probe (f, FALSE);
702
703       if (!ia->spreadsheet)
704         ia->spreadsheet = ods_probe (f, FALSE);
705
706       if (!ia->spreadsheet)
707         {
708           intro_page_create (ia);
709           first_line_page_create (ia);
710           separators_page_create (ia);
711         }
712       else
713         {
714           sheet_spec_page_create (ia);
715         }
716
717       formats_page_create (ia);
718     }
719
720   g_free (f);
721 }
722
723 /* This has to be done on a map signal callback,
724    because GtkFileChooserWidget resets everything when it is mapped. */
725 static void
726 on_map (PsppireImportAssistant *ia, GtkWidget *page)
727 {
728 #if TEXT_FILE
729   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
730
731   if (ia->file_name)
732     gtk_file_chooser_set_filename (fc, ia->file_name);
733 #endif
734
735   on_chosen (ia, page);
736 }
737
738
739
740 static void
741 chooser_page_enter (PsppireImportAssistant *ia, GtkWidget *page)
742 {
743 }
744
745 static void
746 chooser_page_leave (PsppireImportAssistant *ia, GtkWidget *page)
747 {
748   g_print ("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__);
749   g_free (ia->file_name);
750   ia->file_name = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (page));
751   gchar *encoding = psppire_encoding_selector_get_encoding (ia->encoding_selector);
752
753   if (!ia->spreadsheet)
754     {
755       ia->text_file = psppire_text_file_new (ia->file_name, encoding);
756       gtk_tree_view_set_model (GTK_TREE_VIEW (ia->first_line_tree_view),
757                                GTK_TREE_MODEL (ia->text_file));
758     }
759
760
761   g_free (encoding);
762 }
763
764 static void
765 chooser_page_reset (PsppireImportAssistant *ia, GtkWidget *page)
766 {
767   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
768
769   gtk_file_chooser_set_filter (fc, ia->default_filter);
770   gtk_file_chooser_unselect_all (fc);
771
772   on_chosen (ia, page);
773 }
774
775
776
777 static void
778 chooser_page_create (PsppireImportAssistant *ia)
779 {
780   GtkFileFilter *filter = NULL;
781
782   GtkWidget *chooser = gtk_file_chooser_widget_new (GTK_FILE_CHOOSER_ACTION_OPEN);
783
784   g_object_set_data (G_OBJECT (chooser), "on-forward", chooser_page_leave);
785   g_object_set_data (G_OBJECT (chooser), "on-reset",   chooser_page_reset);
786   g_object_set_data (G_OBJECT (chooser), "on-entering",chooser_page_enter);
787
788   g_object_set (chooser, "local-only", FALSE, NULL);
789
790
791   ia->default_filter = gtk_file_filter_new ();
792   gtk_file_filter_set_name (ia->default_filter, _("All Files"));
793   gtk_file_filter_add_pattern (ia->default_filter, "*");
794   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), ia->default_filter);
795
796   filter = gtk_file_filter_new ();
797   gtk_file_filter_set_name (filter, _("Text Files"));
798   gtk_file_filter_add_mime_type (filter, "text/*");
799   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
800
801   filter = gtk_file_filter_new ();
802   gtk_file_filter_set_name (filter, _("Text (*.txt) Files"));
803   gtk_file_filter_add_pattern (filter, "*.txt");
804   gtk_file_filter_add_pattern (filter, "*.TXT");
805   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
806
807   filter = gtk_file_filter_new ();
808   gtk_file_filter_set_name (filter, _("Plain Text (ASCII) Files"));
809   gtk_file_filter_add_mime_type (filter, "text/plain");
810   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
811
812   filter = gtk_file_filter_new ();
813   gtk_file_filter_set_name (filter, _("Comma Separated Value Files"));
814   gtk_file_filter_add_mime_type (filter, "text/csv");
815   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
816
817   /* I've never encountered one of these, but it's listed here:
818      http://www.iana.org/assignments/media-types/text/tab-separated-values  */
819   filter = gtk_file_filter_new ();
820   gtk_file_filter_set_name (filter, _("Tab Separated Value Files"));
821   gtk_file_filter_add_mime_type (filter, "text/tab-separated-values");
822   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
823
824   filter = gtk_file_filter_new ();
825   gtk_file_filter_set_name (filter, _("Gnumeric Spreadsheet Files"));
826   gtk_file_filter_add_mime_type (filter, "application/x-gnumeric");
827   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
828
829   filter = gtk_file_filter_new ();
830   gtk_file_filter_set_name (filter, _("OpenDocument Spreadsheet Files"));
831   gtk_file_filter_add_mime_type (filter, "application/vnd.oasis.opendocument.spreadsheet");
832   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
833
834   filter = gtk_file_filter_new ();
835   gtk_file_filter_set_name (filter, _("All Spreadsheet Files"));
836   gtk_file_filter_add_mime_type (filter, "application/x-gnumeric");
837   gtk_file_filter_add_mime_type (filter, "application/vnd.oasis.opendocument.spreadsheet");
838   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
839
840   ia->encoding_selector = psppire_encoding_selector_new ("Auto", TRUE);
841   gtk_file_chooser_set_extra_widget (GTK_FILE_CHOOSER (chooser), ia->encoding_selector);
842
843   add_page_to_assistant (ia, chooser,
844                          GTK_ASSISTANT_PAGE_INTRO, _("Select File to Import"));
845
846   g_signal_connect_swapped (chooser, "selection-changed", G_CALLBACK (on_chosen), ia);
847   g_signal_connect_swapped (chooser, "map", G_CALLBACK (on_map), ia);
848 }
849
850
851
852 static void
853 psppire_import_assistant_init (PsppireImportAssistant *ia)
854 {
855   ia->builder = builder_new ("text-data-import.ui");
856
857   ia->current_page = -1 ;
858   /* ia->column_cnt = 0; */
859   /* ia->columns = NULL; */
860
861   ia->file_name = NULL;
862
863   ia->spreadsheet = NULL;
864   ia->watch_cursor = 0;
865
866   ia->prop_renderer = gtk_cell_renderer_text_new ();
867   g_object_ref_sink (ia->prop_renderer);
868   ia->fixed_renderer = gtk_cell_renderer_text_new ();
869   g_object_ref_sink (ia->fixed_renderer);
870   g_object_set (G_OBJECT (ia->fixed_renderer),
871                 "family", "Monospace",
872                 (void *) NULL);
873
874   g_signal_connect (ia, "prepare", G_CALLBACK (on_prepare), ia);
875   g_signal_connect (ia, "cancel", G_CALLBACK (on_cancel), ia);
876   g_signal_connect (ia, "close", G_CALLBACK (on_close), ia);
877
878   ia->paste_button = gtk_button_new_with_label (_("Paste"));
879   ia->reset_button = gtk_button_new_with_label (_("Reset"));
880
881   gtk_assistant_add_action_widget (GTK_ASSISTANT(ia), ia->paste_button);
882
883   g_signal_connect (ia->paste_button, "clicked", G_CALLBACK (on_paste), ia);
884   g_signal_connect (ia->reset_button, "clicked", G_CALLBACK (on_reset), ia);
885
886   gtk_assistant_add_action_widget (GTK_ASSISTANT(ia), ia->reset_button);
887
888   gtk_window_set_title (GTK_WINDOW (ia),
889                         _("Importing Delimited Text Data"));
890
891   gtk_window_set_icon_name (GTK_WINDOW (ia), "pspp");
892
893   chooser_page_create (ia);
894
895   gtk_assistant_set_forward_page_func (GTK_ASSISTANT (ia), next_page_func, NULL, NULL);
896
897   gtk_window_maximize (GTK_WINDOW (ia));
898 }
899
900
901 /* Appends a page of the given TYPE, with PAGE as its content, to
902    the GtkAssistant encapsulated by IA.  Returns the GtkWidget
903    that represents the page. */
904 static GtkWidget *
905 add_page_to_assistant (PsppireImportAssistant *ia,
906                        GtkWidget *page, GtkAssistantPageType type, const gchar *title)
907 {
908   GtkWidget *content = page;
909
910   gtk_assistant_append_page (GTK_ASSISTANT (ia), content);
911   gtk_assistant_set_page_type (GTK_ASSISTANT(ia), content, type);
912   gtk_assistant_set_page_title (GTK_ASSISTANT(ia), content, title);
913   gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), content, TRUE);
914
915   return content;
916 }
917
918
919 /* Called when one of the radio buttons is clicked. */
920 static void
921 on_intro_amount_changed (PsppireImportAssistant *p)
922 {
923   gtk_widget_set_sensitive (p->n_cases_spin,
924                             gtk_toggle_button_get_active (
925                                                           GTK_TOGGLE_BUTTON (p->n_cases_button)));
926
927   gtk_widget_set_sensitive (p->percent_spin,
928                             gtk_toggle_button_get_active (
929                                                           GTK_TOGGLE_BUTTON (p->percent_button)));
930 }
931
932
933 #if SHEET_MERGE
934
935
936 /* Sets IA's first_line substructure to match the widgets. */
937 static void
938 set_first_line_options (PsppireImportAssistant *ia)
939 {
940   GtkTreeIter iter;
941   GtkTreeModel *model;
942
943   PsppSheetSelection *selection = pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view));
944   if (pspp_sheet_selection_get_selected (selection, &model, &iter))
945     {
946       GtkTreePath *path = gtk_tree_model_get_path (model, &iter);
947       int row = gtk_tree_path_get_indices (path)[0];
948       gtk_tree_path_free (path);
949
950       ia->skip_lines = row;
951       ia->variable_names =
952         (ia->skip_lines > 0
953          && gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)));
954     }
955
956   gtk_widget_set_sensitive (ia->variable_names_cb, ia->skip_lines > 0);
957 }
958
959
960
961 static void
962 reset_first_line_page (PsppireImportAssistant *ia)
963 {
964   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb), FALSE);
965   PsppSheetSelection *selection = pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view));
966   pspp_sheet_selection_unselect_all (selection);
967   gtk_widget_set_sensitive (ia->variable_names_cb, FALSE);
968 }
969
970 #endif
971
972 static void
973 on_treeview_selection_change (PsppireImportAssistant *ia)
974 {
975   GtkTreeSelection *selection =
976     gtk_tree_view_get_selection (GTK_TREE_VIEW (ia->first_line_tree_view));
977   GtkTreeModel *model = NULL;
978   GtkTreeIter iter;
979   if (gtk_tree_selection_get_selected (selection, &model, &iter))
980     {
981       int n;
982       GtkTreePath *path = gtk_tree_model_get_path (model, &iter);
983       gint *index = gtk_tree_path_get_indices (path);
984
985       n = *index;
986
987       gtk_tree_path_free (path);
988
989       gtk_widget_set_sensitive (ia->variable_names_cb, n > 0);
990
991       ia->delimiters_model
992         = psppire_delimited_text_new (GTK_TREE_MODEL (ia->text_file));
993       g_object_set (ia->delimiters_model, "first-line", n, NULL);
994
995       //      ia->skip_lines = n;
996     }
997 }
998
999
1000 /* Initializes IA's first_line substructure. */
1001 static void
1002 first_line_page_create (PsppireImportAssistant *ia)
1003 {
1004   g_print ("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__);
1005   GtkWidget *w =  get_widget_assert (ia->builder, "FirstLine");
1006
1007   g_object_set_data (G_OBJECT (w), "on-entering", on_treeview_selection_change);
1008
1009   add_page_to_assistant (ia, w,
1010                          GTK_ASSISTANT_PAGE_CONTENT, _("Select the First Line"));
1011
1012   GtkWidget *scrolled_window = get_widget_assert (ia->builder, "first-line-scroller");
1013
1014   if (ia->first_line_tree_view == NULL)
1015     {
1016       ia->first_line_tree_view = gtk_tree_view_new ();
1017
1018       gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (ia->first_line_tree_view), TRUE);
1019
1020       GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
1021       GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes (_("Line"), renderer,
1022                                                                             "text", 0,
1023                                                                             NULL);
1024       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->first_line_tree_view), column);
1025
1026       renderer = gtk_cell_renderer_text_new ();
1027       column = gtk_tree_view_column_new_with_attributes (_("Text"), renderer, "text", 1, NULL);
1028       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->first_line_tree_view), column);
1029
1030       gtk_container_add (GTK_CONTAINER (scrolled_window), ia->first_line_tree_view);
1031
1032       g_signal_connect_swapped (ia->first_line_tree_view, "cursor-changed",
1033                         G_CALLBACK (on_treeview_selection_change), ia);
1034     }
1035   gtk_widget_show_all (scrolled_window);
1036
1037   ia->variable_names_cb = get_widget_assert (ia->builder, "variable-names");
1038
1039 #if SHEET_MERGE
1040   pspp_sheet_selection_set_mode (
1041                                  pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view)),
1042                                  PSPP_SHEET_SELECTION_BROWSE);
1043   pspp_sheet_view_set_rubber_banding (PSPP_SHEET_VIEW (ia->tree_view), TRUE);
1044
1045
1046   g_signal_connect_swapped (pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view)),
1047                             "changed", G_CALLBACK (set_first_line_options), ia);
1048
1049   g_signal_connect_swapped (ia->variable_names_cb, "toggled",
1050                             G_CALLBACK (set_first_line_options), ia);
1051
1052   g_object_set_data (G_OBJECT (w), "on-reset", reset_first_line_page);
1053 #endif
1054 }
1055
1056
1057
1058
1059 static void
1060 intro_on_enter (PsppireImportAssistant *ia)
1061 {
1062   GtkBuilder *builder = ia->builder;
1063   GtkWidget *table  = get_widget_assert (builder, "button-table");
1064
1065   struct string s;
1066
1067   ds_init_empty (&s);
1068   ds_put_cstr (&s, _("This assistant will guide you through the process of "
1069                      "importing data into PSPP from a text file with one line "
1070                      "per case,  in which fields are separated by tabs, "
1071                      "commas, or other delimiters.\n\n"));
1072
1073   if (ia->text_file)
1074     {
1075       if (ia->text_file->total_is_exact)
1076         {
1077           ds_put_format (
1078                          &s, ngettext ("The selected file contains %'lu line of text.  ",
1079                                        "The selected file contains %'lu lines of text.  ",
1080                                        ia->text_file->total_lines),
1081                          ia->text_file->total_lines);
1082         }
1083       else if (ia->text_file->total_lines > 0)
1084         {
1085           ds_put_format (
1086                          &s, ngettext (
1087                                        "The selected file contains approximately %'lu line of text.  ",
1088                                        "The selected file contains approximately %'lu lines of text.  ",
1089                                        ia->text_file->total_lines),
1090                          ia->text_file->total_lines);
1091           ds_put_format (
1092                          &s, ngettext (
1093                                        "Only the first %zu line of the file will be shown for "
1094                                        "preview purposes in the following screens.  ",
1095                                        "Only the first %zu lines of the file will be shown for "
1096                                        "preview purposes in the following screens.  ",
1097                                        ia->text_file->line_cnt),
1098                          ia->text_file->line_cnt);
1099         }
1100     }
1101
1102   ds_put_cstr (&s, _("You may choose below how much of the file should "
1103                      "actually be imported."));
1104
1105   gtk_label_set_text (GTK_LABEL (get_widget_assert (builder, "intro-label")),
1106                       ds_cstr (&s));
1107   ds_destroy (&s);
1108
1109   GtkWidget *w  =  gtk_grid_get_child_at (GTK_GRID (table), 1, 1);
1110   int old_value = w ? gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (ia->n_cases_spin)) : 1;
1111   if (w)
1112     gtk_container_remove (GTK_CONTAINER (table), w);
1113
1114   w  =  gtk_grid_get_child_at (GTK_GRID (table), 1, 2);
1115   if (w)
1116     gtk_container_remove (GTK_CONTAINER (table), w);
1117
1118
1119   GtkWidget *hbox_n_cases = psppire_scanf_new (_("Only the first %4d cases"), &ia->n_cases_spin);
1120
1121   GtkAdjustment *adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (ia->n_cases_spin));
1122   gtk_adjustment_set_lower (adj, 1.0);
1123
1124   if (ia->text_file)
1125     {
1126       if (psppire_text_file_get_total_exact (ia->text_file))
1127         {
1128           gulong total_lines = psppire_text_file_get_n_lines (ia->text_file);
1129           gtk_adjustment_set_upper (adj, total_lines);
1130           gtk_adjustment_set_value (adj, old_value);
1131         }
1132       else
1133         gtk_adjustment_set_upper (adj, DBL_MAX);
1134     }
1135   gtk_grid_attach (GTK_GRID (table), hbox_n_cases,
1136                    1, 1,
1137                    1, 1);
1138
1139
1140   GtkWidget *hbox_percent = psppire_scanf_new (_("Only the first %3d %% of file (approximately)"),
1141                                                &ia->percent_spin);
1142
1143   gtk_grid_attach (GTK_GRID (table), hbox_percent,
1144                    1, 2,
1145                    1, 1);
1146
1147   gtk_widget_show_all (table);
1148
1149   on_intro_amount_changed (ia);
1150 }
1151
1152 /* Initializes IA's intro substructure. */
1153 static void
1154 intro_page_create (PsppireImportAssistant *ia)
1155 {
1156   GtkBuilder *builder = ia->builder;
1157
1158   GtkWidget *w =  get_widget_assert (builder, "Intro");
1159
1160   ia->percent_spin = gtk_spin_button_new_with_range (0, 100, 10);
1161
1162
1163   add_page_to_assistant (ia, w,  GTK_ASSISTANT_PAGE_CONTENT, _("Select the Lines to Import"));
1164
1165   ia->all_cases_button = get_widget_assert (builder, "import-all-cases");
1166
1167   ia->n_cases_button = get_widget_assert (builder, "import-n-cases");
1168
1169   ia->percent_button = get_widget_assert (builder, "import-percent");
1170
1171   g_signal_connect_swapped (ia->all_cases_button, "toggled",
1172                             G_CALLBACK (on_intro_amount_changed), ia);
1173   g_signal_connect_swapped (ia->n_cases_button, "toggled",
1174                             G_CALLBACK (on_intro_amount_changed), ia);
1175   g_signal_connect_swapped (ia->percent_button, "toggled",
1176                             G_CALLBACK (on_intro_amount_changed), ia);
1177
1178
1179   g_object_set_data (G_OBJECT (w), "on-entering", intro_on_enter);
1180   g_object_set_data (G_OBJECT (w), "on-reset", reset_intro_page);
1181 }
1182
1183
1184 GtkWidget *
1185 psppire_import_assistant_new (GtkWindow *toplevel)
1186 {
1187   return GTK_WIDGET (g_object_new (PSPPIRE_TYPE_IMPORT_ASSISTANT,
1188                                    /* Some window managers (notably ratpoison)
1189                                       ignore the maximise command when a window is
1190                                       transient.  This causes problems for this
1191                                       window. */
1192                                    /* "transient-for", toplevel, */
1193                                    NULL));
1194 }
1195
1196
1197
1198 \f
1199
1200 struct column
1201 {
1202   /* Variable name for this column.  This is the variable name
1203      used on the separators page; it can be overridden by the
1204      user on the formats page. */
1205   char *name;
1206
1207   /* Maximum length of any row in this column. */
1208   size_t width;
1209
1210   /* Contents of this column: contents[row] is the contents for
1211      the given row.
1212
1213      A null substring indicates a missing column for that row
1214      (because the line contains an insufficient number of
1215      separators).
1216
1217      contents[] elements may be substrings of the lines[]
1218      strings that represent the whole lines of the file, to
1219      save memory.  Other elements are dynamically allocated
1220      with ss_alloc_substring. */
1221   struct substring *contents;
1222 };
1223
1224 #if SHEET_MERGE
1225
1226 /* Called to render one of the cells in the fields preview tree
1227    view. */
1228 static void
1229 render_input_cell (PsppSheetViewColumn *tree_column, GtkCellRenderer *cell,
1230                    GtkTreeModel *model, GtkTreeIter *iter,
1231                    gpointer ia_)
1232 {
1233   PsppireImportAssistant *ia = ia_;
1234   struct substring field;
1235   size_t row;
1236   gint column;
1237
1238   column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1239                                                "column-number"));
1240   row = empty_list_store_iter_to_row (iter) + ia->skip_lines;
1241   field = ia->columns[column].contents[row];
1242   if (field.string != NULL)
1243     {
1244       GValue text = {0, };
1245       g_value_init (&text, G_TYPE_STRING);
1246       g_value_take_string (&text, ss_xstrdup (field));
1247       g_object_set_property (G_OBJECT (cell), "text", &text);
1248       g_value_unset (&text);
1249       g_object_set (cell, "background-set", FALSE, (void *) NULL);
1250     }
1251   else
1252     g_object_set (cell,
1253                   "text", "",
1254                   "background", "red",
1255                   "background-set", TRUE,
1256                   (void *) NULL);
1257 }
1258
1259 /* Parses the contents of the field at (ROW,COLUMN) according to
1260    its variable format.  If OUTPUTP is non-null, then *OUTPUTP
1261    receives the formatted output for that field (which must be
1262    freed with free).  If TOOLTIPP is non-null, then *TOOLTIPP
1263    receives a message suitable for use in a tooltip, if one is
1264    needed, or a null pointer otherwise.  Returns TRUE if a
1265    tooltip message is needed, otherwise FALSE. */
1266 static bool
1267 parse_field (PsppireImportAssistant *ia,
1268              size_t row, size_t column,
1269              char **outputp, char **tooltipp)
1270 {
1271   const struct fmt_spec *in;
1272   struct fmt_spec out;
1273   char *tooltip;
1274   bool ok;
1275
1276   struct substring field = ia->columns[column].contents[row];
1277   const struct variable *var = dict_get_var (ia->dict, column);
1278   union value val;
1279
1280   value_init (&val, var_get_width (var));
1281   in = var_get_print_format (var);
1282   out = fmt_for_output_from_input (in);
1283   tooltip = NULL;
1284   if (field.string != NULL)
1285     {
1286       char *error = data_in (field, "UTF-8", in->type, &val, var_get_width (var),
1287                              dict_get_encoding (ia->dict));
1288       if (error != NULL)
1289         {
1290           tooltip = xasprintf (_("Cannot parse field content `%.*s' as "
1291                                  "format %s: %s"),
1292                                (int) field.length, field.string,
1293                                fmt_name (in->type), error);
1294           free (error);
1295         }
1296     }
1297   else
1298     {
1299       tooltip = xstrdup (_("This input line has too few separators "
1300                            "to fill in this field."));
1301       value_set_missing (&val, var_get_width (var));
1302     }
1303   if (outputp != NULL)
1304     {
1305       *outputp = data_out (&val, dict_get_encoding (ia->dict),  &out);
1306     }
1307   value_destroy (&val, var_get_width (var));
1308
1309   ok = tooltip == NULL;
1310   if (tooltipp != NULL)
1311     *tooltipp = tooltip;
1312   else
1313     free (tooltip);
1314   return ok;
1315 }
1316
1317 /* Called to render one of the cells in the data preview tree
1318    view. */
1319 static void
1320 render_output_cell (PsppSheetViewColumn *tree_column,
1321                     GtkCellRenderer *cell,
1322                     GtkTreeModel *model,
1323                     GtkTreeIter *iter,
1324                     gpointer ia_)
1325 {
1326   PsppireImportAssistant *ia = ia_;
1327   char *output;
1328   GValue gvalue = { 0, };
1329   bool ok = parse_field (ia,
1330                          (empty_list_store_iter_to_row (iter)
1331                           + ia->skip_lines),
1332                          GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1333                                                              "column-number")),
1334                          &output, NULL);
1335
1336   g_value_init (&gvalue, G_TYPE_STRING);
1337   g_value_take_string (&gvalue, output);
1338   g_object_set_property (G_OBJECT (cell), "text", &gvalue);
1339   g_value_unset (&gvalue);
1340
1341   if (ok)
1342     g_object_set (cell, "background-set", FALSE, (void *) NULL);
1343   else
1344     g_object_set (cell,
1345                   "background", "red",
1346                   "background-set", TRUE,
1347                   (void *) NULL);
1348 }
1349
1350
1351 /* Utility functions used by multiple pages of the assistant. */
1352
1353 static gboolean
1354 get_tooltip_location (GtkWidget *widget, gint wx, gint wy,
1355                       const PsppireImportAssistant *ia,
1356                       size_t *row, size_t *column)
1357 {
1358   PsppSheetView *tree_view = PSPP_SHEET_VIEW (widget);
1359   gint bx, by;
1360   GtkTreePath *path;
1361   GtkTreeIter iter;
1362   PsppSheetViewColumn *tree_column;
1363   GtkTreeModel *tree_model;
1364   bool ok;
1365
1366   pspp_sheet_view_convert_widget_to_bin_window_coords (tree_view,
1367                                                        wx, wy, &bx, &by);
1368   if (!pspp_sheet_view_get_path_at_pos (tree_view, bx, by,
1369                                         &path, &tree_column, NULL, NULL))
1370     return FALSE;
1371
1372   *column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1373                                                 "column-number"));
1374
1375   tree_model = pspp_sheet_view_get_model (tree_view);
1376   ok = gtk_tree_model_get_iter (tree_model, &iter, path);
1377   gtk_tree_path_free (path);
1378   if (!ok)
1379     return FALSE;
1380
1381   *row = empty_list_store_iter_to_row (&iter) + ia->skip_lines;
1382   return TRUE;
1383 }
1384
1385
1386
1387 \f
1388
1389
1390 /* Called to render a tooltip on one of the cells in the fields
1391    preview tree view. */
1392 static gboolean
1393 on_query_input_tooltip (GtkWidget *widget, gint wx, gint wy,
1394                         gboolean keyboard_mode UNUSED,
1395                         GtkTooltip *tooltip, PsppireImportAssistant *ia)
1396 {
1397   size_t row, column;
1398
1399   if (!get_tooltip_location (widget, wx, wy, ia, &row, &column))
1400     return FALSE;
1401
1402   if (ia->columns[column].contents[row].string != NULL)
1403     return FALSE;
1404
1405   gtk_tooltip_set_text (tooltip,
1406                         _("This input line has too few separators "
1407                           "to fill in this field."));
1408   return TRUE;
1409 }
1410
1411
1412 /* Called to render a tooltip for one of the cells in the data
1413    preview tree view. */
1414 static gboolean
1415 on_query_output_tooltip (GtkWidget *widget, gint wx, gint wy,
1416                          gboolean keyboard_mode UNUSED,
1417                          GtkTooltip *tooltip, PsppireImportAssistant *ia)
1418 {
1419   size_t row, column;
1420   char *text;
1421
1422   if (!gtk_widget_get_mapped (widget))
1423     return FALSE;
1424
1425   if (!get_tooltip_location (widget, wx, wy, ia, &row, &column))
1426     return FALSE;
1427
1428   if (parse_field (ia, row, column, NULL, &text))
1429     return FALSE;
1430
1431   gtk_tooltip_set_text (tooltip, text);
1432   free (text);
1433   return TRUE;
1434 }
1435 #endif
1436 \f
1437
1438
1439 static void
1440 set_quote_list (GtkComboBox *cb)
1441 {
1442   GtkListStore *list =  gtk_list_store_new (1, G_TYPE_STRING);
1443   GtkTreeIter iter;
1444   gint i;
1445   const gchar *separator[3] = {"'\"", "\'", "\""};
1446
1447   for (i = 0; i < 3; i++)
1448     {
1449       const gchar *s = separator[i];
1450
1451       /* Add a new row to the model */
1452       gtk_list_store_append (list, &iter);
1453       gtk_list_store_set (list, &iter,
1454                           0, s,
1455                           -1);
1456
1457     }
1458
1459   gtk_combo_box_set_model (GTK_COMBO_BOX (cb), GTK_TREE_MODEL (list));
1460   g_object_unref (list);
1461
1462   gtk_combo_box_set_entry_text_column (cb, 0);
1463 }
1464
1465
1466 #if SHEET_MERGE
1467
1468 /* Sets IA's separators substructure to match the widgets. */
1469 static void
1470 get_separators (PsppireImportAssistant *ia)
1471 {
1472   int i;
1473
1474   ds_clear (&ia->separators);
1475   for (i = 0; i < SEPARATOR_CNT; i++)
1476     {
1477       const struct separator *sep = &separators[i];
1478       GtkWidget *button = get_widget_assert (ia->builder, sep->name);
1479       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
1480         ds_put_byte (&ia->separators, sep->c);
1481     }
1482
1483   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->custom_cb)))
1484     ds_put_cstr (&ia->separators,
1485                  gtk_entry_get_text (GTK_ENTRY (ia->custom_entry)));
1486
1487   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->quote_cb)))
1488     {
1489       const gchar *text = gtk_entry_get_text (GTK_ENTRY (gtk_bin_get_child (GTK_BIN (ia->quote_combo))));
1490       ds_assign_cstr (&ia->quotes, text);
1491     }
1492   else
1493     ds_clear (&ia->quotes);
1494 }
1495
1496
1497
1498
1499
1500
1501 /* Breaks the file data in IA into columns based on the
1502    separators set in IA's separators substructure. */
1503 static void
1504 split_fields (PsppireImportAssistant *ia)
1505 {
1506   size_t columns_allocated;
1507   bool space_sep;
1508   size_t row = 0;
1509
1510   /* Is space in the set of separators? */
1511   space_sep = ss_find_byte (ds_ss (&ia->separators), ' ') != SIZE_MAX;
1512
1513   /* Split all the lines, not just those from
1514      ia->first_line.skip_lines on, so that we split the line that
1515      contains variables names if ia->first_line.variable_names is
1516      TRUE. */
1517   columns_allocated = 0;
1518
1519   gint n_lines = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (ia->text_file), NULL);
1520   GtkTreeIter iter;
1521   gtk_tree_model_get_iter_first (GTK_TREE_MODEL (ia->text_file), &iter);
1522   while (gtk_tree_model_iter_next (GTK_TREE_MODEL (ia->text_file), &iter))
1523     {
1524       row++;
1525       gchar *line_text;
1526       gtk_tree_model_get (GTK_TREE_MODEL (ia->text_file), &iter, 1, &line_text, -1);
1527       struct substring text = ss_cstr (line_text);
1528       g_free (line_text);
1529       size_t column_idx;
1530
1531       for (column_idx = 0; ;column_idx++)
1532         {
1533           struct substring field = SS_EMPTY_INITIALIZER;
1534           struct column *column;
1535
1536           if (space_sep)
1537             {
1538               ss_ltrim (&text, ss_cstr (" "));
1539             }
1540           if (ss_is_empty (text))
1541             {
1542               if (column_idx != 0)
1543                 break;
1544               field = text;
1545             }
1546           else if (!ds_is_empty (&ia->quotes)
1547                    && ds_find_byte (&ia->quotes, text.string[0]) != SIZE_MAX)
1548             {
1549               int quote = ss_get_byte (&text);
1550               struct string s;
1551               int c;
1552
1553               ds_init_empty (&s);
1554               while ((c = ss_get_byte (&text)) != EOF)
1555                 if (c != quote)
1556                   ds_put_byte (&s, c);
1557                 else if (ss_match_byte (&text, quote))
1558                   ds_put_byte (&s, quote);
1559                 else
1560                   break;
1561               field = ds_ss (&s);
1562             }
1563           else
1564             {
1565               ss_get_bytes (&text, ss_cspan (text, ds_ss (&ia->separators)),
1566                             &field);
1567             }
1568
1569           if (column_idx >= ia->column_cnt)
1570             {
1571               struct column *column;
1572
1573               if (ia->column_cnt >= columns_allocated)
1574                 {
1575                   ia->columns = x2nrealloc (ia->columns, &columns_allocated,
1576                                             sizeof *ia->columns);
1577                 }
1578               column = &ia->columns[ia->column_cnt++];
1579               column->name = NULL;
1580               column->width = 0;
1581               column->contents = xcalloc (n_lines,
1582                                           sizeof *column->contents);
1583             }
1584           column = &ia->columns[column_idx];
1585           column->contents[row] = field;
1586           if (ss_length (field) > column->width)
1587             column->width = ss_length (field);
1588
1589           if (space_sep)
1590             ss_ltrim (&text, ss_cstr (" "));
1591           if (ss_is_empty (text))
1592             break;
1593           if (ss_find_byte (ds_ss (&ia->separators), ss_first (text))
1594               != SIZE_MAX)
1595             ss_advance (&text, 1);
1596         }
1597     }
1598 }
1599
1600 #endif
1601
1602 /* Chooses a name for each column on the separators page */
1603 static void
1604 choose_column_names (PsppireImportAssistant *ia)
1605 {
1606   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)))
1607     {
1608       int i;
1609       unsigned long int generated_name_count = 0;
1610       dict_clear (ia->dict);
1611       for (i = 0; i < gtk_tree_model_get_n_columns (ia->delimiters_model) - 1; ++i)
1612         {
1613           const gchar *candidate_name =
1614             psppire_delimited_text_get_header_title (PSPPIRE_DELIMITED_TEXT (ia->delimiters_model), i);
1615
1616           char *name = dict_make_unique_var_name (ia->dict, candidate_name, &generated_name_count);
1617           dict_create_var_assert (ia->dict, name, 0);
1618           free (name);
1619         }
1620     }
1621 }
1622
1623
1624
1625 /* Called when the user toggles one of the separators
1626    checkboxes. */
1627 static void
1628 on_separator_toggle (GtkToggleButton *toggle UNUSED,
1629                      PsppireImportAssistant *ia)
1630 {
1631   int i;
1632   GSList *delimiters = NULL;
1633   for (i = 0; i < SEPARATOR_CNT; i++)
1634     {
1635       const struct separator *s = &separators[i];
1636       GtkWidget *button = get_widget_assert (ia->builder, s->name);
1637       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
1638         {
1639           delimiters = g_slist_prepend (delimiters,  GINT_TO_POINTER (s->c));
1640         }
1641     }
1642
1643   g_object_set (ia->delimiters_model, "delimiters", delimiters, NULL);
1644
1645   //  revise_fields_preview (ia);
1646 }
1647
1648
1649 /* Called when the user changes the entry field for custom
1650    separators. */
1651 static void
1652 on_separators_custom_entry_notify (GObject *gobject UNUSED,
1653                                    GParamSpec *arg1 UNUSED,
1654                                    PsppireImportAssistant *ia)
1655 {
1656   revise_fields_preview (ia);
1657 }
1658
1659 /* Called when the user toggles the checkbox that enables custom
1660    separators. */
1661 static void
1662 on_separators_custom_cb_toggle (GtkToggleButton *custom_cb,
1663                                 PsppireImportAssistant *ia)
1664 {
1665   bool is_active = gtk_toggle_button_get_active (custom_cb);
1666   gtk_widget_set_sensitive (ia->custom_entry, is_active);
1667   revise_fields_preview (ia);
1668 }
1669
1670 /* Called when the user changes the selection in the combo box
1671    that selects a quote character. */
1672 static void
1673 on_quote_combo_change (GtkComboBox *combo, PsppireImportAssistant *ia)
1674 {
1675   //  revise_fields_preview (ia);
1676 }
1677
1678 /* Called when the user toggles the checkbox that enables
1679    quoting. */
1680 static void
1681 on_quote_cb_toggle (GtkToggleButton *quote_cb, PsppireImportAssistant *ia)
1682 {
1683   bool is_active = gtk_toggle_button_get_active (quote_cb);
1684   gtk_widget_set_sensitive (ia->quote_combo, is_active);
1685   revise_fields_preview (ia);
1686 }
1687
1688 /* Initializes IA's separators substructure. */
1689 static void
1690 separators_page_create (PsppireImportAssistant *ia)
1691 {
1692   GtkBuilder *builder = ia->builder;
1693
1694   size_t i;
1695
1696   GtkWidget *w = get_widget_assert (builder, "Separators");
1697
1698   g_object_set_data (G_OBJECT (w), "on-entering", prepare_separators_page);
1699   g_object_set_data (G_OBJECT (w), "on-reset", prepare_separators_page);
1700
1701   add_page_to_assistant (ia, w,   GTK_ASSISTANT_PAGE_CONTENT, _("Choose Separators"));
1702
1703   ia->custom_cb = get_widget_assert (builder, "custom-cb");
1704   ia->custom_entry = get_widget_assert (builder, "custom-entry");
1705   ia->quote_combo = get_widget_assert (builder, "quote-combo");
1706   ia->quote_entry = GTK_ENTRY (gtk_bin_get_child (GTK_BIN (ia->quote_combo)));
1707   ia->quote_cb = get_widget_assert (builder, "quote-cb");
1708
1709   set_quote_list (GTK_COMBO_BOX (ia->quote_combo));
1710
1711   if (ia->fields_tree_view == NULL)
1712     {
1713       GtkWidget *scroller = get_widget_assert (ia->builder, "fields-scroller");
1714       ia->fields_tree_view = gtk_tree_view_new ();
1715       gtk_container_add (GTK_CONTAINER (scroller), GTK_WIDGET (ia->fields_tree_view));
1716       gtk_widget_show_all (scroller);
1717     }
1718
1719   g_signal_connect (ia->quote_combo, "changed",
1720                     G_CALLBACK (on_quote_combo_change), ia);
1721   g_signal_connect (ia->quote_cb, "toggled",
1722                     G_CALLBACK (on_quote_cb_toggle), ia);
1723   g_signal_connect (ia->custom_entry, "notify::text",
1724                     G_CALLBACK (on_separators_custom_entry_notify), ia);
1725   g_signal_connect (ia->custom_cb, "toggled",
1726                     G_CALLBACK (on_separators_custom_cb_toggle), ia);
1727   for (i = 0; i < SEPARATOR_CNT; i++)
1728     g_signal_connect (get_widget_assert (builder, separators[i].name),
1729                       "toggled", G_CALLBACK (on_separator_toggle), ia);
1730
1731 }
1732
1733
1734
1735 \f
1736
1737 #if SHEET_MERGE
1738
1739 /* Called when the user changes one of the variables in the
1740    dictionary. */
1741 static void
1742 on_variable_change (PsppireDict *dict, int dict_idx,
1743                     unsigned int what, const struct variable *oldvar,
1744                     PsppireImportAssistant *ia)
1745 {
1746   PsppSheetView *tv = PSPP_SHEET_VIEW (ia->data_tree_view);
1747   gint column_idx = dict_idx + 1;
1748
1749   push_watch_cursor (ia);
1750
1751   /* Remove previous column and replace with new column. */
1752   pspp_sheet_view_remove_column (tv, pspp_sheet_view_get_column (PSPP_SHEET_VIEW (ia->data_tree_view), column_idx));
1753   pspp_sheet_view_insert_column (tv, PSPP_SHEET_VIEW_COLUMN (make_data_column (ia, ia->data_tree_view, FALSE, dict_idx)),
1754                                  column_idx);
1755
1756   /* Save a copy of the modified variable in modified_vars, so
1757      that its attributes will be preserved if we back up to the
1758      previous page with the Prev button and then come back
1759      here. */
1760   if (dict_idx >= ia->modified_var_cnt)
1761     {
1762       size_t i;
1763       ia->modified_vars = xnrealloc (ia->modified_vars, dict_idx + 1,
1764                                      sizeof *ia->modified_vars);
1765       for (i = 0; i <= dict_idx; i++)
1766         ia->modified_vars[i] = NULL;
1767       ia->modified_var_cnt = dict_idx + 1;
1768     }
1769   if (ia->modified_vars[dict_idx])
1770     var_destroy (ia->modified_vars[dict_idx]);
1771   ia->modified_vars[dict_idx]
1772     = var_clone (psppire_dict_get_variable (dict, dict_idx));
1773
1774   pop_watch_cursor (ia);
1775 }
1776
1777 #endif
1778
1779
1780 static struct casereader_random_class my_casereader_class;
1781
1782 static struct ccase *
1783 my_read (struct casereader *reader, void *aux, casenumber idx)
1784 {
1785   PsppireImportAssistant *ia = PSPPIRE_IMPORT_ASSISTANT (aux);
1786   GtkTreeModel *tm = GTK_TREE_MODEL (ia->delimiters_model);
1787
1788   GtkTreePath *tp = gtk_tree_path_new_from_indices (idx, -1);
1789
1790   const struct caseproto *proto = casereader_get_proto (reader);
1791
1792   GtkTreeIter iter;
1793   struct ccase *c = NULL;
1794   if (gtk_tree_model_get_iter (tm, &iter, tp))
1795     {
1796       c = case_create (proto);
1797       int i;
1798       for (i = 0 ; i < caseproto_get_n_widths (proto); ++i)
1799         {
1800           GValue value = {0};
1801           gtk_tree_model_get_value (tm, &iter, i + 1, &value);
1802
1803           const struct variable *var = dict_get_var (ia->dict, i);
1804
1805           const gchar *ss = g_value_get_string (&value);
1806
1807           union value *v = case_data_rw (c, var);
1808           char *xx = data_in (ss_cstr (ss),
1809                               "UTF-8",
1810                               var_get_write_format (var)->type,
1811                               v, var_get_width (var), "UTF-8");
1812
1813           /* if (xx) */
1814           /*   g_print ("%s:%d Err %s\n", __FILE__, __LINE__, xx); */
1815           free (xx);
1816           g_value_unset (&value);
1817         }
1818     }
1819
1820   gtk_tree_path_free (tp);
1821
1822   return c;
1823 }
1824
1825 static void
1826 my_destroy (struct casereader *reader, void *aux)
1827 {
1828   g_print ("%s:%d %p\n", __FILE__, __LINE__, reader);
1829 }
1830
1831 static void
1832 my_advance (struct casereader *reader, void *aux, casenumber cnt)
1833 {
1834   g_print ("%s:%d\n", __FILE__, __LINE__);
1835 }
1836
1837 static void
1838 foo (struct dictionary *dict, void *aux)
1839 {
1840   PsppireImportAssistant *ia = PSPPIRE_IMPORT_ASSISTANT (aux);
1841   g_print ("%s:%d\n", __FILE__, __LINE__);
1842
1843   struct caseproto *proto = caseproto_create ();
1844
1845   int i;
1846   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1847     {
1848       const struct variable *var = dict_get_var (ia->dict, i);
1849       proto = caseproto_add_width (proto, var_get_width (var));
1850     }
1851
1852
1853   gint n_rows = gtk_tree_model_iter_n_children (ia->delimiters_model, NULL);
1854
1855   struct casereader *reader =
1856     casereader_create_random (proto, n_rows, &my_casereader_class,  ia);
1857
1858
1859   PsppireDataStore *store = NULL;
1860
1861   g_object_get (ia->data_sheet, "data-model", &store, NULL);
1862
1863   psppire_data_store_set_reader (store, reader);
1864 }
1865
1866 /* Called just before the formats page of the assistant is
1867    displayed. */
1868 static void
1869 prepare_formats_page (PsppireImportAssistant *ia)
1870 {
1871   PsppireDict *dict = psppire_dict_new_from_dict (ia->dict);
1872   g_object_set (ia->var_sheet, "data-model", dict, NULL);
1873
1874   my_casereader_class.read = my_read;
1875   my_casereader_class.destroy = my_destroy;
1876   my_casereader_class.advance = my_advance;
1877
1878   struct caseproto *proto = caseproto_create ();
1879   int i;
1880
1881   struct fmt_guesser **fg = xcalloc (sizeof *fg, dict_get_var_cnt (ia->dict));
1882   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1883     {
1884       fg[i] = fmt_guesser_create ();
1885     }
1886
1887   gint n_rows = gtk_tree_model_iter_n_children (ia->delimiters_model, NULL);
1888
1889   GtkTreeIter iter;
1890   gboolean ok;
1891   for (ok = gtk_tree_model_get_iter_first (ia->delimiters_model, &iter);
1892        ok;
1893        ok = gtk_tree_model_iter_next (ia->delimiters_model, &iter))
1894     {
1895       for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1896         {
1897           gchar *s = NULL;
1898           gtk_tree_model_get (ia->delimiters_model, &iter, i+1, &s, -1);
1899           fmt_guesser_add (fg[i], ss_cstr (s));
1900           free (s);
1901         }
1902     }
1903
1904   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1905     {
1906       struct fmt_spec fs;
1907       fmt_guesser_guess (fg[i], &fs);
1908
1909       fmt_fix (&fs, FMT_FOR_INPUT);
1910
1911       struct variable *var = dict_get_var (ia->dict, i);
1912
1913       int width = fmt_var_width (&fs);
1914
1915       var_set_width_and_formats (var, width,
1916                                  &fs, &fs);
1917
1918       proto = caseproto_add_width (proto, width);
1919       fmt_guesser_destroy (fg[i]);
1920     }
1921
1922   free (fg);
1923
1924   //  dict_set_change_callback (ia->dict, foo, ia);
1925
1926   struct casereader *reader =
1927     casereader_create_random (proto, n_rows, &my_casereader_class,  ia);
1928
1929   PsppireDataStore *store = psppire_data_store_new (dict);
1930   psppire_data_store_set_reader (store, reader);
1931
1932   g_object_set (ia->data_sheet, "data-model", store, NULL);
1933
1934
1935   gint pmax;
1936   g_object_get (get_widget_assert (ia->builder, "vpaned1"),
1937                 "max-position", &pmax, NULL);
1938
1939
1940   g_object_set (get_widget_assert (ia->builder, "vpaned1"),
1941                 "position", pmax / 2, NULL);
1942
1943   gtk_widget_show (ia->paste_button);
1944 }
1945
1946 static void
1947 formats_page_create (PsppireImportAssistant *ia)
1948 {
1949   GtkBuilder *builder = ia->builder;
1950
1951   GtkWidget *w = get_widget_assert (builder, "Formats");
1952   g_object_set_data (G_OBJECT (w), "on-entering", prepare_formats_page);
1953   g_object_set_data (G_OBJECT (w), "on-reset", reset_formats_page);
1954
1955   GtkWidget *vars_scroller = get_widget_assert (builder, "vars-scroller");
1956   if (ia->var_sheet == NULL)
1957     {
1958       ia->var_sheet = psppire_variable_sheet_new ();
1959
1960       gtk_container_add (GTK_CONTAINER (vars_scroller), ia->var_sheet);
1961
1962       ia->dict = dict_create (get_default_encoding ());
1963
1964       gtk_widget_show_all (vars_scroller);
1965     }
1966   GtkWidget *data_scroller = get_widget_assert (builder, "data-scroller");
1967   if (ia->data_sheet == NULL)
1968     {
1969       ia->data_sheet = psppire_data_sheet_new ();
1970
1971       gtk_container_add (GTK_CONTAINER (data_scroller), ia->data_sheet);
1972
1973       gtk_widget_show_all (data_scroller);
1974     }
1975
1976   add_page_to_assistant (ia, w,
1977                          GTK_ASSISTANT_PAGE_CONFIRM, _("Adjust Variable Formats"));
1978
1979   ia->modified_vars = NULL;
1980   ia->modified_var_cnt = 0;
1981 }
1982
1983
1984 \f
1985
1986 static void
1987 separators_append_syntax (const PsppireImportAssistant *ia, struct string *s)
1988 {
1989   int i;
1990
1991   ds_put_cstr (s, "  /DELIMITERS=\"");
1992
1993   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (get_widget_assert (ia->builder, "tab"))))
1994     ds_put_cstr (s, "\\t");
1995   for (i = 0; i < SEPARATOR_CNT; i++)
1996     {
1997       const struct separator *seps = &separators[i];
1998       GtkWidget *button = get_widget_assert (ia->builder, seps->name);
1999       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
2000         {
2001           if (seps->c == '\t')
2002             continue;
2003
2004           ds_put_byte (s, seps->c);
2005         }
2006     }
2007   ds_put_cstr (s, "\"\n");
2008   if (!ds_is_empty (&ia->quotes))
2009     syntax_gen_pspp (s, "  /QUALIFIER=%sq\n", ds_cstr (&ia->quotes));
2010 }
2011
2012 static void
2013 formats_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2014 {
2015   int i;
2016   int var_cnt;
2017
2018   g_return_if_fail (ia->dict);
2019
2020   ds_put_cstr (s, "  /VARIABLES=\n");
2021
2022   var_cnt = dict_get_var_cnt (ia->dict);
2023   for (i = 0; i < var_cnt; i++)
2024     {
2025       struct variable *var = dict_get_var (ia->dict, i);
2026       char format_string[FMT_STRING_LEN_MAX + 1];
2027       fmt_to_string (var_get_print_format (var), format_string);
2028       ds_put_format (s, "    %s %s%s\n",
2029                      var_get_name (var), format_string,
2030                      i == var_cnt - 1 ? "." : "");
2031     }
2032 }
2033
2034 static void
2035 first_line_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2036 {
2037   gint first_case = 0;
2038   g_object_get (ia->delimiters_model, "first-line", &first_case, NULL);
2039
2040   if (first_case > 0)
2041     ds_put_format (s, "  /FIRSTCASE=%d\n", first_case + 1);
2042 }
2043
2044 static void
2045 intro_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2046 {
2047   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->n_cases_button)))
2048     ds_put_format (s, "N OF CASES %d.\n",
2049                    gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (ia->n_cases_spin)));
2050   else if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->percent_button)))
2051     ds_put_format (s, "SAMPLE %.4g.\n",
2052                    gtk_spin_button_get_value (GTK_SPIN_BUTTON (ia->percent_spin)) / 100.0);
2053 }
2054
2055
2056 /* Emits PSPP syntax to S that applies the dictionary attributes
2057    (such as missing values and value labels) of the variables in
2058    DICT.  */
2059 static void
2060 apply_dict (const struct dictionary *dict, struct string *s)
2061 {
2062   size_t var_cnt = dict_get_var_cnt (dict);
2063   size_t i;
2064
2065   for (i = 0; i < var_cnt; i++)
2066     {
2067       struct variable *var = dict_get_var (dict, i);
2068       const char *name = var_get_name (var);
2069       enum val_type type = var_get_type (var);
2070       int width = var_get_width (var);
2071       enum measure measure = var_get_measure (var);
2072       enum var_role role = var_get_role (var);
2073       enum alignment alignment = var_get_alignment (var);
2074       const struct fmt_spec *format = var_get_print_format (var);
2075
2076       if (var_has_missing_values (var))
2077         {
2078           const struct missing_values *mv = var_get_missing_values (var);
2079           size_t j;
2080
2081           syntax_gen_pspp (s, "MISSING VALUES %ss (", name);
2082           for (j = 0; j < mv_n_values (mv); j++)
2083             {
2084               if (j)
2085                 ds_put_cstr (s, ", ");
2086               syntax_gen_value (s, mv_get_value (mv, j), width, format);
2087             }
2088
2089           if (mv_has_range (mv))
2090             {
2091               double low, high;
2092               if (mv_has_value (mv))
2093                 ds_put_cstr (s, ", ");
2094               mv_get_range (mv, &low, &high);
2095               syntax_gen_num_range (s, low, high, format);
2096             }
2097           ds_put_cstr (s, ").\n");
2098         }
2099       if (var_has_value_labels (var))
2100         {
2101           const struct val_labs *vls = var_get_value_labels (var);
2102           const struct val_lab **labels = val_labs_sorted (vls);
2103           size_t n_labels = val_labs_count (vls);
2104           size_t i;
2105
2106           syntax_gen_pspp (s, "VALUE LABELS %ss", name);
2107           for (i = 0; i < n_labels; i++)
2108             {
2109               const struct val_lab *vl = labels[i];
2110               ds_put_cstr (s, "\n  ");
2111               syntax_gen_value (s, &vl->value, width, format);
2112               ds_put_byte (s, ' ');
2113               syntax_gen_string (s, ss_cstr (val_lab_get_escaped_label (vl)));
2114             }
2115           free (labels);
2116           ds_put_cstr (s, ".\n");
2117         }
2118       if (var_has_label (var))
2119         syntax_gen_pspp (s, "VARIABLE LABELS %ss %sq.\n",
2120                          name, var_get_label (var));
2121       if (measure != var_default_measure (type))
2122         syntax_gen_pspp (s, "VARIABLE LEVEL %ss (%ss).\n",
2123                          name, measure_to_syntax (measure));
2124       if (role != ROLE_INPUT)
2125         syntax_gen_pspp (s, "VARIABLE ROLE /%ss %ss.\n",
2126                          var_role_to_syntax (role), name);
2127       if (alignment != var_default_alignment (type))
2128         syntax_gen_pspp (s, "VARIABLE ALIGNMENT %ss (%ss).\n",
2129                          name, alignment_to_syntax (alignment));
2130       if (var_get_display_width (var) != var_default_display_width (width))
2131         syntax_gen_pspp (s, "VARIABLE WIDTH %ss (%d).\n",
2132                          name, var_get_display_width (var));
2133     }
2134 }
2135
2136
2137
2138 static char *
2139 sheet_spec_gen_syntax (PsppireImportAssistant *ia)
2140 {
2141   GtkBuilder *builder = ia->builder;
2142   GtkWidget *range_entry = get_widget_assert (builder, "cell-range-entry");
2143   GtkWidget *sheet_entry = get_widget_assert (builder, "sheet-entry");
2144   GtkWidget *rnc = get_widget_assert (builder, "readnames-checkbox");
2145   const gchar *range = gtk_entry_get_text (GTK_ENTRY (range_entry));
2146   int sheet_index = 1 + gtk_combo_box_get_active (GTK_COMBO_BOX (sheet_entry));
2147   gboolean read_names = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (rnc));
2148
2149   struct string s = DS_EMPTY_INITIALIZER;
2150
2151   char *filename;
2152   g_object_get (ia->text_file, "file-name", &filename, NULL);
2153   syntax_gen_pspp (&s,
2154                    "GET DATA"
2155                    "\n  /TYPE=%ss"
2156                    "\n  /FILE=%sq"
2157                    "\n  /SHEET=index %d"
2158                    "\n  /READNAMES=%ss",
2159                    (ia->spreadsheet->type == SPREADSHEET_GNUMERIC) ? "GNM" : "ODS",
2160                    filename,
2161                    sheet_index,
2162                    read_names ? "ON" : "OFF");
2163
2164   if (range && 0 != strcmp ("", range))
2165     {
2166       syntax_gen_pspp (&s,
2167                        "\n  /CELLRANGE=RANGE %sq", range);
2168     }
2169   else
2170     {
2171       syntax_gen_pspp (&s,
2172                        "\n  /CELLRANGE=FULL");
2173     }
2174
2175
2176   syntax_gen_pspp (&s, ".");
2177
2178
2179   return ds_cstr (&s);
2180 }
2181
2182
2183 gchar *
2184 psppire_import_assistant_generate_syntax (PsppireImportAssistant *ia)
2185 {
2186   struct string s = DS_EMPTY_INITIALIZER;
2187
2188   if (!ia->spreadsheet)
2189     {
2190       gchar *file_name = NULL;
2191       gchar *encoding = NULL;
2192       g_object_get (ia->text_file,
2193                     "file-name", &file_name,
2194                     "encoding", &encoding,
2195                     NULL);
2196
2197       if (file_name == NULL)
2198         return NULL;
2199
2200       syntax_gen_pspp (&s,
2201                        "GET DATA"
2202                        "\n  /TYPE=TXT"
2203                        "\n  /FILE=%sq\n",
2204                        file_name);
2205       if (encoding && strcmp (encoding, "Auto"))
2206         syntax_gen_pspp (&s, "  /ENCODING=%sq\n", encoding);
2207
2208       ds_put_cstr (&s,
2209                    "  /ARRANGEMENT=DELIMITED\n"
2210                    "  /DELCASE=LINE\n");
2211
2212       first_line_append_syntax (ia, &s);
2213       separators_append_syntax (ia, &s);
2214
2215       formats_append_syntax (ia, &s);
2216       apply_dict (ia->dict, &s);
2217       intro_append_syntax (ia, &s);
2218     }
2219   else
2220     {
2221       return sheet_spec_gen_syntax (ia);
2222     }
2223
2224   return ds_cstr (&s);
2225 }