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