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