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