]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilechooserdefault.c
Clear cached row sensitivity when the filter changes
[~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, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "config.h"
21
22 #include "gtkfilechooserdefault.h"
23
24 #include "gtkbindings.h"
25 #include "gtkcelllayout.h"
26 #include "gtkcellrendererpixbuf.h"
27 #include "gtkcellrenderertext.h"
28 #include "gtkcheckmenuitem.h"
29 #include "gtkclipboard.h"
30 #include "gtkcomboboxtext.h"
31 #include "gtkentry.h"
32 #include "gtkexpander.h"
33 #include "gtkfilechooserprivate.h"
34 #include "gtkfilechooserdialog.h"
35 #include "gtkfilechooserembed.h"
36 #include "gtkfilechooserentry.h"
37 #include "gtkfilechooserutils.h"
38 #include "gtkfilechooser.h"
39 #include "gtkfilesystem.h"
40 #include "gtkfilesystemmodel.h"
41 #include "gtkframe.h"
42 #include "gtkgrid.h"
43 #include "gtkiconfactory.h"
44 #include "gtkicontheme.h"
45 #include "gtkimage.h"
46 #include "gtkimagemenuitem.h"
47 #include "gtkinfobar.h"
48 #include "gtklabel.h"
49 #include "gtkmarshalers.h"
50 #include "gtkmessagedialog.h"
51 #include "gtkmountoperation.h"
52 #include "gtkpaned.h"
53 #include "gtkpathbar.h"
54 #include "gtkprivate.h"
55 #include "gtkradiobutton.h"
56 #include "gtkrecentfilter.h"
57 #include "gtkrecentmanager.h"
58 #include "gtkscrolledwindow.h"
59 #include "gtkseparatormenuitem.h"
60 #include "gtksettings.h"
61 #include "gtksizegroup.h"
62 #include "gtksizerequest.h"
63 #include "gtkstock.h"
64 #include "gtktoolbar.h"
65 #include "gtktoolbutton.h"
66 #include "gtktooltip.h"
67 #include "gtktreednd.h"
68 #include "gtktreeprivate.h"
69 #include "gtktreeselection.h"
70 #include "gtkbox.h"
71 #include "gtkorientable.h"
72 #include "gtkintl.h"
73
74 #include <errno.h>
75 #include <string.h>
76 #include <time.h>
77 #include <sys/stat.h>
78 #include <sys/types.h>
79 #include <locale.h>
80
81 #ifdef HAVE_UNISTD_H
82 #include <unistd.h>
83 #endif
84 #ifdef G_OS_WIN32
85 #include <io.h>
86 #endif
87
88 /* Values for GtkSelection-related "info" fields */
89 #define SELECTION_TEXT 0
90 #define SELECTION_URI  1
91
92 /* Profiling stuff */
93 #undef PROFILE_FILE_CHOOSER
94 #ifdef PROFILE_FILE_CHOOSER
95
96
97 #ifndef F_OK 
98 #define F_OK 0
99 #endif
100
101 #define PROFILE_INDENT 4
102
103 static int profile_indent;
104
105 static void
106 profile_add_indent (int indent)
107 {
108   profile_indent += indent;
109   if (profile_indent < 0)
110     g_error ("You screwed up your indentation");
111 }
112
113 void
114 _gtk_file_chooser_profile_log (const char *func, int indent, const char *msg1, const char *msg2)
115 {
116   char *str;
117
118   if (indent < 0)
119     profile_add_indent (indent);
120
121   if (profile_indent == 0)
122     str = g_strdup_printf ("MARK: %s %s %s", func ? func : "", msg1 ? msg1 : "", msg2 ? msg2 : "");
123   else
124     str = g_strdup_printf ("MARK: %*c %s %s %s", profile_indent - 1, ' ', func ? func : "", msg1 ? msg1 : "", msg2 ? msg2 : "");
125
126   access (str, F_OK);
127   g_free (str);
128
129   if (indent > 0)
130     profile_add_indent (indent);
131 }
132
133 #define profile_start(x, y) _gtk_file_chooser_profile_log (G_STRFUNC, PROFILE_INDENT, x, y)
134 #define profile_end(x, y) _gtk_file_chooser_profile_log (G_STRFUNC, -PROFILE_INDENT, x, y)
135 #define profile_msg(x, y) _gtk_file_chooser_profile_log (NULL, 0, x, y)
136 #else
137 #define profile_start(x, y)
138 #define profile_end(x, y)
139 #define profile_msg(x, y)
140 #endif
141
142
143
144 typedef struct _GtkFileChooserDefaultClass GtkFileChooserDefaultClass;
145
146 #define GTK_FILE_CHOOSER_DEFAULT_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_FILE_CHOOSER_DEFAULT, GtkFileChooserDefaultClass))
147 #define GTK_IS_FILE_CHOOSER_DEFAULT_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_FILE_CHOOSER_DEFAULT))
148 #define GTK_FILE_CHOOSER_DEFAULT_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_FILE_CHOOSER_DEFAULT, GtkFileChooserDefaultClass))
149
150 #define MAX_LOADING_TIME 500
151
152 #define DEFAULT_NEW_FOLDER_NAME _("Type name of new folder")
153
154 struct _GtkFileChooserDefaultClass
155 {
156   GtkBoxClass parent_class;
157 };
158
159 /* Signal IDs */
160 enum {
161   LOCATION_POPUP,
162   LOCATION_POPUP_ON_PASTE,
163   UP_FOLDER,
164   DOWN_FOLDER,
165   HOME_FOLDER,
166   DESKTOP_FOLDER,
167   QUICK_BOOKMARK,
168   LOCATION_TOGGLE_POPUP,
169   SHOW_HIDDEN,
170   SEARCH_SHORTCUT,
171   RECENT_SHORTCUT,
172
173   LAST_SIGNAL
174 };
175
176 static guint signals[LAST_SIGNAL] = { 0 };
177
178 /* Column numbers for the shortcuts tree.  Keep these in sync with shortcuts_model_create() */
179 enum {
180   SHORTCUTS_COL_PIXBUF,
181   SHORTCUTS_COL_NAME,
182   SHORTCUTS_COL_DATA,
183   SHORTCUTS_COL_TYPE,
184   SHORTCUTS_COL_REMOVABLE,
185   SHORTCUTS_COL_PIXBUF_VISIBLE,
186   SHORTCUTS_COL_CANCELLABLE,
187   SHORTCUTS_COL_NUM_COLUMNS
188 };
189
190 typedef enum {
191   SHORTCUT_TYPE_FILE,
192   SHORTCUT_TYPE_VOLUME,
193   SHORTCUT_TYPE_SEPARATOR,
194   SHORTCUT_TYPE_SEARCH,
195   SHORTCUT_TYPE_RECENT
196 } ShortcutType;
197
198 #define MODEL_ATTRIBUTES "standard::name,standard::type,standard::display-name," \
199                          "standard::is-hidden,standard::is-backup,standard::size," \
200                          "standard::content-type,time::modified"
201 enum {
202   /* the first 3 must be these due to settings caching sort column */
203   MODEL_COL_NAME,
204   MODEL_COL_SIZE,
205   MODEL_COL_MTIME,
206   MODEL_COL_FILE,
207   MODEL_COL_NAME_COLLATED,
208   MODEL_COL_IS_FOLDER,
209   MODEL_COL_IS_SENSITIVE,
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         G_TYPE_BOOLEAN,           /* MODEL_COL_IS_SENSITIVE */  \
227         GDK_TYPE_PIXBUF,          /* MODEL_COL_PIXBUF */        \
228         G_TYPE_STRING,            /* MODEL_COL_SIZE_TEXT */     \
229         G_TYPE_STRING,            /* MODEL_COL_MTIME_TEXT */    \
230         PANGO_TYPE_ELLIPSIZE_MODE /* MODEL_COL_ELLIPSIZE */
231
232 /* Identifiers for target types */
233 enum {
234   GTK_TREE_MODEL_ROW,
235 };
236
237 /* Interesting places in the shortcuts bar */
238 typedef enum {
239   SHORTCUTS_SEARCH,
240   SHORTCUTS_RECENT,
241   SHORTCUTS_RECENT_SEPARATOR,
242   SHORTCUTS_HOME,
243   SHORTCUTS_DESKTOP,
244   SHORTCUTS_VOLUMES,
245   SHORTCUTS_SHORTCUTS,
246   SHORTCUTS_BOOKMARKS_SEPARATOR,
247   SHORTCUTS_BOOKMARKS,
248   SHORTCUTS_CURRENT_FOLDER_SEPARATOR,
249   SHORTCUTS_CURRENT_FOLDER
250 } ShortcutsIndex;
251
252 /* Icon size for if we can't get it from the theme */
253 #define FALLBACK_ICON_SIZE 16
254
255 #define PREVIEW_HBOX_SPACING 12
256 #define NUM_LINES 45
257 #define NUM_CHARS 60
258
259 #define SETTINGS_KEY_LAST_FOLDER_URI     "last-folder-uri"
260 #define SETTINGS_KEY_LOCATION_MODE       "location-mode"
261 #define SETTINGS_KEY_SHOW_HIDDEN         "show-hidden"
262 #define SETTINGS_KEY_SHOW_SIZE_COLUMN    "show-size-column"
263 #define SETTINGS_KEY_SORT_COLUMN         "sort-column"
264 #define SETTINGS_KEY_SORT_ORDER          "sort-order"
265 #define SETTINGS_KEY_WINDOW_POSITION     "window-position"
266 #define SETTINGS_KEY_WINDOW_SIZE         "window-size"
267
268 static void gtk_file_chooser_default_iface_init       (GtkFileChooserIface        *iface);
269 static void gtk_file_chooser_embed_default_iface_init (GtkFileChooserEmbedIface   *iface);
270
271 static GObject* gtk_file_chooser_default_constructor  (GType                  type,
272                                                        guint                  n_construct_properties,
273                                                        GObjectConstructParam *construct_params);
274 static void     gtk_file_chooser_default_finalize     (GObject               *object);
275 static void     gtk_file_chooser_default_set_property (GObject               *object,
276                                                        guint                  prop_id,
277                                                        const GValue          *value,
278                                                        GParamSpec            *pspec);
279 static void     gtk_file_chooser_default_get_property (GObject               *object,
280                                                        guint                  prop_id,
281                                                        GValue                *value,
282                                                        GParamSpec            *pspec);
283 static void     gtk_file_chooser_default_dispose      (GObject               *object);
284 static void     gtk_file_chooser_default_show_all       (GtkWidget             *widget);
285 static void     gtk_file_chooser_default_realize        (GtkWidget             *widget);
286 static void     gtk_file_chooser_default_map            (GtkWidget             *widget);
287 static void     gtk_file_chooser_default_unmap          (GtkWidget             *widget);
288 static void     gtk_file_chooser_default_hierarchy_changed (GtkWidget          *widget,
289                                                             GtkWidget          *previous_toplevel);
290 static void     gtk_file_chooser_default_style_updated  (GtkWidget             *widget);
291 static void     gtk_file_chooser_default_screen_changed (GtkWidget             *widget,
292                                                          GdkScreen             *previous_screen);
293 static void     gtk_file_chooser_default_size_allocate  (GtkWidget             *widget,
294                                                          GtkAllocation         *allocation);
295
296 static gboolean       gtk_file_chooser_default_set_current_folder          (GtkFileChooser    *chooser,
297                                                                             GFile             *folder,
298                                                                             GError           **error);
299 static gboolean       gtk_file_chooser_default_update_current_folder       (GtkFileChooser    *chooser,
300                                                                             GFile             *folder,
301                                                                             gboolean           keep_trail,
302                                                                             gboolean           clear_entry,
303                                                                             GError           **error);
304 static GFile *        gtk_file_chooser_default_get_current_folder          (GtkFileChooser    *chooser);
305 static void           gtk_file_chooser_default_set_current_name            (GtkFileChooser    *chooser,
306                                                                             const gchar       *name);
307 static gboolean       gtk_file_chooser_default_select_file                 (GtkFileChooser    *chooser,
308                                                                             GFile             *file,
309                                                                             GError           **error);
310 static void           gtk_file_chooser_default_unselect_file               (GtkFileChooser    *chooser,
311                                                                             GFile             *file);
312 static void           gtk_file_chooser_default_select_all                  (GtkFileChooser    *chooser);
313 static void           gtk_file_chooser_default_unselect_all                (GtkFileChooser    *chooser);
314 static GSList *       gtk_file_chooser_default_get_files                   (GtkFileChooser    *chooser);
315 static GFile *        gtk_file_chooser_default_get_preview_file            (GtkFileChooser    *chooser);
316 static GtkFileSystem *gtk_file_chooser_default_get_file_system             (GtkFileChooser    *chooser);
317 static void           gtk_file_chooser_default_add_filter                  (GtkFileChooser    *chooser,
318                                                                             GtkFileFilter     *filter);
319 static void           gtk_file_chooser_default_remove_filter               (GtkFileChooser    *chooser,
320                                                                             GtkFileFilter     *filter);
321 static GSList *       gtk_file_chooser_default_list_filters                (GtkFileChooser    *chooser);
322 static gboolean       gtk_file_chooser_default_add_shortcut_folder    (GtkFileChooser    *chooser,
323                                                                        GFile             *file,
324                                                                        GError           **error);
325 static gboolean       gtk_file_chooser_default_remove_shortcut_folder (GtkFileChooser    *chooser,
326                                                                        GFile             *file,
327                                                                        GError           **error);
328 static GSList *       gtk_file_chooser_default_list_shortcut_folders  (GtkFileChooser    *chooser);
329
330 static void           gtk_file_chooser_default_get_default_size       (GtkFileChooserEmbed *chooser_embed,
331                                                                        gint                *default_width,
332                                                                        gint                *default_height);
333 static gboolean       gtk_file_chooser_default_should_respond         (GtkFileChooserEmbed *chooser_embed);
334 static void           gtk_file_chooser_default_initial_focus          (GtkFileChooserEmbed *chooser_embed);
335
336 static void add_selection_to_recent_list (GtkFileChooserDefault *impl);
337
338 static void location_popup_handler  (GtkFileChooserDefault *impl,
339                                      const gchar           *path);
340 static void location_popup_on_paste_handler (GtkFileChooserDefault *impl);
341 static void location_toggle_popup_handler   (GtkFileChooserDefault *impl);
342 static void up_folder_handler       (GtkFileChooserDefault *impl);
343 static void down_folder_handler     (GtkFileChooserDefault *impl);
344 static void home_folder_handler     (GtkFileChooserDefault *impl);
345 static void desktop_folder_handler  (GtkFileChooserDefault *impl);
346 static void quick_bookmark_handler  (GtkFileChooserDefault *impl,
347                                      gint                   bookmark_index);
348 static void show_hidden_handler     (GtkFileChooserDefault *impl);
349 static void search_shortcut_handler (GtkFileChooserDefault *impl);
350 static void recent_shortcut_handler (GtkFileChooserDefault *impl);
351 static void update_appearance       (GtkFileChooserDefault *impl);
352
353 static void set_current_filter   (GtkFileChooserDefault *impl,
354                                   GtkFileFilter         *filter);
355 static void check_preview_change (GtkFileChooserDefault *impl);
356
357 static void filter_combo_changed       (GtkComboBox           *combo_box,
358                                         GtkFileChooserDefault *impl);
359
360 static gboolean shortcuts_key_press_event_cb (GtkWidget             *widget,
361                                               GdkEventKey           *event,
362                                               GtkFileChooserDefault *impl);
363
364 static gboolean shortcuts_select_func   (GtkTreeSelection      *selection,
365                                          GtkTreeModel          *model,
366                                          GtkTreePath           *path,
367                                          gboolean               path_currently_selected,
368                                          gpointer               data);
369 static gboolean shortcuts_get_selected  (GtkFileChooserDefault *impl,
370                                          GtkTreeIter           *iter);
371 static void shortcuts_activate_iter (GtkFileChooserDefault *impl,
372                                      GtkTreeIter           *iter);
373 static int shortcuts_get_index (GtkFileChooserDefault *impl,
374                                 ShortcutsIndex         where);
375 static int shortcut_find_position (GtkFileChooserDefault *impl,
376                                    GFile                 *file);
377
378 static void bookmarks_check_add_sensitivity (GtkFileChooserDefault *impl);
379
380 static gboolean list_select_func   (GtkTreeSelection      *selection,
381                                     GtkTreeModel          *model,
382                                     GtkTreePath           *path,
383                                     gboolean               path_currently_selected,
384                                     gpointer               data);
385
386 static void list_selection_changed     (GtkTreeSelection      *tree_selection,
387                                         GtkFileChooserDefault *impl);
388 static void list_row_activated         (GtkTreeView           *tree_view,
389                                         GtkTreePath           *path,
390                                         GtkTreeViewColumn     *column,
391                                         GtkFileChooserDefault *impl);
392
393 static void path_bar_clicked (GtkPathBar            *path_bar,
394                               GFile                 *file,
395                               GFile                 *child,
396                               gboolean               child_is_hidden,
397                               GtkFileChooserDefault *impl);
398
399 static void add_bookmark_button_clicked_cb    (GtkButton             *button,
400                                                GtkFileChooserDefault *impl);
401 static void remove_bookmark_button_clicked_cb (GtkButton             *button,
402                                                GtkFileChooserDefault *impl);
403
404 static void update_cell_renderer_attributes (GtkFileChooserDefault *impl);
405
406 static void load_remove_timer (GtkFileChooserDefault *impl);
407 static void browse_files_center_selected_row (GtkFileChooserDefault *impl);
408
409 static void location_button_toggled_cb (GtkToggleButton *toggle,
410                                         GtkFileChooserDefault *impl);
411 static void location_switch_to_path_bar (GtkFileChooserDefault *impl);
412
413 static void stop_loading_and_clear_list_model (GtkFileChooserDefault *impl,
414                                                gboolean remove_from_treeview);
415
416 static void     search_setup_widgets         (GtkFileChooserDefault *impl);
417 static void     search_stop_searching        (GtkFileChooserDefault *impl,
418                                               gboolean               remove_query);
419 static void     search_clear_model           (GtkFileChooserDefault *impl, 
420                                               gboolean               remove_from_treeview);
421 static gboolean search_should_respond        (GtkFileChooserDefault *impl);
422 static GSList  *search_get_selected_files    (GtkFileChooserDefault *impl);
423 static void     search_entry_activate_cb     (GtkEntry              *entry, 
424                                               gpointer               data);
425 static void     settings_load                (GtkFileChooserDefault *impl);
426
427 static void     recent_start_loading         (GtkFileChooserDefault *impl);
428 static void     recent_stop_loading          (GtkFileChooserDefault *impl);
429 static void     recent_clear_model           (GtkFileChooserDefault *impl,
430                                               gboolean               remove_from_treeview);
431 static gboolean recent_should_respond        (GtkFileChooserDefault *impl);
432 static GSList * recent_get_selected_files    (GtkFileChooserDefault *impl);
433 static void     set_file_system_backend      (GtkFileChooserDefault *impl);
434 static void     unset_file_system_backend    (GtkFileChooserDefault *impl);
435
436
437
438 \f
439
440 /* Drag and drop interface declarations */
441
442 typedef struct {
443   GtkTreeModelFilter parent;
444
445   GtkFileChooserDefault *impl;
446 } ShortcutsPaneModelFilter;
447
448 typedef struct {
449   GtkTreeModelFilterClass parent_class;
450 } ShortcutsPaneModelFilterClass;
451
452 #define SHORTCUTS_PANE_MODEL_FILTER_TYPE (_shortcuts_pane_model_filter_get_type ())
453 #define SHORTCUTS_PANE_MODEL_FILTER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), SHORTCUTS_PANE_MODEL_FILTER_TYPE, ShortcutsPaneModelFilter))
454
455 static void shortcuts_pane_model_filter_drag_source_iface_init (GtkTreeDragSourceIface *iface);
456
457 G_DEFINE_TYPE_WITH_CODE (ShortcutsPaneModelFilter,
458                          _shortcuts_pane_model_filter,
459                          GTK_TYPE_TREE_MODEL_FILTER,
460                          G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_DRAG_SOURCE,
461                                                 shortcuts_pane_model_filter_drag_source_iface_init))
462
463 static GtkTreeModel *shortcuts_pane_model_filter_new (GtkFileChooserDefault *impl,
464                                                       GtkTreeModel          *child_model,
465                                                       GtkTreePath           *root);
466
467 \f
468
469 G_DEFINE_TYPE_WITH_CODE (GtkFileChooserDefault, _gtk_file_chooser_default, GTK_TYPE_BOX,
470                          G_IMPLEMENT_INTERFACE (GTK_TYPE_FILE_CHOOSER,
471                                                 gtk_file_chooser_default_iface_init)
472                          G_IMPLEMENT_INTERFACE (GTK_TYPE_FILE_CHOOSER_EMBED,
473                                                 gtk_file_chooser_embed_default_iface_init));                                            
474
475
476 static void
477 add_normal_and_shifted_binding (GtkBindingSet  *binding_set,
478                                 guint           keyval,
479                                 GdkModifierType modifiers,
480                                 const gchar    *signal_name)
481 {
482   gtk_binding_entry_add_signal (binding_set,
483                                 keyval, modifiers,
484                                 signal_name, 0);
485
486   gtk_binding_entry_add_signal (binding_set,
487                                 keyval, modifiers | GDK_SHIFT_MASK,
488                                 signal_name, 0);
489 }
490
491 static void
492 _gtk_file_chooser_default_class_init (GtkFileChooserDefaultClass *class)
493 {
494   static const guint quick_bookmark_keyvals[10] = {
495     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
496   };
497   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
498   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
499   GtkBindingSet *binding_set;
500   int i;
501
502   gobject_class->finalize = gtk_file_chooser_default_finalize;
503   gobject_class->constructor = gtk_file_chooser_default_constructor;
504   gobject_class->set_property = gtk_file_chooser_default_set_property;
505   gobject_class->get_property = gtk_file_chooser_default_get_property;
506   gobject_class->dispose = gtk_file_chooser_default_dispose;
507
508   widget_class->show_all = gtk_file_chooser_default_show_all;
509   widget_class->realize = gtk_file_chooser_default_realize;
510   widget_class->map = gtk_file_chooser_default_map;
511   widget_class->unmap = gtk_file_chooser_default_unmap;
512   widget_class->hierarchy_changed = gtk_file_chooser_default_hierarchy_changed;
513   widget_class->style_updated = gtk_file_chooser_default_style_updated;
514   widget_class->screen_changed = gtk_file_chooser_default_screen_changed;
515   widget_class->size_allocate = gtk_file_chooser_default_size_allocate;
516
517   signals[LOCATION_POPUP] =
518     g_signal_new_class_handler (I_("location-popup"),
519                                 G_OBJECT_CLASS_TYPE (class),
520                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
521                                 G_CALLBACK (location_popup_handler),
522                                 NULL, NULL,
523                                 _gtk_marshal_VOID__STRING,
524                                 G_TYPE_NONE, 1, G_TYPE_STRING);
525
526   signals[LOCATION_POPUP_ON_PASTE] =
527     g_signal_new_class_handler (I_("location-popup-on-paste"),
528                                 G_OBJECT_CLASS_TYPE (class),
529                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
530                                 G_CALLBACK (location_popup_on_paste_handler),
531                                 NULL, NULL,
532                                 _gtk_marshal_VOID__VOID,
533                                 G_TYPE_NONE, 0);
534
535   signals[LOCATION_TOGGLE_POPUP] =
536     g_signal_new_class_handler (I_("location-toggle-popup"),
537                                 G_OBJECT_CLASS_TYPE (class),
538                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
539                                 G_CALLBACK (location_toggle_popup_handler),
540                                 NULL, NULL,
541                                 _gtk_marshal_VOID__VOID,
542                                 G_TYPE_NONE, 0);
543
544   signals[UP_FOLDER] =
545     g_signal_new_class_handler (I_("up-folder"),
546                                 G_OBJECT_CLASS_TYPE (class),
547                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
548                                 G_CALLBACK (up_folder_handler),
549                                 NULL, NULL,
550                                 _gtk_marshal_VOID__VOID,
551                                 G_TYPE_NONE, 0);
552
553   signals[DOWN_FOLDER] =
554     g_signal_new_class_handler (I_("down-folder"),
555                                 G_OBJECT_CLASS_TYPE (class),
556                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
557                                 G_CALLBACK (down_folder_handler),
558                                 NULL, NULL,
559                                 _gtk_marshal_VOID__VOID,
560                                 G_TYPE_NONE, 0);
561
562   signals[HOME_FOLDER] =
563     g_signal_new_class_handler (I_("home-folder"),
564                                 G_OBJECT_CLASS_TYPE (class),
565                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
566                                 G_CALLBACK (home_folder_handler),
567                                 NULL, NULL,
568                                 _gtk_marshal_VOID__VOID,
569                                 G_TYPE_NONE, 0);
570
571   signals[DESKTOP_FOLDER] =
572     g_signal_new_class_handler (I_("desktop-folder"),
573                                 G_OBJECT_CLASS_TYPE (class),
574                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
575                                 G_CALLBACK (desktop_folder_handler),
576                                 NULL, NULL,
577                                 _gtk_marshal_VOID__VOID,
578                                 G_TYPE_NONE, 0);
579
580   signals[QUICK_BOOKMARK] =
581     g_signal_new_class_handler (I_("quick-bookmark"),
582                                 G_OBJECT_CLASS_TYPE (class),
583                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
584                                 G_CALLBACK (quick_bookmark_handler),
585                                 NULL, NULL,
586                                 _gtk_marshal_VOID__INT,
587                                 G_TYPE_NONE, 1, G_TYPE_INT);
588
589   signals[SHOW_HIDDEN] =
590     g_signal_new_class_handler (I_("show-hidden"),
591                                 G_OBJECT_CLASS_TYPE (class),
592                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
593                                 G_CALLBACK (show_hidden_handler),
594                                 NULL, NULL,
595                                 _gtk_marshal_VOID__VOID,
596                                 G_TYPE_NONE, 0);
597
598   signals[SEARCH_SHORTCUT] =
599     g_signal_new_class_handler (I_("search-shortcut"),
600                                 G_OBJECT_CLASS_TYPE (class),
601                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
602                                 G_CALLBACK (search_shortcut_handler),
603                                 NULL, NULL,
604                                 _gtk_marshal_VOID__VOID,
605                                 G_TYPE_NONE, 0);
606
607   signals[RECENT_SHORTCUT] =
608     g_signal_new_class_handler (I_("recent-shortcut"),
609                                 G_OBJECT_CLASS_TYPE (class),
610                                 G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
611                                 G_CALLBACK (recent_shortcut_handler),
612                                 NULL, NULL,
613                                 _gtk_marshal_VOID__VOID,
614                                 G_TYPE_NONE, 0);
615
616   binding_set = gtk_binding_set_by_class (class);
617
618   gtk_binding_entry_add_signal (binding_set,
619                                 GDK_KEY_l, GDK_CONTROL_MASK,
620                                 "location-toggle-popup",
621                                 0);
622
623   gtk_binding_entry_add_signal (binding_set,
624                                 GDK_KEY_slash, 0,
625                                 "location-popup",
626                                 1, G_TYPE_STRING, "/");
627   gtk_binding_entry_add_signal (binding_set,
628                                 GDK_KEY_KP_Divide, 0,
629                                 "location-popup",
630                                 1, G_TYPE_STRING, "/");
631
632 #ifdef G_OS_UNIX
633   gtk_binding_entry_add_signal (binding_set,
634                                 GDK_KEY_asciitilde, 0,
635                                 "location-popup",
636                                 1, G_TYPE_STRING, "~");
637 #endif
638
639   gtk_binding_entry_add_signal (binding_set,
640                                 GDK_KEY_v, GDK_CONTROL_MASK,
641                                 "location-popup-on-paste",
642                                 0);
643   gtk_binding_entry_add_signal (binding_set,
644                                 GDK_KEY_BackSpace, 0,
645                                 "up-folder",
646                                 0);
647
648   add_normal_and_shifted_binding (binding_set,
649                                   GDK_KEY_Up, GDK_MOD1_MASK,
650                                   "up-folder");
651
652   add_normal_and_shifted_binding (binding_set,
653                                   GDK_KEY_KP_Up, GDK_MOD1_MASK,
654                                   "up-folder");
655
656   add_normal_and_shifted_binding (binding_set,
657                                   GDK_KEY_Down, GDK_MOD1_MASK,
658                                   "down-folder");
659   add_normal_and_shifted_binding (binding_set,
660                                   GDK_KEY_KP_Down, GDK_MOD1_MASK,
661                                   "down-folder");
662
663   gtk_binding_entry_add_signal (binding_set,
664                                 GDK_KEY_Home, GDK_MOD1_MASK,
665                                 "home-folder",
666                                 0);
667   gtk_binding_entry_add_signal (binding_set,
668                                 GDK_KEY_KP_Home, GDK_MOD1_MASK,
669                                 "home-folder",
670                                 0);
671   gtk_binding_entry_add_signal (binding_set,
672                                 GDK_KEY_d, GDK_MOD1_MASK,
673                                 "desktop-folder",
674                                 0);
675   gtk_binding_entry_add_signal (binding_set,
676                                 GDK_KEY_h, GDK_CONTROL_MASK,
677                                 "show-hidden",
678                                 0);
679   gtk_binding_entry_add_signal (binding_set,
680                                 GDK_KEY_s, GDK_MOD1_MASK,
681                                 "search-shortcut",
682                                 0);
683   gtk_binding_entry_add_signal (binding_set,
684                                 GDK_KEY_r, GDK_MOD1_MASK,
685                                 "recent-shortcut",
686                                 0);
687
688   for (i = 0; i < 10; i++)
689     gtk_binding_entry_add_signal (binding_set,
690                                   quick_bookmark_keyvals[i], GDK_MOD1_MASK,
691                                   "quick-bookmark",
692                                   1, G_TYPE_INT, i);
693
694   _gtk_file_chooser_install_properties (gobject_class);
695 }
696
697 static void
698 gtk_file_chooser_default_iface_init (GtkFileChooserIface *iface)
699 {
700   iface->select_file = gtk_file_chooser_default_select_file;
701   iface->unselect_file = gtk_file_chooser_default_unselect_file;
702   iface->select_all = gtk_file_chooser_default_select_all;
703   iface->unselect_all = gtk_file_chooser_default_unselect_all;
704   iface->get_files = gtk_file_chooser_default_get_files;
705   iface->get_preview_file = gtk_file_chooser_default_get_preview_file;
706   iface->get_file_system = gtk_file_chooser_default_get_file_system;
707   iface->set_current_folder = gtk_file_chooser_default_set_current_folder;
708   iface->get_current_folder = gtk_file_chooser_default_get_current_folder;
709   iface->set_current_name = gtk_file_chooser_default_set_current_name;
710   iface->add_filter = gtk_file_chooser_default_add_filter;
711   iface->remove_filter = gtk_file_chooser_default_remove_filter;
712   iface->list_filters = gtk_file_chooser_default_list_filters;
713   iface->add_shortcut_folder = gtk_file_chooser_default_add_shortcut_folder;
714   iface->remove_shortcut_folder = gtk_file_chooser_default_remove_shortcut_folder;
715   iface->list_shortcut_folders = gtk_file_chooser_default_list_shortcut_folders;
716 }
717
718 static void
719 gtk_file_chooser_embed_default_iface_init (GtkFileChooserEmbedIface *iface)
720 {
721   iface->get_default_size = gtk_file_chooser_default_get_default_size;
722   iface->should_respond = gtk_file_chooser_default_should_respond;
723   iface->initial_focus = gtk_file_chooser_default_initial_focus;
724 }
725
726 static void
727 _gtk_file_chooser_default_init (GtkFileChooserDefault *impl)
728 {
729   profile_start ("start", NULL);
730 #ifdef PROFILE_FILE_CHOOSER
731   access ("MARK: *** CREATE FILE CHOOSER", F_OK);
732 #endif
733   impl->local_only = TRUE;
734   impl->preview_widget_active = TRUE;
735   impl->use_preview_label = TRUE;
736   impl->select_multiple = FALSE;
737   impl->show_hidden = FALSE;
738   impl->show_size_column = TRUE;
739   impl->icon_size = FALLBACK_ICON_SIZE;
740   impl->load_state = LOAD_EMPTY;
741   impl->reload_state = RELOAD_EMPTY;
742   impl->pending_select_files = NULL;
743   impl->location_mode = LOCATION_MODE_PATH_BAR;
744   impl->operation_mode = OPERATION_MODE_BROWSE;
745   impl->sort_column = MODEL_COL_NAME;
746   impl->sort_order = GTK_SORT_ASCENDING;
747   impl->recent_manager = gtk_recent_manager_get_default ();
748   impl->create_folders = TRUE;
749
750   gtk_orientable_set_orientation (GTK_ORIENTABLE (impl),
751                                   GTK_ORIENTATION_VERTICAL);
752   gtk_box_set_spacing (GTK_BOX (impl), 12);
753
754   set_file_system_backend (impl);
755
756   profile_end ("end", NULL);
757 }
758
759 /* Frees the data columns for the specified iter in the shortcuts model*/
760 static void
761 shortcuts_free_row_data (GtkFileChooserDefault *impl,
762                          GtkTreeIter           *iter)
763 {
764   gpointer col_data;
765   ShortcutType shortcut_type;
766   GCancellable *cancellable;
767
768   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), iter,
769                       SHORTCUTS_COL_DATA, &col_data,
770                       SHORTCUTS_COL_TYPE, &shortcut_type,
771                       SHORTCUTS_COL_CANCELLABLE, &cancellable,
772                       -1);
773
774   if (cancellable)
775     {
776       g_cancellable_cancel (cancellable);
777       g_object_unref (cancellable);
778     }
779
780   if (!(shortcut_type == SHORTCUT_TYPE_FILE || 
781         shortcut_type == SHORTCUT_TYPE_VOLUME) ||
782       !col_data)
783     return;
784
785   if (shortcut_type == SHORTCUT_TYPE_VOLUME)
786     {
787       GtkFileSystemVolume *volume;
788
789       volume = col_data;
790       _gtk_file_system_volume_unref (volume);
791     }
792   if (shortcut_type == SHORTCUT_TYPE_FILE)
793     {
794       GFile *file;
795
796       file = col_data;
797       g_object_unref (file);
798     }
799 }
800
801 /* Frees all the data columns in the shortcuts model */
802 static void
803 shortcuts_free (GtkFileChooserDefault *impl)
804 {
805   GtkTreeIter iter;
806
807   if (!impl->shortcuts_model)
808     return;
809
810   if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
811     do
812       {
813         shortcuts_free_row_data (impl, &iter);
814       }
815     while (gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter));
816
817   g_object_unref (impl->shortcuts_model);
818   impl->shortcuts_model = NULL;
819 }
820
821 static void
822 pending_select_files_free (GtkFileChooserDefault *impl)
823 {
824   g_slist_free_full (impl->pending_select_files, g_object_unref);
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 (!gdk_event_triggers_context_menu ((GdkEvent *) event))
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_style (GTK_TOOLBAR (toolbar), GTK_TOOLBAR_ICONS);
3667   gtk_toolbar_set_icon_size (GTK_TOOLBAR (toolbar), GTK_ICON_SIZE_MENU);
3668
3669   context = gtk_widget_get_style_context (toolbar);
3670   gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP);
3671   gtk_style_context_add_class (context, GTK_STYLE_CLASS_INLINE_TOOLBAR);
3672   
3673   gtk_box_pack_start (GTK_BOX (vbox), toolbar, FALSE, FALSE, 0);
3674   gtk_widget_show (toolbar);
3675
3676   /* Add bookmark button */
3677   icon = g_themed_icon_new_with_default_fallbacks ("list-add-symbolic");
3678   impl->browse_shortcuts_add_button = toolbutton_new (impl,
3679                                                       icon,
3680                                                       FALSE,
3681                                                       TRUE,
3682                                                       G_CALLBACK (add_bookmark_button_clicked_cb));
3683   g_object_unref (icon);
3684
3685   gtk_toolbar_insert (GTK_TOOLBAR (toolbar), GTK_TOOL_ITEM (impl->browse_shortcuts_add_button), 0);
3686   gtk_widget_set_tooltip_text (impl->browse_shortcuts_add_button,
3687                                _("Add the selected folder to the Bookmarks"));
3688
3689   /* Remove bookmark button */
3690   icon = g_themed_icon_new_with_default_fallbacks ("list-remove-symbolic");
3691   impl->browse_shortcuts_remove_button = toolbutton_new (impl,
3692                                                          icon,
3693                                                          FALSE,
3694                                                          TRUE,
3695                                                          G_CALLBACK (remove_bookmark_button_clicked_cb));
3696   g_object_unref (icon);
3697   gtk_toolbar_insert (GTK_TOOLBAR (toolbar), GTK_TOOL_ITEM (impl->browse_shortcuts_remove_button), 1);
3698   gtk_widget_set_tooltip_text (impl->browse_shortcuts_remove_button,
3699                                _("Remove the selected bookmark"));
3700
3701   return vbox;
3702 }
3703
3704 static gboolean
3705 key_is_left_or_right (GdkEventKey *event)
3706 {
3707   guint modifiers;
3708
3709   modifiers = gtk_accelerator_get_default_mod_mask ();
3710
3711   return ((event->keyval == GDK_KEY_Right
3712            || event->keyval == GDK_KEY_KP_Right
3713            || event->keyval == GDK_KEY_Left
3714            || event->keyval == GDK_KEY_KP_Left)
3715           && (event->state & modifiers) == 0);
3716 }
3717
3718 /* Handles key press events on the file list, so that we can trap Enter to
3719  * activate the default button on our own.  Also, checks to see if '/' has been
3720  * pressed.
3721  */
3722 static gboolean
3723 browse_files_key_press_event_cb (GtkWidget   *widget,
3724                                  GdkEventKey *event,
3725                                  gpointer     data)
3726 {
3727   GtkFileChooserDefault *impl;
3728   GdkModifierType no_text_input_mask;
3729
3730   impl = (GtkFileChooserDefault *) data;
3731
3732   no_text_input_mask =
3733     gtk_widget_get_modifier_mask (widget, GDK_MODIFIER_INTENT_NO_TEXT_INPUT);
3734
3735   if ((event->keyval == GDK_KEY_slash
3736        || event->keyval == GDK_KEY_KP_Divide
3737 #ifdef G_OS_UNIX
3738        || event->keyval == GDK_KEY_asciitilde
3739 #endif
3740        ) && !(event->state & no_text_input_mask))
3741     {
3742       location_popup_handler (impl, event->string);
3743       return TRUE;
3744     }
3745
3746   if (key_is_left_or_right (event))
3747     {
3748       gtk_widget_grab_focus (impl->browse_shortcuts_tree_view);
3749       return TRUE;
3750     }
3751
3752   if ((event->keyval == GDK_KEY_Return
3753        || event->keyval == GDK_KEY_ISO_Enter
3754        || event->keyval == GDK_KEY_KP_Enter
3755        || event->keyval == GDK_KEY_space
3756        || event->keyval == GDK_KEY_KP_Space)
3757       && !(event->state & gtk_accelerator_get_default_mod_mask ())
3758       && !(impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
3759            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
3760     {
3761       GtkWindow *window;
3762
3763       window = get_toplevel (widget);
3764       if (window)
3765         {
3766           GtkWidget *default_widget, *focus_widget;
3767
3768           default_widget = gtk_window_get_default_widget (window);
3769           focus_widget = gtk_window_get_focus (window);
3770
3771           if (widget != default_widget &&
3772               !(widget == focus_widget && (!default_widget || !gtk_widget_get_sensitive (default_widget))))
3773             {
3774               gtk_window_activate_default (window);
3775
3776               return TRUE;
3777             }
3778         }
3779     }
3780
3781   return FALSE;
3782 }
3783
3784 /* Callback used when the file list's popup menu is detached */
3785 static void
3786 popup_menu_detach_cb (GtkWidget *attach_widget,
3787                       GtkMenu   *menu)
3788 {
3789   GtkFileChooserDefault *impl;
3790
3791   impl = g_object_get_data (G_OBJECT (attach_widget), "GtkFileChooserDefault");
3792   g_assert (GTK_IS_FILE_CHOOSER_DEFAULT (impl));
3793
3794   impl->browse_files_popup_menu = NULL;
3795   impl->browse_files_popup_menu_add_shortcut_item = NULL;
3796   impl->browse_files_popup_menu_hidden_files_item = NULL;
3797   impl->browse_files_popup_menu_copy_file_location_item = NULL;
3798 }
3799
3800 /* Callback used when the "Add to Bookmarks" menu item is activated */
3801 static void
3802 add_to_shortcuts_cb (GtkMenuItem           *item,
3803                      GtkFileChooserDefault *impl)
3804 {
3805   bookmarks_add_selected_folder (impl);
3806 }
3807
3808 /* callback used to set data to clipboard */
3809 static void
3810 copy_file_get_cb  (GtkClipboard     *clipboard,
3811                    GtkSelectionData *selection_data,
3812                    guint             info,
3813                    gpointer          data)
3814 {
3815   GSList *selected_files = data;
3816
3817   if (selected_files)
3818     {
3819       gint num_files = g_slist_length (selected_files);
3820       gchar **uris;
3821       gint i;
3822       GSList *l;
3823
3824       uris = g_new (gchar *, num_files + 1);
3825       uris[num_files] = NULL; /* null terminator */
3826
3827       i = 0;
3828
3829       for (l = selected_files; l; l = l->next)
3830         {
3831           GFile *file = (GFile *) l->data;
3832
3833           if (info == SELECTION_URI)
3834             uris[i] = g_file_get_uri (file);
3835           else /* if (info == SELECTION_TEXT) - let this be the fallback */
3836             uris[i] = g_file_get_parse_name (file);
3837
3838           i++;
3839         }
3840
3841       if (info == SELECTION_URI)
3842         gtk_selection_data_set_uris (selection_data, uris);
3843       else /* if (info == SELECTION_TEXT) - let this be the fallback */
3844         {
3845           char *str = g_strjoinv (" ", uris);
3846           gtk_selection_data_set_text (selection_data, str, -1);
3847           g_free (str);
3848         }
3849
3850       g_strfreev (uris);
3851     }
3852 }
3853
3854 /* callback used to clear the clipboard data */
3855 static void
3856 copy_file_clear_cb (GtkClipboard *clipboard,
3857                     gpointer      data)
3858 {
3859   GSList *selected_files = data;
3860
3861   g_slist_foreach (selected_files, (GFunc) g_object_unref, NULL);
3862   g_slist_free (selected_files);
3863 }
3864
3865 /* Callback used when the "Copy file's location" menu item is activated */
3866 static void
3867 copy_file_location_cb (GtkMenuItem           *item,
3868                        GtkFileChooserDefault *impl)
3869 {
3870   GSList *selected_files = NULL;
3871
3872   selected_files = search_get_selected_files (impl);
3873
3874   if (selected_files)
3875     {
3876       GtkClipboard *clipboard;
3877       GtkTargetList *target_list;
3878       GtkTargetEntry *targets;
3879       int n_targets;
3880
3881       clipboard = gtk_widget_get_clipboard (GTK_WIDGET (impl), GDK_SELECTION_CLIPBOARD);
3882
3883       target_list = gtk_target_list_new (NULL, 0);
3884       gtk_target_list_add_text_targets (target_list, SELECTION_TEXT);
3885       gtk_target_list_add_uri_targets (target_list, SELECTION_URI);
3886
3887       targets = gtk_target_table_new_from_list (target_list, &n_targets);
3888       gtk_target_list_unref (target_list);
3889
3890       gtk_clipboard_set_with_data (clipboard, targets, n_targets,
3891                                    copy_file_get_cb,
3892                                    copy_file_clear_cb,
3893                                    selected_files);
3894
3895       gtk_target_table_free (targets, n_targets);
3896     }
3897 }
3898
3899 /* Callback used when the "Visit this file" menu item is activated */
3900 static void
3901 visit_file_cb (GtkMenuItem *item,
3902                GtkFileChooserDefault *impl)
3903 {
3904   GSList *files;
3905
3906   files = search_get_selected_files (impl);
3907
3908   /* Sigh, just use the first one */
3909   if (files)
3910     {
3911       GFile *file = files->data;
3912
3913       gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (impl), file, NULL); /* NULL-GError */
3914     }
3915
3916   g_slist_foreach (files, (GFunc) g_object_unref, NULL);
3917   g_slist_free (files);
3918 }
3919
3920 /* callback used when the "Show Hidden Files" menu item is toggled */
3921 static void
3922 show_hidden_toggled_cb (GtkCheckMenuItem      *item,
3923                         GtkFileChooserDefault *impl)
3924 {
3925   g_object_set (impl,
3926                 "show-hidden", gtk_check_menu_item_get_active (item),
3927                 NULL);
3928 }
3929
3930 /* Callback used when the "Show Size Column" menu item is toggled */
3931 static void
3932 show_size_column_toggled_cb (GtkCheckMenuItem *item,
3933                              GtkFileChooserDefault *impl)
3934 {
3935   impl->show_size_column = gtk_check_menu_item_get_active (item);
3936
3937   gtk_tree_view_column_set_visible (impl->list_size_column,
3938                                     impl->show_size_column);
3939 }
3940
3941 /* Shows an error dialog about not being able to select a dragged file */
3942 static void
3943 error_selecting_dragged_file_dialog (GtkFileChooserDefault *impl,
3944                                      GFile                 *file,
3945                                      GError                *error)
3946 {
3947   error_dialog (impl,
3948                 _("Could not select file"),
3949                 file, error);
3950 }
3951
3952 static void
3953 file_list_drag_data_select_uris (GtkFileChooserDefault  *impl,
3954                                  gchar                 **uris)
3955 {
3956   int i;
3957   char *uri;
3958   GtkFileChooser *chooser = GTK_FILE_CHOOSER (impl);
3959
3960   for (i = 1; uris[i]; i++)
3961     {
3962       GFile *file;
3963       GError *error = NULL;
3964
3965       uri = uris[i];
3966       file = g_file_new_for_uri (uri);
3967
3968       gtk_file_chooser_default_select_file (chooser, file, &error);
3969       if (error)
3970         error_selecting_dragged_file_dialog (impl, file, error);
3971
3972       g_object_unref (file);
3973     }
3974 }
3975
3976 struct FileListDragData
3977 {
3978   GtkFileChooserDefault *impl;
3979   gchar **uris;
3980   GFile *file;
3981 };
3982
3983 static void
3984 file_list_drag_data_received_get_info_cb (GCancellable *cancellable,
3985                                           GFileInfo    *info,
3986                                           const GError *error,
3987                                           gpointer      user_data)
3988 {
3989   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
3990   struct FileListDragData *data = user_data;
3991   GtkFileChooser *chooser = GTK_FILE_CHOOSER (data->impl);
3992
3993   if (cancellable != data->impl->file_list_drag_data_received_cancellable)
3994     goto out;
3995
3996   data->impl->file_list_drag_data_received_cancellable = NULL;
3997
3998   if (cancelled || error)
3999     goto out;
4000
4001   if ((data->impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
4002        data->impl->action == GTK_FILE_CHOOSER_ACTION_SAVE) &&
4003       data->uris[1] == 0 && !error && _gtk_file_info_consider_as_directory (info))
4004     change_folder_and_display_error (data->impl, data->file, FALSE);
4005   else
4006     {
4007       GError *error = NULL;
4008
4009       gtk_file_chooser_default_unselect_all (chooser);
4010       gtk_file_chooser_default_select_file (chooser, data->file, &error);
4011       if (error)
4012         error_selecting_dragged_file_dialog (data->impl, data->file, error);
4013       else
4014         browse_files_center_selected_row (data->impl);
4015     }
4016
4017   if (data->impl->select_multiple)
4018     file_list_drag_data_select_uris (data->impl, data->uris);
4019
4020 out:
4021   g_object_unref (data->impl);
4022   g_strfreev (data->uris);
4023   g_object_unref (data->file);
4024   g_free (data);
4025
4026   g_object_unref (cancellable);
4027 }
4028
4029 static void
4030 file_list_drag_data_received_cb (GtkWidget        *widget,
4031                                  GdkDragContext   *context,
4032                                  gint              x,
4033                                  gint              y,
4034                                  GtkSelectionData *selection_data,
4035                                  guint             info,
4036                                  guint             time_,
4037                                  gpointer          data)
4038 {
4039   GtkFileChooserDefault *impl;
4040   gchar **uris;
4041   char *uri;
4042   GFile *file;
4043
4044   impl = GTK_FILE_CHOOSER_DEFAULT (data);
4045
4046   /* Allow only drags from other widgets; see bug #533891. */
4047   if (gtk_drag_get_source_widget (context) == widget)
4048     {
4049       g_signal_stop_emission_by_name (widget, "drag-data-received");
4050       return;
4051     }
4052
4053   /* Parse the text/uri-list string, navigate to the first one */
4054   uris = gtk_selection_data_get_uris (selection_data);
4055   if (uris && uris[0])
4056     {
4057       struct FileListDragData *data;
4058
4059       uri = uris[0];
4060       file = g_file_new_for_uri (uri);
4061
4062       data = g_new0 (struct FileListDragData, 1);
4063       data->impl = g_object_ref (impl);
4064       data->uris = uris;
4065       data->file = file;
4066
4067       if (impl->file_list_drag_data_received_cancellable)
4068         g_cancellable_cancel (impl->file_list_drag_data_received_cancellable);
4069
4070       impl->file_list_drag_data_received_cancellable =
4071         _gtk_file_system_get_info (impl->file_system, file,
4072                                    "standard::type",
4073                                    file_list_drag_data_received_get_info_cb,
4074                                    data);
4075     }
4076
4077   g_signal_stop_emission_by_name (widget, "drag-data-received");
4078 }
4079
4080 /* Don't do anything with the drag_drop signal */
4081 static gboolean
4082 file_list_drag_drop_cb (GtkWidget             *widget,
4083                         GdkDragContext        *context,
4084                         gint                   x,
4085                         gint                   y,
4086                         guint                  time_,
4087                         GtkFileChooserDefault *impl)
4088 {
4089   g_signal_stop_emission_by_name (widget, "drag-drop");
4090   return TRUE;
4091 }
4092
4093 /* Disable the normal tree drag motion handler, it makes it look like you're
4094    dropping the dragged item onto a tree item */
4095 static gboolean
4096 file_list_drag_motion_cb (GtkWidget             *widget,
4097                           GdkDragContext        *context,
4098                           gint                   x,
4099                           gint                   y,
4100                           guint                  time_,
4101                           GtkFileChooserDefault *impl)
4102 {
4103   g_signal_stop_emission_by_name (widget, "drag-motion");
4104   return TRUE;
4105 }
4106
4107 /* Sensitizes the "Copy file's location" context menu item if there is actually
4108  * a selection active.
4109  */
4110 static void
4111 check_copy_file_location_sensitivity (GtkFileChooserDefault *impl)
4112 {
4113   GtkTreeSelection *selection;
4114   gboolean active;
4115
4116   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
4117   if (gtk_tree_selection_count_selected_rows (selection) == 0)
4118     active = FALSE;
4119   else
4120     active = TRUE;
4121
4122   if (impl->browse_files_popup_menu_copy_file_location_item)
4123     gtk_widget_set_sensitive (impl->browse_files_popup_menu_copy_file_location_item, active);
4124 }
4125
4126 static GtkWidget *
4127 file_list_add_image_menu_item (GtkFileChooserDefault *impl,
4128                                const char *stock_name,
4129                                const char *mnemonic_label,
4130                                GCallback callback)
4131 {
4132   GtkWidget *item;
4133
4134   item = gtk_image_menu_item_new_with_mnemonic (mnemonic_label);
4135   gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item),
4136                                  gtk_image_new_from_stock (stock_name, GTK_ICON_SIZE_MENU));
4137   g_signal_connect (item, "activate", callback, impl);
4138   gtk_widget_show (item);
4139   gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item);
4140   
4141   return item;
4142 }
4143
4144 static GtkWidget *
4145 file_list_add_check_menu_item (GtkFileChooserDefault *impl,
4146                                const char *mnemonic_label,
4147                                GCallback callback)
4148 {
4149   GtkWidget *item;
4150
4151   item = gtk_check_menu_item_new_with_mnemonic (mnemonic_label);
4152   g_signal_connect (item, "toggled", callback, impl);
4153   gtk_widget_show (item);
4154   gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item);
4155
4156   return item;
4157 }
4158
4159 /* Constructs the popup menu for the file list if needed */
4160 static void
4161 file_list_build_popup_menu (GtkFileChooserDefault *impl)
4162 {
4163   GtkWidget *item;
4164
4165   if (impl->browse_files_popup_menu)
4166     return;
4167
4168   impl->browse_files_popup_menu = gtk_menu_new ();
4169   gtk_menu_attach_to_widget (GTK_MENU (impl->browse_files_popup_menu),
4170                              impl->browse_files_tree_view,
4171                              popup_menu_detach_cb);
4172
4173   impl->browse_files_popup_menu_visit_file_item         = file_list_add_image_menu_item (impl, GTK_STOCK_DIRECTORY, _("_Visit this file"),
4174                                                                                          G_CALLBACK (visit_file_cb));
4175
4176   impl->browse_files_popup_menu_copy_file_location_item = file_list_add_image_menu_item (impl, GTK_STOCK_COPY, _("_Copy file's location"),
4177                                                                                          G_CALLBACK (copy_file_location_cb));
4178
4179   impl->browse_files_popup_menu_add_shortcut_item       = file_list_add_image_menu_item (impl, GTK_STOCK_ADD, _("_Add to Bookmarks"),
4180                                                                                          G_CALLBACK (add_to_shortcuts_cb));
4181
4182   item = gtk_separator_menu_item_new ();
4183   gtk_widget_show (item);
4184   gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item);
4185
4186   impl->browse_files_popup_menu_hidden_files_item       = file_list_add_check_menu_item (impl, _("Show _Hidden Files"),
4187                                                                                          G_CALLBACK (show_hidden_toggled_cb));
4188
4189   impl->browse_files_popup_menu_size_column_item        = file_list_add_check_menu_item (impl, _("Show _Size Column"),
4190                                                                                          G_CALLBACK (show_size_column_toggled_cb));
4191
4192   bookmarks_check_add_sensitivity (impl);
4193   check_copy_file_location_sensitivity (impl);
4194 }
4195
4196 /* Updates the popup menu for the file list, creating it if necessary */
4197 static void
4198 file_list_update_popup_menu (GtkFileChooserDefault *impl)
4199 {
4200   file_list_build_popup_menu (impl);
4201
4202   /* The sensitivity of the Add to Bookmarks item is set in
4203    * bookmarks_check_add_sensitivity()
4204    */
4205
4206   /* 'Visit this file' */
4207   gtk_widget_set_visible (impl->browse_files_popup_menu_visit_file_item, (impl->operation_mode != OPERATION_MODE_BROWSE));
4208
4209   /* 'Show Hidden Files' */
4210   g_signal_handlers_block_by_func (impl->browse_files_popup_menu_hidden_files_item,
4211                                    G_CALLBACK (show_hidden_toggled_cb), impl);
4212   gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (impl->browse_files_popup_menu_hidden_files_item),
4213                                   impl->show_hidden);
4214   g_signal_handlers_unblock_by_func (impl->browse_files_popup_menu_hidden_files_item,
4215                                      G_CALLBACK (show_hidden_toggled_cb), impl);
4216
4217   /* 'Show Size Column' */
4218   g_signal_handlers_block_by_func (impl->browse_files_popup_menu_size_column_item,
4219                                    G_CALLBACK (show_size_column_toggled_cb), impl);
4220   gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (impl->browse_files_popup_menu_size_column_item),
4221                                   impl->show_size_column);
4222   g_signal_handlers_unblock_by_func (impl->browse_files_popup_menu_size_column_item,
4223                                      G_CALLBACK (show_size_column_toggled_cb), impl);
4224 }
4225
4226 static void
4227 popup_position_func (GtkMenu   *menu,
4228                      gint      *x,
4229                      gint      *y,
4230                      gboolean  *push_in,
4231                      gpointer   user_data)
4232 {
4233   GtkAllocation allocation;
4234   GtkWidget *widget = GTK_WIDGET (user_data);
4235   GdkScreen *screen = gtk_widget_get_screen (widget);
4236   GtkRequisition req;
4237   gint monitor_num;
4238   GdkRectangle monitor;
4239
4240   g_return_if_fail (gtk_widget_get_realized (widget));
4241
4242   gdk_window_get_origin (gtk_widget_get_window (widget), x, y);
4243
4244   gtk_widget_get_preferred_size (GTK_WIDGET (menu),
4245                                  &req, NULL);
4246
4247   gtk_widget_get_allocation (widget, &allocation);
4248   *x += (allocation.width - req.width) / 2;
4249   *y += (allocation.height - req.height) / 2;
4250
4251   monitor_num = gdk_screen_get_monitor_at_point (screen, *x, *y);
4252   gtk_menu_set_monitor (menu, monitor_num);
4253   gdk_screen_get_monitor_workarea (screen, monitor_num, &monitor);
4254
4255   *x = CLAMP (*x, monitor.x, monitor.x + MAX (0, monitor.width - req.width));
4256   *y = CLAMP (*y, monitor.y, monitor.y + MAX (0, monitor.height - req.height));
4257
4258   *push_in = FALSE;
4259 }
4260
4261 static void
4262 file_list_popup_menu (GtkFileChooserDefault *impl,
4263                       GdkEventButton        *event)
4264 {
4265   file_list_update_popup_menu (impl);
4266   if (event)
4267     gtk_menu_popup (GTK_MENU (impl->browse_files_popup_menu),
4268                     NULL, NULL, NULL, NULL,
4269                     event->button, event->time);
4270   else
4271     {
4272       gtk_menu_popup (GTK_MENU (impl->browse_files_popup_menu),
4273                       NULL, NULL,
4274                       popup_position_func, impl->browse_files_tree_view,
4275                       0, GDK_CURRENT_TIME);
4276       gtk_menu_shell_select_first (GTK_MENU_SHELL (impl->browse_files_popup_menu),
4277                                    FALSE);
4278     }
4279
4280 }
4281
4282 /* Callback used for the GtkWidget::popup-menu signal of the file list */
4283 static gboolean
4284 list_popup_menu_cb (GtkWidget *widget,
4285                     GtkFileChooserDefault *impl)
4286 {
4287   file_list_popup_menu (impl, NULL);
4288   return TRUE;
4289 }
4290
4291 /* Callback used when a button is pressed on the file list.  We trap button 3 to
4292  * bring up a popup menu.
4293  */
4294 static gboolean
4295 list_button_press_event_cb (GtkWidget             *widget,
4296                             GdkEventButton        *event,
4297                             GtkFileChooserDefault *impl)
4298 {
4299   static gboolean in_press = FALSE;
4300
4301   if (in_press)
4302     return FALSE;
4303
4304   if (!gdk_event_triggers_context_menu ((GdkEvent *) event))
4305     return FALSE;
4306
4307   in_press = TRUE;
4308   gtk_widget_event (impl->browse_files_tree_view, (GdkEvent *) event);
4309   in_press = FALSE;
4310
4311   file_list_popup_menu (impl, event);
4312   return TRUE;
4313 }
4314
4315 typedef struct {
4316   OperationMode operation_mode;
4317   gint general_column;
4318   gint model_column;
4319 } ColumnMap;
4320
4321 /* Sets the sort column IDs for the file list; needs to be done whenever we
4322  * change the model on the treeview.
4323  */
4324 static void
4325 file_list_set_sort_column_ids (GtkFileChooserDefault *impl)
4326 {
4327   gtk_tree_view_column_set_sort_column_id (impl->list_name_column, MODEL_COL_NAME);
4328   gtk_tree_view_column_set_sort_column_id (impl->list_mtime_column, MODEL_COL_MTIME);
4329   gtk_tree_view_column_set_sort_column_id (impl->list_size_column, MODEL_COL_SIZE);
4330 }
4331
4332 static gboolean
4333 file_list_query_tooltip_cb (GtkWidget  *widget,
4334                             gint        x,
4335                             gint        y,
4336                             gboolean    keyboard_tip,
4337                             GtkTooltip *tooltip,
4338                             gpointer    user_data)
4339 {
4340   GtkFileChooserDefault *impl = user_data;
4341   GtkTreeModel *model;
4342   GtkTreePath *path;
4343   GtkTreeIter iter;
4344   GFile *file;
4345   gchar *filename;
4346
4347   if (impl->operation_mode == OPERATION_MODE_BROWSE)
4348     return FALSE;
4349
4350
4351   if (!gtk_tree_view_get_tooltip_context (GTK_TREE_VIEW (impl->browse_files_tree_view),
4352                                           &x, &y,
4353                                           keyboard_tip,
4354                                           &model, &path, &iter))
4355     return FALSE;
4356                                        
4357   gtk_tree_model_get (model, &iter,
4358                       MODEL_COL_FILE, &file,
4359                       -1);
4360
4361   if (file == NULL)
4362     {
4363       gtk_tree_path_free (path);
4364       return FALSE;
4365     }
4366
4367   filename = g_file_get_path (file);
4368   gtk_tooltip_set_text (tooltip, filename);
4369   gtk_tree_view_set_tooltip_row (GTK_TREE_VIEW (impl->browse_files_tree_view),
4370                                  tooltip,
4371                                  path);
4372
4373   g_free (filename);
4374   g_object_unref (file);
4375   gtk_tree_path_free (path);
4376
4377   return TRUE;
4378 }
4379
4380 static void
4381 set_icon_cell_renderer_fixed_size (GtkFileChooserDefault *impl, GtkCellRenderer *renderer)
4382 {
4383   gint xpad, ypad;
4384
4385   gtk_cell_renderer_get_padding (renderer, &xpad, &ypad);
4386   gtk_cell_renderer_set_fixed_size (renderer, 
4387                                     xpad * 2 + impl->icon_size,
4388                                     ypad * 2 + impl->icon_size);
4389 }
4390
4391 /* Creates the widgets for the file list */
4392 static GtkWidget *
4393 create_file_list (GtkFileChooserDefault *impl)
4394 {
4395   GtkWidget *swin;
4396   GtkTreeSelection *selection;
4397   GtkTreeViewColumn *column;
4398   GtkCellRenderer *renderer;
4399
4400   /* Scrolled window */
4401   swin = gtk_scrolled_window_new (NULL, NULL);
4402   gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (swin),
4403                                   GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
4404   gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (swin),
4405                                        GTK_SHADOW_IN);
4406
4407   /* Tree/list view */
4408
4409   impl->browse_files_tree_view = gtk_tree_view_new ();
4410 #ifdef PROFILE_FILE_CHOOSER
4411   g_object_set_data (G_OBJECT (impl->browse_files_tree_view), "fmq-name", "file_list");
4412 #endif
4413   g_object_set_data (G_OBJECT (impl->browse_files_tree_view), I_("GtkFileChooserDefault"), impl);
4414   atk_object_set_name (gtk_widget_get_accessible (impl->browse_files_tree_view), _("Files"));
4415
4416   gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (impl->browse_files_tree_view), TRUE);
4417   gtk_container_add (GTK_CONTAINER (swin), impl->browse_files_tree_view);
4418
4419   gtk_drag_dest_set (impl->browse_files_tree_view,
4420                      GTK_DEST_DEFAULT_ALL,
4421                      NULL, 0,
4422                      GDK_ACTION_COPY | GDK_ACTION_MOVE);
4423   gtk_drag_dest_add_uri_targets (impl->browse_files_tree_view);
4424   
4425   g_signal_connect (impl->browse_files_tree_view, "row-activated",
4426                     G_CALLBACK (list_row_activated), impl);
4427   g_signal_connect (impl->browse_files_tree_view, "key-press-event",
4428                     G_CALLBACK (browse_files_key_press_event_cb), impl);
4429   g_signal_connect (impl->browse_files_tree_view, "popup-menu",
4430                     G_CALLBACK (list_popup_menu_cb), impl);
4431   g_signal_connect (impl->browse_files_tree_view, "button-press-event",
4432                     G_CALLBACK (list_button_press_event_cb), impl);
4433
4434   g_signal_connect (impl->browse_files_tree_view, "drag-data-received",
4435                     G_CALLBACK (file_list_drag_data_received_cb), impl);
4436   g_signal_connect (impl->browse_files_tree_view, "drag-drop",
4437                     G_CALLBACK (file_list_drag_drop_cb), impl);
4438   g_signal_connect (impl->browse_files_tree_view, "drag-motion",
4439                     G_CALLBACK (file_list_drag_motion_cb), impl);
4440
4441   g_object_set (impl->browse_files_tree_view, "has-tooltip", TRUE, NULL);
4442   g_signal_connect (impl->browse_files_tree_view, "query-tooltip",
4443                     G_CALLBACK (file_list_query_tooltip_cb), impl);
4444
4445   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
4446   gtk_tree_selection_set_select_function (selection,
4447                                           list_select_func,
4448                                           impl, NULL);
4449   gtk_tree_view_enable_model_drag_source (GTK_TREE_VIEW (impl->browse_files_tree_view),
4450                                           GDK_BUTTON1_MASK,
4451                                           NULL, 0,
4452                                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4453   gtk_drag_source_add_uri_targets (impl->browse_files_tree_view);
4454
4455   g_signal_connect (selection, "changed",
4456                     G_CALLBACK (list_selection_changed), impl);
4457
4458   /* Keep the column order in sync with update_cell_renderer_attributes() */
4459
4460   /* Filename column */
4461
4462   impl->list_name_column = gtk_tree_view_column_new ();
4463   gtk_tree_view_column_set_expand (impl->list_name_column, TRUE);
4464   gtk_tree_view_column_set_resizable (impl->list_name_column, TRUE);
4465   gtk_tree_view_column_set_title (impl->list_name_column, _("Name"));
4466
4467   renderer = gtk_cell_renderer_pixbuf_new ();
4468   /* We set a fixed size so that we get an empty slot even if no icons are loaded yet */
4469   set_icon_cell_renderer_fixed_size (impl, renderer);
4470   gtk_tree_view_column_pack_start (impl->list_name_column, renderer, FALSE);
4471
4472   impl->list_name_renderer = gtk_cell_renderer_text_new ();
4473   g_object_set (impl->list_name_renderer,
4474                 "ellipsize", PANGO_ELLIPSIZE_END,
4475                 NULL);
4476   g_signal_connect (impl->list_name_renderer, "edited",
4477                     G_CALLBACK (renderer_edited_cb), impl);
4478   g_signal_connect (impl->list_name_renderer, "editing-canceled",
4479                     G_CALLBACK (renderer_editing_canceled_cb), impl);
4480   gtk_tree_view_column_pack_start (impl->list_name_column, impl->list_name_renderer, TRUE);
4481
4482   gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), impl->list_name_column);
4483
4484   /* Size column */
4485
4486   column = gtk_tree_view_column_new ();
4487   gtk_tree_view_column_set_resizable (column, TRUE);
4488   gtk_tree_view_column_set_title (column, _("Size"));
4489
4490   renderer = gtk_cell_renderer_text_new ();
4491   g_object_set (renderer, 
4492                 "alignment", PANGO_ALIGN_RIGHT,
4493                 NULL);
4494   gtk_tree_view_column_pack_start (column, renderer, TRUE); /* bug: it doesn't expand */
4495   gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), column);
4496   impl->list_size_column = column;
4497
4498   /* Modification time column */
4499
4500   column = gtk_tree_view_column_new ();
4501   gtk_tree_view_column_set_resizable (column, TRUE);
4502   gtk_tree_view_column_set_title (column, _("Modified"));
4503
4504   renderer = gtk_cell_renderer_text_new ();
4505   gtk_tree_view_column_pack_start (column, renderer, TRUE);
4506   gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), column);
4507   impl->list_mtime_column = column;
4508   
4509   file_list_set_sort_column_ids (impl);
4510   update_cell_renderer_attributes (impl);
4511
4512   gtk_widget_show_all (swin);
4513
4514   return swin;
4515 }
4516
4517 /* Creates the widgets for the files/folders pane */
4518 static GtkWidget *
4519 file_pane_create (GtkFileChooserDefault *impl,
4520                   GtkSizeGroup          *size_group)
4521 {
4522   GtkWidget *vbox;
4523   GtkWidget *hbox;
4524   GtkWidget *widget;
4525
4526   vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
4527   gtk_widget_show (vbox);
4528
4529   /* Box for lists and preview */
4530
4531   hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, PREVIEW_HBOX_SPACING);
4532   gtk_box_pack_start (GTK_BOX (vbox), hbox, TRUE, TRUE, 0);
4533   gtk_widget_show (hbox);
4534
4535   /* File list */
4536
4537   widget = create_file_list (impl);
4538   gtk_box_pack_start (GTK_BOX (hbox), widget, TRUE, TRUE, 0);
4539   gtk_size_group_add_widget (size_group, widget);
4540
4541   /* Preview */
4542
4543   impl->preview_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
4544   gtk_box_pack_start (GTK_BOX (hbox), impl->preview_box, FALSE, FALSE, 0);
4545   /* Don't show preview box initially */
4546
4547   /* Filter combo */
4548
4549   impl->filter_combo_hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
4550
4551   widget = filter_create (impl);
4552
4553   gtk_widget_show (widget);
4554   gtk_box_pack_end (GTK_BOX (impl->filter_combo_hbox), widget, FALSE, FALSE, 0);
4555
4556   gtk_box_pack_end (GTK_BOX (vbox), impl->filter_combo_hbox, FALSE, FALSE, 0);
4557
4558   return vbox;
4559 }
4560
4561 static void
4562 location_entry_create (GtkFileChooserDefault *impl)
4563 {
4564   if (!impl->location_entry)
4565     impl->location_entry = _gtk_file_chooser_entry_new (TRUE);
4566
4567   _gtk_file_chooser_entry_set_local_only (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->local_only);
4568   _gtk_file_chooser_entry_set_action (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->action);
4569   gtk_entry_set_width_chars (GTK_ENTRY (impl->location_entry), 45);
4570   gtk_entry_set_activates_default (GTK_ENTRY (impl->location_entry), TRUE);
4571 }
4572
4573 /* Creates the widgets specific to Save mode */
4574 static void
4575 save_widgets_create (GtkFileChooserDefault *impl)
4576 {
4577   GtkWidget *vbox;
4578   GtkWidget *widget;
4579
4580   if (impl->save_widgets != NULL)
4581     return;
4582
4583   location_switch_to_path_bar (impl);
4584
4585   vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
4586
4587   impl->save_widgets_table = gtk_grid_new ();
4588   gtk_box_pack_start (GTK_BOX (vbox), impl->save_widgets_table, FALSE, FALSE, 0);
4589   gtk_widget_show (impl->save_widgets_table);
4590   gtk_grid_set_row_spacing (GTK_GRID (impl->save_widgets_table), 12);
4591   gtk_grid_set_column_spacing (GTK_GRID (impl->save_widgets_table), 12);
4592
4593   /* Label */
4594
4595   widget = gtk_label_new_with_mnemonic (_("_Name:"));
4596   gtk_widget_set_halign (widget, GTK_ALIGN_START);
4597   gtk_widget_set_valign (widget, GTK_ALIGN_CENTER);
4598   gtk_grid_attach (GTK_GRID (impl->save_widgets_table), widget, 0, 0, 1, 1);
4599   gtk_widget_show (widget);
4600
4601   /* Location entry */
4602
4603   location_entry_create (impl);
4604   gtk_widget_set_hexpand (impl->location_entry, TRUE);
4605   gtk_grid_attach (GTK_GRID (impl->save_widgets_table), impl->location_entry, 1, 0, 1, 1);
4606   gtk_widget_show (impl->location_entry);
4607   gtk_label_set_mnemonic_widget (GTK_LABEL (widget), impl->location_entry);
4608
4609   /* Folder combo */
4610   impl->save_folder_label = gtk_label_new (NULL);
4611   gtk_widget_set_halign (impl->save_folder_label, GTK_ALIGN_START);
4612   gtk_widget_set_valign (impl->save_folder_label, GTK_ALIGN_CENTER);
4613   gtk_grid_attach (GTK_GRID (impl->save_widgets_table), impl->save_folder_label, 0, 1, 1, 1);
4614   gtk_widget_show (impl->save_folder_label);
4615
4616   impl->save_widgets = vbox;
4617   gtk_box_pack_start (GTK_BOX (impl), impl->save_widgets, FALSE, FALSE, 0);
4618   gtk_box_reorder_child (GTK_BOX (impl), impl->save_widgets, 0);
4619   gtk_widget_show (impl->save_widgets);
4620 }
4621
4622 /* Destroys the widgets specific to Save mode */
4623 static void
4624 save_widgets_destroy (GtkFileChooserDefault *impl)
4625 {
4626   if (impl->save_widgets == NULL)
4627     return;
4628
4629   gtk_widget_destroy (impl->save_widgets);
4630   impl->save_widgets = NULL;
4631   impl->save_widgets_table = NULL;
4632   impl->location_entry = NULL;
4633   impl->save_folder_label = NULL;
4634 }
4635
4636 /* Turns on the path bar widget.  Can be called even if we are already in that
4637  * mode.
4638  */
4639 static void
4640 location_switch_to_path_bar (GtkFileChooserDefault *impl)
4641 {
4642   if (impl->location_entry)
4643     {
4644       gtk_widget_destroy (impl->location_entry);
4645       impl->location_entry = NULL;
4646     }
4647
4648   gtk_widget_hide (impl->location_entry_box);
4649 }
4650
4651 /* Turns on the location entry.  Can be called even if we are already in that
4652  * mode.
4653  */
4654 static void
4655 location_switch_to_filename_entry (GtkFileChooserDefault *impl)
4656 {
4657   /* when in search or recent files mode, we are not showing the
4658    * location_entry_box container, so there's no point in switching
4659    * to it.
4660    */
4661   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
4662       impl->operation_mode == OPERATION_MODE_RECENT)
4663     return;
4664
4665   /* Box */
4666
4667   gtk_widget_show (impl->location_entry_box);
4668
4669   /* Entry */
4670
4671   if (!impl->location_entry)
4672     {
4673       location_entry_create (impl);
4674       gtk_box_pack_start (GTK_BOX (impl->location_entry_box), impl->location_entry, TRUE, TRUE, 0);
4675       gtk_label_set_mnemonic_widget (GTK_LABEL (impl->location_label), impl->location_entry);
4676     }
4677
4678   /* Configure the entry */
4679
4680   _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->current_folder);
4681
4682   /* Done */
4683
4684   gtk_widget_show (impl->location_entry);
4685   gtk_widget_grab_focus (impl->location_entry);
4686 }
4687
4688 /* Sets a new location mode.  set_buttons determines whether the toggle button
4689  * for the mode will also be changed.
4690  */
4691 static void
4692 location_mode_set (GtkFileChooserDefault *impl,
4693                    LocationMode new_mode,
4694                    gboolean set_button)
4695 {
4696   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
4697       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
4698     {
4699       GtkWindow *toplevel;
4700       GtkWidget *current_focus;
4701       gboolean button_active;
4702       gboolean switch_to_file_list;
4703
4704       switch (new_mode)
4705         {
4706         case LOCATION_MODE_PATH_BAR:
4707           button_active = FALSE;
4708
4709           /* The location_entry will disappear when we switch to path bar mode.  So,
4710            * we'll focus the file list in that case, to avoid having a window with
4711            * no focused widget.
4712            */
4713           toplevel = get_toplevel (GTK_WIDGET (impl));
4714           switch_to_file_list = FALSE;
4715           if (toplevel)
4716             {
4717               current_focus = gtk_window_get_focus (toplevel);
4718               if (!current_focus || current_focus == impl->location_entry)
4719                 switch_to_file_list = TRUE;
4720             }
4721
4722           location_switch_to_path_bar (impl);
4723
4724           if (switch_to_file_list)
4725             gtk_widget_grab_focus (impl->browse_files_tree_view);
4726
4727           break;
4728
4729         case LOCATION_MODE_FILENAME_ENTRY:
4730           button_active = TRUE;
4731           location_switch_to_filename_entry (impl);
4732           break;
4733
4734         default:
4735           g_assert_not_reached ();
4736           return;
4737         }
4738
4739       if (set_button)
4740         {
4741           g_signal_handlers_block_by_func (impl->location_button,
4742                                            G_CALLBACK (location_button_toggled_cb), impl);
4743
4744           gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (impl->location_button), button_active);
4745
4746           g_signal_handlers_unblock_by_func (impl->location_button,
4747                                              G_CALLBACK (location_button_toggled_cb), impl);
4748         }
4749     }
4750
4751   impl->location_mode = new_mode;
4752 }
4753
4754 static void
4755 location_toggle_popup_handler (GtkFileChooserDefault *impl)
4756 {
4757   /* when in search or recent files mode, we are not showing the
4758    * location_entry_box container, so there's no point in switching
4759    * to it.
4760    */
4761   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
4762       impl->operation_mode == OPERATION_MODE_RECENT)
4763     return;
4764
4765   /* If the file entry is not visible, show it.
4766    * If it is visible, turn it off only if it is focused.  Otherwise, switch to the entry.
4767    */
4768   if (impl->location_mode == LOCATION_MODE_PATH_BAR)
4769     {
4770       location_mode_set (impl, LOCATION_MODE_FILENAME_ENTRY, TRUE);
4771     }
4772   else if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
4773     {
4774       if (gtk_widget_has_focus (impl->location_entry))
4775         {
4776           location_mode_set (impl, LOCATION_MODE_PATH_BAR, TRUE);
4777         }
4778       else
4779         {
4780           gtk_widget_grab_focus (impl->location_entry);
4781         }
4782     }
4783 }
4784
4785 /* Callback used when one of the location mode buttons is toggled */
4786 static void
4787 location_button_toggled_cb (GtkToggleButton *toggle,
4788                             GtkFileChooserDefault *impl)
4789 {
4790   gboolean is_active;
4791   LocationMode new_mode;
4792
4793   is_active = gtk_toggle_button_get_active (toggle);
4794
4795   if (is_active)
4796     {
4797       g_assert (impl->location_mode == LOCATION_MODE_PATH_BAR);
4798       new_mode = LOCATION_MODE_FILENAME_ENTRY;
4799     }
4800   else
4801     {
4802       g_assert (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY);
4803       new_mode = LOCATION_MODE_PATH_BAR;
4804     }
4805
4806   location_mode_set (impl, new_mode, FALSE);
4807 }
4808
4809 /* Creates a toggle button for the location entry. */
4810 static void
4811 location_button_create (GtkFileChooserDefault *impl)
4812 {
4813   GtkWidget *image;
4814   const char *str;
4815
4816   image = gtk_image_new_from_stock (GTK_STOCK_EDIT, GTK_ICON_SIZE_BUTTON);
4817   gtk_widget_show (image);
4818
4819   impl->location_button = g_object_new (GTK_TYPE_TOGGLE_BUTTON,
4820                                         "image", image,
4821                                         NULL);
4822
4823   g_signal_connect (impl->location_button, "toggled",
4824                     G_CALLBACK (location_button_toggled_cb), impl);
4825
4826   str = _("Type a file name");
4827
4828   gtk_widget_set_tooltip_text (impl->location_button, str);
4829   atk_object_set_name (gtk_widget_get_accessible (impl->location_button), str);
4830 }
4831
4832 typedef enum {
4833   PATH_BAR_FOLDER_PATH,
4834   PATH_BAR_SELECT_A_FOLDER,
4835   PATH_BAR_ERROR_NO_FILENAME,
4836   PATH_BAR_ERROR_NO_FOLDER,
4837   PATH_BAR_RECENTLY_USED,
4838   PATH_BAR_SEARCH
4839 } PathBarMode;
4840
4841 /* Creates the info bar for informational messages or warnings, with its icon and label */
4842 static void
4843 info_bar_create (GtkFileChooserDefault *impl)
4844 {
4845   GtkWidget *content_area;
4846
4847   impl->browse_select_a_folder_info_bar = gtk_info_bar_new ();
4848   impl->browse_select_a_folder_icon = gtk_image_new_from_stock (GTK_STOCK_DIRECTORY, GTK_ICON_SIZE_MENU);
4849   impl->browse_select_a_folder_label = gtk_label_new (NULL);
4850
4851   content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (impl->browse_select_a_folder_info_bar));
4852
4853   gtk_box_pack_start (GTK_BOX (content_area), impl->browse_select_a_folder_icon, FALSE, FALSE, 0);
4854   gtk_box_pack_start (GTK_BOX (content_area), impl->browse_select_a_folder_label, FALSE, FALSE, 0);
4855
4856   gtk_widget_show (impl->browse_select_a_folder_icon);
4857   gtk_widget_show (impl->browse_select_a_folder_label);
4858 }
4859
4860 /* Sets the info bar to show the appropriate informational or warning message */
4861 static void
4862 info_bar_set (GtkFileChooserDefault *impl, PathBarMode mode)
4863 {
4864   char *str;
4865   gboolean free_str;
4866   GtkMessageType message_type;
4867
4868   free_str = FALSE;
4869
4870   switch (mode)
4871     {
4872     case PATH_BAR_SELECT_A_FOLDER:
4873       str = g_strconcat ("<i>", _("Please select a folder below"), "</i>", NULL);
4874       free_str = TRUE;
4875       message_type = GTK_MESSAGE_OTHER;
4876       break;
4877
4878     case PATH_BAR_ERROR_NO_FILENAME:
4879       str = _("Please type a file name");
4880       message_type = GTK_MESSAGE_WARNING;
4881       break;
4882
4883     case PATH_BAR_ERROR_NO_FOLDER:
4884       str = _("Please select a folder below");
4885       message_type = GTK_MESSAGE_WARNING;
4886       break;
4887
4888     default:
4889       g_assert_not_reached ();
4890       return;
4891     }
4892
4893   gtk_info_bar_set_message_type (GTK_INFO_BAR (impl->browse_select_a_folder_info_bar), message_type);
4894   gtk_image_set_from_stock (GTK_IMAGE (impl->browse_select_a_folder_icon),
4895                             (message_type == GTK_MESSAGE_WARNING) ? GTK_STOCK_DIALOG_WARNING : GTK_STOCK_DIRECTORY,
4896                             GTK_ICON_SIZE_MENU);
4897   gtk_label_set_markup (GTK_LABEL (impl->browse_select_a_folder_label), str);
4898
4899   if (free_str)
4900     g_free (str);
4901 }
4902
4903 /* Creates the icon and label used to show that the file chooser is in Search or Recently-used mode */
4904 static void
4905 special_mode_widgets_create (GtkFileChooserDefault *impl)
4906 {
4907   impl->browse_special_mode_icon = gtk_image_new ();
4908   gtk_size_group_add_widget (impl->browse_path_bar_size_group, impl->browse_special_mode_icon);
4909   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->browse_special_mode_icon, FALSE, FALSE, 0);
4910
4911   impl->browse_special_mode_label = gtk_label_new (NULL);
4912   gtk_size_group_add_widget (impl->browse_path_bar_size_group, impl->browse_special_mode_label);
4913   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->browse_special_mode_label, FALSE, FALSE, 0);
4914 }
4915
4916 /* Creates the path bar's container and eveyrthing that goes in it: location button, pathbar, info bar, and Create Folder button */
4917 static void
4918 path_bar_widgets_create (GtkFileChooserDefault *impl)
4919 {
4920   /* Location widgets - note browse_path_bar_hbox is packed in the right place until switch_path_bar() */
4921   impl->browse_path_bar_hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
4922   gtk_widget_show (impl->browse_path_bar_hbox);
4923
4924   /* Size group that allows the path bar to be the same size between modes */
4925   impl->browse_path_bar_size_group = gtk_size_group_new (GTK_SIZE_GROUP_VERTICAL);
4926   gtk_size_group_set_ignore_hidden (impl->browse_path_bar_size_group, FALSE);
4927
4928   /* Location button */
4929   location_button_create (impl);
4930   gtk_size_group_add_widget (impl->browse_path_bar_size_group, impl->location_button);
4931   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->location_button, FALSE, FALSE, 0);
4932
4933   /* Path bar */
4934   impl->browse_path_bar = g_object_new (GTK_TYPE_PATH_BAR, NULL);
4935   _gtk_path_bar_set_file_system (GTK_PATH_BAR (impl->browse_path_bar), impl->file_system);
4936   g_signal_connect (impl->browse_path_bar, "path-clicked", G_CALLBACK (path_bar_clicked), impl);
4937
4938   gtk_size_group_add_widget (impl->browse_path_bar_size_group, impl->browse_path_bar);
4939   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->browse_path_bar, TRUE, TRUE, 0);
4940
4941   /* Info bar */
4942   info_bar_create (impl);
4943   gtk_size_group_add_widget (impl->browse_path_bar_size_group, impl->browse_select_a_folder_info_bar);
4944   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->browse_select_a_folder_info_bar, TRUE, TRUE, 0);
4945
4946   /* Widgets for special modes (recently-used in Open mode, Search mode) */
4947   special_mode_widgets_create (impl);
4948
4949   /* Create Folder */
4950   impl->browse_new_folder_button = gtk_button_new_with_mnemonic (_("Create Fo_lder"));
4951   g_signal_connect (impl->browse_new_folder_button, "clicked",
4952                     G_CALLBACK (new_folder_button_clicked), impl);
4953   gtk_size_group_add_widget (impl->browse_path_bar_size_group, impl->browse_new_folder_button);
4954   gtk_box_pack_end (GTK_BOX (impl->browse_path_bar_hbox), impl->browse_new_folder_button, FALSE, FALSE, 0);
4955 }
4956
4957 /* Sets the path bar's mode to show a label, the actual folder path, or a
4958  * warning message.  You may call this function with PATH_BAR_ERROR_* directly
4959  * if the pathbar is already showing the widgets you expect; otherwise, call
4960  * path_bar_update() instead to set the appropriate widgets automatically.
4961  */
4962 static void
4963 path_bar_set_mode (GtkFileChooserDefault *impl, PathBarMode mode)
4964 {
4965   gboolean path_bar_visible             = FALSE;
4966   gboolean special_mode_widgets_visible = FALSE;
4967   gboolean info_bar_visible             = FALSE;
4968   gboolean create_folder_visible        = FALSE;
4969
4970   char *tmp;
4971
4972   switch (mode)
4973     {
4974     case PATH_BAR_FOLDER_PATH:
4975       path_bar_visible = TRUE;
4976       break;
4977
4978     case PATH_BAR_SELECT_A_FOLDER:
4979     case PATH_BAR_ERROR_NO_FILENAME:
4980     case PATH_BAR_ERROR_NO_FOLDER:
4981       info_bar_set (impl, mode);
4982       info_bar_visible = TRUE;
4983       break;
4984
4985     case PATH_BAR_RECENTLY_USED:
4986       gtk_image_set_from_icon_name (GTK_IMAGE (impl->browse_special_mode_icon), "document-open-recent", GTK_ICON_SIZE_BUTTON);
4987
4988       tmp = g_strdup_printf ("<b>%s</b>", _("Recently Used"));
4989       gtk_label_set_markup (GTK_LABEL (impl->browse_special_mode_label), tmp);
4990       g_free (tmp);
4991
4992       special_mode_widgets_visible = TRUE;
4993       break;
4994
4995     case PATH_BAR_SEARCH:
4996       gtk_image_set_from_stock (GTK_IMAGE (impl->browse_special_mode_icon), GTK_STOCK_FIND, GTK_ICON_SIZE_BUTTON);
4997
4998       tmp = g_strdup_printf ("<b>%s</b>", _("Search:"));
4999       gtk_label_set_markup (GTK_LABEL (impl->browse_special_mode_label), tmp);
5000       g_free (tmp);
5001
5002       special_mode_widgets_visible = TRUE;
5003       break;
5004
5005     default:
5006       g_assert_not_reached ();
5007     }
5008
5009   gtk_widget_set_visible (impl->browse_path_bar,                        path_bar_visible);
5010   gtk_widget_set_visible (impl->browse_special_mode_icon,               special_mode_widgets_visible);
5011   gtk_widget_set_visible (impl->browse_special_mode_label,              special_mode_widgets_visible);
5012   gtk_widget_set_visible (impl->browse_select_a_folder_info_bar,        info_bar_visible);
5013
5014   if (path_bar_visible)
5015     {
5016       if (impl->create_folders
5017           && impl->action != GTK_FILE_CHOOSER_ACTION_OPEN
5018           && impl->operation_mode != OPERATION_MODE_RECENT)
5019         create_folder_visible = TRUE;
5020     }
5021
5022   gtk_widget_set_visible (impl->browse_new_folder_button,               create_folder_visible);
5023 }
5024
5025 /* Creates the main hpaned with the widgets shared by Open and Save mode */
5026 static void
5027 browse_widgets_create (GtkFileChooserDefault *impl)
5028 {
5029   GtkWidget *hpaned;
5030   GtkWidget *widget;
5031   GtkSizeGroup *size_group;
5032
5033   impl->browse_widgets_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
5034   gtk_box_pack_start (GTK_BOX (impl), impl->browse_widgets_box, TRUE, TRUE, 0);
5035   gtk_widget_show (impl->browse_widgets_box);
5036
5037   impl->browse_header_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
5038   gtk_box_pack_start (GTK_BOX (impl->browse_widgets_box), impl->browse_header_box, FALSE, FALSE, 0);
5039   gtk_widget_show (impl->browse_header_box);
5040
5041   /* Path bar, info bar, and their respective machinery - the browse_path_bar_hbox will get packed elsewhere */
5042   path_bar_widgets_create (impl);
5043
5044   /* Box for the location label and entry */
5045
5046   impl->location_entry_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
5047   gtk_box_pack_start (GTK_BOX (impl->browse_header_box), impl->location_entry_box, FALSE, FALSE, 0);
5048
5049   impl->location_label = gtk_label_new_with_mnemonic (_("_Location:"));
5050   gtk_widget_show (impl->location_label);
5051   gtk_box_pack_start (GTK_BOX (impl->location_entry_box), impl->location_label, FALSE, FALSE, 0);
5052
5053   /* size group is used by the scrolled windows of the panes */
5054   size_group = gtk_size_group_new (GTK_SIZE_GROUP_VERTICAL);
5055
5056   /* Paned widget */
5057
5058   hpaned = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL);
5059   gtk_widget_show (hpaned);
5060   gtk_box_pack_start (GTK_BOX (impl->browse_widgets_box), hpaned, TRUE, TRUE, 0);
5061
5062   widget = shortcuts_pane_create (impl, size_group);
5063   gtk_paned_pack1 (GTK_PANED (hpaned), widget, FALSE, FALSE);
5064   widget = file_pane_create (impl, size_group);
5065   gtk_paned_pack2 (GTK_PANED (hpaned), widget, TRUE, FALSE);
5066   gtk_paned_set_position (GTK_PANED (hpaned), 148);
5067   g_object_unref (size_group);
5068 }
5069
5070 static GObject*
5071 gtk_file_chooser_default_constructor (GType                  type,
5072                                       guint                  n_construct_properties,
5073                                       GObjectConstructParam *construct_params)
5074 {
5075   GtkFileChooserDefault *impl;
5076   GObject *object;
5077
5078   profile_start ("start", NULL);
5079
5080   object = G_OBJECT_CLASS (_gtk_file_chooser_default_parent_class)->constructor (type,
5081                                                                                 n_construct_properties,
5082                                                                                 construct_params);
5083   impl = GTK_FILE_CHOOSER_DEFAULT (object);
5084
5085   g_assert (impl->file_system);
5086
5087   gtk_widget_push_composite_child ();
5088
5089   /* Shortcuts model */
5090   shortcuts_model_create (impl);
5091
5092   /* The browse widgets */
5093   browse_widgets_create (impl);
5094
5095   /* Alignment to hold extra widget */
5096   impl->extra_align = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
5097   gtk_widget_set_halign (impl->extra_align, GTK_ALIGN_START);
5098   gtk_widget_set_valign (impl->extra_align, GTK_ALIGN_CENTER);
5099   gtk_box_pack_start (GTK_BOX (impl), impl->extra_align, FALSE, FALSE, 0);
5100
5101   gtk_widget_pop_composite_child ();
5102   update_appearance (impl);
5103
5104   profile_end ("end", NULL);
5105
5106   return object;
5107 }
5108
5109 /* Sets the extra_widget by packing it in the appropriate place */
5110 static void
5111 set_extra_widget (GtkFileChooserDefault *impl,
5112                   GtkWidget             *extra_widget)
5113 {
5114   if (extra_widget)
5115     {
5116       g_object_ref (extra_widget);
5117       /* FIXME: is this right ? */
5118       gtk_widget_show (extra_widget);
5119     }
5120
5121   if (impl->extra_widget)
5122     {
5123       gtk_container_remove (GTK_CONTAINER (impl->extra_align), impl->extra_widget);
5124       g_object_unref (impl->extra_widget);
5125     }
5126
5127   impl->extra_widget = extra_widget;
5128   if (impl->extra_widget)
5129     {
5130       gtk_container_add (GTK_CONTAINER (impl->extra_align), impl->extra_widget);
5131       gtk_widget_show (impl->extra_align);
5132     }
5133   else
5134     gtk_widget_hide (impl->extra_align);
5135 }
5136
5137 static void
5138 set_local_only (GtkFileChooserDefault *impl,
5139                 gboolean               local_only)
5140 {
5141   if (local_only != impl->local_only)
5142     {
5143       impl->local_only = local_only;
5144
5145       if (impl->location_entry)
5146         _gtk_file_chooser_entry_set_local_only (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), local_only);
5147
5148       if (impl->shortcuts_model && impl->file_system)
5149         {
5150           shortcuts_add_volumes (impl);
5151           shortcuts_add_bookmarks (impl);
5152         }
5153
5154       if (local_only && impl->current_folder &&
5155            !g_file_is_native (impl->current_folder))
5156         {
5157           /* If we are pointing to a non-local folder, make an effort to change
5158            * back to a local folder, but it's really up to the app to not cause
5159            * such a situation, so we ignore errors.
5160            */
5161           const gchar *home = g_get_home_dir ();
5162           GFile *home_file;
5163
5164           if (home == NULL)
5165             return;
5166
5167           home_file = g_file_new_for_path (home);
5168
5169           gtk_file_chooser_set_current_folder_file (GTK_FILE_CHOOSER (impl), home_file, NULL);
5170
5171           g_object_unref (home_file);
5172         }
5173     }
5174 }
5175
5176 static void
5177 volumes_bookmarks_changed_cb (GtkFileSystem         *file_system,
5178                               GtkFileChooserDefault *impl)
5179 {
5180   shortcuts_add_volumes (impl);
5181   shortcuts_add_bookmarks (impl);
5182
5183   bookmarks_check_add_sensitivity (impl);
5184   bookmarks_check_remove_sensitivity (impl);
5185   shortcuts_check_popup_sensitivity (impl);
5186 }
5187
5188 /* Sets the file chooser to multiple selection mode */
5189 static void
5190 set_select_multiple (GtkFileChooserDefault *impl,
5191                      gboolean               select_multiple,
5192                      gboolean               property_notify)
5193 {
5194   GtkTreeSelection *selection;
5195   GtkSelectionMode mode;
5196
5197   if (select_multiple == impl->select_multiple)
5198     return;
5199
5200   mode = select_multiple ? GTK_SELECTION_MULTIPLE : GTK_SELECTION_SINGLE;
5201
5202   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
5203   gtk_tree_selection_set_mode (selection, mode);
5204
5205   gtk_tree_view_set_rubber_banding (GTK_TREE_VIEW (impl->browse_files_tree_view), select_multiple);
5206
5207   impl->select_multiple = select_multiple;
5208   g_object_notify (G_OBJECT (impl), "select-multiple");
5209
5210   check_preview_change (impl);
5211 }
5212
5213 static void
5214 set_file_system_backend (GtkFileChooserDefault *impl)
5215 {
5216   profile_start ("start for backend", "default");
5217
5218   impl->file_system = _gtk_file_system_new ();
5219
5220   g_signal_connect (impl->file_system, "volumes-changed",
5221                     G_CALLBACK (volumes_bookmarks_changed_cb), impl);
5222   g_signal_connect (impl->file_system, "bookmarks-changed",
5223                     G_CALLBACK (volumes_bookmarks_changed_cb), impl);
5224
5225   profile_end ("end", NULL);
5226 }
5227
5228 static void
5229 unset_file_system_backend (GtkFileChooserDefault *impl)
5230 {
5231   g_signal_handlers_disconnect_by_func (impl->file_system,
5232                                         G_CALLBACK (volumes_bookmarks_changed_cb), impl);
5233
5234   g_object_unref (impl->file_system);
5235
5236   impl->file_system = NULL;
5237 }
5238
5239 /* Saves the widgets around the pathbar so they can be reparented later
5240  * in the correct place.  This function must be called paired with
5241  * restore_path_bar().
5242  */
5243 static void
5244 save_path_bar (GtkFileChooserDefault *impl)
5245 {
5246   GtkWidget *parent;
5247
5248   g_object_ref (impl->browse_path_bar_hbox);
5249
5250   parent = gtk_widget_get_parent (impl->browse_path_bar_hbox);
5251   if (parent)
5252     gtk_container_remove (GTK_CONTAINER (parent), impl->browse_path_bar_hbox);
5253 }
5254
5255 /* Reparents the path bar and the "Create folder" button to the right place:
5256  * Above the file list in Open mode, or to the right of the "Save in folder:"
5257  * label in Save mode.  The save_path_bar() function must be called before this
5258  * one.
5259  */
5260 static void
5261 restore_path_bar (GtkFileChooserDefault *impl)
5262 {
5263   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
5264       || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
5265     {
5266       gtk_box_pack_start (GTK_BOX (impl->browse_header_box), impl->browse_path_bar_hbox, FALSE, FALSE, 0);
5267       gtk_box_reorder_child (GTK_BOX (impl->browse_header_box), impl->browse_path_bar_hbox, 0);
5268     }
5269   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
5270            || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5271     {
5272       gtk_widget_set_hexpand (impl->browse_path_bar_hbox, TRUE);
5273       gtk_grid_attach (GTK_GRID (impl->save_widgets_table), impl->browse_path_bar_hbox, 1, 1, 1, 1);
5274       gtk_label_set_mnemonic_widget (GTK_LABEL (impl->save_folder_label), impl->browse_path_bar);
5275     }
5276   else
5277     g_assert_not_reached ();
5278
5279   g_object_unref (impl->browse_path_bar_hbox);
5280 }
5281
5282 /* Takes the folder stored in a row in the recent_model, and puts it in the pathbar */
5283 static void
5284 put_recent_folder_in_pathbar (GtkFileChooserDefault *impl, GtkTreeIter *iter)
5285 {
5286   GFile *file;
5287
5288   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), iter,
5289                       MODEL_COL_FILE, &file,
5290                       -1);
5291   _gtk_path_bar_set_file (GTK_PATH_BAR (impl->browse_path_bar), file, FALSE);
5292   g_object_unref (file);
5293 }
5294
5295 /* Sets the pathbar in the appropriate mode according to the current operation mode and action.  This is the central function for
5296  * dealing with the pathbar's widgets; as long as impl->action and impl->operation_mode are set correctly, then calling this
5297  * function will update all the pathbar's widgets.
5298  */
5299 static void
5300 path_bar_update (GtkFileChooserDefault *impl)
5301 {
5302   PathBarMode mode;
5303
5304   switch (impl->operation_mode)
5305     {
5306     case OPERATION_MODE_BROWSE:
5307       mode = PATH_BAR_FOLDER_PATH;
5308       break;
5309
5310     case OPERATION_MODE_RECENT:
5311       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
5312         {
5313           GtkTreeSelection *selection;
5314           gboolean have_selected;
5315           GtkTreeIter iter;
5316
5317           selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
5318
5319           /* Save mode means single-selection mode, so the following is valid */
5320           have_selected = gtk_tree_selection_get_selected (selection, NULL, &iter);
5321
5322           if (have_selected)
5323             {
5324               mode = PATH_BAR_FOLDER_PATH;
5325               put_recent_folder_in_pathbar (impl, &iter);
5326             }
5327           else
5328             mode = PATH_BAR_SELECT_A_FOLDER;
5329         }
5330       else
5331         mode = PATH_BAR_RECENTLY_USED;
5332
5333       break;
5334
5335     case OPERATION_MODE_SEARCH:
5336       mode = PATH_BAR_SEARCH;
5337       break;
5338
5339     default:
5340       g_assert_not_reached ();
5341       return;
5342     }
5343
5344   path_bar_set_mode (impl, mode);
5345 }
5346
5347 static void
5348 operation_mode_discard_search_widgets (GtkFileChooserDefault *impl)
5349 {
5350   if (impl->search_hbox)
5351     {
5352       gtk_widget_destroy (impl->search_hbox);
5353
5354       impl->search_hbox = NULL;
5355       impl->search_entry = NULL;
5356     }
5357 }
5358
5359 /* Stops running operations like populating the browse model, searches, and the recent-files model */
5360 static void
5361 operation_mode_stop (GtkFileChooserDefault *impl, OperationMode mode)
5362 {
5363   switch (mode)
5364     {
5365     case OPERATION_MODE_BROWSE:
5366       stop_loading_and_clear_list_model (impl, TRUE);
5367       break;
5368
5369     case OPERATION_MODE_SEARCH:
5370       search_stop_searching (impl, FALSE);
5371       search_clear_model (impl, TRUE);
5372
5373       operation_mode_discard_search_widgets (impl);
5374       break;
5375
5376     case OPERATION_MODE_RECENT:
5377       recent_stop_loading (impl);
5378       recent_clear_model (impl, TRUE);
5379       break;
5380
5381     default:
5382       g_assert_not_reached ();
5383     }
5384 }
5385
5386 static void
5387 operation_mode_set_browse (GtkFileChooserDefault *impl)
5388 {
5389   path_bar_update (impl);
5390
5391   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
5392       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
5393     {
5394       gtk_widget_show (impl->location_button);
5395       location_mode_set (impl, impl->location_mode, TRUE);
5396
5397       if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
5398         gtk_widget_show (impl->location_entry_box);
5399     }
5400 }
5401
5402 static void
5403 operation_mode_set_search (GtkFileChooserDefault *impl)
5404 {
5405   g_assert (impl->search_hbox == NULL);
5406   g_assert (impl->search_entry == NULL);
5407   g_assert (impl->search_model == NULL);
5408
5409   search_setup_widgets (impl);
5410 }
5411
5412 static void
5413 operation_mode_set_recent (GtkFileChooserDefault *impl)
5414 {
5415   path_bar_update (impl);
5416
5417   /* Hide the location widgets temporarily */
5418   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
5419       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
5420     {
5421       gtk_widget_hide (impl->location_button);
5422       gtk_widget_hide (impl->location_entry_box);
5423     }
5424
5425   recent_start_loading (impl);
5426 }
5427
5428 /* Sometimes we need to frob the selection in the shortcuts list manually */
5429 static void
5430 shortcuts_select_item_without_activating (GtkFileChooserDefault *impl, int pos)
5431 {
5432   GtkTreeSelection *selection;
5433   GtkTreePath *path;
5434
5435   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view));
5436
5437   g_signal_handlers_block_by_func (selection, G_CALLBACK (shortcuts_selection_changed_cb), impl);
5438
5439   path = gtk_tree_path_new_from_indices (pos, -1);
5440   gtk_tree_selection_select_path (selection, path);
5441   gtk_tree_path_free (path);
5442
5443   g_signal_handlers_unblock_by_func (selection, G_CALLBACK (shortcuts_selection_changed_cb), impl);
5444 }
5445
5446 static void
5447 operation_mode_set (GtkFileChooserDefault *impl, OperationMode mode)
5448 {
5449   ShortcutsIndex shortcut_to_select;
5450
5451   operation_mode_stop (impl, impl->operation_mode);
5452
5453   impl->operation_mode = mode;
5454
5455   switch (impl->operation_mode)
5456     {
5457     case OPERATION_MODE_BROWSE:
5458       operation_mode_set_browse (impl);
5459       shortcut_to_select = SHORTCUTS_CURRENT_FOLDER;
5460       break;
5461
5462     case OPERATION_MODE_SEARCH:
5463       operation_mode_set_search (impl);
5464       shortcut_to_select = SHORTCUTS_SEARCH;
5465       break;
5466
5467     case OPERATION_MODE_RECENT:
5468       operation_mode_set_recent (impl);
5469       shortcut_to_select = SHORTCUTS_RECENT;
5470       break;
5471
5472     default:
5473       g_assert_not_reached ();
5474       return;
5475     }
5476
5477   if (shortcut_to_select != SHORTCUTS_CURRENT_FOLDER)
5478     shortcuts_select_item_without_activating (impl, shortcuts_get_index (impl, shortcut_to_select));
5479 }
5480
5481 /* This function is basically a do_all function.
5482  *
5483  * It sets the visibility on all the widgets based on the current state, and
5484  * moves the custom_widget if needed.
5485  */
5486 static void
5487 update_appearance (GtkFileChooserDefault *impl)
5488 {
5489   save_path_bar (impl);
5490
5491   if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5492       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5493     {
5494       const char *text;
5495
5496       gtk_widget_hide (impl->location_button);
5497       save_widgets_create (impl);
5498
5499       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
5500         text = _("Save in _folder:");
5501       else
5502         text = _("Create in _folder:");
5503
5504       gtk_label_set_text_with_mnemonic (GTK_LABEL (impl->save_folder_label), text);
5505
5506       if (impl->select_multiple)
5507         {
5508           g_warning ("Save mode cannot be set in conjunction with multiple selection mode.  "
5509                      "Re-setting to single selection mode.");
5510           set_select_multiple (impl, FALSE, TRUE);
5511         }
5512     }
5513   else if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
5514            impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
5515     {
5516       gtk_widget_show (impl->location_button);
5517       save_widgets_destroy (impl);
5518       location_mode_set (impl, impl->location_mode, TRUE);
5519     }
5520
5521   if (impl->location_entry)
5522     _gtk_file_chooser_entry_set_action (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->action);
5523
5524   restore_path_bar (impl);
5525   path_bar_update (impl);
5526
5527   /* This *is* needed; we need to redraw the file list because the "sensitivity"
5528    * of files may change depending whether we are in a file or folder-only mode.
5529    */
5530   gtk_widget_queue_draw (impl->browse_files_tree_view);
5531
5532   emit_default_size_changed (impl);
5533 }
5534
5535 static void
5536 gtk_file_chooser_default_set_property (GObject      *object,
5537                                        guint         prop_id,
5538                                        const GValue *value,
5539                                        GParamSpec   *pspec)
5540
5541 {
5542   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (object);
5543
5544   switch (prop_id)
5545     {
5546     case GTK_FILE_CHOOSER_PROP_ACTION:
5547       {
5548         GtkFileChooserAction action = g_value_get_enum (value);
5549
5550         if (action != impl->action)
5551           {
5552             gtk_file_chooser_default_unselect_all (GTK_FILE_CHOOSER (impl));
5553             
5554             if ((action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5555                  action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5556                 && impl->select_multiple)
5557               {
5558                 g_warning ("Tried to change the file chooser action to SAVE or CREATE_FOLDER, but "
5559                            "this is not allowed in multiple selection mode.  Resetting the file chooser "
5560                            "to single selection mode.");
5561                 set_select_multiple (impl, FALSE, TRUE);
5562               }
5563             impl->action = action;
5564             update_cell_renderer_attributes (impl);
5565             update_appearance (impl);
5566             settings_load (impl);
5567           }
5568       }
5569       break;
5570
5571     case GTK_FILE_CHOOSER_PROP_FILTER:
5572       set_current_filter (impl, g_value_get_object (value));
5573       break;
5574
5575     case GTK_FILE_CHOOSER_PROP_LOCAL_ONLY:
5576       set_local_only (impl, g_value_get_boolean (value));
5577       break;
5578
5579     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET:
5580       set_preview_widget (impl, g_value_get_object (value));
5581       break;
5582
5583     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET_ACTIVE:
5584       impl->preview_widget_active = g_value_get_boolean (value);
5585       update_preview_widget_visibility (impl);
5586       break;
5587
5588     case GTK_FILE_CHOOSER_PROP_USE_PREVIEW_LABEL:
5589       impl->use_preview_label = g_value_get_boolean (value);
5590       update_preview_widget_visibility (impl);
5591       break;
5592
5593     case GTK_FILE_CHOOSER_PROP_EXTRA_WIDGET:
5594       set_extra_widget (impl, g_value_get_object (value));
5595       break;
5596
5597     case GTK_FILE_CHOOSER_PROP_SELECT_MULTIPLE:
5598       {
5599         gboolean select_multiple = g_value_get_boolean (value);
5600         if ((impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5601              impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5602             && select_multiple)
5603           {
5604             g_warning ("Tried to set the file chooser to multiple selection mode, but this is "
5605                        "not allowed in SAVE or CREATE_FOLDER modes.  Ignoring the change and "
5606                        "leaving the file chooser in single selection mode.");
5607             return;
5608           }
5609
5610         set_select_multiple (impl, select_multiple, FALSE);
5611       }
5612       break;
5613
5614     case GTK_FILE_CHOOSER_PROP_SHOW_HIDDEN:
5615       {
5616         gboolean show_hidden = g_value_get_boolean (value);
5617         if (show_hidden != impl->show_hidden)
5618           {
5619             impl->show_hidden = show_hidden;
5620
5621             if (impl->browse_files_model)
5622               _gtk_file_system_model_set_show_hidden (impl->browse_files_model, show_hidden);
5623           }
5624       }
5625       break;
5626
5627     case GTK_FILE_CHOOSER_PROP_DO_OVERWRITE_CONFIRMATION:
5628       {
5629         gboolean do_overwrite_confirmation = g_value_get_boolean (value);
5630         impl->do_overwrite_confirmation = do_overwrite_confirmation;
5631       }
5632       break;
5633
5634     case GTK_FILE_CHOOSER_PROP_CREATE_FOLDERS:
5635       {
5636         gboolean create_folders = g_value_get_boolean (value);
5637         impl->create_folders = create_folders;
5638         update_appearance (impl);
5639       }
5640       break;
5641
5642     default:
5643       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5644       break;
5645     }
5646 }
5647
5648 static void
5649 gtk_file_chooser_default_get_property (GObject    *object,
5650                                        guint       prop_id,
5651                                        GValue     *value,
5652                                        GParamSpec *pspec)
5653 {
5654   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (object);
5655
5656   switch (prop_id)
5657     {
5658     case GTK_FILE_CHOOSER_PROP_ACTION:
5659       g_value_set_enum (value, impl->action);
5660       break;
5661
5662     case GTK_FILE_CHOOSER_PROP_FILTER:
5663       g_value_set_object (value, impl->current_filter);
5664       break;
5665
5666     case GTK_FILE_CHOOSER_PROP_LOCAL_ONLY:
5667       g_value_set_boolean (value, impl->local_only);
5668       break;
5669
5670     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET:
5671       g_value_set_object (value, impl->preview_widget);
5672       break;
5673
5674     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET_ACTIVE:
5675       g_value_set_boolean (value, impl->preview_widget_active);
5676       break;
5677
5678     case GTK_FILE_CHOOSER_PROP_USE_PREVIEW_LABEL:
5679       g_value_set_boolean (value, impl->use_preview_label);
5680       break;
5681
5682     case GTK_FILE_CHOOSER_PROP_EXTRA_WIDGET:
5683       g_value_set_object (value, impl->extra_widget);
5684       break;
5685
5686     case GTK_FILE_CHOOSER_PROP_SELECT_MULTIPLE:
5687       g_value_set_boolean (value, impl->select_multiple);
5688       break;
5689
5690     case GTK_FILE_CHOOSER_PROP_SHOW_HIDDEN:
5691       g_value_set_boolean (value, impl->show_hidden);
5692       break;
5693
5694     case GTK_FILE_CHOOSER_PROP_DO_OVERWRITE_CONFIRMATION:
5695       g_value_set_boolean (value, impl->do_overwrite_confirmation);
5696       break;
5697
5698     case GTK_FILE_CHOOSER_PROP_CREATE_FOLDERS:
5699       g_value_set_boolean (value, impl->create_folders);
5700       break;
5701
5702     default:
5703       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5704       break;
5705     }
5706 }
5707
5708 /* This cancels everything that may be going on in the background. */
5709 static void
5710 cancel_all_operations (GtkFileChooserDefault *impl)
5711 {
5712   GSList *l;
5713
5714   pending_select_files_free (impl);
5715
5716   /* cancel all pending operations */
5717   if (impl->pending_cancellables)
5718     {
5719       for (l = impl->pending_cancellables; l; l = l->next)
5720         {
5721           GCancellable *cancellable = G_CANCELLABLE (l->data);
5722           g_cancellable_cancel (cancellable);
5723         }
5724       g_slist_free (impl->pending_cancellables);
5725       impl->pending_cancellables = NULL;
5726     }
5727
5728   if (impl->reload_icon_cancellables)
5729     {
5730       for (l = impl->reload_icon_cancellables; l; l = l->next)
5731         {
5732           GCancellable *cancellable = G_CANCELLABLE (l->data);
5733           g_cancellable_cancel (cancellable);
5734         }
5735       g_slist_free (impl->reload_icon_cancellables);
5736       impl->reload_icon_cancellables = NULL;
5737     }
5738
5739   if (impl->loading_shortcuts)
5740     {
5741       for (l = impl->loading_shortcuts; l; l = l->next)
5742         {
5743           GCancellable *cancellable = G_CANCELLABLE (l->data);
5744           g_cancellable_cancel (cancellable);
5745         }
5746       g_slist_free (impl->loading_shortcuts);
5747       impl->loading_shortcuts = NULL;
5748     }
5749
5750   if (impl->file_list_drag_data_received_cancellable)
5751     {
5752       g_cancellable_cancel (impl->file_list_drag_data_received_cancellable);
5753       impl->file_list_drag_data_received_cancellable = NULL;
5754     }
5755
5756   if (impl->update_current_folder_cancellable)
5757     {
5758       g_cancellable_cancel (impl->update_current_folder_cancellable);
5759       impl->update_current_folder_cancellable = NULL;
5760     }
5761
5762   if (impl->should_respond_get_info_cancellable)
5763     {
5764       g_cancellable_cancel (impl->should_respond_get_info_cancellable);
5765       impl->should_respond_get_info_cancellable = NULL;
5766     }
5767
5768   if (impl->update_from_entry_cancellable)
5769     {
5770       g_cancellable_cancel (impl->update_from_entry_cancellable);
5771       impl->update_from_entry_cancellable = NULL;
5772     }
5773
5774   if (impl->shortcuts_activate_iter_cancellable)
5775     {
5776       g_cancellable_cancel (impl->shortcuts_activate_iter_cancellable);
5777       impl->shortcuts_activate_iter_cancellable = NULL;
5778     }
5779
5780   search_stop_searching (impl, TRUE);
5781   recent_stop_loading (impl);
5782 }
5783
5784 /* Removes the settings signal handler.  It's safe to call multiple times */
5785 static void
5786 remove_settings_signal (GtkFileChooserDefault *impl,
5787                         GdkScreen             *screen)
5788 {
5789   if (impl->settings_signal_id)
5790     {
5791       GtkSettings *settings;
5792
5793       settings = gtk_settings_get_for_screen (screen);
5794       g_signal_handler_disconnect (settings,
5795                                    impl->settings_signal_id);
5796       impl->settings_signal_id = 0;
5797     }
5798 }
5799
5800 static void
5801 gtk_file_chooser_default_dispose (GObject *object)
5802 {
5803   GtkFileChooserDefault *impl = (GtkFileChooserDefault *) object;
5804
5805   cancel_all_operations (impl);
5806
5807   if (impl->extra_widget)
5808     {
5809       g_object_unref (impl->extra_widget);
5810       impl->extra_widget = NULL;
5811     }
5812
5813   remove_settings_signal (impl, gtk_widget_get_screen (GTK_WIDGET (impl)));
5814
5815   G_OBJECT_CLASS (_gtk_file_chooser_default_parent_class)->dispose (object);
5816 }
5817
5818 /* We override show-all since we have internal widgets that
5819  * shouldn't be shown when you call show_all(), like the filter
5820  * combo box.
5821  */
5822 static void
5823 gtk_file_chooser_default_show_all (GtkWidget *widget)
5824 {
5825   GtkFileChooserDefault *impl = (GtkFileChooserDefault *) widget;
5826
5827   gtk_widget_show (widget);
5828
5829   if (impl->extra_widget)
5830     gtk_widget_show_all (impl->extra_widget);
5831 }
5832
5833 /* Handler for GtkWindow::set-focus; this is where we save the last-focused
5834  * widget on our toplevel.  See gtk_file_chooser_default_hierarchy_changed()
5835  */
5836 static void
5837 toplevel_set_focus_cb (GtkWindow             *window,
5838                        GtkWidget             *focus,
5839                        GtkFileChooserDefault *impl)
5840 {
5841   impl->toplevel_last_focus_widget = gtk_window_get_focus (window);
5842 }
5843
5844 /* We monitor the focus widget on our toplevel to be able to know which widget
5845  * was last focused at the time our "should_respond" method gets called.
5846  */
5847 static void
5848 gtk_file_chooser_default_hierarchy_changed (GtkWidget *widget,
5849                                             GtkWidget *previous_toplevel)
5850 {
5851   GtkFileChooserDefault *impl;
5852   GtkWidget *toplevel;
5853
5854   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5855   toplevel = gtk_widget_get_toplevel (widget);
5856
5857   if (previous_toplevel && 
5858       impl->toplevel_set_focus_id != 0)
5859     {
5860       g_signal_handler_disconnect (previous_toplevel,
5861                                    impl->toplevel_set_focus_id);
5862       impl->toplevel_set_focus_id = 0;
5863       impl->toplevel_last_focus_widget = NULL;
5864     }
5865
5866   if (gtk_widget_is_toplevel (toplevel))
5867     {
5868       g_assert (impl->toplevel_set_focus_id == 0);
5869       impl->toplevel_set_focus_id = g_signal_connect (toplevel, "set-focus",
5870                                                       G_CALLBACK (toplevel_set_focus_cb), impl);
5871       impl->toplevel_last_focus_widget = gtk_window_get_focus (GTK_WINDOW (toplevel));
5872     }
5873 }
5874
5875 /* Changes the icons wherever it is needed */
5876 static void
5877 change_icon_theme (GtkFileChooserDefault *impl)
5878 {
5879   GtkSettings *settings;
5880   gint width, height;
5881   GtkCellRenderer *renderer;
5882   GList *cells;
5883
5884   profile_start ("start", NULL);
5885
5886   settings = gtk_settings_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
5887
5888   if (gtk_icon_size_lookup_for_settings (settings, GTK_ICON_SIZE_MENU, &width, &height))
5889     impl->icon_size = MAX (width, height);
5890   else
5891     impl->icon_size = FALLBACK_ICON_SIZE;
5892
5893   shortcuts_reload_icons (impl);
5894   /* the first cell in the first column is the icon column, and we have a fixed size there */
5895   cells = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (
5896         gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_files_tree_view), 0)));
5897   renderer = GTK_CELL_RENDERER (cells->data);
5898   set_icon_cell_renderer_fixed_size (impl, renderer);
5899   g_list_free (cells);
5900   if (impl->browse_files_model)
5901     _gtk_file_system_model_clear_cache (impl->browse_files_model, MODEL_COL_PIXBUF);
5902   gtk_widget_queue_resize (impl->browse_files_tree_view);
5903
5904   profile_end ("end", NULL);
5905 }
5906
5907 /* Callback used when a GtkSettings value changes */
5908 static void
5909 settings_notify_cb (GObject               *object,
5910                     GParamSpec            *pspec,
5911                     GtkFileChooserDefault *impl)
5912 {
5913   const char *name;
5914
5915   profile_start ("start", NULL);
5916
5917   name = g_param_spec_get_name (pspec);
5918
5919   if (strcmp (name, "gtk-icon-theme-name") == 0 ||
5920       strcmp (name, "gtk-icon-sizes") == 0)
5921     change_icon_theme (impl);
5922
5923   profile_end ("end", NULL);
5924 }
5925
5926 /* Installs a signal handler for GtkSettings so that we can monitor changes in
5927  * the icon theme.
5928  */
5929 static void
5930 check_icon_theme (GtkFileChooserDefault *impl)
5931 {
5932   GtkSettings *settings;
5933
5934   profile_start ("start", NULL);
5935
5936   if (impl->settings_signal_id)
5937     {
5938       profile_end ("end", NULL);
5939       return;
5940     }
5941
5942   if (gtk_widget_has_screen (GTK_WIDGET (impl)))
5943     {
5944       settings = gtk_settings_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
5945       impl->settings_signal_id = g_signal_connect (settings, "notify",
5946                                                    G_CALLBACK (settings_notify_cb), impl);
5947
5948       change_icon_theme (impl);
5949     }
5950
5951   profile_end ("end", NULL);
5952 }
5953
5954 static void
5955 gtk_file_chooser_default_style_updated (GtkWidget *widget)
5956 {
5957   GtkFileChooserDefault *impl;
5958
5959   profile_start ("start", NULL);
5960
5961   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5962
5963   profile_msg ("    parent class style_udpated start", NULL);
5964   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->style_updated (widget);
5965   profile_msg ("    parent class style_updated end", NULL);
5966
5967   if (gtk_widget_has_screen (GTK_WIDGET (impl)))
5968     change_icon_theme (impl);
5969
5970   emit_default_size_changed (impl);
5971
5972   profile_end ("end", NULL);
5973 }
5974
5975 static void
5976 gtk_file_chooser_default_screen_changed (GtkWidget *widget,
5977                                          GdkScreen *previous_screen)
5978 {
5979   GtkFileChooserDefault *impl;
5980
5981   profile_start ("start", NULL);
5982
5983   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5984
5985   if (GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->screen_changed)
5986     GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->screen_changed (widget, previous_screen);
5987
5988   remove_settings_signal (impl, previous_screen);
5989   check_icon_theme (impl);
5990
5991   emit_default_size_changed (impl);
5992
5993   profile_end ("end", NULL);
5994 }
5995
5996 static void
5997 gtk_file_chooser_default_size_allocate (GtkWidget     *widget,
5998                                         GtkAllocation *allocation)
5999 {
6000   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->size_allocate (widget, allocation);
6001 }
6002
6003 static void
6004 set_sort_column (GtkFileChooserDefault *impl)
6005 {
6006   GtkTreeSortable *sortable;
6007
6008   sortable = GTK_TREE_SORTABLE (gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view)));
6009
6010   /* can happen when we're still populating the model */
6011   if (sortable == NULL)
6012     return;
6013
6014   gtk_tree_sortable_set_sort_column_id (sortable,
6015                                         impl->sort_column,
6016                                         impl->sort_order);
6017 }
6018
6019 static void
6020 settings_ensure (GtkFileChooserDefault *impl)
6021 {
6022   if (impl->settings != NULL)
6023     return;
6024
6025   impl->settings = g_settings_new_with_path ("org.gtk.Settings.FileChooser",
6026                                              "/org/gtk/settings/file-chooser/");
6027   g_settings_delay (impl->settings);
6028 }
6029
6030 static void
6031 settings_load (GtkFileChooserDefault *impl)
6032 {
6033   LocationMode location_mode;
6034   gboolean show_hidden;
6035   gboolean show_size_column;
6036   gint sort_column;
6037   GtkSortType sort_order;
6038
6039   settings_ensure (impl);
6040
6041   location_mode = g_settings_get_enum (impl->settings, SETTINGS_KEY_LOCATION_MODE);
6042   show_hidden = g_settings_get_boolean (impl->settings, SETTINGS_KEY_SHOW_HIDDEN);
6043   show_size_column = g_settings_get_boolean (impl->settings, SETTINGS_KEY_SHOW_SIZE_COLUMN);
6044   sort_column = g_settings_get_enum (impl->settings, SETTINGS_KEY_SORT_COLUMN);
6045   sort_order = g_settings_get_enum (impl->settings, SETTINGS_KEY_SORT_ORDER);
6046
6047   location_mode_set (impl, location_mode, TRUE);
6048
6049   gtk_file_chooser_set_show_hidden (GTK_FILE_CHOOSER (impl), show_hidden);
6050
6051   impl->show_size_column = show_size_column;
6052   gtk_tree_view_column_set_visible (impl->list_size_column, show_size_column);
6053
6054   impl->sort_column = sort_column;
6055   impl->sort_order = sort_order;
6056   /* We don't call set_sort_column() here as the models may not have been
6057    * created yet.  The individual functions that create and set the models will
6058    * call set_sort_column() themselves.
6059    */
6060 }
6061
6062 static void
6063 save_dialog_geometry (GtkFileChooserDefault *impl)
6064 {
6065   GtkWindow *toplevel;
6066   int x, y, width, height;
6067
6068   toplevel = get_toplevel (GTK_WIDGET (impl));
6069
6070   if (!(toplevel && GTK_IS_FILE_CHOOSER_DIALOG (toplevel)))
6071     return;
6072
6073   gtk_window_get_position (toplevel, &x, &y);
6074   gtk_window_get_size (toplevel, &width, &height);
6075
6076   g_settings_set (impl->settings, "window-position", "(ii)", x, y);
6077   g_settings_set (impl->settings, "window-size", "(ii)", width, height);
6078 }
6079
6080 static void
6081 settings_save (GtkFileChooserDefault *impl)
6082 {
6083   char *current_folder_uri;
6084
6085   settings_ensure (impl);
6086
6087   /* Current folder */
6088
6089   if (impl->current_folder)
6090     current_folder_uri = g_file_get_uri (impl->current_folder);
6091   else
6092     current_folder_uri = "";
6093
6094   g_settings_set_string (impl->settings, SETTINGS_KEY_LAST_FOLDER_URI, current_folder_uri);
6095
6096   if (impl->current_folder)
6097     g_free (current_folder_uri);
6098
6099   /* All the other state */
6100
6101   g_settings_set_enum (impl->settings, SETTINGS_KEY_LOCATION_MODE, impl->location_mode);
6102   g_settings_set_boolean (impl->settings, SETTINGS_KEY_SHOW_HIDDEN,
6103                           gtk_file_chooser_get_show_hidden (GTK_FILE_CHOOSER (impl)));
6104   g_settings_set_boolean (impl->settings, SETTINGS_KEY_SHOW_SIZE_COLUMN, impl->show_size_column);
6105   g_settings_set_enum (impl->settings, SETTINGS_KEY_SORT_COLUMN, impl->sort_column);
6106   g_settings_set_enum (impl->settings, SETTINGS_KEY_SORT_ORDER, impl->sort_order);
6107
6108   save_dialog_geometry (impl);
6109
6110   /* Now apply the settings */
6111   g_settings_apply (impl->settings);
6112
6113   g_object_unref (impl->settings);
6114   impl->settings = NULL;
6115 }
6116
6117 /* GtkWidget::realize method */
6118 static void
6119 gtk_file_chooser_default_realize (GtkWidget *widget)
6120 {
6121   GtkFileChooserDefault *impl;
6122
6123   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
6124
6125   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->realize (widget);
6126
6127   emit_default_size_changed (impl);
6128 }
6129
6130 static GFile *
6131 get_file_for_last_folder_opened (GtkFileChooserDefault *impl)
6132 {
6133   char *last_folder_uri;
6134   GFile *file;
6135
6136   settings_ensure (impl);
6137
6138   last_folder_uri = g_settings_get_string (impl->settings, SETTINGS_KEY_LAST_FOLDER_URI);
6139
6140   /* If no last folder is set, we use the user's home directory, since
6141    * this is the starting point for most documents.
6142    */
6143   if (last_folder_uri[0] == '\0')
6144     file = g_file_new_for_path (g_get_home_dir ());
6145   else
6146     file = g_file_new_for_uri (last_folder_uri);
6147
6148   g_free (last_folder_uri);
6149
6150   return file;
6151 }
6152
6153 /* GtkWidget::map method */
6154 static void
6155 gtk_file_chooser_default_map (GtkWidget *widget)
6156 {
6157   GtkFileChooserDefault *impl;
6158
6159   profile_start ("start", NULL);
6160
6161   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
6162
6163   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->map (widget);
6164
6165   if (impl->operation_mode == OPERATION_MODE_BROWSE)
6166     {
6167       switch (impl->reload_state)
6168         {
6169         case RELOAD_EMPTY:
6170           recent_shortcut_handler (impl);
6171           break;
6172         
6173         case RELOAD_HAS_FOLDER:
6174           /* Nothing; we are already loading or loaded, so we
6175            * don't need to reload
6176            */
6177           break;
6178
6179         default:
6180           g_assert_not_reached ();
6181       }
6182     }
6183
6184   volumes_bookmarks_changed_cb (impl->file_system, impl);
6185
6186   settings_load (impl);
6187
6188   profile_end ("end", NULL);
6189 }
6190
6191 /* GtkWidget::unmap method */
6192 static void
6193 gtk_file_chooser_default_unmap (GtkWidget *widget)
6194 {
6195   GtkFileChooserDefault *impl;
6196
6197   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
6198
6199   settings_save (impl);
6200
6201   cancel_all_operations (impl);
6202   impl->reload_state = RELOAD_EMPTY;
6203
6204   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->unmap (widget);
6205 }
6206
6207 #define COMPARE_DIRECTORIES                                                                                    \
6208   GtkFileChooserDefault *impl = user_data;                                                                     \
6209   GtkFileSystemModel *fs_model = GTK_FILE_SYSTEM_MODEL (model);                                                \
6210   gboolean dir_a, dir_b;                                                                                       \
6211                                                                                                                \
6212   dir_a = g_value_get_boolean (_gtk_file_system_model_get_value (fs_model, a, MODEL_COL_IS_FOLDER));           \
6213   dir_b = g_value_get_boolean (_gtk_file_system_model_get_value (fs_model, b, MODEL_COL_IS_FOLDER));           \
6214                                                                                                                \
6215   if (dir_a != dir_b)                                                                                          \
6216     return impl->list_sort_ascending ? (dir_a ? -1 : 1) : (dir_a ? 1 : -1) /* Directories *always* go first */
6217
6218 /* Sort callback for the filename column */
6219 static gint
6220 name_sort_func (GtkTreeModel *model,
6221                 GtkTreeIter  *a,
6222                 GtkTreeIter  *b,
6223                 gpointer      user_data)
6224 {
6225   COMPARE_DIRECTORIES;
6226   else
6227     {
6228       const char *key_a, *key_b;
6229       gint result;
6230
6231       key_a = g_value_get_string (_gtk_file_system_model_get_value (fs_model, a, MODEL_COL_NAME_COLLATED));
6232       key_b = g_value_get_string (_gtk_file_system_model_get_value (fs_model, b, MODEL_COL_NAME_COLLATED));
6233
6234       if (key_a && key_b)
6235         result = strcmp (key_a, key_b);
6236       else if (key_a)
6237         result = 1;
6238       else if (key_b)
6239         result = -1;
6240       else
6241         result = 0;
6242
6243       return result;
6244     }
6245 }
6246
6247 /* Sort callback for the size column */
6248 static gint
6249 size_sort_func (GtkTreeModel *model,
6250                 GtkTreeIter  *a,
6251                 GtkTreeIter  *b,
6252                 gpointer      user_data)
6253 {
6254   COMPARE_DIRECTORIES;
6255   else
6256     {
6257       gint64 size_a, size_b;
6258
6259       size_a = g_value_get_int64 (_gtk_file_system_model_get_value (fs_model, a, MODEL_COL_SIZE));
6260       size_b = g_value_get_int64 (_gtk_file_system_model_get_value (fs_model, b, MODEL_COL_SIZE));
6261
6262       return size_a < size_b ? -1 : (size_a == size_b ? 0 : 1);
6263     }
6264 }
6265
6266 /* Sort callback for the mtime column */
6267 static gint
6268 mtime_sort_func (GtkTreeModel *model,
6269                  GtkTreeIter  *a,
6270                  GtkTreeIter  *b,
6271                  gpointer      user_data)
6272 {
6273   COMPARE_DIRECTORIES;
6274   else
6275     {
6276       glong ta, tb;
6277
6278       ta = g_value_get_long (_gtk_file_system_model_get_value (fs_model, a, MODEL_COL_MTIME));
6279       tb = g_value_get_long (_gtk_file_system_model_get_value (fs_model, b, MODEL_COL_MTIME));
6280
6281       return ta < tb ? -1 : (ta == tb ? 0 : 1);
6282     }
6283 }
6284
6285 /* Callback used when the sort column changes.  We cache the sort order for use
6286  * in name_sort_func().
6287  */
6288 static void
6289 list_sort_column_changed_cb (GtkTreeSortable       *sortable,
6290                              GtkFileChooserDefault *impl)
6291 {
6292   gint sort_column_id;
6293   GtkSortType sort_type;
6294
6295   if (gtk_tree_sortable_get_sort_column_id (sortable, &sort_column_id, &sort_type))
6296     {
6297       impl->list_sort_ascending = (sort_type == GTK_SORT_ASCENDING);
6298       impl->sort_column = sort_column_id;
6299       impl->sort_order = sort_type;
6300     }
6301 }
6302
6303 static void
6304 set_busy_cursor (GtkFileChooserDefault *impl,
6305                  gboolean               busy)
6306 {
6307   GtkWidget *widget;
6308   GtkWindow *toplevel;
6309   GdkDisplay *display;
6310   GdkCursor *cursor;
6311
6312   toplevel = get_toplevel (GTK_WIDGET (impl));
6313   widget = GTK_WIDGET (toplevel);
6314   if (!toplevel || !gtk_widget_get_realized (widget))
6315     return;
6316
6317   display = gtk_widget_get_display (widget);
6318
6319   if (busy)
6320     cursor = gdk_cursor_new_for_display (display, GDK_WATCH);
6321   else
6322     cursor = NULL;
6323
6324   gdk_window_set_cursor (gtk_widget_get_window (widget), cursor);
6325   gdk_display_flush (display);
6326
6327   if (cursor)
6328     g_object_unref (cursor);
6329 }
6330
6331 /* Creates a sort model to wrap the file system model and sets it on the tree view */
6332 static void
6333 load_set_model (GtkFileChooserDefault *impl)
6334 {
6335   profile_start ("start", NULL);
6336
6337   g_assert (impl->browse_files_model != NULL);
6338
6339   profile_msg ("    gtk_tree_view_set_model start", NULL);
6340   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
6341                            GTK_TREE_MODEL (impl->browse_files_model));
6342   gtk_tree_view_columns_autosize (GTK_TREE_VIEW (impl->browse_files_tree_view));
6343   gtk_tree_view_set_search_column (GTK_TREE_VIEW (impl->browse_files_tree_view),
6344                                    MODEL_COL_NAME);
6345   file_list_set_sort_column_ids (impl);
6346   set_sort_column (impl);
6347   profile_msg ("    gtk_tree_view_set_model end", NULL);
6348   impl->list_sort_ascending = TRUE;
6349
6350   profile_end ("end", NULL);
6351 }
6352
6353 /* Timeout callback used when the loading timer expires */
6354 static gboolean
6355 load_timeout_cb (gpointer data)
6356 {
6357   GtkFileChooserDefault *impl;
6358
6359   profile_start ("start", NULL);
6360
6361   impl = GTK_FILE_CHOOSER_DEFAULT (data);
6362   g_assert (impl->load_state == LOAD_PRELOAD);
6363   g_assert (impl->load_timeout_id != 0);
6364   g_assert (impl->browse_files_model != NULL);
6365
6366   impl->load_timeout_id = 0;
6367   impl->load_state = LOAD_LOADING;
6368
6369   load_set_model (impl);
6370
6371   profile_end ("end", NULL);
6372
6373   return FALSE;
6374 }
6375
6376 /* Sets up a new load timer for the model and switches to the LOAD_PRELOAD state */
6377 static void
6378 load_setup_timer (GtkFileChooserDefault *impl)
6379 {
6380   g_assert (impl->load_timeout_id == 0);
6381   g_assert (impl->load_state != LOAD_PRELOAD);
6382
6383   impl->load_timeout_id = gdk_threads_add_timeout (MAX_LOADING_TIME, load_timeout_cb, impl);
6384   impl->load_state = LOAD_PRELOAD;
6385 }
6386
6387 /* Removes the load timeout and switches to the LOAD_FINISHED state */
6388 static void
6389 load_remove_timer (GtkFileChooserDefault *impl)
6390 {
6391   if (impl->load_timeout_id != 0)
6392     {
6393       g_assert (impl->load_state == LOAD_PRELOAD);
6394
6395       g_source_remove (impl->load_timeout_id);
6396       impl->load_timeout_id = 0;
6397       impl->load_state = LOAD_EMPTY;
6398     }
6399   else
6400     g_assert (impl->load_state == LOAD_EMPTY ||
6401               impl->load_state == LOAD_LOADING ||
6402               impl->load_state == LOAD_FINISHED);
6403 }
6404
6405 /* Selects the first row in the file list */
6406 static void
6407 browse_files_select_first_row (GtkFileChooserDefault *impl)
6408 {
6409   GtkTreePath *path;
6410   GtkTreeIter dummy_iter;
6411   GtkTreeModel *tree_model;
6412
6413   tree_model = gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view));
6414
6415   if (!tree_model)
6416     return;
6417
6418   path = gtk_tree_path_new_from_indices (0, -1);
6419
6420   /* If the list is empty, do nothing. */
6421   if (gtk_tree_model_get_iter (tree_model, &dummy_iter, path))
6422       gtk_tree_view_set_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view), path, NULL, FALSE);
6423
6424   gtk_tree_path_free (path);
6425 }
6426
6427 struct center_selected_row_closure {
6428   GtkFileChooserDefault *impl;
6429   gboolean already_centered;
6430 };
6431
6432 /* Callback used from gtk_tree_selection_selected_foreach(); centers the
6433  * selected row in the tree view.
6434  */
6435 static void
6436 center_selected_row_foreach_cb (GtkTreeModel      *model,
6437                                 GtkTreePath       *path,
6438                                 GtkTreeIter       *iter,
6439                                 gpointer           data)
6440 {
6441   struct center_selected_row_closure *closure;
6442
6443   closure = data;
6444   if (closure->already_centered)
6445     return;
6446
6447   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (closure->impl->browse_files_tree_view), path, NULL, TRUE, 0.5, 0.0);
6448   closure->already_centered = TRUE;
6449 }
6450
6451 /* Centers the selected row in the tree view */
6452 static void
6453 browse_files_center_selected_row (GtkFileChooserDefault *impl)
6454 {
6455   struct center_selected_row_closure closure;
6456   GtkTreeSelection *selection;
6457
6458   closure.impl = impl;
6459   closure.already_centered = FALSE;
6460
6461   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6462   gtk_tree_selection_selected_foreach (selection, center_selected_row_foreach_cb, &closure);
6463 }
6464
6465 static gboolean
6466 show_and_select_files (GtkFileChooserDefault *impl,
6467                        GSList                *files)
6468 {
6469   GtkTreeSelection *selection;
6470   GtkFileSystemModel *fsmodel;
6471   gboolean enabled_hidden, removed_filters;
6472   gboolean selected_a_file;
6473   GSList *walk;
6474
6475   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6476   fsmodel = GTK_FILE_SYSTEM_MODEL (gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view)));
6477
6478   enabled_hidden = impl->show_hidden;
6479   removed_filters = (impl->current_filter == NULL);
6480
6481   selected_a_file = FALSE;
6482
6483   for (walk = files; walk; walk = walk->next)
6484     {
6485       GFile *file = walk->data;
6486       GtkTreeIter iter;
6487
6488       /* Is it a hidden file? */
6489
6490       if (!_gtk_file_system_model_get_iter_for_file (fsmodel, &iter, file))
6491         continue;
6492
6493       if (!_gtk_file_system_model_iter_is_visible (fsmodel, &iter))
6494         {
6495           GFileInfo *info = _gtk_file_system_model_get_info (fsmodel, &iter);
6496
6497           if (!enabled_hidden &&
6498               (g_file_info_get_is_hidden (info) ||
6499                g_file_info_get_is_backup (info)))
6500             {
6501               g_object_set (impl, "show-hidden", TRUE, NULL);
6502               enabled_hidden = TRUE;
6503             }
6504         }
6505
6506       /* Is it a filtered file? */
6507
6508       if (!_gtk_file_system_model_get_iter_for_file (fsmodel, &iter, file))
6509         continue; /* re-get the iter as it may change when the model refilters */
6510
6511       if (!_gtk_file_system_model_iter_is_visible (fsmodel, &iter))
6512         {
6513           /* Maybe we should have a way to ask the fsmodel if it had filtered a file */
6514           if (!removed_filters)
6515             {
6516               set_current_filter (impl, NULL);
6517               removed_filters = TRUE;
6518             }
6519         }
6520
6521       /* Okay, can we select the file now? */
6522           
6523       if (!_gtk_file_system_model_get_iter_for_file (fsmodel, &iter, file))
6524         continue;
6525
6526       if (_gtk_file_system_model_iter_is_visible (fsmodel, &iter))
6527         {
6528           GtkTreePath *path;
6529
6530           gtk_tree_selection_select_iter (selection, &iter);
6531
6532           path = gtk_tree_model_get_path (GTK_TREE_MODEL (fsmodel), &iter);
6533           gtk_tree_view_set_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view),
6534                                     path, NULL, FALSE);
6535           gtk_tree_path_free (path);
6536
6537           selected_a_file = TRUE;
6538         }
6539     }
6540
6541   browse_files_center_selected_row (impl);
6542
6543   return selected_a_file;
6544 }
6545
6546 /* Processes the pending operation when a folder is finished loading */
6547 static void
6548 pending_select_files_process (GtkFileChooserDefault *impl)
6549 {
6550   g_assert (impl->load_state == LOAD_FINISHED);
6551   g_assert (impl->browse_files_model != NULL);
6552
6553   if (impl->pending_select_files)
6554     {
6555       show_and_select_files (impl, impl->pending_select_files);
6556       pending_select_files_free (impl);
6557       browse_files_center_selected_row (impl);
6558     }
6559   else
6560     {
6561       /* We only select the first row if the chooser is actually mapped ---
6562        * selecting the first row is to help the user when he is interacting with
6563        * the chooser, but sometimes a chooser works not on behalf of the user,
6564        * but rather on behalf of something else like GtkFileChooserButton.  In
6565        * that case, the chooser's selection should be what the caller expects,
6566        * as the user can't see that something else got selected.  See bug #165264.
6567        */
6568       if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN &&
6569           gtk_widget_get_mapped (GTK_WIDGET (impl)))
6570         browse_files_select_first_row (impl);
6571     }
6572
6573   g_assert (impl->pending_select_files == NULL);
6574 }
6575
6576 static void
6577 show_error_on_reading_current_folder (GtkFileChooserDefault *impl, GError *error)
6578 {
6579   GFileInfo *info;
6580   char *msg;
6581
6582   info = g_file_query_info (impl->current_folder,
6583                             G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
6584                             G_FILE_QUERY_INFO_NONE,
6585                             NULL,
6586                             NULL);
6587   if (info)
6588     {
6589       msg = g_strdup_printf (_("Could not read the contents of %s"), g_file_info_get_display_name (info));
6590       g_object_unref (info);
6591     }
6592   else
6593     msg = g_strdup (_("Could not read the contents of the folder"));
6594
6595   error_message (impl, msg, error->message);
6596   g_free (msg);
6597 }
6598
6599 /* Callback used when the file system model finishes loading */
6600 static void
6601 browse_files_model_finished_loading_cb (GtkFileSystemModel    *model,
6602                                         GError                *error,
6603                                         GtkFileChooserDefault *impl)
6604 {
6605   profile_start ("start", NULL);
6606
6607   if (error)
6608     show_error_on_reading_current_folder (impl, error);
6609
6610   if (impl->load_state == LOAD_PRELOAD)
6611     {
6612       load_remove_timer (impl);
6613       load_set_model (impl);
6614     }
6615   else if (impl->load_state == LOAD_LOADING)
6616     {
6617       /* Nothing */
6618     }
6619   else
6620     {
6621       /* We can't g_assert_not_reached(), as something other than us may have
6622        *  initiated a folder reload.  See #165556.
6623        */
6624       profile_end ("end", NULL);
6625       return;
6626     }
6627
6628   g_assert (impl->load_timeout_id == 0);
6629
6630   impl->load_state = LOAD_FINISHED;
6631
6632   pending_select_files_process (impl);
6633   set_busy_cursor (impl, FALSE);
6634 #ifdef PROFILE_FILE_CHOOSER
6635   access ("MARK: *** FINISHED LOADING", F_OK);
6636 #endif
6637
6638   profile_end ("end", NULL);
6639 }
6640
6641 static void
6642 stop_loading_and_clear_list_model (GtkFileChooserDefault *impl,
6643                                    gboolean remove_from_treeview)
6644 {
6645   load_remove_timer (impl); /* This changes the state to LOAD_EMPTY */
6646   
6647   if (impl->browse_files_model)
6648     {
6649       g_object_unref (impl->browse_files_model);
6650       impl->browse_files_model = NULL;
6651     }
6652
6653   if (remove_from_treeview)
6654     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
6655 }
6656
6657 static char *
6658 my_g_format_time_for_display (glong secs)
6659 {
6660   GDate mtime, now;
6661   gint days_diff;
6662   struct tm tm_mtime;
6663   time_t time_mtime, time_now;
6664   const gchar *format;
6665   gchar *locale_format = NULL;
6666   gchar buf[256];
6667   char *date_str = NULL;
6668 #ifdef G_OS_WIN32
6669   const char *locale, *dot = NULL;
6670   gint64 codepage = -1;
6671   char charset[20];
6672 #endif
6673
6674   time_mtime = secs;
6675
6676 #ifdef HAVE_LOCALTIME_R
6677   localtime_r ((time_t *) &time_mtime, &tm_mtime);
6678 #else
6679   {
6680     struct tm *ptm = localtime ((time_t *) &time_mtime);
6681
6682     if (!ptm)
6683       {
6684         g_warning ("ptm != NULL failed");
6685         
6686         return g_strdup (_("Unknown"));
6687       }
6688     else
6689       memcpy ((void *) &tm_mtime, (void *) ptm, sizeof (struct tm));
6690   }
6691 #endif /* HAVE_LOCALTIME_R */
6692
6693   g_date_set_time_t (&mtime, time_mtime);
6694   time_now = time (NULL);
6695   g_date_set_time_t (&now, time_now);
6696
6697   days_diff = g_date_get_julian (&now) - g_date_get_julian (&mtime);
6698
6699   /* Translators: %H means "hours" and %M means "minutes" */
6700   if (days_diff == 0)
6701     format = _("%H:%M");
6702   else if (days_diff == 1)
6703     format = _("Yesterday at %H:%M");
6704   else
6705     {
6706       if (days_diff > 1 && days_diff < 7)
6707         format = "%A"; /* Days from last week */
6708       else
6709         format = "%x"; /* Any other date */
6710     }
6711
6712 #ifdef G_OS_WIN32
6713   /* g_locale_from_utf8() returns a string in the system
6714    * code-page, which is not always the same as that used by the C
6715    * library. For instance when running a GTK+ program with
6716    * LANG=ko on an English version of Windows, the system
6717    * code-page is 1252, but the code-page used by the C library is
6718    * 949. (It's GTK+ itself that sets the C library locale when it
6719    * notices the LANG environment variable. See gtkmain.c The
6720    * Microsoft C library doesn't look at any locale environment
6721    * variables.) We need to pass strftime() a string in the C
6722    * library's code-page. See bug #509885.
6723    */
6724   locale = setlocale (LC_ALL, NULL);
6725   if (locale != NULL)
6726     dot = strchr (locale, '.');
6727   if (dot != NULL)
6728     {
6729       codepage = g_ascii_strtoll (dot+1, NULL, 10);
6730       
6731       /* All codepages should fit in 16 bits AFAIK */
6732       if (codepage > 0 && codepage < 65536)
6733         {
6734           sprintf (charset, "CP%u", (guint) codepage);
6735           locale_format = g_convert (format, -1, charset, "UTF-8", NULL, NULL, NULL);
6736         }
6737     }
6738 #else
6739   locale_format = g_locale_from_utf8 (format, -1, NULL, NULL, NULL);
6740 #endif
6741   if (locale_format != NULL &&
6742       strftime (buf, sizeof (buf), locale_format, &tm_mtime) != 0)
6743     {
6744 #ifdef G_OS_WIN32
6745       /* As above but in opposite direction... */
6746       if (codepage > 0 && codepage < 65536)
6747         date_str = g_convert (buf, -1, "UTF-8", charset, NULL, NULL, NULL);
6748 #else
6749       date_str = g_locale_to_utf8 (buf, -1, NULL, NULL, NULL);
6750 #endif
6751     }
6752
6753   if (date_str == NULL)
6754     date_str = g_strdup (_("Unknown"));
6755
6756   g_free (locale_format);
6757   return date_str;
6758 }
6759
6760 static void
6761 copy_attribute (GFileInfo *to, GFileInfo *from, const char *attribute)
6762 {
6763   GFileAttributeType type;
6764   gpointer value;
6765
6766   if (g_file_info_get_attribute_data (from, attribute, &type, &value, NULL))
6767     g_file_info_set_attribute (to, attribute, type, value);
6768 }
6769
6770 static void
6771 file_system_model_got_thumbnail (GObject *object, GAsyncResult *res, gpointer data)
6772 {
6773   GtkFileSystemModel *model = data; /* might be unreffed if operation was cancelled */
6774   GFile *file = G_FILE (object);
6775   GFileInfo *queried, *info;
6776   GtkTreeIter iter;
6777
6778   queried = g_file_query_info_finish (file, res, NULL);
6779   if (queried == NULL)
6780     return;
6781
6782   GDK_THREADS_ENTER ();
6783
6784   /* now we know model is valid */
6785
6786   /* file was deleted */
6787   if (!_gtk_file_system_model_get_iter_for_file (model, &iter, file))
6788     {
6789       GDK_THREADS_LEAVE ();
6790       return;
6791     }
6792
6793   info = g_file_info_dup (_gtk_file_system_model_get_info (model, &iter));
6794
6795   copy_attribute (info, queried, G_FILE_ATTRIBUTE_THUMBNAIL_PATH);
6796   copy_attribute (info, queried, G_FILE_ATTRIBUTE_THUMBNAILING_FAILED);
6797   copy_attribute (info, queried, G_FILE_ATTRIBUTE_STANDARD_ICON);
6798
6799   _gtk_file_system_model_update_file (model, file, info, FALSE);
6800
6801   g_object_unref (info);
6802
6803   GDK_THREADS_LEAVE ();
6804 }
6805
6806 static gboolean
6807 file_system_model_set (GtkFileSystemModel *model,
6808                        GFile              *file,
6809                        GFileInfo          *info,
6810                        int                 column,
6811                        GValue             *value,
6812                        gpointer            data)
6813 {
6814   GtkFileChooserDefault *impl = data;
6815  
6816   switch (column)
6817     {
6818     case MODEL_COL_FILE:
6819       g_value_set_object (value, file);
6820       break;
6821     case MODEL_COL_NAME:
6822       if (info == NULL)
6823         g_value_set_string (value, DEFAULT_NEW_FOLDER_NAME);
6824       else 
6825         g_value_set_string (value, g_file_info_get_display_name (info));
6826       break;
6827     case MODEL_COL_NAME_COLLATED:
6828       if (info == NULL)
6829         g_value_take_string (value, g_utf8_collate_key_for_filename (DEFAULT_NEW_FOLDER_NAME, -1));
6830       else 
6831         g_value_take_string (value, g_utf8_collate_key_for_filename (g_file_info_get_display_name (info), -1));
6832       break;
6833     case MODEL_COL_IS_FOLDER:
6834       g_value_set_boolean (value, info == NULL || _gtk_file_info_consider_as_directory (info));
6835       break;
6836     case MODEL_COL_IS_SENSITIVE:
6837       if (info)
6838         {
6839           gboolean sensitive = TRUE;
6840
6841           if (!(impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER
6842                 || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
6843             {
6844               sensitive = TRUE; /* for file modes... */
6845             }
6846           else if (!_gtk_file_info_consider_as_directory (info))
6847             {
6848               sensitive = FALSE; /* for folder modes, files are not sensitive... */
6849             }
6850           else
6851             {
6852               /* ... and for folder modes, folders are sensitive only if the filter says so */
6853               GtkTreeIter iter;
6854               if (!_gtk_file_system_model_get_iter_for_file (model, &iter, file))
6855                 g_assert_not_reached ();
6856               sensitive = !_gtk_file_system_model_iter_is_filtered_out (model, &iter);
6857             }
6858
6859           g_value_set_boolean (value, sensitive);
6860         }
6861       else
6862         g_value_set_boolean (value, TRUE);
6863       break;
6864     case MODEL_COL_PIXBUF:
6865       if (info)
6866         {
6867           if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_ICON))
6868             {
6869               g_value_take_object (value, _gtk_file_info_render_icon (info, GTK_WIDGET (impl), impl->icon_size));
6870             }
6871           else
6872             {
6873               GtkTreeModel *tree_model;
6874               GtkTreePath *path, *start, *end;
6875               GtkTreeIter iter;
6876
6877               if (impl->browse_files_tree_view == NULL ||
6878                   g_file_info_has_attribute (info, "filechooser::queried"))
6879                 return FALSE;
6880
6881               tree_model = gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view));
6882               if (tree_model != GTK_TREE_MODEL (model))
6883                 return FALSE;
6884
6885               if (!_gtk_file_system_model_get_iter_for_file (model,
6886                                                              &iter,
6887                                                              file))
6888                 g_assert_not_reached ();
6889               if (!gtk_tree_view_get_visible_range (GTK_TREE_VIEW (impl->browse_files_tree_view), &start, &end))
6890                 return FALSE;
6891               path = gtk_tree_model_get_path (tree_model, &iter);
6892               if (gtk_tree_path_compare (start, path) != 1 &&
6893                   gtk_tree_path_compare (path, end) != 1)
6894                 {
6895                   g_file_info_set_attribute_boolean (info, "filechooser::queried", TRUE);
6896                   g_file_query_info_async (file,
6897                                            G_FILE_ATTRIBUTE_THUMBNAIL_PATH ","
6898                                            G_FILE_ATTRIBUTE_THUMBNAILING_FAILED ","
6899                                            G_FILE_ATTRIBUTE_STANDARD_ICON,
6900                                            G_FILE_QUERY_INFO_NONE,
6901                                            G_PRIORITY_DEFAULT,
6902                                            _gtk_file_system_model_get_cancellable (model),
6903                                            file_system_model_got_thumbnail,
6904                                            model);
6905                 }
6906               gtk_tree_path_free (path);
6907               gtk_tree_path_free (start);
6908               gtk_tree_path_free (end);
6909               return FALSE;
6910             }
6911         }
6912       else
6913         g_value_set_object (value, NULL);
6914       break;
6915     case MODEL_COL_SIZE:
6916       g_value_set_int64 (value, info ? g_file_info_get_size (info) : 0);
6917       break;
6918     case MODEL_COL_SIZE_TEXT:
6919       if (info == NULL || _gtk_file_info_consider_as_directory (info))
6920         g_value_set_string (value, NULL);
6921       else
6922         g_value_take_string (value, g_format_size (g_file_info_get_size (info)));
6923       break;
6924     case MODEL_COL_MTIME:
6925     case MODEL_COL_MTIME_TEXT:
6926       {
6927         GTimeVal tv;
6928         if (info == NULL)
6929           break;
6930         g_file_info_get_modification_time (info, &tv);
6931         if (column == MODEL_COL_MTIME)
6932           g_value_set_long (value, tv.tv_sec);
6933         else if (tv.tv_sec == 0)
6934           g_value_set_static_string (value, _("Unknown"));
6935         else
6936           g_value_take_string (value, my_g_format_time_for_display (tv.tv_sec));
6937         break;
6938       }
6939     case MODEL_COL_ELLIPSIZE:
6940       g_value_set_enum (value, info ? PANGO_ELLIPSIZE_END : PANGO_ELLIPSIZE_NONE);
6941       break;
6942     default:
6943       g_assert_not_reached ();
6944       break;
6945     }
6946
6947   return TRUE;
6948 }
6949
6950 /* Gets rid of the old list model and creates a new one for the current folder */
6951 static gboolean
6952 set_list_model (GtkFileChooserDefault *impl,
6953                 GError               **error)
6954 {
6955   g_assert (impl->current_folder != NULL);
6956
6957   profile_start ("start", NULL);
6958
6959   stop_loading_and_clear_list_model (impl, TRUE);
6960
6961   set_busy_cursor (impl, TRUE);
6962
6963   impl->browse_files_model = 
6964     _gtk_file_system_model_new_for_directory (impl->current_folder,
6965                                               MODEL_ATTRIBUTES,
6966                                               file_system_model_set,
6967                                               impl,
6968                                               MODEL_COLUMN_TYPES);
6969
6970   _gtk_file_system_model_set_show_hidden (impl->browse_files_model, impl->show_hidden);
6971
6972   profile_msg ("    set sort function", NULL);
6973   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_NAME, name_sort_func, impl, NULL);
6974   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_SIZE, size_sort_func, impl, NULL);
6975   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_MTIME, mtime_sort_func, impl, NULL);
6976   gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), NULL, NULL, NULL);
6977   set_sort_column (impl);
6978   impl->list_sort_ascending = TRUE;
6979   g_signal_connect (impl->browse_files_model, "sort-column-changed",
6980                     G_CALLBACK (list_sort_column_changed_cb), impl);
6981
6982   load_setup_timer (impl); /* This changes the state to LOAD_PRELOAD */
6983
6984   g_signal_connect (impl->browse_files_model, "finished-loading",
6985                     G_CALLBACK (browse_files_model_finished_loading_cb), impl);
6986
6987   _gtk_file_system_model_set_filter (impl->browse_files_model, impl->current_filter);
6988
6989   profile_end ("end", NULL);
6990
6991   return TRUE;
6992 }
6993
6994 struct update_chooser_entry_selected_foreach_closure {
6995   int num_selected;
6996   GtkTreeIter first_selected_iter;
6997 };
6998
6999 static gint
7000 compare_utf8_filenames (const gchar *a,
7001                         const gchar *b)
7002 {
7003   gchar *a_folded, *b_folded;
7004   gint retval;
7005
7006   a_folded = g_utf8_strdown (a, -1);
7007   b_folded = g_utf8_strdown (b, -1);
7008
7009   retval = strcmp (a_folded, b_folded);
7010
7011   g_free (a_folded);
7012   g_free (b_folded);
7013
7014   return retval;
7015 }
7016
7017 static void
7018 update_chooser_entry_selected_foreach (GtkTreeModel *model,
7019                                        GtkTreePath *path,
7020                                        GtkTreeIter *iter,
7021                                        gpointer data)
7022 {
7023   struct update_chooser_entry_selected_foreach_closure *closure;
7024
7025   closure = data;
7026   closure->num_selected++;
7027
7028   if (closure->num_selected == 1)
7029     closure->first_selected_iter = *iter;
7030 }
7031
7032 static void
7033 update_chooser_entry (GtkFileChooserDefault *impl)
7034 {
7035   GtkTreeSelection *selection;
7036   struct update_chooser_entry_selected_foreach_closure closure;
7037
7038   /* no need to update the file chooser's entry if there's no entry */
7039   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7040       !impl->location_entry)
7041     return;
7042
7043   if (!(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
7044         || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
7045         || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
7046              || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
7047             && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)))
7048     return;
7049
7050   g_assert (impl->location_entry != NULL);
7051
7052   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7053   closure.num_selected = 0;
7054   gtk_tree_selection_selected_foreach (selection, update_chooser_entry_selected_foreach, &closure);
7055
7056   if (closure.num_selected == 0)
7057     {
7058       if (impl->operation_mode == OPERATION_MODE_RECENT)
7059         _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), NULL);
7060       else
7061         goto maybe_clear_entry;
7062     }
7063   else if (closure.num_selected == 1)
7064     {
7065       if (impl->operation_mode == OPERATION_MODE_BROWSE)
7066         {
7067           GFileInfo *info;
7068           gboolean change_entry;
7069
7070           info = _gtk_file_system_model_get_info (impl->browse_files_model, &closure.first_selected_iter);
7071
7072           /* If the cursor moved to the row of the newly created folder,
7073            * retrieving info will return NULL.
7074            */
7075           if (!info)
7076             return;
7077
7078           g_free (impl->browse_files_last_selected_name);
7079           impl->browse_files_last_selected_name =
7080             g_strdup (g_file_info_get_display_name (info));
7081
7082           if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
7083               impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7084               impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
7085             {
7086               /* Don't change the name when clicking on a folder... */
7087               change_entry = (! _gtk_file_info_consider_as_directory (info));
7088             }
7089           else
7090             change_entry = TRUE; /* ... unless we are in SELECT_FOLDER mode */
7091
7092           if (change_entry)
7093             {
7094               gtk_entry_set_text (GTK_ENTRY (impl->location_entry), impl->browse_files_last_selected_name);
7095
7096               if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
7097                 _gtk_file_chooser_entry_select_filename (GTK_FILE_CHOOSER_ENTRY (impl->location_entry));
7098             }
7099
7100           return;
7101         }
7102       else if (impl->operation_mode == OPERATION_MODE_RECENT
7103                && impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
7104         {
7105           GFile *folder;
7106
7107           /* Set the base folder on the name entry, so it will do completion relative to the correct recent-folder */
7108
7109           gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &closure.first_selected_iter,
7110                               MODEL_COL_FILE, &folder,
7111                               -1);
7112           _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), folder);
7113           g_object_unref (folder);
7114           return;
7115         }
7116     }
7117   else
7118     {
7119       g_assert (!(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7120                   impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER));
7121
7122       /* Multiple selection, so just clear the entry. */
7123       g_free (impl->browse_files_last_selected_name);
7124       impl->browse_files_last_selected_name = NULL;
7125
7126       gtk_entry_set_text (GTK_ENTRY (impl->location_entry), "");
7127       return;
7128     }
7129
7130  maybe_clear_entry:
7131
7132   if ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
7133       && impl->browse_files_last_selected_name)
7134     {
7135       const char *entry_text;
7136       int len;
7137       gboolean clear_entry;
7138
7139       entry_text = gtk_entry_get_text (GTK_ENTRY (impl->location_entry));
7140       len = strlen (entry_text);
7141       if (len != 0)
7142         {
7143           /* The file chooser entry may have appended a "/" to its text.
7144            * So take it out, and compare the result to the old selection.
7145            */
7146           if (entry_text[len - 1] == G_DIR_SEPARATOR)
7147             {
7148               gchar *tmp;
7149
7150               tmp = g_strndup (entry_text, len - 1);
7151               clear_entry = (compare_utf8_filenames (impl->browse_files_last_selected_name, tmp) == 0);
7152               g_free (tmp);
7153             }
7154           else
7155             clear_entry = (compare_utf8_filenames (impl->browse_files_last_selected_name, entry_text) == 0);
7156         }
7157       else
7158         clear_entry = FALSE;
7159
7160       if (clear_entry)
7161         gtk_entry_set_text (GTK_ENTRY (impl->location_entry), "");
7162     }
7163 }
7164
7165 static gboolean
7166 gtk_file_chooser_default_set_current_folder (GtkFileChooser  *chooser,
7167                                              GFile           *file,
7168                                              GError         **error)
7169 {
7170   return gtk_file_chooser_default_update_current_folder (chooser, file, FALSE, FALSE, error);
7171 }
7172
7173
7174 struct UpdateCurrentFolderData
7175 {
7176   GtkFileChooserDefault *impl;
7177   GFile *file;
7178   gboolean keep_trail;
7179   gboolean clear_entry;
7180   GFile *original_file;
7181   GError *original_error;
7182 };
7183
7184 static void
7185 update_current_folder_mount_enclosing_volume_cb (GCancellable        *cancellable,
7186                                                  GtkFileSystemVolume *volume,
7187                                                  const GError        *error,
7188                                                  gpointer             user_data)
7189 {
7190   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
7191   struct UpdateCurrentFolderData *data = user_data;
7192   GtkFileChooserDefault *impl = data->impl;
7193
7194   if (cancellable != impl->update_current_folder_cancellable)
7195     goto out;
7196
7197   impl->update_current_folder_cancellable = NULL;
7198   set_busy_cursor (impl, FALSE);
7199
7200   if (cancelled)
7201     goto out;
7202
7203   if (error)
7204     {
7205       error_changing_folder_dialog (data->impl, data->file, g_error_copy (error));
7206       impl->reload_state = RELOAD_EMPTY;
7207       goto out;
7208     }
7209
7210   change_folder_and_display_error (impl, data->file, data->clear_entry);
7211
7212 out:
7213   g_object_unref (data->file);
7214   g_free (data);
7215
7216   g_object_unref (cancellable);
7217 }
7218
7219 static void
7220 update_current_folder_get_info_cb (GCancellable *cancellable,
7221                                    GFileInfo    *info,
7222                                    const GError *error,
7223                                    gpointer      user_data)
7224 {
7225   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
7226   struct UpdateCurrentFolderData *data = user_data;
7227   GtkFileChooserDefault *impl = data->impl;
7228
7229   if (cancellable != impl->update_current_folder_cancellable)
7230     goto out;
7231
7232   impl->update_current_folder_cancellable = NULL;
7233   impl->reload_state = RELOAD_EMPTY;
7234
7235   set_busy_cursor (impl, FALSE);
7236
7237   if (cancelled)
7238     goto out;
7239
7240   if (error)
7241     {
7242       GFile *parent_file;
7243
7244       if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_MOUNTED))
7245         {
7246           GMountOperation *mount_operation;
7247           GtkWidget *toplevel;
7248
7249           g_object_unref (cancellable);
7250           toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
7251
7252           mount_operation = gtk_mount_operation_new (GTK_WINDOW (toplevel));
7253
7254           set_busy_cursor (impl, TRUE);
7255
7256           impl->update_current_folder_cancellable =
7257             _gtk_file_system_mount_enclosing_volume (impl->file_system, data->file,
7258                                                      mount_operation,
7259                                                      update_current_folder_mount_enclosing_volume_cb,
7260                                                      data);
7261
7262           return;
7263         }
7264
7265       if (!data->original_file)
7266         {
7267           data->original_file = g_object_ref (data->file);
7268           data->original_error = g_error_copy (error);
7269         }
7270
7271       parent_file = g_file_get_parent (data->file);
7272
7273       /* get parent path and try to change the folder to that */
7274       if (parent_file)
7275         {
7276           g_object_unref (data->file);
7277           data->file = parent_file;
7278
7279           g_object_unref (cancellable);
7280
7281           /* restart the update current folder operation */
7282           impl->reload_state = RELOAD_HAS_FOLDER;
7283
7284           impl->update_current_folder_cancellable =
7285             _gtk_file_system_get_info (impl->file_system, data->file,
7286                                        "standard::type",
7287                                        update_current_folder_get_info_cb,
7288                                        data);
7289
7290           set_busy_cursor (impl, TRUE);
7291
7292           return;
7293         }
7294       else
7295         {
7296           /* Error and bail out, ignoring "not found" errors since they're useless:
7297            * they only happen when a program defaults to a folder that has been (re)moved.
7298            */
7299           if (!g_error_matches (data->original_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
7300             error_changing_folder_dialog (impl, data->original_file, data->original_error);
7301           else
7302             g_error_free (data->original_error);
7303
7304           g_object_unref (data->original_file);
7305
7306           goto out;
7307         }
7308     }
7309
7310   if (data->original_file)
7311     {
7312       /* Error and bail out, ignoring "not found" errors since they're useless:
7313        * they only happen when a program defaults to a folder that has been (re)moved.
7314        */
7315       if (!g_error_matches (data->original_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
7316         error_changing_folder_dialog (impl, data->original_file, data->original_error);
7317       else
7318         g_error_free (data->original_error);
7319
7320       g_object_unref (data->original_file);
7321     }
7322
7323   if (! _gtk_file_info_consider_as_directory (info))
7324     goto out;
7325
7326   _gtk_path_bar_set_file (GTK_PATH_BAR (impl->browse_path_bar), data->file, data->keep_trail);
7327
7328   if (impl->current_folder != data->file)
7329     {
7330       if (impl->current_folder)
7331         g_object_unref (impl->current_folder);
7332
7333       impl->current_folder = g_object_ref (data->file);
7334     }
7335
7336   impl->reload_state = RELOAD_HAS_FOLDER;
7337
7338   /* Update the widgets that may trigger a folder change themselves.  */
7339
7340   if (!impl->changing_folder)
7341     {
7342       impl->changing_folder = TRUE;
7343
7344       shortcuts_update_current_folder (impl);
7345
7346       impl->changing_folder = FALSE;
7347     }
7348
7349   /* Set the folder on the save entry */
7350
7351   if (impl->location_entry)
7352     {
7353       _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry),
7354                                                impl->current_folder);
7355
7356       if (data->clear_entry)
7357         gtk_entry_set_text (GTK_ENTRY (impl->location_entry), "");
7358     }
7359
7360   /* Create a new list model.  This is slightly evil; we store the result value
7361    * but perform more actions rather than returning immediately even if it
7362    * generates an error.
7363    */
7364   set_list_model (impl, NULL);
7365
7366   /* Refresh controls */
7367
7368   shortcuts_find_current_folder (impl);
7369
7370   g_signal_emit_by_name (impl, "current-folder-changed", 0);
7371
7372   check_preview_change (impl);
7373   bookmarks_check_add_sensitivity (impl);
7374
7375   g_signal_emit_by_name (impl, "selection-changed", 0);
7376
7377 out:
7378   g_object_unref (data->file);
7379   g_free (data);
7380
7381   g_object_unref (cancellable);
7382 }
7383
7384 static gboolean
7385 gtk_file_chooser_default_update_current_folder (GtkFileChooser    *chooser,
7386                                                 GFile             *file,
7387                                                 gboolean           keep_trail,
7388                                                 gboolean           clear_entry,
7389                                                 GError           **error)
7390 {
7391   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7392   struct UpdateCurrentFolderData *data;
7393
7394   profile_start ("start", NULL);
7395
7396   g_object_ref (file);
7397
7398   operation_mode_set (impl, OPERATION_MODE_BROWSE);
7399
7400   if (impl->local_only && !g_file_is_native (file))
7401     {
7402       g_set_error_literal (error,
7403                            GTK_FILE_CHOOSER_ERROR,
7404                            GTK_FILE_CHOOSER_ERROR_BAD_FILENAME,
7405                            _("Cannot change to folder because it is not local"));
7406
7407       g_object_unref (file);
7408       profile_end ("end - not local", NULL);
7409       return FALSE;
7410     }
7411
7412   if (impl->update_current_folder_cancellable)
7413     g_cancellable_cancel (impl->update_current_folder_cancellable);
7414
7415   /* Test validity of path here.  */
7416   data = g_new0 (struct UpdateCurrentFolderData, 1);
7417   data->impl = impl;
7418   data->file = g_object_ref (file);
7419   data->keep_trail = keep_trail;
7420   data->clear_entry = clear_entry;
7421
7422   impl->reload_state = RELOAD_HAS_FOLDER;
7423
7424   impl->update_current_folder_cancellable =
7425     _gtk_file_system_get_info (impl->file_system, file,
7426                                "standard::type",
7427                                update_current_folder_get_info_cb,
7428                                data);
7429
7430   set_busy_cursor (impl, TRUE);
7431   g_object_unref (file);
7432
7433   profile_end ("end", NULL);
7434   return TRUE;
7435 }
7436
7437 static GFile *
7438 gtk_file_chooser_default_get_current_folder (GtkFileChooser *chooser)
7439 {
7440   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7441
7442   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7443       impl->operation_mode == OPERATION_MODE_RECENT)
7444     return NULL;
7445  
7446   if (impl->reload_state == RELOAD_EMPTY)
7447     {
7448       /* We are unmapped, or we had an error while loading the last folder.
7449        * We'll return the folder used by the last invocation of the file chooser
7450        * since once we get (re)mapped, we'll load *that* folder anyway unless
7451        * the caller explicitly calls set_current_folder() on us.
7452        */
7453       return get_file_for_last_folder_opened (impl);
7454     }
7455
7456   if (impl->current_folder)
7457     return g_object_ref (impl->current_folder);
7458
7459   return NULL;
7460 }
7461
7462 static void
7463 gtk_file_chooser_default_set_current_name (GtkFileChooser *chooser,
7464                                            const gchar    *name)
7465 {
7466   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7467
7468   g_return_if_fail (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7469                     impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
7470
7471   pending_select_files_free (impl);
7472   gtk_entry_set_text (GTK_ENTRY (impl->location_entry), name);
7473 }
7474
7475 static gboolean
7476 gtk_file_chooser_default_select_file (GtkFileChooser  *chooser,
7477                                       GFile           *file,
7478                                       GError         **error)
7479 {
7480   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7481   GFile *parent_file;
7482   gboolean same_path;
7483
7484   parent_file = g_file_get_parent (file);
7485
7486   if (!parent_file)
7487     return gtk_file_chooser_set_current_folder_file (chooser, file, error);
7488
7489   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7490       impl->operation_mode == OPERATION_MODE_RECENT ||
7491       impl->load_state == LOAD_EMPTY)
7492     {
7493       same_path = FALSE;
7494     }
7495   else
7496     {
7497       g_assert (impl->current_folder != NULL);
7498
7499       same_path = g_file_equal (parent_file, impl->current_folder);
7500     }
7501
7502   if (same_path && impl->load_state == LOAD_FINISHED)
7503     {
7504       gboolean result;
7505       GSList files;
7506
7507       files.data = (gpointer) file;
7508       files.next = NULL;
7509
7510       result = show_and_select_files (impl, &files);
7511       g_object_unref (parent_file);
7512       return result;
7513     }
7514
7515   pending_select_files_add (impl, file);
7516
7517   if (!same_path)
7518     {
7519       gboolean result;
7520
7521       result = gtk_file_chooser_set_current_folder_file (chooser, parent_file, error);
7522       g_object_unref (parent_file);
7523       return result;
7524     }
7525
7526   g_object_unref (parent_file);
7527   return TRUE;
7528 }
7529
7530 static void
7531 gtk_file_chooser_default_unselect_file (GtkFileChooser *chooser,
7532                                         GFile          *file)
7533 {
7534   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7535   GtkTreeView *tree_view = GTK_TREE_VIEW (impl->browse_files_tree_view);
7536   GtkTreeIter iter;
7537
7538   if (!impl->browse_files_model)
7539     return;
7540
7541   if (!_gtk_file_system_model_get_iter_for_file (impl->browse_files_model,
7542                                                  &iter,
7543                                                  file))
7544     return;
7545
7546   gtk_tree_selection_unselect_iter (gtk_tree_view_get_selection (tree_view),
7547                                     &iter);
7548 }
7549
7550 static gboolean
7551 maybe_select (GtkTreeModel *model, 
7552               GtkTreePath  *path, 
7553               GtkTreeIter  *iter, 
7554               gpointer     data)
7555 {
7556   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (data);
7557   GtkTreeSelection *selection;
7558   gboolean is_sensitive;
7559   gboolean is_folder;
7560   
7561   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7562   
7563   gtk_tree_model_get (model, iter,
7564                       MODEL_COL_IS_FOLDER, &is_folder,
7565                       MODEL_COL_IS_SENSITIVE, &is_sensitive,
7566                       -1);
7567
7568   if (is_sensitive &&
7569       ((is_folder && impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER) ||
7570        (!is_folder && impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)))
7571     gtk_tree_selection_select_iter (selection, iter);
7572   else
7573     gtk_tree_selection_unselect_iter (selection, iter);
7574     
7575   return FALSE;
7576 }
7577
7578 static void
7579 gtk_file_chooser_default_select_all (GtkFileChooser *chooser)
7580 {
7581   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7582
7583   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7584       impl->operation_mode == OPERATION_MODE_RECENT)
7585     {
7586       GtkTreeSelection *selection;
7587       
7588       selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7589       gtk_tree_selection_select_all (selection);
7590       return;
7591     }
7592
7593   if (impl->select_multiple)
7594     gtk_tree_model_foreach (GTK_TREE_MODEL (impl->browse_files_model), 
7595                             maybe_select, impl);
7596 }
7597
7598 static void
7599 gtk_file_chooser_default_unselect_all (GtkFileChooser *chooser)
7600 {
7601   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7602   GtkTreeSelection *selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7603
7604   gtk_tree_selection_unselect_all (selection);
7605   pending_select_files_free (impl);
7606 }
7607
7608 /* Checks whether the filename entry for the Save modes contains a well-formed filename.
7609  *
7610  * is_well_formed_ret - whether what the user typed passes gkt_file_system_make_path()
7611  *
7612  * is_empty_ret - whether the file entry is totally empty
7613  *
7614  * is_file_part_empty_ret - whether the file part is empty (will be if user types "foobar/", and
7615  *                          the path will be "$cwd/foobar")
7616  */
7617 static void
7618 check_save_entry (GtkFileChooserDefault *impl,
7619                   GFile                **file_ret,
7620                   gboolean              *is_well_formed_ret,
7621                   gboolean              *is_empty_ret,
7622                   gboolean              *is_file_part_empty_ret,
7623                   gboolean              *is_folder)
7624 {
7625   GtkFileChooserEntry *chooser_entry;
7626   GFile *current_folder;
7627   const char *file_part;
7628   GFile *file;
7629   GError *error;
7630
7631   g_assert (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
7632             || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
7633             || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
7634                  || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
7635                 && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY));
7636
7637   chooser_entry = GTK_FILE_CHOOSER_ENTRY (impl->location_entry);
7638
7639   if (strlen (gtk_entry_get_text (GTK_ENTRY (chooser_entry))) == 0)
7640     {
7641       *file_ret = NULL;
7642       *is_well_formed_ret = TRUE;
7643       *is_empty_ret = TRUE;
7644       *is_file_part_empty_ret = TRUE;
7645       *is_folder = FALSE;
7646
7647       return;
7648     }
7649
7650   *is_empty_ret = FALSE;
7651
7652   current_folder = _gtk_file_chooser_entry_get_current_folder (chooser_entry);
7653   if (!current_folder)
7654     {
7655       *file_ret = NULL;
7656       *is_well_formed_ret = FALSE;
7657       *is_file_part_empty_ret = FALSE;
7658       *is_folder = FALSE;
7659
7660       return;
7661     }
7662
7663   file_part = _gtk_file_chooser_entry_get_file_part (chooser_entry);
7664
7665   if (!file_part || file_part[0] == '\0')
7666     {
7667       *file_ret = current_folder;
7668       *is_well_formed_ret = TRUE;
7669       *is_file_part_empty_ret = TRUE;
7670       *is_folder = TRUE;
7671
7672       return;
7673     }
7674
7675   *is_file_part_empty_ret = FALSE;
7676
7677   error = NULL;
7678   file = g_file_get_child_for_display_name (current_folder, file_part, &error);
7679   g_object_unref (current_folder);
7680
7681   if (!file)
7682     {
7683       error_building_filename_dialog (impl, error);
7684       *file_ret = NULL;
7685       *is_well_formed_ret = FALSE;
7686       *is_folder = FALSE;
7687
7688       return;
7689     }
7690
7691   *file_ret = file;
7692   *is_well_formed_ret = TRUE;
7693   *is_folder = _gtk_file_chooser_entry_get_is_folder (chooser_entry, file);
7694 }
7695
7696 struct get_files_closure {
7697   GtkFileChooserDefault *impl;
7698   GSList *result;
7699   GFile *file_from_entry;
7700 };
7701
7702 static void
7703 get_files_foreach (GtkTreeModel *model,
7704                    GtkTreePath  *path,
7705                    GtkTreeIter  *iter,
7706                    gpointer      data)
7707 {
7708   struct get_files_closure *info;
7709   GFile *file;
7710   GtkFileSystemModel *fs_model;
7711
7712   info = data;
7713   fs_model = info->impl->browse_files_model;
7714
7715   file = _gtk_file_system_model_get_file (fs_model, iter);
7716   if (!file)
7717     return; /* We are on the editable row */
7718
7719   if (!info->file_from_entry || !g_file_equal (info->file_from_entry, file))
7720     info->result = g_slist_prepend (info->result, g_object_ref (file));
7721 }
7722
7723 static GSList *
7724 gtk_file_chooser_default_get_files (GtkFileChooser *chooser)
7725 {
7726   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7727   struct get_files_closure info;
7728   GtkWindow *toplevel;
7729   GtkWidget *current_focus;
7730   gboolean file_list_seen;
7731
7732   info.impl = impl;
7733   info.result = NULL;
7734   info.file_from_entry = NULL;
7735
7736   if (impl->operation_mode == OPERATION_MODE_SEARCH)
7737     return search_get_selected_files (impl);
7738
7739   if (impl->operation_mode == OPERATION_MODE_RECENT)
7740     {
7741       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
7742         {
7743           file_list_seen = TRUE;
7744           goto file_entry;
7745         }
7746       else
7747         return recent_get_selected_files (impl);
7748     }
7749
7750   toplevel = get_toplevel (GTK_WIDGET (impl));
7751   if (toplevel)
7752     current_focus = gtk_window_get_focus (toplevel);
7753   else
7754     current_focus = NULL;
7755
7756   file_list_seen = FALSE;
7757   if (current_focus == impl->browse_files_tree_view)
7758     {
7759       GtkTreeSelection *selection;
7760
7761     file_list:
7762
7763       file_list_seen = TRUE;
7764       selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7765       gtk_tree_selection_selected_foreach (selection, get_files_foreach, &info);
7766
7767       /* If there is no selection in the file list, we probably have this situation:
7768        *
7769        * 1. The user typed a filename in the SAVE filename entry ("foo.txt").
7770        * 2. He then double-clicked on a folder ("bar") in the file list
7771        *
7772        * So we want the selection to be "bar/foo.txt".  Jump to the case for the
7773        * filename entry to see if that is the case.
7774        */
7775       if (info.result == NULL && impl->location_entry)
7776         goto file_entry;
7777     }
7778   else if (impl->location_entry && current_focus == impl->location_entry)
7779     {
7780       gboolean is_well_formed, is_empty, is_file_part_empty, is_folder;
7781
7782     file_entry:
7783
7784       check_save_entry (impl, &info.file_from_entry, &is_well_formed, &is_empty, &is_file_part_empty, &is_folder);
7785
7786       if (is_empty)
7787         goto out;
7788
7789       if (!is_well_formed)
7790         return NULL;
7791
7792       if (is_file_part_empty && impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
7793         {
7794           g_object_unref (info.file_from_entry);
7795           return NULL;
7796         }
7797
7798       if (info.file_from_entry)
7799         info.result = g_slist_prepend (info.result, info.file_from_entry);
7800       else if (!file_list_seen) 
7801         goto file_list;
7802       else
7803         return NULL;
7804     }
7805   else if (impl->toplevel_last_focus_widget == impl->browse_files_tree_view)
7806     goto file_list;
7807   else if (impl->location_entry && impl->toplevel_last_focus_widget == impl->location_entry)
7808     goto file_entry;
7809   else
7810     {
7811       /* The focus is on a dialog's action area button or something else */
7812       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7813           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
7814         goto file_entry;
7815       else
7816         goto file_list; 
7817     }
7818
7819  out:
7820
7821   /* If there's no folder selected, and we're in SELECT_FOLDER mode, then we
7822    * fall back to the current directory */
7823   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER &&
7824       info.result == NULL)
7825     {
7826       GFile *current_folder;
7827
7828       current_folder = gtk_file_chooser_get_current_folder_file (chooser);
7829
7830       if (current_folder)
7831         info.result = g_slist_prepend (info.result, current_folder);
7832     }
7833
7834   return g_slist_reverse (info.result);
7835 }
7836
7837 GFile *
7838 gtk_file_chooser_default_get_preview_file (GtkFileChooser *chooser)
7839 {
7840   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7841
7842   if (impl->preview_file)
7843     return g_object_ref (impl->preview_file);
7844   else
7845     return NULL;
7846 }
7847
7848 static GtkFileSystem *
7849 gtk_file_chooser_default_get_file_system (GtkFileChooser *chooser)
7850 {
7851   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7852
7853   return impl->file_system;
7854 }
7855
7856 /* Shows or hides the filter widgets */
7857 static void
7858 show_filters (GtkFileChooserDefault *impl,
7859               gboolean               show)
7860 {
7861   if (show)
7862     gtk_widget_show (impl->filter_combo_hbox);
7863   else
7864     gtk_widget_hide (impl->filter_combo_hbox);
7865 }
7866
7867 static void
7868 gtk_file_chooser_default_add_filter (GtkFileChooser *chooser,
7869                                      GtkFileFilter  *filter)
7870 {
7871   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7872   const gchar *name;
7873
7874   if (g_slist_find (impl->filters, filter))
7875     {
7876       g_warning ("gtk_file_chooser_add_filter() called on filter already in list\n");
7877       return;
7878     }
7879
7880   g_object_ref_sink (filter);
7881   impl->filters = g_slist_append (impl->filters, filter);
7882
7883   name = gtk_file_filter_get_name (filter);
7884   if (!name)
7885     name = "Untitled filter";   /* Place-holder, doesn't need to be marked for translation */
7886
7887   gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (impl->filter_combo), name);
7888
7889   if (!g_slist_find (impl->filters, impl->current_filter))
7890     set_current_filter (impl, filter);
7891
7892   show_filters (impl, TRUE);
7893 }
7894
7895 static void
7896 gtk_file_chooser_default_remove_filter (GtkFileChooser *chooser,
7897                                         GtkFileFilter  *filter)
7898 {
7899   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7900   GtkTreeModel *model;
7901   GtkTreeIter iter;
7902   gint filter_index;
7903
7904   filter_index = g_slist_index (impl->filters, filter);
7905
7906   if (filter_index < 0)
7907     {
7908       g_warning ("gtk_file_chooser_remove_filter() called on filter not in list\n");
7909       return;
7910     }
7911
7912   impl->filters = g_slist_remove (impl->filters, filter);
7913
7914   if (filter == impl->current_filter)
7915     {
7916       if (impl->filters)
7917         set_current_filter (impl, impl->filters->data);
7918       else
7919         set_current_filter (impl, NULL);
7920     }
7921
7922   /* Remove row from the combo box */
7923   model = gtk_combo_box_get_model (GTK_COMBO_BOX (impl->filter_combo));
7924   if (!gtk_tree_model_iter_nth_child  (model, &iter, NULL, filter_index))
7925     g_assert_not_reached ();
7926
7927   gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
7928
7929   g_object_unref (filter);
7930
7931   if (!impl->filters)
7932     show_filters (impl, FALSE);
7933 }
7934
7935 static GSList *
7936 gtk_file_chooser_default_list_filters (GtkFileChooser *chooser)
7937 {
7938   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7939
7940   return g_slist_copy (impl->filters);
7941 }
7942
7943 /* Returns the position in the shortcuts tree where the nth specified shortcut would appear */
7944 static int
7945 shortcuts_get_pos_for_shortcut_folder (GtkFileChooserDefault *impl,
7946                                        int                    pos)
7947 {
7948   return pos + shortcuts_get_index (impl, SHORTCUTS_SHORTCUTS);
7949 }
7950
7951 struct AddShortcutData
7952 {
7953   GtkFileChooserDefault *impl;
7954   GFile *file;
7955 };
7956
7957 static void
7958 add_shortcut_get_info_cb (GCancellable *cancellable,
7959                           GFileInfo    *info,
7960                           const GError *error,
7961                           gpointer      user_data)
7962 {
7963   int pos;
7964   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
7965   struct AddShortcutData *data = user_data;
7966
7967   if (!g_slist_find (data->impl->loading_shortcuts, cancellable))
7968     goto out;
7969
7970   data->impl->loading_shortcuts = g_slist_remove (data->impl->loading_shortcuts, cancellable);
7971
7972   if (cancelled || error || (! _gtk_file_info_consider_as_directory (info)))
7973     goto out;
7974
7975   pos = shortcuts_get_pos_for_shortcut_folder (data->impl, data->impl->num_shortcuts);
7976
7977   shortcuts_insert_file (data->impl, pos, SHORTCUT_TYPE_FILE, NULL, data->file, NULL, FALSE, SHORTCUTS_SHORTCUTS);
7978
7979 out:
7980   g_object_unref (data->impl);
7981   g_object_unref (data->file);
7982   g_free (data);
7983
7984   g_object_unref (cancellable);
7985 }
7986
7987 static gboolean
7988 gtk_file_chooser_default_add_shortcut_folder (GtkFileChooser  *chooser,
7989                                               GFile           *file,
7990                                               GError         **error)
7991 {
7992   GCancellable *cancellable;
7993   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7994   struct AddShortcutData *data;
7995   GSList *l;
7996   int pos;
7997
7998   /* Avoid adding duplicates */
7999   pos = shortcut_find_position (impl, file);
8000   if (pos >= 0 && pos < shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS_SEPARATOR))
8001     {
8002       gchar *uri;
8003
8004       uri = g_file_get_uri (file);
8005       /* translators, "Shortcut" means "Bookmark" here */
8006       g_set_error (error,
8007                    GTK_FILE_CHOOSER_ERROR,
8008                    GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS,
8009                    _("Shortcut %s already exists"),
8010                    uri);
8011       g_free (uri);
8012
8013       return FALSE;
8014     }
8015
8016   for (l = impl->loading_shortcuts; l; l = l->next)
8017     {
8018       GCancellable *c = l->data;
8019       GFile *f;
8020
8021       f = g_object_get_data (G_OBJECT (c), "add-shortcut-path-key");
8022       if (f && g_file_equal (file, f))
8023         {
8024           gchar *uri;
8025
8026           uri = g_file_get_uri (file);
8027           g_set_error (error,
8028                        GTK_FILE_CHOOSER_ERROR,
8029                        GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS,
8030                        _("Shortcut %s already exists"),
8031                        uri);
8032           g_free (uri);
8033
8034           return FALSE;
8035         }
8036     }
8037
8038   data = g_new0 (struct AddShortcutData, 1);
8039   data->impl = g_object_ref (impl);
8040   data->file = g_object_ref (file);
8041
8042   cancellable = _gtk_file_system_get_info (impl->file_system, file,
8043                                            "standard::type",
8044                                            add_shortcut_get_info_cb, data);
8045
8046   if (!cancellable)
8047     return FALSE;
8048
8049   impl->loading_shortcuts = g_slist_append (impl->loading_shortcuts, cancellable);
8050   g_object_set_data (G_OBJECT (cancellable), "add-shortcut-path-key", data->file);
8051
8052   return TRUE;
8053 }
8054
8055 static gboolean
8056 gtk_file_chooser_default_remove_shortcut_folder (GtkFileChooser  *chooser,
8057                                                  GFile           *file,
8058                                                  GError         **error)
8059 {
8060   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
8061   int pos;
8062   GtkTreeIter iter;
8063   GSList *l;
8064   char *uri;
8065   int i;
8066
8067   for (l = impl->loading_shortcuts; l; l = l->next)
8068     {
8069       GCancellable *c = l->data;
8070       GFile *f;
8071
8072       f = g_object_get_data (G_OBJECT (c), "add-shortcut-path-key");
8073       if (f && g_file_equal (file, f))
8074         {
8075           impl->loading_shortcuts = g_slist_remove (impl->loading_shortcuts, c);
8076           g_cancellable_cancel (c);
8077           return TRUE;
8078         }
8079     }
8080
8081   if (impl->num_shortcuts == 0)
8082     goto out;
8083
8084   pos = shortcuts_get_pos_for_shortcut_folder (impl, 0);
8085   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
8086     g_assert_not_reached ();
8087
8088   for (i = 0; i < impl->num_shortcuts; i++)
8089     {
8090       gpointer col_data;
8091       ShortcutType shortcut_type;
8092       GFile *shortcut;
8093
8094       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
8095                           SHORTCUTS_COL_DATA, &col_data,
8096                           SHORTCUTS_COL_TYPE, &shortcut_type,
8097                           -1);
8098       g_assert (col_data != NULL);
8099       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
8100
8101       shortcut = col_data;
8102       if (g_file_equal (shortcut, file))
8103         {
8104           shortcuts_remove_rows (impl, pos + i, 1);
8105           impl->num_shortcuts--;
8106           return TRUE;
8107         }
8108
8109       if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
8110         g_assert_not_reached ();
8111     }
8112
8113  out:
8114
8115   uri = g_file_get_uri (file);
8116   /* translators, "Shortcut" means "Bookmark" here */
8117   g_set_error (error,
8118                GTK_FILE_CHOOSER_ERROR,
8119                GTK_FILE_CHOOSER_ERROR_NONEXISTENT,
8120                _("Shortcut %s does not exist"),
8121                uri);
8122   g_free (uri);
8123
8124   return FALSE;
8125 }
8126
8127 static GSList *
8128 gtk_file_chooser_default_list_shortcut_folders (GtkFileChooser *chooser)
8129 {
8130   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
8131   int pos;
8132   GtkTreeIter iter;
8133   int i;
8134   GSList *list;
8135
8136   if (impl->num_shortcuts == 0)
8137     return NULL;
8138
8139   pos = shortcuts_get_pos_for_shortcut_folder (impl, 0);
8140   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
8141     g_assert_not_reached ();
8142
8143   list = NULL;
8144
8145   for (i = 0; i < impl->num_shortcuts; i++)
8146     {
8147       gpointer col_data;
8148       ShortcutType shortcut_type;
8149       GFile *shortcut;
8150
8151       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
8152                           SHORTCUTS_COL_DATA, &col_data,
8153                           SHORTCUTS_COL_TYPE, &shortcut_type,
8154                           -1);
8155       g_assert (col_data != NULL);
8156       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
8157
8158       shortcut = col_data;
8159       list = g_slist_prepend (list, g_object_ref (shortcut));
8160
8161       if (i != impl->num_shortcuts - 1)
8162         {
8163           if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
8164             g_assert_not_reached ();
8165         }
8166     }
8167
8168   return g_slist_reverse (list);
8169 }
8170
8171 /* Guesses a size based upon font sizes */
8172 static void
8173 find_good_size_from_style (GtkWidget *widget,
8174                            gint      *width,
8175                            gint      *height)
8176 {
8177   GtkStyleContext *context;
8178   GtkStateFlags state;
8179   int font_size;
8180   GdkScreen *screen;
8181   double resolution;
8182
8183   context = gtk_widget_get_style_context (widget);
8184   state = gtk_widget_get_state_flags (widget);
8185
8186   screen = gtk_widget_get_screen (widget);
8187   if (screen)
8188     {
8189       resolution = gdk_screen_get_resolution (screen);
8190       if (resolution < 0.0) /* will be -1 if the resolution is not defined in the GdkScreen */
8191         resolution = 96.0;
8192     }
8193   else
8194     resolution = 96.0; /* wheeee */
8195
8196   font_size = pango_font_description_get_size (gtk_style_context_get_font (context, state));
8197   font_size = PANGO_PIXELS (font_size) * resolution / 72.0;
8198
8199   *width = font_size * NUM_CHARS;
8200   *height = font_size * NUM_LINES;
8201 }
8202
8203 static void
8204 gtk_file_chooser_default_get_default_size (GtkFileChooserEmbed *chooser_embed,
8205                                            gint                *default_width,
8206                                            gint                *default_height)
8207 {
8208   GtkFileChooserDefault *impl;
8209   GtkRequisition req;
8210   int x, y, width, height;
8211
8212   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
8213
8214   settings_ensure (impl);
8215
8216   g_settings_get (impl->settings, SETTINGS_KEY_WINDOW_POSITION, "(ii)", &x, &y);
8217   g_settings_get (impl->settings, SETTINGS_KEY_WINDOW_SIZE, "(ii)", &width, &height);
8218
8219   if (x >= 0 && y >= 0 && width > 0 && height > 0)
8220     {
8221       *default_width = width;
8222       *default_height = height;
8223       return;
8224     }
8225
8226   find_good_size_from_style (GTK_WIDGET (chooser_embed), default_width, default_height);
8227
8228   if (impl->preview_widget_active &&
8229       impl->preview_widget &&
8230       gtk_widget_get_visible (impl->preview_widget))
8231     {
8232       gtk_widget_get_preferred_size (impl->preview_box,
8233                                      &req, NULL);
8234       *default_width += PREVIEW_HBOX_SPACING + req.width;
8235     }
8236
8237   if (impl->extra_widget &&
8238       gtk_widget_get_visible (impl->extra_widget))
8239     {
8240       gtk_widget_get_preferred_size (impl->extra_align,
8241                                      &req, NULL);
8242       *default_height += gtk_box_get_spacing (GTK_BOX (chooser_embed)) + req.height;
8243     }
8244 }
8245
8246 struct switch_folder_closure {
8247   GtkFileChooserDefault *impl;
8248   GFile *file;
8249   int num_selected;
8250 };
8251
8252 /* Used from gtk_tree_selection_selected_foreach() in switch_to_selected_folder() */
8253 static void
8254 switch_folder_foreach_cb (GtkTreeModel      *model,
8255                           GtkTreePath       *path,
8256                           GtkTreeIter       *iter,
8257                           gpointer           data)
8258 {
8259   struct switch_folder_closure *closure;
8260
8261   closure = data;
8262
8263   closure->file = _gtk_file_system_model_get_file (closure->impl->browse_files_model, iter);
8264   closure->num_selected++;
8265 }
8266
8267 /* Changes to the selected folder in the list view */
8268 static void
8269 switch_to_selected_folder (GtkFileChooserDefault *impl)
8270 {
8271   GtkTreeSelection *selection;
8272   struct switch_folder_closure closure;
8273
8274   /* We do this with foreach() rather than get_selected() as we may be in
8275    * multiple selection mode
8276    */
8277
8278   closure.impl = impl;
8279   closure.file = NULL;
8280   closure.num_selected = 0;
8281
8282   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8283   gtk_tree_selection_selected_foreach (selection, switch_folder_foreach_cb, &closure);
8284
8285   g_assert (closure.file && closure.num_selected == 1);
8286
8287   change_folder_and_display_error (impl, closure.file, FALSE);
8288 }
8289
8290 /* Gets the GFileInfo for the selected row in the file list; assumes single
8291  * selection mode.
8292  */
8293 static GFileInfo *
8294 get_selected_file_info_from_file_list (GtkFileChooserDefault *impl,
8295                                        gboolean              *had_selection)
8296 {
8297   GtkTreeSelection *selection;
8298   GtkTreeIter iter;
8299   GFileInfo *info;
8300
8301   g_assert (!impl->select_multiple);
8302   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8303   if (!gtk_tree_selection_get_selected (selection, NULL, &iter))
8304     {
8305       *had_selection = FALSE;
8306       return NULL;
8307     }
8308
8309   *had_selection = TRUE;
8310
8311   info = _gtk_file_system_model_get_info (impl->browse_files_model, &iter);
8312   return info;
8313 }
8314
8315 /* Gets the display name of the selected file in the file list; assumes single
8316  * selection mode and that something is selected.
8317  */
8318 static const gchar *
8319 get_display_name_from_file_list (GtkFileChooserDefault *impl)
8320 {
8321   GFileInfo *info;
8322   gboolean had_selection;
8323
8324   info = get_selected_file_info_from_file_list (impl, &had_selection);
8325   g_assert (had_selection);
8326   g_assert (info != NULL);
8327
8328   return g_file_info_get_display_name (info);
8329 }
8330
8331 static void
8332 add_custom_button_to_dialog (GtkDialog   *dialog,
8333                              const gchar *mnemonic_label,
8334                              const gchar *stock_id,
8335                              gint         response_id)
8336 {
8337   GtkWidget *button;
8338
8339   button = gtk_button_new_with_mnemonic (mnemonic_label);
8340   gtk_widget_set_can_default (button, TRUE);
8341   gtk_button_set_image (GTK_BUTTON (button),
8342                         gtk_image_new_from_stock (stock_id, GTK_ICON_SIZE_BUTTON));
8343   gtk_widget_show (button);
8344
8345   gtk_dialog_add_action_widget (GTK_DIALOG (dialog), button, response_id);
8346 }
8347
8348 /* Presents an overwrite confirmation dialog; returns whether we should accept
8349  * the filename.
8350  */
8351 static gboolean
8352 confirm_dialog_should_accept_filename (GtkFileChooserDefault *impl,
8353                                        const gchar           *file_part,
8354                                        const gchar           *folder_display_name)
8355 {
8356   GtkWindow *toplevel;
8357   GtkWidget *dialog;
8358   int response;
8359
8360   toplevel = get_toplevel (GTK_WIDGET (impl));
8361
8362   dialog = gtk_message_dialog_new (toplevel,
8363                                    GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
8364                                    GTK_MESSAGE_QUESTION,
8365                                    GTK_BUTTONS_NONE,
8366                                    _("A file named \"%s\" already exists.  Do you want to replace it?"),
8367                                    file_part);
8368   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
8369                                             _("The file already exists in \"%s\".  Replacing it will "
8370                                               "overwrite its contents."),
8371                                             folder_display_name);
8372
8373   gtk_dialog_add_button (GTK_DIALOG (dialog), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
8374   add_custom_button_to_dialog (GTK_DIALOG (dialog), _("_Replace"),
8375                                GTK_STOCK_SAVE_AS, GTK_RESPONSE_ACCEPT);
8376   gtk_dialog_set_alternative_button_order (GTK_DIALOG (dialog),
8377                                            GTK_RESPONSE_ACCEPT,
8378                                            GTK_RESPONSE_CANCEL,
8379                                            -1);
8380   gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);
8381
8382   if (gtk_window_has_group (toplevel))
8383     gtk_window_group_add_window (gtk_window_get_group (toplevel),
8384                                  GTK_WINDOW (dialog));
8385
8386   response = gtk_dialog_run (GTK_DIALOG (dialog));
8387
8388   gtk_widget_destroy (dialog);
8389
8390   return (response == GTK_RESPONSE_ACCEPT);
8391 }
8392
8393 struct GetDisplayNameData
8394 {
8395   GtkFileChooserDefault *impl;
8396   gchar *file_part;
8397 };
8398
8399 /* Every time we request a response explicitly, we need to save the selection to the recently-used list,
8400  * as requesting a response means, "the dialog is confirmed".
8401  */
8402 static void
8403 request_response_and_add_to_recent_list (GtkFileChooserDefault *impl)
8404 {
8405   g_signal_emit_by_name (impl, "response-requested");
8406   add_selection_to_recent_list (impl);
8407 }
8408
8409 static void
8410 confirmation_confirm_get_info_cb (GCancellable *cancellable,
8411                                   GFileInfo    *info,
8412                                   const GError *error,
8413                                   gpointer      user_data)
8414 {
8415   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8416   gboolean should_respond = FALSE;
8417   struct GetDisplayNameData *data = user_data;
8418
8419   if (cancellable != data->impl->should_respond_get_info_cancellable)
8420     goto out;
8421
8422   data->impl->should_respond_get_info_cancellable = NULL;
8423
8424   if (cancelled)
8425     goto out;
8426
8427   if (error)
8428     /* Huh?  Did the folder disappear?  Let the caller deal with it */
8429     should_respond = TRUE;
8430   else
8431     should_respond = confirm_dialog_should_accept_filename (data->impl, data->file_part, g_file_info_get_display_name (info));
8432
8433   set_busy_cursor (data->impl, FALSE);
8434   if (should_respond)
8435     request_response_and_add_to_recent_list (data->impl);
8436
8437 out:
8438   g_object_unref (data->impl);
8439   g_free (data->file_part);
8440   g_free (data);
8441
8442   g_object_unref (cancellable);
8443 }
8444
8445 /* Does overwrite confirmation if appropriate, and returns whether the dialog
8446  * should respond.  Can get the file part from the file list or the save entry.
8447  */
8448 static gboolean
8449 should_respond_after_confirm_overwrite (GtkFileChooserDefault *impl,
8450                                         const gchar           *file_part,
8451                                         GFile                 *parent_file)
8452 {
8453   GtkFileChooserConfirmation conf;
8454
8455   if (!impl->do_overwrite_confirmation)
8456     return TRUE;
8457
8458   conf = GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM;
8459
8460   g_signal_emit_by_name (impl, "confirm-overwrite", &conf);
8461
8462   switch (conf)
8463     {
8464     case GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM:
8465       {
8466         struct GetDisplayNameData *data;
8467
8468         g_assert (file_part != NULL);
8469
8470         data = g_new0 (struct GetDisplayNameData, 1);
8471         data->impl = g_object_ref (impl);
8472         data->file_part = g_strdup (file_part);
8473
8474         if (impl->should_respond_get_info_cancellable)
8475           g_cancellable_cancel (impl->should_respond_get_info_cancellable);
8476
8477         impl->should_respond_get_info_cancellable =
8478           _gtk_file_system_get_info (impl->file_system, parent_file,
8479                                      "standard::display-name",
8480                                      confirmation_confirm_get_info_cb,
8481                                      data);
8482         set_busy_cursor (data->impl, TRUE);
8483         return FALSE;
8484       }
8485
8486     case GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME:
8487       return TRUE;
8488
8489     case GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN:
8490       return FALSE;
8491
8492     default:
8493       g_assert_not_reached ();
8494       return FALSE;
8495     }
8496 }
8497
8498 struct FileExistsData
8499 {
8500   GtkFileChooserDefault *impl;
8501   gboolean file_exists_and_is_not_folder;
8502   GFile *parent_file;
8503   GFile *file;
8504 };
8505
8506 static void
8507 name_entry_get_parent_info_cb (GCancellable *cancellable,
8508                                GFileInfo    *info,
8509                                const GError *error,
8510                                gpointer      user_data)
8511 {
8512   gboolean parent_is_folder;
8513   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8514   struct FileExistsData *data = user_data;
8515
8516   if (cancellable != data->impl->should_respond_get_info_cancellable)
8517     goto out;
8518
8519   data->impl->should_respond_get_info_cancellable = NULL;
8520
8521   set_busy_cursor (data->impl, FALSE);
8522
8523   if (cancelled)
8524     goto out;
8525
8526   if (!info)
8527     parent_is_folder = FALSE;
8528   else
8529     parent_is_folder = _gtk_file_info_consider_as_directory (info);
8530
8531   if (parent_is_folder)
8532     {
8533       if (data->impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
8534         {
8535           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) */
8536         }
8537       else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8538         {
8539           if (data->file_exists_and_is_not_folder)
8540             {
8541               gboolean retval;
8542               char *file_part;
8543
8544               /* Dup the string because the string may be modified
8545                * depending on what clients do in the confirm-overwrite
8546                * signal and this corrupts the pointer
8547                */
8548               file_part = g_strdup (_gtk_file_chooser_entry_get_file_part (GTK_FILE_CHOOSER_ENTRY (data->impl->location_entry)));
8549               retval = should_respond_after_confirm_overwrite (data->impl, file_part, data->parent_file);
8550               g_free (file_part);
8551
8552               if (retval)
8553                 request_response_and_add_to_recent_list (data->impl);
8554             }
8555           else
8556             request_response_and_add_to_recent_list (data->impl);
8557         }
8558       else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER
8559                || data->impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8560         {
8561           GError *mkdir_error = NULL;
8562
8563           /* In both cases (SELECT_FOLDER and CREATE_FOLDER), if you type
8564            * "/blah/nonexistent" you *will* want a folder created.
8565            */
8566
8567           set_busy_cursor (data->impl, TRUE);
8568           g_file_make_directory (data->file, NULL, &mkdir_error);
8569           set_busy_cursor (data->impl, FALSE);
8570
8571           if (!mkdir_error)
8572             request_response_and_add_to_recent_list (data->impl);
8573           else
8574             error_creating_folder_dialog (data->impl, data->file, mkdir_error);
8575         }
8576       else
8577         g_assert_not_reached ();
8578     }
8579   else
8580     {
8581       if (info)
8582         {
8583           /* The parent exists, but it's not a folder!  Someone probably typed existing_file.txt/subfile.txt */
8584           error_with_file_under_nonfolder (data->impl, data->parent_file);
8585         }
8586       else
8587         {
8588           GError *error_copy;
8589
8590           /* The parent folder is not readable for some reason */
8591
8592           error_copy = g_error_copy (error);
8593           error_changing_folder_dialog (data->impl, data->parent_file, error_copy);
8594         }
8595     }
8596
8597 out:
8598   g_object_unref (data->impl);
8599   g_object_unref (data->file);
8600   g_object_unref (data->parent_file);
8601   g_free (data);
8602
8603   g_object_unref (cancellable);
8604 }
8605
8606 static void
8607 file_exists_get_info_cb (GCancellable *cancellable,
8608                          GFileInfo    *info,
8609                          const GError *error,
8610                          gpointer      user_data)
8611 {
8612   gboolean data_ownership_taken = FALSE;
8613   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8614   gboolean file_exists;
8615   gboolean is_folder;
8616   gboolean needs_parent_check = FALSE;
8617   struct FileExistsData *data = user_data;
8618
8619   if (cancellable != data->impl->file_exists_get_info_cancellable)
8620     goto out;
8621
8622   data->impl->file_exists_get_info_cancellable = NULL;
8623
8624   set_busy_cursor (data->impl, FALSE);
8625
8626   if (cancelled)
8627     goto out;
8628
8629   file_exists = (info != NULL);
8630   is_folder = (file_exists && _gtk_file_info_consider_as_directory (info));
8631
8632   if (data->impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
8633     {
8634       if (is_folder)
8635         change_folder_and_display_error (data->impl, data->file, TRUE);
8636       else
8637         {
8638           if (file_exists)
8639             request_response_and_add_to_recent_list (data->impl); /* user typed an existing filename; we are done */
8640           else
8641             needs_parent_check = TRUE; /* file doesn't exist; see if its parent exists */
8642         }
8643     }
8644   else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8645     {
8646       if (file_exists && !is_folder)
8647         {
8648           /* Oops, the user typed the name of an existing path which is not
8649            * a folder
8650            */
8651           error_creating_folder_over_existing_file_dialog (data->impl, data->file,
8652                                                            g_error_copy (error));
8653         }
8654       else
8655         {
8656           needs_parent_check = TRUE;
8657         }
8658     }
8659   else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8660     {
8661       if (!file_exists)
8662         {
8663           needs_parent_check = TRUE;
8664         }
8665       else
8666         {
8667           if (is_folder)
8668             {
8669               /* User typed a folder; we are done */
8670               request_response_and_add_to_recent_list (data->impl);
8671             }
8672           else
8673             error_selecting_folder_over_existing_file_dialog (data->impl, data->file);
8674         }
8675     }
8676   else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8677     {
8678       if (is_folder)
8679         change_folder_and_display_error (data->impl, data->file, TRUE);
8680       else
8681         needs_parent_check = TRUE;
8682     }
8683   else
8684     {
8685       g_assert_not_reached();
8686     }
8687
8688   if (needs_parent_check) {
8689     /* check that everything up to the last path component exists (i.e. the parent) */
8690
8691     data->file_exists_and_is_not_folder = file_exists && !is_folder;
8692     data_ownership_taken = TRUE;
8693
8694     if (data->impl->should_respond_get_info_cancellable)
8695       g_cancellable_cancel (data->impl->should_respond_get_info_cancellable);
8696
8697       data->impl->should_respond_get_info_cancellable =
8698         _gtk_file_system_get_info (data->impl->file_system,
8699                                    data->parent_file,
8700                                    "standard::type",
8701                                    name_entry_get_parent_info_cb,
8702                                    data);
8703       set_busy_cursor (data->impl, TRUE);
8704     }
8705
8706 out:
8707   if (!data_ownership_taken)
8708     {
8709       g_object_unref (data->impl);
8710       g_object_unref (data->file);
8711       g_object_unref (data->parent_file);
8712       g_free (data);
8713     }
8714
8715   g_object_unref (cancellable);
8716 }
8717
8718 static void
8719 paste_text_received (GtkClipboard          *clipboard,
8720                      const gchar           *text,
8721                      GtkFileChooserDefault *impl)
8722 {
8723   GFile *file;
8724
8725   if (!text)
8726     return;
8727
8728   file = g_file_new_for_uri (text);
8729
8730   if (!gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (impl), file, NULL))
8731     location_popup_handler (impl, text);
8732
8733   g_object_unref (file);
8734 }
8735
8736 /* Handler for the "location-popup-on-paste" keybinding signal */
8737 static void
8738 location_popup_on_paste_handler (GtkFileChooserDefault *impl)
8739 {
8740   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (impl),
8741                                                       GDK_SELECTION_CLIPBOARD);
8742   gtk_clipboard_request_text (clipboard,
8743                               (GtkClipboardTextReceivedFunc) paste_text_received,
8744                               impl);
8745 }
8746
8747 /* Implementation for GtkFileChooserEmbed::should_respond() */
8748 static void
8749 add_selection_to_recent_list (GtkFileChooserDefault *impl)
8750 {
8751   GSList *files;
8752   GSList *l;
8753
8754   files = gtk_file_chooser_default_get_files (GTK_FILE_CHOOSER (impl));
8755
8756   for (l = files; l; l = l->next)
8757     {
8758       GFile *file = l->data;
8759       char *uri;
8760
8761       uri = g_file_get_uri (file);
8762       if (uri)
8763         {
8764           gtk_recent_manager_add_item (impl->recent_manager, uri);
8765           g_free (uri);
8766         }
8767     }
8768
8769   g_slist_foreach (files, (GFunc) g_object_unref, NULL);
8770   g_slist_free (files);
8771 }
8772
8773 static gboolean
8774 gtk_file_chooser_default_should_respond (GtkFileChooserEmbed *chooser_embed)
8775 {
8776   GtkFileChooserDefault *impl;
8777   GtkWidget *toplevel;
8778   GtkWidget *current_focus;
8779   gboolean retval;
8780
8781   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
8782
8783   toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
8784   g_assert (GTK_IS_WINDOW (toplevel));
8785
8786   retval = FALSE;
8787
8788   current_focus = gtk_window_get_focus (GTK_WINDOW (toplevel));
8789
8790   if (current_focus == impl->browse_files_tree_view)
8791     {
8792       /* The following array encodes what we do based on the impl->action and the
8793        * number of files selected.
8794        */
8795       typedef enum {
8796         NOOP,                   /* Do nothing (don't respond) */
8797         RESPOND,                /* Respond immediately */
8798         RESPOND_OR_SWITCH,      /* Respond immediately if the selected item is a file; switch to it if it is a folder */
8799         ALL_FILES,              /* Respond only if everything selected is a file */
8800         ALL_FOLDERS,            /* Respond only if everything selected is a folder */
8801         SAVE_ENTRY,             /* Go to the code for handling the save entry */
8802         NOT_REACHED             /* Sanity check */
8803       } ActionToTake;
8804       static const ActionToTake what_to_do[4][3] = {
8805         /*                                0 selected            1 selected              many selected */
8806         /* ACTION_OPEN */               { NOOP,                 RESPOND_OR_SWITCH,      ALL_FILES   },
8807         /* ACTION_SAVE */               { SAVE_ENTRY,           RESPOND_OR_SWITCH,      NOT_REACHED },
8808         /* ACTION_SELECT_FOLDER */      { RESPOND,              ALL_FOLDERS,            ALL_FOLDERS },
8809         /* ACTION_CREATE_FOLDER */      { SAVE_ENTRY,           ALL_FOLDERS,            NOT_REACHED }
8810       };
8811
8812       int num_selected;
8813       gboolean all_files, all_folders;
8814       int k;
8815       ActionToTake action;
8816
8817     file_list:
8818
8819       g_assert (impl->action >= GTK_FILE_CHOOSER_ACTION_OPEN && impl->action <= GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
8820
8821       if (impl->operation_mode == OPERATION_MODE_SEARCH)
8822         {
8823           retval = search_should_respond (impl);
8824           goto out;
8825         }
8826
8827       if (impl->operation_mode == OPERATION_MODE_RECENT)
8828         {
8829           if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8830             goto save_entry;
8831           else
8832             {
8833               retval = recent_should_respond (impl);
8834               goto out;
8835             }
8836         }
8837
8838       selection_check (impl, &num_selected, &all_files, &all_folders);
8839
8840       if (num_selected > 2)
8841         k = 2;
8842       else
8843         k = num_selected;
8844
8845       action = what_to_do [impl->action] [k];
8846
8847       switch (action)
8848         {
8849         case NOOP:
8850           return FALSE;
8851
8852         case RESPOND:
8853           retval = TRUE;
8854           goto out;
8855
8856         case RESPOND_OR_SWITCH:
8857           g_assert (num_selected == 1);
8858
8859           if (all_folders)
8860             {
8861               switch_to_selected_folder (impl);
8862               return FALSE;
8863             }
8864           else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8865             {
8866               retval = should_respond_after_confirm_overwrite (impl,
8867                                                                get_display_name_from_file_list (impl),
8868                                                                impl->current_folder);
8869               goto out;
8870             }
8871           else
8872             {
8873               retval = TRUE;
8874               goto out;
8875             }
8876
8877         case ALL_FILES:
8878           retval = all_files;
8879           goto out;
8880
8881         case ALL_FOLDERS:
8882           retval = all_folders;
8883           goto out;
8884
8885         case SAVE_ENTRY:
8886           goto save_entry;
8887
8888         default:
8889           g_assert_not_reached ();
8890         }
8891     }
8892   else if ((impl->location_entry != NULL) && (current_focus == impl->location_entry))
8893     {
8894       GFile *file;
8895       gboolean is_well_formed, is_empty, is_file_part_empty;
8896       gboolean is_folder;
8897       GtkFileChooserEntry *entry;
8898       GError *error;
8899
8900     save_entry:
8901
8902       g_assert (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8903                 || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
8904                 || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
8905                      || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8906                     && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY));
8907
8908       entry = GTK_FILE_CHOOSER_ENTRY (impl->location_entry);
8909       check_save_entry (impl, &file, &is_well_formed, &is_empty, &is_file_part_empty, &is_folder);
8910
8911       if (!is_well_formed)
8912         {
8913           if (!is_empty
8914               && impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8915               && impl->operation_mode == OPERATION_MODE_RECENT)
8916             {
8917               path_bar_set_mode (impl, PATH_BAR_ERROR_NO_FOLDER);
8918 #if 0
8919               /* We'll #ifdef this out, as the fucking treeview selects its first row,
8920                * thus changing our assumption that no selection is present - setting
8921                * a selection causes the error message from path_bar_set_mode() to go away,
8922                * but we want the user to see that message!
8923                */
8924               gtk_widget_grab_focus (impl->browse_files_tree_view);
8925 #endif
8926             }
8927           /* FIXME: else show an "invalid filename" error as the pathbar mode? */
8928
8929           return FALSE;
8930         }
8931
8932       if (is_empty)
8933         {
8934           if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8935               || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8936             {
8937               path_bar_set_mode (impl, PATH_BAR_ERROR_NO_FILENAME);
8938               gtk_widget_grab_focus (impl->location_entry);
8939               return FALSE;
8940             }
8941
8942           goto file_list;
8943         }
8944
8945       g_assert (file != NULL);
8946
8947       error = NULL;
8948       if (is_folder)
8949         {
8950           if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8951               impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8952             {
8953               change_folder_and_display_error (impl, file, TRUE);
8954             }
8955           else if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
8956                    impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8957             {
8958               /* The folder already exists, so we do not need to create it.
8959                * Just respond to terminate the dialog.
8960                */
8961               retval = TRUE;
8962             }
8963           else
8964             {
8965               g_assert_not_reached ();
8966             }
8967         }
8968       else
8969         {
8970           struct FileExistsData *data;
8971
8972           /* We need to check whether file exists and whether it is a folder -
8973            * the GtkFileChooserEntry *does* report is_folder==FALSE as a false
8974            * negative (it doesn't know yet if your last path component is a
8975            * folder).
8976            */
8977
8978           data = g_new0 (struct FileExistsData, 1);
8979           data->impl = g_object_ref (impl);
8980           data->file = g_object_ref (file);
8981           data->parent_file = _gtk_file_chooser_entry_get_current_folder (entry);
8982
8983           if (impl->file_exists_get_info_cancellable)
8984             g_cancellable_cancel (impl->file_exists_get_info_cancellable);
8985
8986           impl->file_exists_get_info_cancellable =
8987             _gtk_file_system_get_info (impl->file_system, file,
8988                                        "standard::type",
8989                                        file_exists_get_info_cb,
8990                                        data);
8991
8992           set_busy_cursor (impl, TRUE);
8993
8994           if (error != NULL)
8995             g_error_free (error);
8996         }
8997
8998       g_object_unref (file);
8999     }
9000   else if (impl->toplevel_last_focus_widget == impl->browse_files_tree_view)
9001     {
9002       /* The focus is on a dialog's action area button, *and* the widget that
9003        * was focused immediately before it is the file list.  
9004        */
9005       goto file_list;
9006     }
9007   else if (impl->operation_mode == OPERATION_MODE_SEARCH && impl->toplevel_last_focus_widget == impl->search_entry)
9008     {
9009       search_entry_activate_cb (GTK_ENTRY (impl->search_entry), impl);
9010       return FALSE;
9011     }
9012   else if (impl->location_entry && impl->toplevel_last_focus_widget == impl->location_entry)
9013     {
9014       /* The focus is on a dialog's action area button, *and* the widget that
9015        * was focused immediately before it is the location entry.
9016        */
9017       goto save_entry;
9018     }
9019   else
9020     /* The focus is on a dialog's action area button or something else */
9021     if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
9022         || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
9023       goto save_entry;
9024     else
9025       goto file_list; 
9026
9027  out:
9028
9029   if (retval)
9030     add_selection_to_recent_list (impl);
9031
9032   return retval;
9033 }
9034
9035 /* Implementation for GtkFileChooserEmbed::initial_focus() */
9036 static void
9037 gtk_file_chooser_default_initial_focus (GtkFileChooserEmbed *chooser_embed)
9038 {
9039   GtkFileChooserDefault *impl;
9040   GtkWidget *widget;
9041
9042   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
9043
9044   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9045       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9046     {
9047       if (impl->location_mode == LOCATION_MODE_PATH_BAR
9048           || impl->operation_mode == OPERATION_MODE_RECENT)
9049         widget = impl->browse_files_tree_view;
9050       else
9051         widget = impl->location_entry;
9052     }
9053   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
9054            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
9055     widget = impl->location_entry;
9056   else
9057     {
9058       g_assert_not_reached ();
9059       widget = NULL;
9060     }
9061
9062   g_assert (widget != NULL);
9063   gtk_widget_grab_focus (widget);
9064 }
9065
9066 /* Callback used from gtk_tree_selection_selected_foreach(); gets the selected GFiles */
9067 static void
9068 search_selected_foreach_get_file_cb (GtkTreeModel *model,
9069                                      GtkTreePath  *path,
9070                                      GtkTreeIter  *iter,
9071                                      gpointer      data)
9072 {
9073   GSList **list;
9074   GFile *file;
9075
9076   list = data;
9077
9078   gtk_tree_model_get (model, iter, MODEL_COL_FILE, &file, -1);
9079   *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 */
9080 }
9081
9082 /* Constructs a list of the selected paths in search mode */
9083 static GSList *
9084 search_get_selected_files (GtkFileChooserDefault *impl)
9085 {
9086   GSList *result;
9087   GtkTreeSelection *selection;
9088
9089   result = NULL;
9090
9091   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9092   gtk_tree_selection_selected_foreach (selection, search_selected_foreach_get_file_cb, &result);
9093   result = g_slist_reverse (result);
9094
9095   return result;
9096 }
9097
9098 /* Called from ::should_respond().  We return whether there are selected files
9099  * in the search list.
9100  */
9101 static gboolean
9102 search_should_respond (GtkFileChooserDefault *impl)
9103 {
9104   GtkTreeSelection *selection;
9105
9106   g_assert (impl->operation_mode == OPERATION_MODE_SEARCH);
9107
9108   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9109   return (gtk_tree_selection_count_selected_rows (selection) != 0);
9110 }
9111
9112 /* Adds one hit from the search engine to the search_model */
9113 static void
9114 search_add_hit (GtkFileChooserDefault *impl,
9115                 gchar                 *uri)
9116 {
9117   GFile *file;
9118
9119   file = g_file_new_for_uri (uri);
9120   if (!file)
9121     return;
9122
9123   if (!g_file_is_native (file))
9124     {
9125       g_object_unref (file);
9126       return;
9127     }
9128
9129   _gtk_file_system_model_add_and_query_file (impl->search_model,
9130                                              file,
9131                                              MODEL_ATTRIBUTES);
9132
9133   g_object_unref (file);
9134 }
9135
9136 /* Callback used from GtkSearchEngine when we get new hits */
9137 static void
9138 search_engine_hits_added_cb (GtkSearchEngine *engine,
9139                              GList           *hits,
9140                              gpointer         data)
9141 {
9142   GtkFileChooserDefault *impl;
9143   GList *l;
9144   
9145   impl = GTK_FILE_CHOOSER_DEFAULT (data);
9146
9147   for (l = hits; l; l = l->next)
9148     search_add_hit (impl, (gchar*)l->data);
9149 }
9150
9151 /* Callback used from GtkSearchEngine when the query is done running */
9152 static void
9153 search_engine_finished_cb (GtkSearchEngine *engine,
9154                            gpointer         data)
9155 {
9156   GtkFileChooserDefault *impl;
9157   
9158   impl = GTK_FILE_CHOOSER_DEFAULT (data);
9159   
9160 #if 0
9161   /* EB: setting the model here will avoid loads of row events,
9162    * but it'll make the search look like blocked.
9163    */
9164   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9165                            GTK_TREE_MODEL (impl->search_model));
9166   file_list_set_sort_column_ids (impl);
9167 #endif
9168
9169   /* FMQ: if search was empty, say that we got no hits */
9170   set_busy_cursor (impl, FALSE);
9171 }
9172
9173 /* Displays a generic error when we cannot create a GtkSearchEngine.  
9174  * It would be better if _gtk_search_engine_new() gave us a GError 
9175  * with a better message, but it doesn't do that right now.
9176  */
9177 static void
9178 search_error_could_not_create_client (GtkFileChooserDefault *impl)
9179 {
9180   error_message (impl,
9181                  _("Could not start the search process"),
9182                  _("The program was not able to create a connection to the indexer "
9183                    "daemon.  Please make sure it is running."));
9184 }
9185
9186 static void
9187 search_engine_error_cb (GtkSearchEngine *engine,
9188                         const gchar     *message,
9189                         gpointer         data)
9190 {
9191   GtkFileChooserDefault *impl;
9192   
9193   impl = GTK_FILE_CHOOSER_DEFAULT (data);
9194
9195   search_stop_searching (impl, TRUE);
9196   error_message (impl, _("Could not send the search request"), message);
9197
9198   set_busy_cursor (impl, FALSE);
9199 }
9200
9201 /* Frees the data in the search_model */
9202 static void
9203 search_clear_model (GtkFileChooserDefault *impl, 
9204                     gboolean               remove_from_treeview)
9205 {
9206   if (!impl->search_model)
9207     return;
9208
9209   g_object_unref (impl->search_model);
9210   impl->search_model = NULL;
9211   
9212   if (remove_from_treeview)
9213     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
9214 }
9215
9216 /* Stops any ongoing searches; does not touch the search_model */
9217 static void
9218 search_stop_searching (GtkFileChooserDefault *impl,
9219                        gboolean               remove_query)
9220 {
9221   if (remove_query && impl->search_query)
9222     {
9223       g_object_unref (impl->search_query);
9224       impl->search_query = NULL;
9225     }
9226   
9227   if (impl->search_engine)
9228     {
9229       _gtk_search_engine_stop (impl->search_engine);
9230       
9231       g_object_unref (impl->search_engine);
9232       impl->search_engine = NULL;
9233     }
9234 }
9235
9236 /* Creates the search_model and puts it in the tree view */
9237 static void
9238 search_setup_model (GtkFileChooserDefault *impl)
9239 {
9240   g_assert (impl->search_model == NULL);
9241
9242   impl->search_model = _gtk_file_system_model_new (file_system_model_set,
9243                                                    impl,
9244                                                    MODEL_COLUMN_TYPES);
9245
9246   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model),
9247                                    MODEL_COL_NAME,
9248                                    name_sort_func,
9249                                    impl, NULL);
9250   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model),
9251                                    MODEL_COL_MTIME,
9252                                    mtime_sort_func,
9253                                    impl, NULL);
9254   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model),
9255                                    MODEL_COL_SIZE,
9256                                    size_sort_func,
9257                                    impl, NULL);
9258   set_sort_column (impl);
9259
9260   /* EB: setting the model here will make the hits list update feel
9261    * more "alive" than setting the model at the end of the search
9262    * run
9263    */
9264   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9265                            GTK_TREE_MODEL (impl->search_model));
9266   file_list_set_sort_column_ids (impl);
9267 }
9268
9269 /* Creates a new query with the specified text and launches it */
9270 static void
9271 search_start_query (GtkFileChooserDefault *impl,
9272                     const gchar           *query_text)
9273 {
9274   search_stop_searching (impl, FALSE);
9275   search_clear_model (impl, TRUE);
9276   search_setup_model (impl);
9277   set_busy_cursor (impl, TRUE);
9278
9279   if (impl->search_engine == NULL)
9280     impl->search_engine = _gtk_search_engine_new ();
9281
9282   if (!impl->search_engine)
9283     {
9284       set_busy_cursor (impl, FALSE);
9285       search_error_could_not_create_client (impl); /* lame; we don't get an error code or anything */
9286       return;
9287     }
9288
9289   if (!impl->search_query)
9290     {
9291       impl->search_query = _gtk_query_new ();
9292       _gtk_query_set_text (impl->search_query, query_text);
9293     }
9294   
9295   _gtk_search_engine_set_query (impl->search_engine, impl->search_query);
9296
9297   g_signal_connect (impl->search_engine, "hits-added",
9298                     G_CALLBACK (search_engine_hits_added_cb), impl);
9299   g_signal_connect (impl->search_engine, "finished",
9300                     G_CALLBACK (search_engine_finished_cb), impl);
9301   g_signal_connect (impl->search_engine, "error",
9302                     G_CALLBACK (search_engine_error_cb), impl);
9303
9304   _gtk_search_engine_start (impl->search_engine);
9305 }
9306
9307 /* Callback used when the user presses Enter while typing on the search
9308  * entry; starts the query
9309  */
9310 static void
9311 search_entry_activate_cb (GtkEntry *entry,
9312                           gpointer data)
9313 {
9314   GtkFileChooserDefault *impl;
9315   const char *text;
9316
9317   impl = GTK_FILE_CHOOSER_DEFAULT (data);
9318
9319   text = gtk_entry_get_text (GTK_ENTRY (impl->search_entry));
9320   if (strlen (text) == 0)
9321     return;
9322
9323   /* reset any existing query object */
9324   if (impl->search_query)
9325     {
9326       g_object_unref (impl->search_query);
9327       impl->search_query = NULL;
9328     }
9329
9330   search_start_query (impl, text);
9331 }
9332
9333 static gboolean
9334 focus_entry_idle_cb (GtkFileChooserDefault *impl)
9335 {
9336   GDK_THREADS_ENTER ();
9337   
9338   g_source_destroy (impl->focus_entry_idle);
9339   impl->focus_entry_idle = NULL;
9340
9341   if (impl->search_entry)
9342     gtk_widget_grab_focus (impl->search_entry);
9343
9344   GDK_THREADS_LEAVE ();
9345
9346   return FALSE;
9347 }
9348
9349 static void
9350 focus_search_entry_in_idle (GtkFileChooserDefault *impl)
9351 {
9352   /* bgo#634558 - When the user clicks on the Search entry in the shortcuts
9353    * pane, we get a selection-changed signal and we set up the search widgets.
9354    * However, gtk_tree_view_button_press() focuses the treeview *after* making
9355    * the change to the selection.  So, we need to re-focus the search entry
9356    * after the treeview has finished doing its work; we'll do that in an idle
9357    * handler.
9358    */
9359
9360   if (!impl->focus_entry_idle)
9361     impl->focus_entry_idle = add_idle_while_impl_is_alive (impl, G_CALLBACK (focus_entry_idle_cb));
9362 }
9363
9364 /* Hides the path bar and creates the search entry */
9365 static void
9366 search_setup_widgets (GtkFileChooserDefault *impl)
9367 {
9368   impl->search_hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
9369
9370   path_bar_update (impl);
9371
9372   impl->search_entry = gtk_entry_new ();
9373   g_signal_connect (impl->search_entry, "activate",
9374                     G_CALLBACK (search_entry_activate_cb),
9375                     impl);
9376   gtk_box_pack_start (GTK_BOX (impl->search_hbox), impl->search_entry, TRUE, TRUE, 0);
9377
9378   /* if there already is a query, restart it */
9379   if (impl->search_query)
9380     {
9381       gchar *query = _gtk_query_get_text (impl->search_query);
9382
9383       if (query)
9384         {
9385           gtk_entry_set_text (GTK_ENTRY (impl->search_entry), query);
9386           search_start_query (impl, query);
9387
9388           g_free (query);
9389         }
9390       else
9391         {
9392           g_object_unref (impl->search_query);
9393           impl->search_query = NULL;
9394         }
9395     }
9396
9397   /* Box for search widgets */
9398   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->search_hbox, TRUE, TRUE, 0);
9399   gtk_widget_show_all (impl->search_hbox);
9400   gtk_size_group_add_widget (GTK_SIZE_GROUP (impl->browse_path_bar_size_group), impl->search_hbox);
9401
9402   /* Hide the location widgets temporarily */
9403
9404   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9405       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9406     {
9407       gtk_widget_hide (impl->location_button);
9408       gtk_widget_hide (impl->location_entry_box);
9409     }
9410
9411   focus_search_entry_in_idle (impl);
9412
9413   /* FMQ: hide the filter combo? */
9414 }
9415
9416 /*
9417  * Recent files support
9418  */
9419
9420 /* Frees the data in the recent_model */
9421 static void
9422 recent_clear_model (GtkFileChooserDefault *impl,
9423                     gboolean               remove_from_treeview)
9424 {
9425   if (!impl->recent_model)
9426     return;
9427
9428   if (remove_from_treeview)
9429     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
9430
9431   g_object_unref (impl->recent_model);
9432   impl->recent_model = NULL;
9433 }
9434
9435 /* Stops any ongoing loading of the recent files list; does
9436  * not touch the recent_model
9437  */
9438 static void
9439 recent_stop_loading (GtkFileChooserDefault *impl)
9440 {
9441   if (impl->load_recent_id)
9442     {
9443       g_source_remove (impl->load_recent_id);
9444       impl->load_recent_id = 0;
9445     }
9446 }
9447
9448 static void
9449 recent_setup_model (GtkFileChooserDefault *impl)
9450 {
9451   g_assert (impl->recent_model == NULL);
9452
9453   impl->recent_model = _gtk_file_system_model_new (file_system_model_set,
9454                                                    impl,
9455                                                    MODEL_COLUMN_TYPES);
9456
9457   _gtk_file_system_model_set_filter (impl->recent_model,
9458                                      impl->current_filter);
9459   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model),
9460                                    MODEL_COL_NAME,
9461                                    name_sort_func,
9462                                    impl, NULL);
9463   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model),
9464                                    MODEL_COL_SIZE,
9465                                    size_sort_func,
9466                                    impl, NULL);
9467   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model),
9468                                    MODEL_COL_MTIME,
9469                                    mtime_sort_func,
9470                                    impl, NULL);
9471   set_sort_column (impl);
9472 }
9473
9474 typedef struct
9475 {
9476   GtkFileChooserDefault *impl;
9477   GList *items;
9478 } RecentLoadData;
9479
9480 static void
9481 recent_idle_cleanup (gpointer data)
9482 {
9483   RecentLoadData *load_data = data;
9484   GtkFileChooserDefault *impl = load_data->impl;
9485
9486   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9487                            GTK_TREE_MODEL (impl->recent_model));
9488   file_list_set_sort_column_ids (impl);
9489   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (impl->recent_model), MODEL_COL_MTIME, GTK_SORT_DESCENDING);
9490
9491   set_busy_cursor (impl, FALSE);
9492   
9493   impl->load_recent_id = 0;
9494   
9495   g_free (load_data);
9496 }
9497
9498 static gint
9499 get_recent_files_limit (GtkWidget *widget)
9500 {
9501   GtkSettings *settings;
9502   gint limit;
9503
9504   if (gtk_widget_has_screen (widget))
9505     settings = gtk_settings_get_for_screen (gtk_widget_get_screen (widget));
9506   else
9507     settings = gtk_settings_get_default ();
9508
9509   g_object_get (G_OBJECT (settings), "gtk-recent-files-limit", &limit, NULL);
9510
9511   return limit;
9512 }
9513
9514 /* Populates the file system model with the GtkRecentInfo* items in the provided list; frees the items */
9515 static void
9516 populate_model_with_recent_items (GtkFileChooserDefault *impl, GList *items)
9517 {
9518   gint limit;
9519   GList *l;
9520   int n;
9521
9522   limit = get_recent_files_limit (GTK_WIDGET (impl));
9523
9524   n = 0;
9525
9526   for (l = items; l; l = l->next)
9527     {
9528       GtkRecentInfo *info = l->data;
9529       GFile *file;
9530
9531       file = g_file_new_for_uri (gtk_recent_info_get_uri (info));
9532       _gtk_file_system_model_add_and_query_file (impl->recent_model,
9533                                                  file,
9534                                                  MODEL_ATTRIBUTES);
9535       g_object_unref (file);
9536
9537       n++;
9538       if (limit != -1 && n >= limit)
9539         break;
9540     }
9541 }
9542
9543 static void
9544 populate_model_with_folders (GtkFileChooserDefault *impl, GList *items)
9545 {
9546   GList *folders;
9547   GList *l;
9548
9549   folders = _gtk_file_chooser_extract_recent_folders (items);
9550
9551   for (l = folders; l; l = l->next)
9552     {
9553       GFile *folder = l->data;
9554
9555       _gtk_file_system_model_add_and_query_file (impl->recent_model,
9556                                                  folder,
9557                                                  MODEL_ATTRIBUTES);
9558     }
9559
9560   g_list_foreach (folders, (GFunc) g_object_unref, NULL);
9561   g_list_free (folders);
9562 }
9563
9564 static gboolean
9565 recent_idle_load (gpointer data)
9566 {
9567   RecentLoadData *load_data = data;
9568   GtkFileChooserDefault *impl = load_data->impl;
9569
9570   if (!impl->recent_manager)
9571     return FALSE;
9572
9573   load_data->items = gtk_recent_manager_get_items (impl->recent_manager);
9574   if (!load_data->items)
9575     return FALSE;
9576
9577   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
9578     populate_model_with_recent_items (impl, load_data->items);
9579   else
9580     populate_model_with_folders (impl, load_data->items);
9581
9582   g_list_foreach (load_data->items, (GFunc) gtk_recent_info_unref, NULL);
9583   g_list_free (load_data->items);
9584   load_data->items = NULL;
9585
9586   return FALSE;
9587 }
9588
9589 static void
9590 recent_start_loading (GtkFileChooserDefault *impl)
9591 {
9592   RecentLoadData *load_data;
9593
9594   recent_stop_loading (impl);
9595   recent_clear_model (impl, TRUE);
9596   recent_setup_model (impl);
9597   set_busy_cursor (impl, TRUE);
9598
9599   g_assert (impl->load_recent_id == 0);
9600
9601   load_data = g_new (RecentLoadData, 1);
9602   load_data->impl = impl;
9603   load_data->items = NULL;
9604
9605   /* begin lazy loading the recent files into the model */
9606   impl->load_recent_id = gdk_threads_add_idle_full (G_PRIORITY_HIGH_IDLE + 30,
9607                                                     recent_idle_load,
9608                                                     load_data,
9609                                                     recent_idle_cleanup);
9610 }
9611
9612 static void
9613 recent_selected_foreach_get_file_cb (GtkTreeModel *model,
9614                                      GtkTreePath  *path,
9615                                      GtkTreeIter  *iter,
9616                                      gpointer      data)
9617 {
9618   GSList **list;
9619   GFile *file;
9620
9621   list = data;
9622
9623   gtk_tree_model_get (model, iter, MODEL_COL_FILE, &file, -1);
9624   *list = g_slist_prepend (*list, file);
9625 }
9626
9627 /* Constructs a list of the selected paths in recent files mode */
9628 static GSList *
9629 recent_get_selected_files (GtkFileChooserDefault *impl)
9630 {
9631   GSList *result;
9632   GtkTreeSelection *selection;
9633
9634   result = NULL;
9635
9636   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9637   gtk_tree_selection_selected_foreach (selection, recent_selected_foreach_get_file_cb, &result);
9638   result = g_slist_reverse (result);
9639
9640   return result;
9641 }
9642
9643 /* Called from ::should_respond().  We return whether there are selected
9644  * files in the recent files list.
9645  */
9646 static gboolean
9647 recent_should_respond (GtkFileChooserDefault *impl)
9648 {
9649   GtkTreeSelection *selection;
9650
9651   g_assert (impl->operation_mode == OPERATION_MODE_RECENT);
9652
9653   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9654   return (gtk_tree_selection_count_selected_rows (selection) != 0);
9655 }
9656
9657 static void
9658 set_current_filter (GtkFileChooserDefault *impl,
9659                     GtkFileFilter         *filter)
9660 {
9661   if (impl->current_filter != filter)
9662     {
9663       int filter_index;
9664
9665       /* NULL filters are allowed to reset to non-filtered status
9666        */
9667       filter_index = g_slist_index (impl->filters, filter);
9668       if (impl->filters && filter && filter_index < 0)
9669         return;
9670
9671       if (impl->current_filter)
9672         g_object_unref (impl->current_filter);
9673       impl->current_filter = filter;
9674       if (impl->current_filter)
9675         {
9676           g_object_ref_sink (impl->current_filter);
9677         }
9678
9679       if (impl->filters)
9680         gtk_combo_box_set_active (GTK_COMBO_BOX (impl->filter_combo),
9681                                   filter_index);
9682
9683       if (impl->browse_files_model)
9684         {
9685           _gtk_file_system_model_set_filter (impl->browse_files_model, impl->current_filter);
9686           _gtk_file_system_model_clear_cache (impl->browse_files_model, MODEL_COL_IS_SENSITIVE);
9687         }
9688
9689       if (impl->search_model)
9690         {
9691           _gtk_file_system_model_set_filter (impl->search_model, filter);
9692           _gtk_file_system_model_clear_cache (impl->search_model, MODEL_COL_IS_SENSITIVE);
9693         }
9694
9695       if (impl->recent_model)
9696         {
9697           _gtk_file_system_model_set_filter (impl->recent_model, filter);
9698           _gtk_file_system_model_clear_cache (impl->recent_model, MODEL_COL_IS_SENSITIVE);
9699         }
9700
9701       g_object_notify (G_OBJECT (impl), "filter");
9702     }
9703 }
9704
9705 static void
9706 filter_combo_changed (GtkComboBox           *combo_box,
9707                       GtkFileChooserDefault *impl)
9708 {
9709   gint new_index = gtk_combo_box_get_active (combo_box);
9710   GtkFileFilter *new_filter = g_slist_nth_data (impl->filters, new_index);
9711
9712   set_current_filter (impl, new_filter);
9713 }
9714
9715 static void
9716 check_preview_change (GtkFileChooserDefault *impl)
9717 {
9718   GtkTreePath *cursor_path;
9719   GFile *new_file;
9720   char *new_display_name;
9721   GtkTreeModel *model;
9722
9723   gtk_tree_view_get_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view), &cursor_path, NULL);
9724   model = gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view));
9725   if (cursor_path)
9726     {
9727       GtkTreeIter iter;
9728
9729       gtk_tree_model_get_iter (model, &iter, cursor_path);
9730       gtk_tree_model_get (model, &iter,
9731                           MODEL_COL_FILE, &new_file,
9732                           MODEL_COL_NAME, &new_display_name,
9733                           -1);
9734       
9735       gtk_tree_path_free (cursor_path);
9736     }
9737   else
9738     {
9739       new_file = NULL;
9740       new_display_name = NULL;
9741     }
9742
9743   if (new_file != impl->preview_file &&
9744       !(new_file && impl->preview_file &&
9745         g_file_equal (new_file, impl->preview_file)))
9746     {
9747       if (impl->preview_file)
9748         {
9749           g_object_unref (impl->preview_file);
9750           g_free (impl->preview_display_name);
9751         }
9752
9753       if (new_file)
9754         {
9755           impl->preview_file = new_file;
9756           impl->preview_display_name = new_display_name;
9757         }
9758       else
9759         {
9760           impl->preview_file = NULL;
9761           impl->preview_display_name = NULL;
9762           g_free (new_display_name);
9763         }
9764
9765       if (impl->use_preview_label && impl->preview_label)
9766         gtk_label_set_text (GTK_LABEL (impl->preview_label), impl->preview_display_name);
9767
9768       g_signal_emit_by_name (impl, "update-preview");
9769     }
9770   else
9771     {
9772       if (new_file)
9773         g_object_unref (new_file);
9774
9775       g_free (new_display_name);
9776     }
9777 }
9778
9779 static void
9780 shortcuts_activate_volume_mount_cb (GCancellable        *cancellable,
9781                                     GtkFileSystemVolume *volume,
9782                                     const GError        *error,
9783                                     gpointer             data)
9784 {
9785   GFile *file;
9786   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
9787   GtkFileChooserDefault *impl = data;
9788
9789   if (cancellable != impl->shortcuts_activate_iter_cancellable)
9790     goto out;
9791
9792   impl->shortcuts_activate_iter_cancellable = NULL;
9793
9794   set_busy_cursor (impl, FALSE);
9795
9796   if (cancelled)
9797     goto out;
9798
9799   if (error)
9800     {
9801       if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED))
9802         {
9803           char *msg, *name;
9804
9805           name = _gtk_file_system_volume_get_display_name (volume);
9806           msg = g_strdup_printf (_("Could not mount %s"), name);
9807
9808           error_message (impl, msg, error->message);
9809
9810           g_free (msg);
9811           g_free (name);
9812         }
9813
9814       goto out;
9815     }
9816
9817   file = _gtk_file_system_volume_get_root (volume);
9818   if (file != NULL)
9819     {
9820       change_folder_and_display_error (impl, file, FALSE);
9821       g_object_unref (file);
9822     }
9823
9824 out:
9825   g_object_unref (impl);
9826   g_object_unref (cancellable);
9827 }
9828
9829
9830 /* Activates a volume by mounting it if necessary and then switching to its
9831  * base path.
9832  */
9833 static void
9834 shortcuts_activate_volume (GtkFileChooserDefault *impl,
9835                            GtkFileSystemVolume   *volume)
9836 {
9837   GFile *file;
9838
9839   operation_mode_set (impl, OPERATION_MODE_BROWSE);
9840
9841   /* We ref the file chooser since volume_mount() may run a main loop, and the
9842    * user could close the file chooser window in the meantime.
9843    */
9844   g_object_ref (impl);
9845
9846   if (!_gtk_file_system_volume_is_mounted (volume))
9847     {
9848       GMountOperation *mount_op;
9849
9850       set_busy_cursor (impl, TRUE);
9851    
9852       mount_op = gtk_mount_operation_new (get_toplevel (GTK_WIDGET (impl)));
9853       impl->shortcuts_activate_iter_cancellable =
9854         _gtk_file_system_mount_volume (impl->file_system, volume, mount_op,
9855                                        shortcuts_activate_volume_mount_cb,
9856                                        g_object_ref (impl));
9857       g_object_unref (mount_op);
9858     }
9859   else
9860     {
9861       file = _gtk_file_system_volume_get_root (volume);
9862       if (file != NULL)
9863         {
9864           change_folder_and_display_error (impl, file, FALSE);
9865           g_object_unref (file);
9866         }
9867     }
9868
9869   g_object_unref (impl);
9870 }
9871
9872 /* Opens the folder or volume at the specified iter in the shortcuts model */
9873 struct ShortcutsActivateData
9874 {
9875   GtkFileChooserDefault *impl;
9876   GFile *file;
9877 };
9878
9879 static void
9880 shortcuts_activate_get_info_cb (GCancellable *cancellable,
9881                                 GFileInfo    *info,
9882                                 const GError *error,
9883                                 gpointer      user_data)
9884 {
9885   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
9886   struct ShortcutsActivateData *data = user_data;
9887
9888   if (cancellable != data->impl->shortcuts_activate_iter_cancellable)
9889     goto out;
9890
9891   data->impl->shortcuts_activate_iter_cancellable = NULL;
9892
9893   if (cancelled)
9894     goto out;
9895
9896   if (!error && _gtk_file_info_consider_as_directory (info))
9897     change_folder_and_display_error (data->impl, data->file, FALSE);
9898   else
9899     gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (data->impl),
9900                                           data->file,
9901                                           NULL);
9902
9903 out:
9904   g_object_unref (data->impl);
9905   g_object_unref (data->file);
9906   g_free (data);
9907
9908   g_object_unref (cancellable);
9909 }
9910
9911 static void
9912 shortcuts_activate_mount_enclosing_volume (GCancellable        *cancellable,
9913                                            GtkFileSystemVolume *volume,
9914                                            const GError        *error,
9915                                            gpointer             user_data)
9916 {
9917   struct ShortcutsActivateData *data = user_data;
9918
9919   if (error)
9920     {
9921       error_changing_folder_dialog (data->impl, data->file, g_error_copy (error));
9922
9923       g_object_unref (data->impl);
9924       g_object_unref (data->file);
9925       g_free (data);
9926
9927       return;
9928     }
9929
9930   data->impl->shortcuts_activate_iter_cancellable =
9931     _gtk_file_system_get_info (data->impl->file_system, data->file,
9932                                "standard::type",
9933                                shortcuts_activate_get_info_cb, data);
9934
9935   if (volume)
9936     _gtk_file_system_volume_unref (volume);
9937 }
9938
9939 static void
9940 shortcuts_activate_iter (GtkFileChooserDefault *impl,
9941                          GtkTreeIter           *iter)
9942 {
9943   gpointer col_data;
9944   ShortcutType shortcut_type;
9945
9946   /* In the Save modes, we want to preserve what the uesr typed in the filename
9947    * entry, so that he may choose another folder without erasing his typed name.
9948    */
9949   if (impl->location_entry
9950       && !(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
9951            || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
9952     gtk_entry_set_text (GTK_ENTRY (impl->location_entry), "");
9953
9954   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), iter,
9955                       SHORTCUTS_COL_DATA, &col_data,
9956                       SHORTCUTS_COL_TYPE, &shortcut_type,
9957                       -1);
9958
9959   if (impl->shortcuts_activate_iter_cancellable)
9960     {
9961       g_cancellable_cancel (impl->shortcuts_activate_iter_cancellable);
9962       impl->shortcuts_activate_iter_cancellable = NULL;
9963     }
9964
9965   if (shortcut_type == SHORTCUT_TYPE_SEPARATOR)
9966     return;
9967   else if (shortcut_type == SHORTCUT_TYPE_VOLUME)
9968     {
9969       GtkFileSystemVolume *volume;
9970
9971       volume = col_data;
9972
9973       operation_mode_set (impl, OPERATION_MODE_BROWSE);
9974
9975       shortcuts_activate_volume (impl, volume);
9976     }
9977   else if (shortcut_type == SHORTCUT_TYPE_FILE)
9978     {
9979       struct ShortcutsActivateData *data;
9980       GtkFileSystemVolume *volume;
9981
9982       operation_mode_set (impl, OPERATION_MODE_BROWSE);
9983
9984       volume = _gtk_file_system_get_volume_for_file (impl->file_system, col_data);
9985
9986       data = g_new0 (struct ShortcutsActivateData, 1);
9987       data->impl = g_object_ref (impl);
9988       data->file = g_object_ref (col_data);
9989
9990       if (!volume || !_gtk_file_system_volume_is_mounted (volume))
9991         {
9992           GMountOperation *mount_operation;
9993           GtkWidget *toplevel;
9994
9995           toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
9996
9997           mount_operation = gtk_mount_operation_new (GTK_WINDOW (toplevel));
9998
9999           impl->shortcuts_activate_iter_cancellable =
10000             _gtk_file_system_mount_enclosing_volume (impl->file_system, col_data,
10001                                                      mount_operation,
10002                                                      shortcuts_activate_mount_enclosing_volume,
10003                                                      data);
10004         }
10005       else
10006         {
10007           impl->shortcuts_activate_iter_cancellable =
10008             _gtk_file_system_get_info (impl->file_system, data->file,
10009                                        "standard::type",
10010                                        shortcuts_activate_get_info_cb, data);
10011         }
10012     }
10013   else if (shortcut_type == SHORTCUT_TYPE_SEARCH)
10014     {
10015       operation_mode_set (impl, OPERATION_MODE_SEARCH);
10016     }
10017   else if (shortcut_type == SHORTCUT_TYPE_RECENT)
10018     {
10019       operation_mode_set (impl, OPERATION_MODE_RECENT);
10020     }
10021 }
10022
10023 /* Handler for GtkWidget::key-press-event on the shortcuts list */
10024 static gboolean
10025 shortcuts_key_press_event_cb (GtkWidget             *widget,
10026                               GdkEventKey           *event,
10027                               GtkFileChooserDefault *impl)
10028 {
10029   guint modifiers;
10030
10031   modifiers = gtk_accelerator_get_default_mod_mask ();
10032
10033   if (key_is_left_or_right (event))
10034     {
10035       gtk_widget_grab_focus (impl->browse_files_tree_view);
10036       return TRUE;
10037     }
10038
10039   if ((event->keyval == GDK_KEY_BackSpace
10040       || event->keyval == GDK_KEY_Delete
10041       || event->keyval == GDK_KEY_KP_Delete)
10042       && (event->state & modifiers) == 0)
10043     {
10044       remove_selected_bookmarks (impl);
10045       return TRUE;
10046     }
10047
10048   if ((event->keyval == GDK_KEY_F2)
10049       && (event->state & modifiers) == 0)
10050     {
10051       rename_selected_bookmark (impl);
10052       return TRUE;
10053     }
10054
10055   return FALSE;
10056 }
10057
10058 static gboolean
10059 shortcuts_select_func  (GtkTreeSelection  *selection,
10060                         GtkTreeModel      *model,
10061                         GtkTreePath       *path,
10062                         gboolean           path_currently_selected,
10063                         gpointer           data)
10064 {
10065   GtkFileChooserDefault *impl = data;
10066   GtkTreeIter filter_iter;
10067   ShortcutType shortcut_type;
10068
10069   if (!gtk_tree_model_get_iter (impl->shortcuts_pane_filter_model, &filter_iter, path))
10070     g_assert_not_reached ();
10071
10072   gtk_tree_model_get (impl->shortcuts_pane_filter_model, &filter_iter, SHORTCUTS_COL_TYPE, &shortcut_type, -1);
10073
10074   return shortcut_type != SHORTCUT_TYPE_SEPARATOR;
10075 }
10076
10077 static gboolean
10078 list_select_func  (GtkTreeSelection  *selection,
10079                    GtkTreeModel      *model,
10080                    GtkTreePath       *path,
10081                    gboolean           path_currently_selected,
10082                    gpointer           data)
10083 {
10084   GtkFileChooserDefault *impl = data;
10085
10086   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10087       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10088     {
10089       GtkTreeIter iter;
10090       gboolean is_sensitive;
10091       gboolean is_folder;
10092
10093       if (!gtk_tree_model_get_iter (model, &iter, path))
10094         return FALSE;
10095       gtk_tree_model_get (model, &iter,
10096                           MODEL_COL_IS_SENSITIVE, &is_sensitive,
10097                           MODEL_COL_IS_FOLDER, &is_folder,
10098                           -1);
10099       if (!is_sensitive || !is_folder)
10100         return FALSE;
10101     }
10102     
10103   return TRUE;
10104 }
10105
10106 static void
10107 list_selection_changed (GtkTreeSelection      *selection,
10108                         GtkFileChooserDefault *impl)
10109 {
10110   /* See if we are in the new folder editable row for Save mode */
10111   if (impl->operation_mode == OPERATION_MODE_BROWSE &&
10112       impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
10113     {
10114       GFileInfo *info;
10115       gboolean had_selection;
10116
10117       info = get_selected_file_info_from_file_list (impl, &had_selection);
10118       if (!had_selection)
10119         goto out; /* normal processing */
10120
10121       if (!info)
10122         return; /* We are on the editable row for New Folder */
10123     }
10124
10125  out:
10126
10127   if (impl->location_entry)
10128     update_chooser_entry (impl);
10129
10130   path_bar_update (impl);
10131
10132   check_preview_change (impl);
10133   bookmarks_check_add_sensitivity (impl);
10134   check_copy_file_location_sensitivity (impl);
10135
10136   g_signal_emit_by_name (impl, "selection-changed", 0);
10137 }
10138
10139 /* Callback used when a row in the file list is activated */
10140 static void
10141 list_row_activated (GtkTreeView           *tree_view,
10142                     GtkTreePath           *path,
10143                     GtkTreeViewColumn     *column,
10144                     GtkFileChooserDefault *impl)
10145 {
10146   GFile *file;
10147   GtkTreeIter iter;
10148   GtkTreeModel *model;
10149   gboolean is_folder;
10150   gboolean is_sensitive;
10151
10152   model = gtk_tree_view_get_model (tree_view);
10153
10154   if (!gtk_tree_model_get_iter (model, &iter, path))
10155     return;
10156
10157   gtk_tree_model_get (model, &iter,
10158                       MODEL_COL_FILE, &file,
10159                       MODEL_COL_IS_FOLDER, &is_folder,
10160                       MODEL_COL_IS_SENSITIVE, &is_sensitive,
10161                       -1);
10162         
10163   if (is_sensitive && is_folder && file)
10164     {
10165       change_folder_and_display_error (impl, file, FALSE);
10166       goto out;
10167     }
10168
10169   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
10170       impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
10171     g_signal_emit_by_name (impl, "file-activated");
10172
10173  out:
10174
10175   if (file)
10176     g_object_unref (file);
10177 }
10178
10179 static void
10180 path_bar_clicked (GtkPathBar            *path_bar,
10181                   GFile                 *file,
10182                   GFile                 *child_file,
10183                   gboolean               child_is_hidden,
10184                   GtkFileChooserDefault *impl)
10185 {
10186   if (child_file)
10187     pending_select_files_add (impl, child_file);
10188
10189   if (!change_folder_and_display_error (impl, file, FALSE))
10190     return;
10191
10192   /* Say we have "/foo/bar/[.baz]" and the user clicks on "bar".  We should then
10193    * show hidden files so that ".baz" appears in the file list, as it will still
10194    * be shown in the path bar: "/foo/[bar]/.baz"
10195    */
10196   if (child_is_hidden)
10197     g_object_set (impl, "show-hidden", TRUE, NULL);
10198 }
10199
10200 static void
10201 update_cell_renderer_attributes (GtkFileChooserDefault *impl)
10202 {
10203   GtkTreeViewColumn *column;
10204   GtkCellRenderer *renderer;
10205   GList *walk, *list;
10206
10207   /* Keep the following column numbers in sync with create_file_list() */
10208
10209   /* name */
10210   column = gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_files_tree_view), 0);
10211   list = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (column));
10212   for (walk = list; walk; walk = walk->next)
10213     {
10214       renderer = walk->data;
10215       if (GTK_IS_CELL_RENDERER_PIXBUF (renderer))
10216         {
10217           gtk_tree_view_column_set_attributes (column, renderer, 
10218                                                "pixbuf", MODEL_COL_PIXBUF,
10219                                                NULL);
10220         }
10221       else
10222         {
10223           gtk_tree_view_column_set_attributes (column, renderer, 
10224                                                "text", MODEL_COL_NAME,
10225                                                "ellipsize", MODEL_COL_ELLIPSIZE,
10226                                                NULL);
10227         }
10228
10229       gtk_tree_view_column_add_attribute (column, renderer, "sensitive", MODEL_COL_IS_SENSITIVE);
10230     }
10231   g_list_free (list);
10232
10233   /* size */
10234   column = gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_files_tree_view), 1);
10235   list = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (column));
10236   renderer = list->data;
10237   gtk_tree_view_column_set_attributes (column, renderer, 
10238                                        "text", MODEL_COL_SIZE_TEXT,
10239                                        NULL);
10240
10241   gtk_tree_view_column_add_attribute (column, renderer, "sensitive", MODEL_COL_IS_SENSITIVE);
10242   g_list_free (list);
10243
10244   /* mtime */
10245   column = gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_files_tree_view), 2);
10246   list = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (column));
10247   renderer = list->data;
10248   gtk_tree_view_column_set_attributes (column, renderer, 
10249                                        "text", MODEL_COL_MTIME_TEXT,
10250                                        NULL);
10251   gtk_tree_view_column_add_attribute (column, renderer, "sensitive", MODEL_COL_IS_SENSITIVE);
10252   g_list_free (list);
10253 }
10254
10255 GtkWidget *
10256 _gtk_file_chooser_default_new (void)
10257 {
10258   return g_object_new (GTK_TYPE_FILE_CHOOSER_DEFAULT, NULL);
10259 }
10260
10261 static void
10262 location_set_user_text (GtkFileChooserDefault *impl,
10263                         const gchar           *path)
10264 {
10265   gtk_entry_set_text (GTK_ENTRY (impl->location_entry), path);
10266   gtk_editable_set_position (GTK_EDITABLE (impl->location_entry), -1);
10267 }
10268
10269 static void
10270 location_popup_handler (GtkFileChooserDefault *impl,
10271                         const gchar           *path)
10272
10273   if (impl->operation_mode != OPERATION_MODE_BROWSE)
10274     {
10275       GtkWidget *widget_to_focus;
10276
10277       operation_mode_set (impl, OPERATION_MODE_BROWSE);
10278       
10279       if (impl->current_folder)
10280         change_folder_and_display_error (impl, impl->current_folder, FALSE);
10281
10282       if (impl->location_mode == LOCATION_MODE_PATH_BAR)
10283         widget_to_focus = impl->browse_files_tree_view;
10284       else
10285         widget_to_focus = impl->location_entry;
10286
10287       gtk_widget_grab_focus (widget_to_focus);
10288       return; 
10289     }
10290   
10291   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
10292       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
10293     {
10294       if (!path)
10295         return;
10296
10297       location_mode_set (impl, LOCATION_MODE_FILENAME_ENTRY, TRUE);
10298       location_set_user_text (impl, path);
10299     }
10300   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
10301            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10302     {
10303       gtk_widget_grab_focus (impl->location_entry);
10304       if (path != NULL)
10305         location_set_user_text (impl, path);
10306     }
10307   else
10308     g_assert_not_reached ();
10309 }
10310
10311 /* Handler for the "up-folder" keybinding signal */
10312 static void
10313 up_folder_handler (GtkFileChooserDefault *impl)
10314 {
10315   _gtk_path_bar_up (GTK_PATH_BAR (impl->browse_path_bar));
10316 }
10317
10318 /* Handler for the "down-folder" keybinding signal */
10319 static void
10320 down_folder_handler (GtkFileChooserDefault *impl)
10321 {
10322   _gtk_path_bar_down (GTK_PATH_BAR (impl->browse_path_bar));
10323 }
10324
10325 /* Switches to the shortcut in the specified index */
10326 static void
10327 switch_to_shortcut (GtkFileChooserDefault *impl,
10328                     int pos)
10329 {
10330   GtkTreeIter iter;
10331
10332   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
10333     g_assert_not_reached ();
10334
10335   shortcuts_activate_iter (impl, &iter);
10336 }
10337
10338 /* Handler for the "home-folder" keybinding signal */
10339 static void
10340 home_folder_handler (GtkFileChooserDefault *impl)
10341 {
10342   if (impl->has_home)
10343     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_HOME));
10344 }
10345
10346 /* Handler for the "desktop-folder" keybinding signal */
10347 static void
10348 desktop_folder_handler (GtkFileChooserDefault *impl)
10349 {
10350   if (impl->has_desktop)
10351     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_DESKTOP));
10352 }
10353
10354 /* Handler for the "search-shortcut" keybinding signal */
10355 static void
10356 search_shortcut_handler (GtkFileChooserDefault *impl)
10357 {
10358   if (impl->has_search)
10359     {
10360       switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_SEARCH));
10361
10362       /* we want the entry widget to grab the focus the first
10363        * time, not the browse_files_tree_view widget.
10364        */
10365       if (impl->search_entry)
10366         gtk_widget_grab_focus (impl->search_entry);
10367     }
10368 }
10369
10370 /* Handler for the "recent-shortcut" keybinding signal */
10371 static void
10372 recent_shortcut_handler (GtkFileChooserDefault *impl)
10373 {
10374   switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_RECENT));
10375 }
10376
10377 static void
10378 quick_bookmark_handler (GtkFileChooserDefault *impl,
10379                         gint bookmark_index)
10380 {
10381   int bookmark_pos;
10382   GtkTreePath *path;
10383
10384   if (bookmark_index < 0 || bookmark_index >= impl->num_bookmarks)
10385     return;
10386
10387   bookmark_pos = shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS) + bookmark_index;
10388
10389   path = gtk_tree_path_new_from_indices (bookmark_pos, -1);
10390   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view),
10391                                 path, NULL,
10392                                 FALSE, 0.0, 0.0);
10393   gtk_tree_path_free (path);
10394
10395   switch_to_shortcut (impl, bookmark_pos);
10396 }
10397
10398 static void
10399 show_hidden_handler (GtkFileChooserDefault *impl)
10400 {
10401   g_object_set (impl,
10402                 "show-hidden", !impl->show_hidden,
10403                 NULL);
10404 }
10405
10406
10407 /* Drag and drop interfaces */
10408
10409 static void
10410 _shortcuts_pane_model_filter_class_init (ShortcutsPaneModelFilterClass *class)
10411 {
10412 }
10413
10414 static void
10415 _shortcuts_pane_model_filter_init (ShortcutsPaneModelFilter *model)
10416 {
10417   model->impl = NULL;
10418 }
10419
10420 /* GtkTreeDragSource::row_draggable implementation for the shortcuts filter model */
10421 static gboolean
10422 shortcuts_pane_model_filter_row_draggable (GtkTreeDragSource *drag_source,
10423                                            GtkTreePath       *path)
10424 {
10425   ShortcutsPaneModelFilter *model;
10426   int pos;
10427   int bookmarks_pos;
10428
10429   model = SHORTCUTS_PANE_MODEL_FILTER (drag_source);
10430
10431   pos = *gtk_tree_path_get_indices (path);
10432   bookmarks_pos = shortcuts_get_index (model->impl, SHORTCUTS_BOOKMARKS);
10433
10434   return (pos >= bookmarks_pos && pos < bookmarks_pos + model->impl->num_bookmarks);
10435 }
10436
10437 /* GtkTreeDragSource::drag_data_get implementation for the shortcuts
10438  * filter model
10439  */
10440 static gboolean
10441 shortcuts_pane_model_filter_drag_data_get (GtkTreeDragSource *drag_source,
10442                                            GtkTreePath       *path,
10443                                            GtkSelectionData  *selection_data)
10444 {
10445   /* FIXME */
10446
10447   return FALSE;
10448 }
10449
10450 /* Fill the GtkTreeDragSourceIface vtable */
10451 static void
10452 shortcuts_pane_model_filter_drag_source_iface_init (GtkTreeDragSourceIface *iface)
10453 {
10454   iface->row_draggable = shortcuts_pane_model_filter_row_draggable;
10455   iface->drag_data_get = shortcuts_pane_model_filter_drag_data_get;
10456 }
10457
10458 #if 0
10459 /* Fill the GtkTreeDragDestIface vtable */
10460 static void
10461 shortcuts_pane_model_filter_drag_dest_iface_init (GtkTreeDragDestIface *iface)
10462 {
10463   iface->drag_data_received = shortcuts_pane_model_filter_drag_data_received;
10464   iface->row_drop_possible = shortcuts_pane_model_filter_row_drop_possible;
10465 }
10466 #endif
10467
10468 static GtkTreeModel *
10469 shortcuts_pane_model_filter_new (GtkFileChooserDefault *impl,
10470                                  GtkTreeModel          *child_model,
10471                                  GtkTreePath           *root)
10472 {
10473   ShortcutsPaneModelFilter *model;
10474
10475   model = g_object_new (SHORTCUTS_PANE_MODEL_FILTER_TYPE,
10476                         "child-model", child_model,
10477                         "virtual-root", root,
10478                         NULL);
10479
10480   model->impl = impl;
10481
10482   return GTK_TREE_MODEL (model);
10483 }
10484