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