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