Import Assistant: Allow separators to be unicode characters
[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/hmap.h"
42 #include "libpspp/hash-functions.h"
43 #include "libpspp/str.h"
44
45 #include "builder-wrapper.h"
46 #include "helper.h"
47 #include "psppire-import-assistant.h"
48 #include "psppire-scanf.h"
49 #include "psppire-dialog.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 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->quotes);
145
146   g_object_unref (ia->builder);
147
148   if (G_OBJECT_CLASS (parent_class)->finalize)
149     G_OBJECT_CLASS (parent_class)->finalize (object);
150 }
151
152
153 static void
154 psppire_import_assistant_class_init (PsppireImportAssistantClass *class)
155 {
156   GObjectClass *object_class = G_OBJECT_CLASS (class);
157
158   parent_class = g_type_class_peek_parent (class);
159
160   object_class->set_property = psppire_import_assistant_set_property;
161   object_class->get_property = psppire_import_assistant_get_property;
162
163   object_class->finalize = psppire_import_assistant_finalize;
164 }
165
166
167 /* Causes the assistant to close, returning RESPONSE for
168    interpretation by text_data_import_assistant. */
169 static void
170 close_assistant (PsppireImportAssistant *ia, int response)
171 {
172   ia->response = response;
173   g_main_loop_quit (ia->main_loop);
174   gtk_widget_hide (GTK_WIDGET (ia));
175 }
176
177
178 /* Called when the Paste button on the last page of the assistant
179    is clicked. */
180 static void
181 on_paste (GtkButton *button, PsppireImportAssistant *ia)
182 {
183   close_assistant (ia, PSPPIRE_RESPONSE_PASTE);
184 }
185
186
187 /* Revises the contents of the fields tree view based on the
188    currently chosen set of separators. */
189 static void
190 revise_fields_preview (PsppireImportAssistant *ia)
191 {
192   choose_column_names (ia);
193 }
194
195
196 struct separator
197 {
198   const char *name;           /* Name (for use with get_widget_assert). */
199   gunichar c;                 /* Separator character. */
200 };
201
202 /* All the separators in the dialog box. */
203 static const struct separator separators[] =
204   {
205     {"space", ' '},
206     {"tab", '\t'},
207     {"bang", '!'},
208     {"colon", ':'},
209     {"comma", ','},
210     {"hyphen", '-'},
211     {"pipe", '|'},
212     {"semicolon", ';'},
213     {"slash", '/'},
214   };
215 #define SEPARATOR_CNT (sizeof separators / sizeof *separators)
216
217 struct separator_count_node
218 {
219   struct hmap_node node;
220   int occurance; /* The number of times the separator occurs in a line */
221   int quantity;  /* The number of lines with this occurance */
222 };
223
224
225 /* Picks the most likely separator and quote characters based on
226    IA's file data. */
227 static void
228 choose_likely_separators (PsppireImportAssistant *ia)
229 {
230   gint first_line = 0;
231   g_object_get (ia->delimiters_model, "first-line", &first_line, NULL);
232
233   gboolean valid;
234   GtkTreeIter iter;
235   int j;
236
237   struct hmap count_map[SEPARATOR_CNT];
238   for (j = 0; j < SEPARATOR_CNT; ++j)
239     hmap_init (count_map + j);
240
241   GtkTreePath *p = gtk_tree_path_new_from_indices (first_line, -1);
242
243   for (valid = gtk_tree_model_get_iter (GTK_TREE_MODEL (ia->text_file), &iter, p);
244        valid;
245        valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (ia->text_file), &iter))
246     {
247       gchar *line_text = NULL;
248       gtk_tree_model_get (GTK_TREE_MODEL (ia->text_file), &iter, 1, &line_text, -1);
249
250       gint *counts = xzalloc (sizeof *counts * SEPARATOR_CNT);
251
252       struct substring cs = ss_cstr (line_text);
253       for (;
254            UINT32_MAX != ss_first_mb (cs);
255            ss_get_mb (&cs))
256         {
257           ucs4_t character = ss_first_mb (cs);
258
259           int s;
260           for (s = 0; s < SEPARATOR_CNT; ++s)
261             {
262               if (character == separators[s].c)
263                 counts[s]++;
264             }
265         }
266
267       int j;
268       for (j = 0; j < SEPARATOR_CNT; ++j)
269         {
270           if (counts[j] > 0)
271             {
272               struct separator_count_node *cn = NULL;
273               unsigned int hash = hash_int (counts[j], 0);
274               HMAP_FOR_EACH_WITH_HASH (cn, struct separator_count_node, node, hash, &count_map[j])
275                 {
276                   if (cn->occurance == counts[j])
277                     break;
278                 }
279
280               if (cn == NULL)
281                 {
282                   struct separator_count_node *new_cn = xzalloc (sizeof *new_cn);
283                   new_cn->occurance = counts[j];
284                   new_cn->quantity = 1;
285                   hmap_insert (&count_map[j], &new_cn->node, hash);
286                 }
287               else
288                 cn->quantity++;
289             }
290         }
291
292       free (line_text);
293       free (counts);
294     }
295   gtk_tree_path_free (p);
296
297   int most_frequent = -1;
298   int largest = 0;
299   for (j = 0; j < SEPARATOR_CNT; ++j)
300     {
301       struct separator_count_node *cn;
302       HMAP_FOR_EACH (cn, struct separator_count_node, node, &count_map[j])
303         {
304           if (largest < cn->quantity)
305             {
306               largest = cn->quantity;
307               most_frequent = j;
308             }
309         }
310       hmap_destroy (&count_map[j]);
311     }
312
313   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (get_widget_assert (ia->builder, separators[most_frequent].name)), TRUE);
314 }
315
316 static void
317 repopulate_delimiter_columns (PsppireImportAssistant *ia)
318 {
319   /* Remove all the columns */
320   while (gtk_tree_view_get_n_columns (GTK_TREE_VIEW (ia->fields_tree_view)) > 0)
321     {
322       GtkTreeViewColumn *tvc = gtk_tree_view_get_column (GTK_TREE_VIEW (ia->fields_tree_view), 0);
323       gtk_tree_view_remove_column (GTK_TREE_VIEW (ia->fields_tree_view), tvc);
324     }
325
326   gint n_fields = gtk_tree_model_get_n_columns (ia->delimiters_model);
327
328   /* ... and put them back again. */
329   gint f;
330   for (f = gtk_tree_view_get_n_columns (GTK_TREE_VIEW (ia->fields_tree_view));
331        f < n_fields; f++)
332     {
333       GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
334
335       const gchar *title = NULL;
336
337       if (f == 0)
338         title = _("line");
339       else
340         {
341           if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)))
342             {
343               title =
344                 psppire_delimited_text_get_header_title
345                 (PSPPIRE_DELIMITED_TEXT (ia->delimiters_model), f - 1);
346             }
347           if (title == NULL)
348             title = _("var");
349         }
350
351       GtkTreeViewColumn *column =
352         gtk_tree_view_column_new_with_attributes (title,
353                                                   renderer,
354                                                   "text", f,
355                                                   NULL);
356       g_object_set (column,
357                     "resizable", TRUE,
358                     "sizing", GTK_TREE_VIEW_COLUMN_AUTOSIZE,
359                     NULL);
360
361       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->fields_tree_view), column);
362     }
363 }
364
365 static void
366 reset_tree_view_model (PsppireImportAssistant *ia)
367 {
368   GtkTreeModel *tm = gtk_tree_view_get_model (GTK_TREE_VIEW (ia->fields_tree_view));
369   g_object_ref (tm);
370   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), NULL);
371
372
373   repopulate_delimiter_columns (ia);
374
375   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), tm);
376   //  gtk_tree_view_columns_autosize (GTK_TREE_VIEW (ia->fields_tree_view));
377
378   g_object_unref (tm);
379 }
380
381 /* Called just before the separators page becomes visible in the
382    assistant, and when the Reset button is clicked. */
383 static void
384 prepare_separators_page (PsppireImportAssistant *ia, GtkWidget *page)
385 {
386   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), ia->delimiters_model);
387
388   g_signal_connect_swapped (ia->delimiters_model, "notify::delimiters",
389                         G_CALLBACK (reset_tree_view_model), ia);
390
391
392   repopulate_delimiter_columns (ia);
393
394   revise_fields_preview (ia);
395   choose_likely_separators (ia);
396 }
397
398 /* Resets IA's intro page to its initial state. */
399 static void
400 reset_intro_page (PsppireImportAssistant *ia)
401 {
402   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ia->all_cases_button),
403                                 TRUE);
404 }
405
406
407
408 /* Clears the set of user-modified variables from IA's formats
409    substructure.  This discards user modifications to variable
410    formats, thereby causing formats to revert to their
411    defaults.  */
412 static void
413 reset_formats_page (PsppireImportAssistant *ia, GtkWidget *page)
414 {
415 }
416
417 static void prepare_formats_page (PsppireImportAssistant *ia);
418
419 /* Called when the Reset button is clicked. */
420 static void
421 on_reset (GtkButton *button, PsppireImportAssistant *ia)
422 {
423   gint pn = gtk_assistant_get_current_page (GTK_ASSISTANT (ia));
424   {
425     GtkWidget *page =  gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), pn);
426
427     page_func *on_reset = g_object_get_data (G_OBJECT (page), "on-reset");
428
429     if (on_reset)
430       on_reset (ia, page);
431   }
432 }
433
434
435 static gint
436 next_page_func (gint old_page, gpointer data)
437 {
438   return old_page + 1;
439 }
440
441
442 /* Called just before PAGE is displayed as the current page of
443    IMPORT_ASSISTANT, this updates IA content according to the new
444    page. */
445 static void
446 on_prepare (GtkAssistant *assistant, GtkWidget *page, PsppireImportAssistant *ia)
447 {
448   gtk_widget_show (ia->reset_button);
449   gtk_widget_hide (ia->paste_button);
450
451   gint pn = gtk_assistant_get_current_page (assistant);
452   gint previous_page_index = ia->current_page;
453
454   if (previous_page_index >= 0)
455     {
456       GtkWidget *closing_page = gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), previous_page_index);
457
458       if (pn > previous_page_index)
459         {
460           page_func *on_forward = g_object_get_data (G_OBJECT (closing_page), "on-forward");
461
462           if (on_forward)
463             on_forward (ia, closing_page);
464         }
465       else
466         {
467           page_func *on_back = g_object_get_data (G_OBJECT (closing_page), "on-back");
468
469           if (on_back)
470             on_back (ia, closing_page);
471         }
472     }
473
474   {
475     GtkWidget *new_page = gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), pn);
476
477     page_func *on_entering = g_object_get_data (G_OBJECT (new_page), "on-entering");
478
479     if (on_entering)
480       on_entering (ia, new_page);
481   }
482
483   ia->current_page = pn;
484 }
485
486 /* Called when the Cancel button in the assistant is clicked. */
487 static void
488 on_cancel (GtkAssistant *assistant, PsppireImportAssistant *ia)
489 {
490   close_assistant (ia, GTK_RESPONSE_CANCEL);
491 }
492
493 /* Called when the Apply button on the last page of the assistant
494    is clicked. */
495 static void
496 on_close (GtkAssistant *assistant, PsppireImportAssistant *ia)
497 {
498   close_assistant (ia, GTK_RESPONSE_APPLY);
499 }
500
501
502 static GtkWidget *
503 add_page_to_assistant (PsppireImportAssistant *ia,
504                        GtkWidget *page, GtkAssistantPageType type, const gchar *);
505
506
507 static void
508 on_sheet_combo_changed (GtkComboBox *cb, PsppireImportAssistant *ia)
509 {
510   GtkTreeIter iter;
511   gchar *range = NULL;
512   GtkTreeModel *model = gtk_combo_box_get_model (cb);
513   GtkBuilder *builder = ia->builder;
514   GtkWidget *range_entry = get_widget_assert (builder, "cell-range-entry");
515
516   gtk_combo_box_get_active_iter (cb, &iter);
517   gtk_tree_model_get (model, &iter, PSPPIRE_SPREADSHEET_MODEL_COL_RANGE, &range, -1);
518   gtk_entry_set_text (GTK_ENTRY (range_entry), range ?  range : "");
519   g_free (range);
520 }
521
522 /* Prepares IA's sheet_spec page. */
523 static void
524 prepare_sheet_spec_page (PsppireImportAssistant *ia)
525 {
526   GtkBuilder *builder = ia->builder;
527   GtkWidget *sheet_entry = get_widget_assert (builder, "sheet-entry");
528   GtkWidget *readnames_checkbox = get_widget_assert (builder, "readnames-checkbox");
529
530   gtk_combo_box_set_model (GTK_COMBO_BOX (sheet_entry),
531                            psppire_spreadsheet_model_new (ia->spreadsheet));
532
533   gtk_combo_box_set_active (GTK_COMBO_BOX (sheet_entry), 0);
534
535   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (readnames_checkbox), FALSE);
536 }
537
538
539 /* Initializes IA's sheet_spec substructure. */
540 static void
541 sheet_spec_page_create (PsppireImportAssistant *ia)
542 {
543   GtkBuilder *builder = ia->builder;
544   GtkWidget *page = get_widget_assert (builder, "Spreadsheet-Importer");
545
546   GtkWidget *combo_box = get_widget_assert (builder, "sheet-entry");
547   GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
548   gtk_cell_layout_clear (GTK_CELL_LAYOUT (combo_box));
549   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), renderer, TRUE);
550   gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), renderer,
551                                   "text", 0,
552                                   NULL);
553
554   g_signal_connect (combo_box, "changed", G_CALLBACK (on_sheet_combo_changed), ia);
555
556   add_page_to_assistant (ia, page,
557                          GTK_ASSISTANT_PAGE_CONTENT, _("Importing Spreadsheet Data"));
558
559   g_object_set_data (G_OBJECT (page), "on-entering", prepare_sheet_spec_page);
560 }
561
562 static void
563 on_chosen (PsppireImportAssistant *ia, GtkWidget *page)
564 {
565   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
566   gchar *f = gtk_file_chooser_get_filename (fc);
567   int i;
568
569   for(i = gtk_assistant_get_n_pages (GTK_ASSISTANT (ia)); i > 0; --i)
570     gtk_assistant_remove_page (GTK_ASSISTANT (ia), i);
571
572   gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), GTK_WIDGET (fc), FALSE);
573
574   if (f && !g_file_test (f, G_FILE_TEST_IS_DIR))
575     {
576       gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), GTK_WIDGET (fc), TRUE);
577
578       if (ia->spreadsheet)
579         spreadsheet_unref (ia->spreadsheet);
580
581       ia->spreadsheet = gnumeric_probe (f, FALSE);
582
583       if (!ia->spreadsheet)
584         ia->spreadsheet = ods_probe (f, FALSE);
585
586       if (!ia->spreadsheet)
587         {
588           intro_page_create (ia);
589           first_line_page_create (ia);
590           separators_page_create (ia);
591         }
592       else
593         {
594           sheet_spec_page_create (ia);
595         }
596
597       formats_page_create (ia);
598     }
599
600   g_free (f);
601 }
602
603 /* This has to be done on a map signal callback,
604    because GtkFileChooserWidget resets everything when it is mapped. */
605 static void
606 on_map (PsppireImportAssistant *ia, GtkWidget *page)
607 {
608 #if TEXT_FILE
609   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
610
611   if (ia->file_name)
612     gtk_file_chooser_set_filename (fc, ia->file_name);
613 #endif
614
615   on_chosen (ia, page);
616 }
617
618
619
620 static void
621 chooser_page_enter (PsppireImportAssistant *ia, GtkWidget *page)
622 {
623 }
624
625 static void
626 chooser_page_leave (PsppireImportAssistant *ia, GtkWidget *page)
627 {
628   g_print ("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__);
629   g_free (ia->file_name);
630   ia->file_name = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (page));
631   gchar *encoding = psppire_encoding_selector_get_encoding (ia->encoding_selector);
632
633   if (!ia->spreadsheet)
634     {
635       ia->text_file = psppire_text_file_new (ia->file_name, encoding);
636       gtk_tree_view_set_model (GTK_TREE_VIEW (ia->first_line_tree_view),
637                                GTK_TREE_MODEL (ia->text_file));
638     }
639
640
641   g_free (encoding);
642 }
643
644 static void
645 chooser_page_reset (PsppireImportAssistant *ia, GtkWidget *page)
646 {
647   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
648
649   gtk_file_chooser_set_filter (fc, ia->default_filter);
650   gtk_file_chooser_unselect_all (fc);
651
652   on_chosen (ia, page);
653 }
654
655
656
657 static void
658 chooser_page_create (PsppireImportAssistant *ia)
659 {
660   GtkFileFilter *filter = NULL;
661
662   GtkWidget *chooser = gtk_file_chooser_widget_new (GTK_FILE_CHOOSER_ACTION_OPEN);
663
664   g_object_set_data (G_OBJECT (chooser), "on-forward", chooser_page_leave);
665   g_object_set_data (G_OBJECT (chooser), "on-reset",   chooser_page_reset);
666   g_object_set_data (G_OBJECT (chooser), "on-entering",chooser_page_enter);
667
668   g_object_set (chooser, "local-only", FALSE, NULL);
669
670
671   ia->default_filter = gtk_file_filter_new ();
672   gtk_file_filter_set_name (ia->default_filter, _("All Files"));
673   gtk_file_filter_add_pattern (ia->default_filter, "*");
674   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), ia->default_filter);
675
676   filter = gtk_file_filter_new ();
677   gtk_file_filter_set_name (filter, _("Text Files"));
678   gtk_file_filter_add_mime_type (filter, "text/*");
679   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
680
681   filter = gtk_file_filter_new ();
682   gtk_file_filter_set_name (filter, _("Text (*.txt) Files"));
683   gtk_file_filter_add_pattern (filter, "*.txt");
684   gtk_file_filter_add_pattern (filter, "*.TXT");
685   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
686
687   filter = gtk_file_filter_new ();
688   gtk_file_filter_set_name (filter, _("Plain Text (ASCII) Files"));
689   gtk_file_filter_add_mime_type (filter, "text/plain");
690   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
691
692   filter = gtk_file_filter_new ();
693   gtk_file_filter_set_name (filter, _("Comma Separated Value Files"));
694   gtk_file_filter_add_mime_type (filter, "text/csv");
695   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
696
697   /* I've never encountered one of these, but it's listed here:
698      http://www.iana.org/assignments/media-types/text/tab-separated-values  */
699   filter = gtk_file_filter_new ();
700   gtk_file_filter_set_name (filter, _("Tab Separated Value Files"));
701   gtk_file_filter_add_mime_type (filter, "text/tab-separated-values");
702   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
703
704   filter = gtk_file_filter_new ();
705   gtk_file_filter_set_name (filter, _("Gnumeric Spreadsheet Files"));
706   gtk_file_filter_add_mime_type (filter, "application/x-gnumeric");
707   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
708
709   filter = gtk_file_filter_new ();
710   gtk_file_filter_set_name (filter, _("OpenDocument Spreadsheet Files"));
711   gtk_file_filter_add_mime_type (filter, "application/vnd.oasis.opendocument.spreadsheet");
712   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
713
714   filter = gtk_file_filter_new ();
715   gtk_file_filter_set_name (filter, _("All Spreadsheet Files"));
716   gtk_file_filter_add_mime_type (filter, "application/x-gnumeric");
717   gtk_file_filter_add_mime_type (filter, "application/vnd.oasis.opendocument.spreadsheet");
718   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
719
720   ia->encoding_selector = psppire_encoding_selector_new ("Auto", TRUE);
721   gtk_file_chooser_set_extra_widget (GTK_FILE_CHOOSER (chooser), ia->encoding_selector);
722
723   add_page_to_assistant (ia, chooser,
724                          GTK_ASSISTANT_PAGE_INTRO, _("Select File to Import"));
725
726   g_signal_connect_swapped (chooser, "selection-changed", G_CALLBACK (on_chosen), ia);
727   g_signal_connect_swapped (chooser, "map", G_CALLBACK (on_map), ia);
728 }
729
730
731
732 static void
733 psppire_import_assistant_init (PsppireImportAssistant *ia)
734 {
735   ia->builder = builder_new ("text-data-import.ui");
736
737   ia->current_page = -1 ;
738   ia->file_name = NULL;
739
740   ia->spreadsheet = NULL;
741
742   g_signal_connect (ia, "prepare", G_CALLBACK (on_prepare), ia);
743   g_signal_connect (ia, "cancel", G_CALLBACK (on_cancel), ia);
744   g_signal_connect (ia, "close", G_CALLBACK (on_close), ia);
745
746   ia->paste_button = gtk_button_new_with_label (_("Paste"));
747   ia->reset_button = gtk_button_new_with_label (_("Reset"));
748
749   gtk_assistant_add_action_widget (GTK_ASSISTANT(ia), ia->paste_button);
750
751   g_signal_connect (ia->paste_button, "clicked", G_CALLBACK (on_paste), ia);
752   g_signal_connect (ia->reset_button, "clicked", G_CALLBACK (on_reset), ia);
753
754   gtk_assistant_add_action_widget (GTK_ASSISTANT(ia), ia->reset_button);
755
756   gtk_window_set_title (GTK_WINDOW (ia),
757                         _("Importing Delimited Text Data"));
758
759   gtk_window_set_icon_name (GTK_WINDOW (ia), "pspp");
760
761   chooser_page_create (ia);
762
763   gtk_assistant_set_forward_page_func (GTK_ASSISTANT (ia), next_page_func, NULL, NULL);
764
765   gtk_window_maximize (GTK_WINDOW (ia));
766 }
767
768
769 /* Appends a page of the given TYPE, with PAGE as its content, to
770    the GtkAssistant encapsulated by IA.  Returns the GtkWidget
771    that represents the page. */
772 static GtkWidget *
773 add_page_to_assistant (PsppireImportAssistant *ia,
774                        GtkWidget *page, GtkAssistantPageType type, const gchar *title)
775 {
776   GtkWidget *content = page;
777
778   gtk_assistant_append_page (GTK_ASSISTANT (ia), content);
779   gtk_assistant_set_page_type (GTK_ASSISTANT(ia), content, type);
780   gtk_assistant_set_page_title (GTK_ASSISTANT(ia), content, title);
781   gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), content, TRUE);
782
783   return content;
784 }
785
786
787 /* Called when one of the radio buttons is clicked. */
788 static void
789 on_intro_amount_changed (PsppireImportAssistant *p)
790 {
791   gtk_widget_set_sensitive (p->n_cases_spin,
792                             gtk_toggle_button_get_active (
793                                                           GTK_TOGGLE_BUTTON (p->n_cases_button)));
794
795   gtk_widget_set_sensitive (p->percent_spin,
796                             gtk_toggle_button_get_active (
797                                                           GTK_TOGGLE_BUTTON (p->percent_button)));
798 }
799
800
801
802 static void
803 on_treeview_selection_change (PsppireImportAssistant *ia)
804 {
805   GtkTreeSelection *selection =
806     gtk_tree_view_get_selection (GTK_TREE_VIEW (ia->first_line_tree_view));
807   GtkTreeModel *model = NULL;
808   GtkTreeIter iter;
809   if (gtk_tree_selection_get_selected (selection, &model, &iter))
810     {
811       int n;
812       GtkTreePath *path = gtk_tree_model_get_path (model, &iter);
813       gint *index = gtk_tree_path_get_indices (path);
814
815       n = *index;
816
817       gtk_tree_path_free (path);
818
819       gtk_widget_set_sensitive (ia->variable_names_cb, n > 0);
820
821       ia->delimiters_model
822         = psppire_delimited_text_new (GTK_TREE_MODEL (ia->text_file));
823       g_object_set (ia->delimiters_model, "first-line", n, NULL);
824
825       g_print ("%s:%d DT %p first line %d\n", __FILE__, __LINE__, ia->delimiters_model, n);
826     }
827 }
828
829
830 /* Initializes IA's first_line substructure. */
831 static void
832 first_line_page_create (PsppireImportAssistant *ia)
833 {
834   g_print ("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__);
835   GtkWidget *w =  get_widget_assert (ia->builder, "FirstLine");
836
837   g_object_set_data (G_OBJECT (w), "on-entering", on_treeview_selection_change);
838
839   add_page_to_assistant (ia, w,
840                          GTK_ASSISTANT_PAGE_CONTENT, _("Select the First Line"));
841
842   GtkWidget *scrolled_window = get_widget_assert (ia->builder, "first-line-scroller");
843
844   if (ia->first_line_tree_view == NULL)
845     {
846       ia->first_line_tree_view = gtk_tree_view_new ();
847
848       gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (ia->first_line_tree_view), TRUE);
849
850       GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
851       GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes (_("Line"), renderer,
852                                                                             "text", 0,
853                                                                             NULL);
854       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->first_line_tree_view), column);
855
856       renderer = gtk_cell_renderer_text_new ();
857       column = gtk_tree_view_column_new_with_attributes (_("Text"), renderer, "text", 1, NULL);
858       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->first_line_tree_view), column);
859
860       gtk_container_add (GTK_CONTAINER (scrolled_window), ia->first_line_tree_view);
861
862       g_signal_connect_swapped (ia->first_line_tree_view, "cursor-changed",
863                         G_CALLBACK (on_treeview_selection_change), ia);
864     }
865   gtk_widget_show_all (scrolled_window);
866
867   ia->variable_names_cb = get_widget_assert (ia->builder, "variable-names");
868
869 }
870
871
872
873
874 static void
875 intro_on_enter (PsppireImportAssistant *ia)
876 {
877   GtkBuilder *builder = ia->builder;
878   GtkWidget *table  = get_widget_assert (builder, "button-table");
879
880   struct string s;
881
882   ds_init_empty (&s);
883   ds_put_cstr (&s, _("This assistant will guide you through the process of "
884                      "importing data into PSPP from a text file with one line "
885                      "per case,  in which fields are separated by tabs, "
886                      "commas, or other delimiters.\n\n"));
887
888   if (ia->text_file)
889     {
890       if (ia->text_file->total_is_exact)
891         {
892           ds_put_format (
893                          &s, ngettext ("The selected file contains %'lu line of text.  ",
894                                        "The selected file contains %'lu lines of text.  ",
895                                        ia->text_file->total_lines),
896                          ia->text_file->total_lines);
897         }
898       else if (ia->text_file->total_lines > 0)
899         {
900           ds_put_format (
901                          &s, ngettext (
902                                        "The selected file contains approximately %'lu line of text.  ",
903                                        "The selected file contains approximately %'lu lines of text.  ",
904                                        ia->text_file->total_lines),
905                          ia->text_file->total_lines);
906           ds_put_format (
907                          &s, ngettext (
908                                        "Only the first %zu line of the file will be shown for "
909                                        "preview purposes in the following screens.  ",
910                                        "Only the first %zu lines of the file will be shown for "
911                                        "preview purposes in the following screens.  ",
912                                        ia->text_file->line_cnt),
913                          ia->text_file->line_cnt);
914         }
915     }
916
917   ds_put_cstr (&s, _("You may choose below how much of the file should "
918                      "actually be imported."));
919
920   gtk_label_set_text (GTK_LABEL (get_widget_assert (builder, "intro-label")),
921                       ds_cstr (&s));
922   ds_destroy (&s);
923
924   GtkWidget *w  =  gtk_grid_get_child_at (GTK_GRID (table), 1, 1);
925   int old_value = w ? gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (ia->n_cases_spin)) : 1;
926   if (w)
927     gtk_container_remove (GTK_CONTAINER (table), w);
928
929   w  =  gtk_grid_get_child_at (GTK_GRID (table), 1, 2);
930   if (w)
931     gtk_container_remove (GTK_CONTAINER (table), w);
932
933
934   GtkWidget *hbox_n_cases = psppire_scanf_new (_("Only the first %4d cases"), &ia->n_cases_spin);
935
936   GtkAdjustment *adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (ia->n_cases_spin));
937   gtk_adjustment_set_lower (adj, 1.0);
938
939   if (ia->text_file)
940     {
941       if (psppire_text_file_get_total_exact (ia->text_file))
942         {
943           gulong total_lines = psppire_text_file_get_n_lines (ia->text_file);
944           gtk_adjustment_set_upper (adj, total_lines);
945           gtk_adjustment_set_value (adj, old_value);
946         }
947       else
948         gtk_adjustment_set_upper (adj, DBL_MAX);
949     }
950   gtk_grid_attach (GTK_GRID (table), hbox_n_cases,
951                    1, 1,
952                    1, 1);
953
954
955   GtkWidget *hbox_percent = psppire_scanf_new (_("Only the first %3d %% of file (approximately)"),
956                                                &ia->percent_spin);
957
958   gtk_grid_attach (GTK_GRID (table), hbox_percent,
959                    1, 2,
960                    1, 1);
961
962   gtk_widget_show_all (table);
963
964   on_intro_amount_changed (ia);
965 }
966
967 /* Initializes IA's intro substructure. */
968 static void
969 intro_page_create (PsppireImportAssistant *ia)
970 {
971   GtkBuilder *builder = ia->builder;
972
973   GtkWidget *w =  get_widget_assert (builder, "Intro");
974
975   ia->percent_spin = gtk_spin_button_new_with_range (0, 100, 10);
976
977
978   add_page_to_assistant (ia, w,  GTK_ASSISTANT_PAGE_CONTENT, _("Select the Lines to Import"));
979
980   ia->all_cases_button = get_widget_assert (builder, "import-all-cases");
981
982   ia->n_cases_button = get_widget_assert (builder, "import-n-cases");
983
984   ia->percent_button = get_widget_assert (builder, "import-percent");
985
986   g_signal_connect_swapped (ia->all_cases_button, "toggled",
987                             G_CALLBACK (on_intro_amount_changed), ia);
988   g_signal_connect_swapped (ia->n_cases_button, "toggled",
989                             G_CALLBACK (on_intro_amount_changed), ia);
990   g_signal_connect_swapped (ia->percent_button, "toggled",
991                             G_CALLBACK (on_intro_amount_changed), ia);
992
993
994   g_object_set_data (G_OBJECT (w), "on-entering", intro_on_enter);
995   g_object_set_data (G_OBJECT (w), "on-reset", reset_intro_page);
996 }
997
998
999 GtkWidget *
1000 psppire_import_assistant_new (GtkWindow *toplevel)
1001 {
1002   return GTK_WIDGET (g_object_new (PSPPIRE_TYPE_IMPORT_ASSISTANT,
1003                                    /* Some window managers (notably ratpoison)
1004                                       ignore the maximise command when a window is
1005                                       transient.  This causes problems for this
1006                                       window. */
1007                                    /* "transient-for", toplevel, */
1008                                    NULL));
1009 }
1010
1011
1012
1013 \f
1014
1015 static void
1016 set_quote_list (GtkComboBox *cb)
1017 {
1018   GtkListStore *list =  gtk_list_store_new (1, G_TYPE_STRING);
1019   GtkTreeIter iter;
1020   gint i;
1021   const gchar *separator[3] = {"'\"", "\'", "\""};
1022
1023   for (i = 0; i < 3; i++)
1024     {
1025       const gchar *s = separator[i];
1026
1027       /* Add a new row to the model */
1028       gtk_list_store_append (list, &iter);
1029       gtk_list_store_set (list, &iter,
1030                           0, s,
1031                           -1);
1032
1033     }
1034
1035   gtk_combo_box_set_model (GTK_COMBO_BOX (cb), GTK_TREE_MODEL (list));
1036   g_object_unref (list);
1037
1038   gtk_combo_box_set_entry_text_column (cb, 0);
1039 }
1040
1041
1042
1043 /* Chooses a name for each column on the separators page */
1044 static void
1045 choose_column_names (PsppireImportAssistant *ia)
1046 {
1047   int i;
1048   unsigned long int generated_name_count = 0;
1049   dict_clear (ia->dict);
1050
1051   g_print ("%s:%d XXX %d\n", __FILE__, __LINE__, gtk_tree_model_get_n_columns (ia->delimiters_model));
1052       
1053   for (i = 0; i < gtk_tree_model_get_n_columns (ia->delimiters_model) - 1; ++i)
1054     {
1055       const gchar *candidate_name = NULL;
1056
1057       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)))
1058         {
1059           candidate_name = psppire_delimited_text_get_header_title (PSPPIRE_DELIMITED_TEXT (ia->delimiters_model), i);
1060         }
1061
1062       g_print ("%s:%d CN is %s\n", __FILE__, __LINE__, candidate_name);
1063
1064       char *name = dict_make_unique_var_name (ia->dict,
1065                                               candidate_name,
1066                                               &generated_name_count);
1067           
1068       dict_create_var_assert (ia->dict, name, 0);
1069       free (name);
1070     }
1071 }
1072
1073
1074
1075 /* Called when the user toggles one of the separators
1076    checkboxes. */
1077 static void
1078 on_separator_toggle (GtkToggleButton *toggle UNUSED,
1079                      PsppireImportAssistant *ia)
1080 {
1081   int i;
1082   GSList *delimiters = NULL;
1083   for (i = 0; i < SEPARATOR_CNT; i++)
1084     {
1085       const struct separator *s = &separators[i];
1086       GtkWidget *button = get_widget_assert (ia->builder, s->name);
1087       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
1088         {
1089           delimiters = g_slist_prepend (delimiters,  GINT_TO_POINTER (s->c));
1090         }
1091     }
1092
1093   g_object_set (ia->delimiters_model, "delimiters", delimiters, NULL);
1094
1095   revise_fields_preview (ia);
1096 }
1097
1098
1099 /* Called when the user changes the entry field for custom
1100    separators. */
1101 static void
1102 on_separators_custom_entry_notify (GObject *gobject UNUSED,
1103                                    GParamSpec *arg1 UNUSED,
1104                                    PsppireImportAssistant *ia)
1105 {
1106   revise_fields_preview (ia);
1107 }
1108
1109 /* Called when the user toggles the checkbox that enables custom
1110    separators. */
1111 static void
1112 on_separators_custom_cb_toggle (GtkToggleButton *custom_cb,
1113                                 PsppireImportAssistant *ia)
1114 {
1115   bool is_active = gtk_toggle_button_get_active (custom_cb);
1116   gtk_widget_set_sensitive (ia->custom_entry, is_active);
1117   revise_fields_preview (ia);
1118 }
1119
1120 /* Called when the user changes the selection in the combo box
1121    that selects a quote character. */
1122 static void
1123 on_quote_combo_change (GtkComboBox *combo, PsppireImportAssistant *ia)
1124 {
1125   //  revise_fields_preview (ia);
1126 }
1127
1128 /* Called when the user toggles the checkbox that enables
1129    quoting. */
1130 static void
1131 on_quote_cb_toggle (GtkToggleButton *quote_cb, PsppireImportAssistant *ia)
1132 {
1133   bool is_active = gtk_toggle_button_get_active (quote_cb);
1134   gtk_widget_set_sensitive (ia->quote_combo, is_active);
1135   revise_fields_preview (ia);
1136 }
1137
1138 /* Initializes IA's separators substructure. */
1139 static void
1140 separators_page_create (PsppireImportAssistant *ia)
1141 {
1142   GtkBuilder *builder = ia->builder;
1143
1144   size_t i;
1145
1146   GtkWidget *w = get_widget_assert (builder, "Separators");
1147
1148   g_object_set_data (G_OBJECT (w), "on-entering", prepare_separators_page);
1149   g_object_set_data (G_OBJECT (w), "on-reset", prepare_separators_page);
1150
1151   add_page_to_assistant (ia, w,   GTK_ASSISTANT_PAGE_CONTENT, _("Choose Separators"));
1152
1153   ia->custom_cb = get_widget_assert (builder, "custom-cb");
1154   ia->custom_entry = get_widget_assert (builder, "custom-entry");
1155   ia->quote_combo = get_widget_assert (builder, "quote-combo");
1156   ia->quote_entry = GTK_ENTRY (gtk_bin_get_child (GTK_BIN (ia->quote_combo)));
1157   ia->quote_cb = get_widget_assert (builder, "quote-cb");
1158
1159   set_quote_list (GTK_COMBO_BOX (ia->quote_combo));
1160
1161   if (ia->fields_tree_view == NULL)
1162     {
1163       GtkWidget *scroller = get_widget_assert (ia->builder, "fields-scroller");
1164       ia->fields_tree_view = gtk_tree_view_new ();
1165       gtk_container_add (GTK_CONTAINER (scroller), GTK_WIDGET (ia->fields_tree_view));
1166       gtk_widget_show_all (scroller);
1167     }
1168
1169   g_signal_connect (ia->quote_combo, "changed",
1170                     G_CALLBACK (on_quote_combo_change), ia);
1171   g_signal_connect (ia->quote_cb, "toggled",
1172                     G_CALLBACK (on_quote_cb_toggle), ia);
1173   g_signal_connect (ia->custom_entry, "notify::text",
1174                     G_CALLBACK (on_separators_custom_entry_notify), ia);
1175   g_signal_connect (ia->custom_cb, "toggled",
1176                     G_CALLBACK (on_separators_custom_cb_toggle), ia);
1177   for (i = 0; i < SEPARATOR_CNT; i++)
1178     g_signal_connect (get_widget_assert (builder, separators[i].name),
1179                       "toggled", G_CALLBACK (on_separator_toggle), ia);
1180
1181 }
1182
1183
1184
1185 \f
1186
1187
1188 static struct casereader_random_class my_casereader_class;
1189
1190 static struct ccase *
1191 my_read (struct casereader *reader, void *aux, casenumber idx)
1192 {
1193   PsppireImportAssistant *ia = PSPPIRE_IMPORT_ASSISTANT (aux);
1194   GtkTreeModel *tm = GTK_TREE_MODEL (ia->delimiters_model);
1195
1196   GtkTreePath *tp = gtk_tree_path_new_from_indices (idx, -1);
1197
1198   const struct caseproto *proto = casereader_get_proto (reader);
1199
1200   GtkTreeIter iter;
1201   struct ccase *c = NULL;
1202   if (gtk_tree_model_get_iter (tm, &iter, tp))
1203     {
1204       c = case_create (proto);
1205       int i;
1206       for (i = 0 ; i < caseproto_get_n_widths (proto); ++i)
1207         {
1208           GValue value = {0};
1209           gtk_tree_model_get_value (tm, &iter, i + 1, &value);
1210
1211           const struct variable *var = dict_get_var (ia->dict, i);
1212
1213           const gchar *ss = g_value_get_string (&value);
1214
1215           union value *v = case_data_rw (c, var);
1216           char *xx = data_in (ss_cstr (ss),
1217                               "UTF-8",
1218                               var_get_write_format (var)->type,
1219                               v, var_get_width (var), "UTF-8");
1220
1221           /* if (xx) */
1222           /*   g_print ("%s:%d Err %s\n", __FILE__, __LINE__, xx); */
1223           free (xx);
1224           g_value_unset (&value);
1225         }
1226     }
1227
1228   gtk_tree_path_free (tp);
1229
1230   return c;
1231 }
1232
1233 static void
1234 my_destroy (struct casereader *reader, void *aux)
1235 {
1236   g_print ("%s:%d %p\n", __FILE__, __LINE__, reader);
1237 }
1238
1239 static void
1240 my_advance (struct casereader *reader, void *aux, casenumber cnt)
1241 {
1242   g_print ("%s:%d\n", __FILE__, __LINE__);
1243 }
1244
1245 static void
1246 foo (struct dictionary *dict, void *aux)
1247 {
1248   PsppireImportAssistant *ia = PSPPIRE_IMPORT_ASSISTANT (aux);
1249   g_print ("%s:%d\n", __FILE__, __LINE__);
1250
1251   struct caseproto *proto = caseproto_create ();
1252
1253   int i;
1254   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1255     {
1256       const struct variable *var = dict_get_var (ia->dict, i);
1257       proto = caseproto_add_width (proto, var_get_width (var));
1258     }
1259
1260
1261   gint n_rows = gtk_tree_model_iter_n_children (ia->delimiters_model, NULL);
1262
1263   struct casereader *reader =
1264     casereader_create_random (proto, n_rows, &my_casereader_class,  ia);
1265
1266
1267   PsppireDataStore *store = NULL;
1268
1269   g_object_get (ia->data_sheet, "data-model", &store, NULL);
1270
1271   psppire_data_store_set_reader (store, reader);
1272 }
1273
1274 /* Called just before the formats page of the assistant is
1275    displayed. */
1276 static void
1277 prepare_formats_page (PsppireImportAssistant *ia)
1278 {
1279   PsppireDict *dict = psppire_dict_new_from_dict (ia->dict);
1280   g_object_set (ia->var_sheet, "data-model", dict, NULL);
1281
1282   my_casereader_class.read = my_read;
1283   my_casereader_class.destroy = my_destroy;
1284   my_casereader_class.advance = my_advance;
1285
1286   struct caseproto *proto = caseproto_create ();
1287   int i;
1288
1289   struct fmt_guesser **fg = xcalloc (sizeof *fg, dict_get_var_cnt (ia->dict));
1290   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1291     {
1292       fg[i] = fmt_guesser_create ();
1293     }
1294
1295   gint n_rows = gtk_tree_model_iter_n_children (ia->delimiters_model, NULL);
1296
1297   GtkTreeIter iter;
1298   gboolean ok;
1299   for (ok = gtk_tree_model_get_iter_first (ia->delimiters_model, &iter);
1300        ok;
1301        ok = gtk_tree_model_iter_next (ia->delimiters_model, &iter))
1302     {
1303       for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1304         {
1305           gchar *s = NULL;
1306           gtk_tree_model_get (ia->delimiters_model, &iter, i+1, &s, -1);
1307           fmt_guesser_add (fg[i], ss_cstr (s));
1308           free (s);
1309         }
1310     }
1311
1312   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1313     {
1314       struct fmt_spec fs;
1315       fmt_guesser_guess (fg[i], &fs);
1316
1317       fmt_fix (&fs, FMT_FOR_INPUT);
1318
1319       struct variable *var = dict_get_var (ia->dict, i);
1320
1321       int width = fmt_var_width (&fs);
1322
1323       var_set_width_and_formats (var, width,
1324                                  &fs, &fs);
1325
1326       proto = caseproto_add_width (proto, width);
1327       fmt_guesser_destroy (fg[i]);
1328     }
1329
1330   free (fg);
1331
1332   //  dict_set_change_callback (ia->dict, foo, ia);
1333
1334   struct casereader *reader =
1335     casereader_create_random (proto, n_rows, &my_casereader_class,  ia);
1336
1337   PsppireDataStore *store = psppire_data_store_new (dict);
1338   psppire_data_store_set_reader (store, reader);
1339
1340   g_object_set (ia->data_sheet, "data-model", store, NULL);
1341
1342
1343   gint pmax;
1344   g_object_get (get_widget_assert (ia->builder, "vpaned1"),
1345                 "max-position", &pmax, NULL);
1346
1347
1348   g_object_set (get_widget_assert (ia->builder, "vpaned1"),
1349                 "position", pmax / 2, NULL);
1350
1351   gtk_widget_show (ia->paste_button);
1352 }
1353
1354 static void
1355 formats_page_create (PsppireImportAssistant *ia)
1356 {
1357   GtkBuilder *builder = ia->builder;
1358
1359   GtkWidget *w = get_widget_assert (builder, "Formats");
1360   g_object_set_data (G_OBJECT (w), "on-entering", prepare_formats_page);
1361   g_object_set_data (G_OBJECT (w), "on-reset", reset_formats_page);
1362
1363   GtkWidget *vars_scroller = get_widget_assert (builder, "vars-scroller");
1364   if (ia->var_sheet == NULL)
1365     {
1366       ia->var_sheet = psppire_variable_sheet_new ();
1367
1368       gtk_container_add (GTK_CONTAINER (vars_scroller), ia->var_sheet);
1369
1370       ia->dict = dict_create (get_default_encoding ());
1371
1372       gtk_widget_show_all (vars_scroller);
1373     }
1374   GtkWidget *data_scroller = get_widget_assert (builder, "data-scroller");
1375   if (ia->data_sheet == NULL)
1376     {
1377       ia->data_sheet = psppire_data_sheet_new ();
1378
1379       gtk_container_add (GTK_CONTAINER (data_scroller), ia->data_sheet);
1380
1381       gtk_widget_show_all (data_scroller);
1382     }
1383
1384   add_page_to_assistant (ia, w,
1385                          GTK_ASSISTANT_PAGE_CONFIRM, _("Adjust Variable Formats"));
1386 }
1387
1388
1389 \f
1390
1391 static void
1392 separators_append_syntax (const PsppireImportAssistant *ia, struct string *s)
1393 {
1394   int i;
1395
1396   ds_put_cstr (s, "  /DELIMITERS=\"");
1397
1398   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (get_widget_assert (ia->builder, "tab"))))
1399     ds_put_cstr (s, "\\t");
1400   for (i = 0; i < SEPARATOR_CNT; i++)
1401     {
1402       const struct separator *seps = &separators[i];
1403       GtkWidget *button = get_widget_assert (ia->builder, seps->name);
1404       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
1405         {
1406           if (seps->c == '\t')
1407             continue;
1408
1409           ds_put_byte (s, seps->c);
1410         }
1411     }
1412   ds_put_cstr (s, "\"\n");
1413   if (!ds_is_empty (&ia->quotes))
1414     syntax_gen_pspp (s, "  /QUALIFIER=%sq\n", ds_cstr (&ia->quotes));
1415 }
1416
1417 static void
1418 formats_append_syntax (const PsppireImportAssistant *ia, struct string *s)
1419 {
1420   int i;
1421   int var_cnt;
1422
1423   g_return_if_fail (ia->dict);
1424
1425   ds_put_cstr (s, "  /VARIABLES=\n");
1426
1427   var_cnt = dict_get_var_cnt (ia->dict);
1428   for (i = 0; i < var_cnt; i++)
1429     {
1430       struct variable *var = dict_get_var (ia->dict, i);
1431       char format_string[FMT_STRING_LEN_MAX + 1];
1432       fmt_to_string (var_get_print_format (var), format_string);
1433       ds_put_format (s, "    %s %s%s\n",
1434                      var_get_name (var), format_string,
1435                      i == var_cnt - 1 ? "." : "");
1436     }
1437 }
1438
1439 static void
1440 first_line_append_syntax (const PsppireImportAssistant *ia, struct string *s)
1441 {
1442   gint first_case = 0;
1443   g_object_get (ia->delimiters_model, "first-line", &first_case, NULL);
1444
1445   if (first_case > 0)
1446     ds_put_format (s, "  /FIRSTCASE=%d\n", first_case + 1);
1447 }
1448
1449 static void
1450 intro_append_syntax (const PsppireImportAssistant *ia, struct string *s)
1451 {
1452   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->n_cases_button)))
1453     ds_put_format (s, "N OF CASES %d.\n",
1454                    gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (ia->n_cases_spin)));
1455   else if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->percent_button)))
1456     ds_put_format (s, "SAMPLE %.4g.\n",
1457                    gtk_spin_button_get_value (GTK_SPIN_BUTTON (ia->percent_spin)) / 100.0);
1458 }
1459
1460
1461 /* Emits PSPP syntax to S that applies the dictionary attributes
1462    (such as missing values and value labels) of the variables in
1463    DICT.  */
1464 static void
1465 apply_dict (const struct dictionary *dict, struct string *s)
1466 {
1467   size_t var_cnt = dict_get_var_cnt (dict);
1468   size_t i;
1469
1470   for (i = 0; i < var_cnt; i++)
1471     {
1472       struct variable *var = dict_get_var (dict, i);
1473       const char *name = var_get_name (var);
1474       enum val_type type = var_get_type (var);
1475       int width = var_get_width (var);
1476       enum measure measure = var_get_measure (var);
1477       enum var_role role = var_get_role (var);
1478       enum alignment alignment = var_get_alignment (var);
1479       const struct fmt_spec *format = var_get_print_format (var);
1480
1481       if (var_has_missing_values (var))
1482         {
1483           const struct missing_values *mv = var_get_missing_values (var);
1484           size_t j;
1485
1486           syntax_gen_pspp (s, "MISSING VALUES %ss (", name);
1487           for (j = 0; j < mv_n_values (mv); j++)
1488             {
1489               if (j)
1490                 ds_put_cstr (s, ", ");
1491               syntax_gen_value (s, mv_get_value (mv, j), width, format);
1492             }
1493
1494           if (mv_has_range (mv))
1495             {
1496               double low, high;
1497               if (mv_has_value (mv))
1498                 ds_put_cstr (s, ", ");
1499               mv_get_range (mv, &low, &high);
1500               syntax_gen_num_range (s, low, high, format);
1501             }
1502           ds_put_cstr (s, ").\n");
1503         }
1504       if (var_has_value_labels (var))
1505         {
1506           const struct val_labs *vls = var_get_value_labels (var);
1507           const struct val_lab **labels = val_labs_sorted (vls);
1508           size_t n_labels = val_labs_count (vls);
1509           size_t i;
1510
1511           syntax_gen_pspp (s, "VALUE LABELS %ss", name);
1512           for (i = 0; i < n_labels; i++)
1513             {
1514               const struct val_lab *vl = labels[i];
1515               ds_put_cstr (s, "\n  ");
1516               syntax_gen_value (s, &vl->value, width, format);
1517               ds_put_byte (s, ' ');
1518               syntax_gen_string (s, ss_cstr (val_lab_get_escaped_label (vl)));
1519             }
1520           free (labels);
1521           ds_put_cstr (s, ".\n");
1522         }
1523       if (var_has_label (var))
1524         syntax_gen_pspp (s, "VARIABLE LABELS %ss %sq.\n",
1525                          name, var_get_label (var));
1526       if (measure != var_default_measure (type))
1527         syntax_gen_pspp (s, "VARIABLE LEVEL %ss (%ss).\n",
1528                          name, measure_to_syntax (measure));
1529       if (role != ROLE_INPUT)
1530         syntax_gen_pspp (s, "VARIABLE ROLE /%ss %ss.\n",
1531                          var_role_to_syntax (role), name);
1532       if (alignment != var_default_alignment (type))
1533         syntax_gen_pspp (s, "VARIABLE ALIGNMENT %ss (%ss).\n",
1534                          name, alignment_to_syntax (alignment));
1535       if (var_get_display_width (var) != var_default_display_width (width))
1536         syntax_gen_pspp (s, "VARIABLE WIDTH %ss (%d).\n",
1537                          name, var_get_display_width (var));
1538     }
1539 }
1540
1541
1542
1543 static char *
1544 sheet_spec_gen_syntax (PsppireImportAssistant *ia)
1545 {
1546   GtkBuilder *builder = ia->builder;
1547   GtkWidget *range_entry = get_widget_assert (builder, "cell-range-entry");
1548   GtkWidget *sheet_entry = get_widget_assert (builder, "sheet-entry");
1549   GtkWidget *rnc = get_widget_assert (builder, "readnames-checkbox");
1550   const gchar *range = gtk_entry_get_text (GTK_ENTRY (range_entry));
1551   int sheet_index = 1 + gtk_combo_box_get_active (GTK_COMBO_BOX (sheet_entry));
1552   gboolean read_names = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (rnc));
1553
1554   struct string s = DS_EMPTY_INITIALIZER;
1555
1556   char *filename;
1557   g_object_get (ia->text_file, "file-name", &filename, NULL);
1558   syntax_gen_pspp (&s,
1559                    "GET DATA"
1560                    "\n  /TYPE=%ss"
1561                    "\n  /FILE=%sq"
1562                    "\n  /SHEET=index %d"
1563                    "\n  /READNAMES=%ss",
1564                    (ia->spreadsheet->type == SPREADSHEET_GNUMERIC) ? "GNM" : "ODS",
1565                    filename,
1566                    sheet_index,
1567                    read_names ? "ON" : "OFF");
1568
1569   if (range && 0 != strcmp ("", range))
1570     {
1571       syntax_gen_pspp (&s,
1572                        "\n  /CELLRANGE=RANGE %sq", range);
1573     }
1574   else
1575     {
1576       syntax_gen_pspp (&s,
1577                        "\n  /CELLRANGE=FULL");
1578     }
1579
1580
1581   syntax_gen_pspp (&s, ".");
1582
1583
1584   return ds_cstr (&s);
1585 }
1586
1587
1588 gchar *
1589 psppire_import_assistant_generate_syntax (PsppireImportAssistant *ia)
1590 {
1591   struct string s = DS_EMPTY_INITIALIZER;
1592
1593   if (!ia->spreadsheet)
1594     {
1595       gchar *file_name = NULL;
1596       gchar *encoding = NULL;
1597       g_object_get (ia->text_file,
1598                     "file-name", &file_name,
1599                     "encoding", &encoding,
1600                     NULL);
1601
1602       if (file_name == NULL)
1603         return NULL;
1604
1605       syntax_gen_pspp (&s,
1606                        "GET DATA"
1607                        "\n  /TYPE=TXT"
1608                        "\n  /FILE=%sq\n",
1609                        file_name);
1610       if (encoding && strcmp (encoding, "Auto"))
1611         syntax_gen_pspp (&s, "  /ENCODING=%sq\n", encoding);
1612
1613       ds_put_cstr (&s,
1614                    "  /ARRANGEMENT=DELIMITED\n"
1615                    "  /DELCASE=LINE\n");
1616
1617       first_line_append_syntax (ia, &s);
1618       separators_append_syntax (ia, &s);
1619
1620       formats_append_syntax (ia, &s);
1621       apply_dict (ia->dict, &s);
1622       intro_append_syntax (ia, &s);
1623     }
1624   else
1625     {
1626       return sheet_spec_gen_syntax (ia);
1627     }
1628
1629   return ds_cstr (&s);
1630 }