]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilechooserdefault.c
gtk/gtkaboutdialog.c gtk/gtkcellrendereraccel.c gtk/gtkcellrenderercombo.c
[~andy/gtk] / gtk / gtkfilechooserdefault.c
1 /* -*- Mode: C; c-file-style: "gnu"; tab-width: 8 -*- */
2 /* GTK - The GIMP Toolkit
3  * gtkfilechooserdefault.c: Default implementation of GtkFileChooser
4  * Copyright (C) 2003, Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #include "config.h"
23
24 #include "gdk/gdkkeysyms.h"
25 #include "gtkalignment.h"
26 #include "gtkbindings.h"
27 #include "gtkcelllayout.h"
28 #include "gtkcellrendererpixbuf.h"
29 #include "gtkcellrenderertext.h"
30 #include "gtkcheckmenuitem.h"
31 #include "gtkclipboard.h"
32 #include "gtkcombobox.h"
33 #include "gtkentry.h"
34 #include "gtkexpander.h"
35 #include "gtkfilechooserprivate.h"
36 #include "gtkfilechooserdefault.h"
37 #include "gtkfilechooserembed.h"
38 #include "gtkfilechooserentry.h"
39 #include "gtkfilechoosersettings.h"
40 #include "gtkfilechooserutils.h"
41 #include "gtkfilechooser.h"
42 #include "gtkfilesystem.h"
43 #include "gtkfilesystemmodel.h"
44 #include "gtkframe.h"
45 #include "gtkhbox.h"
46 #include "gtkhpaned.h"
47 #include "gtkiconfactory.h"
48 #include "gtkicontheme.h"
49 #include "gtkimage.h"
50 #include "gtkimagemenuitem.h"
51 #include "gtklabel.h"
52 #include "gtkmarshalers.h"
53 #include "gtkmessagedialog.h"
54 #include "gtkmountoperation.h"
55 #include "gtkpathbar.h"
56 #include "gtkprivate.h"
57 #include "gtkradiobutton.h"
58 #include "gtkrecentfilter.h"
59 #include "gtkrecentmanager.h"
60 #include "gtkscrolledwindow.h"
61 #include "gtkseparatormenuitem.h"
62 #include "gtksizegroup.h"
63 #include "gtkstock.h"
64 #include "gtktable.h"
65 #include "gtktooltip.h"
66 #include "gtktreednd.h"
67 #include "gtktreeprivate.h"
68 #include "gtktreeselection.h"
69 #include "gtkvbox.h"
70 #include "gtkintl.h"
71
72 #include "gtkalias.h"
73
74 #include <errno.h>
75 #include <string.h>
76 #include <time.h>
77 #include <sys/stat.h>
78 #include <sys/types.h>
79 #include <locale.h>
80
81 #ifdef HAVE_UNISTD_H
82 #include <unistd.h>
83 #endif
84 #ifdef G_OS_WIN32
85 #include <io.h>
86 #endif
87
88 /* Profiling stuff */
89 #undef PROFILE_FILE_CHOOSER
90 #ifdef PROFILE_FILE_CHOOSER
91
92
93 #ifndef F_OK 
94 #define F_OK 0
95 #endif
96
97 #define PROFILE_INDENT 4
98 static int profile_indent;
99
100 static void
101 profile_add_indent (int indent)
102 {
103   profile_indent += indent;
104   if (profile_indent < 0)
105     g_error ("You screwed up your indentation");
106 }
107
108 void
109 _gtk_file_chooser_profile_log (const char *func, int indent, const char *msg1, const char *msg2)
110 {
111   char *str;
112
113   if (indent < 0)
114     profile_add_indent (indent);
115
116   if (profile_indent == 0)
117     str = g_strdup_printf ("MARK: %s %s %s", func ? func : "", msg1 ? msg1 : "", msg2 ? msg2 : "");
118   else
119     str = g_strdup_printf ("MARK: %*c %s %s %s", profile_indent - 1, ' ', func ? func : "", msg1 ? msg1 : "", msg2 ? msg2 : "");
120
121   access (str, F_OK);
122   g_free (str);
123
124   if (indent > 0)
125     profile_add_indent (indent);
126 }
127
128 #define profile_start(x, y) _gtk_file_chooser_profile_log (G_STRFUNC, PROFILE_INDENT, x, y)
129 #define profile_end(x, y) _gtk_file_chooser_profile_log (G_STRFUNC, -PROFILE_INDENT, x, y)
130 #define profile_msg(x, y) _gtk_file_chooser_profile_log (NULL, 0, x, y)
131 #else
132 #define profile_start(x, y)
133 #define profile_end(x, y)
134 #define profile_msg(x, y)
135 #endif
136
137
138
139 typedef struct _GtkFileChooserDefaultClass GtkFileChooserDefaultClass;
140
141 #define GTK_FILE_CHOOSER_DEFAULT_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_FILE_CHOOSER_DEFAULT, GtkFileChooserDefaultClass))
142 #define GTK_IS_FILE_CHOOSER_DEFAULT_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_FILE_CHOOSER_DEFAULT))
143 #define GTK_FILE_CHOOSER_DEFAULT_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_FILE_CHOOSER_DEFAULT, GtkFileChooserDefaultClass))
144
145 #define MAX_LOADING_TIME 500
146
147 struct _GtkFileChooserDefaultClass
148 {
149   GtkVBoxClass parent_class;
150 };
151
152 /* Signal IDs */
153 enum {
154   LOCATION_POPUP,
155   LOCATION_POPUP_ON_PASTE,
156   UP_FOLDER,
157   DOWN_FOLDER,
158   HOME_FOLDER,
159   DESKTOP_FOLDER,
160   QUICK_BOOKMARK,
161   LOCATION_TOGGLE_POPUP,
162   SHOW_HIDDEN,
163   SEARCH_SHORTCUT,
164   RECENT_SHORTCUT,
165
166   LAST_SIGNAL
167 };
168
169 static guint signals[LAST_SIGNAL] = { 0 };
170
171 /* Column numbers for the shortcuts tree.  Keep these in sync with shortcuts_model_create() */
172 enum {
173   SHORTCUTS_COL_PIXBUF,
174   SHORTCUTS_COL_NAME,
175   SHORTCUTS_COL_DATA,
176   SHORTCUTS_COL_TYPE,
177   SHORTCUTS_COL_REMOVABLE,
178   SHORTCUTS_COL_PIXBUF_VISIBLE,
179   SHORTCUTS_COL_CANCELLABLE,
180   SHORTCUTS_COL_NUM_COLUMNS
181 };
182
183 typedef enum {
184   SHORTCUT_TYPE_FILE,
185   SHORTCUT_TYPE_VOLUME,
186   SHORTCUT_TYPE_SEPARATOR,
187   SHORTCUT_TYPE_SEARCH,
188   SHORTCUT_TYPE_RECENT
189 } ShortcutType;
190
191 /* Column numbers for the file list */
192 enum {
193   FILE_LIST_COL_NAME,
194   FILE_LIST_COL_SIZE,
195   FILE_LIST_COL_MTIME,
196   FILE_LIST_COL_NUM_COLUMNS
197 };
198
199 /* Column numbers for the search model.  
200  * Keep this in sync with search_setup_model() 
201  */
202 enum {
203   SEARCH_MODEL_COL_FILE,
204   SEARCH_MODEL_COL_DISPLAY_NAME,
205   SEARCH_MODEL_COL_COLLATION_KEY,
206   SEARCH_MODEL_COL_STAT,
207   SEARCH_MODEL_COL_CANCELLABLE,
208   SEARCH_MODEL_COL_PIXBUF,
209   SEARCH_MODEL_COL_MIME_TYPE,
210   SEARCH_MODEL_COL_IS_FOLDER,
211   SEARCH_MODEL_COL_NUM_COLUMNS
212 };
213
214 enum {
215   RECENT_MODEL_COL_FILE,
216   RECENT_MODEL_COL_DISPLAY_NAME,
217   RECENT_MODEL_COL_INFO,
218   RECENT_MODEL_COL_IS_FOLDER,
219   RECENT_MODEL_COL_CANCELLABLE,
220   RECENT_MODEL_COL_NUM_COLUMNS
221 };
222
223 /* Identifiers for target types */
224 enum {
225   GTK_TREE_MODEL_ROW,
226 };
227
228 static gboolean
229 search_is_possible (GtkFileChooserDefault *impl)
230 {
231   if (impl->search_engine == NULL)
232     impl->search_engine = _gtk_search_engine_new ();
233   
234   return impl->search_engine != NULL;
235 }
236
237 /* Interesting places in the shortcuts bar */
238 typedef enum {
239   SHORTCUTS_SEARCH,
240   SHORTCUTS_RECENT,
241   SHORTCUTS_RECENT_SEPARATOR,
242   SHORTCUTS_HOME,
243   SHORTCUTS_DESKTOP,
244   SHORTCUTS_VOLUMES,
245   SHORTCUTS_SHORTCUTS,
246   SHORTCUTS_BOOKMARKS_SEPARATOR,
247   SHORTCUTS_BOOKMARKS,
248   SHORTCUTS_CURRENT_FOLDER_SEPARATOR,
249   SHORTCUTS_CURRENT_FOLDER
250 } ShortcutsIndex;
251
252 /* Icon size for if we can't get it from the theme */
253 #define FALLBACK_ICON_SIZE 16
254
255 #define PREVIEW_HBOX_SPACING 12
256 #define NUM_LINES 45
257 #define NUM_CHARS 60
258
259 static void gtk_file_chooser_default_iface_init       (GtkFileChooserIface        *iface);
260 static void gtk_file_chooser_embed_default_iface_init (GtkFileChooserEmbedIface   *iface);
261
262 static GObject* gtk_file_chooser_default_constructor  (GType                  type,
263                                                        guint                  n_construct_properties,
264                                                        GObjectConstructParam *construct_params);
265 static void     gtk_file_chooser_default_finalize     (GObject               *object);
266 static void     gtk_file_chooser_default_set_property (GObject               *object,
267                                                        guint                  prop_id,
268                                                        const GValue          *value,
269                                                        GParamSpec            *pspec);
270 static void     gtk_file_chooser_default_get_property (GObject               *object,
271                                                        guint                  prop_id,
272                                                        GValue                *value,
273                                                        GParamSpec            *pspec);
274 static void     gtk_file_chooser_default_dispose      (GObject               *object);
275 static void     gtk_file_chooser_default_show_all       (GtkWidget             *widget);
276 static void     gtk_file_chooser_default_map            (GtkWidget             *widget);
277 static void     gtk_file_chooser_default_unmap          (GtkWidget             *widget);
278 static void     gtk_file_chooser_default_hierarchy_changed (GtkWidget          *widget,
279                                                             GtkWidget          *previous_toplevel);
280 static void     gtk_file_chooser_default_style_set      (GtkWidget             *widget,
281                                                          GtkStyle              *previous_style);
282 static void     gtk_file_chooser_default_screen_changed (GtkWidget             *widget,
283                                                          GdkScreen             *previous_screen);
284 static void     gtk_file_chooser_default_size_allocate  (GtkWidget             *widget,
285                                                          GtkAllocation         *allocation);
286
287 static gboolean       gtk_file_chooser_default_set_current_folder          (GtkFileChooser    *chooser,
288                                                                             GFile             *folder,
289                                                                             GError           **error);
290 static gboolean       gtk_file_chooser_default_update_current_folder       (GtkFileChooser    *chooser,
291                                                                             GFile             *folder,
292                                                                             gboolean           keep_trail,
293                                                                             gboolean           clear_entry,
294                                                                             GError           **error);
295 static GFile *        gtk_file_chooser_default_get_current_folder          (GtkFileChooser    *chooser);
296 static void           gtk_file_chooser_default_set_current_name            (GtkFileChooser    *chooser,
297                                                                             const gchar       *name);
298 static gboolean       gtk_file_chooser_default_select_file                 (GtkFileChooser    *chooser,
299                                                                             GFile             *file,
300                                                                             GError           **error);
301 static void           gtk_file_chooser_default_unselect_file               (GtkFileChooser    *chooser,
302                                                                             GFile             *file);
303 static void           gtk_file_chooser_default_select_all                  (GtkFileChooser    *chooser);
304 static void           gtk_file_chooser_default_unselect_all                (GtkFileChooser    *chooser);
305 static GSList *       gtk_file_chooser_default_get_files                   (GtkFileChooser    *chooser);
306 static GFile *        gtk_file_chooser_default_get_preview_file            (GtkFileChooser    *chooser);
307 static GtkFileSystem *gtk_file_chooser_default_get_file_system             (GtkFileChooser    *chooser);
308 static void           gtk_file_chooser_default_add_filter                  (GtkFileChooser    *chooser,
309                                                                             GtkFileFilter     *filter);
310 static void           gtk_file_chooser_default_remove_filter               (GtkFileChooser    *chooser,
311                                                                             GtkFileFilter     *filter);
312 static GSList *       gtk_file_chooser_default_list_filters                (GtkFileChooser    *chooser);
313 static gboolean       gtk_file_chooser_default_add_shortcut_folder    (GtkFileChooser    *chooser,
314                                                                        GFile             *file,
315                                                                        GError           **error);
316 static gboolean       gtk_file_chooser_default_remove_shortcut_folder (GtkFileChooser    *chooser,
317                                                                        GFile             *file,
318                                                                        GError           **error);
319 static GSList *       gtk_file_chooser_default_list_shortcut_folders  (GtkFileChooser    *chooser);
320
321 static void           gtk_file_chooser_default_get_default_size       (GtkFileChooserEmbed *chooser_embed,
322                                                                        gint                *default_width,
323                                                                        gint                *default_height);
324 static gboolean       gtk_file_chooser_default_should_respond         (GtkFileChooserEmbed *chooser_embed);
325 static void           gtk_file_chooser_default_initial_focus          (GtkFileChooserEmbed *chooser_embed);
326
327 static void location_popup_handler  (GtkFileChooserDefault *impl,
328                                      const gchar           *path);
329 static void location_popup_on_paste_handler (GtkFileChooserDefault *impl);
330 static void location_toggle_popup_handler   (GtkFileChooserDefault *impl);
331 static void up_folder_handler       (GtkFileChooserDefault *impl);
332 static void down_folder_handler     (GtkFileChooserDefault *impl);
333 static void home_folder_handler     (GtkFileChooserDefault *impl);
334 static void desktop_folder_handler  (GtkFileChooserDefault *impl);
335 static void quick_bookmark_handler  (GtkFileChooserDefault *impl,
336                                      gint                   bookmark_index);
337 static void show_hidden_handler     (GtkFileChooserDefault *impl);
338 static void search_shortcut_handler (GtkFileChooserDefault *impl);
339 static void recent_shortcut_handler (GtkFileChooserDefault *impl);
340 static void update_appearance       (GtkFileChooserDefault *impl);
341
342 static void set_current_filter   (GtkFileChooserDefault *impl,
343                                   GtkFileFilter         *filter);
344 static void check_preview_change (GtkFileChooserDefault *impl);
345
346 static void filter_combo_changed       (GtkComboBox           *combo_box,
347                                         GtkFileChooserDefault *impl);
348
349 static gboolean shortcuts_key_press_event_cb (GtkWidget             *widget,
350                                               GdkEventKey           *event,
351                                               GtkFileChooserDefault *impl);
352
353 static gboolean shortcuts_select_func   (GtkTreeSelection      *selection,
354                                          GtkTreeModel          *model,
355                                          GtkTreePath           *path,
356                                          gboolean               path_currently_selected,
357                                          gpointer               data);
358 static gboolean shortcuts_get_selected  (GtkFileChooserDefault *impl,
359                                          GtkTreeIter           *iter);
360 static void shortcuts_activate_iter (GtkFileChooserDefault *impl,
361                                      GtkTreeIter           *iter);
362 static int shortcuts_get_index (GtkFileChooserDefault *impl,
363                                 ShortcutsIndex         where);
364 static int shortcut_find_position (GtkFileChooserDefault *impl,
365                                    GFile                 *file);
366
367 static void bookmarks_check_add_sensitivity (GtkFileChooserDefault *impl);
368
369 static gboolean list_select_func   (GtkTreeSelection      *selection,
370                                     GtkTreeModel          *model,
371                                     GtkTreePath           *path,
372                                     gboolean               path_currently_selected,
373                                     gpointer               data);
374
375 static void list_selection_changed     (GtkTreeSelection      *tree_selection,
376                                         GtkFileChooserDefault *impl);
377 static void list_row_activated         (GtkTreeView           *tree_view,
378                                         GtkTreePath           *path,
379                                         GtkTreeViewColumn     *column,
380                                         GtkFileChooserDefault *impl);
381
382 static void select_func (GtkFileSystemModel *model,
383                          GtkTreePath        *path,
384                          GtkTreeIter        *iter,
385                          gpointer            user_data);
386
387 static void path_bar_clicked (GtkPathBar            *path_bar,
388                               GFile                 *file,
389                               GFile                 *child,
390                               gboolean               child_is_hidden,
391                               GtkFileChooserDefault *impl);
392
393 static void add_bookmark_button_clicked_cb    (GtkButton             *button,
394                                                GtkFileChooserDefault *impl);
395 static void remove_bookmark_button_clicked_cb (GtkButton             *button,
396                                                GtkFileChooserDefault *impl);
397 static void save_folder_combo_changed_cb      (GtkComboBox           *combo,
398                                                GtkFileChooserDefault *impl);
399
400 static void list_icon_data_func (GtkTreeViewColumn *tree_column,
401                                  GtkCellRenderer   *cell,
402                                  GtkTreeModel      *tree_model,
403                                  GtkTreeIter       *iter,
404                                  gpointer           data);
405 static void list_name_data_func (GtkTreeViewColumn *tree_column,
406                                  GtkCellRenderer   *cell,
407                                  GtkTreeModel      *tree_model,
408                                  GtkTreeIter       *iter,
409                                  gpointer           data);
410 #if 0
411 static void list_size_data_func (GtkTreeViewColumn *tree_column,
412                                  GtkCellRenderer   *cell,
413                                  GtkTreeModel      *tree_model,
414                                  GtkTreeIter       *iter,
415                                  gpointer           data);
416 #endif
417 static void list_mtime_data_func (GtkTreeViewColumn *tree_column,
418                                   GtkCellRenderer   *cell,
419                                   GtkTreeModel      *tree_model,
420                                   GtkTreeIter       *iter,
421                                   gpointer           data);
422
423 static GFileInfo       *get_list_file_info (GtkFileChooserDefault *impl,
424                                             GtkTreeIter           *iter);
425
426 static void load_remove_timer (GtkFileChooserDefault *impl);
427 static void browse_files_center_selected_row (GtkFileChooserDefault *impl);
428
429 static void location_button_toggled_cb (GtkToggleButton *toggle,
430                                         GtkFileChooserDefault *impl);
431 static void location_switch_to_path_bar (GtkFileChooserDefault *impl);
432
433 static void     search_stop_searching        (GtkFileChooserDefault *impl,
434                                               gboolean               remove_query);
435 static void     search_clear_model           (GtkFileChooserDefault *impl, 
436                                               gboolean               remove_from_treeview);
437 static gboolean search_should_respond        (GtkFileChooserDefault *impl);
438 static void     search_switch_to_browse_mode (GtkFileChooserDefault *impl);
439 static GSList  *search_get_selected_files    (GtkFileChooserDefault *impl);
440 static void     search_entry_activate_cb     (GtkEntry              *entry, 
441                                               gpointer               data);
442 static void     settings_load                (GtkFileChooserDefault *impl);
443 static void     search_get_valid_child_iter  (GtkFileChooserDefault *impl,
444                                               GtkTreeIter           *child_iter,
445                                               GtkTreeIter           *iter);
446
447 static void     recent_stop_loading          (GtkFileChooserDefault *impl);
448 static void     recent_clear_model           (GtkFileChooserDefault *impl,
449                                               gboolean               remove_from_treeview);
450 static gboolean recent_should_respond        (GtkFileChooserDefault *impl);
451 static void     recent_switch_to_browse_mode (GtkFileChooserDefault *impl);
452 static GSList * recent_get_selected_files    (GtkFileChooserDefault *impl);
453 static void     recent_get_valid_child_iter  (GtkFileChooserDefault *impl,
454                                               GtkTreeIter           *child_iter,
455                                               GtkTreeIter           *iter);
456 static void     set_file_system_backend      (GtkFileChooserDefault *impl);
457
458
459
460 \f
461
462 /* Drag and drop interface declarations */
463
464 typedef struct {
465   GtkTreeModelFilter parent;
466
467   GtkFileChooserDefault *impl;
468 } ShortcutsPaneModelFilter;
469
470 typedef struct {
471   GtkTreeModelFilterClass parent_class;
472 } ShortcutsPaneModelFilterClass;
473
474 #define SHORTCUTS_PANE_MODEL_FILTER_TYPE (_shortcuts_pane_model_filter_get_type ())
475 #define SHORTCUTS_PANE_MODEL_FILTER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SHORTCUTS_PANE_MODEL_FILTER_TYPE, ShortcutsPaneModelFilter))
476
477 static void shortcuts_pane_model_filter_drag_source_iface_init (GtkTreeDragSourceIface *iface);
478
479 G_DEFINE_TYPE_WITH_CODE (ShortcutsPaneModelFilter,
480                          _shortcuts_pane_model_filter,
481                          GTK_TYPE_TREE_MODEL_FILTER,
482                          G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_DRAG_SOURCE,
483                                                 shortcuts_pane_model_filter_drag_source_iface_init))
484
485 static GtkTreeModel *shortcuts_pane_model_filter_new (GtkFileChooserDefault *impl,
486                                                       GtkTreeModel          *child_model,
487                                                       GtkTreePath           *root);
488
489
490 typedef struct {
491   GtkTreeModelSort parent;
492
493   GtkFileChooserDefault *impl;
494 } RecentModelSort;
495
496 typedef struct {
497   GtkTreeModelSortClass parent_class;
498 } RecentModelSortClass;
499
500 #define RECENT_MODEL_SORT_TYPE (_recent_model_sort_get_type ())
501 #define RECENT_MODEL_SORT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), RECENT_MODEL_SORT_TYPE, RecentModelSort))
502
503 static void recent_model_sort_drag_source_iface_init (GtkTreeDragSourceIface *iface);
504
505 G_DEFINE_TYPE_WITH_CODE (RecentModelSort,
506                          _recent_model_sort,
507                          GTK_TYPE_TREE_MODEL_SORT,
508                          G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_DRAG_SOURCE,
509                                                 recent_model_sort_drag_source_iface_init));
510
511 static GtkTreeModel *recent_model_sort_new (GtkFileChooserDefault *impl,
512                                             GtkTreeModel          *child_model);
513
514
515 typedef struct {
516   GtkTreeModelSort parent;
517
518   GtkFileChooserDefault *impl;
519 } SearchModelSort;
520
521 typedef struct {
522   GtkTreeModelSortClass parent_class;
523 } SearchModelSortClass;
524
525 #define SEARCH_MODEL_SORT_TYPE (_search_model_sort_get_type ())
526 #define SEARCH_MODEL_SORT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SEARCH_MODEL_SORT_TYPE, SearchModelSort))
527
528 static void search_model_sort_drag_source_iface_init (GtkTreeDragSourceIface *iface);
529
530 G_DEFINE_TYPE_WITH_CODE (SearchModelSort,
531                          _search_model_sort,
532                          GTK_TYPE_TREE_MODEL_SORT,
533                          G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_DRAG_SOURCE,
534                                                 search_model_sort_drag_source_iface_init));
535
536 static GtkTreeModel *search_model_sort_new (GtkFileChooserDefault *impl,
537                                             GtkTreeModel          *child_model);
538
539 \f
540
541 G_DEFINE_TYPE_WITH_CODE (GtkFileChooserDefault, _gtk_file_chooser_default, GTK_TYPE_VBOX,
542                          G_IMPLEMENT_INTERFACE (GTK_TYPE_FILE_CHOOSER,
543                                                 gtk_file_chooser_default_iface_init)
544                          G_IMPLEMENT_INTERFACE (GTK_TYPE_FILE_CHOOSER_EMBED,
545                                                 gtk_file_chooser_embed_default_iface_init));                                            
546
547 static void
548 _gtk_file_chooser_default_class_init (GtkFileChooserDefaultClass *class)
549 {
550   static const guint quick_bookmark_keyvals[10] = {
551     GDK_1, GDK_2, GDK_3, GDK_4, GDK_5, GDK_6, GDK_7, GDK_8, GDK_9, GDK_0
552   };
553   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
554   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
555   GtkBindingSet *binding_set;
556   int i;
557
558   gobject_class->finalize = gtk_file_chooser_default_finalize;
559   gobject_class->constructor = gtk_file_chooser_default_constructor;
560   gobject_class->set_property = gtk_file_chooser_default_set_property;
561   gobject_class->get_property = gtk_file_chooser_default_get_property;
562   gobject_class->dispose = gtk_file_chooser_default_dispose;
563
564   widget_class->show_all = gtk_file_chooser_default_show_all;
565   widget_class->map = gtk_file_chooser_default_map;
566   widget_class->unmap = gtk_file_chooser_default_unmap;
567   widget_class->hierarchy_changed = gtk_file_chooser_default_hierarchy_changed;
568   widget_class->style_set = gtk_file_chooser_default_style_set;
569   widget_class->screen_changed = gtk_file_chooser_default_screen_changed;
570   widget_class->size_allocate = gtk_file_chooser_default_size_allocate;
571
572   signals[LOCATION_POPUP] =
573     g_signal_new_class_handler (I_("location-popup"),
574                                 G_OBJECT_CLASS_TYPE (class),
575                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
576                                 G_CALLBACK (location_popup_handler),
577                                 NULL, NULL,
578                                 _gtk_marshal_VOID__STRING,
579                                 G_TYPE_NONE, 1, G_TYPE_STRING);
580
581   signals[LOCATION_POPUP_ON_PASTE] =
582     g_signal_new_class_handler (I_("location-popup-on-paste"),
583                                 G_OBJECT_CLASS_TYPE (class),
584                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
585                                 G_CALLBACK (location_popup_on_paste_handler),
586                                 NULL, NULL,
587                                 _gtk_marshal_VOID__VOID,
588                                 G_TYPE_NONE, 0);
589
590   signals[LOCATION_TOGGLE_POPUP] =
591     g_signal_new_class_handler (I_("location-toggle-popup"),
592                                 G_OBJECT_CLASS_TYPE (class),
593                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
594                                 G_CALLBACK (location_toggle_popup_handler),
595                                 NULL, NULL,
596                                 _gtk_marshal_VOID__VOID,
597                                 G_TYPE_NONE, 0);
598
599   signals[UP_FOLDER] =
600     g_signal_new_class_handler (I_("up-folder"),
601                                 G_OBJECT_CLASS_TYPE (class),
602                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
603                                 G_CALLBACK (up_folder_handler),
604                                 NULL, NULL,
605                                 _gtk_marshal_VOID__VOID,
606                                 G_TYPE_NONE, 0);
607
608   signals[DOWN_FOLDER] =
609     g_signal_new_class_handler (I_("down-folder"),
610                                 G_OBJECT_CLASS_TYPE (class),
611                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
612                                 G_CALLBACK (down_folder_handler),
613                                 NULL, NULL,
614                                 _gtk_marshal_VOID__VOID,
615                                 G_TYPE_NONE, 0);
616
617   signals[HOME_FOLDER] =
618     g_signal_new_class_handler (I_("home-folder"),
619                                 G_OBJECT_CLASS_TYPE (class),
620                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
621                                 G_CALLBACK (home_folder_handler),
622                                 NULL, NULL,
623                                 _gtk_marshal_VOID__VOID,
624                                 G_TYPE_NONE, 0);
625
626   signals[DESKTOP_FOLDER] =
627     g_signal_new_class_handler (I_("desktop-folder"),
628                                 G_OBJECT_CLASS_TYPE (class),
629                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
630                                 G_CALLBACK (desktop_folder_handler),
631                                 NULL, NULL,
632                                 _gtk_marshal_VOID__VOID,
633                                 G_TYPE_NONE, 0);
634
635   signals[QUICK_BOOKMARK] =
636     g_signal_new_class_handler (I_("quick-bookmark"),
637                                 G_OBJECT_CLASS_TYPE (class),
638                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
639                                 G_CALLBACK (quick_bookmark_handler),
640                                 NULL, NULL,
641                                 _gtk_marshal_VOID__INT,
642                                 G_TYPE_NONE, 1, G_TYPE_INT);
643
644   signals[SHOW_HIDDEN] =
645     g_signal_new_class_handler (I_("show-hidden"),
646                                 G_OBJECT_CLASS_TYPE (class),
647                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
648                                 G_CALLBACK (show_hidden_handler),
649                                 NULL, NULL,
650                                 _gtk_marshal_VOID__VOID,
651                                 G_TYPE_NONE, 0);
652
653   signals[SEARCH_SHORTCUT] =
654     g_signal_new_class_handler (I_("search-shortcut"),
655                                 G_OBJECT_CLASS_TYPE (class),
656                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
657                                 G_CALLBACK (search_shortcut_handler),
658                                 NULL, NULL,
659                                 _gtk_marshal_VOID__VOID,
660                                 G_TYPE_NONE, 0);
661
662   signals[RECENT_SHORTCUT] =
663     g_signal_new_class_handler (I_("recent-shortcut"),
664                                 G_OBJECT_CLASS_TYPE (class),
665                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
666                                 G_CALLBACK (recent_shortcut_handler),
667                                 NULL, NULL,
668                                 _gtk_marshal_VOID__VOID,
669                                 G_TYPE_NONE, 0);
670
671   binding_set = gtk_binding_set_by_class (class);
672
673   gtk_binding_entry_add_signal (binding_set,
674                                 GDK_l, GDK_CONTROL_MASK,
675                                 "location-toggle-popup",
676                                 0);
677
678   gtk_binding_entry_add_signal (binding_set,
679                                 GDK_slash, 0,
680                                 "location-popup",
681                                 1, G_TYPE_STRING, "/");
682   gtk_binding_entry_add_signal (binding_set,
683                                 GDK_KP_Divide, 0,
684                                 "location-popup",
685                                 1, G_TYPE_STRING, "/");
686
687 #ifdef G_OS_UNIX
688   gtk_binding_entry_add_signal (binding_set,
689                                 GDK_asciitilde, 0,
690                                 "location-popup",
691                                 1, G_TYPE_STRING, "~");
692 #endif
693
694   gtk_binding_entry_add_signal (binding_set,
695                                 GDK_v, GDK_CONTROL_MASK,
696                                 "location-popup-on-paste",
697                                 0);
698   gtk_binding_entry_add_signal (binding_set,
699                                 GDK_Up, GDK_MOD1_MASK,
700                                 "up-folder",
701                                 0);
702   gtk_binding_entry_add_signal (binding_set,
703                                 GDK_BackSpace, 0,
704                                 "up-folder",
705                                 0);
706   gtk_binding_entry_add_signal (binding_set,
707                                 GDK_KP_Up, GDK_MOD1_MASK,
708                                 "up-folder",
709                                 0);
710
711   gtk_binding_entry_add_signal (binding_set,
712                                 GDK_Down, GDK_MOD1_MASK,
713                                 "down-folder",
714                                 0);
715   gtk_binding_entry_add_signal (binding_set,
716                                 GDK_KP_Down, GDK_MOD1_MASK,
717                                 "down-folder",
718                                 0);
719
720   gtk_binding_entry_add_signal (binding_set,
721                                 GDK_Home, GDK_MOD1_MASK,
722                                 "home-folder",
723                                 0);
724   gtk_binding_entry_add_signal (binding_set,
725                                 GDK_KP_Home, GDK_MOD1_MASK,
726                                 "home-folder",
727                                 0);
728   gtk_binding_entry_add_signal (binding_set,
729                                 GDK_d, GDK_MOD1_MASK,
730                                 "desktop-folder",
731                                 0);
732   gtk_binding_entry_add_signal (binding_set,
733                                 GDK_h, GDK_CONTROL_MASK,
734                                 "show-hidden",
735                                 0);
736   gtk_binding_entry_add_signal (binding_set,
737                                 GDK_s, GDK_MOD1_MASK,
738                                 "search-shortcut",
739                                 0);
740   gtk_binding_entry_add_signal (binding_set,
741                                 GDK_r, GDK_MOD1_MASK,
742                                 "recent-shortcut",
743                                 0);
744
745   for (i = 0; i < 10; i++)
746     gtk_binding_entry_add_signal (binding_set,
747                                   quick_bookmark_keyvals[i], GDK_MOD1_MASK,
748                                   "quick-bookmark",
749                                   1, G_TYPE_INT, i);
750
751   _gtk_file_chooser_install_properties (gobject_class);
752 }
753
754 static void
755 gtk_file_chooser_default_iface_init (GtkFileChooserIface *iface)
756 {
757   iface->select_file = gtk_file_chooser_default_select_file;
758   iface->unselect_file = gtk_file_chooser_default_unselect_file;
759   iface->select_all = gtk_file_chooser_default_select_all;
760   iface->unselect_all = gtk_file_chooser_default_unselect_all;
761   iface->get_files = gtk_file_chooser_default_get_files;
762   iface->get_preview_file = gtk_file_chooser_default_get_preview_file;
763   iface->get_file_system = gtk_file_chooser_default_get_file_system;
764   iface->set_current_folder = gtk_file_chooser_default_set_current_folder;
765   iface->get_current_folder = gtk_file_chooser_default_get_current_folder;
766   iface->set_current_name = gtk_file_chooser_default_set_current_name;
767   iface->add_filter = gtk_file_chooser_default_add_filter;
768   iface->remove_filter = gtk_file_chooser_default_remove_filter;
769   iface->list_filters = gtk_file_chooser_default_list_filters;
770   iface->add_shortcut_folder = gtk_file_chooser_default_add_shortcut_folder;
771   iface->remove_shortcut_folder = gtk_file_chooser_default_remove_shortcut_folder;
772   iface->list_shortcut_folders = gtk_file_chooser_default_list_shortcut_folders;
773 }
774
775 static void
776 gtk_file_chooser_embed_default_iface_init (GtkFileChooserEmbedIface *iface)
777 {
778   iface->get_default_size = gtk_file_chooser_default_get_default_size;
779   iface->should_respond = gtk_file_chooser_default_should_respond;
780   iface->initial_focus = gtk_file_chooser_default_initial_focus;
781 }
782
783 static void
784 _gtk_file_chooser_default_init (GtkFileChooserDefault *impl)
785 {
786   profile_start ("start", NULL);
787 #ifdef PROFILE_FILE_CHOOSER
788   access ("MARK: *** CREATE FILE CHOOSER", F_OK);
789 #endif
790   impl->local_only = TRUE;
791   impl->preview_widget_active = TRUE;
792   impl->use_preview_label = TRUE;
793   impl->select_multiple = FALSE;
794   impl->show_hidden = FALSE;
795   impl->icon_size = FALLBACK_ICON_SIZE;
796   impl->load_state = LOAD_EMPTY;
797   impl->reload_state = RELOAD_EMPTY;
798   impl->pending_select_files = NULL;
799   impl->location_mode = LOCATION_MODE_PATH_BAR;
800   impl->operation_mode = OPERATION_MODE_BROWSE;
801   impl->recent_manager = gtk_recent_manager_get_default ();
802
803   gtk_box_set_spacing (GTK_BOX (impl), 12);
804
805   set_file_system_backend (impl);
806
807   profile_end ("end", NULL);
808 }
809
810 /* Frees the data columns for the specified iter in the shortcuts model*/
811 static void
812 shortcuts_free_row_data (GtkFileChooserDefault *impl,
813                          GtkTreeIter           *iter)
814 {
815   gpointer col_data;
816   ShortcutType shortcut_type;
817   GCancellable *cancellable;
818
819   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), iter,
820                       SHORTCUTS_COL_DATA, &col_data,
821                       SHORTCUTS_COL_TYPE, &shortcut_type,
822                       SHORTCUTS_COL_CANCELLABLE, &cancellable,
823                       -1);
824
825   if (cancellable)
826     g_cancellable_cancel (cancellable);
827
828   if (!(shortcut_type == SHORTCUT_TYPE_FILE || 
829         shortcut_type == SHORTCUT_TYPE_VOLUME) ||
830       !col_data)
831     return;
832
833   if (shortcut_type == SHORTCUT_TYPE_VOLUME)
834     {
835       GtkFileSystemVolume *volume;
836
837       volume = col_data;
838       _gtk_file_system_volume_free (volume);
839     }
840   else
841     {
842       GFile *file;
843
844       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
845
846       file = col_data;
847       g_object_unref (file);
848     }
849 }
850
851 /* Frees all the data columns in the shortcuts model */
852 static void
853 shortcuts_free (GtkFileChooserDefault *impl)
854 {
855   GtkTreeIter iter;
856
857   if (!impl->shortcuts_model)
858     return;
859
860   if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
861     do
862       {
863         shortcuts_free_row_data (impl, &iter);
864       }
865     while (gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter));
866
867   g_object_unref (impl->shortcuts_model);
868   impl->shortcuts_model = NULL;
869 }
870
871 static void
872 pending_select_files_free (GtkFileChooserDefault *impl)
873 {
874   g_slist_foreach (impl->pending_select_files, (GFunc) g_object_unref, NULL);
875   g_slist_free (impl->pending_select_files);
876   impl->pending_select_files = NULL;
877 }
878
879 static void
880 pending_select_files_add (GtkFileChooserDefault *impl,
881                           GFile                 *file)
882 {
883   impl->pending_select_files =
884     g_slist_prepend (impl->pending_select_files, g_object_ref (file));
885 }
886
887 /* Used from gtk_tree_selection_selected_foreach() */
888 static void
889 store_selection_foreach (GtkTreeModel *model,
890                          GtkTreePath  *path,
891                          GtkTreeIter  *iter,
892                          gpointer      data)
893 {
894   GtkFileChooserDefault *impl;
895   GtkTreeIter child_iter;
896   GFile *file;
897
898   impl = GTK_FILE_CHOOSER_DEFAULT (data);
899
900   gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model, &child_iter, iter);
901
902   file = _gtk_file_system_model_get_file (impl->browse_files_model, &child_iter);
903   pending_select_files_add (impl, file);
904 }
905
906 /* Stores the current selection in the list of paths to select; this is used to
907  * preserve the selection when reloading the current folder.
908  */
909 static void
910 pending_select_files_store_selection (GtkFileChooserDefault *impl)
911 {
912   GtkTreeSelection *selection;
913
914   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
915   gtk_tree_selection_selected_foreach (selection, store_selection_foreach, impl);
916 }
917
918 static void
919 gtk_file_chooser_default_finalize (GObject *object)
920 {
921   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (object);
922   GSList *l;
923
924   if (impl->shortcuts_pane_filter_model)
925     g_object_unref (impl->shortcuts_pane_filter_model);
926
927   if (impl->shortcuts_combo_filter_model)
928     g_object_unref (impl->shortcuts_combo_filter_model);
929
930   shortcuts_free (impl);
931
932   g_object_unref (impl->file_system);
933
934   g_free (impl->browse_files_last_selected_name);
935
936   for (l = impl->filters; l; l = l->next)
937     {
938       GtkFileFilter *filter;
939
940       filter = GTK_FILE_FILTER (l->data);
941       g_object_unref (filter);
942     }
943   g_slist_free (impl->filters);
944
945   if (impl->current_filter)
946     g_object_unref (impl->current_filter);
947
948   if (impl->current_volume_file)
949     g_object_unref (impl->current_volume_file);
950
951   if (impl->current_folder)
952     g_object_unref (impl->current_folder);
953
954   if (impl->preview_file)
955     g_object_unref (impl->preview_file);
956
957   load_remove_timer (impl);
958
959   /* Free all the Models we have */
960   if (impl->browse_files_model)
961     g_object_unref (impl->browse_files_model);
962
963   if (impl->sort_model)
964     g_object_unref (impl->sort_model);
965
966   search_clear_model (impl, FALSE);
967   recent_clear_model (impl, FALSE);
968
969   g_free (impl->preview_display_name);
970
971   g_free (impl->edited_new_text);
972
973   G_OBJECT_CLASS (_gtk_file_chooser_default_parent_class)->finalize (object);
974 }
975
976 /* Shows an error dialog set as transient for the specified window */
977 static void
978 error_message_with_parent (GtkWindow  *parent,
979                            const char *msg,
980                            const char *detail)
981 {
982   GtkWidget *dialog;
983
984   dialog = gtk_message_dialog_new (parent,
985                                    GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
986                                    GTK_MESSAGE_ERROR,
987                                    GTK_BUTTONS_OK,
988                                    "%s",
989                                    msg);
990   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
991                                             "%s", detail);
992
993   if (parent->group)
994     gtk_window_group_add_window (parent->group, GTK_WINDOW (dialog));
995
996   gtk_dialog_run (GTK_DIALOG (dialog));
997   gtk_widget_destroy (dialog);
998 }
999
1000 /* Returns a toplevel GtkWindow, or NULL if none */
1001 static GtkWindow *
1002 get_toplevel (GtkWidget *widget)
1003 {
1004   GtkWidget *toplevel;
1005
1006   toplevel = gtk_widget_get_toplevel (widget);
1007   if (!GTK_WIDGET_TOPLEVEL (toplevel))
1008     return NULL;
1009   else
1010     return GTK_WINDOW (toplevel);
1011 }
1012
1013 /* Shows an error dialog for the file chooser */
1014 static void
1015 error_message (GtkFileChooserDefault *impl,
1016                const char            *msg,
1017                const char            *detail)
1018 {
1019   error_message_with_parent (get_toplevel (GTK_WIDGET (impl)), msg, detail);
1020 }
1021
1022 /* Shows a simple error dialog relative to a path.  Frees the GError as well. */
1023 static void
1024 error_dialog (GtkFileChooserDefault *impl,
1025               const char            *msg,
1026               GFile                 *file,
1027               GError                *error)
1028 {
1029   if (error)
1030     {
1031       char *uri = NULL;
1032       char *text;
1033
1034       if (file)
1035         uri = g_file_get_uri (file);
1036       text = g_strdup_printf (msg, uri);
1037       error_message (impl, text, error->message);
1038       g_free (text);
1039       g_free (uri);
1040       g_error_free (error);
1041     }
1042 }
1043
1044 /* Displays an error message about not being able to get information for a file.
1045  * Frees the GError as well.
1046  */
1047 static void
1048 error_getting_info_dialog (GtkFileChooserDefault *impl,
1049                            GFile                 *file,
1050                            GError                *error)
1051 {
1052   error_dialog (impl,
1053                 _("Could not retrieve information about the file"),
1054                 file, error);
1055 }
1056
1057 /* Shows an error dialog about not being able to add a bookmark */
1058 static void
1059 error_adding_bookmark_dialog (GtkFileChooserDefault *impl,
1060                               GFile                 *file,
1061                               GError                *error)
1062 {
1063   error_dialog (impl,
1064                 _("Could not add a bookmark"),
1065                 file, error);
1066 }
1067
1068 /* Shows an error dialog about not being able to remove a bookmark */
1069 static void
1070 error_removing_bookmark_dialog (GtkFileChooserDefault *impl,
1071                                 GFile                 *file,
1072                                 GError                *error)
1073 {
1074   error_dialog (impl,
1075                 _("Could not remove bookmark"),
1076                 file, error);
1077 }
1078
1079 /* Shows an error dialog about not being able to create a folder */
1080 static void
1081 error_creating_folder_dialog (GtkFileChooserDefault *impl,
1082                               GFile                 *file,
1083                               GError                *error)
1084 {
1085   error_dialog (impl, 
1086                 _("The folder could not be created"), 
1087                 file, error);
1088 }
1089
1090 /* Shows an error about not being able to create a folder because a file with
1091  * the same name is already there.
1092  */
1093 static void
1094 error_creating_folder_over_existing_file_dialog (GtkFileChooserDefault *impl,
1095                                                  GFile                 *file,
1096                                                  GError                *error)
1097 {
1098   error_dialog (impl,
1099                 _("The folder could not be created, as a file with the same "
1100                   "name already exists.  Try using a different name for the "
1101                   "folder, or rename the file first."),
1102                 file, error);
1103 }
1104
1105 /* Shows an error dialog about not being able to create a filename */
1106 static void
1107 error_building_filename_dialog (GtkFileChooserDefault *impl,
1108                                 GError                *error)
1109 {
1110   error_dialog (impl, _("Invalid file name"), 
1111                 NULL, error);
1112 }
1113
1114 /* Shows an error dialog when we cannot switch to a folder */
1115 static void
1116 error_changing_folder_dialog (GtkFileChooserDefault *impl,
1117                               GFile                 *file,
1118                               GError                *error)
1119 {
1120   error_dialog (impl, _("The folder contents could not be displayed"),
1121                 file, error);
1122 }
1123
1124 /* Changes folders, displaying an error dialog if this fails */
1125 static gboolean
1126 change_folder_and_display_error (GtkFileChooserDefault *impl,
1127                                  GFile                 *file,
1128                                  gboolean               clear_entry)
1129 {
1130   GError *error;
1131   gboolean result;
1132
1133   g_return_val_if_fail (G_IS_FILE (file), FALSE);
1134
1135   /* We copy the path because of this case:
1136    *
1137    * list_row_activated()
1138    *   fetches path from model; path belongs to the model (*)
1139    *   calls change_folder_and_display_error()
1140    *     calls gtk_file_chooser_set_current_folder_file()
1141    *       changing folders fails, sets model to NULL, thus freeing the path in (*)
1142    */
1143
1144   error = NULL;
1145   result = gtk_file_chooser_default_update_current_folder (GTK_FILE_CHOOSER (impl), file, TRUE, clear_entry, &error);
1146
1147   if (!result)
1148     error_changing_folder_dialog (impl, file, error);
1149
1150   return result;
1151 }
1152
1153 static void
1154 update_preview_widget_visibility (GtkFileChooserDefault *impl)
1155 {
1156   if (impl->use_preview_label)
1157     {
1158       if (!impl->preview_label)
1159         {
1160           impl->preview_label = gtk_label_new (impl->preview_display_name);
1161           gtk_box_pack_start (GTK_BOX (impl->preview_box), impl->preview_label, FALSE, FALSE, 0);
1162           gtk_box_reorder_child (GTK_BOX (impl->preview_box), impl->preview_label, 0);
1163           gtk_label_set_ellipsize (GTK_LABEL (impl->preview_label), PANGO_ELLIPSIZE_MIDDLE);
1164           gtk_widget_show (impl->preview_label);
1165         }
1166     }
1167   else
1168     {
1169       if (impl->preview_label)
1170         {
1171           gtk_widget_destroy (impl->preview_label);
1172           impl->preview_label = NULL;
1173         }
1174     }
1175
1176   if (impl->preview_widget_active && impl->preview_widget)
1177     gtk_widget_show (impl->preview_box);
1178   else
1179     gtk_widget_hide (impl->preview_box);
1180
1181   g_signal_emit_by_name (impl, "default-size-changed");
1182 }
1183
1184 static void
1185 set_preview_widget (GtkFileChooserDefault *impl,
1186                     GtkWidget             *preview_widget)
1187 {
1188   if (preview_widget == impl->preview_widget)
1189     return;
1190
1191   if (impl->preview_widget)
1192     gtk_container_remove (GTK_CONTAINER (impl->preview_box),
1193                           impl->preview_widget);
1194
1195   impl->preview_widget = preview_widget;
1196   if (impl->preview_widget)
1197     {
1198       gtk_widget_show (impl->preview_widget);
1199       gtk_box_pack_start (GTK_BOX (impl->preview_box), impl->preview_widget, TRUE, TRUE, 0);
1200       gtk_box_reorder_child (GTK_BOX (impl->preview_box),
1201                              impl->preview_widget,
1202                              (impl->use_preview_label && impl->preview_label) ? 1 : 0);
1203     }
1204
1205   update_preview_widget_visibility (impl);
1206 }
1207
1208 /* Renders a "Search" icon at an appropriate size for a tree view */
1209 static GdkPixbuf *
1210 render_search_icon (GtkFileChooserDefault *impl)
1211 {
1212   return gtk_widget_render_icon (GTK_WIDGET (impl), GTK_STOCK_FIND, GTK_ICON_SIZE_MENU, NULL);
1213 }
1214
1215 static GdkPixbuf *
1216 render_recent_icon (GtkFileChooserDefault *impl)
1217 {
1218   GtkIconTheme *theme;
1219   GdkPixbuf *retval;
1220
1221   if (gtk_widget_has_screen (GTK_WIDGET (impl)))
1222     theme = gtk_icon_theme_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
1223   else
1224     theme = gtk_icon_theme_get_default ();
1225
1226   retval = gtk_icon_theme_load_icon (theme, "document-open-recent",
1227                                      impl->icon_size, 0,
1228                                      NULL);
1229
1230   /* fallback */
1231   if (!retval)
1232     retval = gtk_widget_render_icon (GTK_WIDGET (impl), GTK_STOCK_FILE, GTK_ICON_SIZE_MENU, NULL);
1233
1234   return retval;
1235 }
1236
1237
1238 /* Re-reads all the icons for the shortcuts, used when the theme changes */
1239 struct ReloadIconsData
1240 {
1241   GtkFileChooserDefault *impl;
1242   GtkTreeRowReference *row_ref;
1243 };
1244
1245 static void
1246 shortcuts_reload_icons_get_info_cb (GCancellable *cancellable,
1247                                     GFileInfo    *info,
1248                                     const GError *error,
1249                                     gpointer      user_data)
1250 {
1251   GdkPixbuf *pixbuf;
1252   GtkTreeIter iter;
1253   GtkTreePath *path;
1254   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
1255   struct ReloadIconsData *data = user_data;
1256
1257   if (!g_slist_find (data->impl->reload_icon_cancellables, cancellable))
1258     goto out;
1259
1260   data->impl->reload_icon_cancellables = g_slist_remove (data->impl->reload_icon_cancellables, cancellable);
1261
1262   if (cancelled || error)
1263     goto out;
1264
1265   pixbuf = _gtk_file_info_render_icon (info, GTK_WIDGET (data->impl), data->impl->icon_size);
1266
1267   path = gtk_tree_row_reference_get_path (data->row_ref);
1268   gtk_tree_model_get_iter (GTK_TREE_MODEL (data->impl->shortcuts_model), &iter, path);
1269   gtk_list_store_set (data->impl->shortcuts_model, &iter,
1270                       SHORTCUTS_COL_PIXBUF, pixbuf,
1271                       -1);
1272   gtk_tree_path_free (path);
1273
1274   if (pixbuf)
1275     g_object_unref (pixbuf);
1276
1277 out:
1278   gtk_tree_row_reference_free (data->row_ref);
1279   g_object_unref (data->impl);
1280   g_free (data);
1281
1282   g_object_unref (cancellable);
1283 }
1284
1285 static void
1286 shortcuts_reload_icons (GtkFileChooserDefault *impl)
1287 {
1288   GSList *l;
1289   GtkTreeIter iter;
1290
1291   profile_start ("start", NULL);
1292
1293   if (!gtk_tree_model_get_iter_first (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
1294     goto out;
1295
1296   for (l = impl->reload_icon_cancellables; l; l = l->next)
1297     {
1298       GCancellable *cancellable = G_CANCELLABLE (l->data);
1299       g_cancellable_cancel (cancellable);
1300     }
1301   g_slist_free (impl->reload_icon_cancellables);
1302   impl->reload_icon_cancellables = NULL;
1303
1304   do
1305     {
1306       gpointer data;
1307       ShortcutType shortcut_type;
1308       gboolean pixbuf_visible;
1309       GdkPixbuf *pixbuf;
1310
1311       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
1312                           SHORTCUTS_COL_DATA, &data,
1313                           SHORTCUTS_COL_TYPE, &shortcut_type,
1314                           SHORTCUTS_COL_PIXBUF_VISIBLE, &pixbuf_visible,
1315                           -1);
1316
1317       pixbuf = NULL;
1318       if (pixbuf_visible)
1319         {
1320           if (shortcut_type == SHORTCUT_TYPE_VOLUME)
1321             {
1322               GtkFileSystemVolume *volume;
1323
1324               volume = data;
1325               pixbuf = _gtk_file_system_volume_render_icon (volume, GTK_WIDGET (impl),
1326                                                             impl->icon_size, NULL);
1327             }
1328           else if (shortcut_type == SHORTCUT_TYPE_FILE)
1329             {
1330               if (g_file_is_native (G_FILE (data)))
1331                 {
1332                   GFile *file;
1333                   struct ReloadIconsData *info;
1334                   GtkTreePath *tree_path;
1335                   GCancellable *cancellable;
1336
1337                   file = data;
1338
1339                   info = g_new0 (struct ReloadIconsData, 1);
1340                   info->impl = g_object_ref (impl);
1341                   tree_path = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->shortcuts_model), &iter);
1342                   info->row_ref = gtk_tree_row_reference_new (GTK_TREE_MODEL (impl->shortcuts_model), tree_path);
1343                   gtk_tree_path_free (tree_path);
1344
1345                   cancellable = _gtk_file_system_get_info (impl->file_system, file,
1346                                                            "standard::icon",
1347                                                            shortcuts_reload_icons_get_info_cb,
1348                                                            info);
1349                   impl->reload_icon_cancellables = g_slist_append (impl->reload_icon_cancellables, cancellable);
1350                 }
1351               else
1352                 {
1353                   GtkIconTheme *icon_theme;
1354
1355                   /* Don't call get_info for remote paths to avoid latency and
1356                    * auth dialogs.
1357                    * If we switch to a better bookmarks file format (XBEL), we
1358                    * should use mime info to get a better icon.
1359                    */
1360                   icon_theme = gtk_icon_theme_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
1361                   pixbuf = gtk_icon_theme_load_icon (icon_theme, "folder-remote", 
1362                                                      impl->icon_size, 0, NULL);
1363                 }
1364             }
1365           else if (shortcut_type == SHORTCUT_TYPE_SEARCH)
1366             {
1367               pixbuf = render_search_icon (impl);
1368             }
1369           else if (shortcut_type == SHORTCUT_TYPE_RECENT)
1370             {
1371               pixbuf = render_recent_icon (impl);
1372             }
1373
1374           gtk_list_store_set (impl->shortcuts_model, &iter,
1375                               SHORTCUTS_COL_PIXBUF, pixbuf,
1376                               -1);
1377
1378           if (pixbuf)
1379             g_object_unref (pixbuf);
1380
1381         }
1382     }
1383   while (gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model),&iter));
1384
1385  out:
1386
1387   profile_end ("end", NULL);
1388 }
1389
1390 static void 
1391 shortcuts_find_folder (GtkFileChooserDefault *impl,
1392                        GFile                 *folder)
1393 {
1394   GtkTreeSelection *selection;
1395   int pos;
1396   GtkTreePath *path;
1397
1398   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view));
1399
1400   g_assert (folder != NULL);
1401   pos = shortcut_find_position (impl, folder);
1402   if (pos == -1)
1403     {
1404       gtk_tree_selection_unselect_all (selection);
1405       return;
1406     }
1407
1408   path = gtk_tree_path_new_from_indices (pos, -1);
1409   gtk_tree_selection_select_path (selection, path);
1410   gtk_tree_path_free (path);
1411 }
1412
1413 /* If a shortcut corresponds to the current folder, selects it */
1414 static void
1415 shortcuts_find_current_folder (GtkFileChooserDefault *impl)
1416 {
1417   shortcuts_find_folder (impl, impl->current_folder);
1418 }
1419
1420 /* Removes the specified number of rows from the shortcuts list */
1421 static void
1422 shortcuts_remove_rows (GtkFileChooserDefault *impl,
1423                        int                    start_row,
1424                        int                    n_rows)
1425 {
1426   GtkTreePath *path;
1427
1428   path = gtk_tree_path_new_from_indices (start_row, -1);
1429
1430   for (; n_rows; n_rows--)
1431     {
1432       GtkTreeIter iter;
1433
1434       if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->shortcuts_model), &iter, path))
1435         g_assert_not_reached ();
1436
1437       shortcuts_free_row_data (impl, &iter);
1438       gtk_list_store_remove (impl->shortcuts_model, &iter);
1439     }
1440
1441   gtk_tree_path_free (path);
1442 }
1443
1444 static void
1445 shortcuts_update_count (GtkFileChooserDefault *impl,
1446                         ShortcutsIndex         type,
1447                         gint                   value)
1448 {
1449   switch (type)
1450     {
1451       case SHORTCUTS_HOME:
1452         if (value < 0)
1453           impl->has_home = FALSE;
1454         else
1455           impl->has_home = TRUE;
1456         break;
1457
1458       case SHORTCUTS_DESKTOP:
1459         if (value < 0)
1460           impl->has_desktop = FALSE;
1461         else
1462           impl->has_desktop = TRUE;
1463         break;
1464
1465       case SHORTCUTS_VOLUMES:
1466         impl->num_volumes += value;
1467         break;
1468
1469       case SHORTCUTS_SHORTCUTS:
1470         impl->num_shortcuts += value;
1471         break;
1472
1473       case SHORTCUTS_BOOKMARKS:
1474         impl->num_bookmarks += value;
1475         break;
1476
1477       case SHORTCUTS_CURRENT_FOLDER:
1478         if (value < 0)
1479           impl->shortcuts_current_folder_active = FALSE;
1480         else
1481           impl->shortcuts_current_folder_active = TRUE;
1482         break;
1483
1484       default:
1485         /* nothing */
1486         break;
1487     }
1488 }
1489
1490 struct ShortcutsInsertRequest
1491 {
1492   GtkFileChooserDefault *impl;
1493   GFile *file;
1494   int pos;
1495   char *label_copy;
1496   GtkTreeRowReference *row_ref;
1497   ShortcutsIndex type;
1498   gboolean name_only;
1499   gboolean removable;
1500 };
1501
1502 static void
1503 get_file_info_finished (GCancellable *cancellable,
1504                         GFileInfo    *info,
1505                         const GError *error,
1506                         gpointer      data)
1507 {
1508   gint pos = -1;
1509   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
1510   GdkPixbuf *pixbuf;
1511   GtkTreePath *path;
1512   GtkTreeIter iter;
1513   GCancellable *model_cancellable;
1514   struct ShortcutsInsertRequest *request = data;
1515
1516   path = gtk_tree_row_reference_get_path (request->row_ref);
1517   if (!path)
1518     /* Handle doesn't exist anymore in the model */
1519     goto out;
1520
1521   pos = gtk_tree_path_get_indices (path)[0];
1522   gtk_tree_model_get_iter (GTK_TREE_MODEL (request->impl->shortcuts_model),
1523                            &iter, path);
1524   gtk_tree_path_free (path);
1525
1526   /* validate cancellable, else goto out */
1527   gtk_tree_model_get (GTK_TREE_MODEL (request->impl->shortcuts_model), &iter,
1528                       SHORTCUTS_COL_CANCELLABLE, &model_cancellable,
1529                       -1);
1530   if (cancellable != model_cancellable)
1531     goto out;
1532
1533   /* set the cancellable to NULL in the model (we unref later on) */
1534   gtk_list_store_set (request->impl->shortcuts_model, &iter,
1535                       SHORTCUTS_COL_CANCELLABLE, NULL,
1536                       -1);
1537
1538   if (cancelled)
1539     goto out;
1540
1541   if (!info)
1542     {
1543       gtk_list_store_remove (request->impl->shortcuts_model, &iter);
1544       shortcuts_update_count (request->impl, request->type, -1);
1545
1546       if (request->type == SHORTCUTS_HOME)
1547         {
1548           GFile *home;
1549
1550           home = g_file_new_for_path (g_get_home_dir ());
1551           error_getting_info_dialog (request->impl, home, g_error_copy (error));
1552           g_object_unref (home);
1553         }
1554       else if (request->type == SHORTCUTS_CURRENT_FOLDER)
1555         {
1556           /* Remove the current folder separator */
1557           gint separator_pos = shortcuts_get_index (request->impl, SHORTCUTS_CURRENT_FOLDER_SEPARATOR);
1558           shortcuts_remove_rows (request->impl, separator_pos, 1);
1559         }
1560
1561       goto out;
1562     }
1563   
1564   if (!request->label_copy)
1565     request->label_copy = g_strdup (g_file_info_get_display_name (info));
1566   pixbuf = _gtk_file_info_render_icon (info, GTK_WIDGET (request->impl),
1567                                        request->impl->icon_size);
1568
1569   gtk_list_store_set (request->impl->shortcuts_model, &iter,
1570                       SHORTCUTS_COL_PIXBUF, pixbuf,
1571                       SHORTCUTS_COL_PIXBUF_VISIBLE, TRUE,
1572                       SHORTCUTS_COL_NAME, request->label_copy,
1573                       SHORTCUTS_COL_TYPE, SHORTCUT_TYPE_FILE,
1574                       SHORTCUTS_COL_REMOVABLE, request->removable,
1575                       -1);
1576
1577   if (request->impl->shortcuts_pane_filter_model)
1578     gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (request->impl->shortcuts_pane_filter_model));
1579
1580   if (request->impl->shortcuts_combo_filter_model)
1581     gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (request->impl->shortcuts_combo_filter_model));
1582
1583   if (request->type == SHORTCUTS_CURRENT_FOLDER &&
1584       request->impl->save_folder_combo != NULL)
1585     {
1586       /* The current folder is updated via _activate_iter(), don't
1587        * have save_folder_combo_changed_cb() call _activate_iter()
1588        * again.
1589        */
1590       g_signal_handlers_block_by_func (request->impl->save_folder_combo,
1591                                        G_CALLBACK (save_folder_combo_changed_cb),
1592                                        request->impl);
1593       
1594       if (request->impl->has_search)
1595         pos -= 1;
1596
1597       if (request->impl->has_recent)
1598         pos -= 2;
1599
1600       gtk_combo_box_set_active (GTK_COMBO_BOX (request->impl->save_folder_combo), pos);
1601       g_signal_handlers_unblock_by_func (request->impl->save_folder_combo,
1602                                          G_CALLBACK (save_folder_combo_changed_cb),
1603                                          request->impl);
1604     }
1605
1606   if (pixbuf)
1607     g_object_unref (pixbuf);
1608
1609 out:
1610   g_object_unref (request->impl);
1611   g_object_unref (request->file);
1612   gtk_tree_row_reference_free (request->row_ref);
1613   g_free (request->label_copy);
1614   g_free (request);
1615
1616   g_object_unref (cancellable);
1617 }
1618
1619 /* FIXME: GtkFileSystem needs a function to split a remote path
1620  * into hostname and path components, or maybe just have a 
1621  * gtk_file_system_path_get_display_name().
1622  *
1623  * This function is also used in gtkfilechooserbutton.c
1624  */
1625 gchar *
1626 _gtk_file_chooser_label_for_file (GFile *file)
1627 {
1628   const gchar *path, *start, *end, *p;
1629   gchar *uri, *host, *label;
1630
1631   uri = g_file_get_uri (file);
1632
1633   start = strstr (uri, "://");
1634   if (start)
1635     {
1636       start += 3;
1637       path = strchr (start, '/');
1638       if (path)
1639         end = path;
1640       else
1641         {
1642           end = uri + strlen (uri);
1643           path = "/";
1644         }
1645
1646       /* strip username */
1647       p = strchr (start, '@');
1648       if (p && p < end)
1649         start = p + 1;
1650   
1651       p = strchr (start, ':');
1652       if (p && p < end)
1653         end = p;
1654   
1655       host = g_strndup (start, end - start);
1656   
1657       /* Translators: the first string is a path and the second string 
1658        * is a hostname. Nautilus and the panel contain the same string 
1659        * to translate. 
1660        */
1661       label = g_strdup_printf (_("%1$s on %2$s"), path, host);
1662   
1663       g_free (host);
1664     }
1665   else
1666     {
1667       label = g_strdup (uri);
1668     }
1669   
1670   g_free (uri);
1671
1672   return label;
1673 }
1674
1675 /* Inserts a path in the shortcuts tree, making a copy of it; alternatively,
1676  * inserts a volume.  A position of -1 indicates the end of the tree.
1677  */
1678 static void
1679 shortcuts_insert_file (GtkFileChooserDefault *impl,
1680                        int                    pos,
1681                        ShortcutType           shortcut_type,
1682                        GtkFileSystemVolume   *volume,
1683                        GFile                 *file,
1684                        const char            *label,
1685                        gboolean               removable,
1686                        ShortcutsIndex         type)
1687 {
1688   char *label_copy;
1689   GdkPixbuf *pixbuf = NULL;
1690   gpointer data = NULL;
1691   GtkTreeIter iter;
1692   GtkIconTheme *icon_theme;
1693
1694   profile_start ("start shortcut", NULL);
1695
1696   if (shortcut_type == SHORTCUT_TYPE_VOLUME)
1697     {
1698       data = volume;
1699       label_copy = _gtk_file_system_volume_get_display_name (volume);
1700       pixbuf = _gtk_file_system_volume_render_icon (volume, GTK_WIDGET (impl),
1701                                                     impl->icon_size, NULL);
1702     }
1703   else if (shortcut_type == SHORTCUT_TYPE_FILE)
1704     {
1705       if (g_file_is_native (file))
1706         {
1707           struct ShortcutsInsertRequest *request;
1708           GCancellable *cancellable;
1709           GtkTreePath *p;
1710
1711           request = g_new0 (struct ShortcutsInsertRequest, 1);
1712           request->impl = g_object_ref (impl);
1713           request->file = g_object_ref (file);
1714           request->name_only = TRUE;
1715           request->removable = removable;
1716           request->pos = pos;
1717           request->type = type;
1718           if (label)
1719             request->label_copy = g_strdup (label);
1720
1721           if (pos == -1)
1722             gtk_list_store_append (impl->shortcuts_model, &iter);
1723           else
1724             gtk_list_store_insert (impl->shortcuts_model, &iter, pos);
1725
1726           p = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->shortcuts_model), &iter);
1727           request->row_ref = gtk_tree_row_reference_new (GTK_TREE_MODEL (impl->shortcuts_model), p);
1728           gtk_tree_path_free (p);
1729
1730           cancellable = _gtk_file_system_get_info (request->impl->file_system, request->file,
1731                                                    "standard::is-hidden,standard::display-name,standard::icon",
1732                                                    get_file_info_finished, request);
1733
1734           gtk_list_store_set (impl->shortcuts_model, &iter,
1735                               SHORTCUTS_COL_DATA, g_object_ref (file),
1736                               SHORTCUTS_COL_TYPE, SHORTCUT_TYPE_FILE,
1737                               SHORTCUTS_COL_CANCELLABLE, cancellable,
1738                               -1);
1739
1740           shortcuts_update_count (impl, type, 1);
1741
1742           return;
1743         }
1744       else
1745         {
1746           /* Don't call get_info for remote paths to avoid latency and
1747            * auth dialogs.
1748            */
1749           data = g_object_ref (file);
1750           if (label)
1751             label_copy = g_strdup (label);
1752           else
1753             label_copy = _gtk_file_chooser_label_for_file (file);
1754
1755           /* If we switch to a better bookmarks file format (XBEL), we
1756            * should use mime info to get a better icon.
1757            */
1758           icon_theme = gtk_icon_theme_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
1759           pixbuf = gtk_icon_theme_load_icon (icon_theme, "folder-remote", 
1760                                              impl->icon_size, 0, NULL);
1761         }
1762     }
1763    else
1764     {
1765       g_assert_not_reached ();
1766
1767       return;
1768     }
1769
1770   if (pos == -1)
1771     gtk_list_store_append (impl->shortcuts_model, &iter);
1772   else
1773     gtk_list_store_insert (impl->shortcuts_model, &iter, pos);
1774
1775   shortcuts_update_count (impl, type, 1);
1776
1777   gtk_list_store_set (impl->shortcuts_model, &iter,
1778                       SHORTCUTS_COL_PIXBUF, pixbuf,
1779                       SHORTCUTS_COL_PIXBUF_VISIBLE, TRUE,
1780                       SHORTCUTS_COL_NAME, label_copy,
1781                       SHORTCUTS_COL_DATA, data,
1782                       SHORTCUTS_COL_TYPE, shortcut_type,
1783                       SHORTCUTS_COL_REMOVABLE, removable,
1784                       SHORTCUTS_COL_CANCELLABLE, NULL,
1785                       -1);
1786
1787   if (impl->shortcuts_pane_filter_model)
1788     gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (impl->shortcuts_pane_filter_model));
1789
1790   if (impl->shortcuts_combo_filter_model)
1791     gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (impl->shortcuts_combo_filter_model));
1792
1793   if (type == SHORTCUTS_CURRENT_FOLDER && impl->save_folder_combo != NULL)
1794     {
1795       /* The current folder is updated via _activate_iter(), don't
1796        * have save_folder_combo_changed_cb() call _activate_iter()
1797        * again.
1798        */
1799       gint combo_pos = shortcuts_get_index (impl, SHORTCUTS_CURRENT_FOLDER);
1800
1801       if (impl->has_search)
1802         combo_pos -= 1;
1803
1804       if (impl->has_recent)
1805         combo_pos -= 2;
1806       
1807       g_signal_handlers_block_by_func (impl->save_folder_combo,
1808                                        G_CALLBACK (save_folder_combo_changed_cb),
1809                                        impl);
1810       
1811       gtk_combo_box_set_active (GTK_COMBO_BOX (impl->save_folder_combo), combo_pos);
1812       g_signal_handlers_unblock_by_func (impl->save_folder_combo,
1813                                          G_CALLBACK (save_folder_combo_changed_cb),
1814                                          impl);
1815     }
1816
1817   g_free (label_copy);
1818
1819   if (pixbuf)
1820     g_object_unref (pixbuf);
1821
1822   profile_end ("end", NULL);
1823 }
1824
1825 static void
1826 shortcuts_append_search (GtkFileChooserDefault *impl)
1827 {
1828   GdkPixbuf *pixbuf;
1829   GtkTreeIter iter;
1830
1831   pixbuf = render_search_icon (impl);
1832
1833   gtk_list_store_append (impl->shortcuts_model, &iter);
1834   gtk_list_store_set (impl->shortcuts_model, &iter,
1835                       SHORTCUTS_COL_PIXBUF, pixbuf,
1836                       SHORTCUTS_COL_PIXBUF_VISIBLE, TRUE,
1837                       SHORTCUTS_COL_NAME, _("Search"),
1838                       SHORTCUTS_COL_DATA, NULL,
1839                       SHORTCUTS_COL_TYPE, SHORTCUT_TYPE_SEARCH,
1840                       SHORTCUTS_COL_REMOVABLE, FALSE,
1841                       -1);
1842
1843   if (pixbuf)
1844     g_object_unref (pixbuf);
1845
1846   impl->has_search = TRUE;
1847 }
1848
1849 static void
1850 shortcuts_append_recent (GtkFileChooserDefault *impl)
1851 {
1852   GdkPixbuf *pixbuf;
1853   GtkTreeIter iter;
1854
1855   pixbuf = render_recent_icon (impl);
1856
1857   gtk_list_store_append (impl->shortcuts_model, &iter);
1858   gtk_list_store_set (impl->shortcuts_model, &iter,
1859                       SHORTCUTS_COL_PIXBUF, pixbuf,
1860                       SHORTCUTS_COL_PIXBUF_VISIBLE, TRUE,
1861                       SHORTCUTS_COL_NAME, _("Recently Used"),
1862                       SHORTCUTS_COL_DATA, NULL,
1863                       SHORTCUTS_COL_TYPE, SHORTCUT_TYPE_RECENT,
1864                       SHORTCUTS_COL_REMOVABLE, FALSE,
1865                       -1);
1866   
1867   if (pixbuf)
1868     g_object_unref (pixbuf);
1869
1870   impl->has_recent = TRUE;
1871 }
1872
1873 /* Appends an item for the user's home directory to the shortcuts model */
1874 static void
1875 shortcuts_append_home (GtkFileChooserDefault *impl)
1876 {
1877   const char *home_path;
1878   GFile *home;
1879
1880   profile_start ("start", NULL);
1881
1882   home_path = g_get_home_dir ();
1883   if (home_path == NULL)
1884     {
1885       profile_end ("end - no home directory!?", NULL);
1886       return;
1887     }
1888
1889   home = g_file_new_for_path (home_path);
1890   shortcuts_insert_file (impl, -1, SHORTCUT_TYPE_FILE, NULL, home, NULL, FALSE, SHORTCUTS_HOME);
1891   impl->has_home = TRUE;
1892
1893   g_object_unref (home);
1894
1895   profile_end ("end", NULL);
1896 }
1897
1898 /* Appends the ~/Desktop directory to the shortcuts model */
1899 static void
1900 shortcuts_append_desktop (GtkFileChooserDefault *impl)
1901 {
1902   const char *name;
1903   GFile *file;
1904
1905   profile_start ("start", NULL);
1906
1907   name = g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP);
1908   file = g_file_new_for_path (name);
1909   shortcuts_insert_file (impl, -1, SHORTCUT_TYPE_FILE, NULL, file, _("Desktop"), FALSE, SHORTCUTS_DESKTOP);
1910   impl->has_desktop = TRUE;
1911
1912   /* We do not actually pop up an error dialog if there is no desktop directory
1913    * because some people may really not want to have one.
1914    */
1915
1916   g_object_unref (file);
1917
1918   profile_end ("end", NULL);
1919 }
1920
1921 /* Appends a list of GFile to the shortcuts model; returns how many were inserted */
1922 static int
1923 shortcuts_append_bookmarks (GtkFileChooserDefault *impl,
1924                             GSList                *bookmarks)
1925 {
1926   int start_row;
1927   int num_inserted;
1928   const gchar *label;
1929
1930   profile_start ("start", NULL);
1931
1932   start_row = shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS_SEPARATOR) + 1;
1933   num_inserted = 0;
1934
1935   for (; bookmarks; bookmarks = bookmarks->next)
1936     {
1937       GFile *file;
1938
1939       file = bookmarks->data;
1940
1941       if (impl->local_only && !g_file_is_native (file))
1942         continue;
1943
1944       if (shortcut_find_position (impl, file) != -1)
1945         continue;
1946
1947       label = _gtk_file_system_get_bookmark_label (impl->file_system, file);
1948
1949       shortcuts_insert_file (impl, start_row + num_inserted, SHORTCUT_TYPE_FILE, NULL, file, label, TRUE, SHORTCUTS_BOOKMARKS);
1950       num_inserted++;
1951     }
1952
1953   profile_end ("end", NULL);
1954
1955   return num_inserted;
1956 }
1957
1958 /* Returns the index for the corresponding item in the shortcuts bar */
1959 static int
1960 shortcuts_get_index (GtkFileChooserDefault *impl,
1961                      ShortcutsIndex         where)
1962 {
1963   int n;
1964
1965   n = 0;
1966   
1967   if (where == SHORTCUTS_SEARCH)
1968     goto out;
1969
1970   n += impl->has_search ? 1 : 0;
1971
1972   if (where == SHORTCUTS_RECENT)
1973     goto out;
1974
1975   n += impl->has_recent ? 1 : 0;
1976
1977   if (where == SHORTCUTS_RECENT_SEPARATOR)
1978     goto out;
1979
1980   n += impl->has_recent ? 1 : 0;
1981
1982   if (where == SHORTCUTS_HOME)
1983     goto out;
1984
1985   n += impl->has_home ? 1 : 0;
1986
1987   if (where == SHORTCUTS_DESKTOP)
1988     goto out;
1989
1990   n += impl->has_desktop ? 1 : 0;
1991
1992   if (where == SHORTCUTS_VOLUMES)
1993     goto out;
1994
1995   n += impl->num_volumes;
1996
1997   if (where == SHORTCUTS_SHORTCUTS)
1998     goto out;
1999
2000   n += impl->num_shortcuts;
2001
2002   if (where == SHORTCUTS_BOOKMARKS_SEPARATOR)
2003     goto out;
2004
2005   /* If there are no bookmarks there won't be a separator */
2006   n += (impl->num_bookmarks > 0) ? 1 : 0;
2007
2008   if (where == SHORTCUTS_BOOKMARKS)
2009     goto out;
2010
2011   n += impl->num_bookmarks;
2012
2013   if (where == SHORTCUTS_CURRENT_FOLDER_SEPARATOR)
2014     goto out;
2015
2016   n += 1;
2017
2018   if (where == SHORTCUTS_CURRENT_FOLDER)
2019     goto out;
2020
2021   g_assert_not_reached ();
2022
2023  out:
2024
2025   return n;
2026 }
2027
2028 /* Adds all the file system volumes to the shortcuts model */
2029 static void
2030 shortcuts_add_volumes (GtkFileChooserDefault *impl)
2031 {
2032   int start_row;
2033   GSList *list, *l;
2034   int n;
2035   gboolean old_changing_folders;
2036
2037   profile_start ("start", NULL);
2038
2039   old_changing_folders = impl->changing_folder;
2040   impl->changing_folder = TRUE;
2041
2042   start_row = shortcuts_get_index (impl, SHORTCUTS_VOLUMES);
2043   shortcuts_remove_rows (impl, start_row, impl->num_volumes);
2044   impl->num_volumes = 0;
2045
2046   list = _gtk_file_system_list_volumes (impl->file_system);
2047
2048   n = 0;
2049
2050   for (l = list; l; l = l->next)
2051     {
2052       GtkFileSystemVolume *volume;
2053
2054       volume = l->data;
2055
2056       if (impl->local_only)
2057         {
2058           if (_gtk_file_system_volume_is_mounted (volume))
2059             {
2060               GFile *base_file;
2061
2062               base_file = _gtk_file_system_volume_get_root (volume);
2063               if (base_file != NULL && !g_file_is_native (base_file))
2064                 continue;
2065             }
2066         }
2067
2068       shortcuts_insert_file (impl, start_row + n, SHORTCUT_TYPE_VOLUME, volume, NULL, NULL, FALSE, SHORTCUTS_VOLUMES);
2069       n++;
2070     }
2071
2072   impl->num_volumes = n;
2073   g_slist_free (list);
2074
2075   if (impl->shortcuts_pane_filter_model)
2076     gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (impl->shortcuts_pane_filter_model));
2077
2078   if (impl->shortcuts_combo_filter_model)
2079     gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (impl->shortcuts_combo_filter_model));
2080
2081   impl->changing_folder = old_changing_folders;
2082
2083   profile_end ("end", NULL);
2084 }
2085
2086 /* Inserts a separator node in the shortcuts list */
2087 static void
2088 shortcuts_insert_separator (GtkFileChooserDefault *impl,
2089                             ShortcutsIndex         where)
2090 {
2091   GtkTreeIter iter;
2092
2093   g_assert (where == SHORTCUTS_RECENT_SEPARATOR || 
2094             where == SHORTCUTS_BOOKMARKS_SEPARATOR || 
2095             where == SHORTCUTS_CURRENT_FOLDER_SEPARATOR);
2096
2097   gtk_list_store_insert (impl->shortcuts_model, &iter,
2098                          shortcuts_get_index (impl, where));
2099   gtk_list_store_set (impl->shortcuts_model, &iter,
2100                       SHORTCUTS_COL_PIXBUF, NULL,
2101                       SHORTCUTS_COL_PIXBUF_VISIBLE, FALSE,
2102                       SHORTCUTS_COL_NAME, NULL,
2103                       SHORTCUTS_COL_DATA, NULL,
2104                       SHORTCUTS_COL_TYPE, SHORTCUT_TYPE_SEPARATOR,
2105                       -1);
2106 }
2107
2108 /* Updates the list of bookmarks */
2109 static void
2110 shortcuts_add_bookmarks (GtkFileChooserDefault *impl)
2111 {
2112   GSList *bookmarks;
2113   gboolean old_changing_folders;
2114   GtkTreeIter iter;
2115   GFile *list_selected = NULL;
2116   GFile *combo_selected = NULL;
2117   ShortcutType shortcut_type;
2118   gpointer col_data;
2119
2120   profile_start ("start", NULL);
2121         
2122   old_changing_folders = impl->changing_folder;
2123   impl->changing_folder = TRUE;
2124
2125   if (shortcuts_get_selected (impl, &iter))
2126     {
2127       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), 
2128                           &iter, 
2129                           SHORTCUTS_COL_DATA, &col_data,
2130                           SHORTCUTS_COL_TYPE, &shortcut_type,
2131                           -1);
2132
2133       if (col_data && shortcut_type == SHORTCUT_TYPE_FILE)
2134         list_selected = g_object_ref (col_data);
2135     }
2136
2137   if (impl->save_folder_combo &&
2138       gtk_combo_box_get_active_iter (GTK_COMBO_BOX (impl->save_folder_combo), 
2139                                      &iter))
2140     {
2141       GtkTreeIter child_iter;
2142
2143       gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER  (impl->shortcuts_combo_filter_model),
2144                                                         &child_iter,
2145                                                         &iter);
2146       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), 
2147                           &child_iter, 
2148                           SHORTCUTS_COL_DATA, &col_data,
2149                           SHORTCUTS_COL_TYPE, &shortcut_type,
2150                           -1);
2151       
2152       if (col_data && shortcut_type == SHORTCUT_TYPE_FILE)
2153         combo_selected = g_object_ref (col_data);
2154     }
2155
2156   if (impl->num_bookmarks > 0)
2157     shortcuts_remove_rows (impl,
2158                            shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS_SEPARATOR),
2159                            impl->num_bookmarks + 1);
2160
2161   impl->num_bookmarks = 0;
2162   shortcuts_insert_separator (impl, SHORTCUTS_BOOKMARKS_SEPARATOR);
2163
2164   bookmarks = _gtk_file_system_list_bookmarks (impl->file_system);
2165   shortcuts_append_bookmarks (impl, bookmarks);
2166   g_slist_free (bookmarks);
2167
2168   if (impl->num_bookmarks == 0)
2169     shortcuts_remove_rows (impl, shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS_SEPARATOR), 1);
2170
2171   if (impl->shortcuts_pane_filter_model)
2172     gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (impl->shortcuts_pane_filter_model));
2173
2174   if (impl->shortcuts_combo_filter_model)
2175     gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (impl->shortcuts_combo_filter_model));
2176
2177   if (list_selected)
2178     {
2179       shortcuts_find_folder (impl, list_selected);
2180       g_object_unref (list_selected);
2181     }
2182
2183   if (combo_selected)
2184     {
2185       gint pos;
2186
2187       pos = shortcut_find_position (impl, combo_selected);
2188       if (pos != -1)
2189         {
2190           if (impl->has_search)
2191             pos -= 1;
2192
2193           if (impl->has_recent)
2194             pos -= 2;
2195
2196           gtk_combo_box_set_active (GTK_COMBO_BOX (impl->save_folder_combo), pos);
2197         }
2198
2199       g_object_unref (combo_selected);
2200     }
2201   
2202   impl->changing_folder = old_changing_folders;
2203
2204   profile_end ("end", NULL);
2205 }
2206
2207 /* Appends a separator and a row to the shortcuts list for the current folder */
2208 static void
2209 shortcuts_add_current_folder (GtkFileChooserDefault *impl)
2210 {
2211   int pos;
2212   gboolean success;
2213
2214   g_assert (!impl->shortcuts_current_folder_active);
2215
2216   success = TRUE;
2217
2218   g_assert (impl->current_folder != NULL);
2219
2220   pos = shortcut_find_position (impl, impl->current_folder);
2221   if (pos == -1)
2222     {
2223       GtkFileSystemVolume *volume;
2224       GFile *base_file;
2225
2226       /* Separator */
2227
2228       shortcuts_insert_separator (impl, SHORTCUTS_CURRENT_FOLDER_SEPARATOR);
2229
2230       /* Item */
2231
2232       pos = shortcuts_get_index (impl, SHORTCUTS_CURRENT_FOLDER);
2233
2234       volume = _gtk_file_system_get_volume_for_file (impl->file_system, impl->current_folder);
2235       if (volume)
2236         base_file = _gtk_file_system_volume_get_root (volume);
2237       else
2238         base_file = NULL;
2239
2240       if (base_file && g_file_equal (base_file, impl->current_folder))
2241         shortcuts_insert_file (impl, pos, SHORTCUT_TYPE_VOLUME, volume, NULL, NULL, FALSE, SHORTCUTS_CURRENT_FOLDER);
2242       else
2243         shortcuts_insert_file (impl, pos, SHORTCUT_TYPE_FILE, NULL, impl->current_folder, NULL, FALSE, SHORTCUTS_CURRENT_FOLDER);
2244
2245       if (base_file)
2246         g_object_unref (base_file);
2247     }
2248   else if (impl->save_folder_combo != NULL)
2249     {
2250       if (impl->has_search)
2251         pos -= 1;
2252
2253       if (impl->has_recent)
2254         pos -= 2; /* + separator */
2255
2256       gtk_combo_box_set_active (GTK_COMBO_BOX (impl->save_folder_combo), pos);
2257     }
2258 }
2259
2260 /* Updates the current folder row in the shortcuts model */
2261 static void
2262 shortcuts_update_current_folder (GtkFileChooserDefault *impl)
2263 {
2264   int pos;
2265
2266   pos = shortcuts_get_index (impl, SHORTCUTS_CURRENT_FOLDER_SEPARATOR);
2267
2268   if (impl->shortcuts_current_folder_active)
2269     {
2270       shortcuts_remove_rows (impl, pos, 2);
2271       impl->shortcuts_current_folder_active = FALSE;
2272     }
2273
2274   shortcuts_add_current_folder (impl);
2275 }
2276
2277 /* Filter function used for the shortcuts filter model */
2278 static gboolean
2279 shortcuts_pane_filter_cb (GtkTreeModel *model,
2280                           GtkTreeIter  *iter,
2281                           gpointer      data)
2282 {
2283   GtkFileChooserDefault *impl;
2284   GtkTreePath *path;
2285   int pos;
2286
2287   impl = GTK_FILE_CHOOSER_DEFAULT (data);
2288
2289   path = gtk_tree_model_get_path (model, iter);
2290   if (!path)
2291     return FALSE;
2292
2293   pos = *gtk_tree_path_get_indices (path);
2294   gtk_tree_path_free (path);
2295
2296   return (pos < shortcuts_get_index (impl, SHORTCUTS_CURRENT_FOLDER_SEPARATOR));
2297 }
2298
2299 /* Creates the list model for shortcuts */
2300 static void
2301 shortcuts_model_create (GtkFileChooserDefault *impl)
2302 {
2303   /* Keep this order in sync with the SHORCUTS_COL_* enum values */
2304   impl->shortcuts_model = gtk_list_store_new (SHORTCUTS_COL_NUM_COLUMNS,
2305                                               GDK_TYPE_PIXBUF,  /* pixbuf */
2306                                               G_TYPE_STRING,    /* name */
2307                                               G_TYPE_POINTER,   /* path or volume */
2308                                               G_TYPE_INT,       /* ShortcutType */
2309                                               G_TYPE_BOOLEAN,   /* removable */
2310                                               G_TYPE_BOOLEAN,   /* pixbuf cell visibility */
2311                                               G_TYPE_POINTER);  /* GCancellable */
2312
2313   if (search_is_possible (impl))
2314     {
2315       shortcuts_append_search (impl);
2316     }
2317
2318   if (impl->recent_manager)
2319     {
2320       shortcuts_append_recent (impl);
2321       shortcuts_insert_separator (impl, SHORTCUTS_RECENT_SEPARATOR);
2322     }
2323   
2324   if (impl->file_system)
2325     {
2326       shortcuts_append_home (impl);
2327       shortcuts_append_desktop (impl);
2328       shortcuts_add_volumes (impl);
2329     }
2330
2331   impl->shortcuts_pane_filter_model = shortcuts_pane_model_filter_new (impl,
2332                                                                        GTK_TREE_MODEL (impl->shortcuts_model),
2333                                                                        NULL);
2334
2335   gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (impl->shortcuts_pane_filter_model),
2336                                           shortcuts_pane_filter_cb,
2337                                           impl,
2338                                           NULL);
2339 }
2340
2341 /* Callback used when the "New Folder" button is clicked */
2342 static void
2343 new_folder_button_clicked (GtkButton             *button,
2344                            GtkFileChooserDefault *impl)
2345 {
2346   GtkTreeIter iter;
2347   GtkTreePath *path;
2348
2349   if (!impl->browse_files_model)
2350     return; /* FIXME: this sucks.  Disable the New Folder button or something. */
2351
2352   /* Prevent button from being clicked twice */
2353   gtk_widget_set_sensitive (impl->browse_new_folder_button, FALSE);
2354
2355   _gtk_file_system_model_add_editable (impl->browse_files_model, &iter);
2356
2357   path = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->browse_files_model), &iter);
2358   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (impl->browse_files_tree_view),
2359                                 path, impl->list_name_column,
2360                                 FALSE, 0.0, 0.0);
2361
2362   g_object_set (impl->list_name_renderer, "editable", TRUE, NULL);
2363   gtk_tree_view_set_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view),
2364                             path,
2365                             impl->list_name_column,
2366                             TRUE);
2367
2368   gtk_tree_path_free (path);
2369 }
2370
2371 /* Idle handler for creating a new folder after editing its name cell, or for
2372  * canceling the editing.
2373  */
2374 static gboolean
2375 edited_idle_cb (GtkFileChooserDefault *impl)
2376 {
2377   GDK_THREADS_ENTER ();
2378   
2379   g_source_destroy (impl->edited_idle);
2380   impl->edited_idle = NULL;
2381
2382   _gtk_file_system_model_remove_editable (impl->browse_files_model);
2383   g_object_set (impl->list_name_renderer, "editable", FALSE, NULL);
2384
2385   gtk_widget_set_sensitive (impl->browse_new_folder_button, TRUE);
2386
2387   if (impl->edited_new_text) /* not cancelled? */
2388     {
2389       GError *error = NULL;
2390       GFile *file;
2391
2392       file = g_file_get_child_for_display_name (impl->current_folder,
2393                                                 impl->edited_new_text,
2394                                                 &error);
2395       if (file)
2396         {
2397           GError *error = NULL;
2398
2399           if (!g_file_make_directory (file, NULL, &error))
2400             change_folder_and_display_error (impl, file, FALSE);
2401           else
2402             error_creating_folder_dialog (impl, file, error);
2403
2404           g_object_unref (file);
2405         }
2406       else
2407         error_creating_folder_dialog (impl, file, error);
2408
2409       g_free (impl->edited_new_text);
2410       impl->edited_new_text = NULL;
2411     }
2412
2413   GDK_THREADS_LEAVE ();
2414
2415   return FALSE;
2416 }
2417
2418 static void
2419 queue_edited_idle (GtkFileChooserDefault *impl,
2420                    const gchar           *new_text)
2421 {
2422   /* We create the folder in an idle handler so that we don't modify the tree
2423    * just now.
2424    */
2425
2426   if (!impl->edited_idle)
2427     {
2428       impl->edited_idle = g_idle_source_new ();
2429       g_source_set_closure (impl->edited_idle,
2430                             g_cclosure_new_object (G_CALLBACK (edited_idle_cb),
2431                                                    G_OBJECT (impl)));
2432       g_source_attach (impl->edited_idle, NULL);
2433     }
2434
2435   g_free (impl->edited_new_text);
2436   impl->edited_new_text = g_strdup (new_text);
2437 }
2438
2439 /* Callback used from the text cell renderer when the new folder is named */
2440 static void
2441 renderer_edited_cb (GtkCellRendererText   *cell_renderer_text,
2442                     const gchar           *path,
2443                     const gchar           *new_text,
2444                     GtkFileChooserDefault *impl)
2445 {
2446   /* work around bug #154921 */
2447   g_object_set (cell_renderer_text, 
2448                 "mode", GTK_CELL_RENDERER_MODE_INERT, NULL);
2449   queue_edited_idle (impl, new_text);
2450 }
2451
2452 /* Callback used from the text cell renderer when the new folder edition gets
2453  * canceled.
2454  */
2455 static void
2456 renderer_editing_canceled_cb (GtkCellRendererText   *cell_renderer_text,
2457                               GtkFileChooserDefault *impl)
2458 {
2459   /* work around bug #154921 */
2460   g_object_set (cell_renderer_text, 
2461                 "mode", GTK_CELL_RENDERER_MODE_INERT, NULL);
2462   queue_edited_idle (impl, NULL);
2463 }
2464
2465 /* Creates the widgets for the filter combo box */
2466 static GtkWidget *
2467 filter_create (GtkFileChooserDefault *impl)
2468 {
2469   impl->filter_combo = gtk_combo_box_new_text ();
2470   gtk_combo_box_set_focus_on_click (GTK_COMBO_BOX (impl->filter_combo), FALSE);
2471
2472   g_signal_connect (impl->filter_combo, "changed",
2473                     G_CALLBACK (filter_combo_changed), impl);
2474
2475   gtk_widget_set_tooltip_text (impl->filter_combo,
2476                                _("Select which types of files are shown"));
2477
2478   return impl->filter_combo;
2479 }
2480
2481 static GtkWidget *
2482 button_new (GtkFileChooserDefault *impl,
2483             const char            *text,
2484             const char            *stock_id,
2485             gboolean               sensitive,
2486             gboolean               show,
2487             GCallback              callback)
2488 {
2489   GtkWidget *button;
2490   GtkWidget *image;
2491
2492   button = gtk_button_new_with_mnemonic (text);
2493   image = gtk_image_new_from_stock (stock_id, GTK_ICON_SIZE_BUTTON);
2494   gtk_button_set_image (GTK_BUTTON (button), image);
2495
2496   gtk_widget_set_sensitive (button, sensitive);
2497   g_signal_connect (button, "clicked", callback, impl);
2498
2499   if (show)
2500     gtk_widget_show (button);
2501
2502   return button;
2503 }
2504
2505 /* Looks for a path among the shortcuts; returns its index or -1 if it doesn't exist */
2506 static int
2507 shortcut_find_position (GtkFileChooserDefault *impl,
2508                         GFile                 *file)
2509 {
2510   GtkTreeIter iter;
2511   int i;
2512   int current_folder_separator_idx;
2513
2514   if (!gtk_tree_model_get_iter_first (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
2515     return -1;
2516
2517   current_folder_separator_idx = shortcuts_get_index (impl, SHORTCUTS_CURRENT_FOLDER_SEPARATOR);
2518
2519 #if 0
2520   /* FIXME: is this still needed? */
2521   if (current_folder_separator_idx >= impl->shortcuts_model->length)
2522     return -1;
2523 #endif
2524
2525   for (i = 0; i < current_folder_separator_idx; i++)
2526     {
2527       gpointer col_data;
2528       ShortcutType shortcut_type;
2529
2530       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
2531                           SHORTCUTS_COL_DATA, &col_data,
2532                           SHORTCUTS_COL_TYPE, &shortcut_type,
2533                           -1);
2534
2535       if (col_data)
2536         {
2537           if (shortcut_type == SHORTCUT_TYPE_VOLUME)
2538             {
2539               GtkFileSystemVolume *volume;
2540               GFile *base_file;
2541               gboolean exists;
2542
2543               volume = col_data;
2544               base_file = _gtk_file_system_volume_get_root (volume);
2545
2546               exists = base_file && g_file_equal (file, base_file);
2547
2548               if (base_file)
2549                 g_object_unref (base_file);
2550
2551               if (exists)
2552                 return i;
2553             }
2554           else if (shortcut_type == SHORTCUT_TYPE_FILE)
2555             {
2556               GFile *model_file;
2557
2558               model_file = col_data;
2559
2560               if (model_file && g_file_equal (model_file, file))
2561                 return i;
2562             }
2563         }
2564
2565       if (i < current_folder_separator_idx - 1)
2566         {
2567           if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
2568             g_assert_not_reached ();
2569         }
2570     }
2571
2572   return -1;
2573 }
2574
2575 /* Tries to add a bookmark from a path name */
2576 static gboolean
2577 shortcuts_add_bookmark_from_file (GtkFileChooserDefault *impl,
2578                                   GFile                 *file,
2579                                   int                    pos)
2580 {
2581   GError *error;
2582
2583   g_return_val_if_fail (G_IS_FILE (file), FALSE);
2584
2585   if (shortcut_find_position (impl, file) != -1)
2586     return FALSE;
2587
2588   error = NULL;
2589   if (!_gtk_file_system_insert_bookmark (impl->file_system, file, pos, &error))
2590     {
2591       error_adding_bookmark_dialog (impl, file, error);
2592       return FALSE;
2593     }
2594
2595   return TRUE;
2596 }
2597
2598 static void
2599 add_bookmark_foreach_cb (GtkTreeModel *model,
2600                          GtkTreePath  *path,
2601                          GtkTreeIter  *iter,
2602                          gpointer      data)
2603 {
2604   GtkFileChooserDefault *impl;
2605   GtkFileSystemModel *fs_model;
2606   GtkTreeIter child_iter;
2607   GFile *file;
2608
2609   impl = (GtkFileChooserDefault *) data;
2610
2611   switch (impl->operation_mode)
2612     {
2613     case OPERATION_MODE_BROWSE:
2614       fs_model = impl->browse_files_model;
2615       gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model, &child_iter, iter);
2616       file = _gtk_file_system_model_get_file (fs_model, &child_iter);
2617       break;
2618
2619     case OPERATION_MODE_SEARCH:
2620       search_get_valid_child_iter (impl, &child_iter, iter);
2621       gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
2622                           SEARCH_MODEL_COL_FILE, &file,
2623                           -1);
2624       break;
2625
2626     case OPERATION_MODE_RECENT:
2627       recent_get_valid_child_iter (impl, &child_iter, iter);
2628       gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
2629                           RECENT_MODEL_COL_FILE, &file,
2630                           -1);
2631       break;
2632     }
2633
2634   shortcuts_add_bookmark_from_file (impl, file, -1);
2635 }
2636
2637 /* Adds a bookmark from the currently selected item in the file list */
2638 static void
2639 bookmarks_add_selected_folder (GtkFileChooserDefault *impl)
2640 {
2641   GtkTreeSelection *selection;
2642
2643   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
2644
2645   if (gtk_tree_selection_count_selected_rows (selection) == 0)
2646     shortcuts_add_bookmark_from_file (impl, impl->current_folder, -1);
2647   else
2648     gtk_tree_selection_selected_foreach (selection,
2649                                          add_bookmark_foreach_cb,
2650                                          impl);
2651 }
2652
2653 /* Callback used when the "Add bookmark" button is clicked */
2654 static void
2655 add_bookmark_button_clicked_cb (GtkButton *button,
2656                                 GtkFileChooserDefault *impl)
2657 {
2658   bookmarks_add_selected_folder (impl);
2659 }
2660
2661 /* Returns TRUE plus an iter in the shortcuts_model if a row is selected;
2662  * returns FALSE if no shortcut is selected.
2663  */
2664 static gboolean
2665 shortcuts_get_selected (GtkFileChooserDefault *impl,
2666                         GtkTreeIter           *iter)
2667 {
2668   GtkTreeSelection *selection;
2669   GtkTreeIter parent_iter;
2670
2671   if (!impl->browse_shortcuts_tree_view)
2672     return FALSE;
2673
2674   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view));
2675
2676   if (!gtk_tree_selection_get_selected (selection, NULL, &parent_iter))
2677     return FALSE;
2678
2679   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (impl->shortcuts_pane_filter_model),
2680                                                     iter,
2681                                                     &parent_iter);
2682   return TRUE;
2683 }
2684
2685 /* Removes the selected bookmarks */
2686 static void
2687 remove_selected_bookmarks (GtkFileChooserDefault *impl)
2688 {
2689   GtkTreeIter iter;
2690   gpointer col_data;
2691   GFile *file;
2692   gboolean removable;
2693   GError *error;
2694
2695   if (!shortcuts_get_selected (impl, &iter))
2696     return;
2697
2698   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
2699                       SHORTCUTS_COL_DATA, &col_data,
2700                       SHORTCUTS_COL_REMOVABLE, &removable,
2701                       -1);
2702
2703   if (!removable)
2704     return;
2705
2706   g_assert (col_data != NULL);
2707
2708   file = col_data;
2709
2710   error = NULL;
2711   if (!_gtk_file_system_remove_bookmark (impl->file_system, file, &error))
2712     error_removing_bookmark_dialog (impl, file, error);
2713 }
2714
2715 /* Callback used when the "Remove bookmark" button is clicked */
2716 static void
2717 remove_bookmark_button_clicked_cb (GtkButton *button,
2718                                    GtkFileChooserDefault *impl)
2719 {
2720   remove_selected_bookmarks (impl);
2721 }
2722
2723 struct selection_check_closure {
2724   GtkFileChooserDefault *impl;
2725   int num_selected;
2726   gboolean all_files;
2727   gboolean all_folders;
2728 };
2729
2730 /* Used from gtk_tree_selection_selected_foreach() */
2731 static void
2732 selection_check_foreach_cb (GtkTreeModel *model,
2733                             GtkTreePath  *path,
2734                             GtkTreeIter  *iter,
2735                             gpointer      data)
2736 {
2737   struct selection_check_closure *closure;
2738   GtkTreeIter child_iter;
2739   GFileInfo *info;
2740   gboolean is_folder;
2741
2742   closure = data;
2743   closure->num_selected++;
2744
2745   switch (closure->impl->operation_mode)
2746     {
2747     case OPERATION_MODE_BROWSE:
2748       gtk_tree_model_sort_convert_iter_to_child_iter (closure->impl->sort_model, &child_iter, iter);
2749       info = _gtk_file_system_model_get_info (closure->impl->browse_files_model, &child_iter);
2750       is_folder = info ? (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY) : FALSE;
2751       break;
2752
2753     case OPERATION_MODE_SEARCH:
2754       search_get_valid_child_iter (closure->impl, &child_iter, iter);
2755       gtk_tree_model_get (GTK_TREE_MODEL (closure->impl->search_model), &child_iter,
2756                           SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
2757                           -1);
2758       break;
2759
2760     case OPERATION_MODE_RECENT:
2761       recent_get_valid_child_iter (closure->impl, &child_iter, iter);
2762       gtk_tree_model_get (GTK_TREE_MODEL (closure->impl->recent_model), &child_iter,
2763                           RECENT_MODEL_COL_IS_FOLDER, &is_folder,
2764                           -1);
2765       break;
2766     }
2767
2768   closure->all_folders = closure->all_folders && is_folder;
2769   closure->all_files = closure->all_files && !is_folder;
2770 }
2771
2772 /* Checks whether the selected items in the file list are all files or all folders */
2773 static void
2774 selection_check (GtkFileChooserDefault *impl,
2775                  gint                  *num_selected,
2776                  gboolean              *all_files,
2777                  gboolean              *all_folders)
2778 {
2779   struct selection_check_closure closure;
2780   GtkTreeSelection *selection;
2781
2782   closure.impl = impl;
2783   closure.num_selected = 0;
2784   closure.all_files = TRUE;
2785   closure.all_folders = TRUE;
2786
2787   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
2788   gtk_tree_selection_selected_foreach (selection,
2789                                        selection_check_foreach_cb,
2790                                        &closure);
2791
2792   g_assert (closure.num_selected == 0 || !(closure.all_files && closure.all_folders));
2793
2794   if (num_selected)
2795     *num_selected = closure.num_selected;
2796
2797   if (all_files)
2798     *all_files = closure.all_files;
2799
2800   if (all_folders)
2801     *all_folders = closure.all_folders;
2802 }
2803
2804 struct get_selected_file_closure {
2805   GtkFileChooserDefault *impl;
2806   GFile *file;
2807 };
2808
2809 static void
2810 get_selected_file_foreach_cb (GtkTreeModel *model,
2811                               GtkTreePath  *path,
2812                               GtkTreeIter  *iter,
2813                               gpointer      data)
2814 {
2815   struct get_selected_file_closure *closure;
2816   GtkTreeIter child_iter;
2817
2818   closure = data;
2819
2820   switch (closure->impl->operation_mode)
2821     {
2822     case OPERATION_MODE_BROWSE:
2823       gtk_tree_model_sort_convert_iter_to_child_iter (closure->impl->sort_model, &child_iter, iter);
2824       closure->file = _gtk_file_system_model_get_file (closure->impl->browse_files_model, &child_iter);
2825       break;
2826
2827     case OPERATION_MODE_SEARCH:
2828       search_get_valid_child_iter (closure->impl, &child_iter, iter);
2829       gtk_tree_model_get (GTK_TREE_MODEL (closure->impl->search_model), &child_iter,
2830                           SEARCH_MODEL_COL_FILE, &closure->file,
2831                           -1);
2832       break;
2833
2834     case OPERATION_MODE_RECENT:
2835       recent_get_valid_child_iter (closure->impl, &child_iter, iter);
2836       gtk_tree_model_get (GTK_TREE_MODEL (closure->impl->recent_model), &child_iter,
2837                           RECENT_MODEL_COL_FILE, &closure->file,
2838                           -1);
2839       break;
2840     }
2841 }
2842
2843 /* Returns a selected path from the file list */
2844 static GFile *
2845 get_selected_file (GtkFileChooserDefault *impl)
2846 {
2847   struct get_selected_file_closure closure;
2848   GtkTreeSelection *selection;
2849
2850   closure.impl = impl;
2851   closure.file = NULL;
2852
2853   selection =  gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
2854   gtk_tree_selection_selected_foreach (selection,
2855                                        get_selected_file_foreach_cb,
2856                                        &closure);
2857
2858   return closure.file;
2859 }
2860
2861 typedef struct {
2862   GtkFileChooserDefault *impl;
2863   gchar *tip;
2864 } UpdateTooltipData;
2865
2866 static void 
2867 update_tooltip (GtkTreeModel      *model,
2868                 GtkTreePath       *path,
2869                 GtkTreeIter       *iter,
2870                 gpointer           data)
2871 {
2872   UpdateTooltipData *udata = data;
2873   GtkTreeIter child_iter;
2874   GFileInfo *info;
2875
2876   if (udata->tip == NULL)
2877     {
2878       const gchar *display_name;
2879
2880       switch (udata->impl->operation_mode)
2881         {
2882         case OPERATION_MODE_BROWSE:
2883           gtk_tree_model_sort_convert_iter_to_child_iter (udata->impl->sort_model,
2884                                                           &child_iter,
2885                                                           iter);
2886           info = _gtk_file_system_model_get_info (udata->impl->browse_files_model, &child_iter);
2887           display_name = g_file_info_get_display_name (info);
2888           break;
2889
2890         case OPERATION_MODE_SEARCH:
2891           search_get_valid_child_iter (udata->impl, &child_iter, iter);
2892           gtk_tree_model_get (GTK_TREE_MODEL (udata->impl->search_model), &child_iter,
2893                               SEARCH_MODEL_COL_DISPLAY_NAME, &display_name,
2894                               -1);
2895           break;
2896
2897         case OPERATION_MODE_RECENT:
2898           recent_get_valid_child_iter (udata->impl, &child_iter, iter);
2899           gtk_tree_model_get (GTK_TREE_MODEL (udata->impl->recent_model), &child_iter,
2900                               RECENT_MODEL_COL_DISPLAY_NAME, &display_name,
2901                               -1);
2902           break;
2903         }
2904
2905       udata->tip = g_strdup_printf (_("Add the folder '%s' to the bookmarks"),
2906                                     display_name);
2907     }
2908 }
2909
2910
2911 /* Sensitize the "add bookmark" button if all the selected items are folders, or
2912  * if there are no selected items *and* the current folder is not in the
2913  * bookmarks list.  De-sensitize the button otherwise.
2914  */
2915 static void
2916 bookmarks_check_add_sensitivity (GtkFileChooserDefault *impl)
2917 {
2918   gint num_selected;
2919   gboolean all_folders;
2920   gboolean active;
2921   gchar *tip;
2922
2923   selection_check (impl, &num_selected, NULL, &all_folders);
2924
2925   if (num_selected == 0)
2926     active = (impl->current_folder != NULL) && (shortcut_find_position (impl, impl->current_folder) == -1);
2927   else if (num_selected == 1)
2928     {
2929       GFile *file;
2930
2931       file = get_selected_file (impl);
2932       active = all_folders && (shortcut_find_position (impl, file) == -1);
2933     }
2934   else
2935     active = all_folders;
2936
2937   gtk_widget_set_sensitive (impl->browse_shortcuts_add_button, active);
2938
2939   if (impl->browse_files_popup_menu_add_shortcut_item)
2940     gtk_widget_set_sensitive (impl->browse_files_popup_menu_add_shortcut_item,
2941                               (num_selected == 0) ? FALSE : active);
2942
2943   if (active)
2944     {
2945       if (num_selected == 0)
2946         tip = g_strdup_printf (_("Add the current folder to the bookmarks"));
2947       else if (num_selected > 1)
2948         tip = g_strdup_printf (_("Add the selected folders to the bookmarks"));
2949       else
2950         {
2951           GtkTreeSelection *selection;
2952           UpdateTooltipData data;
2953
2954           selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
2955           data.impl = impl;
2956           data.tip = NULL;
2957           gtk_tree_selection_selected_foreach (selection, update_tooltip, &data);
2958           tip = data.tip;
2959         }
2960
2961       gtk_widget_set_tooltip_text (impl->browse_shortcuts_add_button, tip);
2962       g_free (tip);
2963     }
2964 }
2965
2966 /* Sets the sensitivity of the "remove bookmark" button depending on whether a
2967  * bookmark row is selected in the shortcuts tree.
2968  */
2969 static void
2970 bookmarks_check_remove_sensitivity (GtkFileChooserDefault *impl)
2971 {
2972   GtkTreeIter iter;
2973   gboolean removable = FALSE;
2974   gchar *name = NULL;
2975   
2976   if (shortcuts_get_selected (impl, &iter))
2977     gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
2978                         SHORTCUTS_COL_REMOVABLE, &removable,
2979                         SHORTCUTS_COL_NAME, &name,
2980                         -1);
2981
2982   gtk_widget_set_sensitive (impl->browse_shortcuts_remove_button, removable);
2983
2984   if (removable)
2985     {
2986       gchar *tip;
2987
2988       tip = g_strdup_printf (_("Remove the bookmark '%s'"), name);
2989       gtk_widget_set_tooltip_text (impl->browse_shortcuts_remove_button, tip);
2990       g_free (tip);
2991     }
2992
2993   g_free (name);
2994 }
2995
2996 static void
2997 shortcuts_check_popup_sensitivity (GtkFileChooserDefault *impl)
2998 {
2999   GtkTreeIter iter;
3000   gboolean removable = FALSE;
3001
3002   if (impl->browse_shortcuts_popup_menu == NULL)
3003     return;
3004
3005   if (shortcuts_get_selected (impl, &iter))
3006     gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
3007                         SHORTCUTS_COL_REMOVABLE, &removable,
3008                         -1);
3009
3010   gtk_widget_set_sensitive (impl->browse_shortcuts_popup_menu_remove_item, removable);
3011   gtk_widget_set_sensitive (impl->browse_shortcuts_popup_menu_rename_item, removable);
3012 }
3013
3014 /* GtkWidget::drag-begin handler for the shortcuts list. */
3015 static void
3016 shortcuts_drag_begin_cb (GtkWidget             *widget,
3017                          GdkDragContext        *context,
3018                          GtkFileChooserDefault *impl)
3019 {
3020 #if 0
3021   impl->shortcuts_drag_context = g_object_ref (context);
3022 #endif
3023 }
3024
3025 #if 0
3026 /* Removes the idle handler for outside drags */
3027 static void
3028 shortcuts_cancel_drag_outside_idle (GtkFileChooserDefault *impl)
3029 {
3030   if (!impl->shortcuts_drag_outside_idle)
3031     return;
3032
3033   g_source_destroy (impl->shortcuts_drag_outside_idle);
3034   impl->shortcuts_drag_outside_idle = NULL;
3035 }
3036 #endif
3037
3038 /* GtkWidget::drag-end handler for the shortcuts list. */
3039 static void
3040 shortcuts_drag_end_cb (GtkWidget             *widget,
3041                        GdkDragContext        *context,
3042                        GtkFileChooserDefault *impl)
3043 {
3044 #if 0
3045   g_object_unref (impl->shortcuts_drag_context);
3046
3047   shortcuts_cancel_drag_outside_idle (impl);
3048
3049   if (!impl->shortcuts_drag_outside)
3050     return;
3051
3052   gtk_button_clicked (GTK_BUTTON (impl->browse_shortcuts_remove_button));
3053
3054   impl->shortcuts_drag_outside = FALSE;
3055 #endif
3056 }
3057
3058 /* GtkWidget::drag-data-delete handler for the shortcuts list. */
3059 static void
3060 shortcuts_drag_data_delete_cb (GtkWidget             *widget,
3061                                GdkDragContext        *context,
3062                                GtkFileChooserDefault *impl)
3063 {
3064   g_signal_stop_emission_by_name (widget, "drag_data_delete");
3065 }
3066
3067 #if 0
3068 /* Creates a suitable drag cursor to indicate that the selected bookmark will be
3069  * deleted or not.
3070  */
3071 static void
3072 shortcuts_drag_set_delete_cursor (GtkFileChooserDefault *impl,
3073                                   gboolean               delete)
3074 {
3075   GtkTreeView *tree_view;
3076   GtkTreeIter iter;
3077   GtkTreePath *path;
3078   GdkPixmap *row_pixmap;
3079   GdkBitmap *mask;
3080   int row_pixmap_y;
3081   int cell_y;
3082
3083   tree_view = GTK_TREE_VIEW (impl->browse_shortcuts_tree_view);
3084
3085   /* Find the selected path and get its drag pixmap */
3086
3087   if (!shortcuts_get_selected (impl, &iter))
3088     g_assert_not_reached ();
3089
3090   path = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->shortcuts_model), &iter);
3091
3092   row_pixmap = gtk_tree_view_create_row_drag_icon (tree_view, path);
3093   gtk_tree_path_free (path);
3094
3095   mask = NULL;
3096   row_pixmap_y = 0;
3097
3098   if (delete)
3099     {
3100       GdkPixbuf *pixbuf;
3101
3102       pixbuf = gtk_widget_render_icon (impl->browse_shortcuts_tree_view,
3103                                        GTK_STOCK_DELETE,
3104                                        GTK_ICON_SIZE_DND,
3105                                        NULL);
3106       if (pixbuf)
3107         {
3108           GdkPixmap *composite;
3109           int row_pixmap_width, row_pixmap_height;
3110           int pixbuf_width, pixbuf_height;
3111           int composite_width, composite_height;
3112           int pixbuf_x, pixbuf_y;
3113           GdkGC *gc, *mask_gc;
3114           GdkColor color;
3115           GdkBitmap *pixbuf_mask;
3116
3117           /* Create pixmap and mask for composite image */
3118
3119           gdk_drawable_get_size (row_pixmap, &row_pixmap_width, &row_pixmap_height);
3120           pixbuf_width = gdk_pixbuf_get_width (pixbuf);
3121           pixbuf_height = gdk_pixbuf_get_height (pixbuf);
3122
3123           composite_width = MAX (row_pixmap_width, pixbuf_width);
3124           composite_height = MAX (row_pixmap_height, pixbuf_height);
3125
3126           row_pixmap_y = (composite_height - row_pixmap_height) / 2;
3127
3128           if (gtk_widget_get_direction (impl->browse_shortcuts_tree_view) == GTK_TEXT_DIR_RTL)
3129             pixbuf_x = 0;
3130           else
3131             pixbuf_x = composite_width - pixbuf_width;
3132
3133           pixbuf_y = (composite_height - pixbuf_height) / 2;
3134
3135           composite = gdk_pixmap_new (row_pixmap, composite_width, composite_height, -1);
3136           gc = gdk_gc_new (composite);
3137
3138           mask = gdk_pixmap_new (row_pixmap, composite_width, composite_height, 1);
3139           mask_gc = gdk_gc_new (mask);
3140           color.pixel = 0;
3141           gdk_gc_set_foreground (mask_gc, &color);
3142           gdk_draw_rectangle (mask, mask_gc, TRUE, 0, 0, composite_width, composite_height);
3143
3144           color.red = 0xffff;
3145           color.green = 0xffff;
3146           color.blue = 0xffff;
3147           gdk_gc_set_rgb_fg_color (gc, &color);
3148           gdk_draw_rectangle (composite, gc, TRUE, 0, 0, composite_width, composite_height);
3149
3150           /* Composite the row pixmap and the pixbuf */
3151
3152           gdk_pixbuf_render_pixmap_and_mask_for_colormap
3153             (pixbuf,
3154              gtk_widget_get_colormap (impl->browse_shortcuts_tree_view),
3155              NULL, &pixbuf_mask, 128);
3156           gdk_draw_drawable (mask, mask_gc, pixbuf_mask,
3157                              0, 0,
3158                              pixbuf_x, pixbuf_y,
3159                              pixbuf_width, pixbuf_height);
3160           g_object_unref (pixbuf_mask);
3161
3162           gdk_draw_drawable (composite, gc, row_pixmap,
3163                              0, 0,
3164                              0, row_pixmap_y,
3165                              row_pixmap_width, row_pixmap_height);
3166           color.pixel = 1;
3167           gdk_gc_set_foreground (mask_gc, &color);
3168           gdk_draw_rectangle (mask, mask_gc, TRUE, 0, row_pixmap_y, row_pixmap_width, row_pixmap_height);
3169
3170           gdk_draw_pixbuf (composite, gc, pixbuf,
3171                            0, 0,
3172                            pixbuf_x, pixbuf_y,
3173                            pixbuf_width, pixbuf_height,
3174                            GDK_RGB_DITHER_MAX,
3175                            0, 0);
3176
3177           g_object_unref (pixbuf);
3178           g_object_unref (row_pixmap);
3179
3180           row_pixmap = composite;
3181         }
3182     }
3183
3184   /* The hotspot offsets here are copied from gtk_tree_view_drag_begin(), ugh */
3185
3186   gtk_tree_view_get_path_at_pos (tree_view,
3187                                  tree_view->priv->press_start_x,
3188                                  tree_view->priv->press_start_y,
3189                                  NULL,
3190                                  NULL,
3191                                  NULL,
3192                                  &cell_y);
3193
3194   gtk_drag_set_icon_pixmap (impl->shortcuts_drag_context,
3195                             gdk_drawable_get_colormap (row_pixmap),
3196                             row_pixmap,
3197                             mask,
3198                             tree_view->priv->press_start_x + 1,
3199                             row_pixmap_y + cell_y + 1);
3200
3201   g_object_unref (row_pixmap);
3202   if (mask)
3203     g_object_unref (mask);
3204 }
3205
3206 /* We set the delete cursor and the shortcuts_drag_outside flag in an idle
3207  * handler so that we can tell apart the drag_leave event that comes right
3208  * before a drag_drop, from a normal drag_leave.  We don't want to set the
3209  * cursor nor the flag in the latter case.
3210  */
3211 static gboolean
3212 shortcuts_drag_outside_idle_cb (GtkFileChooserDefault *impl)
3213 {
3214   GDK_THREADS_ENTER ();
3215   
3216   shortcuts_drag_set_delete_cursor (impl, TRUE);
3217   impl->shortcuts_drag_outside = TRUE;
3218
3219   shortcuts_cancel_drag_outside_idle (impl);
3220
3221   GDK_THREADS_LEAVE ();
3222
3223   return FALSE;
3224 }
3225 #endif
3226
3227 /* GtkWidget::drag-leave handler for the shortcuts list.  We unhighlight the
3228  * drop position.
3229  */
3230 static void
3231 shortcuts_drag_leave_cb (GtkWidget             *widget,
3232                          GdkDragContext        *context,
3233                          guint                  time_,
3234                          GtkFileChooserDefault *impl)
3235 {
3236 #if 0
3237   if (gtk_drag_get_source_widget (context) == widget && !impl->shortcuts_drag_outside_idle)
3238     {
3239       impl->shortcuts_drag_outside_idle = g_idle_source_new ();
3240       g_source_set_closure (impl->shortcuts_drag_outside_idle,
3241                             g_cclosure_new_object (G_CALLBACK (shortcuts_drag_outside_idle_cb),
3242                                                    G_OBJECT (impl)));
3243       g_source_attach (impl->shortcuts_drag_outside_idle, NULL);
3244     }
3245 #endif
3246
3247   gtk_tree_view_set_drag_dest_row (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view),
3248                                    NULL,
3249                                    GTK_TREE_VIEW_DROP_BEFORE);
3250
3251   g_signal_stop_emission_by_name (widget, "drag_leave");
3252 }
3253
3254 /* Computes the appropriate row and position for dropping */
3255 static void
3256 shortcuts_compute_drop_position (GtkFileChooserDefault   *impl,
3257                                  int                      x,
3258                                  int                      y,
3259                                  GtkTreePath            **path,
3260                                  GtkTreeViewDropPosition *pos)
3261 {
3262   GtkTreeView *tree_view;
3263   GtkTreeViewColumn *column;
3264   int cell_y;
3265   GdkRectangle cell;
3266   int row;
3267   int bookmarks_index;
3268
3269   tree_view = GTK_TREE_VIEW (impl->browse_shortcuts_tree_view);
3270
3271   bookmarks_index = shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS);
3272
3273   if (!gtk_tree_view_get_path_at_pos (tree_view,
3274                                       x,
3275                                       y - TREE_VIEW_HEADER_HEIGHT (tree_view),
3276                                       path,
3277                                       &column,
3278                                       NULL,
3279                                       &cell_y))
3280     {
3281       row = bookmarks_index + impl->num_bookmarks - 1;
3282       *path = gtk_tree_path_new_from_indices (row, -1);
3283       *pos = GTK_TREE_VIEW_DROP_AFTER;
3284       return;
3285     }
3286
3287   row = *gtk_tree_path_get_indices (*path);
3288   gtk_tree_view_get_background_area (tree_view, *path, column, &cell);
3289   gtk_tree_path_free (*path);
3290
3291   if (row < bookmarks_index)
3292     {
3293       row = bookmarks_index;
3294       *pos = GTK_TREE_VIEW_DROP_BEFORE;
3295     }
3296   else if (row > bookmarks_index + impl->num_bookmarks - 1)
3297     {
3298       row = bookmarks_index + impl->num_bookmarks - 1;
3299       *pos = GTK_TREE_VIEW_DROP_AFTER;
3300     }
3301   else
3302     {
3303       if (cell_y < cell.height / 2)
3304         *pos = GTK_TREE_VIEW_DROP_BEFORE;
3305       else
3306         *pos = GTK_TREE_VIEW_DROP_AFTER;
3307     }
3308
3309   *path = gtk_tree_path_new_from_indices (row, -1);
3310 }
3311
3312 /* GtkWidget::drag-motion handler for the shortcuts list.  We basically
3313  * implement the destination side of DnD by hand, due to limitations in
3314  * GtkTreeView's DnD API.
3315  */
3316 static gboolean
3317 shortcuts_drag_motion_cb (GtkWidget             *widget,
3318                           GdkDragContext        *context,
3319                           gint                   x,
3320                           gint                   y,
3321                           guint                  time_,
3322                           GtkFileChooserDefault *impl)
3323 {
3324   GtkTreePath *path;
3325   GtkTreeViewDropPosition pos;
3326   GdkDragAction action;
3327
3328 #if 0
3329   if (gtk_drag_get_source_widget (context) == widget)
3330     {
3331       shortcuts_cancel_drag_outside_idle (impl);
3332
3333       if (impl->shortcuts_drag_outside)
3334         {
3335           shortcuts_drag_set_delete_cursor (impl, FALSE);
3336           impl->shortcuts_drag_outside = FALSE;
3337         }
3338     }
3339 #endif
3340
3341   if (context->suggested_action == GDK_ACTION_COPY ||
3342       (context->actions & GDK_ACTION_COPY) != 0)
3343     action = GDK_ACTION_COPY;
3344   else if (context->suggested_action == GDK_ACTION_MOVE ||
3345            (context->actions & GDK_ACTION_MOVE) != 0)
3346     action = GDK_ACTION_MOVE;
3347   else
3348     {
3349       action = 0;
3350       goto out;
3351     }
3352
3353   shortcuts_compute_drop_position (impl, x, y, &path, &pos);
3354   gtk_tree_view_set_drag_dest_row (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view), path, pos);
3355   gtk_tree_path_free (path);
3356
3357  out:
3358
3359   g_signal_stop_emission_by_name (widget, "drag_motion");
3360
3361   if (action != 0)
3362     {
3363       gdk_drag_status (context, action, time_);
3364       return TRUE;
3365     }
3366   else
3367     return FALSE;
3368 }
3369
3370 /* GtkWidget::drag-drop handler for the shortcuts list. */
3371 static gboolean
3372 shortcuts_drag_drop_cb (GtkWidget             *widget,
3373                         GdkDragContext        *context,
3374                         gint                   x,
3375                         gint                   y,
3376                         guint                  time_,
3377                         GtkFileChooserDefault *impl)
3378 {
3379 #if 0
3380   shortcuts_cancel_drag_outside_idle (impl);
3381 #endif
3382
3383   g_signal_stop_emission_by_name (widget, "drag_drop");
3384   return TRUE;
3385 }
3386
3387 /* Parses a "text/uri-list" string and inserts its URIs as bookmarks */
3388 static void
3389 shortcuts_drop_uris (GtkFileChooserDefault *impl,
3390                      GtkSelectionData      *selection_data,
3391                      int                    position)
3392 {
3393   gchar **uris;
3394   gint i;
3395
3396   uris = gtk_selection_data_get_uris (selection_data);
3397   if (!uris)
3398     return;
3399
3400   for (i = 0; uris[i]; i++)
3401     {
3402       char *uri;
3403       GFile *file;
3404
3405       uri = uris[i];
3406       file = g_file_new_for_uri (uri);
3407
3408       if (shortcuts_add_bookmark_from_file (impl, file, position))
3409         position++;
3410
3411       g_object_unref (file);
3412     }
3413
3414   g_strfreev (uris);
3415 }
3416
3417 /* Reorders the selected bookmark to the specified position */
3418 static void
3419 shortcuts_reorder (GtkFileChooserDefault *impl,
3420                    int                    new_position)
3421 {
3422   GtkTreeIter iter;
3423   gpointer col_data;
3424   ShortcutType shortcut_type;
3425   GtkTreePath *path;
3426   int old_position;
3427   int bookmarks_index;
3428   GFile *file;
3429   GError *error;
3430   gchar *name;
3431
3432   /* Get the selected path */
3433
3434   if (!shortcuts_get_selected (impl, &iter))
3435     g_assert_not_reached ();
3436
3437   path = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->shortcuts_model), &iter);
3438   old_position = *gtk_tree_path_get_indices (path);
3439   gtk_tree_path_free (path);
3440
3441   bookmarks_index = shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS);
3442   old_position -= bookmarks_index;
3443   g_assert (old_position >= 0 && old_position < impl->num_bookmarks);
3444
3445   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
3446                       SHORTCUTS_COL_NAME, &name,
3447                       SHORTCUTS_COL_DATA, &col_data,
3448                       SHORTCUTS_COL_TYPE, &shortcut_type,
3449                       -1);
3450   g_assert (col_data != NULL);
3451   g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
3452   
3453   file = col_data;
3454   g_object_ref (file); /* removal below will free file, so we need a new ref */
3455
3456   /* Remove the path from the old position and insert it in the new one */
3457
3458   if (new_position > old_position)
3459     new_position--;
3460
3461   if (old_position == new_position)
3462     goto out;
3463
3464   error = NULL;
3465   if (_gtk_file_system_remove_bookmark (impl->file_system, file, &error))
3466     {
3467       shortcuts_add_bookmark_from_file (impl, file, new_position);
3468       _gtk_file_system_set_bookmark_label (impl->file_system, file, name);
3469     }
3470   else
3471     error_adding_bookmark_dialog (impl, file, error);
3472
3473  out:
3474
3475   g_object_unref (file);
3476 }
3477
3478 /* Callback used when we get the drag data for the bookmarks list.  We add the
3479  * received URIs as bookmarks if they are folders.
3480  */
3481 static void
3482 shortcuts_drag_data_received_cb (GtkWidget          *widget,
3483                                  GdkDragContext     *context,
3484                                  gint                x,
3485                                  gint                y,
3486                                  GtkSelectionData   *selection_data,
3487                                  guint               info,
3488                                  guint               time_,
3489                                  gpointer            data)
3490 {
3491   GtkFileChooserDefault *impl;
3492   GtkTreePath *tree_path;
3493   GtkTreeViewDropPosition tree_pos;
3494   int position;
3495   int bookmarks_index;
3496
3497   impl = GTK_FILE_CHOOSER_DEFAULT (data);
3498
3499   /* Compute position */
3500
3501   bookmarks_index = shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS);
3502
3503   shortcuts_compute_drop_position (impl, x, y, &tree_path, &tree_pos);
3504   position = *gtk_tree_path_get_indices (tree_path);
3505   gtk_tree_path_free (tree_path);
3506
3507   if (tree_pos == GTK_TREE_VIEW_DROP_AFTER)
3508     position++;
3509
3510   g_assert (position >= bookmarks_index);
3511   position -= bookmarks_index;
3512
3513   if (gtk_targets_include_uri (&selection_data->target, 1))
3514     shortcuts_drop_uris (impl, selection_data, position);
3515   else if (selection_data->target == gdk_atom_intern_static_string ("GTK_TREE_MODEL_ROW"))
3516     shortcuts_reorder (impl, position);
3517
3518   g_signal_stop_emission_by_name (widget, "drag_data_received");
3519 }
3520
3521 /* Callback used to display a tooltip in the shortcuts tree */
3522 static gboolean
3523 shortcuts_query_tooltip_cb (GtkWidget             *widget,
3524                             gint                   x,
3525                             gint                   y,
3526                             gboolean               keyboard_mode,
3527                             GtkTooltip            *tooltip,
3528                             GtkFileChooserDefault *impl)
3529 {
3530   GtkTreeModel *model;
3531   GtkTreeIter iter;
3532
3533   if (gtk_tree_view_get_tooltip_context (GTK_TREE_VIEW (widget),
3534                                          &x, &y,
3535                                          keyboard_mode,
3536                                          &model,
3537                                          NULL,
3538                                          &iter))
3539     {
3540       gpointer col_data;
3541       ShortcutType shortcut_type;
3542
3543       gtk_tree_model_get (model, &iter,
3544                           SHORTCUTS_COL_DATA, &col_data,
3545                           SHORTCUTS_COL_TYPE, &shortcut_type,
3546                           -1);
3547
3548       if (shortcut_type == SHORTCUT_TYPE_SEPARATOR)
3549         return FALSE;
3550       else if (shortcut_type == SHORTCUT_TYPE_VOLUME)
3551         {
3552           return FALSE;
3553         }
3554       else if (shortcut_type == SHORTCUT_TYPE_FILE)
3555         {
3556           GFile *file;
3557           char *parse_name;
3558
3559           file = G_FILE (col_data);
3560           parse_name = g_file_get_parse_name (file);
3561
3562           gtk_tooltip_set_text (tooltip, parse_name);
3563
3564           g_free (parse_name);
3565
3566           return TRUE;
3567         }
3568       else if (shortcut_type == SHORTCUT_TYPE_SEARCH)
3569         {
3570           return FALSE;
3571         }
3572       else if (shortcut_type == SHORTCUT_TYPE_RECENT)
3573         {
3574           return FALSE;
3575         }
3576     }
3577
3578   return FALSE;
3579 }
3580
3581
3582 /* Callback used when the selection in the shortcuts tree changes */
3583 static void
3584 shortcuts_selection_changed_cb (GtkTreeSelection      *selection,
3585                                 GtkFileChooserDefault *impl)
3586 {
3587   GtkTreeIter iter;
3588   GtkTreeIter child_iter;
3589
3590   bookmarks_check_remove_sensitivity (impl);
3591   shortcuts_check_popup_sensitivity (impl);
3592
3593   if (impl->changing_folder)
3594     return;
3595
3596   if (gtk_tree_selection_get_selected(selection, NULL, &iter))
3597     {
3598       gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (impl->shortcuts_pane_filter_model),
3599                                                         &child_iter,
3600                                                         &iter);
3601       shortcuts_activate_iter (impl, &child_iter);
3602     }
3603 }
3604
3605 static gboolean
3606 shortcuts_row_separator_func (GtkTreeModel *model,
3607                               GtkTreeIter  *iter,
3608                               gpointer      data)
3609 {
3610   ShortcutType shortcut_type;
3611
3612   gtk_tree_model_get (model, iter, SHORTCUTS_COL_TYPE, &shortcut_type, -1);
3613   
3614   return shortcut_type == SHORTCUT_TYPE_SEPARATOR;
3615 }
3616
3617 /* Since GtkTreeView has a keybinding attached to '/', we need to catch
3618  * keypresses before the TreeView gets them.
3619  */
3620 static gboolean
3621 tree_view_keybinding_cb (GtkWidget             *tree_view,
3622                          GdkEventKey           *event,
3623                          GtkFileChooserDefault *impl)
3624 {
3625   if ((event->keyval == GDK_slash
3626        || event->keyval == GDK_KP_Divide
3627 #ifdef G_OS_UNIX
3628        || event->keyval == GDK_asciitilde
3629 #endif
3630        ) && ! (event->state & (~GDK_SHIFT_MASK & gtk_accelerator_get_default_mod_mask ())))
3631     {
3632       location_popup_handler (impl, event->string);
3633       return TRUE;
3634     }
3635
3636   return FALSE;
3637 }
3638
3639 /* Callback used when the file list's popup menu is detached */
3640 static void
3641 shortcuts_popup_menu_detach_cb (GtkWidget *attach_widget,
3642                                 GtkMenu   *menu)
3643 {
3644   GtkFileChooserDefault *impl;
3645   
3646   impl = g_object_get_data (G_OBJECT (attach_widget), "GtkFileChooserDefault");
3647   g_assert (GTK_IS_FILE_CHOOSER_DEFAULT (impl));
3648
3649   impl->browse_shortcuts_popup_menu = NULL;
3650   impl->browse_shortcuts_popup_menu_remove_item = NULL;
3651   impl->browse_shortcuts_popup_menu_rename_item = NULL;
3652 }
3653
3654 static void
3655 remove_shortcut_cb (GtkMenuItem           *item,
3656                     GtkFileChooserDefault *impl)
3657 {
3658   remove_selected_bookmarks (impl);
3659 }
3660
3661 /* Rename the selected bookmark */
3662 static void
3663 rename_selected_bookmark (GtkFileChooserDefault *impl)
3664 {
3665   GtkTreeIter iter;
3666   GtkTreePath *path;
3667   GtkTreeViewColumn *column;
3668   GtkCellRenderer *cell;
3669   GList *renderers;
3670
3671   if (shortcuts_get_selected (impl, &iter))
3672     {
3673       path = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->shortcuts_model), &iter);
3674       column = gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view), 0);
3675       renderers = gtk_tree_view_column_get_cell_renderers (column);
3676       cell = g_list_nth_data (renderers, 1);
3677       g_list_free (renderers);
3678       g_object_set (cell, "editable", TRUE, NULL);
3679       gtk_tree_view_set_cursor_on_cell (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view),
3680                                         path, column, cell, TRUE);
3681       gtk_tree_path_free (path);
3682     }
3683 }
3684
3685 static void
3686 rename_shortcut_cb (GtkMenuItem           *item,
3687                     GtkFileChooserDefault *impl)
3688 {
3689   rename_selected_bookmark (impl);
3690 }
3691
3692 /* Constructs the popup menu for the file list if needed */
3693 static void
3694 shortcuts_build_popup_menu (GtkFileChooserDefault *impl)
3695 {
3696   GtkWidget *item;
3697
3698   if (impl->browse_shortcuts_popup_menu)
3699     return;
3700
3701   impl->browse_shortcuts_popup_menu = gtk_menu_new ();
3702   gtk_menu_attach_to_widget (GTK_MENU (impl->browse_shortcuts_popup_menu),
3703                              impl->browse_shortcuts_tree_view,
3704                              shortcuts_popup_menu_detach_cb);
3705
3706   item = gtk_image_menu_item_new_with_label (_("Remove"));
3707   impl->browse_shortcuts_popup_menu_remove_item = item;
3708   gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item),
3709                                  gtk_image_new_from_stock (GTK_STOCK_REMOVE, GTK_ICON_SIZE_MENU));
3710   g_signal_connect (item, "activate",
3711                     G_CALLBACK (remove_shortcut_cb), impl);
3712   gtk_widget_show (item);
3713   gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_shortcuts_popup_menu), item);
3714
3715   item = gtk_menu_item_new_with_label (_("Rename..."));
3716   impl->browse_shortcuts_popup_menu_rename_item = item;
3717   g_signal_connect (item, "activate",
3718                     G_CALLBACK (rename_shortcut_cb), impl);
3719   gtk_widget_show (item);
3720   gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_shortcuts_popup_menu), item);
3721 }
3722
3723 static void
3724 shortcuts_update_popup_menu (GtkFileChooserDefault *impl)
3725 {
3726   shortcuts_build_popup_menu (impl);  
3727   shortcuts_check_popup_sensitivity (impl);
3728 }
3729
3730 static void
3731 popup_position_func (GtkMenu   *menu,
3732                      gint      *x,
3733                      gint      *y,
3734                      gboolean  *push_in,
3735                      gpointer   user_data);
3736
3737 static void
3738 shortcuts_popup_menu (GtkFileChooserDefault *impl,
3739                       GdkEventButton        *event)
3740 {
3741   shortcuts_update_popup_menu (impl);
3742   if (event)
3743     gtk_menu_popup (GTK_MENU (impl->browse_shortcuts_popup_menu),
3744                     NULL, NULL, NULL, NULL,
3745                     event->button, event->time);
3746   else
3747     {
3748       gtk_menu_popup (GTK_MENU (impl->browse_shortcuts_popup_menu),
3749                       NULL, NULL,
3750                       popup_position_func, impl->browse_shortcuts_tree_view,
3751                       0, GDK_CURRENT_TIME);
3752       gtk_menu_shell_select_first (GTK_MENU_SHELL (impl->browse_shortcuts_popup_menu),
3753                                    FALSE);
3754     }
3755 }
3756
3757 /* Callback used for the GtkWidget::popup-menu signal of the shortcuts list */
3758 static gboolean
3759 shortcuts_popup_menu_cb (GtkWidget *widget,
3760                          GtkFileChooserDefault *impl)
3761 {
3762   shortcuts_popup_menu (impl, NULL);
3763   return TRUE;
3764 }
3765
3766 /* Callback used when a button is pressed on the shortcuts list.  
3767  * We trap button 3 to bring up a popup menu.
3768  */
3769 static gboolean
3770 shortcuts_button_press_event_cb (GtkWidget             *widget,
3771                                  GdkEventButton        *event,
3772                                  GtkFileChooserDefault *impl)
3773 {
3774   static gboolean in_press = FALSE;
3775   gboolean handled;
3776
3777   if (in_press)
3778     return FALSE;
3779
3780   if (event->button != 3)
3781     return FALSE;
3782
3783   in_press = TRUE;
3784   handled = gtk_widget_event (impl->browse_shortcuts_tree_view, (GdkEvent *) event);
3785   in_press = FALSE;
3786
3787   if (!handled)
3788     return FALSE;
3789
3790   shortcuts_popup_menu (impl, event);
3791   return TRUE;
3792 }
3793
3794 static void
3795 shortcuts_edited (GtkCellRenderer       *cell,
3796                   gchar                 *path_string,
3797                   gchar                 *new_text,
3798                   GtkFileChooserDefault *impl)
3799 {
3800   GtkTreePath *path;
3801   GtkTreeIter iter;
3802   GFile *shortcut;
3803
3804   g_object_set (cell, "editable", FALSE, NULL);
3805
3806   path = gtk_tree_path_new_from_string (path_string);
3807   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->shortcuts_model), &iter, path))
3808     g_assert_not_reached ();
3809
3810   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
3811                       SHORTCUTS_COL_DATA, &shortcut,
3812                       -1);
3813   gtk_tree_path_free (path);
3814   
3815   _gtk_file_system_set_bookmark_label (impl->file_system, shortcut, new_text);
3816 }
3817
3818 static void
3819 shortcuts_editing_canceled (GtkCellRenderer       *cell,
3820                             GtkFileChooserDefault *impl)
3821 {
3822   g_object_set (cell, "editable", FALSE, NULL);
3823 }
3824
3825 /* Creates the widgets for the shortcuts and bookmarks tree */
3826 static GtkWidget *
3827 shortcuts_list_create (GtkFileChooserDefault *impl)
3828 {
3829   GtkWidget *swin;
3830   GtkTreeSelection *selection;
3831   GtkTreeViewColumn *column;
3832   GtkCellRenderer *renderer;
3833
3834   /* Target types for dragging a row to/from the shortcuts list */
3835   const GtkTargetEntry tree_model_row_targets[] = {
3836     { "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_WIDGET, GTK_TREE_MODEL_ROW }
3837   };
3838
3839   /* Scrolled window */
3840
3841   swin = gtk_scrolled_window_new (NULL, NULL);
3842   gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (swin),
3843                                   GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
3844   gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (swin),
3845                                        GTK_SHADOW_IN);
3846   gtk_widget_show (swin);
3847
3848   /* Tree */
3849
3850   impl->browse_shortcuts_tree_view = gtk_tree_view_new ();
3851 #ifdef PROFILE_FILE_CHOOSER
3852   g_object_set_data (G_OBJECT (impl->browse_shortcuts_tree_view), "fmq-name", "shortcuts");
3853 #endif
3854   g_signal_connect (impl->browse_shortcuts_tree_view, "key-press-event",
3855                     G_CALLBACK (tree_view_keybinding_cb), impl);
3856   g_signal_connect (impl->browse_shortcuts_tree_view, "popup-menu",
3857                     G_CALLBACK (shortcuts_popup_menu_cb), impl);
3858   g_signal_connect (impl->browse_shortcuts_tree_view, "button-press-event",
3859                     G_CALLBACK (shortcuts_button_press_event_cb), impl);
3860   /* Accessible object name for the file chooser's shortcuts pane */
3861   atk_object_set_name (gtk_widget_get_accessible (impl->browse_shortcuts_tree_view), _("Places"));
3862
3863   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view), impl->shortcuts_pane_filter_model);
3864
3865   gtk_tree_view_enable_model_drag_source (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view),
3866                                           GDK_BUTTON1_MASK,
3867                                           tree_model_row_targets,
3868                                           G_N_ELEMENTS (tree_model_row_targets),
3869                                           GDK_ACTION_MOVE);
3870
3871   gtk_drag_dest_set (impl->browse_shortcuts_tree_view,
3872                      GTK_DEST_DEFAULT_ALL,
3873                      tree_model_row_targets,
3874                      G_N_ELEMENTS (tree_model_row_targets),
3875                      GDK_ACTION_COPY | GDK_ACTION_MOVE);
3876   gtk_drag_dest_add_uri_targets (impl->browse_shortcuts_tree_view);
3877
3878   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view));
3879   gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);
3880   gtk_tree_selection_set_select_function (selection,
3881                                           shortcuts_select_func,
3882                                           impl, NULL);
3883
3884   g_signal_connect (selection, "changed",
3885                     G_CALLBACK (shortcuts_selection_changed_cb), impl);
3886
3887   g_signal_connect (impl->browse_shortcuts_tree_view, "key-press-event",
3888                     G_CALLBACK (shortcuts_key_press_event_cb), impl);
3889
3890   g_signal_connect (impl->browse_shortcuts_tree_view, "drag-begin",
3891                     G_CALLBACK (shortcuts_drag_begin_cb), impl);
3892   g_signal_connect (impl->browse_shortcuts_tree_view, "drag-end",
3893                     G_CALLBACK (shortcuts_drag_end_cb), impl);
3894   g_signal_connect (impl->browse_shortcuts_tree_view, "drag-data-delete",
3895                     G_CALLBACK (shortcuts_drag_data_delete_cb), impl);
3896
3897   g_signal_connect (impl->browse_shortcuts_tree_view, "drag-leave",
3898                     G_CALLBACK (shortcuts_drag_leave_cb), impl);
3899   g_signal_connect (impl->browse_shortcuts_tree_view, "drag-motion",
3900                     G_CALLBACK (shortcuts_drag_motion_cb), impl);
3901   g_signal_connect (impl->browse_shortcuts_tree_view, "drag-drop",
3902                     G_CALLBACK (shortcuts_drag_drop_cb), impl);
3903   g_signal_connect (impl->browse_shortcuts_tree_view, "drag-data-received",
3904                     G_CALLBACK (shortcuts_drag_data_received_cb), impl);
3905
3906   /* Support tooltips */
3907   gtk_widget_set_has_tooltip (impl->browse_shortcuts_tree_view, TRUE);
3908   g_signal_connect (impl->browse_shortcuts_tree_view, "query-tooltip",
3909                     G_CALLBACK (shortcuts_query_tooltip_cb), impl);
3910
3911   gtk_container_add (GTK_CONTAINER (swin), impl->browse_shortcuts_tree_view);
3912   gtk_widget_show (impl->browse_shortcuts_tree_view);
3913
3914   /* Column */
3915
3916   column = gtk_tree_view_column_new ();
3917   /* Column header for the file chooser's shortcuts pane */
3918   gtk_tree_view_column_set_title (column, _("_Places"));
3919
3920   renderer = gtk_cell_renderer_pixbuf_new ();
3921   gtk_tree_view_column_pack_start (column, renderer, FALSE);
3922   gtk_tree_view_column_set_attributes (column, renderer,
3923                                        "pixbuf", SHORTCUTS_COL_PIXBUF,
3924                                        "visible", SHORTCUTS_COL_PIXBUF_VISIBLE,
3925                                        NULL);
3926
3927   renderer = gtk_cell_renderer_text_new ();
3928   g_signal_connect (renderer, "edited", 
3929                     G_CALLBACK (shortcuts_edited), impl);
3930   g_signal_connect (renderer, "editing-canceled", 
3931                     G_CALLBACK (shortcuts_editing_canceled), impl);
3932   gtk_tree_view_column_pack_start (column, renderer, TRUE);
3933   gtk_tree_view_column_set_attributes (column, renderer,
3934                                        "text", SHORTCUTS_COL_NAME,
3935                                        NULL);
3936
3937   gtk_tree_view_set_row_separator_func (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view),
3938                                         shortcuts_row_separator_func,
3939                                         NULL, NULL);
3940
3941   gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view), column);
3942
3943   return swin;
3944 }
3945
3946 /* Creates the widgets for the shortcuts/bookmarks pane */
3947 static GtkWidget *
3948 shortcuts_pane_create (GtkFileChooserDefault *impl,
3949                        GtkSizeGroup          *size_group)
3950 {
3951   GtkWidget *vbox;
3952   GtkWidget *hbox;
3953   GtkWidget *widget;
3954
3955   vbox = gtk_vbox_new (FALSE, 6);
3956   gtk_widget_show (vbox);
3957
3958   /* Shortcuts tree */
3959
3960   widget = shortcuts_list_create (impl);
3961   gtk_box_pack_start (GTK_BOX (vbox), widget, TRUE, TRUE, 0);
3962
3963   /* Box for buttons */
3964
3965   hbox = gtk_hbox_new (TRUE, 6);
3966   gtk_size_group_add_widget (size_group, hbox);
3967   gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
3968   gtk_widget_show (hbox);
3969
3970   /* Add bookmark button */
3971
3972   impl->browse_shortcuts_add_button = button_new (impl,
3973                                                   _("_Add"),
3974                                                   GTK_STOCK_ADD,
3975                                                   FALSE,
3976                                                   TRUE,
3977                                                   G_CALLBACK (add_bookmark_button_clicked_cb));
3978   gtk_box_pack_start (GTK_BOX (hbox), impl->browse_shortcuts_add_button, TRUE, TRUE, 0);
3979   gtk_widget_set_tooltip_text (impl->browse_shortcuts_add_button,
3980                                _("Add the selected folder to the Bookmarks"));
3981
3982   /* Remove bookmark button */
3983
3984   impl->browse_shortcuts_remove_button = button_new (impl,
3985                                                      _("_Remove"),
3986                                                      GTK_STOCK_REMOVE,
3987                                                      FALSE,
3988                                                      TRUE,
3989                                                      G_CALLBACK (remove_bookmark_button_clicked_cb));
3990   gtk_box_pack_start (GTK_BOX (hbox), impl->browse_shortcuts_remove_button, TRUE, TRUE, 0);
3991   gtk_widget_set_tooltip_text (impl->browse_shortcuts_remove_button,
3992                                _("Remove the selected bookmark"));
3993
3994   return vbox;
3995 }
3996
3997 /* Handles key press events on the file list, so that we can trap Enter to
3998  * activate the default button on our own.  Also, checks to see if '/' has been
3999  * pressed.  See comment by tree_view_keybinding_cb() for more details.
4000  */
4001 static gboolean
4002 trap_activate_cb (GtkWidget   *widget,
4003                   GdkEventKey *event,
4004                   gpointer     data)
4005 {
4006   GtkFileChooserDefault *impl;
4007   int modifiers;
4008
4009   impl = (GtkFileChooserDefault *) data;
4010
4011   modifiers = gtk_accelerator_get_default_mod_mask ();
4012
4013   if ((event->keyval == GDK_slash
4014        || event->keyval == GDK_KP_Divide
4015 #ifdef G_OS_UNIX
4016        || event->keyval == GDK_asciitilde
4017 #endif
4018        ) && ! (event->state & (~GDK_SHIFT_MASK & modifiers)))
4019     {
4020       location_popup_handler (impl, event->string);
4021       return TRUE;
4022     }
4023
4024   if ((event->keyval == GDK_Return
4025        || event->keyval == GDK_ISO_Enter
4026        || event->keyval == GDK_KP_Enter
4027        || event->keyval == GDK_space
4028        || event->keyval == GDK_KP_Space)
4029       && ((event->state & modifiers) == 0)
4030       && !(impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
4031            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
4032     {
4033       GtkWindow *window;
4034
4035       window = get_toplevel (widget);
4036       if (window
4037           && widget != window->default_widget
4038           && !(widget == window->focus_widget &&
4039                (!window->default_widget || !GTK_WIDGET_SENSITIVE (window->default_widget))))
4040         {
4041           gtk_window_activate_default (window);
4042           return TRUE;
4043         }
4044     }
4045
4046   return FALSE;
4047 }
4048
4049 /* Callback used when the file list's popup menu is detached */
4050 static void
4051 popup_menu_detach_cb (GtkWidget *attach_widget,
4052                       GtkMenu   *menu)
4053 {
4054   GtkFileChooserDefault *impl;
4055
4056   impl = g_object_get_data (G_OBJECT (attach_widget), "GtkFileChooserDefault");
4057   g_assert (GTK_IS_FILE_CHOOSER_DEFAULT (impl));
4058
4059   impl->browse_files_popup_menu = NULL;
4060   impl->browse_files_popup_menu_add_shortcut_item = NULL;
4061   impl->browse_files_popup_menu_hidden_files_item = NULL;
4062 }
4063
4064 /* Callback used when the "Add to Bookmarks" menu item is activated */
4065 static void
4066 add_to_shortcuts_cb (GtkMenuItem           *item,
4067                      GtkFileChooserDefault *impl)
4068 {
4069   bookmarks_add_selected_folder (impl);
4070 }
4071
4072 /* Callback used when the "Show Hidden Files" menu item is toggled */
4073 static void
4074 show_hidden_toggled_cb (GtkCheckMenuItem      *item,
4075                         GtkFileChooserDefault *impl)
4076 {
4077   g_object_set (impl,
4078                 "show-hidden", gtk_check_menu_item_get_active (item),
4079                 NULL);
4080 }
4081
4082 /* Shows an error dialog about not being able to select a dragged file */
4083 static void
4084 error_selecting_dragged_file_dialog (GtkFileChooserDefault *impl,
4085                                      GFile                 *file,
4086                                      GError                *error)
4087 {
4088   error_dialog (impl,
4089                 _("Could not select file"),
4090                 file, error);
4091 }
4092
4093 static void
4094 file_list_drag_data_select_uris (GtkFileChooserDefault  *impl,
4095                                  gchar                 **uris)
4096 {
4097   int i;
4098   char *uri;
4099   GtkFileChooser *chooser = GTK_FILE_CHOOSER (impl);
4100
4101   for (i = 1; uris[i]; i++)
4102     {
4103       GFile *file;
4104       GError *error = NULL;
4105
4106       uri = uris[i];
4107       file = g_file_new_for_uri (uri);
4108
4109       gtk_file_chooser_default_select_file (chooser, file, &error);
4110       if (error)
4111         error_selecting_dragged_file_dialog (impl, file, error);
4112
4113       g_object_unref (file);
4114     }
4115 }
4116
4117 struct FileListDragData
4118 {
4119   GtkFileChooserDefault *impl;
4120   gchar **uris;
4121   GFile *file;
4122 };
4123
4124 static void
4125 file_list_drag_data_received_get_info_cb (GCancellable *cancellable,
4126                                           GFileInfo    *info,
4127                                           const GError *error,
4128                                           gpointer      user_data)
4129 {
4130   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
4131   struct FileListDragData *data = user_data;
4132   GtkFileChooser *chooser = GTK_FILE_CHOOSER (data->impl);
4133
4134   if (cancellable != data->impl->file_list_drag_data_received_cancellable)
4135     goto out;
4136
4137   data->impl->file_list_drag_data_received_cancellable = NULL;
4138
4139   if (cancelled || error)
4140     goto out;
4141
4142   if ((data->impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
4143        data->impl->action == GTK_FILE_CHOOSER_ACTION_SAVE) &&
4144       data->uris[1] == 0 && !error &&
4145       g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
4146     change_folder_and_display_error (data->impl, data->file, FALSE);
4147   else
4148     {
4149       GError *error = NULL;
4150
4151       gtk_file_chooser_default_unselect_all (chooser);
4152       gtk_file_chooser_default_select_file (chooser, data->file, &error);
4153       if (error)
4154         error_selecting_dragged_file_dialog (data->impl, data->file, error);
4155       else
4156         browse_files_center_selected_row (data->impl);
4157     }
4158
4159   if (data->impl->select_multiple)
4160     file_list_drag_data_select_uris (data->impl, data->uris);
4161
4162 out:
4163   g_object_unref (data->impl);
4164   g_strfreev (data->uris);
4165   g_object_unref (data->file);
4166   g_free (data);
4167
4168   g_object_unref (cancellable);
4169 }
4170
4171 static void
4172 file_list_drag_data_received_cb (GtkWidget          *widget,
4173                                  GdkDragContext     *context,
4174                                  gint                x,
4175                                  gint                y,
4176                                  GtkSelectionData   *selection_data,
4177                                  guint               info,
4178                                  guint               time_,
4179                                  gpointer            data)
4180 {
4181   GtkFileChooserDefault *impl;
4182   GtkFileChooser *chooser;
4183   gchar **uris;
4184   char *uri;
4185   GFile *file;
4186
4187   impl = GTK_FILE_CHOOSER_DEFAULT (data);
4188   chooser = GTK_FILE_CHOOSER (data);
4189   
4190   /* Allow only drags from other widgets; see bug #533891. */
4191   if (gtk_drag_get_source_widget (context) == widget)
4192     return;
4193
4194   /* Parse the text/uri-list string, navigate to the first one */
4195   uris = gtk_selection_data_get_uris (selection_data);
4196   if (uris && uris[0])
4197     {
4198       struct FileListDragData *data;
4199
4200       uri = uris[0];
4201       file = g_file_new_for_uri (uri);
4202
4203       data = g_new0 (struct FileListDragData, 1);
4204       data->impl = g_object_ref (impl);
4205       data->uris = uris;
4206       data->file = file;
4207
4208       if (impl->file_list_drag_data_received_cancellable)
4209         g_cancellable_cancel (impl->file_list_drag_data_received_cancellable);
4210
4211       impl->file_list_drag_data_received_cancellable =
4212         _gtk_file_system_get_info (impl->file_system, file,
4213                                    "standard::type",
4214                                    file_list_drag_data_received_get_info_cb,
4215                                    data);
4216     }
4217
4218   g_signal_stop_emission_by_name (widget, "drag_data_received");
4219 }
4220
4221 /* Don't do anything with the drag_drop signal */
4222 static gboolean
4223 file_list_drag_drop_cb (GtkWidget             *widget,
4224                         GdkDragContext        *context,
4225                         gint                   x,
4226                         gint                   y,
4227                         guint                  time_,
4228                         GtkFileChooserDefault *impl)
4229 {
4230   g_signal_stop_emission_by_name (widget, "drag_drop");
4231   return TRUE;
4232 }
4233
4234 /* Disable the normal tree drag motion handler, it makes it look like you're
4235    dropping the dragged item onto a tree item */
4236 static gboolean
4237 file_list_drag_motion_cb (GtkWidget             *widget,
4238                           GdkDragContext        *context,
4239                           gint                   x,
4240                           gint                   y,
4241                           guint                  time_,
4242                           GtkFileChooserDefault *impl)
4243 {
4244   g_signal_stop_emission_by_name (widget, "drag_motion");
4245   return TRUE;
4246 }
4247
4248 /* Constructs the popup menu for the file list if needed */
4249 static void
4250 file_list_build_popup_menu (GtkFileChooserDefault *impl)
4251 {
4252   GtkWidget *item;
4253
4254   if (impl->browse_files_popup_menu)
4255     return;
4256
4257   impl->browse_files_popup_menu = gtk_menu_new ();
4258   gtk_menu_attach_to_widget (GTK_MENU (impl->browse_files_popup_menu),
4259                              impl->browse_files_tree_view,
4260                              popup_menu_detach_cb);
4261
4262   item = gtk_image_menu_item_new_with_mnemonic (_("_Add to Bookmarks"));
4263   impl->browse_files_popup_menu_add_shortcut_item = item;
4264   gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item),
4265                                  gtk_image_new_from_stock (GTK_STOCK_ADD, GTK_ICON_SIZE_MENU));
4266   gtk_widget_set_sensitive (item, FALSE);
4267   g_signal_connect (item, "activate",
4268                     G_CALLBACK (add_to_shortcuts_cb), impl);
4269   gtk_widget_show (item);
4270   gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item);
4271
4272   item = gtk_separator_menu_item_new ();
4273   gtk_widget_show (item);
4274   gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item);
4275
4276   item = gtk_check_menu_item_new_with_mnemonic (_("Show _Hidden Files"));
4277   impl->browse_files_popup_menu_hidden_files_item = item;
4278   g_signal_connect (item, "toggled",
4279                     G_CALLBACK (show_hidden_toggled_cb), impl);
4280   gtk_widget_show (item);
4281   gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item);
4282 }
4283
4284 /* Updates the popup menu for the file list, creating it if necessary */
4285 static void
4286 file_list_update_popup_menu (GtkFileChooserDefault *impl)
4287 {
4288   file_list_build_popup_menu (impl);
4289
4290   /* FIXME - handle OPERATION_MODE_SEARCH and OPERATION_MODE_RECENT */
4291
4292   /* The sensitivity of the Add to Bookmarks item is set in
4293    * bookmarks_check_add_sensitivity()
4294    */
4295
4296   g_signal_handlers_block_by_func (impl->browse_files_popup_menu_hidden_files_item,
4297                                    G_CALLBACK (show_hidden_toggled_cb), impl);
4298   gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (impl->browse_files_popup_menu_hidden_files_item),
4299                                   impl->show_hidden);
4300   g_signal_handlers_unblock_by_func (impl->browse_files_popup_menu_hidden_files_item,
4301                                      G_CALLBACK (show_hidden_toggled_cb), impl);
4302 }
4303
4304 static void
4305 popup_position_func (GtkMenu   *menu,
4306                      gint      *x,
4307                      gint      *y,
4308                      gboolean  *push_in,
4309                      gpointer   user_data)
4310 {
4311   GtkWidget *widget = GTK_WIDGET (user_data);
4312   GdkScreen *screen = gtk_widget_get_screen (widget);
4313   GtkRequisition req;
4314   gint monitor_num;
4315   GdkRectangle monitor;
4316
4317   g_return_if_fail (GTK_WIDGET_REALIZED (widget));
4318
4319   gdk_window_get_origin (widget->window, x, y);
4320
4321   gtk_widget_size_request (GTK_WIDGET (menu), &req);
4322
4323   *x += (widget->allocation.width - req.width) / 2;
4324   *y += (widget->allocation.height - req.height) / 2;
4325
4326   monitor_num = gdk_screen_get_monitor_at_point (screen, *x, *y);
4327   gtk_menu_set_monitor (menu, monitor_num);
4328   gdk_screen_get_monitor_geometry (screen, monitor_num, &monitor);
4329
4330   *x = CLAMP (*x, monitor.x, monitor.x + MAX (0, monitor.width - req.width));
4331   *y = CLAMP (*y, monitor.y, monitor.y + MAX (0, monitor.height - req.height));
4332
4333   *push_in = FALSE;
4334 }
4335
4336 static void
4337 file_list_popup_menu (GtkFileChooserDefault *impl,
4338                       GdkEventButton        *event)
4339 {
4340   file_list_update_popup_menu (impl);
4341   if (event)
4342     gtk_menu_popup (GTK_MENU (impl->browse_files_popup_menu),
4343                     NULL, NULL, NULL, NULL,
4344                     event->button, event->time);
4345   else
4346     {
4347       gtk_menu_popup (GTK_MENU (impl->browse_files_popup_menu),
4348                       NULL, NULL,
4349                       popup_position_func, impl->browse_files_tree_view,
4350                       0, GDK_CURRENT_TIME);
4351       gtk_menu_shell_select_first (GTK_MENU_SHELL (impl->browse_files_popup_menu),
4352                                    FALSE);
4353     }
4354
4355 }
4356
4357 /* Callback used for the GtkWidget::popup-menu signal of the file list */
4358 static gboolean
4359 list_popup_menu_cb (GtkWidget *widget,
4360                     GtkFileChooserDefault *impl)
4361 {
4362   file_list_popup_menu (impl, NULL);
4363   return TRUE;
4364 }
4365
4366 /* Callback used when a button is pressed on the file list.  We trap button 3 to
4367  * bring up a popup menu.
4368  */
4369 static gboolean
4370 list_button_press_event_cb (GtkWidget             *widget,
4371                             GdkEventButton        *event,
4372                             GtkFileChooserDefault *impl)
4373 {
4374   static gboolean in_press = FALSE;
4375   gboolean handled;
4376
4377   if (in_press)
4378     return FALSE;
4379
4380   if (event->button != 3)
4381     return FALSE;
4382
4383   in_press = TRUE;
4384   handled = gtk_widget_event (impl->browse_files_tree_view, (GdkEvent *) event);
4385   in_press = FALSE;
4386
4387   file_list_popup_menu (impl, event);
4388   return TRUE;
4389 }
4390
4391 /* Sets the sort column IDs for the file list based on the operation mode */
4392 static void
4393 file_list_set_sort_column_ids (GtkFileChooserDefault *impl)
4394 {
4395   int name_id, mtime_id;
4396
4397   name_id = mtime_id = 0;
4398
4399   switch (impl->operation_mode)
4400     {
4401     case OPERATION_MODE_BROWSE:
4402       name_id = FILE_LIST_COL_NAME;
4403       mtime_id = FILE_LIST_COL_MTIME;
4404       break;
4405     case OPERATION_MODE_SEARCH:
4406       name_id = SEARCH_MODEL_COL_FILE;
4407       mtime_id = SEARCH_MODEL_COL_STAT;
4408       break;
4409     case OPERATION_MODE_RECENT:
4410       name_id = RECENT_MODEL_COL_FILE;
4411       mtime_id = RECENT_MODEL_COL_INFO;
4412       break;
4413     }
4414
4415   gtk_tree_view_column_set_sort_column_id (impl->list_name_column, name_id);
4416   gtk_tree_view_column_set_sort_column_id (impl->list_mtime_column, mtime_id);
4417 }
4418
4419 static gboolean
4420 file_list_query_tooltip_cb (GtkWidget  *widget,
4421                             gint        x,
4422                             gint        y,
4423                             gboolean    keyboard_tip,
4424                             GtkTooltip *tooltip,
4425                             gpointer    user_data)
4426 {
4427   GtkFileChooserDefault *impl = user_data;
4428   GtkTreeIter iter, child_iter;
4429   GtkTreePath *path = NULL;
4430   GFile *file;
4431   gchar *filename;
4432
4433   if (impl->operation_mode == OPERATION_MODE_BROWSE)
4434     return FALSE;
4435
4436
4437   gtk_tree_view_get_tooltip_context (GTK_TREE_VIEW (impl->browse_files_tree_view),
4438                                      &x, &y,
4439                                      keyboard_tip,
4440                                      NULL, &path, NULL);
4441                                        
4442   if (!path)
4443     return FALSE;
4444
4445   switch (impl->operation_mode)
4446     {
4447     case OPERATION_MODE_SEARCH:
4448       if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->search_model_sort), &iter, path))
4449         {
4450           gtk_tree_path_free (path);
4451           return FALSE;
4452         }
4453
4454       search_get_valid_child_iter (impl, &child_iter, &iter);
4455       gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
4456                           SEARCH_MODEL_COL_FILE, &file,
4457                           -1);
4458       break;
4459     
4460     case OPERATION_MODE_RECENT:
4461       if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->recent_model_sort), &iter, path))
4462         {
4463           gtk_tree_path_free (path);
4464           return FALSE;
4465         }
4466
4467       recent_get_valid_child_iter (impl, &child_iter, &iter);
4468       gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
4469                           RECENT_MODEL_COL_FILE, &file,
4470                           -1);
4471       break;
4472
4473     case OPERATION_MODE_BROWSE:
4474       g_assert_not_reached ();
4475       return FALSE;
4476     }
4477
4478   if (!file)
4479     {
4480       gtk_tree_path_free (path);
4481       return FALSE;
4482     }
4483
4484   filename = g_file_get_path (file);
4485   gtk_tooltip_set_text (tooltip, filename);
4486   gtk_tree_view_set_tooltip_row (GTK_TREE_VIEW (impl->browse_files_tree_view),
4487                                  tooltip,
4488                                  path);
4489
4490   g_free (filename);
4491   gtk_tree_path_free (path);
4492
4493   return TRUE;
4494 }
4495
4496 /* Creates the widgets for the file list */
4497 static GtkWidget *
4498 create_file_list (GtkFileChooserDefault *impl)
4499 {
4500   GtkWidget *swin;
4501   GtkTreeSelection *selection;
4502   GtkTreeViewColumn *column;
4503   GtkCellRenderer *renderer;
4504
4505   /* Scrolled window */
4506   swin = gtk_scrolled_window_new (NULL, NULL);
4507   gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (swin),
4508                                   GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
4509   gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (swin),
4510                                        GTK_SHADOW_IN);
4511
4512   /* Tree/list view */
4513
4514   impl->browse_files_tree_view = gtk_tree_view_new ();
4515 #ifdef PROFILE_FILE_CHOOSER
4516   g_object_set_data (G_OBJECT (impl->browse_files_tree_view), "fmq-name", "file_list");
4517 #endif
4518   g_object_set_data (G_OBJECT (impl->browse_files_tree_view), I_("GtkFileChooserDefault"), impl);
4519   atk_object_set_name (gtk_widget_get_accessible (impl->browse_files_tree_view), _("Files"));
4520
4521   gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (impl->browse_files_tree_view), TRUE);
4522   gtk_container_add (GTK_CONTAINER (swin), impl->browse_files_tree_view);
4523
4524   gtk_drag_dest_set (impl->browse_files_tree_view,
4525                      GTK_DEST_DEFAULT_ALL,
4526                      NULL, 0,
4527                      GDK_ACTION_COPY | GDK_ACTION_MOVE);
4528   gtk_drag_dest_add_uri_targets (impl->browse_files_tree_view);
4529   
4530   g_signal_connect (impl->browse_files_tree_view, "row-activated",
4531                     G_CALLBACK (list_row_activated), impl);
4532   g_signal_connect (impl->browse_files_tree_view, "key-press-event",
4533                     G_CALLBACK (trap_activate_cb), impl);
4534   g_signal_connect (impl->browse_files_tree_view, "popup-menu",
4535                     G_CALLBACK (list_popup_menu_cb), impl);
4536   g_signal_connect (impl->browse_files_tree_view, "button-press-event",
4537                     G_CALLBACK (list_button_press_event_cb), impl);
4538
4539   g_signal_connect (impl->browse_files_tree_view, "drag-data-received",
4540                     G_CALLBACK (file_list_drag_data_received_cb), impl);
4541   g_signal_connect (impl->browse_files_tree_view, "drag-drop",
4542                     G_CALLBACK (file_list_drag_drop_cb), impl);
4543   g_signal_connect (impl->browse_files_tree_view, "drag-motion",
4544                     G_CALLBACK (file_list_drag_motion_cb), impl);
4545
4546   g_object_set (impl->browse_files_tree_view, "has-tooltip", TRUE, NULL);
4547   g_signal_connect (impl->browse_files_tree_view, "query-tooltip",
4548                     G_CALLBACK (file_list_query_tooltip_cb), impl);
4549
4550   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
4551   gtk_tree_selection_set_select_function (selection,
4552                                           list_select_func,
4553                                           impl, NULL);
4554   gtk_tree_view_enable_model_drag_source (GTK_TREE_VIEW (impl->browse_files_tree_view),
4555                                           GDK_BUTTON1_MASK,
4556                                           NULL, 0,
4557                                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4558   gtk_drag_source_add_uri_targets (impl->browse_files_tree_view);
4559
4560   g_signal_connect (selection, "changed",
4561                     G_CALLBACK (list_selection_changed), impl);
4562
4563   /* Filename column */
4564
4565   impl->list_name_column = gtk_tree_view_column_new ();
4566   gtk_tree_view_column_set_expand (impl->list_name_column, TRUE);
4567   gtk_tree_view_column_set_resizable (impl->list_name_column, TRUE);
4568   gtk_tree_view_column_set_title (impl->list_name_column, _("Name"));
4569   gtk_tree_view_column_set_sort_column_id (impl->list_name_column, FILE_LIST_COL_NAME);
4570
4571   renderer = gtk_cell_renderer_pixbuf_new ();
4572   gtk_tree_view_column_pack_start (impl->list_name_column, renderer, FALSE);
4573   gtk_tree_view_column_set_cell_data_func (impl->list_name_column, renderer,
4574                                            list_icon_data_func, impl, NULL);
4575
4576   impl->list_name_renderer = gtk_cell_renderer_text_new ();
4577   g_object_set (impl->list_name_renderer,
4578                 "ellipsize", PANGO_ELLIPSIZE_END,
4579                 NULL);
4580   g_signal_connect (impl->list_name_renderer, "edited",
4581                     G_CALLBACK (renderer_edited_cb), impl);
4582   g_signal_connect (impl->list_name_renderer, "editing-canceled",
4583                     G_CALLBACK (renderer_editing_canceled_cb), impl);
4584   gtk_tree_view_column_pack_start (impl->list_name_column, impl->list_name_renderer, TRUE);
4585   gtk_tree_view_column_set_cell_data_func (impl->list_name_column, impl->list_name_renderer,
4586                                            list_name_data_func, impl, NULL);
4587
4588   gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), impl->list_name_column);
4589 #if 0
4590   /* Size column */
4591
4592   column = gtk_tree_view_column_new ();
4593   gtk_tree_view_column_set_title (column, _("Size"));
4594
4595   renderer = gtk_cell_renderer_text_new ();
4596   gtk_tree_view_column_pack_start (column, renderer, TRUE); /* bug: it doesn't expand */
4597   gtk_tree_view_column_set_cell_data_func (column, renderer,
4598                                            list_size_data_func, impl, NULL);
4599   gtk_tree_view_column_set_sort_column_id (column, FILE_LIST_COL_SIZE);
4600   gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), column);
4601 #endif
4602
4603   /* Modification time column */
4604
4605   column = gtk_tree_view_column_new ();
4606   gtk_tree_view_column_set_resizable (column, TRUE);
4607   gtk_tree_view_column_set_title (column, _("Modified"));
4608
4609   renderer = gtk_cell_renderer_text_new ();
4610   gtk_tree_view_column_pack_start (column, renderer, TRUE);
4611   gtk_tree_view_column_set_cell_data_func (column, renderer,
4612                                            list_mtime_data_func, impl, NULL);
4613   gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), column);
4614   impl->list_mtime_column = column;
4615   
4616   file_list_set_sort_column_ids (impl);
4617
4618   gtk_widget_show_all (swin);
4619
4620   return swin;
4621 }
4622
4623 static GtkWidget *
4624 create_path_bar (GtkFileChooserDefault *impl)
4625 {
4626   GtkWidget *path_bar;
4627
4628   path_bar = g_object_new (GTK_TYPE_PATH_BAR, NULL);
4629   _gtk_path_bar_set_file_system (GTK_PATH_BAR (path_bar), impl->file_system);
4630
4631   return path_bar;
4632 }
4633
4634 /* Creates the widgets for the files/folders pane */
4635 static GtkWidget *
4636 file_pane_create (GtkFileChooserDefault *impl,
4637                   GtkSizeGroup          *size_group)
4638 {
4639   GtkWidget *vbox;
4640   GtkWidget *hbox;
4641   GtkWidget *widget;
4642
4643   vbox = gtk_vbox_new (FALSE, 6);
4644   gtk_widget_show (vbox);
4645
4646   /* Box for lists and preview */
4647
4648   hbox = gtk_hbox_new (FALSE, PREVIEW_HBOX_SPACING);
4649   gtk_box_pack_start (GTK_BOX (vbox), hbox, TRUE, TRUE, 0);
4650   gtk_widget_show (hbox);
4651
4652   /* File list */
4653
4654   widget = create_file_list (impl);
4655   gtk_box_pack_start (GTK_BOX (hbox), widget, TRUE, TRUE, 0);
4656
4657   /* Preview */
4658
4659   impl->preview_box = gtk_vbox_new (FALSE, 12);
4660   gtk_box_pack_start (GTK_BOX (hbox), impl->preview_box, FALSE, FALSE, 0);
4661   /* Don't show preview box initially */
4662
4663   /* Filter combo */
4664
4665   impl->filter_combo_hbox = gtk_hbox_new (FALSE, 12);
4666
4667   widget = filter_create (impl);
4668
4669   gtk_widget_show (widget);
4670   gtk_box_pack_end (GTK_BOX (impl->filter_combo_hbox), widget, FALSE, FALSE, 0);
4671
4672   gtk_size_group_add_widget (size_group, impl->filter_combo_hbox);
4673   gtk_box_pack_end (GTK_BOX (vbox), impl->filter_combo_hbox, FALSE, FALSE, 0);
4674
4675   return vbox;
4676 }
4677
4678 /* Callback used when the "Browse for more folders" expander is toggled */
4679 static void
4680 expander_changed_cb (GtkExpander           *expander,
4681                      GParamSpec            *pspec,
4682                      GtkFileChooserDefault *impl)
4683 {
4684   impl->expand_folders = gtk_expander_get_expanded(GTK_EXPANDER (impl->save_expander));
4685   update_appearance (impl);
4686 }
4687
4688 /* Callback used when the selection changes in the save folder combo box */
4689 static void
4690 save_folder_combo_changed_cb (GtkComboBox           *combo,
4691                               GtkFileChooserDefault *impl)
4692 {
4693   GtkTreeIter iter;
4694
4695   if (impl->changing_folder)
4696     return;
4697
4698   if (gtk_combo_box_get_active_iter (combo, &iter))
4699     {
4700       GtkTreeIter child_iter;
4701       
4702       gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (impl->shortcuts_combo_filter_model),
4703                                                         &child_iter,
4704                                                         &iter);
4705       shortcuts_activate_iter (impl, &child_iter);
4706     }
4707 }
4708
4709 /* Filter function used to filter out the Search item and its separator.  
4710  * Used for the "Save in folder" combo box, so that these items do not appear in it.
4711  */
4712 static gboolean
4713 shortcuts_combo_filter_func (GtkTreeModel *model,
4714                              GtkTreeIter  *iter,
4715                              gpointer      data)
4716 {
4717   GtkFileChooserDefault *impl;
4718   GtkTreePath *tree_path;
4719   gint *indices;
4720   int idx;
4721   gboolean retval;
4722
4723   impl = GTK_FILE_CHOOSER_DEFAULT (data);
4724
4725   g_assert (model == GTK_TREE_MODEL (impl->shortcuts_model));
4726
4727   tree_path = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->shortcuts_model), iter);
4728   g_assert (tree_path != NULL);
4729
4730   indices = gtk_tree_path_get_indices (tree_path);
4731
4732   retval = TRUE;
4733
4734   if (impl->has_search)
4735     {
4736       idx = shortcuts_get_index (impl, SHORTCUTS_SEARCH);
4737       if (idx == indices[0])
4738         retval = FALSE;
4739     }
4740   
4741   if (impl->has_recent)
4742     {
4743       idx = shortcuts_get_index (impl, SHORTCUTS_RECENT);
4744       if (idx == indices[0])
4745         retval = FALSE;
4746       else
4747         {
4748           idx = shortcuts_get_index (impl, SHORTCUTS_RECENT_SEPARATOR);
4749           if (idx == indices[0])
4750             retval = FALSE;
4751         }
4752      }
4753
4754   gtk_tree_path_free (tree_path);
4755
4756   return retval;
4757  }
4758
4759 /* Creates the combo box with the save folders */
4760 static GtkWidget *
4761 save_folder_combo_create (GtkFileChooserDefault *impl)
4762 {
4763   GtkWidget *combo;
4764   GtkCellRenderer *cell;
4765
4766   impl->shortcuts_combo_filter_model = gtk_tree_model_filter_new (GTK_TREE_MODEL (impl->shortcuts_model), NULL);
4767   gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (impl->shortcuts_combo_filter_model),
4768                                           shortcuts_combo_filter_func,
4769                                           impl,
4770                                           NULL);
4771
4772   combo = g_object_new (GTK_TYPE_COMBO_BOX,
4773                         "model", impl->shortcuts_combo_filter_model,
4774                         "focus-on-click", FALSE,
4775                         NULL);
4776   gtk_widget_show (combo);
4777
4778   cell = gtk_cell_renderer_pixbuf_new ();
4779   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), cell, FALSE);
4780   gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo), cell,
4781                                   "pixbuf", SHORTCUTS_COL_PIXBUF,
4782                                   "visible", SHORTCUTS_COL_PIXBUF_VISIBLE,
4783                                   "sensitive", SHORTCUTS_COL_PIXBUF_VISIBLE,
4784                                   NULL);
4785
4786   cell = gtk_cell_renderer_text_new ();
4787   gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), cell, TRUE);
4788   gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo), cell,
4789                                   "text", SHORTCUTS_COL_NAME,
4790                                   "sensitive", SHORTCUTS_COL_PIXBUF_VISIBLE,
4791                                   NULL);
4792
4793   gtk_combo_box_set_row_separator_func (GTK_COMBO_BOX (combo),
4794                                         shortcuts_row_separator_func,
4795                                         NULL, NULL);
4796
4797   g_signal_connect (combo, "changed",
4798                     G_CALLBACK (save_folder_combo_changed_cb), impl);
4799
4800   return combo;
4801 }
4802
4803 /* Creates the widgets specific to Save mode */
4804 static void
4805 save_widgets_create (GtkFileChooserDefault *impl)
4806 {
4807   GtkWidget *vbox;
4808   GtkWidget *table;
4809   GtkWidget *widget;
4810   GtkWidget *alignment;
4811
4812   if (impl->save_widgets != NULL)
4813     return;
4814
4815   location_switch_to_path_bar (impl);
4816
4817   vbox = gtk_vbox_new (FALSE, 12);
4818
4819   table = gtk_table_new (2, 2, FALSE);
4820   gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, FALSE, 0);
4821   gtk_widget_show (table);
4822   gtk_table_set_row_spacings (GTK_TABLE (table), 12);
4823   gtk_table_set_col_spacings (GTK_TABLE (table), 12);
4824
4825   /* Label */
4826
4827   widget = gtk_label_new_with_mnemonic (_("_Name:"));
4828   gtk_misc_set_alignment (GTK_MISC (widget), 0.0, 0.5);
4829   gtk_table_attach (GTK_TABLE (table), widget,
4830                     0, 1, 0, 1,
4831                     GTK_FILL, GTK_FILL,
4832                     0, 0);
4833   gtk_widget_show (widget);
4834
4835   /* Location entry */
4836
4837   impl->location_entry = _gtk_file_chooser_entry_new (TRUE);
4838   _gtk_file_chooser_entry_set_file_system (GTK_FILE_CHOOSER_ENTRY (impl->location_entry),
4839                                            impl->file_system);
4840   gtk_entry_set_width_chars (GTK_ENTRY (impl->location_entry), 45);
4841   gtk_entry_set_activates_default (GTK_ENTRY (impl->location_entry), TRUE);
4842   gtk_table_attach (GTK_TABLE (table), impl->location_entry,
4843                     1, 2, 0, 1,
4844                     GTK_EXPAND | GTK_FILL, 0,
4845                     0, 0);
4846   gtk_widget_show (impl->location_entry);
4847   gtk_label_set_mnemonic_widget (GTK_LABEL (widget), impl->location_entry);
4848
4849   /* Folder combo */
4850   impl->save_folder_label = gtk_label_new (NULL);
4851   gtk_misc_set_alignment (GTK_MISC (impl->save_folder_label), 0.0, 0.5);
4852   gtk_table_attach (GTK_TABLE (table), impl->save_folder_label,
4853                     0, 1, 1, 2,
4854                     GTK_FILL, GTK_FILL,
4855                     0, 0);
4856   gtk_widget_show (impl->save_folder_label);
4857
4858   impl->save_folder_combo = save_folder_combo_create (impl);
4859   gtk_table_attach (GTK_TABLE (table), impl->save_folder_combo,
4860                     1, 2, 1, 2,
4861                     GTK_EXPAND | GTK_FILL, GTK_FILL,
4862                     0, 0);
4863   gtk_label_set_mnemonic_widget (GTK_LABEL (impl->save_folder_label), impl->save_folder_combo);
4864
4865   /* Expander */
4866   alignment = gtk_alignment_new (0.0, 0.5, 1.0, 1.0);
4867   gtk_box_pack_start (GTK_BOX (vbox), alignment, FALSE, FALSE, 0);
4868
4869   impl->save_expander = gtk_expander_new_with_mnemonic (_("_Browse for other folders"));
4870   gtk_container_add (GTK_CONTAINER (alignment), impl->save_expander);
4871   g_signal_connect (impl->save_expander, "notify::expanded",
4872                     G_CALLBACK (expander_changed_cb),
4873                     impl);
4874   gtk_widget_show_all (alignment);
4875
4876   impl->save_widgets = vbox;
4877   gtk_box_pack_start (GTK_BOX (impl), impl->save_widgets, FALSE, FALSE, 0);
4878   gtk_box_reorder_child (GTK_BOX (impl), impl->save_widgets, 0);
4879   gtk_widget_show (impl->save_widgets);
4880 }
4881
4882 /* Destroys the widgets specific to Save mode */
4883 static void
4884 save_widgets_destroy (GtkFileChooserDefault *impl)
4885 {
4886   if (impl->save_widgets == NULL)
4887     return;
4888
4889   gtk_widget_destroy (impl->save_widgets);
4890   impl->save_widgets = NULL;
4891   impl->location_entry = NULL;
4892   impl->save_folder_label = NULL;
4893   impl->save_folder_combo = NULL;
4894   impl->save_expander = NULL;
4895 }
4896
4897 /* Turns on the path bar widget.  Can be called even if we are already in that
4898  * mode.
4899  */
4900 static void
4901 location_switch_to_path_bar (GtkFileChooserDefault *impl)
4902 {
4903   if (impl->location_entry)
4904     {
4905       gtk_widget_destroy (impl->location_entry);
4906       impl->location_entry = NULL;
4907     }
4908
4909   gtk_widget_hide (impl->location_entry_box);
4910 }
4911
4912 /* Sets the full path of the current folder as the text in the location entry. */
4913 static void
4914 location_entry_set_initial_text (GtkFileChooserDefault *impl)
4915 {
4916   gchar *text, *filename;
4917
4918   if (!impl->current_folder)
4919     return;
4920
4921   filename = g_file_get_path (impl->current_folder);
4922
4923   if (filename)
4924     {
4925       text = g_filename_to_utf8 (filename, -1, NULL, NULL, NULL);
4926       g_free (filename);
4927     }
4928   else
4929     text = g_file_get_uri (impl->current_folder);
4930
4931   if (text)
4932     {
4933       gboolean need_slash;
4934       int len;
4935
4936       len = strlen (text);
4937       need_slash = (text[len - 1] != G_DIR_SEPARATOR);
4938
4939       if (need_slash)
4940         {
4941           char *slash_text;
4942
4943           slash_text = g_new (char, len + 2);
4944           strcpy (slash_text, text);
4945           slash_text[len] = G_DIR_SEPARATOR;
4946           slash_text[len + 1] = 0;
4947
4948           g_free (text);
4949           text = slash_text;
4950         }
4951
4952       _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), text);
4953       g_free (text);
4954     }
4955
4956   g_free (filename);
4957 }
4958
4959 /* Turns on the location entry.  Can be called even if we are already in that
4960  * mode.
4961  */
4962 static void
4963 location_switch_to_filename_entry (GtkFileChooserDefault *impl)
4964 {
4965   /* when in search or recent files mode, we are not showing the
4966    * location_entry_box container, so there's no point in switching
4967    * to it.
4968    */
4969   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
4970       impl->operation_mode == OPERATION_MODE_RECENT)
4971     return;
4972
4973   if (impl->location_entry)
4974     gtk_widget_destroy (impl->location_entry);
4975
4976   /* Box */
4977
4978   gtk_widget_show (impl->location_entry_box);
4979
4980   /* Entry */
4981
4982   impl->location_entry = _gtk_file_chooser_entry_new (TRUE);
4983   _gtk_file_chooser_entry_set_file_system (GTK_FILE_CHOOSER_ENTRY (impl->location_entry),
4984                                            impl->file_system);
4985   gtk_entry_set_activates_default (GTK_ENTRY (impl->location_entry), TRUE);
4986   _gtk_file_chooser_entry_set_action (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->action);
4987
4988   gtk_box_pack_start (GTK_BOX (impl->location_entry_box), impl->location_entry, TRUE, TRUE, 0);
4989   gtk_label_set_mnemonic_widget (GTK_LABEL (impl->location_label), impl->location_entry);
4990
4991   /* Configure the entry */
4992
4993   _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->current_folder);
4994
4995   /* Done */
4996
4997   gtk_widget_show (impl->location_entry);
4998   gtk_widget_grab_focus (impl->location_entry);
4999 }
5000
5001 /* Sets a new location mode.  set_buttons determines whether the toggle button
5002  * for the mode will also be changed.
5003  */
5004 static void
5005 location_mode_set (GtkFileChooserDefault *impl,
5006                    LocationMode new_mode,
5007                    gboolean set_button)
5008 {
5009   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
5010       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
5011     {
5012       GtkWindow *toplevel;
5013       GtkWidget *current_focus;
5014       gboolean button_active;
5015       gboolean switch_to_file_list;
5016
5017       switch (new_mode)
5018         {
5019         case LOCATION_MODE_PATH_BAR:
5020           button_active = FALSE;
5021
5022           /* The location_entry will disappear when we switch to path bar mode.  So,
5023            * we'll focus the file list in that case, to avoid having a window with
5024            * no focused widget.
5025            */
5026           toplevel = get_toplevel (GTK_WIDGET (impl));
5027           switch_to_file_list = FALSE;
5028           if (toplevel)
5029             {
5030               current_focus = gtk_window_get_focus (toplevel);
5031               if (!current_focus || current_focus == impl->location_entry)
5032                 switch_to_file_list = TRUE;
5033             }
5034
5035           location_switch_to_path_bar (impl);
5036
5037           if (switch_to_file_list)
5038             gtk_widget_grab_focus (impl->browse_files_tree_view);
5039
5040           break;
5041
5042         case LOCATION_MODE_FILENAME_ENTRY:
5043           button_active = TRUE;
5044           location_switch_to_filename_entry (impl);
5045           break;
5046
5047         default:
5048           g_assert_not_reached ();
5049           return;
5050         }
5051
5052       if (set_button)
5053         {
5054           g_signal_handlers_block_by_func (impl->location_button,
5055                                            G_CALLBACK (location_button_toggled_cb), impl);
5056
5057           gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (impl->location_button), button_active);
5058
5059           g_signal_handlers_unblock_by_func (impl->location_button,
5060                                              G_CALLBACK (location_button_toggled_cb), impl);
5061         }
5062     }
5063
5064   impl->location_mode = new_mode;
5065 }
5066
5067 static void
5068 location_toggle_popup_handler (GtkFileChooserDefault *impl)
5069 {
5070   /* when in search or recent files mode, we are not showing the
5071    * location_entry_box container, so there's no point in switching
5072    * to it.
5073    */
5074   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
5075       impl->operation_mode == OPERATION_MODE_RECENT)
5076     return;
5077
5078   /* If the file entry is not visible, show it.
5079    * If it is visible, turn it off only if it is focused.  Otherwise, switch to the entry.
5080    */
5081   if (impl->location_mode == LOCATION_MODE_PATH_BAR)
5082     {
5083       location_mode_set (impl, LOCATION_MODE_FILENAME_ENTRY, TRUE);
5084     }
5085   else if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
5086     {
5087       if (GTK_WIDGET_HAS_FOCUS (impl->location_entry))
5088         {
5089           location_mode_set (impl, LOCATION_MODE_PATH_BAR, TRUE);
5090         }
5091       else
5092         {
5093           gtk_widget_grab_focus (impl->location_entry);
5094         }
5095     }
5096 }
5097
5098 /* Callback used when one of the location mode buttons is toggled */
5099 static void
5100 location_button_toggled_cb (GtkToggleButton *toggle,
5101                             GtkFileChooserDefault *impl)
5102 {
5103   gboolean is_active;
5104   LocationMode new_mode;
5105
5106   is_active = gtk_toggle_button_get_active (toggle);
5107
5108   if (is_active)
5109     {
5110       g_assert (impl->location_mode == LOCATION_MODE_PATH_BAR);
5111       new_mode = LOCATION_MODE_FILENAME_ENTRY;
5112     }
5113   else
5114     {
5115       g_assert (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY);
5116       new_mode = LOCATION_MODE_PATH_BAR;
5117     }
5118
5119   location_mode_set (impl, new_mode, FALSE);
5120 }
5121
5122 /* Creates a toggle button for the location entry. */
5123 static void
5124 location_button_create (GtkFileChooserDefault *impl)
5125 {
5126   GtkWidget *image;
5127   const char *str;
5128
5129   image = gtk_image_new_from_stock (GTK_STOCK_EDIT, GTK_ICON_SIZE_BUTTON);
5130   gtk_widget_show (image);
5131
5132   impl->location_button = g_object_new (GTK_TYPE_TOGGLE_BUTTON,
5133                                         "image", image,
5134                                         NULL);
5135
5136   g_signal_connect (impl->location_button, "toggled",
5137                     G_CALLBACK (location_button_toggled_cb), impl);
5138
5139   str = _("Type a file name");
5140
5141   gtk_widget_set_tooltip_text (impl->location_button, str);
5142   atk_object_set_name (gtk_widget_get_accessible (impl->location_button), str);
5143 }
5144
5145 /* Creates the main hpaned with the widgets shared by Open and Save mode */
5146 static GtkWidget *
5147 browse_widgets_create (GtkFileChooserDefault *impl)
5148 {
5149   GtkWidget *vbox;
5150   GtkWidget *hbox;
5151   GtkWidget *hpaned;
5152   GtkWidget *widget;
5153   GtkSizeGroup *size_group;
5154
5155   /* size group is used by the [+][-] buttons and the filter combo */
5156   size_group = gtk_size_group_new (GTK_SIZE_GROUP_VERTICAL);
5157   vbox = gtk_vbox_new (FALSE, 12);
5158
5159   /* Location widgets */
5160   hbox = gtk_hbox_new (FALSE, 12);
5161   gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
5162   gtk_widget_show (hbox);
5163   impl->browse_path_bar_hbox = hbox;
5164
5165   location_button_create (impl);
5166   gtk_box_pack_start (GTK_BOX (hbox), impl->location_button, FALSE, FALSE, 0);
5167
5168   /* Path bar */
5169
5170   impl->browse_path_bar = create_path_bar (impl);
5171   g_signal_connect (impl->browse_path_bar, "path-clicked", G_CALLBACK (path_bar_clicked), impl);
5172   gtk_widget_show_all (impl->browse_path_bar);
5173   gtk_box_pack_start (GTK_BOX (hbox), impl->browse_path_bar, TRUE, TRUE, 0);
5174
5175   /* Create Folder */
5176   impl->browse_new_folder_button = gtk_button_new_with_mnemonic (_("Create Fo_lder"));
5177   g_signal_connect (impl->browse_new_folder_button, "clicked",
5178                     G_CALLBACK (new_folder_button_clicked), impl);
5179   gtk_box_pack_end (GTK_BOX (hbox), impl->browse_new_folder_button, FALSE, FALSE, 0);
5180
5181   /* Box for the location label and entry */
5182
5183   impl->location_entry_box = gtk_hbox_new (FALSE, 12);
5184   gtk_box_pack_start (GTK_BOX (vbox), impl->location_entry_box, FALSE, FALSE, 0);
5185
5186   impl->location_label = gtk_label_new_with_mnemonic (_("_Location:"));
5187   gtk_widget_show (impl->location_label);
5188   gtk_box_pack_start (GTK_BOX (impl->location_entry_box), impl->location_label, FALSE, FALSE, 0);
5189
5190   /* Paned widget */
5191   hpaned = gtk_hpaned_new ();
5192   gtk_widget_show (hpaned);
5193   gtk_box_pack_start (GTK_BOX (vbox), hpaned, TRUE, TRUE, 0);
5194
5195   widget = shortcuts_pane_create (impl, size_group);
5196   gtk_paned_pack1 (GTK_PANED (hpaned), widget, FALSE, FALSE);
5197   widget = file_pane_create (impl, size_group);
5198   gtk_paned_pack2 (GTK_PANED (hpaned), widget, TRUE, FALSE);
5199
5200   g_object_unref (size_group);
5201
5202   return vbox;
5203 }
5204
5205 static GObject*
5206 gtk_file_chooser_default_constructor (GType                  type,
5207                                       guint                  n_construct_properties,
5208                                       GObjectConstructParam *construct_params)
5209 {
5210   GtkFileChooserDefault *impl;
5211   GObject *object;
5212
5213   profile_start ("start", NULL);
5214
5215   object = G_OBJECT_CLASS (_gtk_file_chooser_default_parent_class)->constructor (type,
5216                                                                                 n_construct_properties,
5217                                                                                 construct_params);
5218   impl = GTK_FILE_CHOOSER_DEFAULT (object);
5219
5220   g_assert (impl->file_system);
5221
5222   gtk_widget_push_composite_child ();
5223
5224   /* Shortcuts model */
5225   shortcuts_model_create (impl);
5226
5227   /* The browse widgets */
5228   impl->browse_widgets = browse_widgets_create (impl);
5229   gtk_box_pack_start (GTK_BOX (impl), impl->browse_widgets, TRUE, TRUE, 0);
5230
5231   /* Alignment to hold extra widget */
5232   impl->extra_align = gtk_alignment_new (0.0, 0.5, 1.0, 1.0);
5233   gtk_box_pack_start (GTK_BOX (impl), impl->extra_align, FALSE, FALSE, 0);
5234
5235   gtk_widget_pop_composite_child ();
5236   update_appearance (impl);
5237
5238   profile_end ("end", NULL);
5239
5240   return object;
5241 }
5242
5243 /* Sets the extra_widget by packing it in the appropriate place */
5244 static void
5245 set_extra_widget (GtkFileChooserDefault *impl,
5246                   GtkWidget             *extra_widget)
5247 {
5248   if (extra_widget)
5249     {
5250       g_object_ref (extra_widget);
5251       /* FIXME: is this right ? */
5252       gtk_widget_show (extra_widget);
5253     }
5254
5255   if (impl->extra_widget)
5256     {
5257       gtk_container_remove (GTK_CONTAINER (impl->extra_align), impl->extra_widget);
5258       g_object_unref (impl->extra_widget);
5259     }
5260
5261   impl->extra_widget = extra_widget;
5262   if (impl->extra_widget)
5263     {
5264       gtk_container_add (GTK_CONTAINER (impl->extra_align), impl->extra_widget);
5265       gtk_widget_show (impl->extra_align);
5266     }
5267   else
5268     gtk_widget_hide (impl->extra_align);
5269 }
5270
5271 static void
5272 set_local_only (GtkFileChooserDefault *impl,
5273                 gboolean               local_only)
5274 {
5275   if (local_only != impl->local_only)
5276     {
5277       impl->local_only = local_only;
5278
5279       if (impl->shortcuts_model && impl->file_system)
5280         {
5281           shortcuts_add_volumes (impl);
5282           shortcuts_add_bookmarks (impl);
5283         }
5284
5285       if (local_only && !g_file_is_native (impl->current_folder))
5286         {
5287           /* If we are pointing to a non-local folder, make an effort to change
5288            * back to a local folder, but it's really up to the app to not cause
5289            * such a situation, so we ignore errors.
5290            */
5291           const gchar *home = g_get_home_dir ();
5292           GFile *home_file;
5293
5294           if (home == NULL)
5295             return;
5296
5297           home_file = g_file_new_for_path (home);
5298
5299           gtk_file_chooser_set_current_folder_file (GTK_FILE_CHOOSER (impl), home_file, NULL);
5300
5301           g_object_unref (home_file);
5302         }
5303     }
5304 }
5305
5306 static void
5307 volumes_bookmarks_changed_cb (GtkFileSystem         *file_system,
5308                               GtkFileChooserDefault *impl)
5309 {
5310   shortcuts_add_volumes (impl);
5311   shortcuts_add_bookmarks (impl);
5312
5313   bookmarks_check_add_sensitivity (impl);
5314   bookmarks_check_remove_sensitivity (impl);
5315   shortcuts_check_popup_sensitivity (impl);
5316 }
5317
5318 /* Sets the file chooser to multiple selection mode */
5319 static void
5320 set_select_multiple (GtkFileChooserDefault *impl,
5321                      gboolean               select_multiple,
5322                      gboolean               property_notify)
5323 {
5324   GtkTreeSelection *selection;
5325   GtkSelectionMode mode;
5326
5327   if (select_multiple == impl->select_multiple)
5328     return;
5329
5330   mode = select_multiple ? GTK_SELECTION_MULTIPLE : GTK_SELECTION_BROWSE;
5331
5332   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
5333   gtk_tree_selection_set_mode (selection, mode);
5334
5335   gtk_tree_view_set_rubber_banding (GTK_TREE_VIEW (impl->browse_files_tree_view), select_multiple);
5336
5337   impl->select_multiple = select_multiple;
5338   g_object_notify (G_OBJECT (impl), "select-multiple");
5339
5340   check_preview_change (impl);
5341 }
5342
5343 static void
5344 set_file_system_backend (GtkFileChooserDefault *impl)
5345 {
5346   profile_start ("start for backend", "default");
5347
5348   impl->file_system = _gtk_file_system_new ();
5349
5350   g_signal_connect (impl->file_system, "volumes-changed",
5351                     G_CALLBACK (volumes_bookmarks_changed_cb), impl);
5352   g_signal_connect (impl->file_system, "bookmarks-changed",
5353                     G_CALLBACK (volumes_bookmarks_changed_cb), impl);
5354
5355   profile_end ("end", NULL);
5356 }
5357
5358 /* This function is basically a do_all function.
5359  *
5360  * It sets the visibility on all the widgets based on the current state, and
5361  * moves the custom_widget if needed.
5362  */
5363 static void
5364 update_appearance (GtkFileChooserDefault *impl)
5365 {
5366   if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5367       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5368     {
5369       const char *text;
5370
5371       gtk_widget_hide (impl->location_button);
5372       save_widgets_create (impl);
5373
5374       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
5375         text = _("Save in _folder:");
5376       else
5377         text = _("Create in _folder:");
5378
5379       gtk_label_set_text_with_mnemonic (GTK_LABEL (impl->save_folder_label), text);
5380
5381       if (gtk_expander_get_expanded (GTK_EXPANDER (impl->save_expander)))
5382         {
5383           gtk_widget_set_sensitive (impl->save_folder_label, FALSE);
5384           gtk_widget_set_sensitive (impl->save_folder_combo, FALSE);
5385           gtk_widget_show (impl->browse_widgets);
5386         }
5387       else
5388         {
5389           gtk_widget_set_sensitive (impl->save_folder_label, TRUE);
5390           gtk_widget_set_sensitive (impl->save_folder_combo, TRUE);
5391           gtk_widget_hide (impl->browse_widgets);
5392         }
5393
5394       gtk_widget_show (impl->browse_new_folder_button);
5395
5396       if (impl->select_multiple)
5397         {
5398           g_warning ("Save mode cannot be set in conjunction with multiple selection mode.  "
5399                      "Re-setting to single selection mode.");
5400           set_select_multiple (impl, FALSE, TRUE);
5401         }
5402     }
5403   else if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
5404            impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
5405     {
5406       gtk_widget_show (impl->location_button);
5407       save_widgets_destroy (impl);
5408       gtk_widget_show (impl->browse_widgets);
5409       location_mode_set (impl, impl->location_mode, TRUE);
5410     }
5411
5412   if (impl->location_entry)
5413     _gtk_file_chooser_entry_set_action (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->action);
5414
5415   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
5416     gtk_widget_hide (impl->browse_new_folder_button);
5417   else
5418     gtk_widget_show (impl->browse_new_folder_button);
5419
5420   /* This *is* needed; we need to redraw the file list because the "sensitivity"
5421    * of files may change depending whether we are in a file or folder-only mode.
5422    */
5423   gtk_widget_queue_draw (impl->browse_files_tree_view);
5424
5425   g_signal_emit_by_name (impl, "default-size-changed");
5426 }
5427
5428 static void
5429 gtk_file_chooser_default_set_property (GObject      *object,
5430                                        guint         prop_id,
5431                                        const GValue *value,
5432                                        GParamSpec   *pspec)
5433
5434 {
5435   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (object);
5436
5437   switch (prop_id)
5438     {
5439     case GTK_FILE_CHOOSER_PROP_ACTION:
5440       {
5441         GtkFileChooserAction action = g_value_get_enum (value);
5442
5443         if (action != impl->action)
5444           {
5445             gtk_file_chooser_default_unselect_all (GTK_FILE_CHOOSER (impl));
5446             
5447             if ((action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5448                  action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5449                 && impl->select_multiple)
5450               {
5451                 g_warning ("Tried to change the file chooser action to SAVE or CREATE_FOLDER, but "
5452                            "this is not allowed in multiple selection mode.  Resetting the file chooser "
5453                            "to single selection mode.");
5454                 set_select_multiple (impl, FALSE, TRUE);
5455               }
5456             impl->action = action;
5457             update_appearance (impl);
5458             settings_load (impl);
5459           }
5460       }
5461       break;
5462
5463     case GTK_FILE_CHOOSER_PROP_FILE_SYSTEM_BACKEND:
5464       /* Ignore property */
5465       break;
5466
5467     case GTK_FILE_CHOOSER_PROP_FILTER:
5468       set_current_filter (impl, g_value_get_object (value));
5469       break;
5470
5471     case GTK_FILE_CHOOSER_PROP_LOCAL_ONLY:
5472       set_local_only (impl, g_value_get_boolean (value));
5473       break;
5474
5475     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET:
5476       set_preview_widget (impl, g_value_get_object (value));
5477       break;
5478
5479     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET_ACTIVE:
5480       impl->preview_widget_active = g_value_get_boolean (value);
5481       update_preview_widget_visibility (impl);
5482       break;
5483
5484     case GTK_FILE_CHOOSER_PROP_USE_PREVIEW_LABEL:
5485       impl->use_preview_label = g_value_get_boolean (value);
5486       update_preview_widget_visibility (impl);
5487       break;
5488
5489     case GTK_FILE_CHOOSER_PROP_EXTRA_WIDGET:
5490       set_extra_widget (impl, g_value_get_object (value));
5491       break;
5492
5493     case GTK_FILE_CHOOSER_PROP_SELECT_MULTIPLE:
5494       {
5495         gboolean select_multiple = g_value_get_boolean (value);
5496         if ((impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5497              impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5498             && select_multiple)
5499           {
5500             g_warning ("Tried to set the file chooser to multiple selection mode, but this is "
5501                        "not allowed in SAVE or CREATE_FOLDER modes.  Ignoring the change and "
5502                        "leaving the file chooser in single selection mode.");
5503             return;
5504           }
5505
5506         set_select_multiple (impl, select_multiple, FALSE);
5507       }
5508       break;
5509
5510     case GTK_FILE_CHOOSER_PROP_SHOW_HIDDEN:
5511       {
5512         gboolean show_hidden = g_value_get_boolean (value);
5513         if (show_hidden != impl->show_hidden)
5514           {
5515             impl->show_hidden = show_hidden;
5516
5517             if (impl->browse_files_model)
5518               _gtk_file_system_model_set_show_hidden (impl->browse_files_model, show_hidden);
5519           }
5520       }
5521       break;
5522
5523     case GTK_FILE_CHOOSER_PROP_DO_OVERWRITE_CONFIRMATION:
5524       {
5525         gboolean do_overwrite_confirmation = g_value_get_boolean (value);
5526         impl->do_overwrite_confirmation = do_overwrite_confirmation;
5527       }
5528       break;
5529
5530     default:
5531       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5532       break;
5533     }
5534 }
5535
5536 static void
5537 gtk_file_chooser_default_get_property (GObject    *object,
5538                                        guint       prop_id,
5539                                        GValue     *value,
5540                                        GParamSpec *pspec)
5541 {
5542   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (object);
5543
5544   switch (prop_id)
5545     {
5546     case GTK_FILE_CHOOSER_PROP_ACTION:
5547       g_value_set_enum (value, impl->action);
5548       break;
5549
5550     case GTK_FILE_CHOOSER_PROP_FILTER:
5551       g_value_set_object (value, impl->current_filter);
5552       break;
5553
5554     case GTK_FILE_CHOOSER_PROP_LOCAL_ONLY:
5555       g_value_set_boolean (value, impl->local_only);
5556       break;
5557
5558     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET:
5559       g_value_set_object (value, impl->preview_widget);
5560       break;
5561
5562     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET_ACTIVE:
5563       g_value_set_boolean (value, impl->preview_widget_active);
5564       break;
5565
5566     case GTK_FILE_CHOOSER_PROP_USE_PREVIEW_LABEL:
5567       g_value_set_boolean (value, impl->use_preview_label);
5568       break;
5569
5570     case GTK_FILE_CHOOSER_PROP_EXTRA_WIDGET:
5571       g_value_set_object (value, impl->extra_widget);
5572       break;
5573
5574     case GTK_FILE_CHOOSER_PROP_SELECT_MULTIPLE:
5575       g_value_set_boolean (value, impl->select_multiple);
5576       break;
5577
5578     case GTK_FILE_CHOOSER_PROP_SHOW_HIDDEN:
5579       g_value_set_boolean (value, impl->show_hidden);
5580       break;
5581
5582     case GTK_FILE_CHOOSER_PROP_DO_OVERWRITE_CONFIRMATION:
5583       g_value_set_boolean (value, impl->do_overwrite_confirmation);
5584       break;
5585
5586     default:
5587       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5588       break;
5589     }
5590 }
5591
5592 /* Removes the settings signal handler.  It's safe to call multiple times */
5593 static void
5594 remove_settings_signal (GtkFileChooserDefault *impl,
5595                         GdkScreen             *screen)
5596 {
5597   if (impl->settings_signal_id)
5598     {
5599       GtkSettings *settings;
5600
5601       settings = gtk_settings_get_for_screen (screen);
5602       g_signal_handler_disconnect (settings,
5603                                    impl->settings_signal_id);
5604       impl->settings_signal_id = 0;
5605     }
5606 }
5607
5608 static void
5609 gtk_file_chooser_default_dispose (GObject *object)
5610 {
5611   GSList *l;
5612   GtkFileChooserDefault *impl = (GtkFileChooserDefault *) object;
5613
5614   if (impl->extra_widget)
5615     {
5616       g_object_unref (impl->extra_widget);
5617       impl->extra_widget = NULL;
5618     }
5619
5620   pending_select_files_free (impl);
5621
5622   /* cancel all pending operations */
5623   if (impl->pending_cancellables)
5624     {
5625       for (l = impl->pending_cancellables; l; l = l->next)
5626         {
5627           GCancellable *cancellable = G_CANCELLABLE (l->data);
5628           g_cancellable_cancel (cancellable);
5629         }
5630       g_slist_free (impl->pending_cancellables);
5631       impl->pending_cancellables = NULL;
5632     }
5633
5634   if (impl->reload_icon_cancellables)
5635     {
5636       for (l = impl->reload_icon_cancellables; l; l = l->next)
5637         {
5638           GCancellable *cancellable = G_CANCELLABLE (l->data);
5639           g_cancellable_cancel (cancellable);
5640         }
5641       g_slist_free (impl->reload_icon_cancellables);
5642       impl->reload_icon_cancellables = NULL;
5643     }
5644
5645   if (impl->loading_shortcuts)
5646     {
5647       for (l = impl->loading_shortcuts; l; l = l->next)
5648         {
5649           GCancellable *cancellable = G_CANCELLABLE (l->data);
5650           g_cancellable_cancel (cancellable);
5651         }
5652       g_slist_free (impl->loading_shortcuts);
5653       impl->loading_shortcuts = NULL;
5654     }
5655
5656   if (impl->file_list_drag_data_received_cancellable)
5657     {
5658       g_cancellable_cancel (impl->file_list_drag_data_received_cancellable);
5659       impl->file_list_drag_data_received_cancellable = NULL;
5660     }
5661
5662   if (impl->update_current_folder_cancellable)
5663     {
5664       g_cancellable_cancel (impl->update_current_folder_cancellable);
5665       impl->update_current_folder_cancellable = NULL;
5666     }
5667
5668   if (impl->show_and_select_files_cancellable)
5669     {
5670       g_cancellable_cancel (impl->show_and_select_files_cancellable);
5671       impl->show_and_select_files_cancellable = NULL;
5672     }
5673
5674   if (impl->should_respond_get_info_cancellable)
5675     {
5676       g_cancellable_cancel (impl->should_respond_get_info_cancellable);
5677       impl->should_respond_get_info_cancellable = NULL;
5678     }
5679
5680   if (impl->update_from_entry_cancellable)
5681     {
5682       g_cancellable_cancel (impl->update_from_entry_cancellable);
5683       impl->update_from_entry_cancellable = NULL;
5684     }
5685
5686   if (impl->shortcuts_activate_iter_cancellable)
5687     {
5688       g_cancellable_cancel (impl->shortcuts_activate_iter_cancellable);
5689       impl->shortcuts_activate_iter_cancellable = NULL;
5690     }
5691
5692   search_stop_searching (impl, TRUE);
5693   recent_stop_loading (impl);
5694
5695   remove_settings_signal (impl, gtk_widget_get_screen (GTK_WIDGET (impl)));
5696
5697   G_OBJECT_CLASS (_gtk_file_chooser_default_parent_class)->dispose (object);
5698 }
5699
5700 /* We override show-all since we have internal widgets that
5701  * shouldn't be shown when you call show_all(), like the filter
5702  * combo box.
5703  */
5704 static void
5705 gtk_file_chooser_default_show_all (GtkWidget *widget)
5706 {
5707   GtkFileChooserDefault *impl = (GtkFileChooserDefault *) widget;
5708
5709   gtk_widget_show (widget);
5710
5711   if (impl->extra_widget)
5712     gtk_widget_show_all (impl->extra_widget);
5713 }
5714
5715 /* Handler for GtkWindow::set-focus; this is where we save the last-focused
5716  * widget on our toplevel.  See gtk_file_chooser_default_hierarchy_changed()
5717  */
5718 static void
5719 toplevel_set_focus_cb (GtkWindow             *window,
5720                        GtkWidget             *focus,
5721                        GtkFileChooserDefault *impl)
5722 {
5723   impl->toplevel_last_focus_widget = gtk_window_get_focus (window);
5724 }
5725
5726 /* We monitor the focus widget on our toplevel to be able to know which widget
5727  * was last focused at the time our "should_respond" method gets called.
5728  */
5729 static void
5730 gtk_file_chooser_default_hierarchy_changed (GtkWidget *widget,
5731                                             GtkWidget *previous_toplevel)
5732 {
5733   GtkFileChooserDefault *impl;
5734   GtkWidget *toplevel;
5735
5736   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5737
5738   if (previous_toplevel)
5739     {
5740       g_assert (impl->toplevel_set_focus_id != 0);
5741       g_signal_handler_disconnect (previous_toplevel,
5742                                    impl->toplevel_set_focus_id);
5743       impl->toplevel_set_focus_id = 0;
5744       impl->toplevel_last_focus_widget = NULL;
5745     }
5746   else
5747     g_assert (impl->toplevel_set_focus_id == 0);
5748
5749   toplevel = gtk_widget_get_toplevel (widget);
5750   if (GTK_IS_WINDOW (toplevel))
5751     {
5752       impl->toplevel_set_focus_id = g_signal_connect (toplevel, "set-focus",
5753                                                       G_CALLBACK (toplevel_set_focus_cb), impl);
5754       impl->toplevel_last_focus_widget = gtk_window_get_focus (GTK_WINDOW (toplevel));
5755     }
5756 }
5757
5758 /* Changes the icons wherever it is needed */
5759 static void
5760 change_icon_theme (GtkFileChooserDefault *impl)
5761 {
5762   GtkSettings *settings;
5763   gint width, height;
5764
5765   profile_start ("start", NULL);
5766
5767   settings = gtk_settings_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
5768
5769   if (gtk_icon_size_lookup_for_settings (settings, GTK_ICON_SIZE_MENU, &width, &height))
5770     impl->icon_size = MAX (width, height);
5771   else
5772     impl->icon_size = FALLBACK_ICON_SIZE;
5773
5774   shortcuts_reload_icons (impl);
5775   gtk_widget_queue_resize (impl->browse_files_tree_view);
5776
5777   profile_end ("end", NULL);
5778 }
5779
5780 /* Callback used when a GtkSettings value changes */
5781 static void
5782 settings_notify_cb (GObject               *object,
5783                     GParamSpec            *pspec,
5784                     GtkFileChooserDefault *impl)
5785 {
5786   const char *name;
5787
5788   profile_start ("start", NULL);
5789
5790   name = g_param_spec_get_name (pspec);
5791
5792   if (strcmp (name, "gtk-icon-theme-name") == 0 ||
5793       strcmp (name, "gtk-icon-sizes") == 0)
5794     change_icon_theme (impl);
5795
5796   profile_end ("end", NULL);
5797 }
5798
5799 /* Installs a signal handler for GtkSettings so that we can monitor changes in
5800  * the icon theme.
5801  */
5802 static void
5803 check_icon_theme (GtkFileChooserDefault *impl)
5804 {
5805   GtkSettings *settings;
5806
5807   profile_start ("start", NULL);
5808
5809   if (impl->settings_signal_id)
5810     {
5811       profile_end ("end", NULL);
5812       return;
5813     }
5814
5815   if (gtk_widget_has_screen (GTK_WIDGET (impl)))
5816     {
5817       settings = gtk_settings_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
5818       impl->settings_signal_id = g_signal_connect (settings, "notify",
5819                                                    G_CALLBACK (settings_notify_cb), impl);
5820
5821       change_icon_theme (impl);
5822     }
5823
5824   profile_end ("end", NULL);
5825 }
5826
5827 static void
5828 gtk_file_chooser_default_style_set (GtkWidget *widget,
5829                                     GtkStyle  *previous_style)
5830 {
5831   GtkFileChooserDefault *impl;
5832
5833   profile_start ("start", NULL);
5834
5835   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5836
5837   profile_msg ("    parent class style_set start", NULL);
5838   if (GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->style_set)
5839     GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->style_set (widget, previous_style);
5840   profile_msg ("    parent class style_set end", NULL);
5841
5842   if (gtk_widget_has_screen (GTK_WIDGET (impl)))
5843     change_icon_theme (impl);
5844
5845   profile_msg ("    emit default-size-changed start", NULL);
5846   g_signal_emit_by_name (widget, "default-size-changed");
5847   profile_msg ("    emit default-size-changed end", NULL);
5848
5849   profile_end ("end", NULL);
5850 }
5851
5852 static void
5853 gtk_file_chooser_default_screen_changed (GtkWidget *widget,
5854                                          GdkScreen *previous_screen)
5855 {
5856   GtkFileChooserDefault *impl;
5857
5858   profile_start ("start", NULL);
5859
5860   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5861
5862   if (GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->screen_changed)
5863     GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->screen_changed (widget, previous_screen);
5864
5865   remove_settings_signal (impl, previous_screen);
5866   check_icon_theme (impl);
5867
5868   g_signal_emit_by_name (widget, "default-size-changed");
5869
5870   profile_end ("end", NULL);
5871 }
5872
5873 static void
5874 gtk_file_chooser_default_size_allocate (GtkWidget     *widget,
5875                                         GtkAllocation *allocation)
5876 {
5877   GtkFileChooserDefault *impl;
5878
5879   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5880
5881   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->size_allocate (widget, allocation);
5882
5883   impl->default_width = allocation->width;
5884   impl->default_height = allocation->height;
5885
5886   if (impl->preview_widget_active &&
5887       impl->preview_widget &&
5888       GTK_WIDGET_DRAWABLE (impl->preview_widget))
5889     impl->default_width -= impl->preview_widget->allocation.width + PREVIEW_HBOX_SPACING;
5890
5891   if (impl->extra_widget &&
5892       GTK_WIDGET_DRAWABLE (impl->extra_widget))
5893     impl->default_height -= GTK_BOX (widget)->spacing + impl->extra_widget->allocation.height;
5894 }
5895
5896 static gboolean
5897 get_is_file_filtered (GtkFileChooserDefault *impl,
5898                       GFile                 *file,
5899                       GFileInfo             *file_info)
5900 {
5901   GtkFileFilterInfo filter_info;
5902   GtkFileFilterFlags needed;
5903   gboolean result;
5904
5905   if (!impl->current_filter)
5906     return FALSE;
5907
5908   filter_info.contains = GTK_FILE_FILTER_DISPLAY_NAME | GTK_FILE_FILTER_MIME_TYPE;
5909
5910   needed = gtk_file_filter_get_needed (impl->current_filter);
5911
5912   filter_info.display_name = g_file_info_get_display_name (file_info);
5913   filter_info.mime_type = g_file_info_get_content_type (file_info);
5914
5915   if (needed & GTK_FILE_FILTER_FILENAME)
5916     {
5917       filter_info.filename = g_file_get_path (file);
5918       if (filter_info.filename)
5919         filter_info.contains |= GTK_FILE_FILTER_FILENAME;
5920     }
5921   else
5922     filter_info.filename = NULL;
5923
5924   if (needed & GTK_FILE_FILTER_URI)
5925     {
5926       filter_info.uri = g_file_get_uri (file);
5927       if (filter_info.uri)
5928         filter_info.contains |= GTK_FILE_FILTER_URI;
5929     }
5930   else
5931     filter_info.uri = NULL;
5932
5933   result = gtk_file_filter_filter (impl->current_filter, &filter_info);
5934
5935   if (filter_info.filename)
5936     g_free ((gchar *)filter_info.filename);
5937   if (filter_info.uri)
5938     g_free ((gchar *)filter_info.uri);
5939
5940   return !result;
5941 }
5942
5943 static void
5944 settings_load (GtkFileChooserDefault *impl)
5945 {
5946   GtkFileChooserSettings *settings;
5947   LocationMode location_mode;
5948   gboolean show_hidden;
5949   gboolean expand_folders;
5950
5951   settings = _gtk_file_chooser_settings_new ();
5952
5953   location_mode = _gtk_file_chooser_settings_get_location_mode (settings);
5954   show_hidden = _gtk_file_chooser_settings_get_show_hidden (settings);
5955   expand_folders = _gtk_file_chooser_settings_get_expand_folders (settings);
5956
5957   g_object_unref (settings);
5958
5959   location_mode_set (impl, location_mode, TRUE);
5960   gtk_file_chooser_set_show_hidden (GTK_FILE_CHOOSER (impl), show_hidden);
5961   impl->expand_folders = expand_folders;
5962   if (impl->save_expander)
5963     gtk_expander_set_expanded (GTK_EXPANDER (impl->save_expander), expand_folders);
5964 }
5965
5966 static void
5967 settings_save (GtkFileChooserDefault *impl)
5968 {
5969   GtkFileChooserSettings *settings;
5970
5971   settings = _gtk_file_chooser_settings_new ();
5972
5973   _gtk_file_chooser_settings_set_location_mode (settings, impl->location_mode);
5974   _gtk_file_chooser_settings_set_show_hidden (settings, gtk_file_chooser_get_show_hidden (GTK_FILE_CHOOSER (impl)));
5975   _gtk_file_chooser_settings_set_expand_folders (settings, impl->expand_folders);
5976
5977   /* NULL GError */
5978   _gtk_file_chooser_settings_save (settings, NULL);
5979
5980   g_object_unref (settings);
5981 }
5982
5983 /* GtkWidget::map method */
5984 static void
5985 gtk_file_chooser_default_map (GtkWidget *widget)
5986 {
5987   GtkFileChooserDefault *impl;
5988   char *current_working_dir;
5989
5990   profile_start ("start", NULL);
5991
5992   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5993
5994   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->map (widget);
5995
5996   if (impl->operation_mode == OPERATION_MODE_BROWSE)
5997     {
5998       switch (impl->reload_state)
5999         {
6000         case RELOAD_EMPTY:
6001           /* The user didn't explicitly give us a folder to
6002            * display, so we'll use the cwd
6003            */
6004           current_working_dir = g_get_current_dir ();
6005           gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (impl),
6006                                                current_working_dir);
6007           g_free (current_working_dir);
6008           break;
6009         
6010         case RELOAD_HAS_FOLDER:
6011           /* Nothing; we are already loading or loaded, so we
6012            * don't need to reload
6013            */
6014           break;
6015
6016         case RELOAD_WAS_UNMAPPED:
6017           /* Just reload the current folder; else continue
6018            * the pending load.
6019            */
6020           if (impl->current_folder)
6021             {
6022               pending_select_files_store_selection (impl);
6023               change_folder_and_display_error (impl, impl->current_folder, FALSE);
6024             }
6025           break;
6026
6027         default:
6028           g_assert_not_reached ();
6029       }
6030     }
6031
6032   volumes_bookmarks_changed_cb (impl->file_system, impl);
6033
6034   settings_load (impl);
6035
6036   profile_end ("end", NULL);
6037 }
6038
6039 /* GtkWidget::unmap method */
6040 static void
6041 gtk_file_chooser_default_unmap (GtkWidget *widget)
6042 {
6043   GtkFileChooserDefault *impl;
6044
6045   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
6046
6047   settings_save (impl);
6048
6049   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->unmap (widget);
6050
6051   impl->reload_state = RELOAD_WAS_UNMAPPED;
6052 }
6053
6054 static gboolean
6055 list_model_filter_func (GtkFileSystemModel *model,
6056                         GFile              *file,
6057                         GFileInfo          *file_info,
6058                         gpointer            user_data)
6059 {
6060   GtkFileChooserDefault *impl = user_data;
6061
6062   if (!impl->current_filter)
6063     return TRUE;
6064
6065   if (g_file_info_get_file_type (file_info) == G_FILE_TYPE_DIRECTORY)
6066     return TRUE;
6067
6068   return !get_is_file_filtered (impl, file, file_info);
6069 }
6070
6071 static void
6072 install_list_model_filter (GtkFileChooserDefault *impl)
6073 {
6074   GtkFileSystemModelFilter filter;
6075   gpointer data;
6076
6077   g_assert (impl->browse_files_model != NULL);
6078
6079   if (impl->current_filter)
6080     {
6081       filter = list_model_filter_func;
6082       data   = impl;
6083     }
6084   else
6085     {
6086       filter = NULL;
6087       data   = NULL;
6088     }
6089   
6090   _gtk_file_system_model_set_filter (impl->browse_files_model,
6091                                      filter,
6092                                      data);
6093 }
6094
6095 #define COMPARE_DIRECTORIES                                                                                    \
6096   GtkFileChooserDefault *impl = user_data;                                                                     \
6097   GFileInfo *info_a = _gtk_file_system_model_get_info (impl->browse_files_model, a);                           \
6098   GFileInfo *info_b = _gtk_file_system_model_get_info (impl->browse_files_model, b);                           \
6099   gboolean dir_a, dir_b;                                                                                       \
6100                                                                                                                \
6101   if (info_a)                                                                                                  \
6102     dir_a = (g_file_info_get_file_type (info_a) == G_FILE_TYPE_DIRECTORY);                                     \
6103   else                                                                                                         \
6104     return impl->list_sort_ascending ? -1 : 1;                                                                 \
6105                                                                                                                \
6106   if (info_b)                                                                                                  \
6107     dir_b = (g_file_info_get_file_type (info_b) == G_FILE_TYPE_DIRECTORY);                                     \
6108   else                                                                                                         \
6109     return impl->list_sort_ascending ? 1 : -1;                                                                 \
6110                                                                                                                \
6111   if (dir_a != dir_b)                                                                                          \
6112     return impl->list_sort_ascending ? (dir_a ? -1 : 1) : (dir_a ? 1 : -1) /* Directories *always* go first */
6113
6114 /* Sort callback for the filename column */
6115 static gint
6116 name_sort_func (GtkTreeModel *model,
6117                 GtkTreeIter  *a,
6118                 GtkTreeIter  *b,
6119                 gpointer      user_data)
6120 {
6121   COMPARE_DIRECTORIES;
6122   else
6123     {
6124       gchar *key_a, *key_b;
6125       gint result;
6126
6127       key_a = g_utf8_collate_key_for_filename (g_file_info_get_display_name (info_a), -1);
6128       key_b = g_utf8_collate_key_for_filename (g_file_info_get_display_name (info_b), -1);
6129       result = strcmp (key_a, key_b);
6130
6131       g_free (key_a);
6132       g_free (key_b);
6133
6134       return result;
6135     }
6136 }
6137
6138 /* Sort callback for the size column */
6139 static gint
6140 size_sort_func (GtkTreeModel *model,
6141                 GtkTreeIter  *a,
6142                 GtkTreeIter  *b,
6143                 gpointer      user_data)
6144 {
6145   COMPARE_DIRECTORIES;
6146   else
6147     {
6148       goffset size_a = g_file_info_get_size (info_a);
6149       goffset size_b = g_file_info_get_size (info_b);
6150
6151       return size_a > size_b ? -1 : (size_a == size_b ? 0 : 1);
6152     }
6153 }
6154
6155 /* Sort callback for the mtime column */
6156 static gint
6157 mtime_sort_func (GtkTreeModel *model,
6158                  GtkTreeIter  *a,
6159                  GtkTreeIter  *b,
6160                  gpointer      user_data)
6161 {
6162   COMPARE_DIRECTORIES;
6163   else
6164     {
6165       GTimeVal ta, tb;
6166
6167       g_file_info_get_modification_time (info_a, &ta);
6168       g_file_info_get_modification_time (info_b, &tb);
6169
6170       return ta.tv_sec > tb.tv_sec ? -1 : (ta.tv_sec == tb.tv_sec ? 0 : 1);
6171     }
6172 }
6173
6174 /* Callback used when the sort column changes.  We cache the sort order for use
6175  * in name_sort_func().
6176  */
6177 static void
6178 list_sort_column_changed_cb (GtkTreeSortable       *sortable,
6179                              GtkFileChooserDefault *impl)
6180 {
6181   GtkSortType sort_type;
6182
6183   if (gtk_tree_sortable_get_sort_column_id (sortable, NULL, &sort_type))
6184     impl->list_sort_ascending = (sort_type == GTK_SORT_ASCENDING);
6185 }
6186
6187 static void
6188 set_busy_cursor (GtkFileChooserDefault *impl,
6189                  gboolean               busy)
6190 {
6191   GtkWindow *toplevel;
6192   GdkDisplay *display;
6193   GdkCursor *cursor;
6194
6195   toplevel = get_toplevel (GTK_WIDGET (impl));
6196   if (!toplevel || !GTK_WIDGET_REALIZED (toplevel))
6197     return;
6198
6199   display = gtk_widget_get_display (GTK_WIDGET (toplevel));
6200
6201   if (busy)
6202     cursor = gdk_cursor_new_for_display (display, GDK_WATCH);
6203   else
6204     cursor = NULL;
6205
6206   gdk_window_set_cursor (GTK_WIDGET (toplevel)->window, cursor);
6207   gdk_display_flush (display);
6208
6209   if (cursor)
6210     gdk_cursor_unref (cursor);
6211 }
6212
6213 /* Creates a sort model to wrap the file system model and sets it on the tree view */
6214 static void
6215 load_set_model (GtkFileChooserDefault *impl)
6216 {
6217   profile_start ("start", NULL);
6218
6219   g_assert (impl->browse_files_model != NULL);
6220   g_assert (impl->sort_model == NULL);
6221
6222   profile_msg ("    gtk_tree_model_sort_new_with_model start", NULL);
6223   impl->sort_model = (GtkTreeModelSort *)gtk_tree_model_sort_new_with_model (GTK_TREE_MODEL (impl->browse_files_model));
6224   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->sort_model), FILE_LIST_COL_NAME, name_sort_func, impl, NULL);
6225   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->sort_model), FILE_LIST_COL_SIZE, size_sort_func, impl, NULL);
6226   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->sort_model), FILE_LIST_COL_MTIME, mtime_sort_func, impl, NULL);
6227   gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (impl->sort_model), NULL, NULL, NULL);
6228   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (impl->sort_model), FILE_LIST_COL_NAME, GTK_SORT_ASCENDING);
6229   impl->list_sort_ascending = TRUE;
6230   profile_msg ("    gtk_tree_model_sort_new_with_model end", NULL);
6231
6232   g_signal_connect (impl->sort_model, "sort-column-changed",
6233                     G_CALLBACK (list_sort_column_changed_cb), impl);
6234
6235   profile_msg ("    gtk_tree_view_set_model start", NULL);
6236   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
6237                            GTK_TREE_MODEL (impl->sort_model));
6238   gtk_tree_view_columns_autosize (GTK_TREE_VIEW (impl->browse_files_tree_view));
6239   gtk_tree_view_set_search_column (GTK_TREE_VIEW (impl->browse_files_tree_view),
6240                                    GTK_FILE_SYSTEM_MODEL_DISPLAY_NAME);
6241   profile_msg ("    gtk_tree_view_set_model end", NULL);
6242
6243   profile_end ("end", NULL);
6244 }
6245
6246 /* Timeout callback used when the loading timer expires */
6247 static gboolean
6248 load_timeout_cb (gpointer data)
6249 {
6250   GtkFileChooserDefault *impl;
6251
6252   profile_start ("start", NULL);
6253
6254   impl = GTK_FILE_CHOOSER_DEFAULT (data);
6255   g_assert (impl->load_state == LOAD_PRELOAD);
6256   g_assert (impl->load_timeout_id != 0);
6257   g_assert (impl->browse_files_model != NULL);
6258
6259   impl->load_timeout_id = 0;
6260   impl->load_state = LOAD_LOADING;
6261
6262   load_set_model (impl);
6263
6264   profile_end ("end", NULL);
6265
6266   return FALSE;
6267 }
6268
6269 /* Sets up a new load timer for the model and switches to the LOAD_PRELOAD state */
6270 static void
6271 load_setup_timer (GtkFileChooserDefault *impl)
6272 {
6273   g_assert (impl->load_timeout_id == 0);
6274   g_assert (impl->load_state != LOAD_PRELOAD);
6275
6276   impl->load_timeout_id = gdk_threads_add_timeout (MAX_LOADING_TIME, load_timeout_cb, impl);
6277   impl->load_state = LOAD_PRELOAD;
6278 }
6279
6280 /* Removes the load timeout and switches to the LOAD_FINISHED state */
6281 static void
6282 load_remove_timer (GtkFileChooserDefault *impl)
6283 {
6284   if (impl->load_timeout_id != 0)
6285     {
6286       g_assert (impl->load_state == LOAD_PRELOAD);
6287
6288       g_source_remove (impl->load_timeout_id);
6289       impl->load_timeout_id = 0;
6290       impl->load_state = LOAD_EMPTY;
6291     }
6292   else
6293     g_assert (impl->load_state == LOAD_EMPTY ||
6294               impl->load_state == LOAD_LOADING ||
6295               impl->load_state == LOAD_FINISHED);
6296 }
6297
6298 /* Selects the first row in the file list */
6299 static void
6300 browse_files_select_first_row (GtkFileChooserDefault *impl)
6301 {
6302   GtkTreePath *path;
6303   GtkTreeIter dummy_iter;
6304   GtkTreeModel *tree_model;
6305
6306   if (!impl->sort_model)
6307     return;
6308
6309   path = gtk_tree_path_new_from_indices (0, -1);
6310   tree_model = gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view));
6311
6312   /* If the list is empty, do nothing. */
6313   if (gtk_tree_model_get_iter (tree_model, &dummy_iter, path))
6314       gtk_tree_view_set_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view), path, NULL, FALSE);
6315
6316   gtk_tree_path_free (path);
6317 }
6318
6319 struct center_selected_row_closure {
6320   GtkFileChooserDefault *impl;
6321   gboolean already_centered;
6322 };
6323
6324 /* Callback used from gtk_tree_selection_selected_foreach(); centers the
6325  * selected row in the tree view.
6326  */
6327 static void
6328 center_selected_row_foreach_cb (GtkTreeModel      *model,
6329                                 GtkTreePath       *path,
6330                                 GtkTreeIter       *iter,
6331                                 gpointer           data)
6332 {
6333   struct center_selected_row_closure *closure;
6334
6335   closure = data;
6336   if (closure->already_centered)
6337     return;
6338
6339   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (closure->impl->browse_files_tree_view), path, NULL, TRUE, 0.5, 0.0);
6340   closure->already_centered = TRUE;
6341 }
6342
6343 /* Centers the selected row in the tree view */
6344 static void
6345 browse_files_center_selected_row (GtkFileChooserDefault *impl)
6346 {
6347   struct center_selected_row_closure closure;
6348   GtkTreeSelection *selection;
6349
6350   closure.impl = impl;
6351   closure.already_centered = FALSE;
6352
6353   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6354   gtk_tree_selection_selected_foreach (selection, center_selected_row_foreach_cb, &closure);
6355 }
6356
6357 struct ShowAndSelectPathsData
6358 {
6359   GtkFileChooserDefault *impl;
6360   GSList *files;
6361 };
6362
6363 static void
6364 show_and_select_files_finished_loading (GtkFolder *folder,
6365                                         gpointer   user_data)
6366 {
6367   gboolean have_hidden;
6368   gboolean have_filtered;
6369   GSList *l;
6370   struct ShowAndSelectPathsData *data = user_data;
6371
6372   have_hidden = FALSE;
6373   have_filtered = FALSE;
6374
6375   for (l = data->files; l; l = l->next)
6376     {
6377       GFile *file;
6378       GFileInfo *info;
6379
6380       file = l->data;
6381
6382       info = _gtk_folder_get_info (folder, file);
6383       if (info)
6384         {
6385           if (!have_hidden)
6386             have_hidden = g_file_info_get_is_hidden (info);
6387
6388           if (!have_filtered)
6389             have_filtered = (g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY) &&
6390                              get_is_file_filtered (data->impl, file, info);
6391
6392           g_object_unref (info);
6393
6394           if (have_hidden && have_filtered)
6395             break; /* we now have all the information we need */
6396         }
6397     }
6398
6399   g_signal_handlers_disconnect_by_func (folder,
6400                                         show_and_select_files_finished_loading,
6401                                         user_data);
6402
6403   if (have_hidden)
6404     g_object_set (data->impl, "show-hidden", TRUE, NULL);
6405
6406   if (have_filtered)
6407     set_current_filter (data->impl, NULL);
6408
6409   for (l = data->files; l; l = l->next)
6410     {
6411       GFile *file;
6412
6413       file = l->data;
6414       _gtk_file_system_model_path_do (data->impl->browse_files_model, file,
6415                                       select_func, data->impl);
6416     }
6417
6418   browse_files_center_selected_row (data->impl);
6419
6420   g_object_unref (data->impl);
6421   g_slist_foreach (data->files, (GFunc) g_object_unref, NULL);
6422   g_slist_free (data->files);
6423   g_free (data);
6424 }
6425
6426 static void
6427 show_and_select_files_get_folder_cb (GCancellable *cancellable,
6428                                      GtkFolder    *folder,
6429                                      const GError *error,
6430                                      gpointer      user_data)
6431 {
6432   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
6433   struct ShowAndSelectPathsData *data = user_data;
6434
6435   if (data->impl->show_and_select_files_cancellable != cancellable)
6436     goto out;
6437
6438   data->impl->show_and_select_files_cancellable = NULL;
6439
6440   if (cancelled || error)
6441     goto out;
6442
6443   g_object_unref (cancellable);
6444
6445   if (_gtk_folder_is_finished_loading (folder))
6446     show_and_select_files_finished_loading (folder, user_data);
6447   else
6448     g_signal_connect (folder, "finished-loading",
6449                       G_CALLBACK (show_and_select_files_finished_loading),
6450                       user_data);
6451
6452   return;
6453
6454 out:
6455   g_object_unref (data->impl);
6456   g_slist_foreach (data->files, (GFunc) g_object_unref, NULL);
6457   g_slist_free (data->files);
6458   g_free (data);
6459
6460   g_object_unref (cancellable);
6461 }
6462
6463 static gboolean
6464 show_and_select_files (GtkFileChooserDefault *impl,
6465                        GFile                 *parent_file,
6466                        GSList                *files,
6467                        GError                **error)
6468 {
6469   struct ShowAndSelectPathsData *info;
6470
6471   profile_start ("start", NULL);
6472
6473   if (!files)
6474     {
6475       profile_end ("end", NULL);
6476       return TRUE;
6477     }
6478
6479   info = g_new (struct ShowAndSelectPathsData, 1);
6480   info->impl = g_object_ref (impl);
6481   info->files = g_slist_copy (files);
6482   g_slist_foreach (info->files, (GFunc) g_object_ref, NULL);
6483
6484   if (impl->show_and_select_files_cancellable)
6485     g_cancellable_cancel (impl->show_and_select_files_cancellable);
6486
6487   impl->show_and_select_files_cancellable =
6488     _gtk_file_system_get_folder (impl->file_system, parent_file,
6489                                  "standard::is-hidden,standard::type,standard::name",
6490                                  show_and_select_files_get_folder_cb, info);
6491
6492   profile_end ("end", NULL);
6493   return TRUE;
6494 }
6495
6496 /* Processes the pending operation when a folder is finished loading */
6497 static void
6498 pending_select_files_process (GtkFileChooserDefault *impl)
6499 {
6500   g_assert (impl->load_state == LOAD_FINISHED);
6501   g_assert (impl->browse_files_model != NULL);
6502   g_assert (impl->sort_model != NULL);
6503
6504   if (impl->pending_select_files)
6505     {
6506       /* NULL GError */
6507       show_and_select_files (impl, impl->current_folder, impl->pending_select_files, NULL);
6508       pending_select_files_free (impl);
6509       browse_files_center_selected_row (impl);
6510     }
6511   else
6512     {
6513       /* We only select the first row if the chooser is actually mapped ---
6514        * selecting the first row is to help the user when he is interacting with
6515        * the chooser, but sometimes a chooser works not on behalf of the user,
6516        * but rather on behalf of something else like GtkFileChooserButton.  In
6517        * that case, the chooser's selection should be what the caller expects,
6518        * as the user can't see that something else got selected.  See bug #165264.
6519        */
6520       if (GTK_WIDGET_MAPPED (impl) && impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
6521         browse_files_select_first_row (impl);
6522     }
6523
6524   g_assert (impl->pending_select_files == NULL);
6525 }
6526
6527 /* Callback used when the file system model finishes loading */
6528 static void
6529 browse_files_model_finished_loading_cb (GtkFileSystemModel    *model,
6530                                         GtkFileChooserDefault *impl)
6531 {
6532   profile_start ("start", NULL);
6533
6534   if (impl->load_state == LOAD_PRELOAD)
6535     {
6536       load_remove_timer (impl);
6537       load_set_model (impl);
6538     }
6539   else if (impl->load_state == LOAD_LOADING)
6540     {
6541       /* Nothing */
6542     }
6543   else
6544     {
6545       /* We can't g_assert_not_reached(), as something other than us may have
6546        *  initiated a folder reload.  See #165556.
6547        */
6548       profile_end ("end", NULL);
6549       return;
6550     }
6551
6552   g_assert (impl->load_timeout_id == 0);
6553
6554   impl->load_state = LOAD_FINISHED;
6555
6556   pending_select_files_process (impl);
6557   set_busy_cursor (impl, FALSE);
6558 #ifdef PROFILE_FILE_CHOOSER
6559   access ("MARK: *** FINISHED LOADING", F_OK);
6560 #endif
6561
6562   profile_end ("end", NULL);
6563 }
6564
6565 static void
6566 stop_loading_and_clear_list_model (GtkFileChooserDefault *impl)
6567 {
6568   load_remove_timer (impl); /* This changes the state to LOAD_EMPTY */
6569   
6570   if (impl->browse_files_model)
6571     {
6572       g_object_unref (impl->browse_files_model);
6573       impl->browse_files_model = NULL;
6574     }
6575
6576   if (impl->sort_model)
6577     {
6578       g_object_unref (impl->sort_model);
6579       impl->sort_model = NULL;
6580     }
6581   
6582   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
6583 }
6584
6585 /* Gets rid of the old list model and creates a new one for the current folder */
6586 static gboolean
6587 set_list_model (GtkFileChooserDefault *impl,
6588                 GError               **error)
6589 {
6590   g_assert (impl->current_folder != NULL);
6591
6592   profile_start ("start", NULL);
6593
6594   stop_loading_and_clear_list_model (impl);
6595
6596   set_busy_cursor (impl, TRUE);
6597   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
6598
6599   impl->browse_files_model = _gtk_file_system_model_new (impl->file_system,
6600                                                          impl->current_folder, 0,
6601                                                          "standard,time,thumbnail::*",
6602                                                          error);
6603   if (!impl->browse_files_model)
6604     {
6605       set_busy_cursor (impl, FALSE);
6606       profile_end ("end", NULL);
6607       return FALSE;
6608     }
6609
6610   load_setup_timer (impl); /* This changes the state to LOAD_PRELOAD */
6611
6612   g_signal_connect (impl->browse_files_model, "finished-loading",
6613                     G_CALLBACK (browse_files_model_finished_loading_cb), impl);
6614
6615   _gtk_file_system_model_set_show_hidden (impl->browse_files_model, impl->show_hidden);
6616
6617   install_list_model_filter (impl);
6618
6619   profile_end ("end", NULL);
6620
6621   return TRUE;
6622 }
6623
6624 struct update_chooser_entry_selected_foreach_closure {
6625   int num_selected;
6626   GtkTreeIter first_selected_iter;
6627 };
6628
6629 static gint
6630 compare_utf8_filenames (const gchar *a,
6631                         const gchar *b)
6632 {
6633   gchar *a_folded, *b_folded;
6634   gint retval;
6635
6636   a_folded = g_utf8_strdown (a, -1);
6637   b_folded = g_utf8_strdown (b, -1);
6638
6639   retval = strcmp (a_folded, b_folded);
6640
6641   g_free (a_folded);
6642   g_free (b_folded);
6643
6644   return retval;
6645 }
6646
6647 static void
6648 update_chooser_entry_selected_foreach (GtkTreeModel *model,
6649                                        GtkTreePath *path,
6650                                        GtkTreeIter *iter,
6651                                        gpointer data)
6652 {
6653   struct update_chooser_entry_selected_foreach_closure *closure;
6654
6655   closure = data;
6656   closure->num_selected++;
6657
6658   if (closure->num_selected == 1)
6659     closure->first_selected_iter = *iter;
6660 }
6661
6662 static void
6663 update_chooser_entry (GtkFileChooserDefault *impl)
6664 {
6665   GtkTreeSelection *selection;
6666   struct update_chooser_entry_selected_foreach_closure closure;
6667   const char *file_part;
6668
6669   /* no need to update the file chooser's entry if there's no entry */
6670   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
6671       impl->operation_mode == OPERATION_MODE_RECENT ||
6672       !impl->location_entry)
6673     return;
6674
6675   if (!(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
6676         || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
6677         || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
6678              || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
6679             && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)))
6680     return;
6681
6682   g_assert (impl->location_entry != NULL);
6683
6684   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6685   closure.num_selected = 0;
6686   gtk_tree_selection_selected_foreach (selection, update_chooser_entry_selected_foreach, &closure);
6687
6688   file_part = NULL;
6689
6690   if (closure.num_selected == 0)
6691     {
6692       goto maybe_clear_entry;
6693     }
6694   else if (closure.num_selected == 1)
6695     {
6696       GtkTreeIter child_iter;
6697       
6698       if (impl->operation_mode == OPERATION_MODE_BROWSE)
6699         {
6700           GFileInfo *info;
6701           gboolean change_entry;
6702
6703           gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
6704                                                           &child_iter,
6705                                                           &closure.first_selected_iter);
6706
6707           info = _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
6708
6709           /* If the cursor moved to the row of the newly created folder, 
6710            * retrieving info will return NULL.
6711            */
6712           if (!info)
6713             return;
6714
6715           g_free (impl->browse_files_last_selected_name);
6716           impl->browse_files_last_selected_name =
6717             g_strdup (g_file_info_get_display_name (info));
6718
6719           if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
6720               impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
6721               impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
6722             {
6723               /* We don't want the name to change when clicking on a folder... */
6724               change_entry = (g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY);
6725             }
6726           else
6727             change_entry = TRUE; /* ... unless we are in SELECT_FOLDER mode */
6728
6729           if (change_entry)
6730             {
6731               _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->browse_files_last_selected_name);
6732
6733               if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
6734                 _gtk_file_chooser_entry_select_filename (GTK_FILE_CHOOSER_ENTRY (impl->location_entry));
6735             }
6736
6737           return;
6738         }
6739     }
6740   else
6741     {
6742       g_assert (!(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
6743                   impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER));
6744
6745       /* Multiple selection, so just clear the entry. */
6746
6747       g_free (impl->browse_files_last_selected_name);
6748       impl->browse_files_last_selected_name = NULL;
6749
6750       _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
6751       return;
6752     }
6753
6754  maybe_clear_entry:
6755
6756   if ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
6757       && impl->browse_files_last_selected_name)
6758     {
6759       const char *entry_text;
6760       int len;
6761       gboolean clear_entry;
6762
6763       entry_text = gtk_entry_get_text (GTK_ENTRY (impl->location_entry));
6764       len = strlen (entry_text);
6765       if (len != 0)
6766         {
6767           /* The file chooser entry may have appended a "/" to its text.  So
6768            * take it out, and compare the result to the old selection.
6769            */
6770           if (entry_text[len - 1] == G_DIR_SEPARATOR)
6771             {
6772               char *tmp;
6773
6774               tmp = g_strndup (entry_text, len - 1);
6775               clear_entry = (compare_utf8_filenames (impl->browse_files_last_selected_name, tmp) == 0);
6776               g_free (tmp);
6777             }
6778           else
6779             clear_entry = (compare_utf8_filenames (impl->browse_files_last_selected_name, entry_text) == 0);
6780         }
6781       else
6782         clear_entry = FALSE;
6783
6784       if (clear_entry)
6785         _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
6786     }
6787 }
6788
6789 static gboolean
6790 gtk_file_chooser_default_set_current_folder (GtkFileChooser  *chooser,
6791                                              GFile           *file,
6792                                              GError         **error)
6793 {
6794   return gtk_file_chooser_default_update_current_folder (chooser, file, FALSE, FALSE, error);
6795 }
6796
6797
6798 struct UpdateCurrentFolderData
6799 {
6800   GtkFileChooserDefault *impl;
6801   GFile *file;
6802   gboolean keep_trail;
6803   gboolean clear_entry;
6804   GFile *original_file;
6805   GError *original_error;
6806 };
6807
6808 static void
6809 update_current_folder_get_info_cb (GCancellable *cancellable,
6810                                    GFileInfo    *info,
6811                                    const GError *error,
6812                                    gpointer      user_data)
6813 {
6814   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
6815   struct UpdateCurrentFolderData *data = user_data;
6816   GtkFileChooserDefault *impl = data->impl;
6817
6818   if (cancellable != impl->update_current_folder_cancellable)
6819     goto out;
6820
6821   impl->update_current_folder_cancellable = NULL;
6822   impl->reload_state = RELOAD_EMPTY;
6823
6824   set_busy_cursor (impl, FALSE);
6825
6826   if (cancelled)
6827     goto out;
6828
6829   if (error)
6830     {
6831       GFile *parent_file;
6832
6833       if (!data->original_file)
6834         {
6835           data->original_file = g_object_ref (data->file);
6836           data->original_error = g_error_copy (error);
6837         }
6838
6839       parent_file = g_file_get_parent (data->file);
6840
6841       /* get parent path and try to change the folder to that */
6842       if (parent_file)
6843         {
6844           g_object_unref (data->file);
6845           data->file = parent_file;
6846
6847           g_object_unref (cancellable);
6848
6849           /* restart the update current folder operation */
6850           impl->reload_state = RELOAD_HAS_FOLDER;
6851
6852           impl->update_current_folder_cancellable =
6853             _gtk_file_system_get_info (impl->file_system, data->file,
6854                                        "standard::type",
6855                                        update_current_folder_get_info_cb,
6856                                        data);
6857
6858           set_busy_cursor (impl, TRUE);
6859
6860           return;
6861         }
6862       else
6863         {
6864           /* error and bail out */
6865           error_changing_folder_dialog (impl, data->original_file, data->original_error);
6866           g_object_unref (data->original_file);
6867
6868           goto out;
6869         }
6870     }
6871
6872   if (data->original_file)
6873     {
6874       error_changing_folder_dialog (impl, data->original_file, data->original_error);
6875
6876       g_object_unref (data->original_file);
6877     }
6878
6879   if (g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY)
6880     goto out;
6881
6882   if (!_gtk_path_bar_set_file (GTK_PATH_BAR (impl->browse_path_bar), data->file, data->keep_trail, NULL))
6883     goto out;
6884
6885   if (impl->current_folder != data->file)
6886     {
6887       if (impl->current_folder)
6888         g_object_unref (impl->current_folder);
6889
6890       impl->current_folder = g_object_ref (data->file);
6891
6892       impl->reload_state = RELOAD_HAS_FOLDER;
6893     }
6894
6895   /* Update the widgets that may trigger a folder change themselves.  */
6896
6897   if (!impl->changing_folder)
6898     {
6899       impl->changing_folder = TRUE;
6900
6901       shortcuts_update_current_folder (impl);
6902
6903       impl->changing_folder = FALSE;
6904     }
6905
6906   /* Set the folder on the save entry */
6907
6908   if (impl->location_entry)
6909     {
6910       _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry),
6911                                                impl->current_folder);
6912
6913       if (data->clear_entry)
6914         _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
6915     }
6916
6917   /* Create a new list model.  This is slightly evil; we store the result value
6918    * but perform more actions rather than returning immediately even if it
6919    * generates an error.
6920    */
6921   set_list_model (impl, NULL);
6922
6923   /* Refresh controls */
6924
6925   shortcuts_find_current_folder (impl);
6926
6927   g_signal_emit_by_name (impl, "current-folder-changed", 0);
6928
6929   check_preview_change (impl);
6930   bookmarks_check_add_sensitivity (impl);
6931
6932   g_signal_emit_by_name (impl, "selection-changed", 0);
6933
6934 out:
6935   g_object_unref (data->file);
6936   g_free (data);
6937
6938   g_object_unref (cancellable);
6939 }
6940
6941 static gboolean
6942 gtk_file_chooser_default_update_current_folder (GtkFileChooser    *chooser,
6943                                                 GFile             *file,
6944                                                 gboolean           keep_trail,
6945                                                 gboolean           clear_entry,
6946                                                 GError           **error)
6947 {
6948   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
6949   struct UpdateCurrentFolderData *data;
6950
6951   profile_start ("start", NULL);
6952
6953   g_object_ref (file);
6954
6955   switch (impl->operation_mode)
6956     {
6957     case OPERATION_MODE_SEARCH:
6958       search_switch_to_browse_mode (impl);
6959       break;
6960     case OPERATION_MODE_RECENT:
6961       recent_switch_to_browse_mode (impl);
6962       break;
6963     case OPERATION_MODE_BROWSE:
6964       break;
6965     }
6966
6967   if (impl->local_only && !g_file_is_native (file))
6968     {
6969       g_set_error_literal (error,
6970                            GTK_FILE_CHOOSER_ERROR,
6971                            GTK_FILE_CHOOSER_ERROR_BAD_FILENAME,
6972                            _("Cannot change to folder because it is not local"));
6973
6974       g_object_unref (file);
6975       profile_end ("end - not local", NULL);
6976       return FALSE;
6977     }
6978
6979   if (impl->update_current_folder_cancellable)
6980     g_cancellable_cancel (impl->update_current_folder_cancellable);
6981
6982   /* Test validity of path here.  */
6983   data = g_new0 (struct UpdateCurrentFolderData, 1);
6984   data->impl = impl;
6985   data->file = g_object_ref (file);
6986   data->keep_trail = keep_trail;
6987   data->clear_entry = clear_entry;
6988
6989   impl->reload_state = RELOAD_HAS_FOLDER;
6990
6991   impl->update_current_folder_cancellable =
6992     _gtk_file_system_get_info (impl->file_system, file,
6993                                "standard::type",
6994                                update_current_folder_get_info_cb,
6995                                data);
6996
6997   set_busy_cursor (impl, TRUE);
6998   g_object_unref (file);
6999
7000   profile_end ("end", NULL);
7001   return TRUE;
7002 }
7003
7004 static GFile *
7005 gtk_file_chooser_default_get_current_folder (GtkFileChooser *chooser)
7006 {
7007   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7008
7009   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7010       impl->operation_mode == OPERATION_MODE_RECENT)
7011     return NULL;
7012  
7013   if (impl->reload_state == RELOAD_EMPTY)
7014     {
7015       char *current_working_dir;
7016       GFile *file;
7017
7018       /* We are unmapped, or we had an error while loading the last folder.  We'll return
7019        * the $cwd since once we get (re)mapped, we'll load $cwd anyway unless the caller
7020        * explicitly calls set_current_folder() on us.
7021        */
7022       current_working_dir = g_get_current_dir ();
7023       file = g_file_new_for_path (current_working_dir);
7024       g_free (current_working_dir);
7025       return file;
7026     }
7027
7028   if (impl->current_folder)
7029     return g_object_ref (impl->current_folder);
7030
7031   return NULL;
7032 }
7033
7034 static void
7035 gtk_file_chooser_default_set_current_name (GtkFileChooser *chooser,
7036                                            const gchar    *name)
7037 {
7038   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7039
7040   g_return_if_fail (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7041                     impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
7042
7043   pending_select_files_free (impl);
7044   _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), name);
7045 }
7046
7047 static void
7048 select_func (GtkFileSystemModel *model,
7049              GtkTreePath        *path,
7050              GtkTreeIter        *iter,
7051              gpointer            user_data)
7052 {
7053   GtkFileChooserDefault *impl = user_data;
7054   GtkTreeSelection *selection;
7055   GtkTreeIter sorted_iter;
7056
7057   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7058
7059   gtk_tree_model_sort_convert_child_iter_to_iter (impl->sort_model, &sorted_iter, iter);
7060   gtk_tree_selection_select_iter (selection, &sorted_iter);
7061 }
7062
7063 static gboolean
7064 gtk_file_chooser_default_select_file (GtkFileChooser  *chooser,
7065                                       GFile           *file,
7066                                       GError         **error)
7067 {
7068   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7069   GFile *parent_file;
7070   gboolean same_path;
7071
7072   parent_file = g_file_get_parent (file);
7073
7074   if (!parent_file)
7075     return gtk_file_chooser_set_current_folder_file (chooser, file, error);
7076
7077   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7078       impl->operation_mode == OPERATION_MODE_RECENT ||
7079       impl->load_state == LOAD_EMPTY)
7080     {
7081       same_path = FALSE;
7082     }
7083   else
7084     {
7085       g_assert (impl->current_folder != NULL);
7086
7087       same_path = g_file_equal (parent_file, impl->current_folder);
7088     }
7089
7090   if (same_path && impl->load_state == LOAD_FINISHED)
7091     {
7092       gboolean result;
7093       GSList files;
7094
7095       files.data = (gpointer) file;
7096       files.next = NULL;
7097
7098       result = show_and_select_files (impl, parent_file, &files, error);
7099       g_object_unref (parent_file);
7100       return result;
7101     }
7102
7103   pending_select_files_add (impl, file);
7104
7105   if (!same_path)
7106     {
7107       gboolean result;
7108
7109       result = gtk_file_chooser_set_current_folder_file (chooser, parent_file, error);
7110       g_object_unref (parent_file);
7111       return result;
7112     }
7113
7114   g_object_unref (parent_file);
7115   return TRUE;
7116 }
7117
7118 static void
7119 unselect_func (GtkFileSystemModel *model,
7120                GtkTreePath        *path,
7121                GtkTreeIter        *iter,
7122                gpointer            user_data)
7123 {
7124   GtkFileChooserDefault *impl = user_data;
7125   GtkTreeView *tree_view = GTK_TREE_VIEW (impl->browse_files_tree_view);
7126   GtkTreePath *sorted_path;
7127
7128   sorted_path = gtk_tree_model_sort_convert_child_path_to_path (impl->sort_model,
7129                                                                 path);
7130   gtk_tree_selection_unselect_path (gtk_tree_view_get_selection (tree_view),
7131                                     sorted_path);
7132   gtk_tree_path_free (sorted_path);
7133 }
7134
7135 static void
7136 gtk_file_chooser_default_unselect_file (GtkFileChooser *chooser,
7137                                         GFile          *file)
7138 {
7139   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7140
7141   if (!impl->browse_files_model)
7142     return;
7143
7144   _gtk_file_system_model_path_do (impl->browse_files_model, file,
7145                                   unselect_func, impl);
7146 }
7147
7148 static gboolean
7149 maybe_select (GtkTreeModel *model, 
7150               GtkTreePath  *path, 
7151               GtkTreeIter  *iter, 
7152               gpointer     data)
7153 {
7154   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (data);
7155   GtkTreeSelection *selection;
7156   GFileInfo *info;
7157   gboolean is_folder;
7158   
7159   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7160   
7161   info = get_list_file_info (impl, iter);
7162   is_folder = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
7163
7164   if ((is_folder && impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER) ||
7165       (!is_folder && impl->action == GTK_FILE_CHOOSER_ACTION_OPEN))
7166     gtk_tree_selection_select_iter (selection, iter);
7167   else
7168     gtk_tree_selection_unselect_iter (selection, iter);
7169     
7170   return FALSE;
7171 }
7172
7173 static void
7174 gtk_file_chooser_default_select_all (GtkFileChooser *chooser)
7175 {
7176   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7177
7178   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7179       impl->operation_mode == OPERATION_MODE_RECENT)
7180     {
7181       GtkTreeSelection *selection;
7182       
7183       selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7184       gtk_tree_selection_select_all (selection);
7185       return;
7186     }
7187
7188   if (impl->select_multiple)
7189     gtk_tree_model_foreach (GTK_TREE_MODEL (impl->sort_model), 
7190                             maybe_select, impl);
7191 }
7192
7193 static void
7194 gtk_file_chooser_default_unselect_all (GtkFileChooser *chooser)
7195 {
7196   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7197   GtkTreeSelection *selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7198
7199   gtk_tree_selection_unselect_all (selection);
7200   pending_select_files_free (impl);
7201 }
7202
7203 /* Checks whether the filename entry for the Save modes contains a well-formed filename.
7204  *
7205  * is_well_formed_ret - whether what the user typed passes gkt_file_system_make_path()
7206  *
7207  * is_empty_ret - whether the file entry is totally empty
7208  *
7209  * is_file_part_empty_ret - whether the file part is empty (will be if user types "foobar/", and
7210  *                          the path will be "$cwd/foobar")
7211  */
7212 static void
7213 check_save_entry (GtkFileChooserDefault *impl,
7214                   GFile                **file_ret,
7215                   gboolean              *is_well_formed_ret,
7216                   gboolean              *is_empty_ret,
7217                   gboolean              *is_file_part_empty_ret,
7218                   gboolean              *is_folder)
7219 {
7220   GtkFileChooserEntry *chooser_entry;
7221   GFile *current_folder;
7222   const char *file_part;
7223   GFile *file;
7224   GError *error;
7225
7226   g_assert (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
7227             || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
7228             || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
7229                  || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
7230                 && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY));
7231
7232   chooser_entry = GTK_FILE_CHOOSER_ENTRY (impl->location_entry);
7233
7234   if (strlen (gtk_entry_get_text (GTK_ENTRY (chooser_entry))) == 0)
7235     {
7236       *file_ret = NULL;
7237       *is_well_formed_ret = TRUE;
7238       *is_empty_ret = TRUE;
7239       *is_file_part_empty_ret = TRUE;
7240       *is_folder = FALSE;
7241
7242       return;
7243     }
7244
7245   *is_empty_ret = FALSE;
7246
7247   current_folder = _gtk_file_chooser_entry_get_current_folder (chooser_entry);
7248   if (!current_folder)
7249     {
7250       *file_ret = NULL;
7251       *is_well_formed_ret = FALSE;
7252       *is_file_part_empty_ret = FALSE;
7253       *is_folder = FALSE;
7254
7255       return;
7256     }
7257
7258   file_part = _gtk_file_chooser_entry_get_file_part (chooser_entry);
7259
7260   if (!file_part || file_part[0] == '\0')
7261     {
7262       *file_ret = g_object_ref (current_folder);
7263       *is_well_formed_ret = TRUE;
7264       *is_file_part_empty_ret = TRUE;
7265       *is_folder = TRUE;
7266
7267       return;
7268     }
7269
7270   *is_file_part_empty_ret = FALSE;
7271
7272   error = NULL;
7273   file = g_file_get_child_for_display_name (current_folder, file_part, &error);
7274
7275   if (!file)
7276     {
7277       error_building_filename_dialog (impl, error);
7278       *file_ret = NULL;
7279       *is_well_formed_ret = FALSE;
7280       *is_folder = FALSE;
7281
7282       return;
7283     }
7284
7285   *file_ret = file;
7286   *is_well_formed_ret = TRUE;
7287   *is_folder = _gtk_file_chooser_entry_get_is_folder (chooser_entry, file);
7288 }
7289
7290 struct get_files_closure {
7291   GtkFileChooserDefault *impl;
7292   GSList *result;
7293   GFile *file_from_entry;
7294 };
7295
7296 static void
7297 get_files_foreach (GtkTreeModel *model,
7298                    GtkTreePath  *path,
7299                    GtkTreeIter  *iter,
7300                    gpointer      data)
7301 {
7302   struct get_files_closure *info;
7303   GFile *file;
7304   GtkFileSystemModel *fs_model;
7305   GtkTreeIter sel_iter;
7306
7307   info = data;
7308   fs_model = info->impl->browse_files_model;
7309   gtk_tree_model_sort_convert_iter_to_child_iter (info->impl->sort_model, &sel_iter, iter);
7310
7311   file = _gtk_file_system_model_get_file (fs_model, &sel_iter);
7312   if (!file)
7313     return; /* We are on the editable row */
7314
7315   if (!info->file_from_entry || !g_file_equal (info->file_from_entry, file))
7316     info->result = g_slist_prepend (info->result, g_object_ref (file));
7317 }
7318
7319 static GSList *
7320 gtk_file_chooser_default_get_files (GtkFileChooser *chooser)
7321 {
7322   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7323   struct get_files_closure info;
7324   GtkWindow *toplevel;
7325   GtkWidget *current_focus;
7326   gboolean file_list_seen;
7327
7328   if (impl->operation_mode == OPERATION_MODE_SEARCH)
7329     return search_get_selected_files (impl);
7330
7331   if (impl->operation_mode == OPERATION_MODE_RECENT)
7332     return recent_get_selected_files (impl);
7333
7334   info.impl = impl;
7335   info.result = NULL;
7336   info.file_from_entry = NULL;
7337
7338   toplevel = get_toplevel (GTK_WIDGET (impl));
7339   if (toplevel)
7340     current_focus = gtk_window_get_focus (toplevel);
7341   else
7342     current_focus = NULL;
7343
7344   file_list_seen = FALSE;
7345   if (current_focus == impl->browse_files_tree_view)
7346     {
7347       GtkTreeSelection *selection;
7348
7349     file_list:
7350
7351       file_list_seen = TRUE;
7352       selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7353       gtk_tree_selection_selected_foreach (selection, get_files_foreach, &info);
7354
7355       /* If there is no selection in the file list, we probably have this situation:
7356        *
7357        * 1. The user typed a filename in the SAVE filename entry ("foo.txt").
7358        * 2. He then double-clicked on a folder ("bar") in the file list
7359        *
7360        * So we want the selection to be "bar/foo.txt".  Jump to the case for the
7361        * filename entry to see if that is the case.
7362        */
7363       if (info.result == NULL && impl->location_entry)
7364         goto file_entry;
7365     }
7366   else if (impl->location_entry && current_focus == impl->location_entry)
7367     {
7368       gboolean is_well_formed, is_empty, is_file_part_empty, is_folder;
7369
7370     file_entry:
7371
7372       check_save_entry (impl, &info.file_from_entry, &is_well_formed, &is_empty, &is_file_part_empty, &is_folder);
7373
7374       if (is_empty)
7375         goto out;
7376
7377       if (!is_well_formed)
7378         return NULL;
7379
7380       if (is_file_part_empty && impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
7381         {
7382           g_object_unref (info.file_from_entry);
7383           return NULL;
7384         }
7385
7386       if (info.file_from_entry)
7387         info.result = g_slist_prepend (info.result, info.file_from_entry);
7388       else if (!file_list_seen) 
7389         goto file_list;
7390       else
7391         return NULL;
7392     }
7393   else if (impl->toplevel_last_focus_widget == impl->browse_files_tree_view)
7394     goto file_list;
7395   else if (impl->location_entry && impl->toplevel_last_focus_widget == impl->location_entry)
7396     goto file_entry;
7397   else
7398     {
7399       /* The focus is on a dialog's action area button or something else */
7400       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7401           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
7402         goto file_entry;
7403       else
7404         goto file_list; 
7405     }
7406
7407  out:
7408
7409   /* If there's no folder selected, and we're in SELECT_FOLDER mode, then we
7410    * fall back to the current directory */
7411   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER &&
7412       info.result == NULL)
7413     {
7414       GFile *current_folder;
7415
7416       current_folder = gtk_file_chooser_get_current_folder_file (chooser);
7417
7418       if (current_folder)
7419         info.result = g_slist_prepend (info.result, current_folder);
7420     }
7421
7422   return g_slist_reverse (info.result);
7423 }
7424
7425 GFile *
7426 gtk_file_chooser_default_get_preview_file (GtkFileChooser *chooser)
7427 {
7428   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7429
7430   if (impl->preview_file)
7431     return g_object_ref (impl->preview_file);
7432   else
7433     return NULL;
7434 }
7435
7436 static GtkFileSystem *
7437 gtk_file_chooser_default_get_file_system (GtkFileChooser *chooser)
7438 {
7439   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7440
7441   return impl->file_system;
7442 }
7443
7444 /* Shows or hides the filter widgets */
7445 static void
7446 show_filters (GtkFileChooserDefault *impl,
7447               gboolean               show)
7448 {
7449   if (show)
7450     gtk_widget_show (impl->filter_combo_hbox);
7451   else
7452     gtk_widget_hide (impl->filter_combo_hbox);
7453 }
7454
7455 static void
7456 gtk_file_chooser_default_add_filter (GtkFileChooser *chooser,
7457                                      GtkFileFilter  *filter)
7458 {
7459   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7460   const gchar *name;
7461
7462   if (g_slist_find (impl->filters, filter))
7463     {
7464       g_warning ("gtk_file_chooser_add_filter() called on filter already in list\n");
7465       return;
7466     }
7467
7468   g_object_ref_sink (filter);
7469   impl->filters = g_slist_append (impl->filters, filter);
7470
7471   name = gtk_file_filter_get_name (filter);
7472   if (!name)
7473     name = "Untitled filter";   /* Place-holder, doesn't need to be marked for translation */
7474
7475   gtk_combo_box_append_text (GTK_COMBO_BOX (impl->filter_combo), name);
7476
7477   if (!g_slist_find (impl->filters, impl->current_filter))
7478     set_current_filter (impl, filter);
7479
7480   show_filters (impl, TRUE);
7481 }
7482
7483 static void
7484 gtk_file_chooser_default_remove_filter (GtkFileChooser *chooser,
7485                                         GtkFileFilter  *filter)
7486 {
7487   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7488   GtkTreeModel *model;
7489   GtkTreeIter iter;
7490   gint filter_index;
7491
7492   filter_index = g_slist_index (impl->filters, filter);
7493
7494   if (filter_index < 0)
7495     {
7496       g_warning ("gtk_file_chooser_remove_filter() called on filter not in list\n");
7497       return;
7498     }
7499
7500   impl->filters = g_slist_remove (impl->filters, filter);
7501
7502   if (filter == impl->current_filter)
7503     {
7504       if (impl->filters)
7505         set_current_filter (impl, impl->filters->data);
7506       else
7507         set_current_filter (impl, NULL);
7508     }
7509
7510   /* Remove row from the combo box */
7511   model = gtk_combo_box_get_model (GTK_COMBO_BOX (impl->filter_combo));
7512   if (!gtk_tree_model_iter_nth_child  (model, &iter, NULL, filter_index))
7513     g_assert_not_reached ();
7514
7515   gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
7516
7517   g_object_unref (filter);
7518
7519   if (!impl->filters)
7520     show_filters (impl, FALSE);
7521 }
7522
7523 static GSList *
7524 gtk_file_chooser_default_list_filters (GtkFileChooser *chooser)
7525 {
7526   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7527
7528   return g_slist_copy (impl->filters);
7529 }
7530
7531 /* Returns the position in the shortcuts tree where the nth specified shortcut would appear */
7532 static int
7533 shortcuts_get_pos_for_shortcut_folder (GtkFileChooserDefault *impl,
7534                                        int                    pos)
7535 {
7536   return pos + shortcuts_get_index (impl, SHORTCUTS_SHORTCUTS);
7537 }
7538
7539 struct AddShortcutData
7540 {
7541   GtkFileChooserDefault *impl;
7542   GFile *file;
7543 };
7544
7545 static void
7546 add_shortcut_get_info_cb (GCancellable *cancellable,
7547                           GFileInfo    *info,
7548                           const GError *error,
7549                           gpointer      user_data)
7550 {
7551   int pos;
7552   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
7553   struct AddShortcutData *data = user_data;
7554
7555   if (!g_slist_find (data->impl->loading_shortcuts, cancellable))
7556     goto out;
7557
7558   data->impl->loading_shortcuts = g_slist_remove (data->impl->loading_shortcuts, cancellable);
7559
7560   if (cancelled || error || g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY)
7561     goto out;
7562
7563   pos = shortcuts_get_pos_for_shortcut_folder (data->impl, data->impl->num_shortcuts);
7564
7565   shortcuts_insert_file (data->impl, pos, SHORTCUT_TYPE_FILE, NULL, data->file, NULL, FALSE, SHORTCUTS_SHORTCUTS);
7566
7567 out:
7568   g_object_unref (data->impl);
7569   g_object_unref (data->file);
7570   g_free (data);
7571
7572   g_object_unref (cancellable);
7573 }
7574
7575 static gboolean
7576 gtk_file_chooser_default_add_shortcut_folder (GtkFileChooser  *chooser,
7577                                               GFile           *file,
7578                                               GError         **error)
7579 {
7580   GCancellable *cancellable;
7581   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7582   struct AddShortcutData *data;
7583   GSList *l;
7584   int pos;
7585
7586   /* Avoid adding duplicates */
7587   pos = shortcut_find_position (impl, file);
7588   if (pos >= 0 && pos < shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS_SEPARATOR))
7589     {
7590       gchar *uri;
7591
7592       uri = g_file_get_uri (file);
7593       /* translators, "Shortcut" means "Bookmark" here */
7594       g_set_error (error,
7595                    GTK_FILE_CHOOSER_ERROR,
7596                    GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS,
7597                    _("Shortcut %s already exists"),
7598                    uri);
7599       g_free (uri);
7600
7601       return FALSE;
7602     }
7603
7604   for (l = impl->loading_shortcuts; l; l = l->next)
7605     {
7606       GCancellable *c = l->data;
7607       GFile *f;
7608
7609       f = g_object_get_data (G_OBJECT (c), "add-shortcut-path-key");
7610       if (f && g_file_equal (file, f))
7611         {
7612           gchar *uri;
7613
7614           uri = g_file_get_uri (file);
7615           g_set_error (error,
7616                        GTK_FILE_CHOOSER_ERROR,
7617                        GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS,
7618                        _("Shortcut %s already exists"),
7619                        uri);
7620           g_free (uri);
7621
7622           return FALSE;
7623         }
7624     }
7625
7626   data = g_new0 (struct AddShortcutData, 1);
7627   data->impl = g_object_ref (impl);
7628   data->file = g_object_ref (file);
7629
7630   cancellable = _gtk_file_system_get_info (impl->file_system, file,
7631                                            "standard::type",
7632                                            add_shortcut_get_info_cb, data);
7633
7634   if (!cancellable)
7635     return FALSE;
7636
7637   impl->loading_shortcuts = g_slist_append (impl->loading_shortcuts, cancellable);
7638   g_object_set_data (G_OBJECT (cancellable), "add-shortcut-path-key", data->file);
7639
7640   return TRUE;
7641 }
7642
7643 static gboolean
7644 gtk_file_chooser_default_remove_shortcut_folder (GtkFileChooser  *chooser,
7645                                                  GFile           *file,
7646                                                  GError         **error)
7647 {
7648   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7649   int pos;
7650   GtkTreeIter iter;
7651   GSList *l;
7652   char *uri;
7653   int i;
7654
7655   for (l = impl->loading_shortcuts; l; l = l->next)
7656     {
7657       GCancellable *c = l->data;
7658       GFile *f;
7659
7660       f = g_object_get_data (G_OBJECT (c), "add-shortcut-path-key");
7661       if (f && g_file_equal (file, f))
7662         {
7663           impl->loading_shortcuts = g_slist_remove (impl->loading_shortcuts, c);
7664           g_cancellable_cancel (c);
7665           return TRUE;
7666         }
7667     }
7668
7669   if (impl->num_shortcuts == 0)
7670     goto out;
7671
7672   pos = shortcuts_get_pos_for_shortcut_folder (impl, 0);
7673   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
7674     g_assert_not_reached ();
7675
7676   for (i = 0; i < impl->num_shortcuts; i++)
7677     {
7678       gpointer col_data;
7679       ShortcutType shortcut_type;
7680       GFile *shortcut;
7681
7682       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
7683                           SHORTCUTS_COL_DATA, &col_data,
7684                           SHORTCUTS_COL_TYPE, &shortcut_type,
7685                           -1);
7686       g_assert (col_data != NULL);
7687       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
7688
7689       shortcut = col_data;
7690       if (g_file_equal (shortcut, file))
7691         {
7692           shortcuts_remove_rows (impl, pos + i, 1);
7693           impl->num_shortcuts--;
7694           return TRUE;
7695         }
7696
7697       if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
7698         g_assert_not_reached ();
7699     }
7700
7701  out:
7702
7703   uri = g_file_get_uri (file);
7704   /* translators, "Shortcut" means "Bookmark" here */
7705   g_set_error (error,
7706                GTK_FILE_CHOOSER_ERROR,
7707                GTK_FILE_CHOOSER_ERROR_NONEXISTENT,
7708                _("Shortcut %s does not exist"),
7709                uri);
7710   g_free (uri);
7711
7712   return FALSE;
7713 }
7714
7715 static GSList *
7716 gtk_file_chooser_default_list_shortcut_folders (GtkFileChooser *chooser)
7717 {
7718   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7719   int pos;
7720   GtkTreeIter iter;
7721   int i;
7722   GSList *list;
7723
7724   if (impl->num_shortcuts == 0)
7725     return NULL;
7726
7727   pos = shortcuts_get_pos_for_shortcut_folder (impl, 0);
7728   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
7729     g_assert_not_reached ();
7730
7731   list = NULL;
7732
7733   for (i = 0; i < impl->num_shortcuts; i++)
7734     {
7735       gpointer col_data;
7736       ShortcutType shortcut_type;
7737       GFile *shortcut;
7738
7739       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
7740                           SHORTCUTS_COL_DATA, &col_data,
7741                           SHORTCUTS_COL_TYPE, &shortcut_type,
7742                           -1);
7743       g_assert (col_data != NULL);
7744       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
7745
7746       shortcut = col_data;
7747       list = g_slist_prepend (list, g_object_ref (shortcut));
7748
7749       if (i != impl->num_shortcuts - 1)
7750         {
7751           if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
7752             g_assert_not_reached ();
7753         }
7754     }
7755
7756   return g_slist_reverse (list);
7757 }
7758
7759 /* Guesses a size based upon font sizes */
7760 static void
7761 find_good_size_from_style (GtkWidget *widget,
7762                            gint      *width,
7763                            gint      *height)
7764 {
7765   GtkFileChooserDefault *impl;
7766   int font_size;
7767   GdkScreen *screen;
7768   double resolution;
7769
7770   g_assert (widget->style != NULL);
7771   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
7772
7773   if (impl->default_width == 0 &&
7774       impl->default_height == 0)
7775     {
7776       screen = gtk_widget_get_screen (widget);
7777       if (screen)
7778         {
7779           resolution = gdk_screen_get_resolution (screen);
7780           if (resolution < 0.0) /* will be -1 if the resolution is not defined in the GdkScreen */
7781             resolution = 96.0;
7782         }
7783       else
7784         resolution = 96.0; /* wheeee */
7785
7786       font_size = pango_font_description_get_size (widget->style->font_desc);
7787       font_size = PANGO_PIXELS (font_size) * resolution / 72.0;
7788
7789       impl->default_width = font_size * NUM_CHARS;
7790       impl->default_height = font_size * NUM_LINES;
7791     }
7792
7793   *width = impl->default_width;
7794   *height = impl->default_height;
7795 }
7796
7797 static void
7798 gtk_file_chooser_default_get_default_size (GtkFileChooserEmbed *chooser_embed,
7799                                            gint                *default_width,
7800                                            gint                *default_height)
7801 {
7802   GtkFileChooserDefault *impl;
7803   GtkRequisition req;
7804
7805   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
7806   find_good_size_from_style (GTK_WIDGET (chooser_embed), default_width, default_height);
7807
7808   if (impl->preview_widget_active &&
7809       impl->preview_widget &&
7810       GTK_WIDGET_VISIBLE (impl->preview_widget))
7811     {
7812       gtk_widget_size_request (impl->preview_box, &req);
7813       *default_width += PREVIEW_HBOX_SPACING + req.width;
7814     }
7815
7816   if (impl->extra_widget &&
7817       GTK_WIDGET_VISIBLE (impl->extra_widget))
7818     {
7819       gtk_widget_size_request (impl->extra_align, &req);
7820       *default_height += GTK_BOX (chooser_embed)->spacing + req.height;
7821     }
7822 }
7823
7824 struct switch_folder_closure {
7825   GtkFileChooserDefault *impl;
7826   GFile *file;
7827   int num_selected;
7828 };
7829
7830 /* Used from gtk_tree_selection_selected_foreach() in switch_to_selected_folder() */
7831 static void
7832 switch_folder_foreach_cb (GtkTreeModel      *model,
7833                           GtkTreePath       *path,
7834                           GtkTreeIter       *iter,
7835                           gpointer           data)
7836 {
7837   struct switch_folder_closure *closure;
7838   GtkTreeIter child_iter;
7839
7840   closure = data;
7841
7842   gtk_tree_model_sort_convert_iter_to_child_iter (closure->impl->sort_model, &child_iter, iter);
7843
7844   closure->file = _gtk_file_system_model_get_file (closure->impl->browse_files_model, &child_iter);
7845   closure->num_selected++;
7846 }
7847
7848 /* Changes to the selected folder in the list view */
7849 static void
7850 switch_to_selected_folder (GtkFileChooserDefault *impl)
7851 {
7852   GtkTreeSelection *selection;
7853   struct switch_folder_closure closure;
7854
7855   /* We do this with foreach() rather than get_selected() as we may be in
7856    * multiple selection mode
7857    */
7858
7859   closure.impl = impl;
7860   closure.file = NULL;
7861   closure.num_selected = 0;
7862
7863   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7864   gtk_tree_selection_selected_foreach (selection, switch_folder_foreach_cb, &closure);
7865
7866   g_assert (closure.file && closure.num_selected == 1);
7867
7868   change_folder_and_display_error (impl, closure.file, FALSE);
7869 }
7870
7871 /* Gets the GFileInfo for the selected row in the file list; assumes single
7872  * selection mode.
7873  */
7874 static GFileInfo *
7875 get_selected_file_info_from_file_list (GtkFileChooserDefault *impl,
7876                                        gboolean              *had_selection)
7877 {
7878   GtkTreeSelection *selection;
7879   GtkTreeIter iter, child_iter;
7880   GFileInfo *info;
7881
7882   g_assert (!impl->select_multiple);
7883   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7884   if (!gtk_tree_selection_get_selected (selection, NULL, &iter))
7885     {
7886       *had_selection = FALSE;
7887       return NULL;
7888     }
7889
7890   *had_selection = TRUE;
7891
7892   gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
7893                                                   &child_iter,
7894                                                   &iter);
7895
7896   info = _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
7897   return info;
7898 }
7899
7900 /* Gets the display name of the selected file in the file list; assumes single
7901  * selection mode and that something is selected.
7902  */
7903 static const gchar *
7904 get_display_name_from_file_list (GtkFileChooserDefault *impl)
7905 {
7906   GFileInfo *info;
7907   gboolean had_selection;
7908
7909   info = get_selected_file_info_from_file_list (impl, &had_selection);
7910   g_assert (had_selection);
7911   g_assert (info != NULL);
7912
7913   return g_file_info_get_display_name (info);
7914 }
7915
7916 static void
7917 add_custom_button_to_dialog (GtkDialog   *dialog,
7918                              const gchar *mnemonic_label,
7919                              const gchar *stock_id,
7920                              gint         response_id)
7921 {
7922   GtkWidget *button;
7923
7924   button = gtk_button_new_with_mnemonic (mnemonic_label);
7925   GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
7926   gtk_button_set_image (GTK_BUTTON (button),
7927                         gtk_image_new_from_stock (stock_id, GTK_ICON_SIZE_BUTTON));
7928   gtk_widget_show (button);
7929
7930   gtk_dialog_add_action_widget (GTK_DIALOG (dialog), button, response_id);
7931 }
7932
7933 /* Presents an overwrite confirmation dialog; returns whether we should accept
7934  * the filename.
7935  */
7936 static gboolean
7937 confirm_dialog_should_accept_filename (GtkFileChooserDefault *impl,
7938                                        const gchar           *file_part,
7939                                        const gchar           *folder_display_name)
7940 {
7941   GtkWindow *toplevel;
7942   GtkWidget *dialog;
7943   int response;
7944
7945   toplevel = get_toplevel (GTK_WIDGET (impl));
7946
7947   dialog = gtk_message_dialog_new (toplevel,
7948                                    GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
7949                                    GTK_MESSAGE_QUESTION,
7950                                    GTK_BUTTONS_NONE,
7951                                    _("A file named \"%s\" already exists.  Do you want to replace it?"),
7952                                    file_part);
7953   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
7954                                             _("The file already exists in \"%s\".  Replacing it will "
7955                                               "overwrite its contents."),
7956                                             folder_display_name);
7957
7958   gtk_dialog_add_button (GTK_DIALOG (dialog), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
7959   add_custom_button_to_dialog (GTK_DIALOG (dialog), _("_Replace"),
7960                                GTK_STOCK_SAVE_AS, GTK_RESPONSE_ACCEPT);
7961   gtk_dialog_set_alternative_button_order (GTK_DIALOG (dialog),
7962                                            GTK_RESPONSE_ACCEPT,
7963                                            GTK_RESPONSE_CANCEL,
7964                                            -1);
7965   gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);
7966
7967   if (toplevel->group)
7968     gtk_window_group_add_window (toplevel->group, GTK_WINDOW (dialog));
7969
7970   response = gtk_dialog_run (GTK_DIALOG (dialog));
7971
7972   gtk_widget_destroy (dialog);
7973
7974   return (response == GTK_RESPONSE_ACCEPT);
7975 }
7976
7977 struct GetDisplayNameData
7978 {
7979   GtkFileChooserDefault *impl;
7980   gchar *file_part;
7981 };
7982
7983 static void
7984 confirmation_confirm_get_info_cb (GCancellable *cancellable,
7985                                   GFileInfo    *info,
7986                                   const GError *error,
7987                                   gpointer      user_data)
7988 {
7989   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
7990   gboolean should_respond = FALSE;
7991   struct GetDisplayNameData *data = user_data;
7992
7993   if (cancellable != data->impl->should_respond_get_info_cancellable)
7994     goto out;
7995
7996   data->impl->should_respond_get_info_cancellable = NULL;
7997
7998   if (cancelled)
7999     goto out;
8000
8001   if (error)
8002     /* Huh?  Did the folder disappear?  Let the caller deal with it */
8003     should_respond = TRUE;
8004   else
8005     should_respond = confirm_dialog_should_accept_filename (data->impl, data->file_part, g_file_info_get_display_name (info));
8006
8007   set_busy_cursor (data->impl, FALSE);
8008   if (should_respond)
8009     g_signal_emit_by_name (data->impl, "response-requested");
8010
8011 out:
8012   g_object_unref (data->impl);
8013   g_free (data->file_part);
8014   g_free (data);
8015
8016   g_object_unref (cancellable);
8017 }
8018
8019 /* Does overwrite confirmation if appropriate, and returns whether the dialog
8020  * should respond.  Can get the file part from the file list or the save entry.
8021  */
8022 static gboolean
8023 should_respond_after_confirm_overwrite (GtkFileChooserDefault *impl,
8024                                         const gchar           *file_part,
8025                                         GFile                 *parent_file)
8026 {
8027   GtkFileChooserConfirmation conf;
8028
8029   if (!impl->do_overwrite_confirmation)
8030     return TRUE;
8031
8032   conf = GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM;
8033
8034   g_signal_emit_by_name (impl, "confirm-overwrite", &conf);
8035
8036   switch (conf)
8037     {
8038     case GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM:
8039       {
8040         struct GetDisplayNameData *data;
8041
8042         g_assert (file_part != NULL);
8043
8044         data = g_new0 (struct GetDisplayNameData, 1);
8045         data->impl = g_object_ref (impl);
8046         data->file_part = g_strdup (file_part);
8047
8048         if (impl->should_respond_get_info_cancellable)
8049           g_cancellable_cancel (impl->should_respond_get_info_cancellable);
8050
8051         impl->should_respond_get_info_cancellable =
8052           _gtk_file_system_get_info (impl->file_system, parent_file,
8053                                      "standard::display-name",
8054                                      confirmation_confirm_get_info_cb,
8055                                      data);
8056         set_busy_cursor (data->impl, TRUE);
8057         return FALSE;
8058       }
8059
8060     case GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME:
8061       return TRUE;
8062
8063     case GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN:
8064       return FALSE;
8065
8066     default:
8067       g_assert_not_reached ();
8068       return FALSE;
8069     }
8070 }
8071
8072 struct FileExistsData
8073 {
8074   GtkFileChooserDefault *impl;
8075   gboolean file_exists_and_is_not_folder;
8076   GFile *parent_file;
8077   GFile *file;
8078 };
8079
8080 static void
8081 save_entry_get_info_cb (GCancellable *cancellable,
8082                         GFileInfo    *info,
8083                         const GError *error,
8084                         gpointer      user_data)
8085 {
8086   gboolean parent_is_folder;
8087   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8088   struct FileExistsData *data = user_data;
8089
8090   if (cancellable != data->impl->should_respond_get_info_cancellable)
8091     goto out;
8092
8093   data->impl->should_respond_get_info_cancellable = NULL;
8094
8095   set_busy_cursor (data->impl, FALSE);
8096
8097   if (cancelled)
8098     goto out;
8099
8100   if (!info)
8101     parent_is_folder = FALSE;
8102   else
8103     parent_is_folder = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
8104
8105   if (parent_is_folder)
8106     {
8107       if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8108         {
8109           if (data->file_exists_and_is_not_folder)
8110             {
8111               gboolean retval;
8112               const char *file_part;
8113
8114               file_part = _gtk_file_chooser_entry_get_file_part (GTK_FILE_CHOOSER_ENTRY (data->impl->location_entry));
8115               retval = should_respond_after_confirm_overwrite (data->impl, file_part, data->parent_file);
8116
8117               if (retval)
8118                 g_signal_emit_by_name (data->impl, "response-requested");
8119             }
8120           else
8121             g_signal_emit_by_name (data->impl, "response-requested");
8122         }
8123       else /* GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER */
8124         {
8125           GError *error = NULL;
8126
8127           set_busy_cursor (data->impl, TRUE);
8128           g_file_make_directory (data->file, NULL, &error);
8129           set_busy_cursor (data->impl, FALSE);
8130
8131           if (!error)
8132             g_signal_emit_by_name (data->impl, "response-requested");
8133           else
8134             error_creating_folder_dialog (data->impl, data->file, error);
8135         }
8136     }
8137   else
8138     {
8139       /* This will display an error, which is what we want */
8140       change_folder_and_display_error (data->impl, data->parent_file, FALSE);
8141     }
8142
8143 out:
8144   g_object_unref (data->impl);
8145   g_object_unref (data->file);
8146   g_object_unref (data->parent_file);
8147   g_free (data);
8148
8149   g_object_unref (cancellable);
8150 }
8151
8152 static void
8153 file_exists_get_info_cb (GCancellable *cancellable,
8154                          GFileInfo    *info,
8155                          const GError *error,
8156                          gpointer      user_data)
8157 {
8158   gboolean data_ownership_taken = FALSE;
8159   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8160   gboolean file_exists_and_is_not_folder;
8161   struct FileExistsData *data = user_data;
8162
8163   if (cancellable != data->impl->file_exists_get_info_cancellable)
8164     goto out;
8165
8166   data->impl->file_exists_get_info_cancellable = NULL;
8167
8168   set_busy_cursor (data->impl, FALSE);
8169
8170   if (cancelled)
8171     goto out;
8172
8173   file_exists_and_is_not_folder = info && (g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY);
8174
8175   if (data->impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
8176     /* user typed a filename; we are done */
8177     g_signal_emit_by_name (data->impl, "response-requested");
8178   else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
8179            && file_exists_and_is_not_folder)
8180     {
8181       /* Oops, the user typed the name of an existing path which is not
8182        * a folder
8183        */
8184       error_creating_folder_over_existing_file_dialog (data->impl, data->file,
8185                                                        g_error_copy (error));
8186     }
8187   else
8188     {
8189       /* check that everything up to the last component exists */
8190
8191       data->file_exists_and_is_not_folder = file_exists_and_is_not_folder;
8192       data_ownership_taken = TRUE;
8193
8194       if (data->impl->should_respond_get_info_cancellable)
8195         g_cancellable_cancel (data->impl->should_respond_get_info_cancellable);
8196
8197       data->impl->should_respond_get_info_cancellable =
8198         _gtk_file_system_get_info (data->impl->file_system,
8199                                    data->parent_file,
8200                                    "standard::type",
8201                                    save_entry_get_info_cb,
8202                                    data);
8203       set_busy_cursor (data->impl, TRUE);
8204     }
8205
8206 out:
8207   if (!data_ownership_taken)
8208     {
8209       g_object_unref (data->impl);
8210       g_object_unref (data->file);
8211       g_object_unref (data->parent_file);
8212       g_free (data);
8213     }
8214
8215   g_object_unref (cancellable);
8216 }
8217
8218 static void
8219 paste_text_received (GtkClipboard          *clipboard,
8220                      const gchar           *text,
8221                      GtkFileChooserDefault *impl)
8222 {
8223   GFile *file;
8224
8225   if (!text)
8226     return;
8227
8228   file = g_file_new_for_uri (text);
8229
8230   if (!gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (impl), file, NULL))
8231     location_popup_handler (impl, text);
8232
8233   g_object_unref (file);
8234 }
8235
8236 /* Handler for the "location-popup-on-paste" keybinding signal */
8237 static void
8238 location_popup_on_paste_handler (GtkFileChooserDefault *impl)
8239 {
8240   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (impl),
8241                                                       GDK_SELECTION_CLIPBOARD);
8242   gtk_clipboard_request_text (clipboard,
8243                               (GtkClipboardTextReceivedFunc) paste_text_received,
8244                               impl);
8245 }
8246
8247
8248 /* Implementation for GtkFileChooserEmbed::should_respond() */
8249 static gboolean
8250 gtk_file_chooser_default_should_respond (GtkFileChooserEmbed *chooser_embed)
8251 {
8252   GtkFileChooserDefault *impl;
8253   GtkWidget *toplevel;
8254   GtkWidget *current_focus;
8255
8256   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
8257
8258   toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
8259   g_assert (GTK_IS_WINDOW (toplevel));
8260
8261   current_focus = gtk_window_get_focus (GTK_WINDOW (toplevel));
8262
8263   if (current_focus == impl->browse_files_tree_view)
8264     {
8265       /* The following array encodes what we do based on the impl->action and the
8266        * number of files selected.
8267        */
8268       typedef enum {
8269         NOOP,                   /* Do nothing (don't respond) */
8270         RESPOND,                /* Respond immediately */
8271         RESPOND_OR_SWITCH,      /* Respond immediately if the selected item is a file; switch to it if it is a folder */
8272         ALL_FILES,              /* Respond only if everything selected is a file */
8273         ALL_FOLDERS,            /* Respond only if everything selected is a folder */
8274         SAVE_ENTRY,             /* Go to the code for handling the save entry */
8275         NOT_REACHED             /* Sanity check */
8276       } ActionToTake;
8277       static const ActionToTake what_to_do[4][3] = {
8278         /*                                0 selected            1 selected              many selected */
8279         /* ACTION_OPEN */               { NOOP,                 RESPOND_OR_SWITCH,      ALL_FILES   },
8280         /* ACTION_SAVE */               { SAVE_ENTRY,           RESPOND_OR_SWITCH,      NOT_REACHED },
8281         /* ACTION_SELECT_FOLDER */      { RESPOND,              ALL_FOLDERS,            ALL_FOLDERS },
8282         /* ACTION_CREATE_FOLDER */      { SAVE_ENTRY,           ALL_FOLDERS,            NOT_REACHED }
8283       };
8284
8285       int num_selected;
8286       gboolean all_files, all_folders;
8287       int k;
8288       ActionToTake action;
8289
8290     file_list:
8291
8292       g_assert (impl->action >= GTK_FILE_CHOOSER_ACTION_OPEN && impl->action <= GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
8293
8294       if (impl->operation_mode == OPERATION_MODE_SEARCH)
8295         return search_should_respond (impl);
8296
8297       if (impl->operation_mode == OPERATION_MODE_RECENT)
8298         return recent_should_respond (impl);
8299
8300       selection_check (impl, &num_selected, &all_files, &all_folders);
8301
8302       if (num_selected > 2)
8303         k = 2;
8304       else
8305         k = num_selected;
8306
8307       action = what_to_do [impl->action] [k];
8308
8309       switch (action)
8310         {
8311         case NOOP:
8312           return FALSE;
8313
8314         case RESPOND:
8315           return TRUE;
8316
8317         case RESPOND_OR_SWITCH:
8318           g_assert (num_selected == 1);
8319
8320           if (all_folders)
8321             {
8322               switch_to_selected_folder (impl);
8323               return FALSE;
8324             }
8325           else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8326             return should_respond_after_confirm_overwrite (impl,
8327                                                            get_display_name_from_file_list (impl),
8328                                                            impl->current_folder);
8329           else
8330             return TRUE;
8331
8332         case ALL_FILES:
8333           return all_files;
8334
8335         case ALL_FOLDERS:
8336           return all_folders;
8337
8338         case SAVE_ENTRY:
8339           goto save_entry;
8340
8341         default:
8342           g_assert_not_reached ();
8343         }
8344     }
8345   else if ((impl->location_entry != NULL) && (current_focus == impl->location_entry))
8346     {
8347       GFile *file;
8348       gboolean is_well_formed, is_empty, is_file_part_empty;
8349       gboolean is_folder;
8350       gboolean retval;
8351       GtkFileChooserEntry *entry;
8352       GError *error;
8353
8354     save_entry:
8355
8356       g_assert (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8357                 || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
8358                 || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
8359                      || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8360                     && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY));
8361
8362       entry = GTK_FILE_CHOOSER_ENTRY (impl->location_entry);
8363       check_save_entry (impl, &file, &is_well_formed, &is_empty, &is_file_part_empty, &is_folder);
8364
8365       if (is_empty || !is_well_formed)
8366         return FALSE;
8367
8368       g_assert (file != NULL);
8369
8370       error = NULL;
8371       if (is_folder)
8372         {
8373           if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8374               impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8375             {
8376               change_folder_and_display_error (impl, file, TRUE);
8377               retval = FALSE;
8378             }
8379           else if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
8380                    impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8381             {
8382               /* The folder already exists, so we do not need to create it.
8383                * Just respond to terminate the dialog.
8384                */
8385               retval = TRUE;
8386             }
8387           else
8388             {
8389               g_assert_not_reached ();
8390               retval = FALSE;
8391             }
8392         }
8393       else
8394         {
8395           struct FileExistsData *data;
8396
8397           /* We need to check whether file exists and is not a folder */
8398
8399           data = g_new0 (struct FileExistsData, 1);
8400           data->impl = g_object_ref (impl);
8401           data->file = g_object_ref (file);
8402           data->parent_file = g_object_ref (_gtk_file_chooser_entry_get_current_folder (entry));
8403
8404           if (impl->file_exists_get_info_cancellable)
8405             g_cancellable_cancel (impl->file_exists_get_info_cancellable);
8406
8407           impl->file_exists_get_info_cancellable =
8408             _gtk_file_system_get_info (impl->file_system, file,
8409                                        "standard::type",
8410                                        file_exists_get_info_cb,
8411                                        data);
8412
8413           set_busy_cursor (impl, TRUE);
8414           retval = FALSE;
8415
8416           if (error != NULL)
8417             g_error_free (error);
8418         }
8419
8420       g_object_unref (file);
8421       return retval;
8422     }
8423   else if (impl->toplevel_last_focus_widget == impl->browse_files_tree_view)
8424     {
8425       /* The focus is on a dialog's action area button, *and* the widget that
8426        * was focused immediately before it is the file list.  
8427        */
8428       goto file_list;
8429     }
8430   else if (impl->operation_mode == OPERATION_MODE_SEARCH && impl->toplevel_last_focus_widget == impl->search_entry)
8431     {
8432       search_entry_activate_cb (GTK_ENTRY (impl->search_entry), impl);
8433       return FALSE;
8434     }
8435   else if (impl->location_entry && impl->toplevel_last_focus_widget == impl->location_entry)
8436     {
8437       /* The focus is on a dialog's action area button, *and* the widget that
8438        * was focused immediately before it is the location entry.
8439        */
8440       goto save_entry;
8441     }
8442   else
8443     /* The focus is on a dialog's action area button or something else */
8444     if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8445         || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8446       goto save_entry;
8447     else
8448       goto file_list; 
8449   
8450   g_assert_not_reached ();
8451   return FALSE;
8452 }
8453
8454 /* Implementation for GtkFileChooserEmbed::initial_focus() */
8455 static void
8456 gtk_file_chooser_default_initial_focus (GtkFileChooserEmbed *chooser_embed)
8457 {
8458   GtkFileChooserDefault *impl;
8459   GtkWidget *widget;
8460
8461   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
8462
8463   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8464       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8465     {
8466       if (impl->location_mode == LOCATION_MODE_PATH_BAR)
8467         widget = impl->browse_files_tree_view;
8468       else
8469         widget = impl->location_entry;
8470     }
8471   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
8472            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8473     widget = impl->location_entry;
8474   else
8475     {
8476       g_assert_not_reached ();
8477       widget = NULL;
8478     }
8479
8480   g_assert (widget != NULL);
8481   gtk_widget_grab_focus (widget);
8482 }
8483
8484 /* Callback used from gtk_tree_selection_selected_foreach(); gets the selected GFiles */
8485 static void
8486 search_selected_foreach_get_file_cb (GtkTreeModel *model,
8487                                      GtkTreePath  *path,
8488                                      GtkTreeIter  *iter,
8489                                      gpointer      data)
8490 {
8491   GSList **list;
8492   GFile *file;
8493
8494   list = data;
8495
8496   gtk_tree_model_get (model, iter, SEARCH_MODEL_COL_FILE, &file, -1);
8497   *list = g_slist_prepend (*list, file);
8498 }
8499
8500 /* Constructs a list of the selected paths in search mode */
8501 static GSList *
8502 search_get_selected_files (GtkFileChooserDefault *impl)
8503 {
8504   GSList *result;
8505   GtkTreeSelection *selection;
8506
8507   result = NULL;
8508
8509   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8510   gtk_tree_selection_selected_foreach (selection, search_selected_foreach_get_file_cb, &result);
8511   result = g_slist_reverse (result);
8512
8513   return result;
8514 }
8515
8516 /* Called from ::should_respond().  We return whether there are selected files
8517  * in the search list.
8518  */
8519 static gboolean
8520 search_should_respond (GtkFileChooserDefault *impl)
8521 {
8522   GtkTreeSelection *selection;
8523
8524   g_assert (impl->operation_mode == OPERATION_MODE_SEARCH);
8525
8526   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8527   return (gtk_tree_selection_count_selected_rows (selection) != 0);
8528 }
8529
8530 struct SearchHitInsertRequest
8531 {
8532   GtkFileChooserDefault *impl;
8533   GFile *file;
8534   GtkTreeRowReference *row_ref;
8535 };
8536
8537 static void
8538 search_hit_get_info_cb (GCancellable *cancellable,
8539                         GFileInfo    *info,
8540                         const GError *error,
8541                         gpointer      data)
8542 {
8543   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8544   GdkPixbuf *pixbuf = NULL;
8545   GtkTreePath *path;
8546   GtkTreeIter iter;
8547   GCancellable *model_cancellable;
8548   gboolean is_folder = FALSE;
8549   char *mime_type;
8550   char *display_name;
8551   struct SearchHitInsertRequest *request = data;
8552
8553   if (!request->impl->search_model)
8554     goto out;
8555
8556   path = gtk_tree_row_reference_get_path (request->row_ref);
8557   if (!path)
8558     goto out;
8559
8560   gtk_tree_model_get_iter (GTK_TREE_MODEL (request->impl->search_model),
8561                            &iter, path);
8562   gtk_tree_path_free (path);
8563
8564   gtk_tree_model_get (GTK_TREE_MODEL (request->impl->search_model), &iter,
8565                       SEARCH_MODEL_COL_CANCELLABLE, &model_cancellable,
8566                       -1);
8567   if (cancellable != model_cancellable)
8568     goto out;
8569
8570   /* set the cancellable to NULL in the model */
8571   gtk_list_store_set (request->impl->search_model, &iter,
8572                       SEARCH_MODEL_COL_CANCELLABLE, NULL,
8573                       -1);
8574
8575   if (cancelled)
8576     goto out;
8577
8578   if (!info)
8579     {
8580       gtk_list_store_remove (request->impl->search_model, &iter);
8581       goto out;
8582     }
8583
8584   display_name = g_strdup (g_file_info_get_display_name (info));
8585   mime_type = g_strdup (g_file_info_get_content_type (info));
8586   is_folder = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
8587   pixbuf = _gtk_file_info_render_icon (info, GTK_WIDGET (request->impl),
8588                                        request->impl->icon_size);
8589
8590   gtk_list_store_set (request->impl->search_model, &iter,
8591                       SEARCH_MODEL_COL_PIXBUF, pixbuf,
8592                       SEARCH_MODEL_COL_DISPLAY_NAME, display_name,
8593                       SEARCH_MODEL_COL_MIME_TYPE, mime_type,
8594                       SEARCH_MODEL_COL_IS_FOLDER, is_folder,
8595                       -1);
8596
8597   if (pixbuf)
8598     g_object_unref (pixbuf);
8599
8600 out:
8601   g_object_unref (request->impl);
8602   g_object_unref (request->file);
8603   gtk_tree_row_reference_free (request->row_ref);
8604   g_free (request);
8605
8606   g_object_unref (cancellable);
8607 }
8608
8609 /* Adds one hit from the search engine to the search_model */
8610 static void
8611 search_add_hit (GtkFileChooserDefault *impl,
8612                 gchar                 *uri)
8613 {
8614   GFile *file;
8615   char *filename;
8616   char *tmp;
8617   char *collation_key;
8618   struct stat statbuf;
8619   struct stat *statbuf_copy;
8620   GtkTreeIter iter;
8621   GtkTreePath *p;
8622   GCancellable *cancellable;
8623   struct SearchHitInsertRequest *request;
8624
8625   file = g_file_new_for_uri (uri);
8626
8627   if (!g_file_is_native (file))
8628     {
8629       g_object_unref (file);
8630       return;
8631     }
8632
8633   filename = g_file_get_path (file);
8634
8635   if (stat (filename, &statbuf) != 0)
8636     {
8637       g_object_unref (file);
8638       g_free (filename);
8639       return;
8640     }
8641
8642   statbuf_copy = g_new (struct stat, 1);
8643   *statbuf_copy = statbuf;
8644
8645   tmp = g_file_get_parse_name (file);
8646   collation_key = g_utf8_collate_key_for_filename (tmp, -1);
8647   g_free (tmp);
8648
8649   request = g_new0 (struct SearchHitInsertRequest, 1);
8650   request->impl = g_object_ref (impl);
8651   request->file = g_object_ref (file);
8652
8653   gtk_list_store_append (impl->search_model, &iter);
8654   p = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->search_model), &iter);
8655   
8656   request->row_ref = gtk_tree_row_reference_new (GTK_TREE_MODEL (impl->search_model), p);
8657   gtk_tree_path_free (p);
8658
8659   cancellable = _gtk_file_system_get_info (impl->file_system, file,
8660                                            "standard::type,standard::icon,"
8661                                            "standard::content-type,standard::display-name",
8662                                            search_hit_get_info_cb,
8663                                            request);
8664
8665   gtk_list_store_set (impl->search_model, &iter,
8666                       SEARCH_MODEL_COL_FILE, file,
8667                       SEARCH_MODEL_COL_COLLATION_KEY, collation_key,
8668                       SEARCH_MODEL_COL_STAT, statbuf_copy,
8669                       SEARCH_MODEL_COL_CANCELLABLE, cancellable,
8670                       -1);
8671
8672   g_object_unref (file);
8673   g_free (filename);
8674 }
8675
8676 /* Callback used from GtkSearchEngine when we get new hits */
8677 static void
8678 search_engine_hits_added_cb (GtkSearchEngine *engine,
8679                              GList           *hits,
8680                              gpointer         data)
8681 {
8682   GtkFileChooserDefault *impl;
8683   GList *l;
8684   
8685   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8686
8687   for (l = hits; l; l = l->next)
8688     search_add_hit (impl, (gchar*)l->data);
8689 }
8690
8691 /* Callback used from GtkSearchEngine when the query is done running */
8692 static void
8693 search_engine_finished_cb (GtkSearchEngine *engine,
8694                            gpointer         data)
8695 {
8696   GtkFileChooserDefault *impl;
8697   
8698   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8699   
8700 #if 0
8701   /* EB: setting the model here will avoid loads of row events,
8702    * but it'll make the search look like blocked.
8703    */
8704   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
8705                            GTK_TREE_MODEL (impl->search_model_filter));
8706 #endif
8707
8708   /* FMQ: if search was empty, say that we got no hits */
8709   set_busy_cursor (impl, FALSE);
8710 }
8711
8712 /* Displays a generic error when we cannot create a GtkSearchEngine.  
8713  * It would be better if _gtk_search_engine_new() gave us a GError 
8714  * with a better message, but it doesn't do that right now.
8715  */
8716 static void
8717 search_error_could_not_create_client (GtkFileChooserDefault *impl)
8718 {
8719   error_message (impl,
8720                  _("Could not start the search process"),
8721                  _("The program was not able to create a connection to the indexer "
8722                    "daemon.  Please make sure it is running."));
8723 }
8724
8725 static void
8726 search_engine_error_cb (GtkSearchEngine *engine,
8727                         const gchar     *message,
8728                         gpointer         data)
8729 {
8730   GtkFileChooserDefault *impl;
8731   
8732   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8733
8734   search_stop_searching (impl, TRUE);
8735   error_message (impl, _("Could not send the search request"), message);
8736
8737   set_busy_cursor (impl, FALSE);
8738 }
8739
8740 /* Frees the data in the search_model */
8741 static void
8742 search_clear_model (GtkFileChooserDefault *impl, 
8743                     gboolean               remove_from_treeview)
8744 {
8745   GtkTreeModel *model;
8746   GtkTreeIter iter;
8747
8748   if (!impl->search_model)
8749     return;
8750
8751   model = GTK_TREE_MODEL (impl->search_model);
8752
8753   if (gtk_tree_model_get_iter_first (model, &iter))
8754     do
8755       {
8756         GCancellable *cancellable;
8757
8758         gtk_tree_model_get (model, &iter,
8759                             SEARCH_MODEL_COL_CANCELLABLE, &cancellable,
8760                             -1);
8761
8762         if (cancellable)
8763           g_cancellable_cancel (cancellable);
8764       }
8765     while (gtk_tree_model_iter_next (model, &iter));
8766
8767   g_object_unref (impl->search_model);
8768   impl->search_model = NULL;
8769   
8770   g_object_unref (impl->search_model_filter);
8771   impl->search_model_filter = NULL;
8772   
8773   g_object_unref (impl->search_model_sort);
8774   impl->search_model_sort = NULL;
8775
8776   if (remove_from_treeview)
8777     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
8778 }
8779
8780 /* Stops any ongoing searches; does not touch the search_model */
8781 static void
8782 search_stop_searching (GtkFileChooserDefault *impl,
8783                        gboolean               remove_query)
8784 {
8785   if (remove_query && impl->search_query)
8786     {
8787       g_object_unref (impl->search_query);
8788       impl->search_query = NULL;
8789     }
8790   
8791   if (impl->search_engine)
8792     {
8793       _gtk_search_engine_stop (impl->search_engine);
8794       
8795       g_object_unref (impl->search_engine);
8796       impl->search_engine = NULL;
8797     }
8798 }
8799
8800 /* Stops any pending searches, clears the file list, and switches back to OPERATION_MODE_BROWSE */
8801 static void
8802 search_switch_to_browse_mode (GtkFileChooserDefault *impl)
8803 {
8804   g_assert (impl->operation_mode != OPERATION_MODE_BROWSE);
8805
8806   search_stop_searching (impl, FALSE);
8807   search_clear_model (impl, TRUE);
8808
8809   gtk_widget_destroy (impl->search_hbox);
8810   impl->search_hbox = NULL;
8811   impl->search_entry = NULL;
8812
8813   gtk_widget_show (impl->browse_path_bar);
8814   gtk_widget_show (impl->browse_new_folder_button);
8815
8816   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8817       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8818     {
8819       gtk_widget_show (impl->location_button);
8820
8821       if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
8822         gtk_widget_show (impl->location_entry_box);
8823     }
8824
8825   impl->operation_mode = OPERATION_MODE_BROWSE;
8826
8827   file_list_set_sort_column_ids (impl);
8828 }
8829
8830 /* Sort callback from the path column */
8831 static gint
8832 search_column_path_sort_func (GtkTreeModel *model,
8833                               GtkTreeIter  *a,
8834                               GtkTreeIter  *b,
8835                               gpointer      user_data)
8836 {
8837   GtkFileChooserDefault *impl = user_data;
8838   GtkTreeIter child_a, child_b;
8839   const char *collation_key_a, *collation_key_b;
8840   gboolean is_folder_a, is_folder_b;
8841
8842   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_a, a);
8843   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_b, b);
8844
8845   gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_a,
8846                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder_a,
8847                       SEARCH_MODEL_COL_COLLATION_KEY, &collation_key_a,
8848                       -1);
8849   gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_b,
8850                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder_b,
8851                       SEARCH_MODEL_COL_COLLATION_KEY, &collation_key_b,
8852                       -1);
8853
8854   if (!collation_key_a)
8855     return 1;
8856
8857   if (!collation_key_b)
8858     return -1;
8859
8860   /* always show folders first */
8861   if (is_folder_a != is_folder_b)
8862     return is_folder_a ? 1 : -1;
8863
8864   return strcmp (collation_key_a, collation_key_b);
8865 }
8866
8867 /* Sort callback from the modification time column */
8868 static gint
8869 search_column_mtime_sort_func (GtkTreeModel *model,
8870                                GtkTreeIter  *a,
8871                                GtkTreeIter  *b,
8872                                gpointer      user_data)
8873 {
8874   GtkFileChooserDefault *impl = user_data;
8875   GtkTreeIter child_a, child_b;
8876   const struct stat *statbuf_a, *statbuf_b;
8877   gboolean is_folder_a, is_folder_b;
8878
8879   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_a, a);
8880   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_b, b);
8881
8882   /* Note that although we store a whole struct stat in the model, we only
8883    * compare the mtime here.  If we add another column relative to a struct stat
8884    * (e.g. a file size column), we'll want another sort callback similar to this
8885    * one as well.
8886    */
8887   gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_a,
8888                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder_a,
8889                       SEARCH_MODEL_COL_STAT, &statbuf_a,
8890                       -1);
8891   gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_b,
8892                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder_b,
8893                       SEARCH_MODEL_COL_STAT, &statbuf_b,
8894                       -1);
8895   
8896   if (!statbuf_a)
8897     return 1;
8898
8899   if (!statbuf_b)
8900     return -1;
8901
8902   if (is_folder_a != is_folder_b)
8903     return is_folder_a ? 1 : -1;
8904
8905   if (statbuf_a->st_mtime < statbuf_b->st_mtime)
8906     return -1;
8907   else if (statbuf_a->st_mtime > statbuf_b->st_mtime)
8908     return 1;
8909   else
8910     return 0;
8911 }
8912
8913 static gboolean
8914 search_get_is_filtered (GtkFileChooserDefault *impl,
8915                         GFile                 *file,
8916                         const gchar           *display_name,
8917                         const gchar           *mime_type)
8918 {
8919   GtkFileFilterInfo filter_info;
8920   GtkFileFilterFlags needed;
8921   gboolean result;
8922
8923   if (!impl->current_filter)
8924     return FALSE;
8925
8926   filter_info.contains = GTK_FILE_FILTER_DISPLAY_NAME | GTK_FILE_FILTER_MIME_TYPE;
8927   needed = gtk_file_filter_get_needed (impl->current_filter);
8928
8929   filter_info.display_name = display_name;
8930   filter_info.mime_type = mime_type;
8931
8932   if (needed & GTK_FILE_FILTER_FILENAME)
8933     {
8934       filter_info.filename = g_file_get_path (file);
8935       if (filter_info.filename)
8936         filter_info.contains |= GTK_FILE_FILTER_FILENAME;
8937     }
8938   else
8939     filter_info.filename = NULL;
8940
8941   if (needed & GTK_FILE_FILTER_URI)
8942     {
8943       filter_info.uri = g_file_get_uri (file);
8944       if (filter_info.uri)
8945         filter_info.contains |= GTK_FILE_FILTER_URI;
8946     }
8947   else
8948     filter_info.uri = NULL;
8949
8950   result = gtk_file_filter_filter (impl->current_filter, &filter_info);
8951
8952   if (filter_info.filename)
8953     g_free ((gchar *) filter_info.filename);
8954   if (filter_info.uri)
8955     g_free ((gchar *) filter_info.uri);
8956
8957   return !result;
8958
8959 }
8960
8961 /* Visibility function for the recent filter model */
8962 static gboolean
8963 search_model_visible_func (GtkTreeModel *model,
8964                            GtkTreeIter  *iter,
8965                            gpointer      user_data)
8966 {
8967   GtkFileChooserDefault *impl = user_data;
8968   GFile *file;
8969   gchar *display_name, *mime_type;
8970   gboolean is_folder;
8971
8972   if (!impl->current_filter)
8973     return TRUE;
8974
8975   gtk_tree_model_get (model, iter,
8976                       SEARCH_MODEL_COL_FILE, &file,
8977                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
8978                       SEARCH_MODEL_COL_DISPLAY_NAME, &display_name,
8979                       SEARCH_MODEL_COL_MIME_TYPE, &mime_type,
8980                       -1);
8981
8982   if (!display_name)
8983     return TRUE;
8984
8985   if (is_folder)
8986     return TRUE;
8987
8988   return !search_get_is_filtered (impl, file, display_name, mime_type);
8989 }
8990
8991 /* Creates the search_model and puts it in the tree view */
8992 static void
8993 search_setup_model (GtkFileChooserDefault *impl)
8994 {
8995   g_assert (impl->search_model == NULL);
8996   g_assert (impl->search_model_filter == NULL);
8997   g_assert (impl->search_model_sort == NULL);
8998
8999   /* We store these columns in the search model:
9000    *
9001    * SEARCH_MODEL_COL_FILE - a GFile for the hit's URI, stored
9002    *   as a pointer not as a G_TYPE_FILE
9003    * SEARCH_MODEL_COL_DISPLAY_NAME - a string with the display name, stored
9004    *   as a pointer not as a G_TYPE_STRING
9005    * SEARCH_MODEL_COL_COLLATION_KEY - collation key for the filename, stored
9006    *   as a pointer not as a G_TYPE_STRING
9007    * SEARCH_MODEL_COL_STAT - pointer to a struct stat
9008    * SEARCH_MODEL_COL_CANCELLABLE - cancellable used when getting the hit's info
9009    * SEARCH_MODEL_COL_PIXBUF - GdkPixbuf for the hit's icon
9010    * SEARCH_MODEL_COL_MIME_TYPE - a string with the hit's MIME type
9011    * SEARCH_MODEL_COL_IS_FOLDER - a boolean flag for folders
9012    *
9013    * Keep this in sync with the enumeration defined near the beginning
9014    * of this file.
9015    */
9016   impl->search_model = gtk_list_store_new (SEARCH_MODEL_COL_NUM_COLUMNS,
9017                                            G_TYPE_POINTER,
9018                                            G_TYPE_POINTER,
9019                                            G_TYPE_POINTER,
9020                                            G_TYPE_POINTER,
9021                                            G_TYPE_POINTER,
9022                                            GDK_TYPE_PIXBUF,
9023                                            G_TYPE_POINTER,
9024                                            G_TYPE_BOOLEAN);
9025   
9026   impl->search_model_filter =
9027     GTK_TREE_MODEL_FILTER (gtk_tree_model_filter_new (GTK_TREE_MODEL (impl->search_model), NULL));
9028   gtk_tree_model_filter_set_visible_func (impl->search_model_filter,
9029                                           search_model_visible_func,
9030                                           impl, NULL);
9031
9032   impl->search_model_sort =
9033     GTK_TREE_MODEL_SORT (search_model_sort_new (impl, GTK_TREE_MODEL (impl->search_model_filter)));
9034   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model_sort),
9035                                    SEARCH_MODEL_COL_FILE,
9036                                    search_column_path_sort_func,
9037                                    impl, NULL);
9038   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model_sort),
9039                                    SEARCH_MODEL_COL_STAT,
9040                                    search_column_mtime_sort_func,
9041                                    impl, NULL);
9042   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (impl->search_model_sort),
9043                                         SEARCH_MODEL_COL_STAT,
9044                                         GTK_SORT_DESCENDING);
9045
9046   /* EB: setting the model here will make the hits list update feel
9047    * more "alive" than setting the model at the end of the search
9048    * run
9049    */
9050   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9051                            GTK_TREE_MODEL (impl->search_model_sort));
9052 }
9053
9054 static void
9055 search_get_valid_child_iter (GtkFileChooserDefault *impl,
9056                              GtkTreeIter           *child_iter,
9057                              GtkTreeIter           *iter)
9058 {
9059   GtkTreeIter middle;
9060
9061   if (!impl->search_model)
9062     return;
9063
9064   if (!impl->search_model_filter || !impl->search_model_sort)
9065     return;
9066
9067   /* pass 1: get the iterator in the filter model */
9068   gtk_tree_model_sort_convert_iter_to_child_iter (impl->search_model_sort,
9069                                                   &middle, iter);
9070   
9071   /* pass 2: get the iterator in the real model */
9072   gtk_tree_model_filter_convert_iter_to_child_iter (impl->search_model_filter,
9073                                                     child_iter, &middle);
9074 }
9075
9076 /* Creates a new query with the specified text and launches it */
9077 static void
9078 search_start_query (GtkFileChooserDefault *impl,
9079                     const gchar           *query_text)
9080 {
9081   search_stop_searching (impl, FALSE);
9082   search_clear_model (impl, TRUE);
9083   search_setup_model (impl);
9084   set_busy_cursor (impl, TRUE);
9085
9086   if (impl->search_engine == NULL)
9087     impl->search_engine = _gtk_search_engine_new ();
9088
9089   if (!impl->search_engine)
9090     {
9091       set_busy_cursor (impl, FALSE);
9092       search_error_could_not_create_client (impl); /* lame; we don't get an error code or anything */
9093       return;
9094     }
9095
9096   if (!impl->search_query)
9097     {
9098       impl->search_query = _gtk_query_new ();
9099       _gtk_query_set_text (impl->search_query, query_text);
9100     }
9101   
9102   _gtk_search_engine_set_query (impl->search_engine, impl->search_query);
9103
9104   g_signal_connect (impl->search_engine, "hits-added",
9105                     G_CALLBACK (search_engine_hits_added_cb), impl);
9106   g_signal_connect (impl->search_engine, "finished",
9107                     G_CALLBACK (search_engine_finished_cb), impl);
9108   g_signal_connect (impl->search_engine, "error",
9109                     G_CALLBACK (search_engine_error_cb), impl);
9110
9111   _gtk_search_engine_start (impl->search_engine);
9112 }
9113
9114 /* Callback used when the user presses Enter while typing on the search
9115  * entry; starts the query
9116  */
9117 static void
9118 search_entry_activate_cb (GtkEntry *entry,
9119                           gpointer data)
9120 {
9121   GtkFileChooserDefault *impl;
9122   const char *text;
9123
9124   impl = GTK_FILE_CHOOSER_DEFAULT (data);
9125
9126   text = gtk_entry_get_text (GTK_ENTRY (impl->search_entry));
9127   if (strlen (text) == 0)
9128     return;
9129
9130   /* reset any existing query object */
9131   if (impl->search_query)
9132     {
9133       g_object_unref (impl->search_query);
9134       impl->search_query = NULL;
9135     }
9136
9137   search_start_query (impl, text);
9138 }
9139
9140 /* Hides the path bar and creates the search entry */
9141 static void
9142 search_setup_widgets (GtkFileChooserDefault *impl)
9143 {
9144   GtkWidget *label;
9145
9146   impl->search_hbox = gtk_hbox_new (FALSE, 12);
9147
9148   /* Label */
9149
9150   label = gtk_label_new_with_mnemonic (_("_Search:"));
9151   gtk_box_pack_start (GTK_BOX (impl->search_hbox), label, FALSE, FALSE, 0);
9152
9153   /* Entry */
9154
9155   impl->search_entry = gtk_entry_new ();
9156   gtk_label_set_mnemonic_widget (GTK_LABEL (label), impl->search_entry);
9157   g_signal_connect (impl->search_entry, "activate",
9158                     G_CALLBACK (search_entry_activate_cb),
9159                     impl);
9160   gtk_box_pack_start (GTK_BOX (impl->search_hbox), impl->search_entry, TRUE, TRUE, 0);
9161
9162   /* if there already is a query, restart it */
9163   if (impl->search_query)
9164     {
9165       gchar *query = _gtk_query_get_text (impl->search_query);
9166
9167       if (query)
9168         {
9169           gtk_entry_set_text (GTK_ENTRY (impl->search_entry), query);
9170           search_start_query (impl, query);
9171
9172           g_free (query);
9173         }
9174       else
9175         {
9176           g_object_unref (impl->search_query);
9177           impl->search_query = NULL;
9178         }
9179     }
9180
9181   gtk_widget_hide (impl->browse_path_bar);
9182   gtk_widget_hide (impl->browse_new_folder_button);
9183
9184   /* Box for search widgets */
9185   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->search_hbox, TRUE, TRUE, 0);
9186   gtk_widget_show_all (impl->search_hbox);
9187
9188   /* Hide the location widgets temporarily */
9189
9190   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9191       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9192     {
9193       gtk_widget_hide (impl->location_button);
9194       gtk_widget_hide (impl->location_entry_box);
9195     }
9196
9197   gtk_widget_grab_focus (impl->search_entry);
9198
9199   /* FMQ: hide the filter combo? */
9200 }
9201
9202 /* Main entry point to the searching functions; this gets called when the user
9203  * activates the Search shortcut.
9204  */
9205 static void
9206 search_activate (GtkFileChooserDefault *impl)
9207 {
9208   OperationMode previous_mode;
9209   
9210   if (impl->operation_mode == OPERATION_MODE_SEARCH)
9211     {
9212       gtk_widget_grab_focus (impl->search_entry);
9213       return;
9214     }
9215
9216   previous_mode = impl->operation_mode;
9217   impl->operation_mode = OPERATION_MODE_SEARCH;
9218
9219   switch (previous_mode)
9220     {
9221     case OPERATION_MODE_RECENT:
9222       recent_stop_loading (impl);
9223       recent_clear_model (impl, TRUE);
9224       break;
9225
9226     case OPERATION_MODE_BROWSE:
9227       stop_loading_and_clear_list_model (impl);
9228       break;
9229
9230     case OPERATION_MODE_SEARCH:
9231       g_assert_not_reached ();
9232       break;
9233     }
9234
9235   g_assert (impl->search_hbox == NULL);
9236   g_assert (impl->search_entry == NULL);
9237   g_assert (impl->search_model == NULL);
9238   g_assert (impl->search_model_filter == NULL);
9239
9240   search_setup_widgets (impl);
9241   file_list_set_sort_column_ids (impl);
9242 }
9243
9244 /*
9245  * Recent files support
9246  */
9247
9248 /* Frees the data in the recent_model */
9249 static void
9250 recent_clear_model (GtkFileChooserDefault *impl,
9251                     gboolean               remove_from_treeview)
9252 {
9253   GtkTreeModel *model;
9254   GtkTreeIter iter;
9255
9256   if (!impl->recent_model)
9257     return;
9258
9259   model = GTK_TREE_MODEL (impl->recent_model);
9260   
9261   if (remove_from_treeview)
9262     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
9263
9264   if (gtk_tree_model_get_iter_first (model, &iter))
9265     {
9266       do
9267         {
9268           GFile *file;
9269           GCancellable *cancellable;
9270           GtkRecentInfo *recent_info;
9271           gchar *display_name;
9272
9273           gtk_tree_model_get (model, &iter,
9274                               RECENT_MODEL_COL_DISPLAY_NAME, &display_name,
9275                               RECENT_MODEL_COL_FILE, &file,
9276                               RECENT_MODEL_COL_CANCELLABLE, &cancellable,
9277                               RECENT_MODEL_COL_INFO, &recent_info,
9278                               -1);
9279
9280           if (cancellable)
9281             g_cancellable_cancel (cancellable);
9282
9283           g_object_unref (file);
9284           gtk_recent_info_unref (recent_info);
9285           g_free (display_name);
9286         }
9287       while (gtk_tree_model_iter_next (model, &iter));
9288     }
9289
9290   g_object_unref (impl->recent_model);
9291   impl->recent_model = NULL;
9292
9293   g_object_unref (impl->recent_model_filter);
9294   impl->recent_model_filter = NULL;
9295
9296   g_object_unref (impl->recent_model_sort);
9297   impl->recent_model_sort = NULL;
9298 }
9299
9300 /* Stops any ongoing loading of the recent files list; does
9301  * not touch the recent_model
9302  */
9303 static void
9304 recent_stop_loading (GtkFileChooserDefault *impl)
9305 {
9306   if (impl->load_recent_id)
9307     {
9308       g_source_remove (impl->load_recent_id);
9309       impl->load_recent_id = 0;
9310     }
9311 }
9312
9313 /* Stops any pending load, clears the file list, and switches
9314  * back to OPERATION_MODE_BROWSE
9315  */
9316 static void
9317 recent_switch_to_browse_mode (GtkFileChooserDefault *impl)
9318 {
9319   g_assert (impl->operation_mode != OPERATION_MODE_BROWSE);
9320
9321   recent_stop_loading (impl);
9322   recent_clear_model (impl, TRUE);
9323
9324   gtk_widget_show (impl->browse_path_bar);
9325   gtk_widget_show (impl->browse_new_folder_button);
9326
9327   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9328       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9329     {
9330       gtk_widget_show (impl->location_button);
9331
9332       if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
9333         gtk_widget_show (impl->location_entry_box);
9334     }
9335
9336   impl->operation_mode = OPERATION_MODE_BROWSE;
9337
9338   file_list_set_sort_column_ids (impl);
9339 }
9340
9341 /* Sort callback from the modification time column */
9342 static gint
9343 recent_column_mtime_sort_func (GtkTreeModel *model,
9344                                GtkTreeIter  *a,
9345                                GtkTreeIter  *b,
9346                                gpointer      user_data)
9347 {
9348   GtkFileChooserDefault *impl = user_data;
9349   GtkTreeIter child_a, child_b;
9350   GtkRecentInfo *info_a, *info_b;
9351   gboolean is_folder_a, is_folder_b;
9352
9353   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_a, a);
9354   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_b, b);
9355
9356   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_a,
9357                       RECENT_MODEL_COL_IS_FOLDER, &is_folder_a,
9358                       RECENT_MODEL_COL_INFO, &info_a,
9359                       -1);
9360   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_b,
9361                       RECENT_MODEL_COL_IS_FOLDER, &is_folder_b,
9362                       RECENT_MODEL_COL_INFO, &info_b,
9363                       -1);
9364   
9365   if (!info_a)
9366     return 1;
9367
9368   if (!info_b)
9369     return -1;
9370
9371   /* folders always go first */
9372   if (is_folder_a != is_folder_b)
9373     return is_folder_a ? 1 : -1;
9374
9375   if (gtk_recent_info_get_modified (info_a) < gtk_recent_info_get_modified (info_b))
9376     return -1;
9377   else if (gtk_recent_info_get_modified (info_a) > gtk_recent_info_get_modified (info_b))
9378     return 1;
9379   else
9380     return 0;
9381 }
9382
9383 static gint
9384 recent_column_path_sort_func (GtkTreeModel *model,
9385                               GtkTreeIter  *a,
9386                               GtkTreeIter  *b,
9387                               gpointer      user_data)
9388 {
9389   GtkFileChooserDefault *impl = user_data;
9390   GtkTreeIter child_a, child_b;
9391   gboolean is_folder_a, is_folder_b;
9392   gchar *name_a, *name_b;
9393
9394   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_a, a);
9395   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_b, b);
9396
9397   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_a,
9398                       RECENT_MODEL_COL_IS_FOLDER, &is_folder_a,
9399                       RECENT_MODEL_COL_DISPLAY_NAME, &name_a,
9400                       -1);
9401   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_b,
9402                       RECENT_MODEL_COL_IS_FOLDER, &is_folder_b,
9403                       RECENT_MODEL_COL_DISPLAY_NAME, &name_b,
9404                       -1);
9405
9406   if (!name_a)
9407     return 1;
9408
9409   if (!name_b)
9410     return -1;
9411
9412   if (is_folder_a != is_folder_b)
9413     return is_folder_a ? 1 : -1;
9414
9415   return strcmp (name_a, name_b);
9416 }
9417
9418 static gboolean
9419 recent_get_is_filtered (GtkFileChooserDefault *impl,
9420                         GFile                 *file,
9421                         GtkRecentInfo         *recent_info)
9422 {
9423   GtkFileFilterInfo filter_info;
9424   GtkFileFilterFlags needed;
9425   gboolean result;
9426
9427   if (!impl->current_filter)
9428     return FALSE;
9429
9430   filter_info.contains = GTK_FILE_FILTER_DISPLAY_NAME | GTK_FILE_FILTER_MIME_TYPE;
9431   needed = gtk_file_filter_get_needed (impl->current_filter);
9432
9433   filter_info.display_name = gtk_recent_info_get_display_name (recent_info);
9434   filter_info.mime_type = gtk_recent_info_get_mime_type (recent_info);
9435
9436   if (needed & GTK_FILE_FILTER_FILENAME)
9437     {
9438       filter_info.filename = g_file_get_path (file);
9439       if (filter_info.filename)
9440         filter_info.contains |= GTK_FILE_FILTER_FILENAME;
9441     }
9442   else
9443     filter_info.filename = NULL;
9444
9445   if (needed & GTK_FILE_FILTER_URI)
9446     {
9447       filter_info.uri = g_file_get_uri (file);
9448       if (filter_info.uri)
9449         filter_info.contains |= GTK_FILE_FILTER_URI;
9450     }
9451   else
9452     filter_info.uri = NULL;
9453
9454   result = gtk_file_filter_filter (impl->current_filter, &filter_info);
9455
9456   if (filter_info.filename)
9457     g_free ((gchar *) filter_info.filename);
9458   if (filter_info.uri)
9459     g_free ((gchar *) filter_info.uri);
9460
9461   return !result;
9462 }
9463
9464 /* Visibility function for the recent filter model */
9465 static gboolean
9466 recent_model_visible_func (GtkTreeModel *model,
9467                            GtkTreeIter  *iter,
9468                            gpointer      user_data)
9469 {
9470   GtkFileChooserDefault *impl = user_data;
9471   GFile *file;
9472   GtkRecentInfo *recent_info;
9473   gboolean is_folder;
9474
9475   if (!impl->current_filter)
9476     return TRUE;
9477
9478   gtk_tree_model_get (model, iter,
9479                       RECENT_MODEL_COL_INFO, &recent_info,
9480                       RECENT_MODEL_COL_FILE, &file,
9481                       RECENT_MODEL_COL_IS_FOLDER, &is_folder,
9482                       -1);
9483
9484   if (!recent_info)
9485     return TRUE;
9486
9487   if (is_folder)
9488     return TRUE;
9489
9490   return !recent_get_is_filtered (impl, file, recent_info);
9491 }
9492
9493 static void
9494 recent_setup_model (GtkFileChooserDefault *impl)
9495 {
9496   g_assert (impl->recent_model == NULL);
9497   g_assert (impl->recent_model_filter == NULL);
9498   g_assert (impl->recent_model_sort == NULL);
9499
9500   /* We store these columns in the search model:
9501    *
9502    * RECENT_MODEL_COL_FILE - a pointer to GFile for the hit's URI,
9503    *   stored as a pointer and not as a G_TYPE_FILE;
9504    * RECENT_MODEL_COL_DISPLAY_NAME - a string with the display name,
9505    *   stored as a pointer and not as a G_TYPE_STRING;
9506    * RECENT_MODEL_COL_INFO - GtkRecentInfo, stored as a pointer and not
9507    *   as a GTK_TYPE_RECENT_INFO;
9508    * RECENT_MODEL_COL_IS_FOLDER - boolean flag;
9509    * RECENT_MODEL_COL_CANCELLABLE - GCancellable, stored as a pointer
9510    *   and not as a G_TYPE_CANCELLABLE;
9511    *
9512    * Keep this in sync with the enumeration defined near the beginning of
9513    * this file.
9514    */
9515   impl->recent_model = gtk_list_store_new (RECENT_MODEL_COL_NUM_COLUMNS,
9516                                            G_TYPE_POINTER,
9517                                            G_TYPE_POINTER,
9518                                            G_TYPE_POINTER,
9519                                            G_TYPE_BOOLEAN,
9520                                            G_TYPE_POINTER);
9521
9522   impl->recent_model_filter =
9523     GTK_TREE_MODEL_FILTER (gtk_tree_model_filter_new (GTK_TREE_MODEL (impl->recent_model), NULL));
9524   gtk_tree_model_filter_set_visible_func (impl->recent_model_filter,
9525                                           recent_model_visible_func,
9526                                           impl,
9527                                           NULL);
9528   
9529   /* this is the model that will actually be added to
9530    * the browse_files_tree_view widget; remember: we are
9531    * stuffing the real model into a filter model and then
9532    * into a sort model; this means we'll have to translate
9533    * the child iterator *twice* to get from a path or an
9534    * iterator coming from the tree view widget to the
9535    * real data inside the model.
9536    */
9537   impl->recent_model_sort =
9538     GTK_TREE_MODEL_SORT (recent_model_sort_new (impl, GTK_TREE_MODEL (impl->recent_model_filter)));
9539   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model_sort),
9540                                    RECENT_MODEL_COL_FILE,
9541                                    recent_column_path_sort_func,
9542                                    impl, NULL);
9543   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model_sort),
9544                                    RECENT_MODEL_COL_INFO,
9545                                    recent_column_mtime_sort_func,
9546                                    impl, NULL);
9547   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (impl->recent_model_sort),
9548                                         RECENT_MODEL_COL_INFO,
9549                                         GTK_SORT_DESCENDING);
9550 }
9551
9552 typedef struct
9553 {
9554   GtkFileChooserDefault *impl;
9555   GList *items;
9556   gint n_items;
9557   gint n_loaded_items;
9558   guint needs_sorting : 1;
9559 } RecentLoadData;
9560
9561 static void
9562 recent_idle_cleanup (gpointer data)
9563 {
9564   RecentLoadData *load_data = data;
9565   GtkFileChooserDefault *impl = load_data->impl;
9566
9567   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9568                            GTK_TREE_MODEL (impl->recent_model_sort));
9569
9570   set_busy_cursor (impl, FALSE);
9571   
9572   impl->load_recent_id = 0;
9573   
9574   if (load_data->items)
9575     {
9576       g_list_foreach (load_data->items, (GFunc) gtk_recent_info_unref, NULL);
9577       g_list_free (load_data->items);
9578     }
9579
9580   g_free (load_data);
9581 }
9582
9583 struct RecentItemInsertRequest
9584 {
9585   GtkFileChooserDefault *impl;
9586   GFile *file;
9587   GtkTreeRowReference *row_ref;
9588 };
9589
9590 static void
9591 recent_item_get_info_cb (GCancellable *cancellable,
9592                          GFileInfo    *info,
9593                          const GError *error,
9594                          gpointer      data)
9595 {
9596   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
9597   GtkTreePath *path;
9598   GtkTreeIter iter;
9599   GCancellable *model_cancellable;
9600   gboolean is_folder = FALSE;
9601   struct RecentItemInsertRequest *request = data;
9602
9603   if (!request->impl->recent_model)
9604     goto out;
9605
9606   path = gtk_tree_row_reference_get_path (request->row_ref);
9607   if (!path)
9608     goto out;
9609
9610   gtk_tree_model_get_iter (GTK_TREE_MODEL (request->impl->recent_model),
9611                            &iter, path);
9612   gtk_tree_path_free (path);
9613
9614   gtk_tree_model_get (GTK_TREE_MODEL (request->impl->recent_model), &iter,
9615                       RECENT_MODEL_COL_CANCELLABLE, &model_cancellable,
9616                       -1);
9617   if (cancellable != model_cancellable)
9618     goto out;
9619
9620   gtk_list_store_set (request->impl->recent_model, &iter,
9621                       RECENT_MODEL_COL_CANCELLABLE, NULL,
9622                       -1);
9623
9624   if (cancelled)
9625     goto out;
9626
9627   if (!info)
9628     {
9629       gtk_list_store_remove (request->impl->recent_model, &iter);
9630       goto out;
9631     }
9632
9633   is_folder = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
9634
9635   gtk_list_store_set (request->impl->recent_model, &iter,
9636                       RECENT_MODEL_COL_IS_FOLDER, is_folder,
9637                       -1);
9638
9639 out:
9640   g_object_unref (request->impl);
9641   g_object_unref (request->file);
9642   gtk_tree_row_reference_free (request->row_ref);
9643   g_free (request);
9644
9645   g_object_unref (cancellable);
9646 }
9647
9648 static gint
9649 recent_sort_mru (gconstpointer a,
9650                  gconstpointer b)
9651 {
9652   GtkRecentInfo *info_a = (GtkRecentInfo *) a;
9653   GtkRecentInfo *info_b = (GtkRecentInfo *) b;
9654
9655   return (gtk_recent_info_get_modified (info_b) - gtk_recent_info_get_modified (info_a));
9656 }
9657
9658 static gint
9659 get_recent_files_limit (GtkWidget *widget)
9660 {
9661   GtkSettings *settings;
9662   gint limit;
9663
9664   if (gtk_widget_has_screen (widget))
9665     settings = gtk_settings_get_for_screen (gtk_widget_get_screen (widget));
9666   else
9667     settings = gtk_settings_get_default ();
9668
9669   g_object_get (G_OBJECT (settings), "gtk-recent-files-limit", &limit, NULL);
9670
9671   return limit;
9672 }
9673
9674 static gboolean
9675 recent_idle_load (gpointer data)
9676 {
9677   RecentLoadData *load_data = data;
9678   GtkFileChooserDefault *impl = load_data->impl;
9679   GtkTreeIter iter;
9680   GtkTreePath *p;
9681   GtkRecentInfo *info;
9682   const gchar *uri, *display_name;
9683   GFile *file;
9684   GCancellable *cancellable;
9685   struct RecentItemInsertRequest *request;
9686
9687   if (!impl->recent_manager)
9688     return FALSE;
9689
9690   /* first iteration: load all the items */
9691   if (!load_data->items)
9692     {
9693       load_data->items = gtk_recent_manager_get_items (impl->recent_manager);
9694       if (!load_data->items)
9695         return FALSE;
9696
9697       load_data->needs_sorting = TRUE;
9698
9699       return TRUE;
9700     }
9701   
9702   /* second iteration: preliminary MRU sorting and clamping */
9703   if (load_data->needs_sorting)
9704     {
9705       gint limit;
9706
9707       load_data->items = g_list_sort (load_data->items, recent_sort_mru);
9708       load_data->n_items = g_list_length (load_data->items);
9709
9710       limit = get_recent_files_limit (GTK_WIDGET (impl));
9711       
9712       if (limit != -1 && (load_data->n_items > limit))
9713         {
9714           GList *clamp, *l;
9715
9716           clamp = g_list_nth (load_data->items, limit - 1);
9717           if (G_LIKELY (clamp))
9718             {
9719               l = clamp->next;
9720               clamp->next = NULL;
9721
9722               g_list_foreach (l, (GFunc) gtk_recent_info_unref, NULL);
9723               g_list_free (l);
9724
9725               load_data->n_items = limit;
9726             }
9727          }
9728
9729       load_data->n_loaded_items = 0;
9730       load_data->needs_sorting = FALSE;
9731
9732       return TRUE;
9733     }
9734
9735   info = g_list_nth_data (load_data->items, load_data->n_loaded_items);
9736   g_assert (info != NULL);
9737
9738   uri = gtk_recent_info_get_uri (info);
9739   display_name = gtk_recent_info_get_display_name (info);
9740   file = g_file_new_for_uri (uri);
9741
9742   gtk_list_store_append (impl->recent_model, &iter);
9743   p = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->recent_model), &iter);
9744
9745   request = g_new0 (struct RecentItemInsertRequest, 1);
9746   request->impl = g_object_ref (impl);
9747   request->file = g_object_ref (file);
9748   request->row_ref = gtk_tree_row_reference_new (GTK_TREE_MODEL (impl->recent_model), p);
9749   gtk_tree_path_free (p);
9750
9751   cancellable = _gtk_file_system_get_info (impl->file_system, file,
9752                                            "standard::type",
9753                                            recent_item_get_info_cb,
9754                                            request);
9755
9756   gtk_list_store_set (impl->recent_model, &iter,
9757                       RECENT_MODEL_COL_FILE, file,
9758                       RECENT_MODEL_COL_DISPLAY_NAME, g_strdup (display_name),
9759                       RECENT_MODEL_COL_INFO, gtk_recent_info_ref (info),
9760                       RECENT_MODEL_COL_CANCELLABLE, cancellable,
9761                       -1);
9762
9763   load_data->n_loaded_items += 1;
9764
9765   /* finished loading items */
9766   if (load_data->n_loaded_items == load_data->n_items)
9767     {
9768       g_list_foreach (load_data->items, (GFunc) gtk_recent_info_unref, NULL);
9769       g_list_free (load_data->items);
9770       load_data->items = NULL;
9771
9772       return FALSE;
9773     }
9774
9775   return TRUE;
9776 }
9777
9778 static void
9779 recent_start_loading (GtkFileChooserDefault *impl)
9780 {
9781   RecentLoadData *load_data;
9782
9783   recent_stop_loading (impl);
9784   recent_clear_model (impl, TRUE);
9785   recent_setup_model (impl);
9786   set_busy_cursor (impl, TRUE);
9787
9788   g_assert (impl->load_recent_id == 0);
9789
9790   load_data = g_new (RecentLoadData, 1);
9791   load_data->impl = impl;
9792   load_data->items = NULL;
9793   load_data->n_items = 0;
9794   load_data->n_loaded_items = 0;
9795   load_data->needs_sorting = TRUE;
9796
9797   /* begin lazy loading the recent files into the model */
9798   impl->load_recent_id = gdk_threads_add_idle_full (G_PRIORITY_HIGH_IDLE + 30,
9799                                                     recent_idle_load,
9800                                                     load_data,
9801                                                     recent_idle_cleanup);
9802 }
9803
9804 static void
9805 recent_selected_foreach_get_file_cb (GtkTreeModel *model,
9806                                      GtkTreePath  *path,
9807                                      GtkTreeIter  *iter,
9808                                      gpointer      data)
9809 {
9810   GSList **list;
9811   GFile *file;
9812
9813   list = data;
9814
9815   gtk_tree_model_get (model, iter, RECENT_MODEL_COL_FILE, &file, -1);
9816   *list = g_slist_prepend (*list, g_object_ref (file));
9817 }
9818
9819 /* Constructs a list of the selected paths in recent files mode */
9820 static GSList *
9821 recent_get_selected_files (GtkFileChooserDefault *impl)
9822 {
9823   GSList *result;
9824   GtkTreeSelection *selection;
9825
9826   result = NULL;
9827
9828   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9829   gtk_tree_selection_selected_foreach (selection, recent_selected_foreach_get_file_cb, &result);
9830   result = g_slist_reverse (result);
9831
9832   return result;
9833 }
9834
9835 /* Called from ::should_respond().  We return whether there are selected
9836  * files in the recent files list.
9837  */
9838 static gboolean
9839 recent_should_respond (GtkFileChooserDefault *impl)
9840 {
9841   GtkTreeSelection *selection;
9842
9843   g_assert (impl->operation_mode == OPERATION_MODE_RECENT);
9844
9845   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9846   return (gtk_tree_selection_count_selected_rows (selection) != 0);
9847 }
9848
9849 /* Hide the location widgets temporarily */
9850 static void
9851 recent_hide_entry (GtkFileChooserDefault *impl)
9852 {
9853   gtk_widget_hide (impl->browse_path_bar);
9854   gtk_widget_hide (impl->browse_new_folder_button);
9855   
9856   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9857       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9858     {
9859       gtk_widget_hide (impl->location_button);
9860       gtk_widget_hide (impl->location_entry_box);
9861     }
9862 }
9863
9864 /* Main entry point to the recent files functions; this gets called when
9865  * the user activates the Recently Used shortcut.
9866  */
9867 static void
9868 recent_activate (GtkFileChooserDefault *impl)
9869 {
9870   OperationMode previous_mode;
9871
9872   if (impl->operation_mode == OPERATION_MODE_RECENT)
9873     return;
9874
9875   previous_mode = impl->operation_mode;
9876   impl->operation_mode = OPERATION_MODE_RECENT;
9877
9878   switch (previous_mode)
9879     {
9880     case OPERATION_MODE_SEARCH:
9881       search_stop_searching (impl, FALSE);
9882       search_clear_model (impl, TRUE);
9883
9884       gtk_widget_destroy (impl->search_hbox);
9885       impl->search_hbox = NULL;
9886       impl->search_entry = NULL;
9887       break;
9888
9889     case OPERATION_MODE_BROWSE:
9890       stop_loading_and_clear_list_model (impl);
9891       break;
9892
9893     case OPERATION_MODE_RECENT:
9894       g_assert_not_reached ();
9895       break;
9896     }
9897
9898   recent_hide_entry (impl);
9899   file_list_set_sort_column_ids (impl);
9900   recent_start_loading (impl);
9901 }
9902
9903 /* convert an iterator coming from the model bound to 
9904  * browse_files_tree_view to an interator inside the
9905  * real recent_model
9906  */
9907 static void
9908 recent_get_valid_child_iter (GtkFileChooserDefault *impl,
9909                              GtkTreeIter           *child_iter,
9910                              GtkTreeIter           *iter)
9911 {
9912   GtkTreeIter middle;
9913
9914   if (!impl->recent_model)
9915     return;
9916
9917   if (!impl->recent_model_filter || !impl->recent_model_sort)
9918     return;
9919
9920   /* pass 1: get the iterator in the filter model */
9921   gtk_tree_model_sort_convert_iter_to_child_iter (impl->recent_model_sort,
9922                                                   &middle, iter);
9923   
9924   /* pass 2: get the iterator in the real model */
9925   gtk_tree_model_filter_convert_iter_to_child_iter (impl->recent_model_filter,
9926                                                     child_iter,
9927                                                     &middle);
9928 }
9929
9930
9931 static void
9932 set_current_filter (GtkFileChooserDefault *impl,
9933                     GtkFileFilter         *filter)
9934 {
9935   if (impl->current_filter != filter)
9936     {
9937       int filter_index;
9938
9939       /* NULL filters are allowed to reset to non-filtered status
9940        */
9941       filter_index = g_slist_index (impl->filters, filter);
9942       if (impl->filters && filter && filter_index < 0)
9943         return;
9944
9945       if (impl->current_filter)
9946         g_object_unref (impl->current_filter);
9947       impl->current_filter = filter;
9948       if (impl->current_filter)
9949         {
9950           g_object_ref_sink (impl->current_filter);
9951         }
9952
9953       if (impl->filters)
9954         gtk_combo_box_set_active (GTK_COMBO_BOX (impl->filter_combo),
9955                                   filter_index);
9956
9957       if (impl->browse_files_model)
9958         install_list_model_filter (impl);
9959
9960       if (impl->search_model_filter)
9961         gtk_tree_model_filter_refilter (impl->search_model_filter);
9962
9963       if (impl->recent_model_filter)
9964         gtk_tree_model_filter_refilter (impl->recent_model_filter);
9965
9966       g_object_notify (G_OBJECT (impl), "filter");
9967     }
9968 }
9969
9970 static void
9971 filter_combo_changed (GtkComboBox           *combo_box,
9972                       GtkFileChooserDefault *impl)
9973 {
9974   gint new_index = gtk_combo_box_get_active (combo_box);
9975   GtkFileFilter *new_filter = g_slist_nth_data (impl->filters, new_index);
9976
9977   set_current_filter (impl, new_filter);
9978 }
9979
9980 static void
9981 check_preview_change (GtkFileChooserDefault *impl)
9982 {
9983   GtkTreePath *cursor_path;
9984   GFile *new_file;
9985   const char *new_display_name;
9986
9987   gtk_tree_view_get_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view), &cursor_path, NULL);
9988   new_file = NULL;
9989   new_display_name = NULL;
9990   if (cursor_path)
9991     {
9992       GtkTreeIter child_iter;
9993
9994       if (impl->operation_mode == OPERATION_MODE_BROWSE)
9995         {
9996           if (impl->sort_model)
9997             {
9998               GtkTreeIter iter;
9999               GFileInfo *new_info;
10000
10001               gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->sort_model), &iter, cursor_path);
10002               gtk_tree_path_free (cursor_path);
10003
10004               gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model, &child_iter, &iter);
10005
10006               new_file = _gtk_file_system_model_get_file (impl->browse_files_model, &child_iter);
10007               new_info = _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
10008               if (new_info)
10009                 new_display_name = g_file_info_get_display_name (new_info);
10010             }
10011         }
10012       else if (impl->operation_mode == OPERATION_MODE_SEARCH)
10013         {
10014           GtkTreeIter iter;
10015
10016           gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->search_model_sort),
10017                                    &iter, cursor_path);
10018           gtk_tree_path_free (cursor_path);
10019
10020           search_get_valid_child_iter (impl, &child_iter, &iter);
10021           gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10022                               SEARCH_MODEL_COL_FILE, &new_file,
10023                               SEARCH_MODEL_COL_DISPLAY_NAME, &new_display_name,
10024                               -1);
10025         }
10026       else if (impl->operation_mode == OPERATION_MODE_RECENT)
10027         {
10028           GtkTreeIter iter;
10029
10030           gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->recent_model_sort),
10031                                    &iter, cursor_path);
10032           gtk_tree_path_free (cursor_path);
10033
10034           recent_get_valid_child_iter (impl, &child_iter, &iter);
10035           gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10036                               RECENT_MODEL_COL_FILE, &new_file,
10037                               RECENT_MODEL_COL_DISPLAY_NAME, &new_display_name,
10038                               -1);
10039         }
10040     }
10041
10042   if (new_file != impl->preview_file &&
10043       !(new_file && impl->preview_file &&
10044         g_file_equal (new_file, impl->preview_file)))
10045     {
10046       if (impl->preview_file)
10047         {
10048           g_object_unref (impl->preview_file);
10049           g_free (impl->preview_display_name);
10050         }
10051
10052       if (new_file)
10053         {
10054           impl->preview_file = g_object_ref (new_file);
10055           impl->preview_display_name = g_strdup (new_display_name);
10056         }
10057       else
10058         {
10059           impl->preview_file = NULL;
10060           impl->preview_display_name = NULL;
10061         }
10062
10063       if (impl->use_preview_label && impl->preview_label)
10064         gtk_label_set_text (GTK_LABEL (impl->preview_label), impl->preview_display_name);
10065
10066       g_signal_emit_by_name (impl, "update-preview");
10067     }
10068 }
10069
10070 static void
10071 shortcuts_activate_volume_mount_cb (GCancellable        *cancellable,
10072                                     GtkFileSystemVolume *volume,
10073                                     const GError        *error,
10074                                     gpointer             data)
10075 {
10076   GFile *file;
10077   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
10078   GtkFileChooserDefault *impl = data;
10079
10080   if (cancellable != impl->shortcuts_activate_iter_cancellable)
10081     goto out;
10082
10083   impl->shortcuts_activate_iter_cancellable = NULL;
10084
10085   set_busy_cursor (impl, FALSE);
10086
10087   if (cancelled)
10088     goto out;
10089
10090   if (error)
10091     {
10092       if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED))
10093         {
10094           char *msg, *name;
10095
10096           name = _gtk_file_system_volume_get_display_name (volume);
10097           msg = g_strdup_printf (_("Could not mount %s"), name);
10098
10099           error_message (impl, msg, error->message);
10100
10101           g_free (msg);
10102           g_free (name);
10103         }
10104
10105       goto out;
10106     }
10107
10108   file = _gtk_file_system_volume_get_root (volume);
10109   if (file != NULL)
10110     {
10111       change_folder_and_display_error (impl, file, FALSE);
10112       g_object_unref (file);
10113     }
10114
10115 out:
10116   g_object_unref (impl);
10117   g_object_unref (cancellable);
10118 }
10119
10120
10121 /* Activates a volume by mounting it if necessary and then switching to its
10122  * base path.
10123  */
10124 static void
10125 shortcuts_activate_volume (GtkFileChooserDefault *impl,
10126                            GtkFileSystemVolume   *volume)
10127 {
10128   GFile *file;
10129
10130   switch (impl->operation_mode)
10131     {
10132     case OPERATION_MODE_BROWSE:
10133       break;
10134     case OPERATION_MODE_SEARCH:
10135       search_switch_to_browse_mode (impl);
10136       break;
10137     case OPERATION_MODE_RECENT:
10138       recent_switch_to_browse_mode (impl);
10139       break;
10140     }
10141
10142   /* We ref the file chooser since volume_mount() may run a main loop, and the
10143    * user could close the file chooser window in the meantime.
10144    */
10145   g_object_ref (impl);
10146
10147   if (!_gtk_file_system_volume_is_mounted (volume))
10148     {
10149       set_busy_cursor (impl, TRUE);
10150
10151       impl->shortcuts_activate_iter_cancellable =
10152         _gtk_file_system_mount_volume (impl->file_system, volume, NULL,
10153                                        shortcuts_activate_volume_mount_cb,
10154                                        g_object_ref (impl));
10155     }
10156   else
10157     {
10158       file = _gtk_file_system_volume_get_root (volume);
10159       if (file != NULL)
10160         {
10161           change_folder_and_display_error (impl, file, FALSE);
10162           g_object_unref (file);
10163         }
10164     }
10165
10166   g_object_unref (impl);
10167 }
10168
10169 /* Opens the folder or volume at the specified iter in the shortcuts model */
10170 struct ShortcutsActivateData
10171 {
10172   GtkFileChooserDefault *impl;
10173   GFile *file;
10174 };
10175
10176 static void
10177 shortcuts_activate_get_info_cb (GCancellable *cancellable,
10178                                 GFileInfo    *info,
10179                                 const GError *error,
10180                                 gpointer      user_data)
10181 {
10182   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
10183   struct ShortcutsActivateData *data = user_data;
10184
10185   if (cancellable != data->impl->shortcuts_activate_iter_cancellable)
10186     goto out;
10187
10188   data->impl->shortcuts_activate_iter_cancellable = NULL;
10189
10190   if (cancelled)
10191     goto out;
10192
10193   if (!error && g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
10194     change_folder_and_display_error (data->impl, data->file, FALSE);
10195   else
10196     gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (data->impl),
10197                                           data->file,
10198                                           NULL);
10199
10200 out:
10201   g_object_unref (data->impl);
10202   g_object_unref (data->file);
10203   g_free (data);
10204
10205   g_object_unref (cancellable);
10206 }
10207
10208 static void
10209 shortcuts_activate_mount_enclosing_volume (GCancellable        *cancellable,
10210                                            GtkFileSystemVolume *volume,
10211                                            const GError        *error,
10212                                            gpointer             user_data)
10213 {
10214   struct ShortcutsActivateData *data = user_data;
10215
10216   if (error)
10217     {
10218       error_changing_folder_dialog (data->impl, data->file, g_error_copy (error));
10219
10220       g_object_unref (data->impl);
10221       g_object_unref (data->file);
10222       g_free (data);
10223
10224       return;
10225     }
10226
10227   data->impl->shortcuts_activate_iter_cancellable =
10228     _gtk_file_system_get_info (data->impl->file_system, data->file,
10229                                "standard::type",
10230                                shortcuts_activate_get_info_cb, data);
10231 }
10232
10233 static void
10234 shortcuts_activate_iter (GtkFileChooserDefault *impl,
10235                          GtkTreeIter           *iter)
10236 {
10237   gpointer col_data;
10238   ShortcutType shortcut_type;
10239
10240   if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY
10241       && !(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
10242            || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
10243     _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
10244
10245   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), iter,
10246                       SHORTCUTS_COL_DATA, &col_data,
10247                       SHORTCUTS_COL_TYPE, &shortcut_type,
10248                       -1);
10249
10250   if (impl->shortcuts_activate_iter_cancellable)
10251     {
10252       g_cancellable_cancel (impl->shortcuts_activate_iter_cancellable);
10253       impl->shortcuts_activate_iter_cancellable = NULL;
10254     }
10255
10256   if (shortcut_type == SHORTCUT_TYPE_SEPARATOR)
10257     return;
10258   else if (shortcut_type == SHORTCUT_TYPE_VOLUME)
10259     {
10260       GtkFileSystemVolume *volume;
10261
10262       volume = col_data;
10263
10264       shortcuts_activate_volume (impl, volume);
10265     }
10266   else if (shortcut_type == SHORTCUT_TYPE_FILE)
10267     {
10268       struct ShortcutsActivateData *data;
10269       GtkFileSystemVolume *volume;
10270
10271       volume = _gtk_file_system_get_volume_for_file (impl->file_system, col_data);
10272
10273       data = g_new0 (struct ShortcutsActivateData, 1);
10274       data->impl = g_object_ref (impl);
10275       data->file = g_object_ref (col_data);
10276
10277       if (!volume || !_gtk_file_system_volume_is_mounted (volume))
10278         {
10279           GMountOperation *mount_operation;
10280           GtkWidget *toplevel;
10281
10282           toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
10283
10284           mount_operation = gtk_mount_operation_new (GTK_WINDOW (toplevel));
10285
10286           impl->shortcuts_activate_iter_cancellable =
10287             _gtk_file_system_mount_enclosing_volume (impl->file_system, col_data,
10288                                                      mount_operation,
10289                                                      shortcuts_activate_mount_enclosing_volume,
10290                                                      data);
10291         }
10292       else
10293         {
10294           impl->shortcuts_activate_iter_cancellable =
10295             _gtk_file_system_get_info (impl->file_system, data->file,
10296                                        "standard::type",
10297                                        shortcuts_activate_get_info_cb, data);
10298         }
10299     }
10300   else if (shortcut_type == SHORTCUT_TYPE_SEARCH)
10301     {
10302       search_activate (impl);
10303     }
10304   else if (shortcut_type == SHORTCUT_TYPE_RECENT)
10305     {
10306       recent_activate (impl);
10307     }
10308 }
10309
10310 /* Handler for GtkWidget::key-press-event on the shortcuts list */
10311 static gboolean
10312 shortcuts_key_press_event_cb (GtkWidget             *widget,
10313                               GdkEventKey           *event,
10314                               GtkFileChooserDefault *impl)
10315 {
10316   guint modifiers;
10317
10318   modifiers = gtk_accelerator_get_default_mod_mask ();
10319
10320   if ((event->keyval == GDK_BackSpace
10321       || event->keyval == GDK_Delete
10322       || event->keyval == GDK_KP_Delete)
10323       && (event->state & modifiers) == 0)
10324     {
10325       remove_selected_bookmarks (impl);
10326       return TRUE;
10327     }
10328
10329   if ((event->keyval == GDK_F2)
10330       && (event->state & modifiers) == 0)
10331     {
10332       rename_selected_bookmark (impl);
10333       return TRUE;
10334     }
10335
10336   return FALSE;
10337 }
10338
10339 static gboolean
10340 shortcuts_select_func  (GtkTreeSelection  *selection,
10341                         GtkTreeModel      *model,
10342                         GtkTreePath       *path,
10343                         gboolean           path_currently_selected,
10344                         gpointer           data)
10345 {
10346   GtkFileChooserDefault *impl = data;
10347   GtkTreeIter filter_iter;
10348   ShortcutType shortcut_type;
10349
10350   if (!gtk_tree_model_get_iter (impl->shortcuts_pane_filter_model, &filter_iter, path))
10351     g_assert_not_reached ();
10352
10353   gtk_tree_model_get (impl->shortcuts_pane_filter_model, &filter_iter, SHORTCUTS_COL_TYPE, &shortcut_type, -1);
10354
10355   return shortcut_type != SHORTCUT_TYPE_SEPARATOR;
10356 }
10357
10358 static gboolean
10359 list_select_func  (GtkTreeSelection  *selection,
10360                    GtkTreeModel      *model,
10361                    GtkTreePath       *path,
10362                    gboolean           path_currently_selected,
10363                    gpointer           data)
10364 {
10365   GtkFileChooserDefault *impl = data;
10366
10367   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10368       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10369     {
10370       GtkTreeIter iter, child_iter;
10371
10372       switch (impl->operation_mode)
10373         {
10374         case OPERATION_MODE_SEARCH:
10375           {
10376             gboolean is_folder;
10377
10378             if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->search_model_sort), &iter, path))
10379               return FALSE;
10380
10381             search_get_valid_child_iter (impl, &child_iter, &iter);
10382             gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10383                                 SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10384                                 -1);
10385             if (!is_folder)
10386               return FALSE;
10387           }
10388           break;
10389
10390         case OPERATION_MODE_RECENT:
10391           {
10392             gboolean is_folder;
10393
10394             if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->recent_model_sort), &iter, path))
10395               return FALSE;
10396
10397             recent_get_valid_child_iter (impl, &child_iter, &iter);
10398             gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10399                                 RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10400                                 -1);
10401             if (!is_folder)
10402               return FALSE;
10403           }
10404           break;
10405
10406         case OPERATION_MODE_BROWSE:
10407           {
10408             GFileInfo *info;
10409
10410             if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->sort_model), &iter, path))
10411               return FALSE;
10412
10413             gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model, &child_iter, &iter);
10414             info = _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
10415             if (info && g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY)
10416               return FALSE;
10417           }
10418           break;
10419         }
10420     }
10421     
10422   return TRUE;
10423 }
10424
10425 static void
10426 list_selection_changed (GtkTreeSelection      *selection,
10427                         GtkFileChooserDefault *impl)
10428 {
10429   /* See if we are in the new folder editable row for Save mode */
10430   if (impl->operation_mode == OPERATION_MODE_BROWSE &&
10431       impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
10432     {
10433       GFileInfo *info;
10434       gboolean had_selection;
10435
10436       info = get_selected_file_info_from_file_list (impl, &had_selection);
10437       if (!had_selection)
10438         goto out; /* normal processing */
10439
10440       if (!info)
10441         return; /* We are on the editable row for New Folder */
10442     }
10443
10444  out:
10445
10446   if (impl->location_entry)
10447     update_chooser_entry (impl);
10448
10449   check_preview_change (impl);
10450   bookmarks_check_add_sensitivity (impl);
10451
10452   g_signal_emit_by_name (impl, "selection-changed", 0);
10453 }
10454
10455 /* Callback used when a row in the file list is activated */
10456 static void
10457 list_row_activated (GtkTreeView           *tree_view,
10458                     GtkTreePath           *path,
10459                     GtkTreeViewColumn     *column,
10460                     GtkFileChooserDefault *impl)
10461 {
10462   GtkTreeIter iter;
10463   GtkTreeIter child_iter;
10464
10465   switch (impl->operation_mode)
10466     {
10467     case OPERATION_MODE_SEARCH:
10468       {
10469         GFile *file;
10470         gboolean is_folder;
10471
10472         if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->search_model_sort), &iter, path))
10473           return;
10474
10475         search_get_valid_child_iter (impl, &child_iter, &iter);
10476         gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10477                             SEARCH_MODEL_COL_FILE, &file,
10478                             SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10479                             -1);
10480         
10481         if (is_folder)
10482           {
10483             change_folder_and_display_error (impl, file, FALSE);
10484             return;
10485           }
10486
10487         g_signal_emit_by_name (impl, "file-activated");
10488       }
10489       break;
10490
10491     case OPERATION_MODE_RECENT:
10492       {
10493         GFile *file;
10494         gboolean is_folder;
10495
10496         if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->recent_model_sort), &iter, path))
10497           return;
10498         
10499         recent_get_valid_child_iter (impl, &child_iter, &iter);
10500         gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10501                             RECENT_MODEL_COL_FILE, &file,
10502                             RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10503                             -1);
10504
10505         if (is_folder)
10506           {
10507             change_folder_and_display_error (impl, file, FALSE);
10508             return;
10509           }
10510         
10511         g_signal_emit_by_name (impl, "file-activated");
10512       }
10513       break;
10514     
10515     case OPERATION_MODE_BROWSE:
10516       {
10517         GFileInfo *info;
10518
10519         if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->sort_model), &iter, path))
10520           return;
10521         
10522         gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
10523                                                         &child_iter, &iter);
10524         info = _gtk_file_system_model_get_info (impl->browse_files_model,
10525                                                 &child_iter);
10526
10527         if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
10528           {
10529             GFile *file;
10530
10531             file = _gtk_file_system_model_get_file (impl->browse_files_model, &child_iter);
10532             change_folder_and_display_error (impl, file, FALSE);
10533             return;
10534           }
10535
10536         if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
10537             impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
10538           g_signal_emit_by_name (impl, "file-activated");
10539       }
10540       break;
10541     }
10542 }
10543
10544 static void
10545 path_bar_clicked (GtkPathBar            *path_bar,
10546                   GFile                 *file,
10547                   GFile                 *child_file,
10548                   gboolean               child_is_hidden,
10549                   GtkFileChooserDefault *impl)
10550 {
10551   if (child_file)
10552     pending_select_files_add (impl, child_file);
10553
10554   if (!change_folder_and_display_error (impl, file, FALSE))
10555     return;
10556
10557   /* Say we have "/foo/bar/[.baz]" and the user clicks on "bar".  We should then
10558    * show hidden files so that ".baz" appears in the file list, as it will still
10559    * be shown in the path bar: "/foo/[bar]/.baz"
10560    */
10561   if (child_is_hidden)
10562     g_object_set (impl, "show-hidden", TRUE, NULL);
10563 }
10564
10565 static GFileInfo *
10566 get_list_file_info (GtkFileChooserDefault *impl,
10567                     GtkTreeIter           *iter)
10568 {
10569   GtkTreeIter child_iter;
10570
10571   gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
10572                                                   &child_iter,
10573                                                   iter);
10574
10575   return _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
10576 }
10577
10578 static void
10579 list_icon_data_func (GtkTreeViewColumn *tree_column,
10580                      GtkCellRenderer   *cell,
10581                      GtkTreeModel      *tree_model,
10582                      GtkTreeIter       *iter,
10583                      gpointer           data)
10584 {
10585   GtkFileChooserDefault *impl = data;
10586   GtkTreeIter child_iter;
10587   GdkPixbuf *pixbuf = NULL;
10588   gboolean sensitive = TRUE;
10589
10590   profile_start ("start", NULL);
10591   
10592   switch (impl->operation_mode)
10593     {
10594     case OPERATION_MODE_SEARCH:
10595       {
10596         GtkTreeIter child_iter;
10597         gboolean is_folder;
10598
10599         search_get_valid_child_iter (impl, &child_iter, iter);
10600         gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10601                             SEARCH_MODEL_COL_PIXBUF, &pixbuf,
10602                             SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10603                             -1);
10604         
10605         if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10606             impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10607           sensitive = is_folder;
10608       }
10609       break;
10610
10611     case OPERATION_MODE_RECENT:
10612       {
10613         GtkTreeIter child_iter;
10614         GtkRecentInfo *info;
10615         gboolean is_folder;
10616
10617         recent_get_valid_child_iter (impl, &child_iter, iter);
10618         gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10619                             RECENT_MODEL_COL_INFO, &info,
10620                             RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10621                             -1);
10622         
10623         pixbuf = gtk_recent_info_get_icon (info, impl->icon_size);
10624       
10625         if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER || 
10626             impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10627           sensitive = is_folder;
10628       }
10629       break;
10630     
10631     case OPERATION_MODE_BROWSE:
10632       {
10633         GFileInfo *info;
10634         GFile *file;
10635
10636         info = get_list_file_info (impl, iter);
10637
10638         gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
10639                                                         &child_iter,
10640                                                         iter);
10641         file = _gtk_file_system_model_get_file (impl->browse_files_model, &child_iter);
10642         if (file)
10643           {
10644             if (info)
10645               {
10646                 /* FIXME: NULL GError */
10647                 pixbuf = _gtk_file_info_render_icon (info, GTK_WIDGET (impl), impl->icon_size);
10648               }
10649           }
10650         else
10651           {
10652             /* We are on the editable row */
10653             pixbuf = NULL;
10654           }
10655
10656         if (info &&
10657             (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10658              impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
10659           sensitive = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
10660       }
10661       break;
10662     }
10663     
10664   g_object_set (cell,
10665                 "pixbuf", pixbuf,
10666                 "sensitive", sensitive,
10667                 NULL);
10668     
10669   if (pixbuf)
10670     g_object_unref (pixbuf);
10671
10672   profile_end ("end", NULL);
10673 }
10674
10675 static void
10676 list_name_data_func (GtkTreeViewColumn *tree_column,
10677                      GtkCellRenderer   *cell,
10678                      GtkTreeModel      *tree_model,
10679                      GtkTreeIter       *iter,
10680                      gpointer           data)
10681 {
10682   GtkFileChooserDefault *impl = data;
10683   GFileInfo *info;
10684   gboolean sensitive = TRUE;
10685
10686   if (impl->operation_mode == OPERATION_MODE_SEARCH)
10687     {
10688       GtkTreeIter child_iter;
10689       gchar *display_name;
10690       gboolean is_folder;
10691
10692       search_get_valid_child_iter (impl, &child_iter, iter);
10693       gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10694                           SEARCH_MODEL_COL_DISPLAY_NAME, &display_name,
10695                           SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10696                           -1);
10697
10698       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10699           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10700         {
10701           sensitive = is_folder;
10702         }
10703
10704       g_object_set (cell,
10705                     "text", display_name,
10706                     "sensitive", sensitive,
10707                     "ellipsize", PANGO_ELLIPSIZE_END,
10708                     NULL);
10709       
10710       return;
10711     }
10712
10713   if (impl->operation_mode == OPERATION_MODE_RECENT)
10714     {
10715       GtkTreeIter child_iter;
10716       GtkRecentInfo *recent_info;
10717       gchar *display_name;
10718       gboolean is_folder;
10719
10720       recent_get_valid_child_iter (impl, &child_iter, iter);
10721       gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10722                           RECENT_MODEL_COL_INFO, &recent_info,
10723                           RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10724                           -1);
10725       
10726       display_name = gtk_recent_info_get_short_name (recent_info);
10727
10728       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10729           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10730         {
10731           sensitive = is_folder;
10732         }
10733
10734       g_object_set (cell,
10735                     "text", display_name,
10736                     "sensitive", sensitive,
10737                     "ellipsize", PANGO_ELLIPSIZE_END,
10738                     NULL);
10739
10740       g_free (display_name);
10741
10742       return;
10743     }
10744
10745   info = get_list_file_info (impl, iter);
10746   sensitive = TRUE;
10747
10748   if (!info)
10749     {
10750       g_object_set (cell,
10751                     "text", _("Type name of new folder"),
10752                     "sensitive", TRUE,
10753                     "ellipsize", PANGO_ELLIPSIZE_NONE,
10754                     NULL);
10755
10756       return;
10757     }
10758
10759
10760   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10761       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10762     {
10763       sensitive = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
10764     }
10765
10766   g_object_set (cell,
10767                 "text", g_file_info_get_display_name (info),
10768                 "sensitive", sensitive,
10769                 "ellipsize", PANGO_ELLIPSIZE_END,
10770                 NULL);
10771 }
10772
10773 #if 0
10774 static void
10775 list_size_data_func (GtkTreeViewColumn *tree_column,
10776                      GtkCellRenderer   *cell,
10777                      GtkTreeModel      *tree_model,
10778                      GtkTreeIter       *iter,
10779                      gpointer           data)
10780 {
10781   GtkFileChooserDefault *impl = data;
10782   GFileInfo *info = get_list_file_info (impl, iter);
10783   gint64 size;
10784   gchar *str;
10785   gboolean sensitive = TRUE;
10786
10787   if (!info || g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
10788     {
10789       g_object_set (cell,
10790                     "text", NULL,
10791                     "sensitive", sensitive,
10792                     NULL);
10793       return;
10794     }
10795
10796   size = gtk_file_info_get_size (info);
10797 #if 0
10798   if (size < (gint64)1024)
10799     str = g_strdup_printf (g_dngettext (GETTEXT_DOMAIN, "%d byte", "%d bytes", (gint)size), (gint)size);
10800   else if (size < (gint64)1024*1024)
10801     str = g_strdup_printf (_("%.1f KB"), size / (1024.));
10802   else if (size < (gint64)1024*1024*1024)
10803     str = g_strdup_printf (_("%.1f MB"), size / (1024.*1024.));
10804   else
10805     str = g_strdup_printf (_("%.1f GB"), size / (1024.*1024.*1024.));
10806 #endif
10807   str = g_strdup_printf ("%" G_GINT64_FORMAT, size);
10808   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10809       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10810     sensitive = FALSE;
10811
10812   g_object_set (cell,
10813                 "text", str,
10814                 "sensitive", sensitive,
10815                 "alignment", PANGO_ALIGN_RIGHT,
10816                 NULL);
10817
10818   g_free (str);
10819 }
10820 #endif
10821
10822 /* Tree column data callback for the file list; fetches the mtime of a file */
10823 static void
10824 list_mtime_data_func (GtkTreeViewColumn *tree_column,
10825                       GtkCellRenderer   *cell,
10826                       GtkTreeModel      *tree_model,
10827                       GtkTreeIter       *iter,
10828                       gpointer           data)
10829 {
10830   GtkFileChooserDefault *impl;
10831   GTimeVal timeval = { 0, };
10832   time_t time_mtime;
10833   gchar *date_str = NULL;
10834   gboolean sensitive = TRUE;
10835 #ifdef G_OS_WIN32
10836   const char *locale, *dot = NULL;
10837   gint64 codepage = -1;
10838   char charset[20];
10839 #endif
10840
10841   impl = data;
10842
10843   if (impl->operation_mode == OPERATION_MODE_SEARCH)
10844     {
10845       GtkTreeIter child_iter;
10846       struct stat *statbuf;
10847       gboolean is_folder;
10848
10849       search_get_valid_child_iter (impl, &child_iter, iter);
10850       gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10851                           SEARCH_MODEL_COL_STAT, &statbuf,
10852                           SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10853                           -1);
10854       if (statbuf)
10855         time_mtime = statbuf->st_mtime;
10856       else
10857         time_mtime = 0;
10858
10859
10860       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10861           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10862         sensitive = is_folder;
10863     }
10864   else if (impl->operation_mode == OPERATION_MODE_RECENT)
10865     {
10866       GtkTreeIter child_iter;
10867       GtkRecentInfo *info;
10868       gboolean is_folder;
10869
10870       recent_get_valid_child_iter (impl, &child_iter, iter);
10871       gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10872                           RECENT_MODEL_COL_INFO, &info,
10873                           RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10874                           -1);
10875
10876       if (info)
10877         time_mtime = gtk_recent_info_get_modified (info);
10878       else
10879         time_mtime = 0;
10880
10881       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10882           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10883         sensitive = is_folder;
10884     }
10885   else
10886     {
10887       GFileInfo *info;
10888
10889       info = get_list_file_info (impl, iter);
10890       if (!info)
10891         {
10892           g_object_set (cell,
10893                         "text", "",
10894                         "sensitive", TRUE,
10895                         NULL);
10896           return;
10897         }
10898
10899       g_file_info_get_modification_time (info, &timeval);
10900       time_mtime = timeval.tv_sec;
10901
10902       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10903           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10904         sensitive = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
10905     }
10906
10907   if (G_UNLIKELY (time_mtime == 0))
10908     date_str = g_strdup (_("Unknown"));
10909   else
10910     {
10911       GDate mtime, now;
10912       gint days_diff;
10913       struct tm tm_mtime;
10914       time_t time_now;
10915       const gchar *format;
10916       gchar *locale_format = NULL;
10917       gchar buf[256];
10918
10919 #ifdef HAVE_LOCALTIME_R
10920       localtime_r ((time_t *) &time_mtime, &tm_mtime);
10921 #else
10922       {
10923         struct tm *ptm = localtime ((time_t *) &timeval.tv_sec);
10924
10925         if (!ptm)
10926           {
10927             g_warning ("ptm != NULL failed");
10928             
10929             g_object_set (cell,
10930                           "text", _("Unknown"),
10931                           "sensitive", sensitive,
10932                           NULL);
10933             return;
10934           }
10935         else
10936           memcpy ((void *) &tm_mtime, (void *) ptm, sizeof (struct tm));
10937       }
10938 #endif /* HAVE_LOCALTIME_R */
10939
10940       g_date_set_time_t (&mtime, time_mtime);
10941       time_now = time (NULL);
10942       g_date_set_time_t (&now, time_now);
10943
10944       days_diff = g_date_get_julian (&now) - g_date_get_julian (&mtime);
10945
10946       /* Translators: %H means "hours" and %M means "minutes" */
10947       if (days_diff == 0)
10948         format = _("%H:%M");
10949       else if (days_diff == 1)
10950         format = _("Yesterday at %H:%M");
10951       else
10952         {
10953           if (days_diff > 1 && days_diff < 7)
10954             format = "%A"; /* Days from last week */
10955           else
10956             format = "%x"; /* Any other date */
10957         }
10958
10959 #ifdef G_OS_WIN32
10960       /* g_locale_from_utf8() returns a string in the system
10961        * code-page, which is not always the same as that used by the C
10962        * library. For instance when running a GTK+ program with
10963        * LANG=ko on an English version of Windows, the system
10964        * code-page is 1252, but the code-page used by the C library is
10965        * 949. (It's GTK+ itself that sets the C library locale when it
10966        * notices the LANG environment variable. See gtkmain.c The
10967        * Microsoft C library doesn't look at any locale environment
10968        * variables.) We need to pass strftime() a string in the C
10969        * library's code-page. See bug #509885.
10970        */
10971       locale = setlocale (LC_ALL, NULL);
10972       if (locale != NULL)
10973         dot = strchr (locale, '.');
10974       if (dot != NULL)
10975         {
10976           codepage = g_ascii_strtoll (dot+1, NULL, 10);
10977           
10978           /* All codepages should fit in 16 bits AFAIK */
10979           if (codepage > 0 && codepage < 65536)
10980             {
10981               sprintf (charset, "CP%u", (guint) codepage);
10982               locale_format = g_convert (format, -1, charset, "UTF-8", NULL, NULL, NULL);
10983             }
10984         }
10985 #else
10986       locale_format = g_locale_from_utf8 (format, -1, NULL, NULL, NULL);
10987 #endif
10988       if (locale_format != NULL &&
10989           strftime (buf, sizeof (buf), locale_format, &tm_mtime) != 0)
10990         {
10991 #ifdef G_OS_WIN32
10992           /* As above but in opposite direction... */
10993           if (codepage > 0 && codepage < 65536)
10994             date_str = g_convert (buf, -1, "UTF-8", charset, NULL, NULL, NULL);
10995 #else
10996           date_str = g_locale_to_utf8 (buf, -1, NULL, NULL, NULL);
10997 #endif
10998         }
10999
11000       if (date_str == NULL)
11001         date_str = g_strdup (_("Unknown"));
11002
11003       g_free (locale_format);
11004     }
11005
11006   g_object_set (cell,
11007                 "text", date_str,
11008                 "sensitive", sensitive,
11009                 NULL);
11010   g_free (date_str);
11011 }
11012
11013 GtkWidget *
11014 _gtk_file_chooser_default_new (void)
11015 {
11016   return g_object_new (GTK_TYPE_FILE_CHOOSER_DEFAULT, NULL);
11017 }
11018
11019 static void
11020 location_set_user_text (GtkFileChooserDefault *impl,
11021                         const gchar           *path)
11022 {
11023   _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), path);
11024   gtk_editable_set_position (GTK_EDITABLE (impl->location_entry), -1);
11025 }
11026
11027 static void
11028 location_popup_handler (GtkFileChooserDefault *impl,
11029                         const gchar           *path)
11030
11031   if (impl->operation_mode != OPERATION_MODE_BROWSE)
11032     {
11033       GtkWidget *widget_to_focus;
11034       
11035       /* This will give us the location widgets back */
11036       switch (impl->operation_mode)
11037         {
11038         case OPERATION_MODE_SEARCH:
11039           search_switch_to_browse_mode (impl);
11040           break;
11041         case OPERATION_MODE_RECENT:
11042           recent_switch_to_browse_mode (impl);
11043           break;
11044         case OPERATION_MODE_BROWSE:
11045           g_assert_not_reached ();
11046           break;
11047         }
11048
11049       if (impl->current_folder)
11050         change_folder_and_display_error (impl, impl->current_folder, FALSE);
11051
11052       if (impl->location_mode == LOCATION_MODE_PATH_BAR)
11053         widget_to_focus = impl->browse_files_tree_view;
11054       else
11055         widget_to_focus = impl->location_entry;
11056
11057       gtk_widget_grab_focus (widget_to_focus);
11058       return; 
11059     }
11060   
11061   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
11062       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
11063     {
11064       LocationMode new_mode;
11065
11066       if (path != NULL)
11067         {
11068           /* since the user typed something, we unconditionally want to turn on the entry */
11069           new_mode = LOCATION_MODE_FILENAME_ENTRY;
11070         }
11071       else if (impl->location_mode == LOCATION_MODE_PATH_BAR)
11072         new_mode = LOCATION_MODE_FILENAME_ENTRY;
11073       else if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
11074         new_mode = LOCATION_MODE_PATH_BAR;
11075       else
11076         {
11077           g_assert_not_reached ();
11078           return;
11079         }
11080
11081       location_mode_set (impl, new_mode, TRUE);
11082       if (new_mode == LOCATION_MODE_FILENAME_ENTRY)
11083         {
11084           if (path != NULL)
11085             location_set_user_text (impl, path);
11086           else
11087             {
11088               location_entry_set_initial_text (impl);
11089               gtk_editable_select_region (GTK_EDITABLE (impl->location_entry), 0, -1);
11090             }
11091         }
11092     }
11093   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
11094            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
11095     {
11096       gtk_widget_grab_focus (impl->location_entry);
11097       if (path != NULL)
11098         location_set_user_text (impl, path);
11099     }
11100   else
11101     g_assert_not_reached ();
11102 }
11103
11104 /* Handler for the "up-folder" keybinding signal */
11105 static void
11106 up_folder_handler (GtkFileChooserDefault *impl)
11107 {
11108   _gtk_path_bar_up (GTK_PATH_BAR (impl->browse_path_bar));
11109 }
11110
11111 /* Handler for the "down-folder" keybinding signal */
11112 static void
11113 down_folder_handler (GtkFileChooserDefault *impl)
11114 {
11115   _gtk_path_bar_down (GTK_PATH_BAR (impl->browse_path_bar));
11116 }
11117
11118 /* Switches to the shortcut in the specified index */
11119 static void
11120 switch_to_shortcut (GtkFileChooserDefault *impl,
11121                     int pos)
11122 {
11123   GtkTreeIter iter;
11124
11125   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
11126     g_assert_not_reached ();
11127
11128   shortcuts_activate_iter (impl, &iter);
11129 }
11130
11131 /* Handler for the "home-folder" keybinding signal */
11132 static void
11133 home_folder_handler (GtkFileChooserDefault *impl)
11134 {
11135   if (impl->has_home)
11136     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_HOME));
11137 }
11138
11139 /* Handler for the "desktop-folder" keybinding signal */
11140 static void
11141 desktop_folder_handler (GtkFileChooserDefault *impl)
11142 {
11143   if (impl->has_desktop)
11144     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_DESKTOP));
11145 }
11146
11147 /* Handler for the "search-shortcut" keybinding signal */
11148 static void
11149 search_shortcut_handler (GtkFileChooserDefault *impl)
11150 {
11151   if (impl->has_search)
11152     {
11153       switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_SEARCH));
11154
11155       /* we want the entry widget to grab the focus the first
11156        * time, not the browse_files_tree_view widget.
11157        */
11158       if (impl->search_entry)
11159         gtk_widget_grab_focus (impl->search_entry);
11160     }
11161 }
11162
11163 /* Handler for the "recent-shortcut" keybinding signal */
11164 static void
11165 recent_shortcut_handler (GtkFileChooserDefault *impl)
11166 {
11167   if (impl->has_recent)
11168     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_RECENT));
11169 }
11170
11171 static void
11172 quick_bookmark_handler (GtkFileChooserDefault *impl,
11173                         gint bookmark_index)
11174 {
11175   int bookmark_pos;
11176   GtkTreePath *path;
11177
11178   if (bookmark_index < 0 || bookmark_index >= impl->num_bookmarks)
11179     return;
11180
11181   bookmark_pos = shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS) + bookmark_index;
11182
11183   path = gtk_tree_path_new_from_indices (bookmark_pos, -1);
11184   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view),
11185                                 path, NULL,
11186                                 FALSE, 0.0, 0.0);
11187   gtk_tree_path_free (path);
11188
11189   switch_to_shortcut (impl, bookmark_pos);
11190 }
11191
11192 static void
11193 show_hidden_handler (GtkFileChooserDefault *impl)
11194 {
11195   g_object_set (impl,
11196                 "show-hidden", !impl->show_hidden,
11197                 NULL);
11198 }
11199
11200
11201 /* Drag and drop interfaces */
11202
11203 static void
11204 _shortcuts_pane_model_filter_class_init (ShortcutsPaneModelFilterClass *class)
11205 {
11206 }
11207
11208 static void
11209 _shortcuts_pane_model_filter_init (ShortcutsPaneModelFilter *model)
11210 {
11211   model->impl = NULL;
11212 }
11213
11214 /* GtkTreeDragSource::row_draggable implementation for the shortcuts filter model */
11215 static gboolean
11216 shortcuts_pane_model_filter_row_draggable (GtkTreeDragSource *drag_source,
11217                                            GtkTreePath       *path)
11218 {
11219   ShortcutsPaneModelFilter *model;
11220   int pos;
11221   int bookmarks_pos;
11222
11223   model = SHORTCUTS_PANE_MODEL_FILTER (drag_source);
11224
11225   pos = *gtk_tree_path_get_indices (path);
11226   bookmarks_pos = shortcuts_get_index (model->impl, SHORTCUTS_BOOKMARKS);
11227
11228   return (pos >= bookmarks_pos && pos < bookmarks_pos + model->impl->num_bookmarks);
11229 }
11230
11231 /* GtkTreeDragSource::drag_data_get implementation for the shortcuts filter model */
11232 static gboolean
11233 shortcuts_pane_model_filter_drag_data_get (GtkTreeDragSource *drag_source,
11234                                            GtkTreePath       *path,
11235                                            GtkSelectionData  *selection_data)
11236 {
11237   ShortcutsPaneModelFilter *model;
11238
11239   model = SHORTCUTS_PANE_MODEL_FILTER (drag_source);
11240
11241   /* FIXME */
11242
11243   return FALSE;
11244 }
11245
11246 /* Fill the GtkTreeDragSourceIface vtable */
11247 static void
11248 shortcuts_pane_model_filter_drag_source_iface_init (GtkTreeDragSourceIface *iface)
11249 {
11250   iface->row_draggable = shortcuts_pane_model_filter_row_draggable;
11251   iface->drag_data_get = shortcuts_pane_model_filter_drag_data_get;
11252 }
11253
11254 #if 0
11255 /* Fill the GtkTreeDragDestIface vtable */
11256 static void
11257 shortcuts_pane_model_filter_drag_dest_iface_init (GtkTreeDragDestIface *iface)
11258 {
11259   iface->drag_data_received = shortcuts_pane_model_filter_drag_data_received;
11260   iface->row_drop_possible = shortcuts_pane_model_filter_row_drop_possible;
11261 }
11262 #endif
11263
11264 static GtkTreeModel *
11265 shortcuts_pane_model_filter_new (GtkFileChooserDefault *impl,
11266                                  GtkTreeModel          *child_model,
11267                                  GtkTreePath           *root)
11268 {
11269   ShortcutsPaneModelFilter *model;
11270
11271   model = g_object_new (SHORTCUTS_PANE_MODEL_FILTER_TYPE,
11272                         "child-model", child_model,
11273                         "virtual-root", root,
11274                         NULL);
11275
11276   model->impl = impl;
11277
11278   return GTK_TREE_MODEL (model);
11279 }
11280
11281 \f
11282
11283 static gboolean
11284 recent_model_sort_row_draggable (GtkTreeDragSource *drag_source,
11285                                  GtkTreePath       *path)
11286 {
11287   RecentModelSort *model;
11288   GtkTreeIter iter, child_iter;
11289   gboolean is_folder;
11290
11291   model = RECENT_MODEL_SORT (drag_source);
11292   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
11293     return FALSE;
11294
11295   recent_get_valid_child_iter (model->impl, &child_iter, &iter);
11296   gtk_tree_model_get (GTK_TREE_MODEL (model->impl->recent_model), &child_iter,
11297                       RECENT_MODEL_COL_IS_FOLDER, &is_folder,
11298                       -1);
11299
11300   return is_folder;
11301 }
11302
11303 static gboolean
11304 recent_model_sort_drag_data_get (GtkTreeDragSource *drag_source,
11305                                  GtkTreePath       *path,
11306                                  GtkSelectionData  *selection_data)
11307 {
11308   RecentModelSort *model;
11309   GtkTreeIter iter, child_iter;
11310   GFile *file;
11311   gchar *uris[2];
11312
11313   model = RECENT_MODEL_SORT (drag_source);
11314   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
11315     return FALSE;
11316
11317   recent_get_valid_child_iter (model->impl, &child_iter, &iter);
11318   gtk_tree_model_get (GTK_TREE_MODEL (model->impl->recent_model), &child_iter,
11319                       RECENT_MODEL_COL_FILE, &file,
11320                       -1);
11321   g_assert (file != NULL);
11322
11323   uris[0] = g_file_get_uri (file);
11324   uris[1] = NULL;
11325
11326   gtk_selection_data_set_uris (selection_data, uris);
11327
11328   g_free (uris[0]);
11329
11330   return TRUE;
11331 }
11332
11333 static void
11334 recent_model_sort_drag_source_iface_init (GtkTreeDragSourceIface *iface)
11335 {
11336   iface->row_draggable = recent_model_sort_row_draggable;
11337   iface->drag_data_get = recent_model_sort_drag_data_get;
11338 }
11339
11340 static void
11341 _recent_model_sort_class_init (RecentModelSortClass *klass)
11342 {
11343
11344 }
11345
11346 static void
11347 _recent_model_sort_init (RecentModelSort *model)
11348 {
11349   model->impl = NULL;
11350 }
11351
11352 static GtkTreeModel *
11353 recent_model_sort_new (GtkFileChooserDefault *impl,
11354                        GtkTreeModel          *child_model)
11355 {
11356   RecentModelSort *model;
11357
11358   model = g_object_new (RECENT_MODEL_SORT_TYPE,
11359                         "model", child_model,
11360                         NULL);
11361   model->impl = impl;
11362
11363   return GTK_TREE_MODEL (model);
11364 }
11365
11366 \f
11367
11368 static gboolean
11369 search_model_sort_row_draggable (GtkTreeDragSource *drag_source,
11370                                  GtkTreePath       *path)
11371 {
11372   SearchModelSort *model;
11373   GtkTreeIter iter, child_iter;
11374   gboolean is_folder;
11375
11376   model = SEARCH_MODEL_SORT (drag_source);
11377   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
11378     return FALSE;
11379
11380   search_get_valid_child_iter (model->impl, &child_iter, &iter);
11381   gtk_tree_model_get (GTK_TREE_MODEL (model->impl->search_model), &child_iter,
11382                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
11383                       -1);
11384
11385   return is_folder;
11386 }
11387
11388 static gboolean
11389 search_model_sort_drag_data_get (GtkTreeDragSource *drag_source,
11390                                  GtkTreePath       *path,
11391                                  GtkSelectionData  *selection_data)
11392 {
11393   SearchModelSort *model;
11394   GtkTreeIter iter, child_iter;
11395   GFile *file;
11396   gchar *uris[2];
11397
11398   model = SEARCH_MODEL_SORT (drag_source);
11399   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
11400     return FALSE;
11401
11402   search_get_valid_child_iter (model->impl, &child_iter, &iter);
11403   gtk_tree_model_get (GTK_TREE_MODEL (model->impl->search_model), &child_iter,
11404                       RECENT_MODEL_COL_FILE, &file,
11405                       -1);
11406   g_assert (file != NULL);
11407
11408   uris[0] = g_file_get_uri (file);
11409   uris[1] = NULL;
11410
11411   gtk_selection_data_set_uris (selection_data, uris);
11412
11413   g_free (uris[0]);
11414
11415   return TRUE;
11416 }
11417
11418 static void
11419 search_model_sort_drag_source_iface_init (GtkTreeDragSourceIface *iface)
11420 {
11421   iface->row_draggable = search_model_sort_row_draggable;
11422   iface->drag_data_get = search_model_sort_drag_data_get;
11423 }
11424
11425 static void
11426 _search_model_sort_class_init (SearchModelSortClass *klass)
11427 {
11428
11429 }
11430
11431 static void
11432 _search_model_sort_init (SearchModelSort *model)
11433 {
11434   model->impl = NULL;
11435 }
11436
11437 static GtkTreeModel *
11438 search_model_sort_new (GtkFileChooserDefault *impl,
11439                        GtkTreeModel          *child_model)
11440 {
11441   SearchModelSort *model;
11442
11443   model = g_object_new (SEARCH_MODEL_SORT_TYPE,
11444                         "model", child_model,
11445                         NULL);
11446   model->impl = impl;
11447
11448   return GTK_TREE_MODEL (model);
11449 }