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