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