a1cbfac51354f8b01628f2e585e350eda23d1979
[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   gtk_window_fullscreen (GTK_WINDOW (ia));
967 }
968
969
970 /* Appends a page of the given TYPE, with PAGE as its content, to
971    the GtkAssistant encapsulated by IA.  Returns the GtkWidget
972    that represents the page. */
973 static GtkWidget *
974 add_page_to_assistant (PsppireImportAssistant *ia,
975                        GtkWidget *page, GtkAssistantPageType type, const gchar *title)
976 {
977   GtkWidget *content = page;
978
979   gtk_assistant_append_page (GTK_ASSISTANT (ia), content);
980   gtk_assistant_set_page_type (GTK_ASSISTANT(ia), content, type);
981   gtk_assistant_set_page_title (GTK_ASSISTANT(ia), content, title);
982   gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), content, TRUE);
983
984   return content;
985 }
986
987
988 /* Called when one of the radio buttons is clicked. */
989 static void
990 on_intro_amount_changed (PsppireImportAssistant *p)
991 {
992   gtk_widget_set_sensitive (p->n_cases_spin,
993                             gtk_toggle_button_get_active (
994                                                           GTK_TOGGLE_BUTTON (p->n_cases_button)));
995
996   gtk_widget_set_sensitive (p->percent_spin,
997                             gtk_toggle_button_get_active (
998                                                           GTK_TOGGLE_BUTTON (p->percent_button)));
999 }
1000
1001
1002 static void
1003 render_line (PsppSheetViewColumn *tree_column,
1004              GtkCellRenderer *cell,
1005              GtkTreeModel *tree_model,
1006              GtkTreeIter *iter,
1007              gpointer data)
1008 {
1009   gint row = empty_list_store_iter_to_row (iter);
1010   struct string *lines;
1011   
1012   lines = g_object_get_data (G_OBJECT (tree_model), "lines");
1013   g_return_if_fail (lines != NULL);
1014
1015   g_object_set (cell, "text", ds_cstr (&lines[row]), NULL);
1016 }
1017
1018 /* Sets the widgets to match IA's first_line substructure. */
1019 static void
1020 set_first_line (PsppireImportAssistant *ia)
1021 {
1022   GtkTreePath *path = gtk_tree_path_new_from_indices (ia->skip_lines, -1);
1023
1024   
1025   set_model_on_treeview (ia, ia->tree_view, 0);
1026
1027   pspp_sheet_view_set_cursor (PSPP_SHEET_VIEW (ia->tree_view),
1028                               path, NULL, false);
1029   gtk_tree_path_free (path);
1030
1031   gtk_toggle_button_set_active (
1032                                 GTK_TOGGLE_BUTTON (ia->variable_names_cb),
1033                                 ia->variable_names);
1034   gtk_widget_set_sensitive (ia->variable_names_cb,
1035                             ia->skip_lines > 0);
1036 }
1037
1038
1039 /* Creates and returns a tree view that contains each of the
1040    lines in IA's file as a row. */
1041 static GtkWidget *
1042 create_lines_tree_view (GtkContainer *parent, PsppireImportAssistant *ia)
1043 {
1044   size_t max_line_length;
1045   gint content_width, header_width;
1046   size_t i;
1047   const gchar *title = _("Text");
1048   GtkWidget *tree_view = make_tree_view (ia);
1049   PsppSheetViewColumn *column =
1050     pspp_sheet_view_column_new_with_attributes (title,
1051                                                 ia->fixed_renderer, (void *) NULL);
1052   
1053   pspp_sheet_view_column_set_cell_data_func (column, ia->fixed_renderer,
1054                                              render_line, NULL, NULL);
1055   pspp_sheet_view_column_set_resizable (column, TRUE);
1056   pspp_sheet_view_column_set_expand (column, TRUE);
1057
1058   max_line_length = 0;
1059   for (i = 0; i < ia->line_cnt; i++)
1060     {
1061       size_t w = ds_length (&ia->lines[i]);
1062       max_line_length = MAX (max_line_length, w);
1063     }
1064
1065   content_width = get_monospace_width (tree_view, ia->fixed_renderer,
1066                                        max_line_length);
1067   header_width = get_string_width (tree_view, ia->prop_renderer, title);
1068   pspp_sheet_view_column_set_fixed_width (column, MAX (content_width,
1069                                                        header_width));
1070   pspp_sheet_view_append_column (PSPP_SHEET_VIEW (tree_view), column);
1071
1072   GtkWidget *oldtv = gtk_bin_get_child (GTK_BIN (parent));
1073   if (oldtv)
1074     gtk_container_remove (parent, oldtv);
1075   
1076   gtk_container_add (parent, tree_view);
1077   gtk_widget_show (tree_view);
1078
1079   return tree_view;
1080 }
1081
1082
1083 /* Sets IA's first_line substructure to match the widgets. */
1084 static void
1085 set_first_line_options (PsppireImportAssistant *ia)
1086 {
1087   GtkTreeIter iter;
1088   GtkTreeModel *model;
1089
1090   PsppSheetSelection *selection = pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view));
1091   if (pspp_sheet_selection_get_selected (selection, &model, &iter))
1092     {
1093       GtkTreePath *path = gtk_tree_model_get_path (model, &iter);
1094       int row = gtk_tree_path_get_indices (path)[0];
1095       gtk_tree_path_free (path);
1096
1097       ia->skip_lines = row;
1098       ia->variable_names =
1099         (ia->skip_lines > 0
1100          && gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)));
1101     }
1102
1103   gtk_widget_set_sensitive (ia->variable_names_cb, ia->skip_lines > 0);
1104 }
1105
1106 static void
1107 reset_first_line_page (PsppireImportAssistant *ia)
1108 {
1109   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb), FALSE);
1110   PsppSheetSelection *selection = pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view));
1111   pspp_sheet_selection_unselect_all (selection);
1112   gtk_widget_set_sensitive (ia->variable_names_cb, FALSE);
1113 }
1114
1115
1116 /* Initializes IA's first_line substructure. */
1117 static void
1118 first_line_page_create (PsppireImportAssistant *ia)
1119 {
1120   GtkWidget *w =  get_widget_assert (ia->builder, "FirstLine");
1121
1122   g_object_set_data (G_OBJECT (w), "on-entering", set_first_line);
1123   
1124   add_page_to_assistant (ia, w,
1125                          GTK_ASSISTANT_PAGE_CONTENT, _("Select the First Line"));
1126
1127   ia->tree_view = GTK_WIDGET (create_lines_tree_view (
1128                                                       GTK_CONTAINER (get_widget_assert (ia->builder, "first-line-scroller")), ia));
1129   ia->variable_names_cb = get_widget_assert (ia->builder, "variable-names");
1130   pspp_sheet_selection_set_mode (
1131                                  pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view)),
1132                                  PSPP_SHEET_SELECTION_BROWSE);
1133   pspp_sheet_view_set_rubber_banding (PSPP_SHEET_VIEW (ia->tree_view), TRUE);
1134
1135
1136   g_signal_connect_swapped (pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view)),
1137                             "changed", G_CALLBACK (set_first_line_options), ia);
1138
1139   g_signal_connect_swapped (ia->variable_names_cb, "toggled",
1140                             G_CALLBACK (set_first_line_options), ia);
1141
1142
1143   g_object_set_data (G_OBJECT (w), "on-reset", reset_first_line_page);
1144 }
1145
1146
1147 static void
1148 intro_on_enter (PsppireImportAssistant *ia)
1149 {
1150   GtkBuilder *builder = ia->builder;
1151   GtkWidget *table  = get_widget_assert (builder, "button-table");
1152
1153   struct string s;
1154
1155   if (ia->line_cnt > MAX_PREVIEW_LINES)
1156     ia->line_cnt = MAX_PREVIEW_LINES;
1157   
1158   ds_init_empty (&s);
1159   ds_put_cstr (&s, _("This assistant will guide you through the process of "
1160                      "importing data into PSPP from a text file with one line "
1161                      "per case,  in which fields are separated by tabs, "
1162                      "commas, or other delimiters.\n\n"));
1163
1164   if (ia->total_is_exact)
1165     {
1166       ds_put_format (
1167                      &s, ngettext ("The selected file contains %'lu line of text.  ",
1168                                    "The selected file contains %'lu lines of text.  ",
1169                                    ia->total_lines),
1170                      ia->total_lines);
1171     }
1172   else if (ia->total_lines > 0)
1173     {
1174       ds_put_format (
1175                      &s, ngettext (
1176                                    "The selected file contains approximately %'lu line of text.  ",
1177                                    "The selected file contains approximately %'lu lines of text.  ",
1178                                    ia->total_lines),
1179                      ia->total_lines);
1180       ds_put_format (
1181                      &s, ngettext (
1182                                    "Only the first %zu line of the file will be shown for "
1183                                    "preview purposes in the following screens.  ",
1184                                    "Only the first %zu lines of the file will be shown for "
1185                                    "preview purposes in the following screens.  ",
1186                                    ia->line_cnt),
1187                      ia->line_cnt);
1188     }
1189
1190   ds_put_cstr (&s, _("You may choose below how much of the file should "
1191                      "actually be imported."));
1192
1193   gtk_label_set_text (GTK_LABEL (get_widget_assert (builder, "intro-label")),
1194                       ds_cstr (&s));
1195   ds_destroy (&s);
1196
1197   GtkWidget *w  =  gtk_grid_get_child_at (GTK_GRID (table), 1, 1);
1198   int old_value = w ? gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (ia->n_cases_spin)) : 1;
1199   if (w)
1200     gtk_container_remove (GTK_CONTAINER (table), w);
1201
1202   w  =  gtk_grid_get_child_at (GTK_GRID (table), 1, 2);
1203   if (w)
1204     gtk_container_remove (GTK_CONTAINER (table), w);
1205
1206   
1207   GtkWidget *hbox_n_cases = psppire_scanf_new (_("Only the first %4d cases"), &ia->n_cases_spin);
1208
1209   GtkAdjustment *adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (ia->n_cases_spin));
1210   gtk_adjustment_set_lower (adj, 1.0);
1211   if (ia->total_is_exact)
1212     gtk_adjustment_set_value (adj, old_value);
1213   if (ia->total_is_exact)
1214     gtk_adjustment_set_upper (adj, ia->total_lines);
1215   else
1216     gtk_adjustment_set_upper (adj, DBL_MAX);
1217
1218   gtk_grid_attach (GTK_GRID (table), hbox_n_cases,
1219                    1, 1,
1220                    1, 1);
1221
1222
1223   GtkWidget *hbox_percent = psppire_scanf_new (_("Only the first %3d %% of file (approximately)"),
1224                                                &ia->percent_spin);
1225
1226   gtk_grid_attach (GTK_GRID (table), hbox_percent,
1227                    1, 2,
1228                    1, 1);
1229
1230   gtk_widget_show_all (table);
1231
1232   on_intro_amount_changed (ia);
1233 }
1234
1235 /* Initializes IA's intro substructure. */
1236 static void
1237 intro_page_create (PsppireImportAssistant *ia)
1238 {
1239   GtkBuilder *builder = ia->builder;
1240
1241   GtkWidget *w =  get_widget_assert (builder, "Intro");
1242
1243   ia->percent_spin = gtk_spin_button_new_with_range (0, 100, 10);
1244
1245
1246   add_page_to_assistant (ia, w,  GTK_ASSISTANT_PAGE_CONTENT, _("Select the Lines to Import"));
1247
1248   ia->all_cases_button = get_widget_assert (builder, "import-all-cases");
1249
1250   ia->n_cases_button = get_widget_assert (builder, "import-n-cases");
1251
1252   ia->percent_button = get_widget_assert (builder, "import-percent");
1253
1254   g_signal_connect_swapped (ia->all_cases_button, "toggled",
1255                             G_CALLBACK (on_intro_amount_changed), ia);
1256   g_signal_connect_swapped (ia->n_cases_button, "toggled",
1257                             G_CALLBACK (on_intro_amount_changed), ia);
1258   g_signal_connect_swapped (ia->percent_button, "toggled",
1259                             G_CALLBACK (on_intro_amount_changed), ia);
1260
1261
1262   g_object_set_data (G_OBJECT (w), "on-entering", intro_on_enter);
1263   g_object_set_data (G_OBJECT (w), "on-reset", reset_intro_page);
1264 }
1265
1266
1267 GtkWidget *
1268 psppire_import_assistant_new (GtkWindow *toplevel)
1269 {
1270   return GTK_WIDGET (g_object_new (PSPPIRE_TYPE_IMPORT_ASSISTANT,
1271                                    "transient-for", toplevel,
1272                                    NULL));
1273 }
1274
1275 \f
1276
1277 struct column
1278 {
1279   /* Variable name for this column.  This is the variable name
1280      used on the separators page; it can be overridden by the
1281      user on the formats page. */
1282   char *name;
1283
1284   /* Maximum length of any row in this column. */
1285   size_t width;
1286
1287   /* Contents of this column: contents[row] is the contents for
1288      the given row.
1289
1290      A null substring indicates a missing column for that row
1291      (because the line contains an insufficient number of
1292      separators).
1293
1294      contents[] elements may be substrings of the lines[]
1295      strings that represent the whole lines of the file, to
1296      save memory.  Other elements are dynamically allocated
1297      with ss_alloc_substring. */
1298   struct substring *contents;
1299 };
1300
1301
1302 static void
1303 destroy_columns (PsppireImportAssistant *ia)
1304 {
1305   struct column *col;
1306   for (col = ia->columns; col < &ia->columns[ia->column_cnt]; col++)
1307     {
1308       free (col->name);
1309       free (col->contents);
1310     }
1311   
1312   free (ia->columns);
1313 }
1314
1315 /* Called to render one of the cells in the fields preview tree
1316    view. */
1317 static void
1318 render_input_cell (PsppSheetViewColumn *tree_column, GtkCellRenderer *cell,
1319                    GtkTreeModel *model, GtkTreeIter *iter,
1320                    gpointer ia_)
1321 {
1322   PsppireImportAssistant *ia = ia_;
1323   struct substring field;
1324   size_t row;
1325   gint column;
1326
1327   column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1328                                                "column-number"));
1329   row = empty_list_store_iter_to_row (iter) + ia->skip_lines;
1330   field = ia->columns[column].contents[row];
1331   if (field.string != NULL)
1332     {
1333       GValue text = {0, };
1334       g_value_init (&text, G_TYPE_STRING);
1335       g_value_take_string (&text, ss_xstrdup (field));
1336       g_object_set_property (G_OBJECT (cell), "text", &text);
1337       g_value_unset (&text);
1338       g_object_set (cell, "background-set", FALSE, (void *) NULL);
1339     }
1340   else
1341     g_object_set (cell,
1342                   "text", "",
1343                   "background", "red",
1344                   "background-set", TRUE,
1345                   (void *) NULL);
1346 }
1347
1348
1349 /* Parses the contents of the field at (ROW,COLUMN) according to
1350    its variable format.  If OUTPUTP is non-null, then *OUTPUTP
1351    receives the formatted output for that field (which must be
1352    freed with free).  If TOOLTIPP is non-null, then *TOOLTIPP
1353    receives a message suitable for use in a tooltip, if one is
1354    needed, or a null pointer otherwise.  Returns TRUE if a
1355    tooltip message is needed, otherwise FALSE. */
1356 static bool
1357 parse_field (PsppireImportAssistant *ia,
1358              size_t row, size_t column,
1359              char **outputp, char **tooltipp)
1360 {
1361   const struct fmt_spec *in;
1362   struct fmt_spec out;
1363   char *tooltip;
1364   bool ok;
1365
1366   struct substring field = ia->columns[column].contents[row];
1367   struct variable *var = dict_get_var (ia->dict, column);
1368   union value val;
1369
1370   value_init (&val, var_get_width (var));
1371   in = var_get_print_format (var);
1372   out = fmt_for_output_from_input (in);
1373   tooltip = NULL;
1374   if (field.string != NULL)
1375     {
1376       char *error = data_in (field, "UTF-8", in->type, &val, var_get_width (var),
1377                              dict_get_encoding (ia->dict));
1378       if (error != NULL)
1379         {
1380           tooltip = xasprintf (_("Cannot parse field content `%.*s' as "
1381                                  "format %s: %s"),
1382                                (int) field.length, field.string,
1383                                fmt_name (in->type), error);
1384           free (error);
1385         }
1386     }
1387   else
1388     {
1389       tooltip = xstrdup (_("This input line has too few separators "
1390                            "to fill in this field."));
1391       value_set_missing (&val, var_get_width (var));
1392     }
1393   if (outputp != NULL)
1394     {
1395       *outputp = data_out (&val, dict_get_encoding (ia->dict),  &out);
1396     }
1397   value_destroy (&val, var_get_width (var));
1398
1399   ok = tooltip == NULL;
1400   if (tooltipp != NULL)
1401     *tooltipp = tooltip;
1402   else
1403     free (tooltip);
1404   return ok;
1405 }
1406
1407
1408 /* Called to render one of the cells in the data preview tree
1409    view. */
1410 static void
1411 render_output_cell (PsppSheetViewColumn *tree_column,
1412                     GtkCellRenderer *cell,
1413                     GtkTreeModel *model,
1414                     GtkTreeIter *iter,
1415                     gpointer ia_)
1416 {
1417   PsppireImportAssistant *ia = ia_;
1418   char *output;
1419   GValue gvalue = { 0, };
1420   bool ok = parse_field (ia,
1421                          (empty_list_store_iter_to_row (iter)
1422                           + ia->skip_lines),
1423                          GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1424                                                              "column-number")),
1425                          &output, NULL);
1426
1427   g_value_init (&gvalue, G_TYPE_STRING);
1428   g_value_take_string (&gvalue, output);
1429   g_object_set_property (G_OBJECT (cell), "text", &gvalue);
1430   g_value_unset (&gvalue);
1431
1432   if (ok)
1433     g_object_set (cell, "background-set", FALSE, (void *) NULL);
1434   else
1435     g_object_set (cell,
1436                   "background", "red",
1437                   "background-set", TRUE,
1438                   (void *) NULL);
1439 }
1440
1441
1442 /* Utility functions used by multiple pages of the assistant. */
1443
1444 static gboolean
1445 get_tooltip_location (GtkWidget *widget, gint wx, gint wy,
1446                       const PsppireImportAssistant *ia,
1447                       size_t *row, size_t *column)
1448 {
1449   PsppSheetView *tree_view = PSPP_SHEET_VIEW (widget);
1450   gint bx, by;
1451   GtkTreePath *path;
1452   GtkTreeIter iter;
1453   PsppSheetViewColumn *tree_column;
1454   GtkTreeModel *tree_model;
1455   bool ok;
1456
1457   pspp_sheet_view_convert_widget_to_bin_window_coords (tree_view,
1458                                                        wx, wy, &bx, &by);
1459   if (!pspp_sheet_view_get_path_at_pos (tree_view, bx, by,
1460                                         &path, &tree_column, NULL, NULL))
1461     return FALSE;
1462
1463   *column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1464                                                 "column-number"));
1465
1466   tree_model = pspp_sheet_view_get_model (tree_view);
1467   ok = gtk_tree_model_get_iter (tree_model, &iter, path);
1468   gtk_tree_path_free (path);
1469   if (!ok)
1470     return FALSE;
1471
1472   *row = empty_list_store_iter_to_row (&iter) + ia->skip_lines;
1473   return TRUE;
1474 }
1475
1476
1477 \f
1478
1479
1480 /* Called to render a tooltip on one of the cells in the fields
1481    preview tree view. */
1482 static gboolean
1483 on_query_input_tooltip (GtkWidget *widget, gint wx, gint wy,
1484                         gboolean keyboard_mode UNUSED,
1485                         GtkTooltip *tooltip, PsppireImportAssistant *ia)
1486 {
1487   size_t row, column;
1488
1489   if (!get_tooltip_location (widget, wx, wy, ia, &row, &column))
1490     return FALSE;
1491
1492   if (ia->columns[column].contents[row].string != NULL)
1493     return FALSE;
1494
1495   gtk_tooltip_set_text (tooltip,
1496                         _("This input line has too few separators "
1497                           "to fill in this field."));
1498   return TRUE;
1499 }
1500
1501
1502 /* Called to render a tooltip for one of the cells in the data
1503    preview tree view. */
1504 static gboolean
1505 on_query_output_tooltip (GtkWidget *widget, gint wx, gint wy,
1506                          gboolean keyboard_mode UNUSED,
1507                          GtkTooltip *tooltip, PsppireImportAssistant *ia)
1508 {
1509   size_t row, column;
1510   char *text;
1511
1512   if (!gtk_widget_get_mapped (widget))
1513     return FALSE;
1514
1515   if (!get_tooltip_location (widget, wx, wy, ia, &row, &column))
1516     return FALSE;
1517
1518   if (parse_field (ia, row, column, NULL, &text))
1519     return FALSE;
1520
1521   gtk_tooltip_set_text (tooltip, text);
1522   free (text);
1523   return TRUE;
1524 }
1525
1526 \f
1527
1528
1529 static void
1530 set_quote_list (GtkComboBox *cb)
1531 {
1532   GtkListStore *list =  gtk_list_store_new (1, G_TYPE_STRING);
1533   GtkTreeIter iter;
1534   gint i;
1535   const gchar *seperator[3] = {"'\"", "\'", "\""};
1536
1537   for (i = 0; i < 3; i++)
1538     {
1539       const gchar *s = seperator[i];
1540
1541       /* Add a new row to the model */
1542       gtk_list_store_append (list, &iter);
1543       gtk_list_store_set (list, &iter,
1544                           0, s,
1545                           -1);
1546
1547     }
1548
1549   gtk_combo_box_set_model (GTK_COMBO_BOX (cb), GTK_TREE_MODEL (list));
1550   g_object_unref (list);
1551
1552   gtk_combo_box_set_entry_text_column (cb, 0);
1553 }
1554
1555
1556
1557
1558 /* Sets IA's separators substructure to match the widgets. */
1559 static void
1560 get_separators (PsppireImportAssistant *ia)
1561 {
1562   int i;
1563
1564   ds_clear (&ia->separators);
1565   for (i = 0; i < SEPARATOR_CNT; i++)
1566     {
1567       const struct separator *sep = &separators[i];
1568       GtkWidget *button = get_widget_assert (ia->builder, sep->name);
1569       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
1570         ds_put_byte (&ia->separators, sep->c);
1571     }
1572
1573   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->custom_cb)))
1574     ds_put_cstr (&ia->separators,
1575                  gtk_entry_get_text (GTK_ENTRY (ia->custom_entry)));
1576
1577   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->quote_cb)))
1578     {
1579       const gchar *text = gtk_entry_get_text (GTK_ENTRY (gtk_bin_get_child (GTK_BIN (ia->quote_combo))));
1580       ds_assign_cstr (&ia->quotes, text);
1581     }
1582   else
1583     ds_clear (&ia->quotes);
1584 }
1585
1586
1587
1588
1589 /* Frees and clears the column data in IA's separators
1590    substructure. */
1591 static void
1592 clear_fields (PsppireImportAssistant *ia)
1593 {
1594   if (ia->column_cnt > 0)
1595     {
1596       struct column *col;
1597       size_t row;
1598
1599       for (row = 0; row < ia->line_cnt; row++)
1600         {
1601           const struct string *line = &ia->lines[row];
1602           const char *line_start = ds_data (line);
1603           const char *line_end = ds_end (line);
1604
1605           for (col = ia->columns; col < &ia->columns[ia->column_cnt]; col++)
1606             {
1607               char *s = ss_data (col->contents[row]);
1608               if (!(s >= line_start && s <= line_end))
1609                 ss_dealloc (&col->contents[row]);
1610             }
1611         }
1612
1613       for (col = ia->columns; col < &ia->columns[ia->column_cnt]; col++)
1614         {
1615           free (col->name);
1616           free (col->contents);
1617         }
1618
1619       free (ia->columns);
1620       ia->columns = NULL;
1621       ia->column_cnt = 0;
1622     }
1623 }
1624
1625
1626 /* Breaks the file data in IA into columns based on the
1627    separators set in IA's separators substructure. */
1628 static void
1629 split_fields (PsppireImportAssistant *ia)
1630 {
1631   size_t columns_allocated;
1632   bool space_sep;
1633   size_t row;
1634
1635   clear_fields (ia);
1636
1637   /* Is space in the set of separators? */
1638   space_sep = ss_find_byte (ds_ss (&ia->separators), ' ') != SIZE_MAX;
1639
1640   /* Split all the lines, not just those from
1641      ia->first_line.skip_lines on, so that we split the line that
1642      contains variables names if ia->first_line.variable_names is
1643      TRUE. */
1644   columns_allocated = 0;
1645   for (row = 0; row < ia->line_cnt; row++)
1646     {
1647       struct string *line = &ia->lines[row];
1648       struct substring text = ds_ss (line);
1649       size_t column_idx;
1650
1651       for (column_idx = 0; ; column_idx++)
1652         {
1653           struct substring field = SS_EMPTY_INITIALIZER;
1654           struct column *column;
1655
1656           if (space_sep)
1657             {
1658               ss_ltrim (&text, ss_cstr (" "));
1659             }
1660           if (ss_is_empty (text))
1661             {
1662               if (column_idx != 0)
1663                 break;
1664               field = text;
1665             }
1666           else if (!ds_is_empty (&ia->quotes)
1667                    && ds_find_byte (&ia->quotes, text.string[0]) != SIZE_MAX)
1668             {
1669               int quote = ss_get_byte (&text);
1670               struct string s;
1671               int c;
1672
1673               ds_init_empty (&s);
1674               while ((c = ss_get_byte (&text)) != EOF)
1675                 if (c != quote)
1676                   ds_put_byte (&s, c);
1677                 else if (ss_match_byte (&text, quote))
1678                   ds_put_byte (&s, quote);
1679                 else
1680                   break;
1681               field = ds_ss (&s);
1682             }
1683           else
1684             {
1685               ss_get_bytes (&text, ss_cspan (text, ds_ss (&ia->separators)),
1686                             &field);
1687             }
1688
1689           if (column_idx >= ia->column_cnt)
1690             {
1691               struct column *column;
1692
1693               if (ia->column_cnt >= columns_allocated)
1694                 {
1695                   ia->columns = x2nrealloc (ia->columns, &columns_allocated,
1696                                             sizeof *ia->columns);
1697                 }
1698               column = &ia->columns[ia->column_cnt++];
1699               column->name = NULL;
1700               column->width = 0;
1701               column->contents = xcalloc (ia->line_cnt,
1702                                           sizeof *column->contents);
1703             }
1704           column = &ia->columns[column_idx];
1705           column->contents[row] = field;
1706           if (ss_length (field) > column->width)
1707             column->width = ss_length (field);
1708
1709           if (space_sep)
1710             ss_ltrim (&text, ss_cstr (" "));
1711           if (ss_is_empty (text))
1712             break;
1713           if (ss_find_byte (ds_ss (&ia->separators), ss_first (text))
1714               != SIZE_MAX)
1715             ss_advance (&text, 1);
1716         }
1717     }
1718 }
1719
1720 static PsppSheetViewColumn *
1721 make_data_column (PsppireImportAssistant *ia, GtkWidget *tree_view,
1722                   bool input, gint dict_idx)
1723 {
1724   struct variable *var = NULL;
1725   struct column *column = NULL;
1726   size_t char_cnt;
1727   gint content_width, header_width;
1728   PsppSheetViewColumn *tree_column;
1729   char *name;
1730
1731   if (input)
1732     column = &ia->columns[dict_idx];
1733   else
1734     var = dict_get_var (ia->dict, dict_idx);
1735
1736   name = escape_underscores (input ? column->name : var_get_name (var));
1737   char_cnt = input ? column->width : var_get_print_format (var)->w;
1738   content_width = get_monospace_width (tree_view, ia->fixed_renderer,
1739                                        char_cnt);
1740   header_width = get_string_width (tree_view, ia->prop_renderer,
1741                                    name);
1742
1743   tree_column = pspp_sheet_view_column_new ();
1744   g_object_set_data (G_OBJECT (tree_column), "column-number",
1745                      GINT_TO_POINTER (dict_idx));
1746   pspp_sheet_view_column_set_title (tree_column, name);
1747   pspp_sheet_view_column_pack_start (tree_column, ia->fixed_renderer,
1748                                      FALSE);
1749   pspp_sheet_view_column_set_cell_data_func (
1750                                              tree_column, ia->fixed_renderer,
1751                                              input ? render_input_cell : render_output_cell, ia, NULL);
1752   pspp_sheet_view_column_set_fixed_width (tree_column, MAX (content_width,
1753                                                             header_width));
1754
1755   free (name);
1756
1757   return tree_column;
1758 }
1759
1760
1761 static GtkWidget *
1762 create_data_tree_view (gboolean input, GtkContainer *parent,
1763                        PsppireImportAssistant *ia)
1764 {
1765   gint i;
1766   GtkWidget *tree_view = make_tree_view (ia);
1767
1768   set_model_on_treeview (ia, tree_view, ia->skip_lines);
1769   
1770   pspp_sheet_selection_set_mode (pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (tree_view)),
1771                                  PSPP_SHEET_SELECTION_NONE);
1772
1773   for (i = 0; i < ia->column_cnt; i++)
1774     {
1775       PsppSheetViewColumn *w = make_data_column (ia, tree_view, input, i);
1776
1777       pspp_sheet_view_append_column (PSPP_SHEET_VIEW (tree_view), w);
1778     }
1779
1780   g_object_set (G_OBJECT (tree_view), "has-tooltip", TRUE, (void *) NULL);
1781   g_signal_connect (tree_view, "query-tooltip",
1782                     G_CALLBACK (input ? on_query_input_tooltip
1783                                 : on_query_output_tooltip), ia);
1784
1785   GtkWidget *child = gtk_bin_get_child (GTK_BIN (parent));
1786   if (child)
1787     {
1788       g_object_ref (child);
1789       gtk_container_remove (parent, child);
1790     }
1791   gtk_container_add (parent, tree_view);
1792   if (child)
1793     g_object_unref (child);
1794
1795   gtk_widget_show (tree_view);
1796
1797   return tree_view;
1798 }
1799
1800
1801 /* Chooses a name for each column on the separators page */
1802 static void
1803 choose_column_names (PsppireImportAssistant *ia)
1804 {
1805   struct dictionary *dict;
1806   unsigned long int generated_name_count = 0;
1807   struct column *col;
1808   size_t name_row;
1809
1810   dict = dict_create (get_default_encoding ());
1811   name_row = ia->variable_names && ia->skip_lines ? ia->skip_lines : 0;
1812   for (col = ia->columns; col < &ia->columns[ia->column_cnt]; col++)
1813     {
1814       char *hint, *name;
1815
1816       hint = name_row ? ss_xstrdup (col->contents[name_row - 1]) : NULL;
1817       name = dict_make_unique_var_name (dict, hint, &generated_name_count);
1818       free (hint);
1819
1820       col->name = name;
1821       dict_create_var_assert (dict, name, 0);
1822     }
1823   dict_destroy (dict);
1824 }
1825
1826
1827
1828 /* Called when the user toggles one of the separators
1829    checkboxes. */
1830 static void
1831 on_separator_toggle (GtkToggleButton *toggle UNUSED,
1832                      PsppireImportAssistant *ia)
1833 {
1834   revise_fields_preview (ia);
1835 }
1836
1837 /* Called when the user changes the entry field for custom
1838    separators. */
1839 static void
1840 on_separators_custom_entry_notify (GObject *gobject UNUSED,
1841                                    GParamSpec *arg1 UNUSED,
1842                                    PsppireImportAssistant *ia)
1843 {
1844   revise_fields_preview (ia);
1845 }
1846
1847 /* Called when the user toggles the checkbox that enables custom
1848    separators. */
1849 static void
1850 on_separators_custom_cb_toggle (GtkToggleButton *custom_cb,
1851                                 PsppireImportAssistant *ia)
1852 {
1853   bool is_active = gtk_toggle_button_get_active (custom_cb);
1854   gtk_widget_set_sensitive (ia->custom_entry, is_active);
1855   revise_fields_preview (ia);
1856 }
1857
1858 /* Called when the user changes the selection in the combo box
1859    that selects a quote character. */
1860 static void
1861 on_quote_combo_change (GtkComboBox *combo, PsppireImportAssistant *ia)
1862 {
1863   revise_fields_preview (ia);
1864 }
1865
1866 /* Called when the user toggles the checkbox that enables
1867    quoting. */
1868 static void
1869 on_quote_cb_toggle (GtkToggleButton *quote_cb, PsppireImportAssistant *ia)
1870 {
1871   bool is_active = gtk_toggle_button_get_active (quote_cb);
1872   gtk_widget_set_sensitive (ia->quote_combo, is_active);
1873   revise_fields_preview (ia);
1874 }
1875
1876 /* Initializes IA's separators substructure. */
1877 static void
1878 separators_page_create (PsppireImportAssistant *ia)
1879 {
1880   GtkBuilder *builder = ia->builder;
1881
1882   size_t i;
1883
1884   GtkWidget *w = get_widget_assert (builder, "Separators");
1885
1886   g_object_set_data (G_OBJECT (w), "on-entering", prepare_separators_page);
1887   g_object_set_data (G_OBJECT (w), "on-reset", prepare_separators_page);
1888   
1889
1890   add_page_to_assistant (ia, w,   GTK_ASSISTANT_PAGE_CONTENT, _("Choose Separators"));
1891
1892   ia->custom_cb = get_widget_assert (builder, "custom-cb");
1893   ia->custom_entry = get_widget_assert (builder, "custom-entry");
1894   ia->quote_combo = get_widget_assert (builder, "quote-combo");
1895   ia->quote_entry = GTK_ENTRY (gtk_bin_get_child (GTK_BIN (ia->quote_combo)));
1896   ia->quote_cb = get_widget_assert (builder, "quote-cb");
1897
1898   set_quote_list (GTK_COMBO_BOX (ia->quote_combo));
1899   ia->fields_tree_view = NULL; 
1900
1901   g_signal_connect (ia->quote_combo, "changed",
1902                     G_CALLBACK (on_quote_combo_change), ia);
1903   g_signal_connect (ia->quote_cb, "toggled",
1904                     G_CALLBACK (on_quote_cb_toggle), ia);
1905   g_signal_connect (ia->custom_entry, "notify::text",
1906                     G_CALLBACK (on_separators_custom_entry_notify), ia);
1907   g_signal_connect (ia->custom_cb, "toggled",
1908                     G_CALLBACK (on_separators_custom_cb_toggle), ia);
1909   for (i = 0; i < SEPARATOR_CNT; i++)
1910     g_signal_connect (get_widget_assert (builder, separators[i].name),
1911                       "toggled", G_CALLBACK (on_separator_toggle), ia);
1912 }
1913
1914
1915
1916 \f
1917 /* Called when the user changes one of the variables in the
1918    dictionary. */
1919 static void
1920 on_variable_change (PsppireDict *dict, int dict_idx,
1921                     unsigned int what, const struct variable *oldvar,
1922                     PsppireImportAssistant *ia)
1923 {
1924   PsppSheetView *tv = PSPP_SHEET_VIEW (ia->data_tree_view);
1925   gint column_idx = dict_idx + 1;
1926
1927   push_watch_cursor (ia);
1928
1929   /* Remove previous column and replace with new column. */
1930   pspp_sheet_view_remove_column (tv, pspp_sheet_view_get_column (PSPP_SHEET_VIEW (ia->data_tree_view), column_idx));
1931   pspp_sheet_view_insert_column (tv, PSPP_SHEET_VIEW_COLUMN (make_data_column (ia, ia->data_tree_view, FALSE, dict_idx)),
1932                                  column_idx);
1933
1934   /* Save a copy of the modified variable in modified_vars, so
1935      that its attributes will be preserved if we back up to the
1936      previous page with the Prev button and then come back
1937      here. */
1938   if (dict_idx >= ia->modified_var_cnt)
1939     {
1940       size_t i;
1941       ia->modified_vars = xnrealloc (ia->modified_vars, dict_idx + 1,
1942                                      sizeof *ia->modified_vars);
1943       for (i = 0; i <= dict_idx; i++)
1944         ia->modified_vars[i] = NULL;
1945       ia->modified_var_cnt = dict_idx + 1;
1946     }
1947   if (ia->modified_vars[dict_idx])
1948     var_destroy (ia->modified_vars[dict_idx]);
1949   ia->modified_vars[dict_idx]
1950     = var_clone (psppire_dict_get_variable (dict, dict_idx));
1951
1952   pop_watch_cursor (ia);
1953 }
1954
1955
1956
1957
1958 /* Called just before the formats page of the assistant is
1959    displayed. */
1960 static void
1961 prepare_formats_page (PsppireImportAssistant *ia)
1962 {
1963   PsppireDict *psppire_dict = NULL;
1964   PsppireVarSheet *var_sheet;
1965   GtkBin *vars_scroller;
1966   GtkWidget *old_var_sheet;
1967
1968   
1969   push_watch_cursor (ia);
1970
1971   if (ia->spreadsheet == NULL)
1972     {
1973       struct fmt_guesser *fg;
1974       unsigned long int number = 0;
1975       size_t column_idx;
1976
1977       
1978       ia->dict = dict_create (get_default_encoding ());
1979       fg = fmt_guesser_create ();
1980       for (column_idx = 0; column_idx < ia->column_cnt; column_idx++)
1981         {
1982           struct variable *modified_var = 
1983             (column_idx < ia->modified_var_cnt ? ia->modified_vars[column_idx] : NULL);
1984
1985           if (modified_var == NULL)
1986             {
1987               struct column *column = &ia->columns[column_idx];
1988               struct variable *var;
1989               struct fmt_spec format;
1990               char *name;
1991               size_t row;
1992
1993               /* Choose variable name. */
1994               name = dict_make_unique_var_name (ia->dict, column->name, &number);
1995
1996               /* Choose variable format. */
1997               fmt_guesser_clear (fg);
1998               for (row = ia->skip_lines; row < ia->line_cnt; row++)
1999                 fmt_guesser_add (fg, column->contents[row]);
2000               fmt_guesser_guess (fg, &format);
2001               fmt_fix_input (&format);
2002
2003               /* Create variable. */
2004               var = dict_create_var_assert (ia->dict, name, fmt_var_width (&format));
2005               var_set_both_formats (var, &format);
2006
2007               free (name);
2008             }
2009           else
2010             {
2011               char *name;
2012
2013               name = dict_make_unique_var_name (ia->dict, var_get_name (modified_var),
2014                                                 &number);
2015               dict_clone_var_as_assert (ia->dict, modified_var, name);
2016               free (name);
2017             }
2018         }
2019       fmt_guesser_destroy (fg);
2020     }
2021   else
2022     {
2023       int row_start = -1;
2024       int row_stop = -1;
2025       int col_start = -1;
2026       int col_stop = -1;
2027
2028       GtkBuilder *builder = ia->builder;
2029
2030       struct casereader *reader = NULL;
2031
2032       GtkWidget *readnames_checkbox = get_widget_assert (builder, "readnames-checkbox");
2033       GtkWidget *range_entry = get_widget_assert (builder, "cell-range-entry");
2034       const gchar *range = gtk_entry_get_text (GTK_ENTRY (range_entry));
2035       GtkWidget *combo_box = get_widget_assert (builder, "sheet-entry");
2036
2037       gint num = gtk_combo_box_get_active (GTK_COMBO_BOX (combo_box));
2038
2039       struct spreadsheet_read_options sro;
2040   
2041       sro.sheet_name = NULL;
2042       sro.cell_range = NULL;
2043       sro.sheet_index = num + 1;
2044
2045       if ( convert_cell_ref (range, &col_start, &row_start, &col_stop, &row_stop))
2046         {
2047           sro.cell_range = g_strdup (range);
2048         }
2049
2050       sro.read_names = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (readnames_checkbox));
2051       sro.asw = -1;
2052   
2053       switch (ia->spreadsheet->type)
2054         {
2055         case SPREADSHEET_ODS:
2056         case SPREADSHEET_GNUMERIC:
2057           {
2058             reader = spreadsheet_make_reader (ia->spreadsheet, &sro);
2059             ia->dict = ia->spreadsheet->dict;
2060           }
2061           break;
2062         default:
2063           g_assert_not_reached ();
2064           break;
2065         }
2066       g_free (sro.cell_range);
2067
2068       if (reader && ia->dict)
2069         {
2070           struct ccase *c;
2071           int col;
2072
2073           ia->column_cnt = dict_get_var_cnt (ia->dict);
2074           ia->columns = xcalloc (ia->column_cnt, sizeof (*ia->columns));
2075           for (col = 0; col < ia->column_cnt ; ++col)
2076             {
2077               const struct variable *var = dict_get_var (ia->dict, col);
2078               ia->columns[col].name = xstrdup (var_get_name (var));
2079               ia->columns[col].contents = NULL;
2080             }
2081
2082           casenumber rows = 0;
2083           for (; (c = casereader_read (reader)) != NULL; case_unref (c))
2084             {
2085               rows++;
2086               for (col = 0; col < ia->column_cnt ; ++col)
2087                 {
2088                   char *ss;
2089                   const struct variable *var = dict_get_var (ia->dict, col);
2090               
2091                   ia->columns[col].contents = xrealloc (ia->columns[col].contents,
2092                                                         sizeof (struct substring) * rows);
2093               
2094                   ss = data_out (case_data (c, var), dict_get_encoding (ia->dict), 
2095                                  var_get_print_format (var));
2096               
2097                   ia->columns[col].contents[rows - 1] = ss_cstr (ss);
2098                 }
2099           
2100               if (rows > MAX_PREVIEW_LINES)
2101                 {
2102                   case_unref (c);
2103                   break;
2104                 }
2105             }
2106           casereader_destroy (reader);
2107           ia->line_cnt = rows;
2108         }
2109       else
2110         {
2111           GtkWidget * dialog = gtk_message_dialog_new (NULL,
2112                                                        GTK_DIALOG_MODAL,
2113                                                        GTK_MESSAGE_ERROR,
2114                                                        GTK_BUTTONS_CLOSE,
2115                                                        _("An error occurred reading the spreadsheet file."));
2116
2117           gtk_dialog_run (GTK_DIALOG (dialog));
2118           gtk_widget_destroy (dialog);
2119         }
2120     }
2121
2122   psppire_dict = psppire_dict_new_from_dict (ia->dict);
2123   g_signal_connect (psppire_dict, "variable-changed",
2124                     G_CALLBACK (on_variable_change), ia);
2125   ia->psppire_dict = psppire_dict;
2126
2127   
2128   /* XXX: PsppireVarStore doesn't hold a reference to
2129      psppire_dict for now, but it should.  After it does, we
2130      should g_object_ref the psppire_dict here, since we also
2131      hold a reference via ia->formats->dict. */
2132   var_sheet = PSPPIRE_VAR_SHEET (psppire_var_sheet_new ());
2133   g_object_set (var_sheet,
2134                 "dictionary", psppire_dict,
2135                 "may-create-vars", FALSE,
2136                 "may-delete-vars", FALSE,
2137                 "format-use", FMT_FOR_INPUT,
2138                 "enable-grid-lines", PSPP_SHEET_VIEW_GRID_LINES_BOTH,
2139                 (void *) NULL);
2140
2141   vars_scroller = GTK_BIN (get_widget_assert (ia->builder, "vars-scroller"));
2142   old_var_sheet = gtk_bin_get_child (GTK_BIN (vars_scroller));
2143   if (old_var_sheet != NULL)
2144     gtk_container_remove (GTK_CONTAINER (vars_scroller),  old_var_sheet);
2145   gtk_container_add (GTK_CONTAINER (vars_scroller), GTK_WIDGET (var_sheet));
2146   gtk_widget_show (GTK_WIDGET (var_sheet));
2147
2148   ia->data_tree_view =
2149     GTK_WIDGET (create_data_tree_view (
2150                                        FALSE,
2151                                        GTK_CONTAINER (get_widget_assert (ia->builder, "data-scroller")),
2152                                        ia));
2153
2154   gtk_widget_show (ia->paste_button);
2155
2156   pop_watch_cursor (ia);
2157 }
2158
2159 static void
2160 formats_page_create (PsppireImportAssistant *ia)
2161 {
2162   GtkBuilder *builder = ia->builder;
2163
2164
2165   GtkWidget *w = get_widget_assert (builder, "Formats");
2166   g_object_set_data (G_OBJECT (w), "on-entering", prepare_formats_page);
2167   g_object_set_data (G_OBJECT (w), "on-reset", reset_formats_page);
2168   
2169   add_page_to_assistant (ia, w,
2170                          GTK_ASSISTANT_PAGE_CONFIRM, _("Adjust Variable Formats"));
2171
2172   ia->data_tree_view = NULL;
2173   ia->modified_vars = NULL;
2174   ia->modified_var_cnt = 0;
2175 }
2176
2177
2178 \f
2179
2180 static void 
2181 separators_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2182 {
2183   int i;
2184   ds_put_cstr (s, "  /DELIMITERS=\"");
2185   if (ds_find_byte (&ia->separators, '\t') != SIZE_MAX)
2186     ds_put_cstr (s, "\\t");
2187   if (ds_find_byte (&ia->separators, '\\') != SIZE_MAX)
2188     ds_put_cstr (s, "\\\\");
2189   for (i = 0; i < ds_length (&ia->separators); i++)
2190     {
2191       char c = ds_at (&ia->separators, i);
2192       if (c == '"')
2193         ds_put_cstr (s, "\"\"");
2194       else if (c != '\t' && c != '\\')
2195         ds_put_byte (s, c);
2196     }
2197   ds_put_cstr (s, "\"\n");
2198   if (!ds_is_empty (&ia->quotes))
2199     syntax_gen_pspp (s, "  /QUALIFIER=%sq\n", ds_cstr (&ia->quotes));
2200 }
2201
2202
2203 static void
2204 formats_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2205 {
2206   int i;
2207   int var_cnt;
2208
2209   g_return_if_fail (ia->dict);
2210   
2211   ds_put_cstr (s, "  /VARIABLES=\n");
2212   
2213   var_cnt = dict_get_var_cnt (ia->dict);
2214   for (i = 0; i < var_cnt; i++)
2215     {
2216       struct variable *var = dict_get_var (ia->dict, i);
2217       char format_string[FMT_STRING_LEN_MAX + 1];
2218       fmt_to_string (var_get_print_format (var), format_string);
2219       ds_put_format (s, "    %s %s%s\n",
2220                      var_get_name (var), format_string,
2221                      i == var_cnt - 1 ? "." : "");
2222     }
2223 }
2224
2225
2226 static void
2227 first_line_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2228 {
2229   if (ia->skip_lines > 0)
2230     ds_put_format (s, "  /FIRSTCASE=%d\n", ia->skip_lines + 1);
2231 }
2232
2233
2234 static void
2235 intro_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2236 {
2237   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->n_cases_button)))
2238     ds_put_format (s, "N OF CASES %d.\n",
2239                    gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (ia->n_cases_spin)));
2240   else if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->percent_button)))
2241     ds_put_format (s, "SAMPLE %.4g.\n",
2242                    gtk_spin_button_get_value (GTK_SPIN_BUTTON (ia->percent_spin)) / 100.0);
2243 }
2244
2245
2246 /* Emits PSPP syntax to S that applies the dictionary attributes
2247    (such as missing values and value labels) of the variables in
2248    DICT.  */
2249 static void
2250 apply_dict (const struct dictionary *dict, struct string *s)
2251 {
2252   size_t var_cnt = dict_get_var_cnt (dict);
2253   size_t i;
2254
2255   for (i = 0; i < var_cnt; i++)
2256     {
2257       struct variable *var = dict_get_var (dict, i);
2258       const char *name = var_get_name (var);
2259       enum val_type type = var_get_type (var);
2260       int width = var_get_width (var);
2261       enum measure measure = var_get_measure (var);
2262       enum var_role role = var_get_role (var);
2263       enum alignment alignment = var_get_alignment (var);
2264       const struct fmt_spec *format = var_get_print_format (var);
2265
2266       if (var_has_missing_values (var))
2267         {
2268           const struct missing_values *mv = var_get_missing_values (var);
2269           size_t j;
2270
2271           syntax_gen_pspp (s, "MISSING VALUES %ss (", name);
2272           for (j = 0; j < mv_n_values (mv); j++)
2273             {
2274               if (j)
2275                 ds_put_cstr (s, ", ");
2276               syntax_gen_value (s, mv_get_value (mv, j), width, format);
2277             }
2278
2279           if (mv_has_range (mv))
2280             {
2281               double low, high;
2282               if (mv_has_value (mv))
2283                 ds_put_cstr (s, ", ");
2284               mv_get_range (mv, &low, &high);
2285               syntax_gen_num_range (s, low, high, format);
2286             }
2287           ds_put_cstr (s, ").\n");
2288         }
2289       if (var_has_value_labels (var))
2290         {
2291           const struct val_labs *vls = var_get_value_labels (var);
2292           const struct val_lab **labels = val_labs_sorted (vls);
2293           size_t n_labels = val_labs_count (vls);
2294           size_t i;
2295
2296           syntax_gen_pspp (s, "VALUE LABELS %ss", name);
2297           for (i = 0; i < n_labels; i++)
2298             {
2299               const struct val_lab *vl = labels[i];
2300               ds_put_cstr (s, "\n  ");
2301               syntax_gen_value (s, &vl->value, width, format);
2302               ds_put_byte (s, ' ');
2303               syntax_gen_string (s, ss_cstr (val_lab_get_escaped_label (vl)));
2304             }
2305           free (labels);
2306           ds_put_cstr (s, ".\n");
2307         }
2308       if (var_has_label (var))
2309         syntax_gen_pspp (s, "VARIABLE LABELS %ss %sq.\n",
2310                          name, var_get_label (var));
2311       if (measure != var_default_measure (type))
2312         syntax_gen_pspp (s, "VARIABLE LEVEL %ss (%ss).\n",
2313                          name, measure_to_syntax (measure));
2314       if (role != ROLE_INPUT)
2315         syntax_gen_pspp (s, "VARIABLE ROLE /%ss %ss.\n",
2316                          var_role_to_syntax (role), name);
2317       if (alignment != var_default_alignment (type))
2318         syntax_gen_pspp (s, "VARIABLE ALIGNMENT %ss (%ss).\n",
2319                          name, alignment_to_syntax (alignment));
2320       if (var_get_display_width (var) != var_default_display_width (width))
2321         syntax_gen_pspp (s, "VARIABLE WIDTH %ss (%d).\n",
2322                          name, var_get_display_width (var));
2323     }
2324 }
2325
2326
2327
2328 static char *
2329 sheet_spec_gen_syntax (PsppireImportAssistant *ia)
2330 {
2331   GtkBuilder *builder = ia->builder;
2332   GtkWidget *range_entry = get_widget_assert (builder, "cell-range-entry");
2333   GtkWidget *sheet_entry = get_widget_assert (builder, "sheet-entry");
2334   GtkWidget *rnc = get_widget_assert (builder, "readnames-checkbox");
2335   const gchar *range = gtk_entry_get_text (GTK_ENTRY (range_entry));
2336   int sheet_index = 1 + gtk_combo_box_get_active (GTK_COMBO_BOX (sheet_entry));
2337   gboolean read_names = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (rnc));
2338
2339   struct string s = DS_EMPTY_INITIALIZER;
2340
2341   syntax_gen_pspp (&s,
2342                    "GET DATA"
2343                    "\n  /TYPE=%ss"
2344                    "\n  /FILE=%sq"
2345                    "\n  /SHEET=index %d"
2346                    "\n  /READNAMES=%ss",
2347                    (ia->spreadsheet->type == SPREADSHEET_GNUMERIC) ? "GNM" : "ODS",
2348                    ia->file_name,                        
2349                    sheet_index,
2350                    read_names ? "ON" : "OFF");
2351
2352
2353   if (range && 0 != strcmp ("", range))
2354     {
2355       syntax_gen_pspp (&s,
2356                        "\n  /CELLRANGE=RANGE %sq", range);
2357     }
2358   else
2359     {
2360       syntax_gen_pspp (&s,
2361                        "\n  /CELLRANGE=FULL");
2362     }
2363
2364
2365   syntax_gen_pspp (&s, ".");
2366
2367   
2368   return ds_cstr (&s);
2369 }
2370
2371 gchar *
2372 psppire_import_assistant_generate_syntax (PsppireImportAssistant *ia)
2373 {
2374   struct string s = DS_EMPTY_INITIALIZER;
2375
2376   if (!ia->spreadsheet)
2377     {
2378       if (ia->file_name == NULL)
2379         return NULL;
2380
2381       syntax_gen_pspp (&s,
2382                        "GET DATA"
2383                        "\n  /TYPE=TXT"
2384                        "\n  /FILE=%sq\n",
2385                        ia->file_name);
2386       if (ia->encoding && strcmp (ia->encoding, "Auto"))
2387         syntax_gen_pspp (&s, "  /ENCODING=%sq\n", ia->encoding);
2388
2389       ds_put_cstr (&s,
2390                    "  /ARRANGEMENT=DELIMITED\n"
2391                    "  /DELCASE=LINE\n");
2392
2393       first_line_append_syntax (ia, &s);
2394       separators_append_syntax (ia, &s);
2395
2396       formats_append_syntax (ia, &s);
2397       apply_dict (ia->dict, &s);
2398       intro_append_syntax (ia, &s);
2399     }
2400   else
2401     {
2402       return sheet_spec_gen_syntax (ia);
2403     }
2404   
2405   return ds_cstr (&s);
2406 }