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