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