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