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