]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilechooserentry.c
filechooserentry: Simplify append_common_prefix()
[~andy/gtk] / gtk / gtkfilechooserentry.c
1 /* GTK - The GIMP Toolkit
2  * gtkfilechooserentry.c: Entry with filename completion
3  * Copyright (C) 2003, Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "gtkfilechooserentry.h"
24
25 #include <string.h>
26
27 #include "gtkcelllayout.h"
28 #include "gtkcellrenderertext.h"
29 #include "gtkentry.h"
30 #include "gtkfilesystemmodel.h"
31 #include "gtklabel.h"
32 #include "gtkmain.h"
33 #include "gtksizerequest.h"
34 #include "gtkwindow.h"
35 #include "gtkintl.h"
36
37 typedef struct _GtkFileChooserEntryClass GtkFileChooserEntryClass;
38
39 #define GTK_FILE_CHOOSER_ENTRY_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_FILE_CHOOSER_ENTRY, GtkFileChooserEntryClass))
40 #define GTK_IS_FILE_CHOOSER_ENTRY_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_FILE_CHOOSER_ENTRY))
41 #define GTK_FILE_CHOOSER_ENTRY_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_FILE_CHOOSER_ENTRY, GtkFileChooserEntryClass))
42
43 struct _GtkFileChooserEntryClass
44 {
45   GtkEntryClass parent_class;
46 };
47
48 /* Action to take when the current folder finishes loading (for explicit or automatic completion) */
49 typedef enum {
50   LOAD_COMPLETE_NOTHING,
51   LOAD_COMPLETE_EXPLICIT_COMPLETION
52 } LoadCompleteAction;
53
54 typedef enum
55 {
56   REFRESH_OK,
57   REFRESH_INVALID_INPUT,
58   REFRESH_INCOMPLETE_HOSTNAME,
59   REFRESH_NONEXISTENT,
60   REFRESH_NOT_LOCAL
61 } RefreshStatus;
62
63 struct _GtkFileChooserEntry
64 {
65   GtkEntry parent_instance;
66
67   GtkFileChooserAction action;
68
69   GFile *base_folder;
70   GFile *current_folder_file;
71   gchar *dir_part;
72   gchar *file_part;
73   gint file_part_pos;
74
75   LoadCompleteAction load_complete_action;
76
77   GtkTreeModel *completion_store;
78
79   guint current_folder_loaded : 1;
80   guint in_change      : 1;
81   guint eat_tabs       : 1;
82   guint local_only     : 1;
83 };
84
85 enum
86 {
87   DISPLAY_NAME_COLUMN,
88   FULL_PATH_COLUMN,
89   FILE_COLUMN,
90   N_COLUMNS
91 };
92
93 static void     gtk_file_chooser_entry_finalize       (GObject          *object);
94 static void     gtk_file_chooser_entry_dispose        (GObject          *object);
95 static void     gtk_file_chooser_entry_grab_focus     (GtkWidget        *widget);
96 static gboolean gtk_file_chooser_entry_key_press_event (GtkWidget *widget,
97                                                         GdkEventKey *event);
98 static gboolean gtk_file_chooser_entry_focus_out_event (GtkWidget       *widget,
99                                                         GdkEventFocus   *event);
100 static void     gtk_file_chooser_entry_activate       (GtkEntry         *entry);
101
102 #ifdef G_OS_WIN32
103 static gint     insert_text_callback      (GtkFileChooserEntry *widget,
104                                            const gchar         *new_text,
105                                            gint                 new_text_length,
106                                            gint                *position,
107                                            gpointer             user_data);
108 static void     delete_text_callback      (GtkFileChooserEntry *widget,
109                                            gint                 start_pos,
110                                            gint                 end_pos,
111                                            gpointer             user_data);
112 #endif
113
114 static gboolean match_selected_callback   (GtkEntryCompletion  *completion,
115                                            GtkTreeModel        *model,
116                                            GtkTreeIter         *iter,
117                                            GtkFileChooserEntry *chooser_entry);
118 static gboolean completion_match_func     (GtkEntryCompletion  *comp,
119                                            const char          *key,
120                                            GtkTreeIter         *iter,
121                                            gpointer             data);
122
123 static RefreshStatus refresh_current_folder_and_file_part (GtkFileChooserEntry *chooser_entry,
124                                                            const char          *text);
125 static void finished_loading_cb (GtkFileSystemModel  *model,
126                                  GError              *error,
127                                  GtkFileChooserEntry *chooser_entry);
128
129 G_DEFINE_TYPE (GtkFileChooserEntry, _gtk_file_chooser_entry, GTK_TYPE_ENTRY)
130
131 static void
132 gtk_file_chooser_entry_dispatch_properties_changed (GObject     *object,
133                                                     guint        n_pspecs,
134                                                     GParamSpec **pspecs)
135 {
136   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
137   GtkEditable *editable = GTK_EDITABLE (object);
138   guint i;
139
140   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->dispatch_properties_changed (object, n_pspecs, pspecs);
141
142   /* What we are after: The text in front of the cursor was modified.
143    * Unfortunately, there's no other way to catch this. */
144
145   if (chooser_entry->in_change)
146     return;
147
148   for (i = 0; i < n_pspecs; i++)
149     {
150       if (pspecs[i]->name == I_("cursor-position") ||
151           pspecs[i]->name == I_("selection-bound") ||
152           pspecs[i]->name == I_("text"))
153         {
154           char *text;
155           int start, end;
156
157           chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
158
159           gtk_editable_get_selection_bounds (editable, &start, &end);
160           text = gtk_editable_get_chars (editable, 0, MIN (start, end));
161           refresh_current_folder_and_file_part (chooser_entry, text);
162           g_free (text);
163
164           break;
165         }
166     }
167 }
168
169 static void
170 _gtk_file_chooser_entry_class_init (GtkFileChooserEntryClass *class)
171 {
172   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
173   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
174   GtkEntryClass *entry_class = GTK_ENTRY_CLASS (class);
175
176   gobject_class->finalize = gtk_file_chooser_entry_finalize;
177   gobject_class->dispose = gtk_file_chooser_entry_dispose;
178   gobject_class->dispatch_properties_changed = gtk_file_chooser_entry_dispatch_properties_changed;
179
180   widget_class->grab_focus = gtk_file_chooser_entry_grab_focus;
181   widget_class->key_press_event = gtk_file_chooser_entry_key_press_event;
182   widget_class->focus_out_event = gtk_file_chooser_entry_focus_out_event;
183
184   entry_class->activate = gtk_file_chooser_entry_activate;
185 }
186
187 static void
188 _gtk_file_chooser_entry_init (GtkFileChooserEntry *chooser_entry)
189 {
190   GtkEntryCompletion *comp;
191   GtkCellRenderer *cell;
192
193   chooser_entry->local_only = TRUE;
194   chooser_entry->base_folder = g_file_new_for_path (g_get_home_dir ());
195
196   g_object_set (chooser_entry, "truncate-multiline", TRUE, NULL);
197
198   comp = gtk_entry_completion_new ();
199   gtk_entry_completion_set_popup_single_match (comp, FALSE);
200   /* see docs for gtk_entry_completion_set_text_column() */
201   g_object_set (comp, "text-column", FULL_PATH_COLUMN, NULL);
202
203   gtk_entry_completion_set_match_func (comp,
204                                        completion_match_func,
205                                        chooser_entry,
206                                        NULL);
207
208   cell = gtk_cell_renderer_text_new ();
209   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (comp),
210                               cell, TRUE);
211   gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (comp),
212                                  cell,
213                                  "text", DISPLAY_NAME_COLUMN);
214
215   g_signal_connect (comp, "match-selected",
216                     G_CALLBACK (match_selected_callback), chooser_entry);
217
218   gtk_entry_set_completion (GTK_ENTRY (chooser_entry), comp);
219   g_object_unref (comp);
220
221 #ifdef G_OS_WIN32
222   g_signal_connect (chooser_entry, "insert-text",
223                     G_CALLBACK (insert_text_callback), NULL);
224   g_signal_connect (chooser_entry, "delete-text",
225                     G_CALLBACK (delete_text_callback), NULL);
226 #endif
227 }
228
229 static void
230 gtk_file_chooser_entry_finalize (GObject *object)
231 {
232   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
233
234   g_object_unref (chooser_entry->base_folder);
235
236   if (chooser_entry->current_folder_file)
237     g_object_unref (chooser_entry->current_folder_file);
238
239   g_free (chooser_entry->dir_part);
240   g_free (chooser_entry->file_part);
241
242   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->finalize (object);
243 }
244
245 static void
246 discard_loading_and_current_folder_file (GtkFileChooserEntry *chooser_entry)
247 {
248   if (chooser_entry->current_folder_file)
249     {
250       g_object_unref (chooser_entry->current_folder_file);
251       chooser_entry->current_folder_file = NULL;
252     }
253 }
254
255 static void
256 gtk_file_chooser_entry_dispose (GObject *object)
257 {
258   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
259
260   discard_loading_and_current_folder_file (chooser_entry);
261
262   if (chooser_entry->completion_store)
263     {
264       g_object_unref (chooser_entry->completion_store);
265       chooser_entry->completion_store = NULL;
266     }
267
268   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->dispose (object);
269 }
270
271 /* Match functions for the GtkEntryCompletion */
272 static gboolean
273 match_selected_callback (GtkEntryCompletion  *completion,
274                          GtkTreeModel        *model,
275                          GtkTreeIter         *iter,
276                          GtkFileChooserEntry *chooser_entry)
277 {
278   char *path;
279   
280   gtk_tree_model_get (model, iter,
281                       FULL_PATH_COLUMN, &path,
282                       -1);
283
284   /* We don't set in_change here as we want to update the current_folder
285    * variable */
286   gtk_editable_delete_text (GTK_EDITABLE (chooser_entry),
287                             0,
288                             gtk_editable_get_position (GTK_EDITABLE (chooser_entry)));
289   gtk_editable_insert_text (GTK_EDITABLE (chooser_entry),
290                             path,
291                             0,
292                             NULL); 
293
294   g_free (path);
295
296   return TRUE;
297 }
298
299 /* Match function for the GtkEntryCompletion */
300 static gboolean
301 completion_match_func (GtkEntryCompletion *comp,
302                        const char         *key_unused,
303                        GtkTreeIter        *iter,
304                        gpointer            data)
305 {
306   GtkFileChooserEntry *chooser_entry;
307   char *name = NULL;
308   gboolean result;
309   char *norm_file_part;
310   char *norm_name;
311
312   chooser_entry = GTK_FILE_CHOOSER_ENTRY (data);
313
314   /* We ignore the key because it is the contents of the entry.  Instead, we
315    * just use our precomputed file_part.
316    */
317   if (!chooser_entry->file_part)
318     {
319       return FALSE;
320     }
321
322   gtk_tree_model_get (chooser_entry->completion_store, iter, DISPLAY_NAME_COLUMN, &name, -1);
323   if (!name)
324     {
325       return FALSE; /* Uninitialized row, ugh */
326     }
327
328   /* If we have an empty file_part, then we're at the root of a directory.  In
329    * that case, we want to match all non-dot files.  We might want to match
330    * dot_files too if show_hidden is TRUE on the fileselector in the future.
331    */
332   /* Additionally, support for gnome .hidden files would be sweet, too */
333   if (chooser_entry->file_part[0] == '\000')
334     {
335       if (name[0] == '.')
336         result = FALSE;
337       else
338         result = TRUE;
339       g_free (name);
340
341       return result;
342     }
343
344
345   norm_file_part = g_utf8_normalize (chooser_entry->file_part, -1, G_NORMALIZE_ALL);
346   norm_name = g_utf8_normalize (name, -1, G_NORMALIZE_ALL);
347
348 #ifdef G_PLATFORM_WIN32
349   {
350     gchar *temp;
351
352     temp = norm_file_part;
353     norm_file_part = g_utf8_casefold (norm_file_part, -1);
354     g_free (temp);
355
356     temp = norm_name;
357     norm_name = g_utf8_casefold (norm_name, -1);
358     g_free (temp);
359   }
360 #endif
361
362   result = (strncmp (norm_file_part, norm_name, strlen (norm_file_part)) == 0);
363
364   g_free (norm_file_part);
365   g_free (norm_name);
366   g_free (name);
367   
368   return result;
369 }
370
371 static void
372 clear_completions (GtkFileChooserEntry *chooser_entry)
373 {
374   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
375 }
376
377 static void
378 beep (GtkFileChooserEntry *chooser_entry)
379 {
380   gtk_widget_error_bell (GTK_WIDGET (chooser_entry));
381 }
382
383 static gboolean
384 is_valid_scheme_character (char c)
385 {
386   return g_ascii_isalnum (c) || c == '+' || c == '-' || c == '.';
387 }
388
389 static gboolean
390 has_uri_scheme (const char *str)
391 {
392   const char *p;
393
394   p = str;
395
396   if (!is_valid_scheme_character (*p))
397     return FALSE;
398
399   do
400     p++;
401   while (is_valid_scheme_character (*p));
402
403   return (strncmp (p, "://", 3) == 0);
404 }
405
406 static GFile *
407 gtk_file_chooser_get_file_for_text (GtkFileChooserEntry *chooser_entry,
408                                     const gchar         *str)
409 {
410   GFile *file;
411
412   if (str[0] == '~' || g_path_is_absolute (str) || has_uri_scheme (str))
413     file = g_file_parse_name (str);
414   else
415     file = g_file_resolve_relative_path (chooser_entry->base_folder, str);
416
417   return file;
418 }
419
420 static GFile *
421 gtk_file_chooser_get_directory_for_text (GtkFileChooserEntry *chooser_entry,
422                                          const char *         text)
423 {
424   GFile *file, *parent;
425
426   file = gtk_file_chooser_get_file_for_text (chooser_entry, text);
427
428   if (text[0] == 0 || text[strlen (text) - 1] == G_DIR_SEPARATOR)
429     return file;
430
431   parent = g_file_get_parent (file);
432   g_object_unref (file);
433
434   return parent;
435 }
436
437 static gboolean
438 gtk_file_chooser_entry_parse (GtkFileChooserEntry  *chooser_entry,
439                               const gchar          *str,
440                               GFile               **folder,
441                               gchar               **file_part,
442                               GError              **error)
443 {
444   GFile *file;
445   gboolean result = FALSE;
446   gboolean is_dir = FALSE;
447   gchar *last_slash = NULL;
448
449   if (str && *str)
450     is_dir = (str [strlen (str) - 1] == G_DIR_SEPARATOR);
451
452   last_slash = strrchr (str, G_DIR_SEPARATOR);
453
454   file = gtk_file_chooser_get_file_for_text (chooser_entry, str);
455
456   if (g_file_equal (chooser_entry->base_folder, file))
457     {
458       /* this is when user types '.', could be the
459        * beginning of a hidden file, ./ or ../
460        */
461       *folder = g_object_ref (file);
462       *file_part = g_strdup (str);
463       result = TRUE;
464     }
465   else if (is_dir)
466     {
467       /* it's a dir, or at least it ends with the dir separator */
468       *folder = g_object_ref (file);
469       *file_part = g_strdup ("");
470       result = TRUE;
471     }
472   else
473     {
474       GFile *parent_file;
475
476       parent_file = g_file_get_parent (file);
477
478       if (!parent_file)
479         {
480           g_set_error (error,
481                        GTK_FILE_CHOOSER_ERROR,
482                        GTK_FILE_CHOOSER_ERROR_NONEXISTENT,
483                        "Could not get parent file");
484           *folder = NULL;
485           *file_part = NULL;
486         }
487       else
488         {
489           *folder = parent_file;
490           result = TRUE;
491
492           if (last_slash)
493             *file_part = g_strdup (last_slash + 1);
494           else
495             *file_part = g_strdup (str);
496         }
497     }
498
499   g_object_unref (file);
500
501   return result;
502 }
503
504 /* Determines if the completion model has entries with a common prefix relative
505  * to the current contents of the entry.  Also, if there's one and only one such
506  * path, stores it in unique_path_ret.
507  */
508 static gboolean
509 find_common_prefix (GtkFileChooserEntry *chooser_entry,
510                     gchar               **common_prefix_ret,
511                     GFile               **unique_file_ret,
512                     gboolean             *is_complete_not_unique_ret,
513                     gboolean             *prefix_expands_the_file_part_ret,
514                     GError              **error)
515 {
516   GtkEditable *editable;
517   GtkTreeIter iter;
518   gboolean parsed;
519   gboolean valid;
520   char *text_up_to_cursor;
521   GFile *parsed_folder_file;
522   char *parsed_file_part;
523
524   *common_prefix_ret = NULL;
525   *unique_file_ret = NULL;
526   *is_complete_not_unique_ret = FALSE;
527   *prefix_expands_the_file_part_ret = FALSE;
528
529   editable = GTK_EDITABLE (chooser_entry);
530
531   text_up_to_cursor = gtk_editable_get_chars (editable, 0, gtk_editable_get_position (editable));
532
533   parsed = gtk_file_chooser_entry_parse (chooser_entry,
534                                          text_up_to_cursor,
535                                          &parsed_folder_file,
536                                          &parsed_file_part,
537                                          error);
538
539   g_free (text_up_to_cursor);
540
541   if (!parsed)
542     return FALSE;
543
544   g_assert (parsed_folder_file != NULL
545             && g_file_equal (parsed_folder_file, chooser_entry->current_folder_file));
546
547   g_object_unref (parsed_folder_file);
548
549   /* First pass: find the common prefix */
550
551   valid = gtk_tree_model_get_iter_first (chooser_entry->completion_store, &iter);
552
553   while (valid)
554     {
555       gchar *display_name;
556       GFile *file;
557
558       gtk_tree_model_get (chooser_entry->completion_store,
559                           &iter,
560                           DISPLAY_NAME_COLUMN, &display_name,
561                           FILE_COLUMN, &file,
562                           -1);
563
564       if (g_str_has_prefix (display_name, parsed_file_part))
565         {
566           if (!*common_prefix_ret)
567             {
568               *common_prefix_ret = g_strdup (display_name);
569               *unique_file_ret = g_object_ref (file);
570             }
571           else
572             {
573               gchar *p = *common_prefix_ret;
574               const gchar *q = display_name;
575
576               while (*p && *p == *q)
577                 {
578                   p++;
579                   q++;
580                 }
581
582               *p = '\0';
583
584               if (*unique_file_ret)
585                 {
586                   g_object_unref (*unique_file_ret);
587                   *unique_file_ret = NULL;
588                 }
589             }
590         }
591
592       g_free (display_name);
593       g_object_unref (file);
594       valid = gtk_tree_model_iter_next (chooser_entry->completion_store, &iter);
595     }
596
597   /* Second pass: see if the prefix we found is a complete match */
598
599   if (*common_prefix_ret != NULL)
600     {
601       valid = gtk_tree_model_get_iter_first (chooser_entry->completion_store, &iter);
602
603       while (valid)
604         {
605           gchar *display_name;
606           int len;
607
608           gtk_tree_model_get (chooser_entry->completion_store,
609                               &iter,
610                               DISPLAY_NAME_COLUMN, &display_name,
611                               -1);
612           len = strlen (display_name);
613           g_assert (len > 0);
614
615           if (G_IS_DIR_SEPARATOR (display_name[len - 1]))
616             len--;
617
618           if (*unique_file_ret == NULL && strncmp (*common_prefix_ret, display_name, len) == 0)
619             *is_complete_not_unique_ret = TRUE;
620
621           g_free (display_name);
622           valid = gtk_tree_model_iter_next (chooser_entry->completion_store, &iter);
623         }
624
625       /* Finally:  Did we generate a new completion, or was the user's input already completed as far as it could go? */
626
627       *prefix_expands_the_file_part_ret = g_utf8_strlen (*common_prefix_ret, -1) > g_utf8_strlen (parsed_file_part, -1);
628     }
629
630   g_free (parsed_file_part);
631
632   return TRUE;
633 }
634
635 /* Finds a common prefix based on the contents of the entry
636  * and mandatorily appends it
637  */
638 static void
639 explicitly_complete (GtkFileChooserEntry *chooser_entry)
640 {
641   gchar *common_prefix;
642   GFile *unique_file;
643   gboolean is_complete_not_unique;
644   gboolean prefix_expands_the_file_part;
645   gint cursor_pos;
646   gint pos;
647
648   clear_completions (chooser_entry);
649
650   if (chooser_entry->completion_store == NULL
651       || !find_common_prefix (chooser_entry, &common_prefix, &unique_file, &is_complete_not_unique, &prefix_expands_the_file_part, NULL)
652       || !common_prefix
653       || !prefix_expands_the_file_part)
654     {
655       beep (chooser_entry);
656       return;
657     }
658
659   cursor_pos = gtk_editable_get_position (GTK_EDITABLE (chooser_entry));
660   pos = chooser_entry->file_part_pos;
661
662   chooser_entry->in_change = TRUE;
663   gtk_editable_delete_text (GTK_EDITABLE (chooser_entry),
664                             pos, cursor_pos);
665   gtk_editable_insert_text (GTK_EDITABLE (chooser_entry),
666                             common_prefix, -1,
667                             &pos);
668   chooser_entry->in_change = FALSE;
669
670   gtk_editable_set_position (GTK_EDITABLE (chooser_entry), pos);
671 }
672
673 static void
674 gtk_file_chooser_entry_grab_focus (GtkWidget *widget)
675 {
676   GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->grab_focus (widget);
677   _gtk_file_chooser_entry_select_filename (GTK_FILE_CHOOSER_ENTRY (widget));
678 }
679
680 static void
681 start_explicit_completion (GtkFileChooserEntry *chooser_entry)
682 {
683   RefreshStatus status;
684   gboolean is_error;
685   char *text;
686
687   text = gtk_editable_get_chars (GTK_EDITABLE (chooser_entry),
688                                  0, gtk_editable_get_position (GTK_EDITABLE (chooser_entry)));
689   status = refresh_current_folder_and_file_part (chooser_entry, text);
690   g_free (text);
691
692   is_error = FALSE;
693
694   switch (status)
695     {
696     case REFRESH_OK:
697       g_assert (chooser_entry->current_folder_file != NULL);
698
699       if (chooser_entry->current_folder_loaded)
700         explicitly_complete (chooser_entry);
701       else
702         {
703           chooser_entry->load_complete_action = LOAD_COMPLETE_EXPLICIT_COMPLETION;
704         }
705
706       break;
707
708     case REFRESH_INVALID_INPUT:
709       is_error = TRUE;
710       break;
711
712     case REFRESH_INCOMPLETE_HOSTNAME:
713       is_error = TRUE;
714       break;
715
716     case REFRESH_NONEXISTENT:
717       is_error = TRUE;
718       break;
719
720     case REFRESH_NOT_LOCAL:
721       is_error = TRUE;
722       break;
723
724     default:
725       g_assert_not_reached ();
726       return;
727     }
728
729   if (is_error)
730     {
731       g_assert (chooser_entry->current_folder_file == NULL);
732
733       beep (chooser_entry);
734       chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
735     }
736 }
737
738 static gboolean
739 gtk_file_chooser_entry_key_press_event (GtkWidget *widget,
740                                         GdkEventKey *event)
741 {
742   GtkFileChooserEntry *chooser_entry;
743   GtkEditable *editable;
744   GdkModifierType state;
745   gboolean control_pressed;
746
747   chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
748   editable = GTK_EDITABLE (widget);
749
750   if (!chooser_entry->eat_tabs)
751     return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->key_press_event (widget, event);
752
753   control_pressed = FALSE;
754
755   if (gtk_get_current_event_state (&state))
756     {
757       if ((state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK)
758         control_pressed = TRUE;
759     }
760
761   /* This is a bit evil -- it makes Tab never leave the entry. It basically
762    * makes it 'safe' for people to hit. */
763   if (event->keyval == GDK_KEY_Tab && !control_pressed)
764     {
765       gint start, end;
766
767       gtk_editable_get_selection_bounds (editable, &start, &end);
768       
769       if (start != end)
770         gtk_editable_set_position (editable, MAX (start, end));
771       else
772         start_explicit_completion (chooser_entry);
773
774       return TRUE;
775      }
776
777   return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->key_press_event (widget, event);
778
779 }
780
781 static gboolean
782 gtk_file_chooser_entry_focus_out_event (GtkWidget     *widget,
783                                         GdkEventFocus *event)
784 {
785   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
786
787   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
788  
789   return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->focus_out_event (widget, event);
790 }
791
792 static void
793 commit_completion_and_refresh (GtkFileChooserEntry *chooser_entry)
794 {
795   /* Here we ignore the result of refresh_current_folder_and_file_part(); there is nothing we can do with it */
796   refresh_current_folder_and_file_part (chooser_entry, gtk_entry_get_text (GTK_ENTRY (chooser_entry)));
797 }
798
799 static void
800 gtk_file_chooser_entry_activate (GtkEntry *entry)
801 {
802   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (entry);
803
804   commit_completion_and_refresh (chooser_entry);
805   GTK_ENTRY_CLASS (_gtk_file_chooser_entry_parent_class)->activate (entry);
806 }
807
808 static void
809 discard_completion_store (GtkFileChooserEntry *chooser_entry)
810 {
811   if (!chooser_entry->completion_store)
812     return;
813
814   gtk_entry_completion_set_model (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)), NULL);
815   gtk_entry_completion_set_inline_completion (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)), FALSE);
816   g_object_unref (chooser_entry->completion_store);
817   chooser_entry->completion_store = NULL;
818 }
819
820 static gboolean
821 completion_store_set (GtkFileSystemModel  *model,
822                       GFile               *file,
823                       GFileInfo           *info,
824                       int                  column,
825                       GValue              *value,
826                       gpointer             data)
827 {
828   GtkFileChooserEntry *chooser_entry = data;
829
830   const char *prefix = "";
831   const char *suffix = "";
832
833   switch (column)
834     {
835     case FILE_COLUMN:
836       g_value_set_object (value, file);
837       break;
838     case FULL_PATH_COLUMN:
839       prefix = chooser_entry->dir_part;
840       /* fall through */
841     case DISPLAY_NAME_COLUMN:
842       if (_gtk_file_info_consider_as_directory (info))
843         suffix = G_DIR_SEPARATOR_S;
844
845       g_value_take_string (value, g_strconcat (
846               prefix,
847               g_file_info_get_display_name (info),
848               suffix,
849               NULL));
850       break;
851     default:
852       g_assert_not_reached ();
853       break;
854     }
855
856   return TRUE;
857 }
858
859 /* Fills the completion store from the contents of the current folder */
860 static void
861 populate_completion_store (GtkFileChooserEntry *chooser_entry)
862 {
863   discard_completion_store (chooser_entry);
864
865   chooser_entry->completion_store = GTK_TREE_MODEL (
866       _gtk_file_system_model_new_for_directory (chooser_entry->current_folder_file,
867                                                 "standard::name,standard::display-name,standard::type",
868                                                 completion_store_set,
869                                                 chooser_entry,
870                                                 N_COLUMNS,
871                                                 G_TYPE_STRING,
872                                                 G_TYPE_STRING,
873                                                 G_TYPE_FILE));
874   g_signal_connect (chooser_entry->completion_store, "finished-loading",
875                     G_CALLBACK (finished_loading_cb), chooser_entry);
876
877   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (chooser_entry->completion_store),
878                                         DISPLAY_NAME_COLUMN, GTK_SORT_ASCENDING);
879
880   gtk_entry_completion_set_model (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)),
881                                   chooser_entry->completion_store);
882 }
883
884 /* When we finish loading the current folder, this function should get called to
885  * perform the deferred explicit completion.
886  */
887 static void
888 perform_load_complete_action (GtkFileChooserEntry *chooser_entry)
889 {
890   switch (chooser_entry->load_complete_action)
891     {
892     case LOAD_COMPLETE_NOTHING:
893       break;
894
895     case LOAD_COMPLETE_EXPLICIT_COMPLETION:
896       explicitly_complete (chooser_entry);
897       break;
898
899     default:
900       g_assert_not_reached ();
901     }
902
903 }
904
905 /* Callback when the current folder finishes loading */
906 static void
907 finished_loading_cb (GtkFileSystemModel  *model,
908                      GError              *error,
909                      GtkFileChooserEntry *chooser_entry)
910 {
911   GtkEntryCompletion *completion;
912
913   chooser_entry->current_folder_loaded = TRUE;
914
915   if (error)
916     {
917       LoadCompleteAction old_load_complete_action;
918
919       old_load_complete_action = chooser_entry->load_complete_action;
920
921       discard_completion_store (chooser_entry);
922       clear_completions (chooser_entry);
923
924       if (old_load_complete_action == LOAD_COMPLETE_EXPLICIT_COMPLETION)
925         {
926           /* Since this came from explicit user action (Tab completion), we'll present errors visually */
927
928           beep (chooser_entry);
929         }
930
931       return;
932     }
933
934   perform_load_complete_action (chooser_entry);
935
936   gtk_widget_set_tooltip_text (GTK_WIDGET (chooser_entry), NULL);
937
938   completion = gtk_entry_get_completion (GTK_ENTRY (chooser_entry));
939   gtk_entry_completion_set_inline_completion (completion, TRUE);
940   gtk_entry_completion_complete (completion);
941   gtk_entry_completion_insert_prefix (completion);
942 }
943
944 static RefreshStatus
945 reload_current_folder (GtkFileChooserEntry *chooser_entry,
946                        GFile               *folder_file)
947 {
948   g_assert (folder_file != NULL);
949
950   if (chooser_entry->current_folder_file
951       && g_file_equal (folder_file, chooser_entry->current_folder_file))
952     return REFRESH_OK;
953
954   if (chooser_entry->current_folder_file)
955     {
956       discard_loading_and_current_folder_file (chooser_entry);
957     }
958   
959   if (chooser_entry->local_only
960       && !g_file_is_native (folder_file))
961     return REFRESH_NOT_LOCAL;
962
963   chooser_entry->current_folder_file = g_object_ref (folder_file);
964   chooser_entry->current_folder_loaded = FALSE;
965
966   populate_completion_store (chooser_entry);
967
968   return REFRESH_OK;
969 }
970
971 static RefreshStatus
972 refresh_current_folder_and_file_part (GtkFileChooserEntry *chooser_entry,
973                                       const gchar *        text)
974 {
975   GFile *folder_file;
976   gchar *file_part;
977   gsize total_len, file_part_len;
978   gint file_part_pos;
979   GError *error;
980   RefreshStatus result;
981
982   error = NULL;
983   if (!gtk_file_chooser_entry_parse (chooser_entry,
984                                      text, &folder_file, &file_part, &error))
985     {
986       folder_file = g_object_ref (chooser_entry->base_folder);
987
988       if (g_error_matches (error, GTK_FILE_CHOOSER_ERROR, GTK_FILE_CHOOSER_ERROR_NONEXISTENT))
989         result = REFRESH_NONEXISTENT;
990       else
991         result = REFRESH_INVALID_INPUT;
992
993       if (error)
994         g_error_free (error);
995
996       file_part = g_strdup ("");
997       file_part_pos = -1;
998     }
999   else
1000     {
1001       g_assert (folder_file != NULL);
1002
1003       file_part_len = strlen (file_part);
1004       total_len = strlen (text);
1005       if (total_len > file_part_len)
1006         file_part_pos = g_utf8_strlen (text, total_len - file_part_len);
1007       else
1008         file_part_pos = 0;
1009
1010       result = REFRESH_OK;
1011     }
1012
1013   g_free (chooser_entry->file_part);
1014   g_free (chooser_entry->dir_part);
1015
1016   chooser_entry->dir_part = file_part_pos > 0 ? g_strndup (text, file_part_pos) : g_strdup ("");
1017   chooser_entry->file_part = file_part;
1018   chooser_entry->file_part_pos = file_part_pos;
1019
1020   if (result == REFRESH_OK)
1021     {
1022       result = reload_current_folder (chooser_entry, folder_file);
1023     }
1024   else
1025     {
1026       discard_loading_and_current_folder_file (chooser_entry);
1027     }
1028
1029   if (folder_file)
1030     g_object_unref (folder_file);
1031
1032   g_assert (/* we are OK and we have a current folder file and (loading process or folder handle)... */
1033             ((result == REFRESH_OK)
1034              && (chooser_entry->current_folder_file != NULL))
1035             /* ... OR we have an error, and we don't have a current folder file nor a loading process nor a folder handle */
1036             || ((result != REFRESH_OK)
1037                 && (chooser_entry->current_folder_file == NULL)));
1038
1039   return result;
1040 }
1041
1042 #ifdef G_OS_WIN32
1043 static gint
1044 insert_text_callback (GtkFileChooserEntry *chooser_entry,
1045                       const gchar         *new_text,
1046                       gint                 new_text_length,
1047                       gint                *position,
1048                       gpointer             user_data)
1049 {
1050   const gchar *colon = memchr (new_text, ':', new_text_length);
1051   gint i;
1052
1053   /* Disallow these characters altogether */
1054   for (i = 0; i < new_text_length; i++)
1055     {
1056       if (new_text[i] == '<' ||
1057           new_text[i] == '>' ||
1058           new_text[i] == '"' ||
1059           new_text[i] == '|' ||
1060           new_text[i] == '*' ||
1061           new_text[i] == '?')
1062         break;
1063     }
1064
1065   if (i < new_text_length ||
1066       /* Disallow entering text that would cause a colon to be anywhere except
1067        * after a drive letter.
1068        */
1069       (colon != NULL &&
1070        *position + (colon - new_text) != 1) ||
1071       (new_text_length > 0 &&
1072        *position <= 1 &&
1073        gtk_entry_get_text_length (GTK_ENTRY (chooser_entry)) >= 2 &&
1074        gtk_entry_get_text (GTK_ENTRY (chooser_entry))[1] == ':'))
1075     {
1076       gtk_widget_error_bell (GTK_WIDGET (chooser_entry));
1077       g_signal_stop_emission_by_name (chooser_entry, "insert_text");
1078       return FALSE;
1079     }
1080
1081   return TRUE;
1082 }
1083
1084 static void
1085 delete_text_callback (GtkFileChooserEntry *chooser_entry,
1086                       gint                 start_pos,
1087                       gint                 end_pos,
1088                       gpointer             user_data)
1089 {
1090   /* If deleting a drive letter, delete the colon, too */
1091   if (start_pos == 0 && end_pos == 1 &&
1092       gtk_entry_get_text_length (GTK_ENTRY (chooser_entry)) >= 2 &&
1093       gtk_entry_get_text (GTK_ENTRY (chooser_entry))[1] == ':')
1094     {
1095       g_signal_handlers_block_by_func (chooser_entry,
1096                                        G_CALLBACK (delete_text_callback),
1097                                        user_data);
1098       gtk_editable_delete_text (GTK_EDITABLE (chooser_entry), 0, 1);
1099       g_signal_handlers_unblock_by_func (chooser_entry,
1100                                          G_CALLBACK (delete_text_callback),
1101                                          user_data);
1102     }
1103 }
1104 #endif
1105
1106 /**
1107  * _gtk_file_chooser_entry_new:
1108  * @eat_tabs: If %FALSE, allow focus navigation with the tab key.
1109  *
1110  * Creates a new #GtkFileChooserEntry object. #GtkFileChooserEntry
1111  * is an internal implementation widget for the GTK+ file chooser
1112  * which is an entry with completion with respect to a
1113  * #GtkFileSystem object.
1114  *
1115  * Return value: the newly created #GtkFileChooserEntry
1116  **/
1117 GtkWidget *
1118 _gtk_file_chooser_entry_new (gboolean       eat_tabs)
1119 {
1120   GtkFileChooserEntry *chooser_entry;
1121
1122   chooser_entry = g_object_new (GTK_TYPE_FILE_CHOOSER_ENTRY, NULL);
1123   chooser_entry->eat_tabs = (eat_tabs != FALSE);
1124
1125   return GTK_WIDGET (chooser_entry);
1126 }
1127
1128 /**
1129  * _gtk_file_chooser_entry_set_base_folder:
1130  * @chooser_entry: a #GtkFileChooserEntry
1131  * @file: file for a folder in the chooser entries current file system.
1132  *
1133  * Sets the folder with respect to which completions occur.
1134  **/
1135 void
1136 _gtk_file_chooser_entry_set_base_folder (GtkFileChooserEntry *chooser_entry,
1137                                          GFile               *file)
1138 {
1139   if (file)
1140     g_object_ref (file);
1141   else
1142     file = g_file_new_for_path (g_get_home_dir ());
1143
1144   if (g_file_equal (chooser_entry->base_folder, file))
1145     {
1146       g_object_unref (file);
1147       return;
1148     }
1149
1150   if (chooser_entry->base_folder)
1151     g_object_unref (chooser_entry->base_folder);
1152
1153   chooser_entry->base_folder = file;
1154
1155   clear_completions (chooser_entry);
1156 }
1157
1158 /**
1159  * _gtk_file_chooser_entry_get_current_folder:
1160  * @chooser_entry: a #GtkFileChooserEntry
1161  *
1162  * Gets the current folder for the #GtkFileChooserEntry. If the
1163  * user has only entered a filename, this will be in the base folder
1164  * (see _gtk_file_chooser_entry_set_base_folder()), but if the
1165  * user has entered a relative or absolute path, then it will
1166  * be different.  If the user has entered unparsable text, or text which
1167  * the entry cannot handle, this will return %NULL.
1168  *
1169  * Return value: the file for the current folder - you must g_object_unref()
1170  *   the value after use.
1171  **/
1172 GFile *
1173 _gtk_file_chooser_entry_get_current_folder (GtkFileChooserEntry *chooser_entry)
1174 {
1175   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry), NULL);
1176
1177   return gtk_file_chooser_get_directory_for_text (chooser_entry,
1178                                                   gtk_entry_get_text (GTK_ENTRY (chooser_entry)));
1179 }
1180
1181 /**
1182  * _gtk_file_chooser_entry_get_file_part:
1183  * @chooser_entry: a #GtkFileChooserEntry
1184  *
1185  * Gets the non-folder portion of whatever the user has entered
1186  * into the file selector. What is returned is a UTF-8 string,
1187  * and if a filename path is needed, g_file_get_child_for_display_name()
1188  * must be used
1189   *
1190  * Return value: the entered filename - this value is owned by the
1191  *  chooser entry and must not be modified or freed.
1192  **/
1193 const gchar *
1194 _gtk_file_chooser_entry_get_file_part (GtkFileChooserEntry *chooser_entry)
1195 {
1196   const char *last_slash, *text;
1197
1198   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry), NULL);
1199
1200   text = gtk_entry_get_text (GTK_ENTRY (chooser_entry));
1201   last_slash = strrchr (text, G_DIR_SEPARATOR);
1202   if (last_slash)
1203     return last_slash + 1;
1204   else
1205     return text;
1206 }
1207
1208 /**
1209  * _gtk_file_chooser_entry_set_file_part:
1210  * @chooser_entry: a #GtkFileChooserEntry
1211  * @file_part: text to display in the entry, in UTF-8
1212  *
1213  * Sets the current text shown in the file chooser entry.
1214  **/
1215 void
1216 _gtk_file_chooser_entry_set_file_part (GtkFileChooserEntry *chooser_entry,
1217                                        const gchar         *file_part)
1218 {
1219   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1220
1221   chooser_entry->in_change = TRUE;
1222   clear_completions (chooser_entry);
1223   gtk_entry_set_text (GTK_ENTRY (chooser_entry), file_part);
1224   chooser_entry->in_change = FALSE;
1225 }
1226
1227
1228 /**
1229  * _gtk_file_chooser_entry_set_action:
1230  * @chooser_entry: a #GtkFileChooserEntry
1231  * @action: the action which is performed by the file selector using this entry
1232  *
1233  * Sets action which is performed by the file selector using this entry. 
1234  * The #GtkFileChooserEntry will use different completion strategies for 
1235  * different actions.
1236  **/
1237 void
1238 _gtk_file_chooser_entry_set_action (GtkFileChooserEntry *chooser_entry,
1239                                     GtkFileChooserAction action)
1240 {
1241   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1242   
1243   if (chooser_entry->action != action)
1244     {
1245       GtkEntryCompletion *comp;
1246
1247       chooser_entry->action = action;
1248
1249       comp = gtk_entry_get_completion (GTK_ENTRY (chooser_entry));
1250
1251       /* FIXME: do we need to actually set the following? */
1252
1253       switch (action)
1254         {
1255         case GTK_FILE_CHOOSER_ACTION_OPEN:
1256         case GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER:
1257           gtk_entry_completion_set_popup_single_match (comp, FALSE);
1258           break;
1259         case GTK_FILE_CHOOSER_ACTION_SAVE:
1260         case GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER:
1261           gtk_entry_completion_set_popup_single_match (comp, TRUE);
1262           break;
1263         }
1264     }
1265 }
1266
1267
1268 /**
1269  * _gtk_file_chooser_entry_get_action:
1270  * @chooser_entry: a #GtkFileChooserEntry
1271  *
1272  * Gets the action for this entry. 
1273  *
1274  * Returns: the action
1275  **/
1276 GtkFileChooserAction
1277 _gtk_file_chooser_entry_get_action (GtkFileChooserEntry *chooser_entry)
1278 {
1279   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry),
1280                         GTK_FILE_CHOOSER_ACTION_OPEN);
1281   
1282   return chooser_entry->action;
1283 }
1284
1285 gboolean
1286 _gtk_file_chooser_entry_get_is_folder (GtkFileChooserEntry *chooser_entry,
1287                                        GFile               *file)
1288 {
1289   GtkTreeIter iter;
1290   GFileInfo *info;
1291
1292   if (chooser_entry->completion_store == NULL ||
1293       !_gtk_file_system_model_get_iter_for_file (GTK_FILE_SYSTEM_MODEL (chooser_entry->completion_store),
1294                                                  &iter,
1295                                                  file))
1296     return FALSE;
1297
1298   info = _gtk_file_system_model_get_info (GTK_FILE_SYSTEM_MODEL (chooser_entry->completion_store),
1299                                           &iter);
1300
1301   return _gtk_file_info_consider_as_directory (info);
1302 }
1303
1304
1305 /*
1306  * _gtk_file_chooser_entry_select_filename:
1307  * @chooser_entry: a #GtkFileChooserEntry
1308  *
1309  * Selects the filename (without the extension) for user edition.
1310  */
1311 void
1312 _gtk_file_chooser_entry_select_filename (GtkFileChooserEntry *chooser_entry)
1313 {
1314   const gchar *str, *ext;
1315   glong len = -1;
1316
1317   if (chooser_entry->action == GTK_FILE_CHOOSER_ACTION_SAVE)
1318     {
1319       str = gtk_entry_get_text (GTK_ENTRY (chooser_entry));
1320       ext = g_strrstr (str, ".");
1321
1322       if (ext)
1323        len = g_utf8_pointer_to_offset (str, ext);
1324     }
1325
1326   gtk_editable_select_region (GTK_EDITABLE (chooser_entry), 0, (gint) len);
1327 }
1328
1329 void
1330 _gtk_file_chooser_entry_set_local_only (GtkFileChooserEntry *chooser_entry,
1331                                         gboolean             local_only)
1332 {
1333   chooser_entry->local_only = local_only;
1334   clear_completions (chooser_entry);
1335 }
1336
1337 gboolean
1338 _gtk_file_chooser_entry_get_local_only (GtkFileChooserEntry *chooser_entry)
1339 {
1340   return chooser_entry->local_only;
1341 }