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