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