]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilechooserentry.c
filechooserentry: Add gtk_file_chooser_entry_get_completion_text()
[~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
101 #ifdef G_OS_WIN32
102 static gint     insert_text_callback      (GtkFileChooserEntry *widget,
103                                            const gchar         *new_text,
104                                            gint                 new_text_length,
105                                            gint                *position,
106                                            gpointer             user_data);
107 static void     delete_text_callback      (GtkFileChooserEntry *widget,
108                                            gint                 start_pos,
109                                            gint                 end_pos,
110                                            gpointer             user_data);
111 #endif
112
113 static gboolean match_selected_callback   (GtkEntryCompletion  *completion,
114                                            GtkTreeModel        *model,
115                                            GtkTreeIter         *iter,
116                                            GtkFileChooserEntry *chooser_entry);
117 static gboolean completion_match_func     (GtkEntryCompletion  *comp,
118                                            const char          *key,
119                                            GtkTreeIter         *iter,
120                                            gpointer             data);
121
122 static RefreshStatus refresh_current_folder_and_file_part (GtkFileChooserEntry *chooser_entry,
123                                                            const char          *text);
124 static void finished_loading_cb (GtkFileSystemModel  *model,
125                                  GError              *error,
126                                  GtkFileChooserEntry *chooser_entry);
127
128 G_DEFINE_TYPE (GtkFileChooserEntry, _gtk_file_chooser_entry, GTK_TYPE_ENTRY)
129
130 static char *
131 gtk_file_chooser_entry_get_completion_text (GtkFileChooserEntry *chooser_entry)
132 {
133   GtkEditable *editable = GTK_EDITABLE (chooser_entry);
134   int start, end;
135
136   gtk_editable_get_selection_bounds (editable, &start, &end);
137   return gtk_editable_get_chars (editable, 0, MIN (start, end));
138 }
139
140 static void
141 gtk_file_chooser_entry_dispatch_properties_changed (GObject     *object,
142                                                     guint        n_pspecs,
143                                                     GParamSpec **pspecs)
144 {
145   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
146   guint i;
147
148   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->dispatch_properties_changed (object, n_pspecs, pspecs);
149
150   /* What we are after: The text in front of the cursor was modified.
151    * Unfortunately, there's no other way to catch this. */
152
153   if (chooser_entry->in_change)
154     return;
155
156   for (i = 0; i < n_pspecs; i++)
157     {
158       if (pspecs[i]->name == I_("cursor-position") ||
159           pspecs[i]->name == I_("selection-bound") ||
160           pspecs[i]->name == I_("text"))
161         {
162           char *text;
163
164           chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
165
166           text = gtk_file_chooser_entry_get_completion_text (chooser_entry);
167           refresh_current_folder_and_file_part (chooser_entry, text);
168           g_free (text);
169
170           break;
171         }
172     }
173 }
174
175 static void
176 _gtk_file_chooser_entry_class_init (GtkFileChooserEntryClass *class)
177 {
178   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
179   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
180
181   gobject_class->finalize = gtk_file_chooser_entry_finalize;
182   gobject_class->dispose = gtk_file_chooser_entry_dispose;
183   gobject_class->dispatch_properties_changed = gtk_file_chooser_entry_dispatch_properties_changed;
184
185   widget_class->grab_focus = gtk_file_chooser_entry_grab_focus;
186   widget_class->key_press_event = gtk_file_chooser_entry_key_press_event;
187   widget_class->focus_out_event = gtk_file_chooser_entry_focus_out_event;
188 }
189
190 static void
191 _gtk_file_chooser_entry_init (GtkFileChooserEntry *chooser_entry)
192 {
193   GtkEntryCompletion *comp;
194   GtkCellRenderer *cell;
195
196   chooser_entry->local_only = TRUE;
197   chooser_entry->base_folder = g_file_new_for_path (g_get_home_dir ());
198
199   g_object_set (chooser_entry, "truncate-multiline", TRUE, NULL);
200
201   comp = gtk_entry_completion_new ();
202   gtk_entry_completion_set_popup_single_match (comp, FALSE);
203   /* see docs for gtk_entry_completion_set_text_column() */
204   g_object_set (comp, "text-column", FULL_PATH_COLUMN, NULL);
205
206   gtk_entry_completion_set_match_func (comp,
207                                        completion_match_func,
208                                        chooser_entry,
209                                        NULL);
210
211   cell = gtk_cell_renderer_text_new ();
212   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (comp),
213                               cell, TRUE);
214   gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (comp),
215                                  cell,
216                                  "text", DISPLAY_NAME_COLUMN);
217
218   g_signal_connect (comp, "match-selected",
219                     G_CALLBACK (match_selected_callback), chooser_entry);
220
221   gtk_entry_set_completion (GTK_ENTRY (chooser_entry), comp);
222   g_object_unref (comp);
223
224 #ifdef G_OS_WIN32
225   g_signal_connect (chooser_entry, "insert-text",
226                     G_CALLBACK (insert_text_callback), NULL);
227   g_signal_connect (chooser_entry, "delete-text",
228                     G_CALLBACK (delete_text_callback), NULL);
229 #endif
230 }
231
232 static void
233 gtk_file_chooser_entry_finalize (GObject *object)
234 {
235   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
236
237   g_object_unref (chooser_entry->base_folder);
238
239   if (chooser_entry->current_folder_file)
240     g_object_unref (chooser_entry->current_folder_file);
241
242   g_free (chooser_entry->dir_part);
243   g_free (chooser_entry->file_part);
244
245   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->finalize (object);
246 }
247
248 static void
249 discard_loading_and_current_folder_file (GtkFileChooserEntry *chooser_entry)
250 {
251   if (chooser_entry->current_folder_file)
252     {
253       g_object_unref (chooser_entry->current_folder_file);
254       chooser_entry->current_folder_file = NULL;
255     }
256 }
257
258 static void
259 gtk_file_chooser_entry_dispose (GObject *object)
260 {
261   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
262
263   discard_loading_and_current_folder_file (chooser_entry);
264
265   if (chooser_entry->completion_store)
266     {
267       g_object_unref (chooser_entry->completion_store);
268       chooser_entry->completion_store = NULL;
269     }
270
271   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->dispose (object);
272 }
273
274 /* Match functions for the GtkEntryCompletion */
275 static gboolean
276 match_selected_callback (GtkEntryCompletion  *completion,
277                          GtkTreeModel        *model,
278                          GtkTreeIter         *iter,
279                          GtkFileChooserEntry *chooser_entry)
280 {
281   char *path;
282   
283   gtk_tree_model_get (model, iter,
284                       FULL_PATH_COLUMN, &path,
285                       -1);
286
287   /* We don't set in_change here as we want to update the current_folder
288    * variable */
289   gtk_editable_delete_text (GTK_EDITABLE (chooser_entry),
290                             0,
291                             gtk_editable_get_position (GTK_EDITABLE (chooser_entry)));
292   gtk_editable_insert_text (GTK_EDITABLE (chooser_entry),
293                             path,
294                             0,
295                             NULL); 
296
297   g_free (path);
298
299   return TRUE;
300 }
301
302 /* Match function for the GtkEntryCompletion */
303 static gboolean
304 completion_match_func (GtkEntryCompletion *comp,
305                        const char         *key_unused,
306                        GtkTreeIter        *iter,
307                        gpointer            data)
308 {
309   GtkFileChooserEntry *chooser_entry;
310   char *name = NULL;
311   gboolean result;
312   char *norm_file_part;
313   char *norm_name;
314
315   chooser_entry = GTK_FILE_CHOOSER_ENTRY (data);
316
317   /* We ignore the key because it is the contents of the entry.  Instead, we
318    * just use our precomputed file_part.
319    */
320   if (!chooser_entry->file_part)
321     {
322       return FALSE;
323     }
324
325   gtk_tree_model_get (chooser_entry->completion_store, iter, DISPLAY_NAME_COLUMN, &name, -1);
326   if (!name)
327     {
328       return FALSE; /* Uninitialized row, ugh */
329     }
330
331   /* If we have an empty file_part, then we're at the root of a directory.  In
332    * that case, we want to match all non-dot files.  We might want to match
333    * dot_files too if show_hidden is TRUE on the fileselector in the future.
334    */
335   /* Additionally, support for gnome .hidden files would be sweet, too */
336   if (chooser_entry->file_part[0] == '\000')
337     {
338       if (name[0] == '.')
339         result = FALSE;
340       else
341         result = TRUE;
342       g_free (name);
343
344       return result;
345     }
346
347
348   norm_file_part = g_utf8_normalize (chooser_entry->file_part, -1, G_NORMALIZE_ALL);
349   norm_name = g_utf8_normalize (name, -1, G_NORMALIZE_ALL);
350
351 #ifdef G_PLATFORM_WIN32
352   {
353     gchar *temp;
354
355     temp = norm_file_part;
356     norm_file_part = g_utf8_casefold (norm_file_part, -1);
357     g_free (temp);
358
359     temp = norm_name;
360     norm_name = g_utf8_casefold (norm_name, -1);
361     g_free (temp);
362   }
363 #endif
364
365   result = (strncmp (norm_file_part, norm_name, strlen (norm_file_part)) == 0);
366
367   g_free (norm_file_part);
368   g_free (norm_name);
369   g_free (name);
370   
371   return result;
372 }
373
374 static void
375 clear_completions (GtkFileChooserEntry *chooser_entry)
376 {
377   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
378 }
379
380 static void
381 beep (GtkFileChooserEntry *chooser_entry)
382 {
383   gtk_widget_error_bell (GTK_WIDGET (chooser_entry));
384 }
385
386 static gboolean
387 is_valid_scheme_character (char c)
388 {
389   return g_ascii_isalnum (c) || c == '+' || c == '-' || c == '.';
390 }
391
392 static gboolean
393 has_uri_scheme (const char *str)
394 {
395   const char *p;
396
397   p = str;
398
399   if (!is_valid_scheme_character (*p))
400     return FALSE;
401
402   do
403     p++;
404   while (is_valid_scheme_character (*p));
405
406   return (strncmp (p, "://", 3) == 0);
407 }
408
409 static GFile *
410 gtk_file_chooser_get_file_for_text (GtkFileChooserEntry *chooser_entry,
411                                     const gchar         *str)
412 {
413   GFile *file;
414
415   if (str[0] == '~' || g_path_is_absolute (str) || has_uri_scheme (str))
416     file = g_file_parse_name (str);
417   else
418     file = g_file_resolve_relative_path (chooser_entry->base_folder, str);
419
420   return file;
421 }
422
423 static GFile *
424 gtk_file_chooser_get_directory_for_text (GtkFileChooserEntry *chooser_entry,
425                                          const char *         text)
426 {
427   GFile *file, *parent;
428
429   file = gtk_file_chooser_get_file_for_text (chooser_entry, text);
430
431   if (text[0] == 0 || text[strlen (text) - 1] == G_DIR_SEPARATOR)
432     return file;
433
434   parent = g_file_get_parent (file);
435   g_object_unref (file);
436
437   return parent;
438 }
439
440 static gboolean
441 gtk_file_chooser_entry_parse (GtkFileChooserEntry  *chooser_entry,
442                               const gchar          *str,
443                               GFile               **folder,
444                               gchar               **file_part,
445                               GError              **error)
446 {
447   GFile *file;
448   gboolean result = FALSE;
449   gboolean is_dir = FALSE;
450   gchar *last_slash = NULL;
451
452   if (str && *str)
453     is_dir = (str [strlen (str) - 1] == G_DIR_SEPARATOR);
454
455   last_slash = strrchr (str, G_DIR_SEPARATOR);
456
457   file = gtk_file_chooser_get_file_for_text (chooser_entry, str);
458
459   if (g_file_equal (chooser_entry->base_folder, file))
460     {
461       /* this is when user types '.', could be the
462        * beginning of a hidden file, ./ or ../
463        */
464       *folder = g_object_ref (file);
465       *file_part = g_strdup (str);
466       result = TRUE;
467     }
468   else if (is_dir)
469     {
470       /* it's a dir, or at least it ends with the dir separator */
471       *folder = g_object_ref (file);
472       *file_part = g_strdup ("");
473       result = TRUE;
474     }
475   else
476     {
477       GFile *parent_file;
478
479       parent_file = g_file_get_parent (file);
480
481       if (!parent_file)
482         {
483           g_set_error (error,
484                        GTK_FILE_CHOOSER_ERROR,
485                        GTK_FILE_CHOOSER_ERROR_NONEXISTENT,
486                        "Could not get parent file");
487           *folder = NULL;
488           *file_part = NULL;
489         }
490       else
491         {
492           *folder = parent_file;
493           result = TRUE;
494
495           if (last_slash)
496             *file_part = g_strdup (last_slash + 1);
497           else
498             *file_part = g_strdup (str);
499         }
500     }
501
502   g_object_unref (file);
503
504   return result;
505 }
506
507 /* Determines if the completion model has entries with a common prefix relative
508  * to the current contents of the entry.  Also, if there's one and only one such
509  * path, stores it in unique_path_ret.
510  */
511 static gboolean
512 find_common_prefix (GtkFileChooserEntry *chooser_entry,
513                     gchar               **common_prefix_ret,
514                     GFile               **unique_file_ret,
515                     gboolean             *is_complete_not_unique_ret,
516                     gboolean             *prefix_expands_the_file_part_ret,
517                     GError              **error)
518 {
519   GtkTreeIter iter;
520   gboolean parsed;
521   gboolean valid;
522   char *text_up_to_cursor;
523   GFile *parsed_folder_file;
524   char *parsed_file_part;
525
526   *common_prefix_ret = NULL;
527   *unique_file_ret = NULL;
528   *is_complete_not_unique_ret = FALSE;
529   *prefix_expands_the_file_part_ret = FALSE;
530
531   text_up_to_cursor = gtk_file_chooser_entry_get_completion_text (chooser_entry);
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   if (chooser_entry->current_folder_loaded)
684     explicitly_complete (chooser_entry);
685   else
686     chooser_entry->load_complete_action = LOAD_COMPLETE_EXPLICIT_COMPLETION;
687 }
688
689 static gboolean
690 gtk_file_chooser_entry_key_press_event (GtkWidget *widget,
691                                         GdkEventKey *event)
692 {
693   GtkFileChooserEntry *chooser_entry;
694   GtkEditable *editable;
695   GdkModifierType state;
696   gboolean control_pressed;
697
698   chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
699   editable = GTK_EDITABLE (widget);
700
701   if (!chooser_entry->eat_tabs)
702     return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->key_press_event (widget, event);
703
704   control_pressed = FALSE;
705
706   if (gtk_get_current_event_state (&state))
707     {
708       if ((state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK)
709         control_pressed = TRUE;
710     }
711
712   /* This is a bit evil -- it makes Tab never leave the entry. It basically
713    * makes it 'safe' for people to hit. */
714   if (event->keyval == GDK_KEY_Tab && !control_pressed)
715     {
716       gint start, end;
717
718       gtk_editable_get_selection_bounds (editable, &start, &end);
719       
720       if (start != end)
721         gtk_editable_set_position (editable, MAX (start, end));
722       else
723         start_explicit_completion (chooser_entry);
724
725       return TRUE;
726      }
727
728   return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->key_press_event (widget, event);
729
730 }
731
732 static gboolean
733 gtk_file_chooser_entry_focus_out_event (GtkWidget     *widget,
734                                         GdkEventFocus *event)
735 {
736   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
737
738   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
739  
740   return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->focus_out_event (widget, event);
741 }
742
743 static void
744 discard_completion_store (GtkFileChooserEntry *chooser_entry)
745 {
746   if (!chooser_entry->completion_store)
747     return;
748
749   gtk_entry_completion_set_model (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)), NULL);
750   gtk_entry_completion_set_inline_completion (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)), FALSE);
751   g_object_unref (chooser_entry->completion_store);
752   chooser_entry->completion_store = NULL;
753 }
754
755 static gboolean
756 completion_store_set (GtkFileSystemModel  *model,
757                       GFile               *file,
758                       GFileInfo           *info,
759                       int                  column,
760                       GValue              *value,
761                       gpointer             data)
762 {
763   GtkFileChooserEntry *chooser_entry = data;
764
765   const char *prefix = "";
766   const char *suffix = "";
767
768   switch (column)
769     {
770     case FILE_COLUMN:
771       g_value_set_object (value, file);
772       break;
773     case FULL_PATH_COLUMN:
774       prefix = chooser_entry->dir_part;
775       /* fall through */
776     case DISPLAY_NAME_COLUMN:
777       if (_gtk_file_info_consider_as_directory (info))
778         suffix = G_DIR_SEPARATOR_S;
779
780       g_value_take_string (value, g_strconcat (
781               prefix,
782               g_file_info_get_display_name (info),
783               suffix,
784               NULL));
785       break;
786     default:
787       g_assert_not_reached ();
788       break;
789     }
790
791   return TRUE;
792 }
793
794 /* Fills the completion store from the contents of the current folder */
795 static void
796 populate_completion_store (GtkFileChooserEntry *chooser_entry)
797 {
798   discard_completion_store (chooser_entry);
799
800   chooser_entry->completion_store = GTK_TREE_MODEL (
801       _gtk_file_system_model_new_for_directory (chooser_entry->current_folder_file,
802                                                 "standard::name,standard::display-name,standard::type",
803                                                 completion_store_set,
804                                                 chooser_entry,
805                                                 N_COLUMNS,
806                                                 G_TYPE_STRING,
807                                                 G_TYPE_STRING,
808                                                 G_TYPE_FILE));
809   g_signal_connect (chooser_entry->completion_store, "finished-loading",
810                     G_CALLBACK (finished_loading_cb), chooser_entry);
811
812   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (chooser_entry->completion_store),
813                                         DISPLAY_NAME_COLUMN, GTK_SORT_ASCENDING);
814
815   gtk_entry_completion_set_model (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)),
816                                   chooser_entry->completion_store);
817 }
818
819 /* When we finish loading the current folder, this function should get called to
820  * perform the deferred explicit completion.
821  */
822 static void
823 perform_load_complete_action (GtkFileChooserEntry *chooser_entry)
824 {
825   switch (chooser_entry->load_complete_action)
826     {
827     case LOAD_COMPLETE_NOTHING:
828       break;
829
830     case LOAD_COMPLETE_EXPLICIT_COMPLETION:
831       explicitly_complete (chooser_entry);
832       break;
833
834     default:
835       g_assert_not_reached ();
836     }
837
838 }
839
840 /* Callback when the current folder finishes loading */
841 static void
842 finished_loading_cb (GtkFileSystemModel  *model,
843                      GError              *error,
844                      GtkFileChooserEntry *chooser_entry)
845 {
846   GtkEntryCompletion *completion;
847
848   chooser_entry->current_folder_loaded = TRUE;
849
850   if (error)
851     {
852       LoadCompleteAction old_load_complete_action;
853
854       old_load_complete_action = chooser_entry->load_complete_action;
855
856       discard_completion_store (chooser_entry);
857       clear_completions (chooser_entry);
858
859       if (old_load_complete_action == LOAD_COMPLETE_EXPLICIT_COMPLETION)
860         {
861           /* Since this came from explicit user action (Tab completion), we'll present errors visually */
862
863           beep (chooser_entry);
864         }
865
866       return;
867     }
868
869   perform_load_complete_action (chooser_entry);
870
871   gtk_widget_set_tooltip_text (GTK_WIDGET (chooser_entry), NULL);
872
873   completion = gtk_entry_get_completion (GTK_ENTRY (chooser_entry));
874   gtk_entry_completion_set_inline_completion (completion, TRUE);
875   gtk_entry_completion_complete (completion);
876   gtk_entry_completion_insert_prefix (completion);
877 }
878
879 static RefreshStatus
880 reload_current_folder (GtkFileChooserEntry *chooser_entry,
881                        GFile               *folder_file)
882 {
883   g_assert (folder_file != NULL);
884
885   if (chooser_entry->current_folder_file
886       && g_file_equal (folder_file, chooser_entry->current_folder_file))
887     return REFRESH_OK;
888
889   if (chooser_entry->current_folder_file)
890     {
891       discard_loading_and_current_folder_file (chooser_entry);
892     }
893   
894   if (chooser_entry->local_only
895       && !g_file_is_native (folder_file))
896     return REFRESH_NOT_LOCAL;
897
898   chooser_entry->current_folder_file = g_object_ref (folder_file);
899   chooser_entry->current_folder_loaded = FALSE;
900
901   populate_completion_store (chooser_entry);
902
903   return REFRESH_OK;
904 }
905
906 static RefreshStatus
907 refresh_current_folder_and_file_part (GtkFileChooserEntry *chooser_entry,
908                                       const gchar *        text)
909 {
910   GFile *folder_file;
911   gchar *file_part;
912   gsize total_len, file_part_len;
913   gint file_part_pos;
914   GError *error;
915   RefreshStatus result;
916
917   error = NULL;
918   if (!gtk_file_chooser_entry_parse (chooser_entry,
919                                      text, &folder_file, &file_part, &error))
920     {
921       folder_file = g_object_ref (chooser_entry->base_folder);
922
923       if (g_error_matches (error, GTK_FILE_CHOOSER_ERROR, GTK_FILE_CHOOSER_ERROR_NONEXISTENT))
924         result = REFRESH_NONEXISTENT;
925       else
926         result = REFRESH_INVALID_INPUT;
927
928       if (error)
929         g_error_free (error);
930
931       file_part = g_strdup ("");
932       file_part_pos = -1;
933     }
934   else
935     {
936       g_assert (folder_file != NULL);
937
938       file_part_len = strlen (file_part);
939       total_len = strlen (text);
940       if (total_len > file_part_len)
941         file_part_pos = g_utf8_strlen (text, total_len - file_part_len);
942       else
943         file_part_pos = 0;
944
945       result = REFRESH_OK;
946     }
947
948   g_free (chooser_entry->file_part);
949   g_free (chooser_entry->dir_part);
950
951   chooser_entry->dir_part = file_part_pos > 0 ? g_strndup (text, file_part_pos) : g_strdup ("");
952   chooser_entry->file_part = file_part;
953   chooser_entry->file_part_pos = file_part_pos;
954
955   if (result == REFRESH_OK)
956     {
957       result = reload_current_folder (chooser_entry, folder_file);
958     }
959   else
960     {
961       discard_loading_and_current_folder_file (chooser_entry);
962     }
963
964   if (folder_file)
965     g_object_unref (folder_file);
966
967   g_assert (/* we are OK and we have a current folder file and (loading process or folder handle)... */
968             ((result == REFRESH_OK)
969              && (chooser_entry->current_folder_file != NULL))
970             /* ... OR we have an error, and we don't have a current folder file nor a loading process nor a folder handle */
971             || ((result != REFRESH_OK)
972                 && (chooser_entry->current_folder_file == NULL)));
973
974   return result;
975 }
976
977 #ifdef G_OS_WIN32
978 static gint
979 insert_text_callback (GtkFileChooserEntry *chooser_entry,
980                       const gchar         *new_text,
981                       gint                 new_text_length,
982                       gint                *position,
983                       gpointer             user_data)
984 {
985   const gchar *colon = memchr (new_text, ':', new_text_length);
986   gint i;
987
988   /* Disallow these characters altogether */
989   for (i = 0; i < new_text_length; i++)
990     {
991       if (new_text[i] == '<' ||
992           new_text[i] == '>' ||
993           new_text[i] == '"' ||
994           new_text[i] == '|' ||
995           new_text[i] == '*' ||
996           new_text[i] == '?')
997         break;
998     }
999
1000   if (i < new_text_length ||
1001       /* Disallow entering text that would cause a colon to be anywhere except
1002        * after a drive letter.
1003        */
1004       (colon != NULL &&
1005        *position + (colon - new_text) != 1) ||
1006       (new_text_length > 0 &&
1007        *position <= 1 &&
1008        gtk_entry_get_text_length (GTK_ENTRY (chooser_entry)) >= 2 &&
1009        gtk_entry_get_text (GTK_ENTRY (chooser_entry))[1] == ':'))
1010     {
1011       gtk_widget_error_bell (GTK_WIDGET (chooser_entry));
1012       g_signal_stop_emission_by_name (chooser_entry, "insert_text");
1013       return FALSE;
1014     }
1015
1016   return TRUE;
1017 }
1018
1019 static void
1020 delete_text_callback (GtkFileChooserEntry *chooser_entry,
1021                       gint                 start_pos,
1022                       gint                 end_pos,
1023                       gpointer             user_data)
1024 {
1025   /* If deleting a drive letter, delete the colon, too */
1026   if (start_pos == 0 && end_pos == 1 &&
1027       gtk_entry_get_text_length (GTK_ENTRY (chooser_entry)) >= 2 &&
1028       gtk_entry_get_text (GTK_ENTRY (chooser_entry))[1] == ':')
1029     {
1030       g_signal_handlers_block_by_func (chooser_entry,
1031                                        G_CALLBACK (delete_text_callback),
1032                                        user_data);
1033       gtk_editable_delete_text (GTK_EDITABLE (chooser_entry), 0, 1);
1034       g_signal_handlers_unblock_by_func (chooser_entry,
1035                                          G_CALLBACK (delete_text_callback),
1036                                          user_data);
1037     }
1038 }
1039 #endif
1040
1041 /**
1042  * _gtk_file_chooser_entry_new:
1043  * @eat_tabs: If %FALSE, allow focus navigation with the tab key.
1044  *
1045  * Creates a new #GtkFileChooserEntry object. #GtkFileChooserEntry
1046  * is an internal implementation widget for the GTK+ file chooser
1047  * which is an entry with completion with respect to a
1048  * #GtkFileSystem object.
1049  *
1050  * Return value: the newly created #GtkFileChooserEntry
1051  **/
1052 GtkWidget *
1053 _gtk_file_chooser_entry_new (gboolean       eat_tabs)
1054 {
1055   GtkFileChooserEntry *chooser_entry;
1056
1057   chooser_entry = g_object_new (GTK_TYPE_FILE_CHOOSER_ENTRY, NULL);
1058   chooser_entry->eat_tabs = (eat_tabs != FALSE);
1059
1060   return GTK_WIDGET (chooser_entry);
1061 }
1062
1063 /**
1064  * _gtk_file_chooser_entry_set_base_folder:
1065  * @chooser_entry: a #GtkFileChooserEntry
1066  * @file: file for a folder in the chooser entries current file system.
1067  *
1068  * Sets the folder with respect to which completions occur.
1069  **/
1070 void
1071 _gtk_file_chooser_entry_set_base_folder (GtkFileChooserEntry *chooser_entry,
1072                                          GFile               *file)
1073 {
1074   if (file)
1075     g_object_ref (file);
1076   else
1077     file = g_file_new_for_path (g_get_home_dir ());
1078
1079   if (g_file_equal (chooser_entry->base_folder, file))
1080     {
1081       g_object_unref (file);
1082       return;
1083     }
1084
1085   if (chooser_entry->base_folder)
1086     g_object_unref (chooser_entry->base_folder);
1087
1088   chooser_entry->base_folder = file;
1089
1090   clear_completions (chooser_entry);
1091 }
1092
1093 /**
1094  * _gtk_file_chooser_entry_get_current_folder:
1095  * @chooser_entry: a #GtkFileChooserEntry
1096  *
1097  * Gets the current folder for the #GtkFileChooserEntry. If the
1098  * user has only entered a filename, this will be in the base folder
1099  * (see _gtk_file_chooser_entry_set_base_folder()), but if the
1100  * user has entered a relative or absolute path, then it will
1101  * be different.  If the user has entered unparsable text, or text which
1102  * the entry cannot handle, this will return %NULL.
1103  *
1104  * Return value: the file for the current folder - you must g_object_unref()
1105  *   the value after use.
1106  **/
1107 GFile *
1108 _gtk_file_chooser_entry_get_current_folder (GtkFileChooserEntry *chooser_entry)
1109 {
1110   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry), NULL);
1111
1112   return gtk_file_chooser_get_directory_for_text (chooser_entry,
1113                                                   gtk_entry_get_text (GTK_ENTRY (chooser_entry)));
1114 }
1115
1116 /**
1117  * _gtk_file_chooser_entry_get_file_part:
1118  * @chooser_entry: a #GtkFileChooserEntry
1119  *
1120  * Gets the non-folder portion of whatever the user has entered
1121  * into the file selector. What is returned is a UTF-8 string,
1122  * and if a filename path is needed, g_file_get_child_for_display_name()
1123  * must be used
1124   *
1125  * Return value: the entered filename - this value is owned by the
1126  *  chooser entry and must not be modified or freed.
1127  **/
1128 const gchar *
1129 _gtk_file_chooser_entry_get_file_part (GtkFileChooserEntry *chooser_entry)
1130 {
1131   const char *last_slash, *text;
1132
1133   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry), NULL);
1134
1135   text = gtk_entry_get_text (GTK_ENTRY (chooser_entry));
1136   last_slash = strrchr (text, G_DIR_SEPARATOR);
1137   if (last_slash)
1138     return last_slash + 1;
1139   else
1140     return text;
1141 }
1142
1143 /**
1144  * _gtk_file_chooser_entry_set_file_part:
1145  * @chooser_entry: a #GtkFileChooserEntry
1146  * @file_part: text to display in the entry, in UTF-8
1147  *
1148  * Sets the current text shown in the file chooser entry.
1149  **/
1150 void
1151 _gtk_file_chooser_entry_set_file_part (GtkFileChooserEntry *chooser_entry,
1152                                        const gchar         *file_part)
1153 {
1154   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1155
1156   chooser_entry->in_change = TRUE;
1157   clear_completions (chooser_entry);
1158   gtk_entry_set_text (GTK_ENTRY (chooser_entry), file_part);
1159   chooser_entry->in_change = FALSE;
1160 }
1161
1162
1163 /**
1164  * _gtk_file_chooser_entry_set_action:
1165  * @chooser_entry: a #GtkFileChooserEntry
1166  * @action: the action which is performed by the file selector using this entry
1167  *
1168  * Sets action which is performed by the file selector using this entry. 
1169  * The #GtkFileChooserEntry will use different completion strategies for 
1170  * different actions.
1171  **/
1172 void
1173 _gtk_file_chooser_entry_set_action (GtkFileChooserEntry *chooser_entry,
1174                                     GtkFileChooserAction action)
1175 {
1176   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1177   
1178   if (chooser_entry->action != action)
1179     {
1180       GtkEntryCompletion *comp;
1181
1182       chooser_entry->action = action;
1183
1184       comp = gtk_entry_get_completion (GTK_ENTRY (chooser_entry));
1185
1186       /* FIXME: do we need to actually set the following? */
1187
1188       switch (action)
1189         {
1190         case GTK_FILE_CHOOSER_ACTION_OPEN:
1191         case GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER:
1192           gtk_entry_completion_set_popup_single_match (comp, FALSE);
1193           break;
1194         case GTK_FILE_CHOOSER_ACTION_SAVE:
1195         case GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER:
1196           gtk_entry_completion_set_popup_single_match (comp, TRUE);
1197           break;
1198         }
1199     }
1200 }
1201
1202
1203 /**
1204  * _gtk_file_chooser_entry_get_action:
1205  * @chooser_entry: a #GtkFileChooserEntry
1206  *
1207  * Gets the action for this entry. 
1208  *
1209  * Returns: the action
1210  **/
1211 GtkFileChooserAction
1212 _gtk_file_chooser_entry_get_action (GtkFileChooserEntry *chooser_entry)
1213 {
1214   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry),
1215                         GTK_FILE_CHOOSER_ACTION_OPEN);
1216   
1217   return chooser_entry->action;
1218 }
1219
1220 gboolean
1221 _gtk_file_chooser_entry_get_is_folder (GtkFileChooserEntry *chooser_entry,
1222                                        GFile               *file)
1223 {
1224   GtkTreeIter iter;
1225   GFileInfo *info;
1226
1227   if (chooser_entry->completion_store == NULL ||
1228       !_gtk_file_system_model_get_iter_for_file (GTK_FILE_SYSTEM_MODEL (chooser_entry->completion_store),
1229                                                  &iter,
1230                                                  file))
1231     return FALSE;
1232
1233   info = _gtk_file_system_model_get_info (GTK_FILE_SYSTEM_MODEL (chooser_entry->completion_store),
1234                                           &iter);
1235
1236   return _gtk_file_info_consider_as_directory (info);
1237 }
1238
1239
1240 /*
1241  * _gtk_file_chooser_entry_select_filename:
1242  * @chooser_entry: a #GtkFileChooserEntry
1243  *
1244  * Selects the filename (without the extension) for user edition.
1245  */
1246 void
1247 _gtk_file_chooser_entry_select_filename (GtkFileChooserEntry *chooser_entry)
1248 {
1249   const gchar *str, *ext;
1250   glong len = -1;
1251
1252   if (chooser_entry->action == GTK_FILE_CHOOSER_ACTION_SAVE)
1253     {
1254       str = gtk_entry_get_text (GTK_ENTRY (chooser_entry));
1255       ext = g_strrstr (str, ".");
1256
1257       if (ext)
1258        len = g_utf8_pointer_to_offset (str, ext);
1259     }
1260
1261   gtk_editable_select_region (GTK_EDITABLE (chooser_entry), 0, (gint) len);
1262 }
1263
1264 void
1265 _gtk_file_chooser_entry_set_local_only (GtkFileChooserEntry *chooser_entry,
1266                                         gboolean             local_only)
1267 {
1268   chooser_entry->local_only = local_only;
1269   clear_completions (chooser_entry);
1270 }
1271
1272 gboolean
1273 _gtk_file_chooser_entry_get_local_only (GtkFileChooserEntry *chooser_entry)
1274 {
1275   return chooser_entry->local_only;
1276 }