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