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