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