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