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