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