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