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