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