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