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