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