Import Assistant: Fix generation of /DELIMITERS subcommand
[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/str.h"
42
43 #include "builder-wrapper.h"
44 #include "helper.h"
45 #include "psppire-import-assistant.h"
46 #include "psppire-scanf.h"
47 #include "psppire-dialog.h"
48 #include "psppire-empty-list-store.h"
49 #include "psppire-encoding-selector.h"
50 #include "psppire-spreadsheet-model.h"
51 #include "psppire-text-file.h"
52 #include "psppire-delimited-text.h"
53 #include "psppire-data-sheet.h"
54 #include "psppire-data-store.h"
55 #include "psppire-dict.h"
56 #include "psppire-variable-sheet.h"
57
58 #include "ui/syntax-gen.h"
59
60 #include <gettext.h>
61 #define _(msgid) gettext (msgid)
62 #define N_(msgid) msgid
63
64 enum { MAX_LINE_LEN = 16384 }; /* Max length of an acceptable line. */
65
66
67 /* Sets IA's separators substructure to match the widgets. */
68 static void get_separators (PsppireImportAssistant *ia);
69 static void split_fields (PsppireImportAssistant *ia);
70
71 /* Chooses a name for each column on the separators page */
72 static void choose_column_names (PsppireImportAssistant *ia);
73
74
75
76 static void intro_page_create (PsppireImportAssistant *ia);
77 static void first_line_page_create (PsppireImportAssistant *ia);
78
79 static void separators_page_create (PsppireImportAssistant *ia);
80 static void formats_page_create (PsppireImportAssistant *ia);
81
82 static void push_watch_cursor (PsppireImportAssistant *ia);
83 static void pop_watch_cursor (PsppireImportAssistant *ia);
84
85
86
87 static void psppire_import_assistant_init            (PsppireImportAssistant      *act);
88 static void psppire_import_assistant_class_init      (PsppireImportAssistantClass *class);
89
90 G_DEFINE_TYPE (PsppireImportAssistant, psppire_import_assistant, GTK_TYPE_ASSISTANT);
91
92
93 /* Properties */
94 enum
95   {
96     PROP_0,
97   };
98
99 static void
100 psppire_import_assistant_set_property (GObject         *object,
101                                        guint            prop_id,
102                                        const GValue    *value,
103                                        GParamSpec      *pspec)
104 {
105   //   PsppireImportAssistant *act = PSPPIRE_IMPORT_ASSISTANT (object);
106
107   switch (prop_id)
108     {
109     default:
110       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
111       break;
112     };
113 }
114
115
116 static void
117 psppire_import_assistant_get_property (GObject    *object,
118                                        guint            prop_id,
119                                        GValue          *value,
120                                        GParamSpec      *pspec)
121 {
122   //  PsppireImportAssistant *assistant = PSPPIRE_IMPORT_ASSISTANT (object);
123
124   switch (prop_id)
125     {
126     default:
127       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
128       break;
129     };
130 }
131
132 static GObjectClass * parent_class = NULL;
133
134
135 static void
136 psppire_import_assistant_finalize (GObject *object)
137 {
138   PsppireImportAssistant *ia = PSPPIRE_IMPORT_ASSISTANT (object);
139
140
141   if (ia->spreadsheet)
142     spreadsheet_unref (ia->spreadsheet);
143
144   ds_destroy (&ia->quotes);
145
146   g_object_unref (ia->builder);
147
148   g_object_unref (ia->prop_renderer);
149   g_object_unref (ia->fixed_renderer);
150
151   if (G_OBJECT_CLASS (parent_class)->finalize)
152     G_OBJECT_CLASS (parent_class)->finalize (object);
153 }
154
155
156 static void
157 psppire_import_assistant_class_init (PsppireImportAssistantClass *class)
158 {
159   GObjectClass *object_class = G_OBJECT_CLASS (class);
160
161   parent_class = g_type_class_peek_parent (class);
162
163   object_class->set_property = psppire_import_assistant_set_property;
164   object_class->get_property = psppire_import_assistant_get_property;
165
166   object_class->finalize = psppire_import_assistant_finalize;
167 }
168
169
170 /* Causes the assistant to close, returning RESPONSE for
171    interpretation by text_data_import_assistant. */
172 static void
173 close_assistant (PsppireImportAssistant *ia, int response)
174 {
175   ia->response = response;
176   g_main_loop_quit (ia->main_loop);
177   gtk_widget_hide (GTK_WIDGET (ia));
178 }
179
180
181 /* Called when the Paste button on the last page of the assistant
182    is clicked. */
183 static void
184 on_paste (GtkButton *button, PsppireImportAssistant *ia)
185 {
186   close_assistant (ia, PSPPIRE_RESPONSE_PASTE);
187 }
188
189
190 /* Revises the contents of the fields tree view based on the
191    currently chosen set of separators. */
192 static void
193 revise_fields_preview (PsppireImportAssistant *ia)
194 {
195   push_watch_cursor (ia);
196
197   //  get_separators (ia);
198   //  split_fields (ia);
199   choose_column_names (ia);
200
201   pop_watch_cursor (ia);
202 }
203
204
205 #if SHEET_MERGE
206
207 /* Chooses the most common character among those in TARGETS,
208    based on the frequency data in HISTOGRAM, and stores it in
209    RESULT.  If there is a tie for the most common character among
210    those in TARGETS, the earliest character is chosen.  If none
211    of the TARGETS appear at all, then DEF is used as a
212    fallback. */
213 static void
214 find_commonest_chars (unsigned long int histogram[UCHAR_MAX + 1],
215                       const char *targets, const char *def,
216                       struct string *result)
217 {
218   unsigned char max = 0;
219   unsigned long int max_count = 0;
220
221   for (; *targets != '\0'; targets++)
222     {
223       unsigned char c = *targets;
224       unsigned long int count = histogram[c];
225       if (count > max_count)
226         {
227           max = c;
228           max_count = count;
229         }
230     }
231   if (max_count > 0)
232     {
233       ds_clear (result);
234       ds_put_byte (result, max);
235     }
236   else
237     ds_assign_cstr (result, def);
238 }
239
240 /* Picks the most likely separator and quote characters based on
241    IA's file data. */
242 static void
243 choose_likely_separators (PsppireImportAssistant *ia)
244 {
245   unsigned long int histogram[UCHAR_MAX + 1] = { 0 };
246
247   /* Construct a histogram of all the characters used in the
248      file. */
249   gboolean valid;
250   GtkTreeIter iter;
251   for (valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (ia->text_file), &iter);
252        valid;
253        valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (ia->text_file), &iter))
254     {
255       gchar *xxx = 0;
256       gtk_tree_model_get (GTK_TREE_MODEL (ia->text_file), &iter, 1, &xxx, -1);
257       struct substring line = ss_cstr (xxx);
258       size_t length = ss_length (line);
259       size_t i;
260       for (i = 0; i < length; i++)
261         histogram[(unsigned char) line.string[i]]++;
262       g_free (xxx);
263     }
264
265   find_commonest_chars (histogram, "\"'", "", &ia->quotes);
266   find_commonest_chars (histogram, ",;:/|!\t-", ",", &ia->separators);
267 }
268
269 #endif
270
271 static void set_separators (PsppireImportAssistant *ia);
272
273
274 static void
275 repopulate_delimiter_columns (PsppireImportAssistant *ia)
276 {
277   /* Remove all the columns */
278   while (gtk_tree_view_get_n_columns (GTK_TREE_VIEW (ia->fields_tree_view)) > 0)
279     {
280       GtkTreeViewColumn *tvc = gtk_tree_view_get_column (GTK_TREE_VIEW (ia->fields_tree_view), 0);
281       gtk_tree_view_remove_column (GTK_TREE_VIEW (ia->fields_tree_view), tvc);
282     }
283
284   gint n_fields = gtk_tree_model_get_n_columns (ia->delimiters_model);
285
286   /* ... and put them back again. */
287   gint f;
288   for (f = gtk_tree_view_get_n_columns (GTK_TREE_VIEW (ia->fields_tree_view));
289        f < n_fields; f++)
290     {
291       GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
292
293       const gchar *title = NULL;
294
295       if (f == 0)
296         title = _("line");
297       else
298         {
299           if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)))
300             {
301               title =
302                 psppire_delimited_text_get_header_title
303                 (PSPPIRE_DELIMITED_TEXT (ia->delimiters_model), f - 1);
304             }
305           if (title == NULL)
306             title = _("var");
307         }
308
309       GtkTreeViewColumn *column =
310         gtk_tree_view_column_new_with_attributes (title,
311                                                   renderer,
312                                                   "text", f,
313                                                   NULL);
314       g_object_set (column,
315                     "resizable", TRUE,
316                     "sizing", GTK_TREE_VIEW_COLUMN_AUTOSIZE,
317                     NULL);
318
319       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->fields_tree_view), column);
320     }
321 }
322
323 static void
324 reset_tree_view_model (PsppireImportAssistant *ia)
325 {
326   GtkTreeModel *tm = gtk_tree_view_get_model (GTK_TREE_VIEW (ia->fields_tree_view));
327   g_object_ref (tm);
328   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), NULL);
329
330
331   repopulate_delimiter_columns (ia);
332
333   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), tm);
334   //  gtk_tree_view_columns_autosize (GTK_TREE_VIEW (ia->fields_tree_view));
335
336   g_object_unref (tm);
337 }
338
339 /* Called just before the separators page becomes visible in the
340    assistant, and when the Reset button is clicked. */
341 static void
342 prepare_separators_page (PsppireImportAssistant *ia, GtkWidget *page)
343 {
344   gtk_tree_view_set_model (GTK_TREE_VIEW (ia->fields_tree_view), ia->delimiters_model);
345
346   g_signal_connect_swapped (ia->delimiters_model, "notify::delimiters",
347                         G_CALLBACK (reset_tree_view_model), ia);
348
349
350   repopulate_delimiter_columns (ia);
351
352   revise_fields_preview (ia);
353   //  choose_likely_separators (ia);
354   //  set_separators (ia);
355 }
356
357 struct separator
358 {
359   const char *name;           /* Name (for use with get_widget_assert). */
360   gunichar c;                 /* Separator character. */
361 };
362
363 /* All the separators in the dialog box. */
364 static const struct separator separators[] =
365   {
366     {"space", ' '},
367     {"tab", '\t'},
368     {"bang", '!'},
369     {"colon", ':'},
370     {"comma", ','},
371     {"hyphen", '-'},
372     {"pipe", '|'},
373     {"semicolon", ';'},
374     {"slash", '/'},
375   };
376 #define SEPARATOR_CNT (sizeof separators / sizeof *separators)
377
378
379 #if SHEET_MERGE
380
381 /* Sets the widgets to match IA's separators substructure. */
382 static void
383 set_separators (PsppireImportAssistant *ia)
384 {
385   unsigned int seps;
386   struct string custom;
387   bool any_custom;
388   bool any_quotes;
389   size_t i;
390
391   ds_init_empty (&custom);
392   seps = 0;
393   for (i = 0; i < ds_length (&ia->separators); i++)
394     {
395       unsigned char c = ds_at (&ia->separators, i);
396       int j;
397
398       for (j = 0; j < SEPARATOR_CNT; j++)
399         {
400           const struct separator *s = &separators[j];
401           if (s->c == c)
402             {
403               seps += 1u << j;
404               goto next;
405             }
406         }
407
408       ds_put_byte (&custom, c);
409     next:;
410     }
411
412   for (i = 0; i < SEPARATOR_CNT; i++)
413     {
414       const struct separator *s = &separators[i];
415       GtkWidget *button = get_widget_assert (ia->builder, s->name);
416       gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button),
417                                     (seps & (1u << i)) != 0);
418     }
419   any_custom = !ds_is_empty (&custom);
420   gtk_entry_set_text (GTK_ENTRY (ia->custom_entry), ds_cstr (&custom));
421   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ia->custom_cb),
422                                 any_custom);
423   gtk_widget_set_sensitive (ia->custom_entry, any_custom);
424   ds_destroy (&custom);
425
426   any_quotes = !ds_is_empty (&ia->quotes);
427
428   gtk_entry_set_text (ia->quote_entry,
429                       any_quotes ? ds_cstr (&ia->quotes) : "\"");
430   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ia->quote_cb),
431                                 any_quotes);
432   gtk_widget_set_sensitive (ia->quote_combo, any_quotes);
433 }
434
435 #endif
436
437 /* Resets IA's intro page to its initial state. */
438 static void
439 reset_intro_page (PsppireImportAssistant *ia)
440 {
441   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ia->all_cases_button),
442                                 TRUE);
443 }
444
445
446
447 /* Clears the set of user-modified variables from IA's formats
448    substructure.  This discards user modifications to variable
449    formats, thereby causing formats to revert to their
450    defaults.  */
451 static void
452 reset_formats_page (PsppireImportAssistant *ia, GtkWidget *page)
453 {
454   size_t i;
455
456   for (i = 0; i < ia->modified_var_cnt; i++)
457     var_destroy (ia->modified_vars[i]);
458   free (ia->modified_vars);
459   ia->modified_vars = NULL;
460   ia->modified_var_cnt = 0;
461 }
462
463 static void prepare_formats_page (PsppireImportAssistant *ia);
464
465 /* Called when the Reset button is clicked. */
466 static void
467 on_reset (GtkButton *button, PsppireImportAssistant *ia)
468 {
469   gint pn = gtk_assistant_get_current_page (GTK_ASSISTANT (ia));
470   {
471     GtkWidget *page =  gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), pn);
472
473     page_func *on_reset = g_object_get_data (G_OBJECT (page), "on-reset");
474
475     if (on_reset)
476       on_reset (ia, page);
477   }
478 }
479
480
481 static gint
482 next_page_func (gint old_page, gpointer data)
483 {
484   return old_page + 1;
485 }
486
487
488 /* Called just before PAGE is displayed as the current page of
489    IMPORT_ASSISTANT, this updates IA content according to the new
490    page. */
491 static void
492 on_prepare (GtkAssistant *assistant, GtkWidget *page, PsppireImportAssistant *ia)
493 {
494   gtk_widget_show (ia->reset_button);
495   gtk_widget_hide (ia->paste_button);
496
497   gint pn = gtk_assistant_get_current_page (assistant);
498   gint previous_page_index = ia->current_page;
499
500   if (previous_page_index >= 0)
501     {
502       GtkWidget *closing_page = gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), previous_page_index);
503
504       if (pn > previous_page_index)
505         {
506           page_func *on_forward = g_object_get_data (G_OBJECT (closing_page), "on-forward");
507
508           if (on_forward)
509             on_forward (ia, closing_page);
510         }
511       else
512         {
513           page_func *on_back = g_object_get_data (G_OBJECT (closing_page), "on-back");
514
515           if (on_back)
516             on_back (ia, closing_page);
517         }
518     }
519
520   {
521     GtkWidget *new_page = gtk_assistant_get_nth_page (GTK_ASSISTANT (ia), pn);
522
523     page_func *on_entering = g_object_get_data (G_OBJECT (new_page), "on-entering");
524
525     if (on_entering)
526       on_entering (ia, new_page);
527   }
528
529   ia->current_page = pn;
530 }
531
532 /* Called when the Cancel button in the assistant is clicked. */
533 static void
534 on_cancel (GtkAssistant *assistant, PsppireImportAssistant *ia)
535 {
536   close_assistant (ia, GTK_RESPONSE_CANCEL);
537 }
538
539 /* Called when the Apply button on the last page of the assistant
540    is clicked. */
541 static void
542 on_close (GtkAssistant *assistant, PsppireImportAssistant *ia)
543 {
544   close_assistant (ia, GTK_RESPONSE_APPLY);
545 }
546
547
548 /* Increments the "watch cursor" level, setting the cursor for
549    the assistant window to a watch face to indicate to the user
550    that the ongoing operation may take some time. */
551 static void
552 push_watch_cursor (PsppireImportAssistant *ia)
553 {
554   if (++ia->watch_cursor == 1)
555     {
556       GtkWidget *widget = GTK_WIDGET (ia);
557       GdkDisplay *display = gtk_widget_get_display (widget);
558       GdkCursor *cursor = gdk_cursor_new_for_display (display, GDK_WATCH);
559       gdk_window_set_cursor (gtk_widget_get_window (widget), cursor);
560       g_object_unref (cursor);
561       gdk_display_flush (display);
562     }
563 }
564
565 /* Decrements the "watch cursor" level.  If the level reaches
566    zero, the cursor is reset to its default shape. */
567 static void
568 pop_watch_cursor (PsppireImportAssistant *ia)
569 {
570   if (--ia->watch_cursor == 0)
571     {
572       GtkWidget *widget = GTK_WIDGET (ia);
573       gdk_window_set_cursor (gtk_widget_get_window (widget), NULL);
574     }
575 }
576
577 #if SHEET_MERGE
578 static gint
579 get_string_width (GtkWidget *treeview, GtkCellRenderer *renderer,
580                   const char *string)
581 {
582   gint width;
583   g_object_set (G_OBJECT (renderer), "text", string, (void *) NULL);
584   gtk_cell_renderer_get_preferred_width (renderer, treeview,
585                                          NULL, &width);
586   return width;
587 }
588
589 static gint
590 get_monospace_width (GtkWidget *treeview, GtkCellRenderer *renderer,
591                      size_t char_cnt)
592 {
593   struct string s;
594   gint width;
595
596   ds_init_empty (&s);
597   ds_put_byte_multiple (&s, '0', char_cnt);
598   ds_put_byte (&s, ' ');
599   width = get_string_width (treeview, renderer, ds_cstr (&s));
600   ds_destroy (&s);
601
602   return width;
603 }
604
605 static void
606 set_model_on_treeview (PsppireImportAssistant *ia, GtkWidget *tree_view, size_t first_line)
607 {
608   GtkTreeModel *model = GTK_TREE_MODEL (psppire_empty_list_store_new (ia->line_cnt - first_line));
609
610   g_object_set_data (G_OBJECT (model), "lines", &ia->lines + first_line);
611   g_object_set_data (G_OBJECT (model), "first-line", GINT_TO_POINTER (first_line));
612
613   pspp_sheet_view_set_model (PSPP_SHEET_VIEW (tree_view), model);
614
615   g_object_unref (model);
616 }
617
618 static GtkWidget *
619 make_tree_view (const PsppireImportAssistant *ia)
620 {
621   GtkWidget *tree_view = pspp_sheet_view_new ();
622   pspp_sheet_view_set_grid_lines (PSPP_SHEET_VIEW (tree_view), PSPP_SHEET_VIEW_GRID_LINES_BOTH);
623
624   add_line_number_column (ia, tree_view);
625
626   return tree_view;
627 }
628 #endif
629
630 static GtkWidget *
631 add_page_to_assistant (PsppireImportAssistant *ia,
632                        GtkWidget *page, GtkAssistantPageType type, const gchar *);
633
634
635 static void
636 on_sheet_combo_changed (GtkComboBox *cb, PsppireImportAssistant *ia)
637 {
638   GtkTreeIter iter;
639   gchar *range = NULL;
640   GtkTreeModel *model = gtk_combo_box_get_model (cb);
641   GtkBuilder *builder = ia->builder;
642   GtkWidget *range_entry = get_widget_assert (builder, "cell-range-entry");
643
644   gtk_combo_box_get_active_iter (cb, &iter);
645   gtk_tree_model_get (model, &iter, PSPPIRE_SPREADSHEET_MODEL_COL_RANGE, &range, -1);
646   gtk_entry_set_text (GTK_ENTRY (range_entry), range ?  range : "");
647   g_free (range);
648 }
649
650 /* Prepares IA's sheet_spec page. */
651 static void
652 prepare_sheet_spec_page (PsppireImportAssistant *ia)
653 {
654   GtkBuilder *builder = ia->builder;
655   GtkWidget *sheet_entry = get_widget_assert (builder, "sheet-entry");
656   GtkWidget *readnames_checkbox = get_widget_assert (builder, "readnames-checkbox");
657
658   gtk_combo_box_set_model (GTK_COMBO_BOX (sheet_entry),
659                            psppire_spreadsheet_model_new (ia->spreadsheet));
660
661   gtk_combo_box_set_active (GTK_COMBO_BOX (sheet_entry), 0);
662
663   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (readnames_checkbox), FALSE);
664 }
665
666
667 /* Initializes IA's sheet_spec substructure. */
668 static void
669 sheet_spec_page_create (PsppireImportAssistant *ia)
670 {
671   GtkBuilder *builder = ia->builder;
672   GtkWidget *page = get_widget_assert (builder, "Spreadsheet-Importer");
673
674   GtkWidget *combo_box = get_widget_assert (builder, "sheet-entry");
675   GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
676   gtk_cell_layout_clear (GTK_CELL_LAYOUT (combo_box));
677   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), renderer, TRUE);
678   gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), renderer,
679                                   "text", 0,
680                                   NULL);
681
682   g_signal_connect (combo_box, "changed", G_CALLBACK (on_sheet_combo_changed), ia);
683
684   add_page_to_assistant (ia, page,
685                          GTK_ASSISTANT_PAGE_CONTENT, _("Importing Spreadsheet Data"));
686
687   g_object_set_data (G_OBJECT (page), "on-entering", prepare_sheet_spec_page);
688 }
689
690 static void
691 on_chosen (PsppireImportAssistant *ia, GtkWidget *page)
692 {
693   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
694   gchar *f = gtk_file_chooser_get_filename (fc);
695   int i;
696
697   for(i = gtk_assistant_get_n_pages (GTK_ASSISTANT (ia)); i > 0; --i)
698     gtk_assistant_remove_page (GTK_ASSISTANT (ia), i);
699
700   gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), GTK_WIDGET (fc), FALSE);
701
702   if (f && !g_file_test (f, G_FILE_TEST_IS_DIR))
703     {
704       gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), GTK_WIDGET (fc), TRUE);
705
706       if (ia->spreadsheet)
707         spreadsheet_unref (ia->spreadsheet);
708
709       ia->spreadsheet = gnumeric_probe (f, FALSE);
710
711       if (!ia->spreadsheet)
712         ia->spreadsheet = ods_probe (f, FALSE);
713
714       if (!ia->spreadsheet)
715         {
716           intro_page_create (ia);
717           first_line_page_create (ia);
718           separators_page_create (ia);
719         }
720       else
721         {
722           sheet_spec_page_create (ia);
723         }
724
725       formats_page_create (ia);
726     }
727
728   g_free (f);
729 }
730
731 /* This has to be done on a map signal callback,
732    because GtkFileChooserWidget resets everything when it is mapped. */
733 static void
734 on_map (PsppireImportAssistant *ia, GtkWidget *page)
735 {
736 #if TEXT_FILE
737   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
738
739   if (ia->file_name)
740     gtk_file_chooser_set_filename (fc, ia->file_name);
741 #endif
742
743   on_chosen (ia, page);
744 }
745
746
747
748 static void
749 chooser_page_enter (PsppireImportAssistant *ia, GtkWidget *page)
750 {
751 }
752
753 static void
754 chooser_page_leave (PsppireImportAssistant *ia, GtkWidget *page)
755 {
756   g_print ("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__);
757   g_free (ia->file_name);
758   ia->file_name = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (page));
759   gchar *encoding = psppire_encoding_selector_get_encoding (ia->encoding_selector);
760
761   if (!ia->spreadsheet)
762     {
763       ia->text_file = psppire_text_file_new (ia->file_name, encoding);
764       gtk_tree_view_set_model (GTK_TREE_VIEW (ia->first_line_tree_view),
765                                GTK_TREE_MODEL (ia->text_file));
766     }
767
768
769   g_free (encoding);
770 }
771
772 static void
773 chooser_page_reset (PsppireImportAssistant *ia, GtkWidget *page)
774 {
775   GtkFileChooser *fc = GTK_FILE_CHOOSER (page);
776
777   gtk_file_chooser_set_filter (fc, ia->default_filter);
778   gtk_file_chooser_unselect_all (fc);
779
780   on_chosen (ia, page);
781 }
782
783
784
785 static void
786 chooser_page_create (PsppireImportAssistant *ia)
787 {
788   GtkFileFilter *filter = NULL;
789
790   GtkWidget *chooser = gtk_file_chooser_widget_new (GTK_FILE_CHOOSER_ACTION_OPEN);
791
792   g_object_set_data (G_OBJECT (chooser), "on-forward", chooser_page_leave);
793   g_object_set_data (G_OBJECT (chooser), "on-reset",   chooser_page_reset);
794   g_object_set_data (G_OBJECT (chooser), "on-entering",chooser_page_enter);
795
796   g_object_set (chooser, "local-only", FALSE, NULL);
797
798
799   ia->default_filter = gtk_file_filter_new ();
800   gtk_file_filter_set_name (ia->default_filter, _("All Files"));
801   gtk_file_filter_add_pattern (ia->default_filter, "*");
802   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), ia->default_filter);
803
804   filter = gtk_file_filter_new ();
805   gtk_file_filter_set_name (filter, _("Text Files"));
806   gtk_file_filter_add_mime_type (filter, "text/*");
807   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
808
809   filter = gtk_file_filter_new ();
810   gtk_file_filter_set_name (filter, _("Text (*.txt) Files"));
811   gtk_file_filter_add_pattern (filter, "*.txt");
812   gtk_file_filter_add_pattern (filter, "*.TXT");
813   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
814
815   filter = gtk_file_filter_new ();
816   gtk_file_filter_set_name (filter, _("Plain Text (ASCII) Files"));
817   gtk_file_filter_add_mime_type (filter, "text/plain");
818   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
819
820   filter = gtk_file_filter_new ();
821   gtk_file_filter_set_name (filter, _("Comma Separated Value Files"));
822   gtk_file_filter_add_mime_type (filter, "text/csv");
823   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
824
825   /* I've never encountered one of these, but it's listed here:
826      http://www.iana.org/assignments/media-types/text/tab-separated-values  */
827   filter = gtk_file_filter_new ();
828   gtk_file_filter_set_name (filter, _("Tab Separated Value Files"));
829   gtk_file_filter_add_mime_type (filter, "text/tab-separated-values");
830   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
831
832   filter = gtk_file_filter_new ();
833   gtk_file_filter_set_name (filter, _("Gnumeric Spreadsheet Files"));
834   gtk_file_filter_add_mime_type (filter, "application/x-gnumeric");
835   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
836
837   filter = gtk_file_filter_new ();
838   gtk_file_filter_set_name (filter, _("OpenDocument Spreadsheet Files"));
839   gtk_file_filter_add_mime_type (filter, "application/vnd.oasis.opendocument.spreadsheet");
840   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
841
842   filter = gtk_file_filter_new ();
843   gtk_file_filter_set_name (filter, _("All Spreadsheet Files"));
844   gtk_file_filter_add_mime_type (filter, "application/x-gnumeric");
845   gtk_file_filter_add_mime_type (filter, "application/vnd.oasis.opendocument.spreadsheet");
846   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
847
848   ia->encoding_selector = psppire_encoding_selector_new ("Auto", TRUE);
849   gtk_file_chooser_set_extra_widget (GTK_FILE_CHOOSER (chooser), ia->encoding_selector);
850
851   add_page_to_assistant (ia, chooser,
852                          GTK_ASSISTANT_PAGE_INTRO, _("Select File to Import"));
853
854   g_signal_connect_swapped (chooser, "selection-changed", G_CALLBACK (on_chosen), ia);
855   g_signal_connect_swapped (chooser, "map", G_CALLBACK (on_map), ia);
856 }
857
858
859
860 static void
861 psppire_import_assistant_init (PsppireImportAssistant *ia)
862 {
863   ia->builder = builder_new ("text-data-import.ui");
864
865   ia->current_page = -1 ;
866   /* ia->column_cnt = 0; */
867   /* ia->columns = NULL; */
868
869   ia->file_name = NULL;
870
871   ia->spreadsheet = NULL;
872   ia->watch_cursor = 0;
873
874   ia->prop_renderer = gtk_cell_renderer_text_new ();
875   g_object_ref_sink (ia->prop_renderer);
876   ia->fixed_renderer = gtk_cell_renderer_text_new ();
877   g_object_ref_sink (ia->fixed_renderer);
878   g_object_set (G_OBJECT (ia->fixed_renderer),
879                 "family", "Monospace",
880                 (void *) NULL);
881
882   g_signal_connect (ia, "prepare", G_CALLBACK (on_prepare), ia);
883   g_signal_connect (ia, "cancel", G_CALLBACK (on_cancel), ia);
884   g_signal_connect (ia, "close", G_CALLBACK (on_close), ia);
885
886   ia->paste_button = gtk_button_new_with_label (_("Paste"));
887   ia->reset_button = gtk_button_new_with_label (_("Reset"));
888
889   gtk_assistant_add_action_widget (GTK_ASSISTANT(ia), ia->paste_button);
890
891   g_signal_connect (ia->paste_button, "clicked", G_CALLBACK (on_paste), ia);
892   g_signal_connect (ia->reset_button, "clicked", G_CALLBACK (on_reset), ia);
893
894   gtk_assistant_add_action_widget (GTK_ASSISTANT(ia), ia->reset_button);
895
896   gtk_window_set_title (GTK_WINDOW (ia),
897                         _("Importing Delimited Text Data"));
898
899   gtk_window_set_icon_name (GTK_WINDOW (ia), "pspp");
900
901   chooser_page_create (ia);
902
903   gtk_assistant_set_forward_page_func (GTK_ASSISTANT (ia), next_page_func, NULL, NULL);
904
905   gtk_window_maximize (GTK_WINDOW (ia));
906 }
907
908
909 /* Appends a page of the given TYPE, with PAGE as its content, to
910    the GtkAssistant encapsulated by IA.  Returns the GtkWidget
911    that represents the page. */
912 static GtkWidget *
913 add_page_to_assistant (PsppireImportAssistant *ia,
914                        GtkWidget *page, GtkAssistantPageType type, const gchar *title)
915 {
916   GtkWidget *content = page;
917
918   gtk_assistant_append_page (GTK_ASSISTANT (ia), content);
919   gtk_assistant_set_page_type (GTK_ASSISTANT(ia), content, type);
920   gtk_assistant_set_page_title (GTK_ASSISTANT(ia), content, title);
921   gtk_assistant_set_page_complete (GTK_ASSISTANT(ia), content, TRUE);
922
923   return content;
924 }
925
926
927 /* Called when one of the radio buttons is clicked. */
928 static void
929 on_intro_amount_changed (PsppireImportAssistant *p)
930 {
931   gtk_widget_set_sensitive (p->n_cases_spin,
932                             gtk_toggle_button_get_active (
933                                                           GTK_TOGGLE_BUTTON (p->n_cases_button)));
934
935   gtk_widget_set_sensitive (p->percent_spin,
936                             gtk_toggle_button_get_active (
937                                                           GTK_TOGGLE_BUTTON (p->percent_button)));
938 }
939
940
941 #if SHEET_MERGE
942
943
944 /* Sets IA's first_line substructure to match the widgets. */
945 static void
946 set_first_line_options (PsppireImportAssistant *ia)
947 {
948   GtkTreeIter iter;
949   GtkTreeModel *model;
950
951   PsppSheetSelection *selection = pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view));
952   if (pspp_sheet_selection_get_selected (selection, &model, &iter))
953     {
954       GtkTreePath *path = gtk_tree_model_get_path (model, &iter);
955       int row = gtk_tree_path_get_indices (path)[0];
956       gtk_tree_path_free (path);
957
958       ia->skip_lines = row;
959       ia->variable_names =
960         (ia->skip_lines > 0
961          && gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)));
962     }
963
964   gtk_widget_set_sensitive (ia->variable_names_cb, ia->skip_lines > 0);
965 }
966
967
968
969 static void
970 reset_first_line_page (PsppireImportAssistant *ia)
971 {
972   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb), FALSE);
973   PsppSheetSelection *selection = pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view));
974   pspp_sheet_selection_unselect_all (selection);
975   gtk_widget_set_sensitive (ia->variable_names_cb, FALSE);
976 }
977
978 #endif
979
980 static void
981 on_treeview_selection_change (PsppireImportAssistant *ia)
982 {
983   GtkTreeSelection *selection =
984     gtk_tree_view_get_selection (GTK_TREE_VIEW (ia->first_line_tree_view));
985   GtkTreeModel *model = NULL;
986   GtkTreeIter iter;
987   if (gtk_tree_selection_get_selected (selection, &model, &iter))
988     {
989       int n;
990       GtkTreePath *path = gtk_tree_model_get_path (model, &iter);
991       gint *index = gtk_tree_path_get_indices (path);
992
993       n = *index;
994
995       gtk_tree_path_free (path);
996
997       gtk_widget_set_sensitive (ia->variable_names_cb, n > 0);
998
999       ia->delimiters_model
1000         = psppire_delimited_text_new (GTK_TREE_MODEL (ia->text_file));
1001       g_object_set (ia->delimiters_model, "first-line", n, NULL);
1002
1003       //      ia->skip_lines = n;
1004     }
1005 }
1006
1007
1008 /* Initializes IA's first_line substructure. */
1009 static void
1010 first_line_page_create (PsppireImportAssistant *ia)
1011 {
1012   g_print ("%s:%d %s\n", __FILE__, __LINE__, __FUNCTION__);
1013   GtkWidget *w =  get_widget_assert (ia->builder, "FirstLine");
1014
1015   g_object_set_data (G_OBJECT (w), "on-entering", on_treeview_selection_change);
1016
1017   add_page_to_assistant (ia, w,
1018                          GTK_ASSISTANT_PAGE_CONTENT, _("Select the First Line"));
1019
1020   GtkWidget *scrolled_window = get_widget_assert (ia->builder, "first-line-scroller");
1021
1022   if (ia->first_line_tree_view == NULL)
1023     {
1024       ia->first_line_tree_view = gtk_tree_view_new ();
1025
1026       gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (ia->first_line_tree_view), TRUE);
1027
1028       GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
1029       GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes (_("Line"), renderer,
1030                                                                             "text", 0,
1031                                                                             NULL);
1032       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->first_line_tree_view), column);
1033
1034       renderer = gtk_cell_renderer_text_new ();
1035       column = gtk_tree_view_column_new_with_attributes (_("Text"), renderer, "text", 1, NULL);
1036       gtk_tree_view_append_column (GTK_TREE_VIEW (ia->first_line_tree_view), column);
1037
1038       gtk_container_add (GTK_CONTAINER (scrolled_window), ia->first_line_tree_view);
1039
1040       g_signal_connect_swapped (ia->first_line_tree_view, "cursor-changed",
1041                         G_CALLBACK (on_treeview_selection_change), ia);
1042     }
1043   gtk_widget_show_all (scrolled_window);
1044
1045   ia->variable_names_cb = get_widget_assert (ia->builder, "variable-names");
1046
1047 #if SHEET_MERGE
1048   pspp_sheet_selection_set_mode (
1049                                  pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view)),
1050                                  PSPP_SHEET_SELECTION_BROWSE);
1051   pspp_sheet_view_set_rubber_banding (PSPP_SHEET_VIEW (ia->tree_view), TRUE);
1052
1053
1054   g_signal_connect_swapped (pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (ia->tree_view)),
1055                             "changed", G_CALLBACK (set_first_line_options), ia);
1056
1057   g_signal_connect_swapped (ia->variable_names_cb, "toggled",
1058                             G_CALLBACK (set_first_line_options), ia);
1059
1060   g_object_set_data (G_OBJECT (w), "on-reset", reset_first_line_page);
1061 #endif
1062 }
1063
1064
1065
1066
1067 static void
1068 intro_on_enter (PsppireImportAssistant *ia)
1069 {
1070   GtkBuilder *builder = ia->builder;
1071   GtkWidget *table  = get_widget_assert (builder, "button-table");
1072
1073   struct string s;
1074
1075   ds_init_empty (&s);
1076   ds_put_cstr (&s, _("This assistant will guide you through the process of "
1077                      "importing data into PSPP from a text file with one line "
1078                      "per case,  in which fields are separated by tabs, "
1079                      "commas, or other delimiters.\n\n"));
1080
1081   if (ia->text_file)
1082     {
1083       if (ia->text_file->total_is_exact)
1084         {
1085           ds_put_format (
1086                          &s, ngettext ("The selected file contains %'lu line of text.  ",
1087                                        "The selected file contains %'lu lines of text.  ",
1088                                        ia->text_file->total_lines),
1089                          ia->text_file->total_lines);
1090         }
1091       else if (ia->text_file->total_lines > 0)
1092         {
1093           ds_put_format (
1094                          &s, ngettext (
1095                                        "The selected file contains approximately %'lu line of text.  ",
1096                                        "The selected file contains approximately %'lu lines of text.  ",
1097                                        ia->text_file->total_lines),
1098                          ia->text_file->total_lines);
1099           ds_put_format (
1100                          &s, ngettext (
1101                                        "Only the first %zu line of the file will be shown for "
1102                                        "preview purposes in the following screens.  ",
1103                                        "Only the first %zu lines of the file will be shown for "
1104                                        "preview purposes in the following screens.  ",
1105                                        ia->text_file->line_cnt),
1106                          ia->text_file->line_cnt);
1107         }
1108     }
1109
1110   ds_put_cstr (&s, _("You may choose below how much of the file should "
1111                      "actually be imported."));
1112
1113   gtk_label_set_text (GTK_LABEL (get_widget_assert (builder, "intro-label")),
1114                       ds_cstr (&s));
1115   ds_destroy (&s);
1116
1117   GtkWidget *w  =  gtk_grid_get_child_at (GTK_GRID (table), 1, 1);
1118   int old_value = w ? gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (ia->n_cases_spin)) : 1;
1119   if (w)
1120     gtk_container_remove (GTK_CONTAINER (table), w);
1121
1122   w  =  gtk_grid_get_child_at (GTK_GRID (table), 1, 2);
1123   if (w)
1124     gtk_container_remove (GTK_CONTAINER (table), w);
1125
1126
1127   GtkWidget *hbox_n_cases = psppire_scanf_new (_("Only the first %4d cases"), &ia->n_cases_spin);
1128
1129   GtkAdjustment *adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (ia->n_cases_spin));
1130   gtk_adjustment_set_lower (adj, 1.0);
1131
1132   if (ia->text_file)
1133     {
1134       if (psppire_text_file_get_total_exact (ia->text_file))
1135         {
1136           gulong total_lines = psppire_text_file_get_n_lines (ia->text_file);
1137           gtk_adjustment_set_upper (adj, total_lines);
1138           gtk_adjustment_set_value (adj, old_value);
1139         }
1140       else
1141         gtk_adjustment_set_upper (adj, DBL_MAX);
1142     }
1143   gtk_grid_attach (GTK_GRID (table), hbox_n_cases,
1144                    1, 1,
1145                    1, 1);
1146
1147
1148   GtkWidget *hbox_percent = psppire_scanf_new (_("Only the first %3d %% of file (approximately)"),
1149                                                &ia->percent_spin);
1150
1151   gtk_grid_attach (GTK_GRID (table), hbox_percent,
1152                    1, 2,
1153                    1, 1);
1154
1155   gtk_widget_show_all (table);
1156
1157   on_intro_amount_changed (ia);
1158 }
1159
1160 /* Initializes IA's intro substructure. */
1161 static void
1162 intro_page_create (PsppireImportAssistant *ia)
1163 {
1164   GtkBuilder *builder = ia->builder;
1165
1166   GtkWidget *w =  get_widget_assert (builder, "Intro");
1167
1168   ia->percent_spin = gtk_spin_button_new_with_range (0, 100, 10);
1169
1170
1171   add_page_to_assistant (ia, w,  GTK_ASSISTANT_PAGE_CONTENT, _("Select the Lines to Import"));
1172
1173   ia->all_cases_button = get_widget_assert (builder, "import-all-cases");
1174
1175   ia->n_cases_button = get_widget_assert (builder, "import-n-cases");
1176
1177   ia->percent_button = get_widget_assert (builder, "import-percent");
1178
1179   g_signal_connect_swapped (ia->all_cases_button, "toggled",
1180                             G_CALLBACK (on_intro_amount_changed), ia);
1181   g_signal_connect_swapped (ia->n_cases_button, "toggled",
1182                             G_CALLBACK (on_intro_amount_changed), ia);
1183   g_signal_connect_swapped (ia->percent_button, "toggled",
1184                             G_CALLBACK (on_intro_amount_changed), ia);
1185
1186
1187   g_object_set_data (G_OBJECT (w), "on-entering", intro_on_enter);
1188   g_object_set_data (G_OBJECT (w), "on-reset", reset_intro_page);
1189 }
1190
1191
1192 GtkWidget *
1193 psppire_import_assistant_new (GtkWindow *toplevel)
1194 {
1195   return GTK_WIDGET (g_object_new (PSPPIRE_TYPE_IMPORT_ASSISTANT,
1196                                    /* Some window managers (notably ratpoison)
1197                                       ignore the maximise command when a window is
1198                                       transient.  This causes problems for this
1199                                       window. */
1200                                    /* "transient-for", toplevel, */
1201                                    NULL));
1202 }
1203
1204
1205
1206 \f
1207
1208 struct column
1209 {
1210   /* Variable name for this column.  This is the variable name
1211      used on the separators page; it can be overridden by the
1212      user on the formats page. */
1213   char *name;
1214
1215   /* Maximum length of any row in this column. */
1216   size_t width;
1217
1218   /* Contents of this column: contents[row] is the contents for
1219      the given row.
1220
1221      A null substring indicates a missing column for that row
1222      (because the line contains an insufficient number of
1223      separators).
1224
1225      contents[] elements may be substrings of the lines[]
1226      strings that represent the whole lines of the file, to
1227      save memory.  Other elements are dynamically allocated
1228      with ss_alloc_substring. */
1229   struct substring *contents;
1230 };
1231
1232 #if SHEET_MERGE
1233
1234 /* Called to render one of the cells in the fields preview tree
1235    view. */
1236 static void
1237 render_input_cell (PsppSheetViewColumn *tree_column, GtkCellRenderer *cell,
1238                    GtkTreeModel *model, GtkTreeIter *iter,
1239                    gpointer ia_)
1240 {
1241   PsppireImportAssistant *ia = ia_;
1242   struct substring field;
1243   size_t row;
1244   gint column;
1245
1246   column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1247                                                "column-number"));
1248   row = empty_list_store_iter_to_row (iter) + ia->skip_lines;
1249   field = ia->columns[column].contents[row];
1250   if (field.string != NULL)
1251     {
1252       GValue text = {0, };
1253       g_value_init (&text, G_TYPE_STRING);
1254       g_value_take_string (&text, ss_xstrdup (field));
1255       g_object_set_property (G_OBJECT (cell), "text", &text);
1256       g_value_unset (&text);
1257       g_object_set (cell, "background-set", FALSE, (void *) NULL);
1258     }
1259   else
1260     g_object_set (cell,
1261                   "text", "",
1262                   "background", "red",
1263                   "background-set", TRUE,
1264                   (void *) NULL);
1265 }
1266
1267 /* Parses the contents of the field at (ROW,COLUMN) according to
1268    its variable format.  If OUTPUTP is non-null, then *OUTPUTP
1269    receives the formatted output for that field (which must be
1270    freed with free).  If TOOLTIPP is non-null, then *TOOLTIPP
1271    receives a message suitable for use in a tooltip, if one is
1272    needed, or a null pointer otherwise.  Returns TRUE if a
1273    tooltip message is needed, otherwise FALSE. */
1274 static bool
1275 parse_field (PsppireImportAssistant *ia,
1276              size_t row, size_t column,
1277              char **outputp, char **tooltipp)
1278 {
1279   const struct fmt_spec *in;
1280   struct fmt_spec out;
1281   char *tooltip;
1282   bool ok;
1283
1284   struct substring field = ia->columns[column].contents[row];
1285   const struct variable *var = dict_get_var (ia->dict, column);
1286   union value val;
1287
1288   value_init (&val, var_get_width (var));
1289   in = var_get_print_format (var);
1290   out = fmt_for_output_from_input (in);
1291   tooltip = NULL;
1292   if (field.string != NULL)
1293     {
1294       char *error = data_in (field, "UTF-8", in->type, &val, var_get_width (var),
1295                              dict_get_encoding (ia->dict));
1296       if (error != NULL)
1297         {
1298           tooltip = xasprintf (_("Cannot parse field content `%.*s' as "
1299                                  "format %s: %s"),
1300                                (int) field.length, field.string,
1301                                fmt_name (in->type), error);
1302           free (error);
1303         }
1304     }
1305   else
1306     {
1307       tooltip = xstrdup (_("This input line has too few separators "
1308                            "to fill in this field."));
1309       value_set_missing (&val, var_get_width (var));
1310     }
1311   if (outputp != NULL)
1312     {
1313       *outputp = data_out (&val, dict_get_encoding (ia->dict),  &out);
1314     }
1315   value_destroy (&val, var_get_width (var));
1316
1317   ok = tooltip == NULL;
1318   if (tooltipp != NULL)
1319     *tooltipp = tooltip;
1320   else
1321     free (tooltip);
1322   return ok;
1323 }
1324
1325 /* Called to render one of the cells in the data preview tree
1326    view. */
1327 static void
1328 render_output_cell (PsppSheetViewColumn *tree_column,
1329                     GtkCellRenderer *cell,
1330                     GtkTreeModel *model,
1331                     GtkTreeIter *iter,
1332                     gpointer ia_)
1333 {
1334   PsppireImportAssistant *ia = ia_;
1335   char *output;
1336   GValue gvalue = { 0, };
1337   bool ok = parse_field (ia,
1338                          (empty_list_store_iter_to_row (iter)
1339                           + ia->skip_lines),
1340                          GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1341                                                              "column-number")),
1342                          &output, NULL);
1343
1344   g_value_init (&gvalue, G_TYPE_STRING);
1345   g_value_take_string (&gvalue, output);
1346   g_object_set_property (G_OBJECT (cell), "text", &gvalue);
1347   g_value_unset (&gvalue);
1348
1349   if (ok)
1350     g_object_set (cell, "background-set", FALSE, (void *) NULL);
1351   else
1352     g_object_set (cell,
1353                   "background", "red",
1354                   "background-set", TRUE,
1355                   (void *) NULL);
1356 }
1357
1358
1359 /* Utility functions used by multiple pages of the assistant. */
1360
1361 static gboolean
1362 get_tooltip_location (GtkWidget *widget, gint wx, gint wy,
1363                       const PsppireImportAssistant *ia,
1364                       size_t *row, size_t *column)
1365 {
1366   PsppSheetView *tree_view = PSPP_SHEET_VIEW (widget);
1367   gint bx, by;
1368   GtkTreePath *path;
1369   GtkTreeIter iter;
1370   PsppSheetViewColumn *tree_column;
1371   GtkTreeModel *tree_model;
1372   bool ok;
1373
1374   pspp_sheet_view_convert_widget_to_bin_window_coords (tree_view,
1375                                                        wx, wy, &bx, &by);
1376   if (!pspp_sheet_view_get_path_at_pos (tree_view, bx, by,
1377                                         &path, &tree_column, NULL, NULL))
1378     return FALSE;
1379
1380   *column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (tree_column),
1381                                                 "column-number"));
1382
1383   tree_model = pspp_sheet_view_get_model (tree_view);
1384   ok = gtk_tree_model_get_iter (tree_model, &iter, path);
1385   gtk_tree_path_free (path);
1386   if (!ok)
1387     return FALSE;
1388
1389   *row = empty_list_store_iter_to_row (&iter) + ia->skip_lines;
1390   return TRUE;
1391 }
1392
1393
1394
1395 \f
1396
1397
1398 /* Called to render a tooltip on one of the cells in the fields
1399    preview tree view. */
1400 static gboolean
1401 on_query_input_tooltip (GtkWidget *widget, gint wx, gint wy,
1402                         gboolean keyboard_mode UNUSED,
1403                         GtkTooltip *tooltip, PsppireImportAssistant *ia)
1404 {
1405   size_t row, column;
1406
1407   if (!get_tooltip_location (widget, wx, wy, ia, &row, &column))
1408     return FALSE;
1409
1410   if (ia->columns[column].contents[row].string != NULL)
1411     return FALSE;
1412
1413   gtk_tooltip_set_text (tooltip,
1414                         _("This input line has too few separators "
1415                           "to fill in this field."));
1416   return TRUE;
1417 }
1418
1419
1420 /* Called to render a tooltip for one of the cells in the data
1421    preview tree view. */
1422 static gboolean
1423 on_query_output_tooltip (GtkWidget *widget, gint wx, gint wy,
1424                          gboolean keyboard_mode UNUSED,
1425                          GtkTooltip *tooltip, PsppireImportAssistant *ia)
1426 {
1427   size_t row, column;
1428   char *text;
1429
1430   if (!gtk_widget_get_mapped (widget))
1431     return FALSE;
1432
1433   if (!get_tooltip_location (widget, wx, wy, ia, &row, &column))
1434     return FALSE;
1435
1436   if (parse_field (ia, row, column, NULL, &text))
1437     return FALSE;
1438
1439   gtk_tooltip_set_text (tooltip, text);
1440   free (text);
1441   return TRUE;
1442 }
1443 #endif
1444 \f
1445
1446
1447 static void
1448 set_quote_list (GtkComboBox *cb)
1449 {
1450   GtkListStore *list =  gtk_list_store_new (1, G_TYPE_STRING);
1451   GtkTreeIter iter;
1452   gint i;
1453   const gchar *seperator[3] = {"'\"", "\'", "\""};
1454
1455   for (i = 0; i < 3; i++)
1456     {
1457       const gchar *s = seperator[i];
1458
1459       /* Add a new row to the model */
1460       gtk_list_store_append (list, &iter);
1461       gtk_list_store_set (list, &iter,
1462                           0, s,
1463                           -1);
1464
1465     }
1466
1467   gtk_combo_box_set_model (GTK_COMBO_BOX (cb), GTK_TREE_MODEL (list));
1468   g_object_unref (list);
1469
1470   gtk_combo_box_set_entry_text_column (cb, 0);
1471 }
1472
1473
1474 #if SHEET_MERGE
1475
1476 /* Sets IA's separators substructure to match the widgets. */
1477 static void
1478 get_separators (PsppireImportAssistant *ia)
1479 {
1480   int i;
1481
1482   ds_clear (&ia->separators);
1483   for (i = 0; i < SEPARATOR_CNT; i++)
1484     {
1485       const struct separator *sep = &separators[i];
1486       GtkWidget *button = get_widget_assert (ia->builder, sep->name);
1487       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
1488         ds_put_byte (&ia->separators, sep->c);
1489     }
1490
1491   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->custom_cb)))
1492     ds_put_cstr (&ia->separators,
1493                  gtk_entry_get_text (GTK_ENTRY (ia->custom_entry)));
1494
1495   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->quote_cb)))
1496     {
1497       const gchar *text = gtk_entry_get_text (GTK_ENTRY (gtk_bin_get_child (GTK_BIN (ia->quote_combo))));
1498       ds_assign_cstr (&ia->quotes, text);
1499     }
1500   else
1501     ds_clear (&ia->quotes);
1502 }
1503
1504
1505
1506
1507
1508
1509 /* Breaks the file data in IA into columns based on the
1510    separators set in IA's separators substructure. */
1511 static void
1512 split_fields (PsppireImportAssistant *ia)
1513 {
1514   size_t columns_allocated;
1515   bool space_sep;
1516   size_t row = 0;
1517
1518   /* Is space in the set of separators? */
1519   space_sep = ss_find_byte (ds_ss (&ia->separators), ' ') != SIZE_MAX;
1520
1521   /* Split all the lines, not just those from
1522      ia->first_line.skip_lines on, so that we split the line that
1523      contains variables names if ia->first_line.variable_names is
1524      TRUE. */
1525   columns_allocated = 0;
1526
1527   gint n_lines = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (ia->text_file), NULL);
1528   GtkTreeIter iter;
1529   gtk_tree_model_get_iter_first (GTK_TREE_MODEL (ia->text_file), &iter);
1530   while (gtk_tree_model_iter_next (GTK_TREE_MODEL (ia->text_file), &iter))
1531     {
1532       row++;
1533       gchar *xxx;
1534       gtk_tree_model_get (GTK_TREE_MODEL (ia->text_file), &iter, 1, &xxx, -1);
1535       struct substring text = ss_cstr (xxx);
1536       g_free (xxx);
1537       size_t column_idx;
1538
1539       for (column_idx = 0; ;column_idx++)
1540         {
1541           struct substring field = SS_EMPTY_INITIALIZER;
1542           struct column *column;
1543
1544           if (space_sep)
1545             {
1546               ss_ltrim (&text, ss_cstr (" "));
1547             }
1548           if (ss_is_empty (text))
1549             {
1550               if (column_idx != 0)
1551                 break;
1552               field = text;
1553             }
1554           else if (!ds_is_empty (&ia->quotes)
1555                    && ds_find_byte (&ia->quotes, text.string[0]) != SIZE_MAX)
1556             {
1557               int quote = ss_get_byte (&text);
1558               struct string s;
1559               int c;
1560
1561               ds_init_empty (&s);
1562               while ((c = ss_get_byte (&text)) != EOF)
1563                 if (c != quote)
1564                   ds_put_byte (&s, c);
1565                 else if (ss_match_byte (&text, quote))
1566                   ds_put_byte (&s, quote);
1567                 else
1568                   break;
1569               field = ds_ss (&s);
1570             }
1571           else
1572             {
1573               ss_get_bytes (&text, ss_cspan (text, ds_ss (&ia->separators)),
1574                             &field);
1575             }
1576
1577           if (column_idx >= ia->column_cnt)
1578             {
1579               struct column *column;
1580
1581               if (ia->column_cnt >= columns_allocated)
1582                 {
1583                   ia->columns = x2nrealloc (ia->columns, &columns_allocated,
1584                                             sizeof *ia->columns);
1585                 }
1586               column = &ia->columns[ia->column_cnt++];
1587               column->name = NULL;
1588               column->width = 0;
1589               column->contents = xcalloc (n_lines,
1590                                           sizeof *column->contents);
1591             }
1592           column = &ia->columns[column_idx];
1593           column->contents[row] = field;
1594           if (ss_length (field) > column->width)
1595             column->width = ss_length (field);
1596
1597           if (space_sep)
1598             ss_ltrim (&text, ss_cstr (" "));
1599           if (ss_is_empty (text))
1600             break;
1601           if (ss_find_byte (ds_ss (&ia->separators), ss_first (text))
1602               != SIZE_MAX)
1603             ss_advance (&text, 1);
1604         }
1605     }
1606 }
1607
1608 #endif
1609
1610 /* Chooses a name for each column on the separators page */
1611 static void
1612 choose_column_names (PsppireImportAssistant *ia)
1613 {
1614   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->variable_names_cb)))
1615     {
1616       int i;
1617       unsigned long int generated_name_count = 0;
1618       dict_clear (ia->dict);
1619       for (i = 0; i < gtk_tree_model_get_n_columns (ia->delimiters_model) - 1; ++i)
1620         {
1621           const gchar *candidate_name =
1622             psppire_delimited_text_get_header_title (PSPPIRE_DELIMITED_TEXT (ia->delimiters_model), i);
1623
1624           char *name = dict_make_unique_var_name (ia->dict, candidate_name, &generated_name_count);
1625           dict_create_var_assert (ia->dict, name, 0);
1626           free (name);
1627         }
1628     }
1629 }
1630
1631
1632
1633 /* Called when the user toggles one of the separators
1634    checkboxes. */
1635 static void
1636 on_separator_toggle (GtkToggleButton *toggle UNUSED,
1637                      PsppireImportAssistant *ia)
1638 {
1639   int i;
1640   GSList *delimiters = NULL;
1641   for (i = 0; i < SEPARATOR_CNT; i++)
1642     {
1643       const struct separator *s = &separators[i];
1644       GtkWidget *button = get_widget_assert (ia->builder, s->name);
1645       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
1646         {
1647           delimiters = g_slist_prepend (delimiters,  GINT_TO_POINTER (s->c));
1648         }
1649     }
1650
1651   g_object_set (ia->delimiters_model, "delimiters", delimiters, NULL);
1652
1653   //  revise_fields_preview (ia);
1654 }
1655
1656
1657 /* Called when the user changes the entry field for custom
1658    separators. */
1659 static void
1660 on_separators_custom_entry_notify (GObject *gobject UNUSED,
1661                                    GParamSpec *arg1 UNUSED,
1662                                    PsppireImportAssistant *ia)
1663 {
1664   revise_fields_preview (ia);
1665 }
1666
1667 /* Called when the user toggles the checkbox that enables custom
1668    separators. */
1669 static void
1670 on_separators_custom_cb_toggle (GtkToggleButton *custom_cb,
1671                                 PsppireImportAssistant *ia)
1672 {
1673   bool is_active = gtk_toggle_button_get_active (custom_cb);
1674   gtk_widget_set_sensitive (ia->custom_entry, is_active);
1675   revise_fields_preview (ia);
1676 }
1677
1678 /* Called when the user changes the selection in the combo box
1679    that selects a quote character. */
1680 static void
1681 on_quote_combo_change (GtkComboBox *combo, PsppireImportAssistant *ia)
1682 {
1683   //  revise_fields_preview (ia);
1684 }
1685
1686 /* Called when the user toggles the checkbox that enables
1687    quoting. */
1688 static void
1689 on_quote_cb_toggle (GtkToggleButton *quote_cb, PsppireImportAssistant *ia)
1690 {
1691   bool is_active = gtk_toggle_button_get_active (quote_cb);
1692   gtk_widget_set_sensitive (ia->quote_combo, is_active);
1693   revise_fields_preview (ia);
1694 }
1695
1696 /* Initializes IA's separators substructure. */
1697 static void
1698 separators_page_create (PsppireImportAssistant *ia)
1699 {
1700   GtkBuilder *builder = ia->builder;
1701
1702   size_t i;
1703
1704   GtkWidget *w = get_widget_assert (builder, "Separators");
1705
1706   g_object_set_data (G_OBJECT (w), "on-entering", prepare_separators_page);
1707   g_object_set_data (G_OBJECT (w), "on-reset", prepare_separators_page);
1708
1709   add_page_to_assistant (ia, w,   GTK_ASSISTANT_PAGE_CONTENT, _("Choose Separators"));
1710
1711   ia->custom_cb = get_widget_assert (builder, "custom-cb");
1712   ia->custom_entry = get_widget_assert (builder, "custom-entry");
1713   ia->quote_combo = get_widget_assert (builder, "quote-combo");
1714   ia->quote_entry = GTK_ENTRY (gtk_bin_get_child (GTK_BIN (ia->quote_combo)));
1715   ia->quote_cb = get_widget_assert (builder, "quote-cb");
1716
1717   set_quote_list (GTK_COMBO_BOX (ia->quote_combo));
1718
1719   if (ia->fields_tree_view == NULL)
1720     {
1721       GtkWidget *scroller = get_widget_assert (ia->builder, "fields-scroller");
1722       ia->fields_tree_view = gtk_tree_view_new ();
1723       gtk_container_add (GTK_CONTAINER (scroller), GTK_WIDGET (ia->fields_tree_view));
1724       gtk_widget_show_all (scroller);
1725     }
1726
1727   g_signal_connect (ia->quote_combo, "changed",
1728                     G_CALLBACK (on_quote_combo_change), ia);
1729   g_signal_connect (ia->quote_cb, "toggled",
1730                     G_CALLBACK (on_quote_cb_toggle), ia);
1731   g_signal_connect (ia->custom_entry, "notify::text",
1732                     G_CALLBACK (on_separators_custom_entry_notify), ia);
1733   g_signal_connect (ia->custom_cb, "toggled",
1734                     G_CALLBACK (on_separators_custom_cb_toggle), ia);
1735   for (i = 0; i < SEPARATOR_CNT; i++)
1736     g_signal_connect (get_widget_assert (builder, separators[i].name),
1737                       "toggled", G_CALLBACK (on_separator_toggle), ia);
1738
1739 }
1740
1741
1742
1743 \f
1744
1745 #if SHEET_MERGE
1746
1747 /* Called when the user changes one of the variables in the
1748    dictionary. */
1749 static void
1750 on_variable_change (PsppireDict *dict, int dict_idx,
1751                     unsigned int what, const struct variable *oldvar,
1752                     PsppireImportAssistant *ia)
1753 {
1754   PsppSheetView *tv = PSPP_SHEET_VIEW (ia->data_tree_view);
1755   gint column_idx = dict_idx + 1;
1756
1757   push_watch_cursor (ia);
1758
1759   /* Remove previous column and replace with new column. */
1760   pspp_sheet_view_remove_column (tv, pspp_sheet_view_get_column (PSPP_SHEET_VIEW (ia->data_tree_view), column_idx));
1761   pspp_sheet_view_insert_column (tv, PSPP_SHEET_VIEW_COLUMN (make_data_column (ia, ia->data_tree_view, FALSE, dict_idx)),
1762                                  column_idx);
1763
1764   /* Save a copy of the modified variable in modified_vars, so
1765      that its attributes will be preserved if we back up to the
1766      previous page with the Prev button and then come back
1767      here. */
1768   if (dict_idx >= ia->modified_var_cnt)
1769     {
1770       size_t i;
1771       ia->modified_vars = xnrealloc (ia->modified_vars, dict_idx + 1,
1772                                      sizeof *ia->modified_vars);
1773       for (i = 0; i <= dict_idx; i++)
1774         ia->modified_vars[i] = NULL;
1775       ia->modified_var_cnt = dict_idx + 1;
1776     }
1777   if (ia->modified_vars[dict_idx])
1778     var_destroy (ia->modified_vars[dict_idx]);
1779   ia->modified_vars[dict_idx]
1780     = var_clone (psppire_dict_get_variable (dict, dict_idx));
1781
1782   pop_watch_cursor (ia);
1783 }
1784
1785 #endif
1786
1787
1788 static struct casereader_random_class my_casereader_class;
1789
1790 static struct ccase *
1791 my_read (struct casereader *reader, void *aux, casenumber idx)
1792 {
1793   PsppireImportAssistant *ia = PSPPIRE_IMPORT_ASSISTANT (aux);
1794   GtkTreeModel *tm = GTK_TREE_MODEL (ia->delimiters_model);
1795
1796   GtkTreePath *tp = gtk_tree_path_new_from_indices (idx, -1);
1797
1798   const struct caseproto *proto = casereader_get_proto (reader);
1799
1800   GtkTreeIter iter;
1801   struct ccase *c = NULL;
1802   if (gtk_tree_model_get_iter (tm, &iter, tp))
1803     {
1804       c = case_create (proto);
1805       int i;
1806       for (i = 0 ; i < caseproto_get_n_widths (proto); ++i)
1807         {
1808           GValue value = {0};
1809           gtk_tree_model_get_value (tm, &iter, i + 1, &value);
1810
1811           const struct variable *var = dict_get_var (ia->dict, i);
1812
1813           const gchar *ss = g_value_get_string (&value);
1814
1815           union value *v = case_data_rw (c, var);
1816           char *xx = data_in (ss_cstr (ss),
1817                               "UTF-8",
1818                               var_get_write_format (var)->type,
1819                               v, var_get_width (var), "UTF-8");
1820
1821           /* if (xx) */
1822           /*   g_print ("%s:%d Err %s\n", __FILE__, __LINE__, xx); */
1823           free (xx);
1824           g_value_unset (&value);
1825         }
1826     }
1827
1828   gtk_tree_path_free (tp);
1829
1830   return c;
1831 }
1832
1833 static void
1834 my_destroy (struct casereader *reader, void *aux)
1835 {
1836   g_print ("%s:%d %p\n", __FILE__, __LINE__, reader);
1837 }
1838
1839 static void
1840 my_advance (struct casereader *reader, void *aux, casenumber cnt)
1841 {
1842   g_print ("%s:%d\n", __FILE__, __LINE__);
1843 }
1844
1845
1846 static void
1847 foo (struct dictionary *dict, void *aux)
1848 {
1849   PsppireImportAssistant *ia = PSPPIRE_IMPORT_ASSISTANT (aux);
1850   g_print ("%s:%d\n", __FILE__, __LINE__);
1851
1852   struct caseproto *proto = caseproto_create ();
1853
1854   int i;
1855   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1856     {
1857       const struct variable *var = dict_get_var (ia->dict, i);
1858       proto = caseproto_add_width (proto, var_get_width (var));
1859     }
1860
1861
1862   gint n_rows = gtk_tree_model_iter_n_children (ia->delimiters_model, NULL);
1863
1864   struct casereader *reader =
1865     casereader_create_random (proto, n_rows, &my_casereader_class,  ia);
1866
1867
1868   PsppireDataStore *store = NULL;
1869
1870   g_object_get (ia->data_sheet, "data-model", &store, NULL);
1871
1872   psppire_data_store_set_reader (store, reader);
1873 }
1874
1875 /* Called just before the formats page of the assistant is
1876    displayed. */
1877 static void
1878 prepare_formats_page (PsppireImportAssistant *ia)
1879 {
1880   PsppireDict *dict = psppire_dict_new_from_dict (ia->dict);
1881   g_object_set (ia->var_sheet, "data-model", dict, NULL);
1882
1883   my_casereader_class.read = my_read;
1884   my_casereader_class.destroy = my_destroy;
1885   my_casereader_class.advance = my_advance;
1886
1887   struct caseproto *proto = caseproto_create ();
1888   int i;
1889
1890   struct fmt_guesser **fg = xcalloc (sizeof *fg, dict_get_var_cnt (ia->dict));
1891   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1892     {
1893       fg[i] = fmt_guesser_create ();
1894     }
1895
1896   gint n_rows = gtk_tree_model_iter_n_children (ia->delimiters_model, NULL);
1897
1898   GtkTreeIter iter;
1899   gboolean ok;
1900   for (ok = gtk_tree_model_get_iter_first (ia->delimiters_model, &iter);
1901        ok;
1902        ok = gtk_tree_model_iter_next (ia->delimiters_model, &iter))
1903     {
1904       for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1905         {
1906           gchar *s = NULL;
1907           gtk_tree_model_get (ia->delimiters_model, &iter, i+1, &s, -1);
1908           fmt_guesser_add (fg[i], ss_cstr (s));
1909           free (s);
1910         }
1911     }
1912
1913   for (i = 0 ; i < dict_get_var_cnt (ia->dict); ++i)
1914     {
1915       struct fmt_spec fs;
1916       fmt_guesser_guess (fg[i], &fs);
1917
1918       fmt_fix (&fs, FMT_FOR_INPUT);
1919
1920       struct variable *var = dict_get_var (ia->dict, i);
1921
1922       int width = fmt_var_width (&fs);
1923
1924       var_set_width_and_formats (var, width,
1925                                  &fs, &fs);
1926
1927       proto = caseproto_add_width (proto, width);
1928       fmt_guesser_destroy (fg[i]);
1929     }
1930
1931   free (fg);
1932
1933   //  dict_set_change_callback (ia->dict, foo, ia);
1934
1935   struct casereader *reader =
1936     casereader_create_random (proto, n_rows, &my_casereader_class,  ia);
1937
1938   PsppireDataStore *store = psppire_data_store_new (dict);
1939   psppire_data_store_set_reader (store, reader);
1940
1941   g_object_set (ia->data_sheet, "data-model", store, NULL);
1942
1943
1944   gint pmax;
1945   g_object_get (get_widget_assert (ia->builder, "vpaned1"),
1946                 "max-position", &pmax, NULL);
1947
1948
1949   g_object_set (get_widget_assert (ia->builder, "vpaned1"),
1950                 "position", pmax / 2, NULL);
1951
1952   gtk_widget_show (ia->paste_button);
1953 }
1954
1955 static void
1956 formats_page_create (PsppireImportAssistant *ia)
1957 {
1958   GtkBuilder *builder = ia->builder;
1959
1960   GtkWidget *w = get_widget_assert (builder, "Formats");
1961   g_object_set_data (G_OBJECT (w), "on-entering", prepare_formats_page);
1962   g_object_set_data (G_OBJECT (w), "on-reset", reset_formats_page);
1963
1964   GtkWidget *vars_scroller = get_widget_assert (builder, "vars-scroller");
1965   if (ia->var_sheet == NULL)
1966     {
1967       ia->var_sheet = psppire_variable_sheet_new ();
1968
1969       gtk_container_add (GTK_CONTAINER (vars_scroller), ia->var_sheet);
1970
1971       ia->dict = dict_create (get_default_encoding ());
1972
1973       gtk_widget_show_all (vars_scroller);
1974     }
1975   GtkWidget *data_scroller = get_widget_assert (builder, "data-scroller");
1976   if (ia->data_sheet == NULL)
1977     {
1978       ia->data_sheet = psppire_data_sheet_new ();
1979
1980       gtk_container_add (GTK_CONTAINER (data_scroller), ia->data_sheet);
1981
1982       gtk_widget_show_all (data_scroller);
1983     }
1984
1985   add_page_to_assistant (ia, w,
1986                          GTK_ASSISTANT_PAGE_CONFIRM, _("Adjust Variable Formats"));
1987
1988   ia->modified_vars = NULL;
1989   ia->modified_var_cnt = 0;
1990 }
1991
1992
1993 \f
1994
1995 static void
1996 separators_append_syntax (const PsppireImportAssistant *ia, struct string *s)
1997 {
1998   int i;
1999
2000   ds_put_cstr (s, "  /DELIMITERS=\"");
2001
2002   if (gtk_toggle_button_get_active (get_widget_assert (ia->builder, "tab")))
2003     ds_put_cstr (s, "\\t");
2004   for (i = 0; i < SEPARATOR_CNT; i++)
2005     {
2006       const struct separator *seps = &separators[i];
2007       GtkWidget *button = get_widget_assert (ia->builder, seps->name);
2008       if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
2009         {
2010           if (seps->c == '\t')
2011             continue;
2012
2013           ds_put_byte (s, seps->c);
2014         }
2015     }
2016   ds_put_cstr (s, "\"\n");
2017   if (!ds_is_empty (&ia->quotes))
2018     syntax_gen_pspp (s, "  /QUALIFIER=%sq\n", ds_cstr (&ia->quotes));
2019 }
2020
2021 static void
2022 formats_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2023 {
2024   int i;
2025   int var_cnt;
2026
2027   g_return_if_fail (ia->dict);
2028
2029   ds_put_cstr (s, "  /VARIABLES=\n");
2030
2031   var_cnt = dict_get_var_cnt (ia->dict);
2032   for (i = 0; i < var_cnt; i++)
2033     {
2034       struct variable *var = dict_get_var (ia->dict, i);
2035       char format_string[FMT_STRING_LEN_MAX + 1];
2036       fmt_to_string (var_get_print_format (var), format_string);
2037       ds_put_format (s, "    %s %s%s\n",
2038                      var_get_name (var), format_string,
2039                      i == var_cnt - 1 ? "." : "");
2040     }
2041 }
2042
2043 static void
2044 first_line_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2045 {
2046   gint first_case = 0;
2047   g_object_get (ia->delimiters_model, "first-line", &first_case, NULL);
2048
2049   if (first_case > 0)
2050     ds_put_format (s, "  /FIRSTCASE=%d\n", first_case + 1);
2051 }
2052
2053 static void
2054 intro_append_syntax (const PsppireImportAssistant *ia, struct string *s)
2055 {
2056   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->n_cases_button)))
2057     ds_put_format (s, "N OF CASES %d.\n",
2058                    gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (ia->n_cases_spin)));
2059   else if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (ia->percent_button)))
2060     ds_put_format (s, "SAMPLE %.4g.\n",
2061                    gtk_spin_button_get_value (GTK_SPIN_BUTTON (ia->percent_spin)) / 100.0);
2062 }
2063
2064
2065 /* Emits PSPP syntax to S that applies the dictionary attributes
2066    (such as missing values and value labels) of the variables in
2067    DICT.  */
2068 static void
2069 apply_dict (const struct dictionary *dict, struct string *s)
2070 {
2071   size_t var_cnt = dict_get_var_cnt (dict);
2072   size_t i;
2073
2074   for (i = 0; i < var_cnt; i++)
2075     {
2076       struct variable *var = dict_get_var (dict, i);
2077       const char *name = var_get_name (var);
2078       enum val_type type = var_get_type (var);
2079       int width = var_get_width (var);
2080       enum measure measure = var_get_measure (var);
2081       enum var_role role = var_get_role (var);
2082       enum alignment alignment = var_get_alignment (var);
2083       const struct fmt_spec *format = var_get_print_format (var);
2084
2085       if (var_has_missing_values (var))
2086         {
2087           const struct missing_values *mv = var_get_missing_values (var);
2088           size_t j;
2089
2090           syntax_gen_pspp (s, "MISSING VALUES %ss (", name);
2091           for (j = 0; j < mv_n_values (mv); j++)
2092             {
2093               if (j)
2094                 ds_put_cstr (s, ", ");
2095               syntax_gen_value (s, mv_get_value (mv, j), width, format);
2096             }
2097
2098           if (mv_has_range (mv))
2099             {
2100               double low, high;
2101               if (mv_has_value (mv))
2102                 ds_put_cstr (s, ", ");
2103               mv_get_range (mv, &low, &high);
2104               syntax_gen_num_range (s, low, high, format);
2105             }
2106           ds_put_cstr (s, ").\n");
2107         }
2108       if (var_has_value_labels (var))
2109         {
2110           const struct val_labs *vls = var_get_value_labels (var);
2111           const struct val_lab **labels = val_labs_sorted (vls);
2112           size_t n_labels = val_labs_count (vls);
2113           size_t i;
2114
2115           syntax_gen_pspp (s, "VALUE LABELS %ss", name);
2116           for (i = 0; i < n_labels; i++)
2117             {
2118               const struct val_lab *vl = labels[i];
2119               ds_put_cstr (s, "\n  ");
2120               syntax_gen_value (s, &vl->value, width, format);
2121               ds_put_byte (s, ' ');
2122               syntax_gen_string (s, ss_cstr (val_lab_get_escaped_label (vl)));
2123             }
2124           free (labels);
2125           ds_put_cstr (s, ".\n");
2126         }
2127       if (var_has_label (var))
2128         syntax_gen_pspp (s, "VARIABLE LABELS %ss %sq.\n",
2129                          name, var_get_label (var));
2130       if (measure != var_default_measure (type))
2131         syntax_gen_pspp (s, "VARIABLE LEVEL %ss (%ss).\n",
2132                          name, measure_to_syntax (measure));
2133       if (role != ROLE_INPUT)
2134         syntax_gen_pspp (s, "VARIABLE ROLE /%ss %ss.\n",
2135                          var_role_to_syntax (role), name);
2136       if (alignment != var_default_alignment (type))
2137         syntax_gen_pspp (s, "VARIABLE ALIGNMENT %ss (%ss).\n",
2138                          name, alignment_to_syntax (alignment));
2139       if (var_get_display_width (var) != var_default_display_width (width))
2140         syntax_gen_pspp (s, "VARIABLE WIDTH %ss (%d).\n",
2141                          name, var_get_display_width (var));
2142     }
2143 }
2144
2145
2146
2147 static char *
2148 sheet_spec_gen_syntax (PsppireImportAssistant *ia)
2149 {
2150   GtkBuilder *builder = ia->builder;
2151   GtkWidget *range_entry = get_widget_assert (builder, "cell-range-entry");
2152   GtkWidget *sheet_entry = get_widget_assert (builder, "sheet-entry");
2153   GtkWidget *rnc = get_widget_assert (builder, "readnames-checkbox");
2154   const gchar *range = gtk_entry_get_text (GTK_ENTRY (range_entry));
2155   int sheet_index = 1 + gtk_combo_box_get_active (GTK_COMBO_BOX (sheet_entry));
2156   gboolean read_names = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (rnc));
2157
2158   struct string s = DS_EMPTY_INITIALIZER;
2159
2160   char *filename;
2161   g_object_get (ia->text_file, "file-name", &filename, NULL);
2162   syntax_gen_pspp (&s,
2163                    "GET DATA"
2164                    "\n  /TYPE=%ss"
2165                    "\n  /FILE=%sq"
2166                    "\n  /SHEET=index %d"
2167                    "\n  /READNAMES=%ss",
2168                    (ia->spreadsheet->type == SPREADSHEET_GNUMERIC) ? "GNM" : "ODS",
2169                    filename,
2170                    sheet_index,
2171                    read_names ? "ON" : "OFF");
2172
2173   if (range && 0 != strcmp ("", range))
2174     {
2175       syntax_gen_pspp (&s,
2176                        "\n  /CELLRANGE=RANGE %sq", range);
2177     }
2178   else
2179     {
2180       syntax_gen_pspp (&s,
2181                        "\n  /CELLRANGE=FULL");
2182     }
2183
2184
2185   syntax_gen_pspp (&s, ".");
2186
2187
2188   return ds_cstr (&s);
2189 }
2190
2191
2192 gchar *
2193 psppire_import_assistant_generate_syntax (PsppireImportAssistant *ia)
2194 {
2195   struct string s = DS_EMPTY_INITIALIZER;
2196
2197   if (!ia->spreadsheet)
2198     {
2199       gchar *file_name = NULL;
2200       gchar *encoding = NULL;
2201       g_object_get (ia->text_file,
2202                     "file-name", &file_name,
2203                     "encoding", &encoding,
2204                     NULL);
2205
2206       if (file_name == NULL)
2207         return NULL;
2208
2209       syntax_gen_pspp (&s,
2210                        "GET DATA"
2211                        "\n  /TYPE=TXT"
2212                        "\n  /FILE=%sq\n",
2213                        file_name);
2214       if (encoding && strcmp (encoding, "Auto"))
2215         syntax_gen_pspp (&s, "  /ENCODING=%sq\n", encoding);
2216
2217       ds_put_cstr (&s,
2218                    "  /ARRANGEMENT=DELIMITED\n"
2219                    "  /DELCASE=LINE\n");
2220
2221       first_line_append_syntax (ia, &s);
2222       separators_append_syntax (ia, &s);
2223
2224       formats_append_syntax (ia, &s);
2225       apply_dict (ia->dict, &s);
2226       intro_append_syntax (ia, &s);
2227     }
2228   else
2229     {
2230       return sheet_spec_gen_syntax (ia);
2231     }
2232
2233   return ds_cstr (&s);
2234 }