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