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