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