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