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