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