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