]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilechooserentry.c
filechooserentry: Don't override activate
[~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_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   GFile *base_folder;
70   GFile *current_folder_file;
71   gchar *dir_part;
72   gchar *file_part;
73   gint file_part_pos;
74
75   LoadCompleteAction load_complete_action;
76
77   GtkTreeModel *completion_store;
78
79   guint current_folder_loaded : 1;
80   guint in_change      : 1;
81   guint eat_tabs       : 1;
82   guint local_only     : 1;
83 };
84
85 enum
86 {
87   DISPLAY_NAME_COLUMN,
88   FULL_PATH_COLUMN,
89   FILE_COLUMN,
90   N_COLUMNS
91 };
92
93 static void     gtk_file_chooser_entry_finalize       (GObject          *object);
94 static void     gtk_file_chooser_entry_dispose        (GObject          *object);
95 static void     gtk_file_chooser_entry_grab_focus     (GtkWidget        *widget);
96 static gboolean gtk_file_chooser_entry_key_press_event (GtkWidget *widget,
97                                                         GdkEventKey *event);
98 static gboolean gtk_file_chooser_entry_focus_out_event (GtkWidget       *widget,
99                                                         GdkEventFocus   *event);
100
101 #ifdef G_OS_WIN32
102 static gint     insert_text_callback      (GtkFileChooserEntry *widget,
103                                            const gchar         *new_text,
104                                            gint                 new_text_length,
105                                            gint                *position,
106                                            gpointer             user_data);
107 static void     delete_text_callback      (GtkFileChooserEntry *widget,
108                                            gint                 start_pos,
109                                            gint                 end_pos,
110                                            gpointer             user_data);
111 #endif
112
113 static gboolean match_selected_callback   (GtkEntryCompletion  *completion,
114                                            GtkTreeModel        *model,
115                                            GtkTreeIter         *iter,
116                                            GtkFileChooserEntry *chooser_entry);
117 static gboolean completion_match_func     (GtkEntryCompletion  *comp,
118                                            const char          *key,
119                                            GtkTreeIter         *iter,
120                                            gpointer             data);
121
122 static RefreshStatus refresh_current_folder_and_file_part (GtkFileChooserEntry *chooser_entry,
123                                                            const char          *text);
124 static void finished_loading_cb (GtkFileSystemModel  *model,
125                                  GError              *error,
126                                  GtkFileChooserEntry *chooser_entry);
127
128 G_DEFINE_TYPE (GtkFileChooserEntry, _gtk_file_chooser_entry, GTK_TYPE_ENTRY)
129
130 static void
131 gtk_file_chooser_entry_dispatch_properties_changed (GObject     *object,
132                                                     guint        n_pspecs,
133                                                     GParamSpec **pspecs)
134 {
135   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
136   GtkEditable *editable = GTK_EDITABLE (object);
137   guint i;
138
139   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->dispatch_properties_changed (object, n_pspecs, pspecs);
140
141   /* What we are after: The text in front of the cursor was modified.
142    * Unfortunately, there's no other way to catch this. */
143
144   if (chooser_entry->in_change)
145     return;
146
147   for (i = 0; i < n_pspecs; i++)
148     {
149       if (pspecs[i]->name == I_("cursor-position") ||
150           pspecs[i]->name == I_("selection-bound") ||
151           pspecs[i]->name == I_("text"))
152         {
153           char *text;
154           int start, end;
155
156           chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
157
158           gtk_editable_get_selection_bounds (editable, &start, &end);
159           text = gtk_editable_get_chars (editable, 0, MIN (start, end));
160           refresh_current_folder_and_file_part (chooser_entry, text);
161           g_free (text);
162
163           break;
164         }
165     }
166 }
167
168 static void
169 _gtk_file_chooser_entry_class_init (GtkFileChooserEntryClass *class)
170 {
171   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
172   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
173
174   gobject_class->finalize = gtk_file_chooser_entry_finalize;
175   gobject_class->dispose = gtk_file_chooser_entry_dispose;
176   gobject_class->dispatch_properties_changed = gtk_file_chooser_entry_dispatch_properties_changed;
177
178   widget_class->grab_focus = gtk_file_chooser_entry_grab_focus;
179   widget_class->key_press_event = gtk_file_chooser_entry_key_press_event;
180   widget_class->focus_out_event = gtk_file_chooser_entry_focus_out_event;
181 }
182
183 static void
184 _gtk_file_chooser_entry_init (GtkFileChooserEntry *chooser_entry)
185 {
186   GtkEntryCompletion *comp;
187   GtkCellRenderer *cell;
188
189   chooser_entry->local_only = TRUE;
190   chooser_entry->base_folder = g_file_new_for_path (g_get_home_dir ());
191
192   g_object_set (chooser_entry, "truncate-multiline", TRUE, NULL);
193
194   comp = gtk_entry_completion_new ();
195   gtk_entry_completion_set_popup_single_match (comp, FALSE);
196   /* see docs for gtk_entry_completion_set_text_column() */
197   g_object_set (comp, "text-column", FULL_PATH_COLUMN, NULL);
198
199   gtk_entry_completion_set_match_func (comp,
200                                        completion_match_func,
201                                        chooser_entry,
202                                        NULL);
203
204   cell = gtk_cell_renderer_text_new ();
205   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (comp),
206                               cell, TRUE);
207   gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (comp),
208                                  cell,
209                                  "text", DISPLAY_NAME_COLUMN);
210
211   g_signal_connect (comp, "match-selected",
212                     G_CALLBACK (match_selected_callback), chooser_entry);
213
214   gtk_entry_set_completion (GTK_ENTRY (chooser_entry), comp);
215   g_object_unref (comp);
216
217 #ifdef G_OS_WIN32
218   g_signal_connect (chooser_entry, "insert-text",
219                     G_CALLBACK (insert_text_callback), NULL);
220   g_signal_connect (chooser_entry, "delete-text",
221                     G_CALLBACK (delete_text_callback), NULL);
222 #endif
223 }
224
225 static void
226 gtk_file_chooser_entry_finalize (GObject *object)
227 {
228   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
229
230   g_object_unref (chooser_entry->base_folder);
231
232   if (chooser_entry->current_folder_file)
233     g_object_unref (chooser_entry->current_folder_file);
234
235   g_free (chooser_entry->dir_part);
236   g_free (chooser_entry->file_part);
237
238   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->finalize (object);
239 }
240
241 static void
242 discard_loading_and_current_folder_file (GtkFileChooserEntry *chooser_entry)
243 {
244   if (chooser_entry->current_folder_file)
245     {
246       g_object_unref (chooser_entry->current_folder_file);
247       chooser_entry->current_folder_file = NULL;
248     }
249 }
250
251 static void
252 gtk_file_chooser_entry_dispose (GObject *object)
253 {
254   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (object);
255
256   discard_loading_and_current_folder_file (chooser_entry);
257
258   if (chooser_entry->completion_store)
259     {
260       g_object_unref (chooser_entry->completion_store);
261       chooser_entry->completion_store = NULL;
262     }
263
264   G_OBJECT_CLASS (_gtk_file_chooser_entry_parent_class)->dispose (object);
265 }
266
267 /* Match functions for the GtkEntryCompletion */
268 static gboolean
269 match_selected_callback (GtkEntryCompletion  *completion,
270                          GtkTreeModel        *model,
271                          GtkTreeIter         *iter,
272                          GtkFileChooserEntry *chooser_entry)
273 {
274   char *path;
275   
276   gtk_tree_model_get (model, iter,
277                       FULL_PATH_COLUMN, &path,
278                       -1);
279
280   /* We don't set in_change here as we want to update the current_folder
281    * variable */
282   gtk_editable_delete_text (GTK_EDITABLE (chooser_entry),
283                             0,
284                             gtk_editable_get_position (GTK_EDITABLE (chooser_entry)));
285   gtk_editable_insert_text (GTK_EDITABLE (chooser_entry),
286                             path,
287                             0,
288                             NULL); 
289
290   g_free (path);
291
292   return TRUE;
293 }
294
295 /* Match function for the GtkEntryCompletion */
296 static gboolean
297 completion_match_func (GtkEntryCompletion *comp,
298                        const char         *key_unused,
299                        GtkTreeIter        *iter,
300                        gpointer            data)
301 {
302   GtkFileChooserEntry *chooser_entry;
303   char *name = NULL;
304   gboolean result;
305   char *norm_file_part;
306   char *norm_name;
307
308   chooser_entry = GTK_FILE_CHOOSER_ENTRY (data);
309
310   /* We ignore the key because it is the contents of the entry.  Instead, we
311    * just use our precomputed file_part.
312    */
313   if (!chooser_entry->file_part)
314     {
315       return FALSE;
316     }
317
318   gtk_tree_model_get (chooser_entry->completion_store, iter, DISPLAY_NAME_COLUMN, &name, -1);
319   if (!name)
320     {
321       return FALSE; /* Uninitialized row, ugh */
322     }
323
324   /* If we have an empty file_part, then we're at the root of a directory.  In
325    * that case, we want to match all non-dot files.  We might want to match
326    * dot_files too if show_hidden is TRUE on the fileselector in the future.
327    */
328   /* Additionally, support for gnome .hidden files would be sweet, too */
329   if (chooser_entry->file_part[0] == '\000')
330     {
331       if (name[0] == '.')
332         result = FALSE;
333       else
334         result = TRUE;
335       g_free (name);
336
337       return result;
338     }
339
340
341   norm_file_part = g_utf8_normalize (chooser_entry->file_part, -1, G_NORMALIZE_ALL);
342   norm_name = g_utf8_normalize (name, -1, G_NORMALIZE_ALL);
343
344 #ifdef G_PLATFORM_WIN32
345   {
346     gchar *temp;
347
348     temp = norm_file_part;
349     norm_file_part = g_utf8_casefold (norm_file_part, -1);
350     g_free (temp);
351
352     temp = norm_name;
353     norm_name = g_utf8_casefold (norm_name, -1);
354     g_free (temp);
355   }
356 #endif
357
358   result = (strncmp (norm_file_part, norm_name, strlen (norm_file_part)) == 0);
359
360   g_free (norm_file_part);
361   g_free (norm_name);
362   g_free (name);
363   
364   return result;
365 }
366
367 static void
368 clear_completions (GtkFileChooserEntry *chooser_entry)
369 {
370   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
371 }
372
373 static void
374 beep (GtkFileChooserEntry *chooser_entry)
375 {
376   gtk_widget_error_bell (GTK_WIDGET (chooser_entry));
377 }
378
379 static gboolean
380 is_valid_scheme_character (char c)
381 {
382   return g_ascii_isalnum (c) || c == '+' || c == '-' || c == '.';
383 }
384
385 static gboolean
386 has_uri_scheme (const char *str)
387 {
388   const char *p;
389
390   p = str;
391
392   if (!is_valid_scheme_character (*p))
393     return FALSE;
394
395   do
396     p++;
397   while (is_valid_scheme_character (*p));
398
399   return (strncmp (p, "://", 3) == 0);
400 }
401
402 static GFile *
403 gtk_file_chooser_get_file_for_text (GtkFileChooserEntry *chooser_entry,
404                                     const gchar         *str)
405 {
406   GFile *file;
407
408   if (str[0] == '~' || g_path_is_absolute (str) || has_uri_scheme (str))
409     file = g_file_parse_name (str);
410   else
411     file = g_file_resolve_relative_path (chooser_entry->base_folder, str);
412
413   return file;
414 }
415
416 static GFile *
417 gtk_file_chooser_get_directory_for_text (GtkFileChooserEntry *chooser_entry,
418                                          const char *         text)
419 {
420   GFile *file, *parent;
421
422   file = gtk_file_chooser_get_file_for_text (chooser_entry, text);
423
424   if (text[0] == 0 || text[strlen (text) - 1] == G_DIR_SEPARATOR)
425     return file;
426
427   parent = g_file_get_parent (file);
428   g_object_unref (file);
429
430   return parent;
431 }
432
433 static gboolean
434 gtk_file_chooser_entry_parse (GtkFileChooserEntry  *chooser_entry,
435                               const gchar          *str,
436                               GFile               **folder,
437                               gchar               **file_part,
438                               GError              **error)
439 {
440   GFile *file;
441   gboolean result = FALSE;
442   gboolean is_dir = FALSE;
443   gchar *last_slash = NULL;
444
445   if (str && *str)
446     is_dir = (str [strlen (str) - 1] == G_DIR_SEPARATOR);
447
448   last_slash = strrchr (str, G_DIR_SEPARATOR);
449
450   file = gtk_file_chooser_get_file_for_text (chooser_entry, str);
451
452   if (g_file_equal (chooser_entry->base_folder, file))
453     {
454       /* this is when user types '.', could be the
455        * beginning of a hidden file, ./ or ../
456        */
457       *folder = g_object_ref (file);
458       *file_part = g_strdup (str);
459       result = TRUE;
460     }
461   else if (is_dir)
462     {
463       /* it's a dir, or at least it ends with the dir separator */
464       *folder = g_object_ref (file);
465       *file_part = g_strdup ("");
466       result = TRUE;
467     }
468   else
469     {
470       GFile *parent_file;
471
472       parent_file = g_file_get_parent (file);
473
474       if (!parent_file)
475         {
476           g_set_error (error,
477                        GTK_FILE_CHOOSER_ERROR,
478                        GTK_FILE_CHOOSER_ERROR_NONEXISTENT,
479                        "Could not get parent file");
480           *folder = NULL;
481           *file_part = NULL;
482         }
483       else
484         {
485           *folder = parent_file;
486           result = TRUE;
487
488           if (last_slash)
489             *file_part = g_strdup (last_slash + 1);
490           else
491             *file_part = g_strdup (str);
492         }
493     }
494
495   g_object_unref (file);
496
497   return result;
498 }
499
500 /* Determines if the completion model has entries with a common prefix relative
501  * to the current contents of the entry.  Also, if there's one and only one such
502  * path, stores it in unique_path_ret.
503  */
504 static gboolean
505 find_common_prefix (GtkFileChooserEntry *chooser_entry,
506                     gchar               **common_prefix_ret,
507                     GFile               **unique_file_ret,
508                     gboolean             *is_complete_not_unique_ret,
509                     gboolean             *prefix_expands_the_file_part_ret,
510                     GError              **error)
511 {
512   GtkEditable *editable;
513   GtkTreeIter iter;
514   gboolean parsed;
515   gboolean valid;
516   char *text_up_to_cursor;
517   GFile *parsed_folder_file;
518   char *parsed_file_part;
519
520   *common_prefix_ret = NULL;
521   *unique_file_ret = NULL;
522   *is_complete_not_unique_ret = FALSE;
523   *prefix_expands_the_file_part_ret = FALSE;
524
525   editable = GTK_EDITABLE (chooser_entry);
526
527   text_up_to_cursor = gtk_editable_get_chars (editable, 0, gtk_editable_get_position (editable));
528
529   parsed = gtk_file_chooser_entry_parse (chooser_entry,
530                                          text_up_to_cursor,
531                                          &parsed_folder_file,
532                                          &parsed_file_part,
533                                          error);
534
535   g_free (text_up_to_cursor);
536
537   if (!parsed)
538     return FALSE;
539
540   g_assert (parsed_folder_file != NULL
541             && 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 (chooser_entry->completion_store, &iter);
548
549   while (valid)
550     {
551       gchar *display_name;
552       GFile *file;
553
554       gtk_tree_model_get (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 = g_strdup (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 (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 (chooser_entry->completion_store, &iter);
598
599       while (valid)
600         {
601           gchar *display_name;
602           int len;
603
604           gtk_tree_model_get (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 (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 /* Finds a common prefix based on the contents of the entry
632  * and mandatorily appends it
633  */
634 static void
635 explicitly_complete (GtkFileChooserEntry *chooser_entry)
636 {
637   gchar *common_prefix;
638   GFile *unique_file;
639   gboolean is_complete_not_unique;
640   gboolean prefix_expands_the_file_part;
641   gint cursor_pos;
642   gint pos;
643
644   clear_completions (chooser_entry);
645
646   if (chooser_entry->completion_store == NULL
647       || !find_common_prefix (chooser_entry, &common_prefix, &unique_file, &is_complete_not_unique, &prefix_expands_the_file_part, NULL)
648       || !common_prefix
649       || !prefix_expands_the_file_part)
650     {
651       beep (chooser_entry);
652       return;
653     }
654
655   cursor_pos = gtk_editable_get_position (GTK_EDITABLE (chooser_entry));
656   pos = chooser_entry->file_part_pos;
657
658   chooser_entry->in_change = TRUE;
659   gtk_editable_delete_text (GTK_EDITABLE (chooser_entry),
660                             pos, cursor_pos);
661   gtk_editable_insert_text (GTK_EDITABLE (chooser_entry),
662                             common_prefix, -1,
663                             &pos);
664   chooser_entry->in_change = FALSE;
665
666   gtk_editable_set_position (GTK_EDITABLE (chooser_entry), pos);
667 }
668
669 static void
670 gtk_file_chooser_entry_grab_focus (GtkWidget *widget)
671 {
672   GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->grab_focus (widget);
673   _gtk_file_chooser_entry_select_filename (GTK_FILE_CHOOSER_ENTRY (widget));
674 }
675
676 static void
677 start_explicit_completion (GtkFileChooserEntry *chooser_entry)
678 {
679   RefreshStatus status;
680   gboolean is_error;
681   char *text;
682
683   text = gtk_editable_get_chars (GTK_EDITABLE (chooser_entry),
684                                  0, gtk_editable_get_position (GTK_EDITABLE (chooser_entry)));
685   status = refresh_current_folder_and_file_part (chooser_entry, text);
686   g_free (text);
687
688   is_error = FALSE;
689
690   switch (status)
691     {
692     case REFRESH_OK:
693       g_assert (chooser_entry->current_folder_file != NULL);
694
695       if (chooser_entry->current_folder_loaded)
696         explicitly_complete (chooser_entry);
697       else
698         {
699           chooser_entry->load_complete_action = LOAD_COMPLETE_EXPLICIT_COMPLETION;
700         }
701
702       break;
703
704     case REFRESH_INVALID_INPUT:
705       is_error = TRUE;
706       break;
707
708     case REFRESH_INCOMPLETE_HOSTNAME:
709       is_error = TRUE;
710       break;
711
712     case REFRESH_NONEXISTENT:
713       is_error = TRUE;
714       break;
715
716     case REFRESH_NOT_LOCAL:
717       is_error = TRUE;
718       break;
719
720     default:
721       g_assert_not_reached ();
722       return;
723     }
724
725   if (is_error)
726     {
727       g_assert (chooser_entry->current_folder_file == NULL);
728
729       beep (chooser_entry);
730       chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
731     }
732 }
733
734 static gboolean
735 gtk_file_chooser_entry_key_press_event (GtkWidget *widget,
736                                         GdkEventKey *event)
737 {
738   GtkFileChooserEntry *chooser_entry;
739   GtkEditable *editable;
740   GdkModifierType state;
741   gboolean control_pressed;
742
743   chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
744   editable = GTK_EDITABLE (widget);
745
746   if (!chooser_entry->eat_tabs)
747     return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->key_press_event (widget, event);
748
749   control_pressed = FALSE;
750
751   if (gtk_get_current_event_state (&state))
752     {
753       if ((state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK)
754         control_pressed = TRUE;
755     }
756
757   /* This is a bit evil -- it makes Tab never leave the entry. It basically
758    * makes it 'safe' for people to hit. */
759   if (event->keyval == GDK_KEY_Tab && !control_pressed)
760     {
761       gint start, end;
762
763       gtk_editable_get_selection_bounds (editable, &start, &end);
764       
765       if (start != end)
766         gtk_editable_set_position (editable, MAX (start, end));
767       else
768         start_explicit_completion (chooser_entry);
769
770       return TRUE;
771      }
772
773   return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->key_press_event (widget, event);
774
775 }
776
777 static gboolean
778 gtk_file_chooser_entry_focus_out_event (GtkWidget     *widget,
779                                         GdkEventFocus *event)
780 {
781   GtkFileChooserEntry *chooser_entry = GTK_FILE_CHOOSER_ENTRY (widget);
782
783   chooser_entry->load_complete_action = LOAD_COMPLETE_NOTHING;
784  
785   return GTK_WIDGET_CLASS (_gtk_file_chooser_entry_parent_class)->focus_out_event (widget, event);
786 }
787
788 static void
789 discard_completion_store (GtkFileChooserEntry *chooser_entry)
790 {
791   if (!chooser_entry->completion_store)
792     return;
793
794   gtk_entry_completion_set_model (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)), NULL);
795   gtk_entry_completion_set_inline_completion (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)), FALSE);
796   g_object_unref (chooser_entry->completion_store);
797   chooser_entry->completion_store = NULL;
798 }
799
800 static gboolean
801 completion_store_set (GtkFileSystemModel  *model,
802                       GFile               *file,
803                       GFileInfo           *info,
804                       int                  column,
805                       GValue              *value,
806                       gpointer             data)
807 {
808   GtkFileChooserEntry *chooser_entry = data;
809
810   const char *prefix = "";
811   const char *suffix = "";
812
813   switch (column)
814     {
815     case FILE_COLUMN:
816       g_value_set_object (value, file);
817       break;
818     case FULL_PATH_COLUMN:
819       prefix = chooser_entry->dir_part;
820       /* fall through */
821     case DISPLAY_NAME_COLUMN:
822       if (_gtk_file_info_consider_as_directory (info))
823         suffix = G_DIR_SEPARATOR_S;
824
825       g_value_take_string (value, g_strconcat (
826               prefix,
827               g_file_info_get_display_name (info),
828               suffix,
829               NULL));
830       break;
831     default:
832       g_assert_not_reached ();
833       break;
834     }
835
836   return TRUE;
837 }
838
839 /* Fills the completion store from the contents of the current folder */
840 static void
841 populate_completion_store (GtkFileChooserEntry *chooser_entry)
842 {
843   discard_completion_store (chooser_entry);
844
845   chooser_entry->completion_store = GTK_TREE_MODEL (
846       _gtk_file_system_model_new_for_directory (chooser_entry->current_folder_file,
847                                                 "standard::name,standard::display-name,standard::type",
848                                                 completion_store_set,
849                                                 chooser_entry,
850                                                 N_COLUMNS,
851                                                 G_TYPE_STRING,
852                                                 G_TYPE_STRING,
853                                                 G_TYPE_FILE));
854   g_signal_connect (chooser_entry->completion_store, "finished-loading",
855                     G_CALLBACK (finished_loading_cb), chooser_entry);
856
857   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (chooser_entry->completion_store),
858                                         DISPLAY_NAME_COLUMN, GTK_SORT_ASCENDING);
859
860   gtk_entry_completion_set_model (gtk_entry_get_completion (GTK_ENTRY (chooser_entry)),
861                                   chooser_entry->completion_store);
862 }
863
864 /* When we finish loading the current folder, this function should get called to
865  * perform the deferred explicit completion.
866  */
867 static void
868 perform_load_complete_action (GtkFileChooserEntry *chooser_entry)
869 {
870   switch (chooser_entry->load_complete_action)
871     {
872     case LOAD_COMPLETE_NOTHING:
873       break;
874
875     case LOAD_COMPLETE_EXPLICIT_COMPLETION:
876       explicitly_complete (chooser_entry);
877       break;
878
879     default:
880       g_assert_not_reached ();
881     }
882
883 }
884
885 /* Callback when the current folder finishes loading */
886 static void
887 finished_loading_cb (GtkFileSystemModel  *model,
888                      GError              *error,
889                      GtkFileChooserEntry *chooser_entry)
890 {
891   GtkEntryCompletion *completion;
892
893   chooser_entry->current_folder_loaded = TRUE;
894
895   if (error)
896     {
897       LoadCompleteAction old_load_complete_action;
898
899       old_load_complete_action = chooser_entry->load_complete_action;
900
901       discard_completion_store (chooser_entry);
902       clear_completions (chooser_entry);
903
904       if (old_load_complete_action == LOAD_COMPLETE_EXPLICIT_COMPLETION)
905         {
906           /* Since this came from explicit user action (Tab completion), we'll present errors visually */
907
908           beep (chooser_entry);
909         }
910
911       return;
912     }
913
914   perform_load_complete_action (chooser_entry);
915
916   gtk_widget_set_tooltip_text (GTK_WIDGET (chooser_entry), NULL);
917
918   completion = gtk_entry_get_completion (GTK_ENTRY (chooser_entry));
919   gtk_entry_completion_set_inline_completion (completion, TRUE);
920   gtk_entry_completion_complete (completion);
921   gtk_entry_completion_insert_prefix (completion);
922 }
923
924 static RefreshStatus
925 reload_current_folder (GtkFileChooserEntry *chooser_entry,
926                        GFile               *folder_file)
927 {
928   g_assert (folder_file != NULL);
929
930   if (chooser_entry->current_folder_file
931       && g_file_equal (folder_file, chooser_entry->current_folder_file))
932     return REFRESH_OK;
933
934   if (chooser_entry->current_folder_file)
935     {
936       discard_loading_and_current_folder_file (chooser_entry);
937     }
938   
939   if (chooser_entry->local_only
940       && !g_file_is_native (folder_file))
941     return REFRESH_NOT_LOCAL;
942
943   chooser_entry->current_folder_file = g_object_ref (folder_file);
944   chooser_entry->current_folder_loaded = FALSE;
945
946   populate_completion_store (chooser_entry);
947
948   return REFRESH_OK;
949 }
950
951 static RefreshStatus
952 refresh_current_folder_and_file_part (GtkFileChooserEntry *chooser_entry,
953                                       const gchar *        text)
954 {
955   GFile *folder_file;
956   gchar *file_part;
957   gsize total_len, file_part_len;
958   gint file_part_pos;
959   GError *error;
960   RefreshStatus result;
961
962   error = NULL;
963   if (!gtk_file_chooser_entry_parse (chooser_entry,
964                                      text, &folder_file, &file_part, &error))
965     {
966       folder_file = g_object_ref (chooser_entry->base_folder);
967
968       if (g_error_matches (error, GTK_FILE_CHOOSER_ERROR, GTK_FILE_CHOOSER_ERROR_NONEXISTENT))
969         result = REFRESH_NONEXISTENT;
970       else
971         result = REFRESH_INVALID_INPUT;
972
973       if (error)
974         g_error_free (error);
975
976       file_part = g_strdup ("");
977       file_part_pos = -1;
978     }
979   else
980     {
981       g_assert (folder_file != NULL);
982
983       file_part_len = strlen (file_part);
984       total_len = strlen (text);
985       if (total_len > file_part_len)
986         file_part_pos = g_utf8_strlen (text, total_len - file_part_len);
987       else
988         file_part_pos = 0;
989
990       result = REFRESH_OK;
991     }
992
993   g_free (chooser_entry->file_part);
994   g_free (chooser_entry->dir_part);
995
996   chooser_entry->dir_part = file_part_pos > 0 ? g_strndup (text, file_part_pos) : g_strdup ("");
997   chooser_entry->file_part = file_part;
998   chooser_entry->file_part_pos = file_part_pos;
999
1000   if (result == REFRESH_OK)
1001     {
1002       result = reload_current_folder (chooser_entry, folder_file);
1003     }
1004   else
1005     {
1006       discard_loading_and_current_folder_file (chooser_entry);
1007     }
1008
1009   if (folder_file)
1010     g_object_unref (folder_file);
1011
1012   g_assert (/* we are OK and we have a current folder file and (loading process or folder handle)... */
1013             ((result == REFRESH_OK)
1014              && (chooser_entry->current_folder_file != NULL))
1015             /* ... OR we have an error, and we don't have a current folder file nor a loading process nor a folder handle */
1016             || ((result != REFRESH_OK)
1017                 && (chooser_entry->current_folder_file == NULL)));
1018
1019   return result;
1020 }
1021
1022 #ifdef G_OS_WIN32
1023 static gint
1024 insert_text_callback (GtkFileChooserEntry *chooser_entry,
1025                       const gchar         *new_text,
1026                       gint                 new_text_length,
1027                       gint                *position,
1028                       gpointer             user_data)
1029 {
1030   const gchar *colon = memchr (new_text, ':', new_text_length);
1031   gint i;
1032
1033   /* Disallow these characters altogether */
1034   for (i = 0; i < new_text_length; i++)
1035     {
1036       if (new_text[i] == '<' ||
1037           new_text[i] == '>' ||
1038           new_text[i] == '"' ||
1039           new_text[i] == '|' ||
1040           new_text[i] == '*' ||
1041           new_text[i] == '?')
1042         break;
1043     }
1044
1045   if (i < new_text_length ||
1046       /* Disallow entering text that would cause a colon to be anywhere except
1047        * after a drive letter.
1048        */
1049       (colon != NULL &&
1050        *position + (colon - new_text) != 1) ||
1051       (new_text_length > 0 &&
1052        *position <= 1 &&
1053        gtk_entry_get_text_length (GTK_ENTRY (chooser_entry)) >= 2 &&
1054        gtk_entry_get_text (GTK_ENTRY (chooser_entry))[1] == ':'))
1055     {
1056       gtk_widget_error_bell (GTK_WIDGET (chooser_entry));
1057       g_signal_stop_emission_by_name (chooser_entry, "insert_text");
1058       return FALSE;
1059     }
1060
1061   return TRUE;
1062 }
1063
1064 static void
1065 delete_text_callback (GtkFileChooserEntry *chooser_entry,
1066                       gint                 start_pos,
1067                       gint                 end_pos,
1068                       gpointer             user_data)
1069 {
1070   /* If deleting a drive letter, delete the colon, too */
1071   if (start_pos == 0 && end_pos == 1 &&
1072       gtk_entry_get_text_length (GTK_ENTRY (chooser_entry)) >= 2 &&
1073       gtk_entry_get_text (GTK_ENTRY (chooser_entry))[1] == ':')
1074     {
1075       g_signal_handlers_block_by_func (chooser_entry,
1076                                        G_CALLBACK (delete_text_callback),
1077                                        user_data);
1078       gtk_editable_delete_text (GTK_EDITABLE (chooser_entry), 0, 1);
1079       g_signal_handlers_unblock_by_func (chooser_entry,
1080                                          G_CALLBACK (delete_text_callback),
1081                                          user_data);
1082     }
1083 }
1084 #endif
1085
1086 /**
1087  * _gtk_file_chooser_entry_new:
1088  * @eat_tabs: If %FALSE, allow focus navigation with the tab key.
1089  *
1090  * Creates a new #GtkFileChooserEntry object. #GtkFileChooserEntry
1091  * is an internal implementation widget for the GTK+ file chooser
1092  * which is an entry with completion with respect to a
1093  * #GtkFileSystem object.
1094  *
1095  * Return value: the newly created #GtkFileChooserEntry
1096  **/
1097 GtkWidget *
1098 _gtk_file_chooser_entry_new (gboolean       eat_tabs)
1099 {
1100   GtkFileChooserEntry *chooser_entry;
1101
1102   chooser_entry = g_object_new (GTK_TYPE_FILE_CHOOSER_ENTRY, NULL);
1103   chooser_entry->eat_tabs = (eat_tabs != FALSE);
1104
1105   return GTK_WIDGET (chooser_entry);
1106 }
1107
1108 /**
1109  * _gtk_file_chooser_entry_set_base_folder:
1110  * @chooser_entry: a #GtkFileChooserEntry
1111  * @file: file for a folder in the chooser entries current file system.
1112  *
1113  * Sets the folder with respect to which completions occur.
1114  **/
1115 void
1116 _gtk_file_chooser_entry_set_base_folder (GtkFileChooserEntry *chooser_entry,
1117                                          GFile               *file)
1118 {
1119   if (file)
1120     g_object_ref (file);
1121   else
1122     file = g_file_new_for_path (g_get_home_dir ());
1123
1124   if (g_file_equal (chooser_entry->base_folder, file))
1125     {
1126       g_object_unref (file);
1127       return;
1128     }
1129
1130   if (chooser_entry->base_folder)
1131     g_object_unref (chooser_entry->base_folder);
1132
1133   chooser_entry->base_folder = file;
1134
1135   clear_completions (chooser_entry);
1136 }
1137
1138 /**
1139  * _gtk_file_chooser_entry_get_current_folder:
1140  * @chooser_entry: a #GtkFileChooserEntry
1141  *
1142  * Gets the current folder for the #GtkFileChooserEntry. If the
1143  * user has only entered a filename, this will be in the base folder
1144  * (see _gtk_file_chooser_entry_set_base_folder()), but if the
1145  * user has entered a relative or absolute path, then it will
1146  * be different.  If the user has entered unparsable text, or text which
1147  * the entry cannot handle, this will return %NULL.
1148  *
1149  * Return value: the file for the current folder - you must g_object_unref()
1150  *   the value after use.
1151  **/
1152 GFile *
1153 _gtk_file_chooser_entry_get_current_folder (GtkFileChooserEntry *chooser_entry)
1154 {
1155   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry), NULL);
1156
1157   return gtk_file_chooser_get_directory_for_text (chooser_entry,
1158                                                   gtk_entry_get_text (GTK_ENTRY (chooser_entry)));
1159 }
1160
1161 /**
1162  * _gtk_file_chooser_entry_get_file_part:
1163  * @chooser_entry: a #GtkFileChooserEntry
1164  *
1165  * Gets the non-folder portion of whatever the user has entered
1166  * into the file selector. What is returned is a UTF-8 string,
1167  * and if a filename path is needed, g_file_get_child_for_display_name()
1168  * must be used
1169   *
1170  * Return value: the entered filename - this value is owned by the
1171  *  chooser entry and must not be modified or freed.
1172  **/
1173 const gchar *
1174 _gtk_file_chooser_entry_get_file_part (GtkFileChooserEntry *chooser_entry)
1175 {
1176   const char *last_slash, *text;
1177
1178   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry), NULL);
1179
1180   text = gtk_entry_get_text (GTK_ENTRY (chooser_entry));
1181   last_slash = strrchr (text, G_DIR_SEPARATOR);
1182   if (last_slash)
1183     return last_slash + 1;
1184   else
1185     return text;
1186 }
1187
1188 /**
1189  * _gtk_file_chooser_entry_set_file_part:
1190  * @chooser_entry: a #GtkFileChooserEntry
1191  * @file_part: text to display in the entry, in UTF-8
1192  *
1193  * Sets the current text shown in the file chooser entry.
1194  **/
1195 void
1196 _gtk_file_chooser_entry_set_file_part (GtkFileChooserEntry *chooser_entry,
1197                                        const gchar         *file_part)
1198 {
1199   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1200
1201   chooser_entry->in_change = TRUE;
1202   clear_completions (chooser_entry);
1203   gtk_entry_set_text (GTK_ENTRY (chooser_entry), file_part);
1204   chooser_entry->in_change = FALSE;
1205 }
1206
1207
1208 /**
1209  * _gtk_file_chooser_entry_set_action:
1210  * @chooser_entry: a #GtkFileChooserEntry
1211  * @action: the action which is performed by the file selector using this entry
1212  *
1213  * Sets action which is performed by the file selector using this entry. 
1214  * The #GtkFileChooserEntry will use different completion strategies for 
1215  * different actions.
1216  **/
1217 void
1218 _gtk_file_chooser_entry_set_action (GtkFileChooserEntry *chooser_entry,
1219                                     GtkFileChooserAction action)
1220 {
1221   g_return_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry));
1222   
1223   if (chooser_entry->action != action)
1224     {
1225       GtkEntryCompletion *comp;
1226
1227       chooser_entry->action = action;
1228
1229       comp = gtk_entry_get_completion (GTK_ENTRY (chooser_entry));
1230
1231       /* FIXME: do we need to actually set the following? */
1232
1233       switch (action)
1234         {
1235         case GTK_FILE_CHOOSER_ACTION_OPEN:
1236         case GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER:
1237           gtk_entry_completion_set_popup_single_match (comp, FALSE);
1238           break;
1239         case GTK_FILE_CHOOSER_ACTION_SAVE:
1240         case GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER:
1241           gtk_entry_completion_set_popup_single_match (comp, TRUE);
1242           break;
1243         }
1244     }
1245 }
1246
1247
1248 /**
1249  * _gtk_file_chooser_entry_get_action:
1250  * @chooser_entry: a #GtkFileChooserEntry
1251  *
1252  * Gets the action for this entry. 
1253  *
1254  * Returns: the action
1255  **/
1256 GtkFileChooserAction
1257 _gtk_file_chooser_entry_get_action (GtkFileChooserEntry *chooser_entry)
1258 {
1259   g_return_val_if_fail (GTK_IS_FILE_CHOOSER_ENTRY (chooser_entry),
1260                         GTK_FILE_CHOOSER_ACTION_OPEN);
1261   
1262   return chooser_entry->action;
1263 }
1264
1265 gboolean
1266 _gtk_file_chooser_entry_get_is_folder (GtkFileChooserEntry *chooser_entry,
1267                                        GFile               *file)
1268 {
1269   GtkTreeIter iter;
1270   GFileInfo *info;
1271
1272   if (chooser_entry->completion_store == NULL ||
1273       !_gtk_file_system_model_get_iter_for_file (GTK_FILE_SYSTEM_MODEL (chooser_entry->completion_store),
1274                                                  &iter,
1275                                                  file))
1276     return FALSE;
1277
1278   info = _gtk_file_system_model_get_info (GTK_FILE_SYSTEM_MODEL (chooser_entry->completion_store),
1279                                           &iter);
1280
1281   return _gtk_file_info_consider_as_directory (info);
1282 }
1283
1284
1285 /*
1286  * _gtk_file_chooser_entry_select_filename:
1287  * @chooser_entry: a #GtkFileChooserEntry
1288  *
1289  * Selects the filename (without the extension) for user edition.
1290  */
1291 void
1292 _gtk_file_chooser_entry_select_filename (GtkFileChooserEntry *chooser_entry)
1293 {
1294   const gchar *str, *ext;
1295   glong len = -1;
1296
1297   if (chooser_entry->action == GTK_FILE_CHOOSER_ACTION_SAVE)
1298     {
1299       str = gtk_entry_get_text (GTK_ENTRY (chooser_entry));
1300       ext = g_strrstr (str, ".");
1301
1302       if (ext)
1303        len = g_utf8_pointer_to_offset (str, ext);
1304     }
1305
1306   gtk_editable_select_region (GTK_EDITABLE (chooser_entry), 0, (gint) len);
1307 }
1308
1309 void
1310 _gtk_file_chooser_entry_set_local_only (GtkFileChooserEntry *chooser_entry,
1311                                         gboolean             local_only)
1312 {
1313   chooser_entry->local_only = local_only;
1314   clear_completions (chooser_entry);
1315 }
1316
1317 gboolean
1318 _gtk_file_chooser_entry_get_local_only (GtkFileChooserEntry *chooser_entry)
1319 {
1320   return chooser_entry->local_only;
1321 }