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