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