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