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