]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilechooserentry.c
GtkFileChooserEntry: fix the computation of 'complete but not unique' and appending...
[~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 #include <string.h>
23
24 #include "gtkalignment.h"
25 #include "gtkcelllayout.h"
26 #include "gtkcellrenderertext.h"
27 #include "gtkentry.h"
28 #include "gtkfilechooserentry.h"
29 #include "gtklabel.h"
30 #include "gtkmain.h"
31 #include "gtkwindow.h"
32 #include "gtkintl.h"
33 #include "gtkalias.h"
34
35 typedef struct _GtkFileChooserEntryClass GtkFileChooserEntryClass;
36
37 #define GTK_FILE_CHOOSER_ENTRY_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_FILE_CHOOSER_ENTRY, GtkFileChooserEntryClass))
38 #define GTK_IS_FILE_CHOOSER_ENTRY_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_FILE_CHOOSER_ENTRY))
39 #define GTK_FILE_CHOOSER_ENTRY_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_FILE_CHOOSER_ENTRY, GtkFileChooserEntryClass))
40
41 struct _GtkFileChooserEntryClass
42 {
43   GtkEntryClass parent_class;
44 };
45
46 /* Action to take when the current folder finishes loading (for explicit or automatic completion) */
47 typedef enum {
48   LOAD_COMPLETE_NOTHING,
49   LOAD_COMPLETE_AUTOCOMPLETE,
50   LOAD_COMPLETE_EXPLICIT_COMPLETION
51 } LoadCompleteAction;
52
53 typedef enum
54 {
55   REFRESH_OK,
56   REFRESH_INVALID_INPUT,
57   REFRESH_INCOMPLETE_HOSTNAME,
58   REFRESH_NONEXISTENT,
59   REFRESH_NOT_LOCAL
60 } RefreshStatus;
61
62 struct _GtkFileChooserEntry
63 {
64   GtkEntry parent_instance;
65
66   GtkFileChooserAction action;
67
68   GtkFileSystem *file_system;
69   GFile *base_folder;
70   GFile *current_folder_file;
71   gchar *file_part;
72   gint file_part_pos;
73
74   /* Folder being loaded or already loaded */
75   GtkFolder *current_folder;
76   GCancellable *load_folder_cancellable;
77
78   LoadCompleteAction load_complete_action;
79
80   GtkListStore *completion_store;
81
82   guint start_autocompletion_idle_id;
83
84   GtkWidget *completion_feedback_window;
85   GtkWidget *completion_feedback_label;
86   guint completion_feedback_timeout_id;
87
88   guint has_completion : 1;
89   guint in_change      : 1;
90   guint eat_tabs       : 1;
91   guint local_only     : 1;
92 };
93
94 enum
95 {
96   DISPLAY_NAME_COLUMN,
97   FILE_COLUMN,
98   N_COLUMNS
99 };
100
101 #define COMPLETION_FEEDBACK_TIMEOUT_MS 2000
102
103 static void     gtk_file_chooser_entry_iface_init     (GtkEditableClass *iface);
104
105 static void     gtk_file_chooser_entry_finalize       (GObject          *object);
106 static void     gtk_file_chooser_entry_dispose        (GObject          *object);
107 static void     gtk_file_chooser_entry_grab_focus     (GtkWidget        *widget);
108 static void     gtk_file_chooser_entry_unmap          (GtkWidget        *widget);
109 static gboolean gtk_file_chooser_entry_focus          (GtkWidget        *widget,
110                                                        GtkDirectionType  direction);
111 static gboolean gtk_file_chooser_entry_focus_out_event (GtkWidget       *widget,
112                                                         GdkEventFocus   *event);
113 static void     gtk_file_chooser_entry_activate       (GtkEntry         *entry);
114 static void     gtk_file_chooser_entry_do_insert_text (GtkEditable *editable,
115                                                        const gchar *new_text,
116                                                        gint         new_text_length,
117                                                        gint        *position);
118 static void     gtk_file_chooser_entry_do_delete_text (GtkEditable *editable,
119                                                        gint         start_pos,
120                                                        gint         end_pos);
121 static void     gtk_file_chooser_entry_set_position (GtkEditable *editable,
122                                                      gint         position);
123 static void     gtk_file_chooser_entry_set_selection_bounds (GtkEditable *editable,
124                                                              gint         start_pos,
125                                                              gint         end_pos);
126
127 #ifdef G_OS_WIN32
128 static gint     insert_text_callback      (GtkFileChooserEntry *widget,
129                                            const gchar         *new_text,
130                                            gint                 new_text_length,
131                                            gint                *position,
132                                            gpointer             user_data);
133 static void     delete_text_callback      (GtkFileChooserEntry *widget,
134                                            gint                 start_pos,
135                                            gint                 end_pos,
136                                            gpointer             user_data);
137 #endif
138
139 static gboolean match_selected_callback   (GtkEntryCompletion  *completion,
140                                            GtkTreeModel        *model,
141                                            GtkTreeIter         *iter,
142                                            GtkFileChooserEntry *chooser_entry);
143 static gboolean completion_match_func     (GtkEntryCompletion  *comp,
144                                            const char          *key,
145                                            GtkTreeIter         *iter,
146                                            gpointer             data);
147 static char    *maybe_append_separator_to_file (GtkFileChooserEntry *chooser_entry,
148                                                 GFile               *file,
149                                                 gchar               *display_name,
150                                                 gboolean            *appended);
151
152 typedef enum {
153   REFRESH_UP_TO_CURSOR_POSITION,
154   REFRESH_WHOLE_TEXT
155 } RefreshMode;
156
157 static RefreshStatus refresh_current_folder_and_file_part (GtkFileChooserEntry *chooser_entry,
158                                                   RefreshMode refresh_mode);
159 static void finished_loading_cb (GtkFolder *folder,
160                                  gpointer   data);
161 static void autocomplete (GtkFileChooserEntry *chooser_entry);
162 static void install_start_autocompletion_idle (GtkFileChooserEntry *chooser_entry);
163 static void remove_completion_feedback (GtkFileChooserEntry *chooser_entry);
164 static void pop_up_completion_feedback (GtkFileChooserEntry *chooser_entry,
165                                         const gchar         *feedback);
166
167 static GtkEditableClass *parent_editable_iface;
168
169 G_DEFINE_TYPE_WITH_CODE (GtkFileChooserEntry, _gtk_file_chooser_entry, GTK_TYPE_ENTRY,
170                          G_IMPLEMENT_INTERFACE (GTK_TYPE_EDITABLE,
171                                                 gtk_file_chooser_entry_iface_init))
172
173 static void
174 _gtk_file_chooser_entry_class_init (GtkFileChooserEntryClass *class)
175 {
176   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
177   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
178   GtkEntryClass *entry_class = GTK_ENTRY_CLASS (class);
179
180   gobject_class->finalize = gtk_file_chooser_entry_finalize;
181   gobject_class->dispose = gtk_file_chooser_entry_dispose;
182
183   widget_class->grab_focus = gtk_file_chooser_entry_grab_focus;
184   widget_class->unmap = gtk_file_chooser_entry_unmap;
185   widget_class->focus = gtk_file_chooser_entry_focus;
186   widget_class->focus_out_event = gtk_file_chooser_entry_focus_out_event;
187
188   entry_class->activate = gtk_file_chooser_entry_activate;
189 }
190
191 static void
192 gtk_file_chooser_entry_iface_init (GtkEditableClass *iface)
193 {
194   parent_editable_iface = g_type_interface_peek_parent (iface);
195
196   iface->do_insert_text = gtk_file_chooser_entry_do_insert_text;
197   iface->do_delete_text = gtk_file_chooser_entry_do_delete_text;
198   iface->set_position = gtk_file_chooser_entry_set_position;
199   iface->set_selection_bounds = gtk_file_chooser_entry_set_selection_bounds;
200 }
201
202 static void
203 _gtk_file_chooser_entry_init (GtkFileChooserEntry *chooser_entry)
204 {
205   GtkEntryCompletion *comp;
206   GtkCellRenderer *cell;
207
208   chooser_entry->local_only = TRUE;
209
210   g_object_set (chooser_entry, "truncate-multiline", TRUE, NULL);
211
212   comp = gtk_entry_completion_new ();
213   gtk_entry_completion_set_popup_single_match (comp, FALSE);
214
215   gtk_entry_completion_set_match_func (comp,
216                                        completion_match_func,
217                                        chooser_entry,
218                                        NULL);
219
220   cell = gtk_cell_renderer_text_new ();
221   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (comp),
222                               cell, TRUE);
223   gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (comp),
224                                  cell,
225                                  "text", 0);
226
227   g_signal_connect (comp, "match-selected",
228                     G_CALLBACK (match_selected_callback), chooser_entry);
229
230   gtk_entry_set_completion (GTK_ENTRY (chooser_entry), comp);
231   g_object_unref (comp);
232
233 #ifdef G_OS_WIN32
234   g_signal_connect (chooser_entry, "insert-text",
235                     G_CALLBACK (insert_text_callback), NULL);
236   g_signal_connect (chooser_entry, "delete-text",
237                     G_CALLBACK (delete_text_callback), NULL);
238 #endif
239 }
240
241 static void
242 gtk_file_chooser_entry_finalize (GObject *object)
243 {
244   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
245
246   if (chooser_entry->base_folder)
247     g_object_unref (chooser_entry->base_folder);
248
249   if (chooser_entry->current_folder)
250     g_object_unref (chooser_entry->current_folder);
251
252   if (chooser_entry->current_folder_file)
253     g_object_unref (chooser_entry->current_folder_file);
254
255   g_free (chooser_entry->file_part);
256
257   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->finalize (object);
258 }
259
260 static void
261 discard_current_folder (GtkFileChooserEntry *chooser_entry)
262 {
263   if (chooser_entry->current_folder)
264     {
265       g_signal_handlers_disconnect_by_func (chooser_entry->current_folder,
266                                             G_CALLBACK (finished_loading_cb), chooser_entry);
267       g_object_unref (chooser_entry->current_folder);
268       chooser_entry->current_folder = NULL;
269     }
270 }
271
272 static void
273 discard_loading_and_current_folder_file (GtkFileChooserEntry *chooser_entry)
274 {
275   if (chooser_entry->load_folder_cancellable)
276     {
277       g_cancellable_cancel (chooser_entry->load_folder_cancellable);
278       chooser_entry->load_folder_cancellable = NULL;
279     }
280
281   if (chooser_entry->current_folder_file)
282     {
283       g_object_unref (chooser_entry->current_folder_file);
284       chooser_entry->current_folder_file = NULL;
285     }
286 }
287
288 static void
289 gtk_file_chooser_entry_dispose (GObject *object)
290 {
291   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
292
293   remove_completion_feedback (chooser_entry);
294   discard_current_folder (chooser_entry);
295   discard_loading_and_current_folder_file (chooser_entry);
296
297   if (chooser_entry->start_autocompletion_idle_id != 0)
298     {
299       g_source_remove (chooser_entry->start_autocompletion_idle_id);
300       chooser_entry->start_autocompletion_idle_id = 0;
301     }
302
303   if (chooser_entry->completion_store)
304     {
305       g_object_unref (chooser_entry->completion_store);
306       chooser_entry->completion_store = NULL;
307     }
308
309   if (chooser_entry->file_system)
310     {
311       g_object_unref (chooser_entry->file_system);
312       chooser_entry->file_system = NULL;
313     }
314
315   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->dispose (object);
316 }
317
318 /* Match functions for the GtkEntryCompletion */
319 static gboolean
320 match_selected_callback (GtkEntryCompletion  *completion,
321                          GtkTreeModel        *model,
322                          GtkTreeIter         *iter,
323                          GtkFileChooserEntry *chooser_entry)
324 {
325   char *display_name;
326   GFile *file;
327   gint pos;
328   gboolean dummy;
329   
330   gtk_tree_model_get (model, iter,
331                       DISPLAY_NAME_COLUMN, &display_name,
332                       FILE_COLUMN, &file,
333                       -1);
334
335   if (!display_name || !file)
336     {
337       /* these shouldn't complain if passed NULL */
338       g_object_unref (file);
339       g_free (display_name);
340       return FALSE;
341     }
342
343   display_name = maybe_append_separator_to_file (chooser_entry, file, display_name, &dummy);
344
345   pos = chooser_entry->file_part_pos;
346
347   /* We don't set in_change here as we want to update the current_folder
348    * variable */
349   gtk_editable_delete_text (GTK_EDITABLE (chooser_entry),
350                             pos, -1);
351   gtk_editable_insert_text (GTK_EDITABLE (chooser_entry),
352                             display_name, -1, 
353                             &pos);
354   gtk_editable_set_position (GTK_EDITABLE (chooser_entry), -1);
355
356   g_object_unref (file);
357   g_free (display_name);
358
359   return TRUE;
360 }
361
362 /* Match function for the GtkEntryCompletion */
363 static gboolean
364 completion_match_func (GtkEntryCompletion *comp,
365                        const char         *key_unused,
366                        GtkTreeIter        *iter,
367                        gpointer            data)
368 {
369   GtkFileChooserEntry *chooser_entry;
370   char *name;
371   gboolean result;
372   char *norm_file_part;
373   char *norm_name;
374
375   chooser_entry = GTK_FILE_CHOOSER_ENTRY (data);
376
377   /* We ignore the key because it is the contents of the entry.  Instead, we
378    * just use our precomputed file_part.
379    */
380   if (!chooser_entry->file_part)
381     {
382       return FALSE;
383     }
384
385   gtk_tree_model_get (GTK_TREE_MODEL (chooser_entry->completion_store), iter, DISPLAY_NAME_COLUMN, &name, -1);
386   if (!name)
387     {
388       return FALSE; /* Uninitialized row, ugh */
389     }
390
391   /* If we have an empty file_part, then we're at the root of a directory.  In
392    * that case, we want to match all non-dot files.  We might want to match
393    * dot_files too if show_hidden is TRUE on the fileselector in the future.
394    */
395   /* Additionally, support for gnome .hidden files would be sweet, too */
396   if (chooser_entry->file_part[0] == '\000')
397     {
398       if (name[0] == '.')
399         result = FALSE;
400       else
401         result = TRUE;
402       g_free (name);
403
404       return result;
405     }
406
407
408   norm_file_part = g_utf8_normalize (chooser_entry->file_part, -1, G_NORMALIZE_ALL);
409   norm_name = g_utf8_normalize (name, -1, G_NORMALIZE_ALL);
410
411 #ifdef G_PLATFORM_WIN32
412   {
413     gchar *temp;
414
415     temp = norm_file_part;
416     norm_file_part = g_utf8_casefold (norm_file_part, -1);
417     g_free (temp);
418
419     temp = norm_name;
420     norm_name = g_utf8_casefold (norm_name, -1);
421     g_free (temp);
422   }
423 #endif
424
425   result = (strncmp (norm_file_part, norm_name, strlen (norm_file_part)) == 0);
426
427   g_free (norm_file_part);
428   g_free (norm_name);
429   g_free (name);
430   
431   return result;
432 }
433
434 static void
435 clear_completions (GtkFileChooserEntry *chooser_entry)
436 {
437   chooser_entry->has_completion = FALSE;
438   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
439
440   remove_completion_feedback (chooser_entry);
441 }
442
443 static void
444 beep (GtkFileChooserEntry *chooser_entry)
445 {
446   gtk_widget_error_bell (GTK_WIDGET (chooser_entry));
447 }
448
449 /* This function will append a directory separator to paths to
450  * display_name iff the path associated with it is a directory.
451  * maybe_append_separator_to_file will g_free the display_name and
452  * return a new one if needed.  Otherwise, it will return the old one.
453  * You should be safe calling
454  *
455  * display_name = maybe_append_separator_to_file (entry, file, display_name, &appended);
456  * ...
457  * g_free (display_name);
458  */
459 static char *
460 maybe_append_separator_to_file (GtkFileChooserEntry *chooser_entry,
461                                 GFile               *file,
462                                 gchar               *display_name,
463                                 gboolean            *appended)
464 {
465   *appended = FALSE;
466
467   if (!g_str_has_suffix (display_name, G_DIR_SEPARATOR_S) && file)
468     {
469       GFileInfo *info;
470
471       info = _gtk_folder_get_info (chooser_entry->current_folder, file);
472
473       if (info)
474         {
475           if (_gtk_file_info_consider_as_directory (info))
476             {
477               gchar *tmp = display_name;
478               display_name = g_strconcat (tmp, G_DIR_SEPARATOR_S, NULL);
479               *appended = TRUE;
480               g_free (tmp);
481             }
482
483           g_object_unref (info);
484         }
485     }
486
487   return display_name;
488 }
489
490 static char *
491 trim_dir_separator_suffix (const char *str)
492 {
493   int len;
494
495   len = strlen (str);
496   if (len > 0 && G_IS_DIR_SEPARATOR (str[len - 1]))
497     return g_strndup (str, len - 1);
498   else
499     return g_strdup (str);
500 }
501
502 /* Determines if the completion model has entries with a common prefix relative
503  * to the current contents of the entry.  Also, if there's one and only one such
504  * path, stores it in unique_path_ret.
505  */
506 static gboolean
507 find_common_prefix (GtkFileChooserEntry *chooser_entry,
508                     gchar               **common_prefix_ret,
509                     GFile               **unique_file_ret,
510                     gboolean             *is_complete_not_unique_ret,
511                     gboolean             *prefix_expands_the_file_part_ret,
512                     GError              **error)
513 {
514   GtkEditable *editable;
515   GtkTreeIter iter;
516   gboolean parsed;
517   gboolean valid;
518   char *text_up_to_cursor;
519   GFile *parsed_folder_file;
520   char *parsed_file_part;
521
522   *common_prefix_ret = NULL;
523   *unique_file_ret = NULL;
524   *is_complete_not_unique_ret = FALSE;
525   *prefix_expands_the_file_part_ret = FALSE;
526
527   editable = GTK_EDITABLE (chooser_entry);
528
529   text_up_to_cursor = gtk_editable_get_chars (editable, 0, gtk_editable_get_position (editable));
530
531   parsed = _gtk_file_system_parse (chooser_entry->file_system,
532                                    chooser_entry->base_folder,
533                                    text_up_to_cursor,
534                                    &parsed_folder_file,
535                                    &parsed_file_part,
536                                    error);
537
538   g_free (text_up_to_cursor);
539
540   if (!parsed)
541     return FALSE;
542
543   g_assert (parsed_folder_file != NULL
544             && chooser_entry->current_folder != 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 (GTK_TREE_MODEL (chooser_entry->completion_store), &iter);
552
553   while (valid)
554     {
555       gchar *display_name;
556       GFile *file;
557
558       gtk_tree_model_get (GTK_TREE_MODEL (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 = trim_dir_separator_suffix (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 (GTK_TREE_MODEL (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 (GTK_TREE_MODEL (chooser_entry->completion_store), &iter);
602
603       while (valid)
604         {
605           gchar *display_name;
606           int len;
607
608           gtk_tree_model_get (GTK_TREE_MODEL (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 (GTK_TREE_MODEL (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 static gboolean
636 char_after_cursor_is_directory_separator (GtkFileChooserEntry *chooser_entry)
637 {
638   int cursor_pos;
639   gboolean result;
640
641   result = FALSE;
642
643   cursor_pos = gtk_editable_get_position (GTK_EDITABLE (chooser_entry));
644   if (cursor_pos < GTK_ENTRY (chooser_entry)->text_length)
645     {
646       char *next_char_str;
647
648       next_char_str = gtk_editable_get_chars (GTK_EDITABLE (chooser_entry), cursor_pos, cursor_pos + 1);
649       if (G_IS_DIR_SEPARATOR (*next_char_str))
650         result = TRUE;
651
652       g_free (next_char_str);
653     }
654
655   return result;
656 }
657
658 typedef enum {
659   INVALID_INPUT,                /* what the user typed is bogus */
660   NO_MATCH,                     /* no matches based on what the user typed */
661   NOTHING_INSERTED_COMPLETE,    /* what the user typed is already completed as far as it will go */
662   NOTHING_INSERTED_UNIQUE,      /* what the user typed is already completed, and is a unique match */
663   COMPLETED,                    /* completion inserted (ambiguous suffix) */
664   COMPLETED_UNIQUE,             /* completion inserted, and it is a complete name and a unique match */
665   COMPLETE_BUT_NOT_UNIQUE       /* completion inserted, it is a complete name but not unique */
666 } CommonPrefixResult;
667
668 /* Finds a common prefix based on the contents of the entry and mandatorily appends it */
669 static CommonPrefixResult
670 append_common_prefix (GtkFileChooserEntry *chooser_entry,
671                       gboolean             highlight,
672                       gboolean             show_errors)
673 {
674   gchar *common_prefix;
675   GFile *unique_file;
676   gboolean is_complete_not_unique;
677   gboolean prefix_expands_the_file_part;
678   GError *error;
679   CommonPrefixResult result;
680   gboolean have_result;
681
682   clear_completions (chooser_entry);
683
684   if (chooser_entry->completion_store == NULL)
685     return NO_MATCH;
686
687   error = NULL;
688   if (!find_common_prefix (chooser_entry, &common_prefix, &unique_file, &is_complete_not_unique, &prefix_expands_the_file_part, &error))
689     {
690       /* If the user types an incomplete hostname ("http://foo" without a slash
691        * after that), it's not an error.  We just don't want to pop up a
692        * meaningless completion window in that state.
693        */
694       if (!g_error_matches (error, GTK_FILE_CHOOSER_ERROR, GTK_FILE_CHOOSER_ERROR_INCOMPLETE_HOSTNAME)
695           && show_errors)
696         {
697           beep (chooser_entry);
698           pop_up_completion_feedback (chooser_entry, _("Invalid path"));
699         }
700
701       g_error_free (error);
702
703       return INVALID_INPUT;
704     }
705
706   have_result = FALSE;
707
708   if (unique_file)
709     {
710       if (!char_after_cursor_is_directory_separator (chooser_entry))
711         {
712           gboolean appended;
713
714           common_prefix = maybe_append_separator_to_file (chooser_entry,
715                                                           unique_file,
716                                                           common_prefix,
717                                                           &appended);
718           if (appended)
719             prefix_expands_the_file_part = TRUE;
720         }
721
722       g_object_unref (unique_file);
723
724       if (prefix_expands_the_file_part)
725         result = COMPLETED_UNIQUE;
726       else
727         result = NOTHING_INSERTED_UNIQUE;
728
729       have_result = TRUE;
730     }
731   else
732     {
733       if (is_complete_not_unique)
734         {
735           result = COMPLETE_BUT_NOT_UNIQUE;
736           have_result = TRUE;
737         }
738     }
739
740   if (common_prefix)
741     {
742       gint cursor_pos;
743       gint common_prefix_len;
744       gint pos;
745
746       cursor_pos = gtk_editable_get_position (GTK_EDITABLE (chooser_entry));
747       common_prefix_len = g_utf8_strlen (common_prefix, -1);
748
749       pos = chooser_entry->file_part_pos;
750
751       if (prefix_expands_the_file_part)
752         {
753           chooser_entry->in_change = TRUE;
754           gtk_editable_delete_text (GTK_EDITABLE (chooser_entry),
755                                     pos, cursor_pos);
756           gtk_editable_insert_text (GTK_EDITABLE (chooser_entry),
757                                     common_prefix, -1, 
758                                     &pos);
759           chooser_entry->in_change = FALSE;
760
761           if (highlight)
762             {
763               gtk_editable_select_region (GTK_EDITABLE (chooser_entry),
764                                           cursor_pos,
765                                           pos); /* equivalent to cursor_pos + common_prefix_len); */
766               chooser_entry->has_completion = TRUE;
767             }
768           else
769             gtk_editable_set_position (GTK_EDITABLE (chooser_entry), pos);
770         }
771       else if (!have_result)
772         {
773           result = NOTHING_INSERTED_COMPLETE;
774           have_result = TRUE;
775         }
776
777       g_free (common_prefix);
778
779       if (have_result)
780         return result;
781       else
782         return COMPLETED;
783     }
784   else
785     {
786       if (have_result)
787         return result;
788       else
789         return NO_MATCH;
790     }
791 }
792
793 static void
794 gtk_file_chooser_entry_do_insert_text (GtkEditable *editable,
795                                        const gchar *new_text,
796                                        gint         new_text_length,
797                                        gint        *position)
798 {
799   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (editable);
800   gint old_text_len;
801   gint insert_pos;
802
803   old_text_len = GTK_ENTRY (chooser_entry)->text_length;
804   insert_pos = *position;
805
806   parent_editable_iface->do_insert_text (editable, new_text, new_text_length, position);
807
808   if (chooser_entry->in_change)
809     return;
810
811   remove_completion_feedback (chooser_entry);
812
813   if ((chooser_entry->action == GTK_FILE_CHOOSER_ACTION_OPEN
814        || chooser_entry->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
815       && insert_pos == old_text_len)
816     install_start_autocompletion_idle (chooser_entry);
817 }
818
819 static void
820 clear_completions_if_not_in_change (GtkFileChooserEntry *chooser_entry)
821 {
822   if (chooser_entry->in_change)
823     return;
824
825   clear_completions (chooser_entry);
826 }
827
828 static void
829 gtk_file_chooser_entry_do_delete_text (GtkEditable *editable,
830                                        gint         start_pos,
831                                        gint         end_pos)
832 {
833   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (editable);
834
835   parent_editable_iface->do_delete_text (editable, start_pos, end_pos);
836
837   clear_completions_if_not_in_change (chooser_entry);
838 }
839
840 static void
841 gtk_file_chooser_entry_set_position (GtkEditable *editable,
842                                      gint         position)
843 {
844   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (editable);
845
846   parent_editable_iface->set_position (editable, position);
847
848   clear_completions_if_not_in_change (chooser_entry);
849 }
850
851 static void
852 gtk_file_chooser_entry_set_selection_bounds (GtkEditable *editable,
853                                              gint         start_pos,
854                                              gint         end_pos)
855 {
856   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (editable);
857
858   parent_editable_iface->set_selection_bounds (editable, start_pos, end_pos);
859
860   clear_completions_if_not_in_change (chooser_entry);
861 }
862
863 static void
864 gtk_file_chooser_entry_grab_focus (GtkWidget *widget)
865 {
866   GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->grab_focus (widget);
867   _gtk_file_chooser_entry_select_filename (GTK_FILE_CHOOSER_ENTRY (widget));
868 }
869
870 static void
871 gtk_file_chooser_entry_unmap (GtkWidget *widget)
872 {
873   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
874
875   remove_completion_feedback (chooser_entry);
876
877   GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->unmap (widget);
878 }
879
880 static gboolean
881 completion_feedback_window_expose_event_cb (GtkWidget      *widget,
882                                             GdkEventExpose *event,
883                                             gpointer        data)
884 {
885   /* Stolen from gtk_tooltip_paint_window() */
886
887   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (data);
888
889   gtk_paint_flat_box (chooser_entry->completion_feedback_window->style,
890                       chooser_entry->completion_feedback_window->window,
891                       GTK_STATE_NORMAL,
892                       GTK_SHADOW_OUT,
893                       NULL,
894                       chooser_entry->completion_feedback_window,
895                       "tooltip",
896                       0, 0,
897                       chooser_entry->completion_feedback_window->allocation.width,
898                       chooser_entry->completion_feedback_window->allocation.height);
899
900   return FALSE;
901 }
902
903 static void
904 set_invisible_mouse_cursor (GdkWindow *window)
905 {
906   GdkDisplay *display;
907   GdkCursor *cursor;
908
909   display = gdk_drawable_get_display (window);
910   cursor = gdk_cursor_new_for_display (display, GDK_BLANK_CURSOR);
911
912   gdk_window_set_cursor (window, cursor);
913
914   gdk_cursor_unref (cursor);
915 }
916
917 static void
918 completion_feedback_window_realize_cb (GtkWidget *widget,
919                                        gpointer data)
920 {
921   /* We hide the mouse cursor inside the completion feedback window, since
922    * GtkEntry hides the cursor when the user types.  We don't want the cursor to
923    * come back if the completion feedback ends up where the mouse is.
924    */
925   set_invisible_mouse_cursor (widget->window);
926 }
927
928 static void
929 create_completion_feedback_window (GtkFileChooserEntry *chooser_entry)
930 {
931   /* Stolen from gtk_tooltip_init() */
932
933   GtkWidget *alignment;
934
935   chooser_entry->completion_feedback_window = gtk_window_new (GTK_WINDOW_POPUP);
936   gtk_window_set_type_hint (GTK_WINDOW (chooser_entry->completion_feedback_window),
937                             GDK_WINDOW_TYPE_HINT_TOOLTIP);
938   gtk_widget_set_app_paintable (chooser_entry->completion_feedback_window, TRUE);
939   gtk_window_set_resizable (GTK_WINDOW (chooser_entry->completion_feedback_window), FALSE);
940   gtk_widget_set_name (chooser_entry->completion_feedback_window, "gtk-tooltip");
941
942   alignment = gtk_alignment_new (0.5, 0.5, 1.0, 1.0);
943   gtk_alignment_set_padding (GTK_ALIGNMENT (alignment),
944                              chooser_entry->completion_feedback_window->style->ythickness,
945                              chooser_entry->completion_feedback_window->style->ythickness,
946                              chooser_entry->completion_feedback_window->style->xthickness,
947                              chooser_entry->completion_feedback_window->style->xthickness);
948   gtk_container_add (GTK_CONTAINER (chooser_entry->completion_feedback_window), alignment);
949   gtk_widget_show (alignment);
950
951   g_signal_connect (chooser_entry->completion_feedback_window, "expose-event",
952                     G_CALLBACK (completion_feedback_window_expose_event_cb), chooser_entry);
953   g_signal_connect (chooser_entry->completion_feedback_window, "realize",
954                     G_CALLBACK (completion_feedback_window_realize_cb), chooser_entry);
955   /* FIXME: connect to motion-notify-event, and *show* the cursor when the mouse moves */
956
957   chooser_entry->completion_feedback_label = gtk_label_new (NULL);
958   gtk_container_add (GTK_CONTAINER (alignment), chooser_entry->completion_feedback_label);
959   gtk_widget_show (chooser_entry->completion_feedback_label);
960 }
961
962 static gboolean
963 completion_feedback_timeout_cb (gpointer data)
964 {
965   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (data);
966
967   chooser_entry->completion_feedback_timeout_id = 0;
968
969   remove_completion_feedback (chooser_entry);
970   return FALSE;
971 }
972
973 static void
974 install_completion_feedback_timer (GtkFileChooserEntry *chooser_entry)
975 {
976   if (chooser_entry->completion_feedback_timeout_id != 0)
977     g_source_remove (chooser_entry->completion_feedback_timeout_id);
978
979   chooser_entry->completion_feedback_timeout_id = gdk_threads_add_timeout (COMPLETION_FEEDBACK_TIMEOUT_MS,
980                                                                            completion_feedback_timeout_cb,
981                                                                            chooser_entry);
982 }
983
984 /* Gets the x position of the text cursor in the entry, in widget coordinates */
985 static void
986 get_entry_cursor_x (GtkFileChooserEntry *chooser_entry,
987                     gint                *x_ret)
988 {
989   /* FIXME: see the docs for gtk_entry_get_layout_offsets().  As an exercise for
990    * the reader, you have to implement support for the entry's scroll offset and
991    * RTL layouts and all the fancy Pango stuff.
992    */
993
994   PangoLayout *layout;
995   gint layout_x, layout_y;
996   gint layout_index;
997   PangoRectangle strong_pos;
998
999   layout = gtk_entry_get_layout (GTK_ENTRY (chooser_entry));
1000
1001   gtk_entry_get_layout_offsets (GTK_ENTRY (chooser_entry), &layout_x, &layout_y);
1002
1003   layout_index = gtk_entry_text_index_to_layout_index (GTK_ENTRY (chooser_entry),
1004                                                        GTK_ENTRY (chooser_entry)->current_pos);
1005
1006   pango_layout_get_cursor_pos (layout, layout_index, &strong_pos, NULL);
1007
1008   *x_ret = layout_x + strong_pos.x / PANGO_SCALE;
1009 }
1010
1011 static void
1012 show_completion_feedback_window (GtkFileChooserEntry *chooser_entry)
1013 {
1014   /* More or less stolen from gtk_tooltip_position() */
1015
1016   GtkRequisition feedback_req;
1017   gint entry_x, entry_y;
1018   gint cursor_x;
1019   GtkAllocation *entry_allocation;
1020   int feedback_x, feedback_y;
1021
1022   gtk_widget_size_request (chooser_entry->completion_feedback_window, &feedback_req);
1023
1024   gdk_window_get_origin (GTK_WIDGET (chooser_entry)->window, &entry_x, &entry_y);
1025   entry_allocation = &(GTK_WIDGET (chooser_entry)->allocation);
1026
1027   get_entry_cursor_x (chooser_entry, &cursor_x);
1028
1029   /* FIXME: fit to the screen if we bump on the screen's edge */
1030   feedback_x = entry_x + cursor_x + entry_allocation->height / 2; /* cheap "half M-width" */
1031   feedback_y = entry_y + (entry_allocation->height - feedback_req.height) / 2;
1032
1033   gtk_window_move (GTK_WINDOW (chooser_entry->completion_feedback_window), feedback_x, feedback_y);
1034   gtk_widget_show (chooser_entry->completion_feedback_window);
1035
1036   install_completion_feedback_timer (chooser_entry);
1037 }
1038
1039 static void
1040 pop_up_completion_feedback (GtkFileChooserEntry *chooser_entry,
1041                             const gchar         *feedback)
1042 {
1043   if (chooser_entry->completion_feedback_window == NULL)
1044     create_completion_feedback_window (chooser_entry);
1045
1046   gtk_label_set_text (GTK_LABEL (chooser_entry->completion_feedback_label), feedback);
1047
1048   show_completion_feedback_window (chooser_entry);
1049 }
1050
1051 static void
1052 remove_completion_feedback (GtkFileChooserEntry *chooser_entry)
1053 {
1054   if (chooser_entry->completion_feedback_window)
1055     gtk_widget_destroy (chooser_entry->completion_feedback_window);
1056
1057   chooser_entry->completion_feedback_window = NULL;
1058   chooser_entry->completion_feedback_label = NULL;
1059
1060   if (chooser_entry->completion_feedback_timeout_id != 0)
1061     {
1062       g_source_remove (chooser_entry->completion_feedback_timeout_id);
1063       chooser_entry->completion_feedback_timeout_id = 0;
1064     }
1065 }
1066
1067 static void
1068 explicitly_complete (GtkFileChooserEntry *chooser_entry)
1069 {
1070   CommonPrefixResult result;
1071
1072   g_assert (chooser_entry->current_folder != NULL);
1073   g_assert (_gtk_folder_is_finished_loading (chooser_entry->current_folder));
1074
1075   /* FIXME: see what Emacs does in case there is no common prefix, or there is more than one match:
1076    *
1077    * - If there is a common prefix, insert it (done)
1078    * - If there is no common prefix, pop up the suggestion window
1079    * - If there are no matches at all, beep and bring up a tooltip (done)
1080    * - If the suggestion window is already up, scroll it
1081    */
1082   result = append_common_prefix (chooser_entry, FALSE, TRUE);
1083
1084   switch (result)
1085     {
1086     case INVALID_INPUT:
1087       /* We already beeped in append_common_prefix(); do nothing here */
1088       break;
1089
1090     case NO_MATCH:
1091       beep (chooser_entry);
1092       /* translators: this text is shown when there are no completions 
1093        * for something the user typed in a file chooser entry
1094        */
1095       pop_up_completion_feedback (chooser_entry, _("No match"));
1096       break;
1097
1098     case NOTHING_INSERTED_COMPLETE:
1099       /* FIXME: pop up the suggestion window or scroll it */
1100       break;
1101
1102     case NOTHING_INSERTED_UNIQUE:
1103       /* translators: this text is shown when there is exactly one completion 
1104        * for something the user typed in a file chooser entry
1105        */
1106       pop_up_completion_feedback (chooser_entry, _("Sole completion"));
1107       break;
1108
1109     case COMPLETED:
1110       /* Nothing to do */
1111       break;
1112
1113     case COMPLETED_UNIQUE:
1114       /* Nothing to do */
1115       break;
1116
1117     case COMPLETE_BUT_NOT_UNIQUE:
1118       /* translators: this text is shown when the text in a file chooser
1119        * entry is a complete filename, but could be continued to find
1120        * a longer match
1121        */
1122       pop_up_completion_feedback (chooser_entry, _("Complete, but not unique"));
1123       break;
1124
1125     default:
1126       g_assert_not_reached ();
1127     }
1128 }
1129
1130 static void
1131 start_explicit_completion (GtkFileChooserEntry *chooser_entry)
1132 {
1133   RefreshStatus status;
1134   gboolean is_error;
1135   char *feedback_msg;
1136
1137   status = refresh_current_folder_and_file_part (chooser_entry, REFRESH_UP_TO_CURSOR_POSITION);
1138
1139   is_error = FALSE;
1140
1141   switch (status)
1142     {
1143     case REFRESH_OK:
1144       g_assert (chooser_entry->current_folder_file != NULL);
1145
1146       if (chooser_entry->current_folder && _gtk_folder_is_finished_loading (chooser_entry->current_folder))
1147         explicitly_complete (chooser_entry);
1148       else
1149         {
1150           chooser_entry->load_complete_action = LOAD_COMPLETE_EXPLICIT_COMPLETION;
1151
1152           /* Translators: this text is shown while the system is searching
1153            * for possible completions for filenames in a file chooser entry. */
1154           pop_up_completion_feedback (chooser_entry, _("Completing..."));
1155         }
1156
1157       break;
1158
1159     case REFRESH_INVALID_INPUT:
1160       is_error = TRUE;
1161       /* Translators: this is shown in the feedback for Tab-completion in a file
1162        * chooser's text entry, when the user enters an invalid path. */
1163       feedback_msg = _("Invalid path");
1164       break;
1165
1166     case REFRESH_INCOMPLETE_HOSTNAME:
1167       is_error = TRUE;
1168
1169       if (chooser_entry->local_only)
1170         {
1171           /* hostnames in a local_only file chooser?  user error */
1172
1173           /* Translators: this is shown in the feedback for Tab-completion in a
1174            * file chooser's text entry when the user enters something like
1175            * "sftp://blahblah" in an app that only supports local filenames. */
1176           feedback_msg = _("Only local files may be selected");
1177         }
1178       else
1179         {
1180           /* Another option is to complete the hostname based on the remote volumes that are mounted */
1181
1182           /* Translators: this is shown in the feedback for Tab-completion in a
1183            * file chooser's text entry when the user hasn't entered the first '/'
1184            * after a hostname and yet hits Tab (such as "sftp://blahblah[Tab]") */
1185           feedback_msg = _("Incomplete hostname; end it with '/'");
1186         }
1187
1188       break;
1189
1190     case REFRESH_NONEXISTENT:
1191       is_error = TRUE;
1192
1193       /* Translators: this is shown in the feedback for Tab-completion in a file
1194        * chooser's text entry when the user enters a path that does not exist
1195        * and then hits Tab */
1196       feedback_msg = _("Path does not exist");
1197       break;
1198
1199     case REFRESH_NOT_LOCAL:
1200       is_error = TRUE;
1201       feedback_msg = _("Only local files may be selected");
1202       break;
1203
1204     default:
1205       g_assert_not_reached ();
1206       return;
1207     }
1208
1209   if (is_error)
1210     {
1211       g_assert (chooser_entry->current_folder_file == NULL);
1212
1213       beep (chooser_entry);
1214       pop_up_completion_feedback (chooser_entry, feedback_msg);
1215       chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
1216     }
1217 }
1218
1219 static gboolean
1220 gtk_file_chooser_entry_focus (GtkWidget        *widget,
1221                               GtkDirectionType  direction)
1222 {
1223   GtkFileChooserEntry *chooser_entry;
1224   GtkEditable *editable;
1225   GtkEntry *entry;
1226   GdkModifierType state;
1227   gboolean control_pressed;
1228
1229   chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
1230   editable = GTK_EDITABLE (widget);
1231   entry = GTK_ENTRY (widget);
1232
1233   if (!chooser_entry->eat_tabs)
1234     return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->focus (widget, direction);
1235
1236   control_pressed = FALSE;
1237
1238   if (gtk_get_current_event_state (&state))
1239     {
1240       if ((state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK)
1241         control_pressed = TRUE;
1242     }
1243
1244   /* This is a bit evil -- it makes Tab never leave the entry. It basically
1245    * makes it 'safe' for people to hit. */
1246   if ((direction == GTK_DIR_TAB_FORWARD) &&
1247       (GTK_WIDGET_HAS_FOCUS (widget)) &&
1248       (! control_pressed))
1249     {
1250       if (chooser_entry->has_completion)
1251         gtk_editable_set_position (editable, entry->text_length);
1252       else
1253         start_explicit_completion (chooser_entry);
1254
1255       return TRUE;
1256     }
1257   else
1258     return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->focus (widget, direction);
1259 }
1260
1261 static gboolean
1262 gtk_file_chooser_entry_focus_out_event (GtkWidget     *widget,
1263                                         GdkEventFocus *event)
1264 {
1265   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
1266
1267   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
1268  
1269   return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->focus_out_event (widget, event);
1270 }
1271
1272 static void
1273 commit_completion_and_refresh (GtkFileChooserEntry *chooser_entry)
1274 {
1275   if (chooser_entry->has_completion)
1276     {
1277       gtk_editable_set_position (GTK_EDITABLE (chooser_entry),
1278                                  GTK_ENTRY (chooser_entry)->text_length);
1279     }
1280
1281   /* Here we ignore the result of refresh_current_folder_and_file_part(); there is nothing we can do with it */
1282   refresh_current_folder_and_file_part (chooser_entry, REFRESH_WHOLE_TEXT);
1283 }
1284
1285 static void
1286 gtk_file_chooser_entry_activate (GtkEntry *entry)
1287 {
1288   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (entry);
1289
1290   commit_completion_and_refresh (chooser_entry);
1291   GTK_ENTRY_CLASS (_gtk_file_chooser_entry_parent_class)->activate (entry);
1292 }
1293
1294 static void
1295 discard_completion_store (GtkFileChooserEntry *chooser_entry)
1296 {
1297   if (!chooser_entry->completion_store)
1298     return;
1299
1300   gtk_entry_completion_set_model (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)), NULL);
1301   g_object_unref (chooser_entry->completion_store);
1302   chooser_entry->completion_store = NULL;
1303 }
1304
1305 /* Fills the completion store from the contents of the current folder */
1306 static void
1307 populate_completion_store (GtkFileChooserEntry *chooser_entry)
1308 {
1309   GSList *files;
1310   GSList *tmp_list;
1311
1312   discard_completion_store (chooser_entry);
1313
1314   files = _gtk_folder_list_children (chooser_entry->current_folder);
1315
1316   chooser_entry->completion_store = gtk_list_store_new (N_COLUMNS,
1317                                                         G_TYPE_STRING,
1318                                                         G_TYPE_FILE);
1319
1320   for (tmp_list = files; tmp_list; tmp_list = tmp_list->next)
1321     {
1322       GFileInfo *info;
1323       GFile *file;
1324
1325       file = tmp_list->data;
1326
1327       info = _gtk_folder_get_info (chooser_entry->current_folder, file);
1328
1329       if (info)
1330         {
1331           gchar *display_name = g_strdup (g_file_info_get_display_name (info));
1332           GtkTreeIter iter;
1333           gboolean dummy;
1334
1335           display_name = maybe_append_separator_to_file (chooser_entry, file, display_name, &dummy);
1336
1337           gtk_list_store_append (chooser_entry->completion_store, &iter);
1338           gtk_list_store_set (chooser_entry->completion_store, &iter,
1339                               DISPLAY_NAME_COLUMN, display_name,
1340                               FILE_COLUMN, file,
1341                               -1);
1342
1343           g_object_unref (info);
1344           g_free (display_name);
1345         }
1346     }
1347
1348   g_slist_foreach (files, (GFunc) g_object_unref, NULL);
1349   g_slist_free (files);
1350
1351   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (chooser_entry->completion_store),
1352                                         DISPLAY_NAME_COLUMN, GTK_SORT_ASCENDING);
1353
1354   gtk_entry_completion_set_model (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)),
1355                                   GTK_TREE_MODEL (chooser_entry->completion_store));
1356 }
1357
1358 /* When we finish loading the current folder, this function should get called to
1359  * perform the deferred autocompletion or explicit completion.
1360  */
1361 static void
1362 perform_load_complete_action (GtkFileChooserEntry *chooser_entry)
1363 {
1364   switch (chooser_entry->load_complete_action)
1365     {
1366     case LOAD_COMPLETE_NOTHING:
1367       break;
1368
1369     case LOAD_COMPLETE_AUTOCOMPLETE:
1370       autocomplete (chooser_entry);
1371       break;
1372
1373     case LOAD_COMPLETE_EXPLICIT_COMPLETION:
1374       explicitly_complete (chooser_entry);
1375       break;
1376
1377     default:
1378       g_assert_not_reached ();
1379     }
1380
1381   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
1382 }
1383
1384 static void
1385 finish_folder_load (GtkFileChooserEntry *chooser_entry)
1386 {
1387   populate_completion_store (chooser_entry);
1388   perform_load_complete_action (chooser_entry);
1389
1390   gtk_widget_set_tooltip_text (GTK_WIDGET (chooser_entry), NULL);
1391 }
1392
1393 /* Callback when the current folder finishes loading */
1394 static void
1395 finished_loading_cb (GtkFolder *folder,
1396                      gpointer   data)
1397 {
1398   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (data);
1399
1400   finish_folder_load (chooser_entry);
1401 }
1402
1403 /* Callback when the current folder's handle gets obtained (not necessarily loaded completely) */
1404 static void
1405 load_directory_get_folder_callback (GCancellable  *cancellable,
1406                                     GtkFolder     *folder,
1407                                     const GError  *error,
1408                                     gpointer       data)
1409 {
1410   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
1411   GtkFileChooserEntry *chooser_entry = data;
1412
1413   if (cancellable != chooser_entry->load_folder_cancellable)
1414     goto out;
1415
1416   chooser_entry->load_folder_cancellable = NULL;
1417
1418   if (error)
1419     {
1420       LoadCompleteAction old_load_complete_action;
1421
1422       old_load_complete_action = chooser_entry->load_complete_action;
1423
1424       discard_completion_store (chooser_entry);
1425       clear_completions (chooser_entry);
1426
1427       if (old_load_complete_action == LOAD_COMPLETE_EXPLICIT_COMPLETION)
1428         {
1429           /* Since this came from explicit user action (Tab completion), we'll present errors visually */
1430
1431           beep (chooser_entry);
1432           pop_up_completion_feedback (chooser_entry, error->message);
1433         }
1434
1435       discard_current_folder (chooser_entry);
1436     }
1437
1438   if (cancelled || error)
1439     goto out;
1440
1441   g_assert (folder != NULL);
1442   chooser_entry->current_folder = g_object_ref (folder);
1443
1444   discard_completion_store (chooser_entry);
1445
1446   if (_gtk_folder_is_finished_loading (chooser_entry->current_folder))
1447     finish_folder_load (chooser_entry);
1448   else
1449     g_signal_connect (chooser_entry->current_folder, "finished-loading",
1450                       G_CALLBACK (finished_loading_cb), chooser_entry);
1451
1452 out:
1453   g_object_unref (chooser_entry);
1454   g_object_unref (cancellable);
1455 }
1456
1457 static RefreshStatus
1458 start_loading_current_folder (GtkFileChooserEntry *chooser_entry)
1459 {
1460   if (chooser_entry->file_system == NULL)
1461     return REFRESH_OK;
1462
1463   g_assert (chooser_entry->current_folder_file != NULL);
1464   g_assert (chooser_entry->current_folder == NULL);
1465   g_assert (chooser_entry->load_folder_cancellable == NULL);
1466
1467   if (chooser_entry->local_only
1468       && !g_file_is_native (chooser_entry->current_folder_file))
1469     {
1470       g_object_unref (chooser_entry->current_folder_file);
1471       chooser_entry->current_folder_file = NULL;
1472
1473       return REFRESH_NOT_LOCAL;
1474     }
1475
1476   chooser_entry->load_folder_cancellable =
1477     _gtk_file_system_get_folder (chooser_entry->file_system,
1478                                  chooser_entry->current_folder_file,
1479                                 "standard::name,standard::display-name,standard::type",
1480                                  load_directory_get_folder_callback,
1481                                  g_object_ref (chooser_entry));
1482
1483   return REFRESH_OK;
1484 }
1485
1486 static RefreshStatus
1487 reload_current_folder (GtkFileChooserEntry *chooser_entry,
1488                        GFile               *folder_file,
1489                        gboolean             force_reload)
1490 {
1491   gboolean reload = FALSE;
1492
1493   g_assert (folder_file != NULL);
1494
1495   if (chooser_entry->current_folder_file)
1496     {
1497       if ((!(g_file_equal (folder_file, chooser_entry->current_folder_file)
1498              && chooser_entry->load_folder_cancellable))
1499           || force_reload)
1500         {
1501           reload = TRUE;
1502
1503           discard_current_folder (chooser_entry);
1504           discard_loading_and_current_folder_file (chooser_entry);
1505
1506           chooser_entry->current_folder_file = g_object_ref (folder_file);
1507         }
1508     }
1509   else
1510     {
1511       chooser_entry->current_folder_file = g_object_ref (folder_file);
1512       reload = TRUE;
1513     }
1514
1515   if (reload)
1516     return start_loading_current_folder (chooser_entry);
1517   else
1518     return REFRESH_OK;
1519 }
1520
1521 static RefreshStatus
1522 refresh_current_folder_and_file_part (GtkFileChooserEntry *chooser_entry,
1523                                       RefreshMode          refresh_mode)
1524 {
1525   GtkEditable *editable;
1526   gint end_pos;
1527   gchar *text;
1528   GFile *folder_file;
1529   gchar *file_part;
1530   gsize total_len, file_part_len;
1531   gint file_part_pos;
1532   GError *error;
1533   RefreshStatus result;
1534
1535   editable = GTK_EDITABLE (chooser_entry);
1536
1537   switch (refresh_mode)
1538     {
1539     case REFRESH_UP_TO_CURSOR_POSITION:
1540       end_pos = gtk_editable_get_position (editable);
1541       break;
1542
1543     case REFRESH_WHOLE_TEXT:
1544       end_pos = GTK_ENTRY (chooser_entry)->text_length;
1545       break;
1546
1547     default:
1548       g_assert_not_reached ();
1549       return REFRESH_INVALID_INPUT;
1550     }
1551
1552   text = gtk_editable_get_chars (editable, 0, end_pos);
1553
1554   error = NULL;
1555   if (!chooser_entry->file_system ||
1556       !chooser_entry->base_folder ||
1557       !_gtk_file_system_parse (chooser_entry->file_system,
1558                                chooser_entry->base_folder, text,
1559                                &folder_file, &file_part, &error))
1560     {
1561       if (g_error_matches (error, GTK_FILE_CHOOSER_ERROR, GTK_FILE_CHOOSER_ERROR_INCOMPLETE_HOSTNAME))
1562         {
1563           folder_file = NULL;
1564           result = REFRESH_INCOMPLETE_HOSTNAME;
1565         }
1566       else
1567         {
1568           folder_file = (chooser_entry->base_folder) ? g_object_ref (chooser_entry->base_folder) : NULL;
1569
1570           if (g_error_matches (error, GTK_FILE_CHOOSER_ERROR, GTK_FILE_CHOOSER_ERROR_NONEXISTENT))
1571             result = REFRESH_NONEXISTENT;
1572           else
1573             result = REFRESH_INVALID_INPUT;
1574         }
1575
1576       if (error)
1577         g_error_free (error);
1578
1579       file_part = g_strdup ("");
1580       file_part_pos = -1;
1581     }
1582   else
1583     {
1584       g_assert (folder_file != NULL);
1585
1586       file_part_len = strlen (file_part);
1587       total_len = strlen (text);
1588       if (total_len > file_part_len)
1589         file_part_pos = g_utf8_strlen (text, total_len - file_part_len);
1590       else
1591         file_part_pos = 0;
1592
1593       result = REFRESH_OK;
1594     }
1595
1596   g_free (text);
1597
1598   g_free (chooser_entry->file_part);
1599
1600   chooser_entry->file_part = file_part;
1601   chooser_entry->file_part_pos = file_part_pos;
1602
1603   if (result == REFRESH_OK)
1604     {
1605       result = reload_current_folder (chooser_entry, folder_file, file_part_pos == -1);
1606     }
1607   else
1608     {
1609       discard_current_folder (chooser_entry);
1610       discard_loading_and_current_folder_file (chooser_entry);
1611     }
1612
1613   if (folder_file)
1614     g_object_unref (folder_file);
1615
1616   g_assert (/* we are OK and we have a current folder file and (loading process or folder handle)... */
1617             ((result == REFRESH_OK)
1618              && (chooser_entry->current_folder_file != NULL)
1619              && (((chooser_entry->load_folder_cancellable != NULL) && (chooser_entry->current_folder == NULL))
1620                  || ((chooser_entry->load_folder_cancellable == NULL) && (chooser_entry->current_folder != NULL))))
1621             /* ... OR we have an error, and we don't have a current folder file nor a loading process nor a folder handle */
1622             || ((result != REFRESH_OK)
1623                 && (chooser_entry->current_folder_file == NULL)
1624                 && (chooser_entry->load_folder_cancellable == NULL)
1625                 && (chooser_entry->current_folder == NULL)));
1626
1627   return result;
1628 }
1629
1630 static void
1631 autocomplete (GtkFileChooserEntry *chooser_entry)
1632 {
1633   g_assert (chooser_entry->current_folder != NULL);
1634   g_assert (_gtk_folder_is_finished_loading (chooser_entry->current_folder));
1635   g_assert (gtk_editable_get_position (GTK_EDITABLE (chooser_entry)) == GTK_ENTRY (chooser_entry)->text_length);
1636
1637   append_common_prefix (chooser_entry, TRUE, FALSE);
1638 }
1639
1640 static void
1641 start_autocompletion (GtkFileChooserEntry *chooser_entry)
1642 {
1643   RefreshStatus status;
1644
1645   status = refresh_current_folder_and_file_part (chooser_entry, REFRESH_UP_TO_CURSOR_POSITION);
1646
1647   switch (status)
1648     {
1649     case REFRESH_OK:
1650       g_assert (chooser_entry->current_folder_file != NULL);
1651
1652       if (chooser_entry->current_folder && _gtk_folder_is_finished_loading (chooser_entry->current_folder))
1653         autocomplete (chooser_entry);
1654       else
1655         chooser_entry->load_complete_action = LOAD_COMPLETE_AUTOCOMPLETE;
1656
1657       break;
1658
1659     case REFRESH_INVALID_INPUT:
1660     case REFRESH_INCOMPLETE_HOSTNAME:
1661     case REFRESH_NONEXISTENT:
1662     case REFRESH_NOT_LOCAL:
1663       /* We don't beep or anything, since this is autocompletion - the user
1664        * didn't request any action explicitly.
1665        */
1666       break;
1667
1668     default:
1669       g_assert_not_reached ();
1670     }
1671 }
1672
1673 static gboolean
1674 start_autocompletion_idle_handler (gpointer data)
1675 {
1676   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (data);
1677
1678   start_autocompletion (chooser_entry);
1679
1680   chooser_entry->start_autocompletion_idle_id = 0;
1681
1682   return FALSE;
1683 }
1684
1685 static void
1686 install_start_autocompletion_idle (GtkFileChooserEntry *chooser_entry)
1687 {
1688   if (chooser_entry->start_autocompletion_idle_id != 0)
1689     return;
1690
1691   chooser_entry->start_autocompletion_idle_id = gdk_threads_add_idle (start_autocompletion_idle_handler, chooser_entry);
1692 }
1693
1694 #ifdef G_OS_WIN32
1695 static gint
1696 insert_text_callback (GtkFileChooserEntry *chooser_entry,
1697                       const gchar         *new_text,
1698                       gint                 new_text_length,
1699                       gint                *position,
1700                       gpointer             user_data)
1701 {
1702   const gchar *colon = memchr (new_text, ':', new_text_length);
1703   gint i;
1704
1705   /* Disallow these characters altogether */
1706   for (i = 0; i < new_text_length; i++)
1707     {
1708       if (new_text[i] == '<' ||
1709           new_text[i] == '>' ||
1710           new_text[i] == '"' ||
1711           new_text[i] == '|' ||
1712           new_text[i] == '*' ||
1713           new_text[i] == '?')
1714         break;
1715     }
1716
1717   if (i < new_text_length ||
1718       /* Disallow entering text that would cause a colon to be anywhere except
1719        * after a drive letter.
1720        */
1721       (colon != NULL &&
1722        *position + (colon - new_text) != 1) ||
1723       (new_text_length > 0 &&
1724        *position <= 1 &&
1725        GTK_ENTRY (chooser_entry)->text_length >= 2 &&
1726        gtk_entry_get_text (GTK_ENTRY (chooser_entry))[1] == ':'))
1727     {
1728       gtk_widget_error_bell (GTK_WIDGET (chooser_entry));
1729       g_signal_stop_emission_by_name (chooser_entry, "insert_text");
1730       return FALSE;
1731     }
1732
1733   return TRUE;
1734 }
1735
1736 static void
1737 delete_text_callback (GtkFileChooserEntry *chooser_entry,
1738                       gint                 start_pos,
1739                       gint                 end_pos,
1740                       gpointer             user_data)
1741 {
1742   /* If deleting a drive letter, delete the colon, too */
1743   if (start_pos == 0 && end_pos == 1 &&
1744       GTK_ENTRY (chooser_entry)->text_length >= 2 &&
1745       gtk_entry_get_text (GTK_ENTRY (chooser_entry))[1] == ':')
1746     {
1747       g_signal_handlers_block_by_func (chooser_entry,
1748                                        G_CALLBACK (delete_text_callback),
1749                                        user_data);
1750       gtk_editable_delete_text (GTK_EDITABLE (chooser_entry), 0, 1);
1751       g_signal_handlers_unblock_by_func (chooser_entry,
1752                                          G_CALLBACK (delete_text_callback),
1753                                          user_data);
1754     }
1755 }
1756 #endif
1757
1758 /**
1759  * _gtk_file_chooser_entry_new:
1760  * @eat_tabs: If %FALSE, allow focus navigation with the tab key.
1761  *
1762  * Creates a new #GtkFileChooserEntry object. #GtkFileChooserEntry
1763  * is an internal implementation widget for the GTK+ file chooser
1764  * which is an entry with completion with respect to a
1765  * #GtkFileSystem object.
1766  *
1767  * Return value: the newly created #GtkFileChooserEntry
1768  **/
1769 GtkWidget *
1770 _gtk_file_chooser_entry_new (gboolean eat_tabs)
1771 {
1772   GtkFileChooserEntry *chooser_entry;
1773
1774   chooser_entry = g_object_new (GTK_TYPE_FILE_CHOOSER_ENTRY, NULL);
1775   chooser_entry->eat_tabs = (eat_tabs != FALSE);
1776
1777   return GTK_WIDGET (chooser_entry);
1778 }
1779
1780 /**
1781  * _gtk_file_chooser_entry_set_file_system:
1782  * @chooser_entry: a #GtkFileChooser
1783  * @file_system: an object implementing #GtkFileSystem
1784  *
1785  * Sets the file system for @chooser_entry.
1786  **/
1787 void
1788 _gtk_file_chooser_entry_set_file_system (GtkFileChooserEntry *chooser_entry,
1789                                          GtkFileSystem       *file_system)
1790 {
1791   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1792   g_return_if_fail (GTK_IS_FILE_SYSTEM (file_system));
1793
1794   if (file_system != chooser_entry->file_system)
1795     {
1796       if (chooser_entry->file_system)
1797         g_object_unref (chooser_entry->file_system);
1798
1799       chooser_entry->file_system = g_object_ref (file_system);
1800     }
1801 }
1802
1803 /**
1804  * _gtk_file_chooser_entry_set_base_folder:
1805  * @chooser_entry: a #GtkFileChooserEntry
1806  * @file: file for a folder in the chooser entries current file system.
1807  *
1808  * Sets the folder with respect to which completions occur.
1809  **/
1810 void
1811 _gtk_file_chooser_entry_set_base_folder (GtkFileChooserEntry *chooser_entry,
1812                                          GFile               *file)
1813 {
1814   if (chooser_entry->base_folder)
1815     g_object_unref (chooser_entry->base_folder);
1816
1817   chooser_entry->base_folder = file;
1818
1819   if (chooser_entry->base_folder)
1820     g_object_ref (chooser_entry->base_folder);
1821
1822   clear_completions (chooser_entry);
1823   _gtk_file_chooser_entry_select_filename (chooser_entry);
1824 }
1825
1826 /**
1827  * _gtk_file_chooser_entry_get_current_folder:
1828  * @chooser_entry: a #GtkFileChooserEntry
1829  *
1830  * Gets the current folder for the #GtkFileChooserEntry. If the
1831  * user has only entered a filename, this will be in the base folder
1832  * (see _gtk_file_chooser_entry_set_base_folder()), but if the
1833  * user has entered a relative or absolute path, then it will
1834  * be different.  If the user has entered unparsable text, or text which
1835  * the entry cannot handle, this will return %NULL.
1836  *
1837  * Return value: the file for the current folder - this value is owned by the
1838  *  chooser entry and must not be modified or freed.
1839  **/
1840 GFile *
1841 _gtk_file_chooser_entry_get_current_folder (GtkFileChooserEntry *chooser_entry)
1842 {
1843   commit_completion_and_refresh (chooser_entry);
1844   return chooser_entry->current_folder_file;
1845 }
1846
1847 /**
1848  * _gtk_file_chooser_entry_get_file_part:
1849  * @chooser_entry: a #GtkFileChooserEntry
1850  *
1851  * Gets the non-folder portion of whatever the user has entered
1852  * into the file selector. What is returned is a UTF-8 string,
1853  * and if a filename path is needed, g_file_get_child_for_display_name()
1854  * must be used
1855   *
1856  * Return value: the entered filename - this value is owned by the
1857  *  chooser entry and must not be modified or freed.
1858  **/
1859 const gchar *
1860 _gtk_file_chooser_entry_get_file_part (GtkFileChooserEntry *chooser_entry)
1861 {
1862   commit_completion_and_refresh (chooser_entry);
1863   return chooser_entry->file_part;
1864 }
1865
1866 /**
1867  * _gtk_file_chooser_entry_set_file_part:
1868  * @chooser_entry: a #GtkFileChooserEntry
1869  * @file_part: text to display in the entry, in UTF-8
1870  *
1871  * Sets the current text shown in the file chooser entry.
1872  **/
1873 void
1874 _gtk_file_chooser_entry_set_file_part (GtkFileChooserEntry *chooser_entry,
1875                                        const gchar         *file_part)
1876 {
1877   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1878
1879   chooser_entry->in_change = TRUE;
1880   clear_completions (chooser_entry);
1881   gtk_entry_set_text (GTK_ENTRY (chooser_entry), file_part);
1882   chooser_entry->in_change = FALSE;
1883 }
1884
1885
1886 /**
1887  * _gtk_file_chooser_entry_set_action:
1888  * @chooser_entry: a #GtkFileChooserEntry
1889  * @action: the action which is performed by the file selector using this entry
1890  *
1891  * Sets action which is performed by the file selector using this entry. 
1892  * The #GtkFileChooserEntry will use different completion strategies for 
1893  * different actions.
1894  **/
1895 void
1896 _gtk_file_chooser_entry_set_action (GtkFileChooserEntry *chooser_entry,
1897                                     GtkFileChooserAction action)
1898 {
1899   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1900   
1901   if (chooser_entry->action != action)
1902     {
1903       GtkEntryCompletion *comp;
1904
1905       chooser_entry->action = action;
1906
1907       comp = gtk_entry_get_completion (GTK_ENTRY (chooser_entry));
1908
1909       /* FIXME: do we need to actually set the following? */
1910
1911       switch (action)
1912         {
1913         case GTK_FILE_CHOOSER_ACTION_OPEN:
1914         case GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER:
1915           gtk_entry_completion_set_popup_single_match (comp, FALSE);
1916           break;
1917         case GTK_FILE_CHOOSER_ACTION_SAVE:
1918         case GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER:
1919           gtk_entry_completion_set_popup_single_match (comp, TRUE);
1920           break;
1921         }
1922     }
1923 }
1924
1925
1926 /**
1927  * _gtk_file_chooser_entry_get_action:
1928  * @chooser_entry: a #GtkFileChooserEntry
1929  *
1930  * Gets the action for this entry. 
1931  *
1932  * Returns: the action
1933  **/
1934 GtkFileChooserAction
1935 _gtk_file_chooser_entry_get_action (GtkFileChooserEntry *chooser_entry)
1936 {
1937   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry),
1938                         GTK_FILE_CHOOSER_ACTION_OPEN);
1939   
1940   return chooser_entry->action;
1941 }
1942
1943 gboolean
1944 _gtk_file_chooser_entry_get_is_folder (GtkFileChooserEntry *chooser_entry,
1945                                        GFile               *file)
1946 {
1947   gboolean retval = FALSE;
1948
1949   if (chooser_entry->current_folder)
1950     {
1951       GFileInfo *file_info;
1952
1953       file_info = _gtk_folder_get_info (chooser_entry->current_folder, file);
1954
1955       if (file_info)
1956         {
1957           retval = _gtk_file_info_consider_as_directory (file_info);
1958           g_object_unref (file_info);
1959         }
1960     }
1961
1962   return retval;
1963 }
1964
1965
1966 /*
1967  * _gtk_file_chooser_entry_select_filename:
1968  * @chooser_entry: a #GtkFileChooserEntry
1969  *
1970  * Selects the filename (without the extension) for user edition.
1971  */
1972 void
1973 _gtk_file_chooser_entry_select_filename (GtkFileChooserEntry *chooser_entry)
1974 {
1975   const gchar *str, *ext;
1976   glong len = -1;
1977
1978   if (chooser_entry->action == GTK_FILE_CHOOSER_ACTION_SAVE)
1979     {
1980       str = gtk_entry_get_text (GTK_ENTRY (chooser_entry));
1981       ext = g_strrstr (str, ".");
1982
1983       if (ext)
1984        len = g_utf8_pointer_to_offset (str, ext);
1985     }
1986
1987   gtk_editable_select_region (GTK_EDITABLE (chooser_entry), 0, (gint) len);
1988 }
1989
1990 void
1991 _gtk_file_chooser_entry_set_local_only (GtkFileChooserEntry *chooser_entry,
1992                                         gboolean             local_only)
1993 {
1994   chooser_entry->local_only = local_only;
1995   clear_completions (chooser_entry);
1996 }
1997
1998 gboolean
1999 _gtk_file_chooser_entry_get_local_only (GtkFileChooserEntry *chooser_entry)
2000 {
2001   return chooser_entry->local_only;
2002 }