]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilechooserdefault.c
Rename stop_operation() to operation_mode_stop()
[~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 /* Stops running operations like populating the browse model, searches, and the recent-files model */
5231 static void
5232 operation_mode_stop (GtkFileChooserDefault *impl, OperationMode mode)
5233 {
5234   switch (mode)
5235     {
5236     case OPERATION_MODE_BROWSE:
5237       stop_loading_and_clear_list_model (impl, TRUE);
5238       break;
5239
5240     case OPERATION_MODE_SEARCH:
5241       search_stop_searching (impl, FALSE);
5242       search_clear_model (impl, TRUE);
5243
5244       gtk_widget_destroy (impl->search_hbox);
5245       impl->search_hbox = NULL;
5246       impl->search_entry = NULL;
5247       break;
5248
5249     case OPERATION_MODE_RECENT:
5250       recent_stop_loading (impl);
5251       recent_clear_model (impl, TRUE);
5252       break;
5253
5254     default:
5255       g_assert_not_reached ();
5256     }
5257 }
5258
5259 /* This function is basically a do_all function.
5260  *
5261  * It sets the visibility on all the widgets based on the current state, and
5262  * moves the custom_widget if needed.
5263  */
5264 static void
5265 update_appearance (GtkFileChooserDefault *impl)
5266 {
5267   save_path_bar (impl);
5268
5269   if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5270       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5271     {
5272       const char *text;
5273
5274       gtk_widget_hide (impl->location_button);
5275       save_widgets_create (impl);
5276
5277       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
5278         text = _("Save in _folder:");
5279       else
5280         text = _("Create in _folder:");
5281
5282       gtk_label_set_text_with_mnemonic (GTK_LABEL (impl->save_folder_label), text);
5283
5284       if (impl->select_multiple)
5285         {
5286           g_warning ("Save mode cannot be set in conjunction with multiple selection mode.  "
5287                      "Re-setting to single selection mode.");
5288           set_select_multiple (impl, FALSE, TRUE);
5289         }
5290     }
5291   else if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
5292            impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
5293     {
5294       gtk_widget_show (impl->location_button);
5295       save_widgets_destroy (impl);
5296       gtk_widget_show (impl->browse_widgets_box);
5297       location_mode_set (impl, impl->location_mode, TRUE);
5298     }
5299
5300   if (impl->location_entry)
5301     _gtk_file_chooser_entry_set_action (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->action);
5302
5303   restore_path_bar (impl);
5304   path_bar_update (impl);
5305
5306   /* This *is* needed; we need to redraw the file list because the "sensitivity"
5307    * of files may change depending whether we are in a file or folder-only mode.
5308    */
5309   gtk_widget_queue_draw (impl->browse_files_tree_view);
5310
5311   emit_default_size_changed (impl);
5312 }
5313
5314 static void
5315 gtk_file_chooser_default_set_property (GObject      *object,
5316                                        guint         prop_id,
5317                                        const GValue *value,
5318                                        GParamSpec   *pspec)
5319
5320 {
5321   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (object);
5322
5323   switch (prop_id)
5324     {
5325     case GTK_FILE_CHOOSER_PROP_ACTION:
5326       {
5327         GtkFileChooserAction action = g_value_get_enum (value);
5328
5329         if (action != impl->action)
5330           {
5331             gtk_file_chooser_default_unselect_all (GTK_FILE_CHOOSER (impl));
5332             
5333             if ((action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5334                  action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5335                 && impl->select_multiple)
5336               {
5337                 g_warning ("Tried to change the file chooser action to SAVE or CREATE_FOLDER, but "
5338                            "this is not allowed in multiple selection mode.  Resetting the file chooser "
5339                            "to single selection mode.");
5340                 set_select_multiple (impl, FALSE, TRUE);
5341               }
5342             impl->action = action;
5343             update_cell_renderer_attributes (impl);
5344             update_appearance (impl);
5345             settings_load (impl);
5346           }
5347       }
5348       break;
5349
5350     case GTK_FILE_CHOOSER_PROP_FILTER:
5351       set_current_filter (impl, g_value_get_object (value));
5352       break;
5353
5354     case GTK_FILE_CHOOSER_PROP_LOCAL_ONLY:
5355       set_local_only (impl, g_value_get_boolean (value));
5356       break;
5357
5358     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET:
5359       set_preview_widget (impl, g_value_get_object (value));
5360       break;
5361
5362     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET_ACTIVE:
5363       impl->preview_widget_active = g_value_get_boolean (value);
5364       update_preview_widget_visibility (impl);
5365       break;
5366
5367     case GTK_FILE_CHOOSER_PROP_USE_PREVIEW_LABEL:
5368       impl->use_preview_label = g_value_get_boolean (value);
5369       update_preview_widget_visibility (impl);
5370       break;
5371
5372     case GTK_FILE_CHOOSER_PROP_EXTRA_WIDGET:
5373       set_extra_widget (impl, g_value_get_object (value));
5374       break;
5375
5376     case GTK_FILE_CHOOSER_PROP_SELECT_MULTIPLE:
5377       {
5378         gboolean select_multiple = g_value_get_boolean (value);
5379         if ((impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
5380              impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
5381             && select_multiple)
5382           {
5383             g_warning ("Tried to set the file chooser to multiple selection mode, but this is "
5384                        "not allowed in SAVE or CREATE_FOLDER modes.  Ignoring the change and "
5385                        "leaving the file chooser in single selection mode.");
5386             return;
5387           }
5388
5389         set_select_multiple (impl, select_multiple, FALSE);
5390       }
5391       break;
5392
5393     case GTK_FILE_CHOOSER_PROP_SHOW_HIDDEN:
5394       {
5395         gboolean show_hidden = g_value_get_boolean (value);
5396         if (show_hidden != impl->show_hidden)
5397           {
5398             impl->show_hidden = show_hidden;
5399
5400             if (impl->browse_files_model)
5401               _gtk_file_system_model_set_show_hidden (impl->browse_files_model, show_hidden);
5402           }
5403       }
5404       break;
5405
5406     case GTK_FILE_CHOOSER_PROP_DO_OVERWRITE_CONFIRMATION:
5407       {
5408         gboolean do_overwrite_confirmation = g_value_get_boolean (value);
5409         impl->do_overwrite_confirmation = do_overwrite_confirmation;
5410       }
5411       break;
5412
5413     case GTK_FILE_CHOOSER_PROP_CREATE_FOLDERS:
5414       {
5415         gboolean create_folders = g_value_get_boolean (value);
5416         impl->create_folders = create_folders;
5417         update_appearance (impl);
5418       }
5419       break;
5420
5421     default:
5422       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5423       break;
5424     }
5425 }
5426
5427 static void
5428 gtk_file_chooser_default_get_property (GObject    *object,
5429                                        guint       prop_id,
5430                                        GValue     *value,
5431                                        GParamSpec *pspec)
5432 {
5433   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (object);
5434
5435   switch (prop_id)
5436     {
5437     case GTK_FILE_CHOOSER_PROP_ACTION:
5438       g_value_set_enum (value, impl->action);
5439       break;
5440
5441     case GTK_FILE_CHOOSER_PROP_FILTER:
5442       g_value_set_object (value, impl->current_filter);
5443       break;
5444
5445     case GTK_FILE_CHOOSER_PROP_LOCAL_ONLY:
5446       g_value_set_boolean (value, impl->local_only);
5447       break;
5448
5449     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET:
5450       g_value_set_object (value, impl->preview_widget);
5451       break;
5452
5453     case GTK_FILE_CHOOSER_PROP_PREVIEW_WIDGET_ACTIVE:
5454       g_value_set_boolean (value, impl->preview_widget_active);
5455       break;
5456
5457     case GTK_FILE_CHOOSER_PROP_USE_PREVIEW_LABEL:
5458       g_value_set_boolean (value, impl->use_preview_label);
5459       break;
5460
5461     case GTK_FILE_CHOOSER_PROP_EXTRA_WIDGET:
5462       g_value_set_object (value, impl->extra_widget);
5463       break;
5464
5465     case GTK_FILE_CHOOSER_PROP_SELECT_MULTIPLE:
5466       g_value_set_boolean (value, impl->select_multiple);
5467       break;
5468
5469     case GTK_FILE_CHOOSER_PROP_SHOW_HIDDEN:
5470       g_value_set_boolean (value, impl->show_hidden);
5471       break;
5472
5473     case GTK_FILE_CHOOSER_PROP_DO_OVERWRITE_CONFIRMATION:
5474       g_value_set_boolean (value, impl->do_overwrite_confirmation);
5475       break;
5476
5477     case GTK_FILE_CHOOSER_PROP_CREATE_FOLDERS:
5478       g_value_set_boolean (value, impl->create_folders);
5479       break;
5480
5481     default:
5482       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5483       break;
5484     }
5485 }
5486
5487 /* This cancels everything that may be going on in the background. */
5488 static void
5489 cancel_all_operations (GtkFileChooserDefault *impl)
5490 {
5491   GSList *l;
5492
5493   pending_select_files_free (impl);
5494
5495   /* cancel all pending operations */
5496   if (impl->pending_cancellables)
5497     {
5498       for (l = impl->pending_cancellables; l; l = l->next)
5499         {
5500           GCancellable *cancellable = G_CANCELLABLE (l->data);
5501           g_cancellable_cancel (cancellable);
5502         }
5503       g_slist_free (impl->pending_cancellables);
5504       impl->pending_cancellables = NULL;
5505     }
5506
5507   if (impl->reload_icon_cancellables)
5508     {
5509       for (l = impl->reload_icon_cancellables; l; l = l->next)
5510         {
5511           GCancellable *cancellable = G_CANCELLABLE (l->data);
5512           g_cancellable_cancel (cancellable);
5513         }
5514       g_slist_free (impl->reload_icon_cancellables);
5515       impl->reload_icon_cancellables = NULL;
5516     }
5517
5518   if (impl->loading_shortcuts)
5519     {
5520       for (l = impl->loading_shortcuts; l; l = l->next)
5521         {
5522           GCancellable *cancellable = G_CANCELLABLE (l->data);
5523           g_cancellable_cancel (cancellable);
5524         }
5525       g_slist_free (impl->loading_shortcuts);
5526       impl->loading_shortcuts = NULL;
5527     }
5528
5529   if (impl->file_list_drag_data_received_cancellable)
5530     {
5531       g_cancellable_cancel (impl->file_list_drag_data_received_cancellable);
5532       impl->file_list_drag_data_received_cancellable = NULL;
5533     }
5534
5535   if (impl->update_current_folder_cancellable)
5536     {
5537       g_cancellable_cancel (impl->update_current_folder_cancellable);
5538       impl->update_current_folder_cancellable = NULL;
5539     }
5540
5541   if (impl->should_respond_get_info_cancellable)
5542     {
5543       g_cancellable_cancel (impl->should_respond_get_info_cancellable);
5544       impl->should_respond_get_info_cancellable = NULL;
5545     }
5546
5547   if (impl->update_from_entry_cancellable)
5548     {
5549       g_cancellable_cancel (impl->update_from_entry_cancellable);
5550       impl->update_from_entry_cancellable = NULL;
5551     }
5552
5553   if (impl->shortcuts_activate_iter_cancellable)
5554     {
5555       g_cancellable_cancel (impl->shortcuts_activate_iter_cancellable);
5556       impl->shortcuts_activate_iter_cancellable = NULL;
5557     }
5558
5559   search_stop_searching (impl, TRUE);
5560   recent_stop_loading (impl);
5561 }
5562
5563 /* Removes the settings signal handler.  It's safe to call multiple times */
5564 static void
5565 remove_settings_signal (GtkFileChooserDefault *impl,
5566                         GdkScreen             *screen)
5567 {
5568   if (impl->settings_signal_id)
5569     {
5570       GtkSettings *settings;
5571
5572       settings = gtk_settings_get_for_screen (screen);
5573       g_signal_handler_disconnect (settings,
5574                                    impl->settings_signal_id);
5575       impl->settings_signal_id = 0;
5576     }
5577 }
5578
5579 static void
5580 gtk_file_chooser_default_dispose (GObject *object)
5581 {
5582   GtkFileChooserDefault *impl = (GtkFileChooserDefault *) object;
5583
5584   cancel_all_operations (impl);
5585
5586   if (impl->extra_widget)
5587     {
5588       g_object_unref (impl->extra_widget);
5589       impl->extra_widget = NULL;
5590     }
5591
5592   remove_settings_signal (impl, gtk_widget_get_screen (GTK_WIDGET (impl)));
5593
5594   G_OBJECT_CLASS (_gtk_file_chooser_default_parent_class)->dispose (object);
5595 }
5596
5597 /* We override show-all since we have internal widgets that
5598  * shouldn't be shown when you call show_all(), like the filter
5599  * combo box.
5600  */
5601 static void
5602 gtk_file_chooser_default_show_all (GtkWidget *widget)
5603 {
5604   GtkFileChooserDefault *impl = (GtkFileChooserDefault *) widget;
5605
5606   gtk_widget_show (widget);
5607
5608   if (impl->extra_widget)
5609     gtk_widget_show_all (impl->extra_widget);
5610 }
5611
5612 /* Handler for GtkWindow::set-focus; this is where we save the last-focused
5613  * widget on our toplevel.  See gtk_file_chooser_default_hierarchy_changed()
5614  */
5615 static void
5616 toplevel_set_focus_cb (GtkWindow             *window,
5617                        GtkWidget             *focus,
5618                        GtkFileChooserDefault *impl)
5619 {
5620   impl->toplevel_last_focus_widget = gtk_window_get_focus (window);
5621 }
5622
5623 /* We monitor the focus widget on our toplevel to be able to know which widget
5624  * was last focused at the time our "should_respond" method gets called.
5625  */
5626 static void
5627 gtk_file_chooser_default_hierarchy_changed (GtkWidget *widget,
5628                                             GtkWidget *previous_toplevel)
5629 {
5630   GtkFileChooserDefault *impl;
5631   GtkWidget *toplevel;
5632
5633   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5634   toplevel = gtk_widget_get_toplevel (widget);
5635
5636   if (previous_toplevel && 
5637       impl->toplevel_set_focus_id != 0)
5638     {
5639       g_signal_handler_disconnect (previous_toplevel,
5640                                    impl->toplevel_set_focus_id);
5641       impl->toplevel_set_focus_id = 0;
5642       impl->toplevel_last_focus_widget = NULL;
5643     }
5644
5645   if (gtk_widget_is_toplevel (toplevel))
5646     {
5647       g_assert (impl->toplevel_set_focus_id == 0);
5648       impl->toplevel_set_focus_id = g_signal_connect (toplevel, "set-focus",
5649                                                       G_CALLBACK (toplevel_set_focus_cb), impl);
5650       impl->toplevel_last_focus_widget = gtk_window_get_focus (GTK_WINDOW (toplevel));
5651     }
5652 }
5653
5654 /* Changes the icons wherever it is needed */
5655 static void
5656 change_icon_theme (GtkFileChooserDefault *impl)
5657 {
5658   GtkSettings *settings;
5659   gint width, height;
5660   GtkCellRenderer *renderer;
5661   GList *cells;
5662
5663   profile_start ("start", NULL);
5664
5665   settings = gtk_settings_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
5666
5667   if (gtk_icon_size_lookup_for_settings (settings, GTK_ICON_SIZE_MENU, &width, &height))
5668     impl->icon_size = MAX (width, height);
5669   else
5670     impl->icon_size = FALLBACK_ICON_SIZE;
5671
5672   shortcuts_reload_icons (impl);
5673   /* the first cell in the first column is the icon column, and we have a fixed size there */
5674   cells = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (
5675         gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_files_tree_view), 0)));
5676   renderer = GTK_CELL_RENDERER (cells->data);
5677   set_icon_cell_renderer_fixed_size (impl, renderer);
5678   g_list_free (cells);
5679   if (impl->browse_files_model)
5680     _gtk_file_system_model_clear_cache (impl->browse_files_model, MODEL_COL_PIXBUF);
5681   gtk_widget_queue_resize (impl->browse_files_tree_view);
5682
5683   profile_end ("end", NULL);
5684 }
5685
5686 /* Callback used when a GtkSettings value changes */
5687 static void
5688 settings_notify_cb (GObject               *object,
5689                     GParamSpec            *pspec,
5690                     GtkFileChooserDefault *impl)
5691 {
5692   const char *name;
5693
5694   profile_start ("start", NULL);
5695
5696   name = g_param_spec_get_name (pspec);
5697
5698   if (strcmp (name, "gtk-icon-theme-name") == 0 ||
5699       strcmp (name, "gtk-icon-sizes") == 0)
5700     change_icon_theme (impl);
5701
5702   profile_end ("end", NULL);
5703 }
5704
5705 /* Installs a signal handler for GtkSettings so that we can monitor changes in
5706  * the icon theme.
5707  */
5708 static void
5709 check_icon_theme (GtkFileChooserDefault *impl)
5710 {
5711   GtkSettings *settings;
5712
5713   profile_start ("start", NULL);
5714
5715   if (impl->settings_signal_id)
5716     {
5717       profile_end ("end", NULL);
5718       return;
5719     }
5720
5721   if (gtk_widget_has_screen (GTK_WIDGET (impl)))
5722     {
5723       settings = gtk_settings_get_for_screen (gtk_widget_get_screen (GTK_WIDGET (impl)));
5724       impl->settings_signal_id = g_signal_connect (settings, "notify",
5725                                                    G_CALLBACK (settings_notify_cb), impl);
5726
5727       change_icon_theme (impl);
5728     }
5729
5730   profile_end ("end", NULL);
5731 }
5732
5733 static void
5734 gtk_file_chooser_default_style_updated (GtkWidget *widget)
5735 {
5736   GtkFileChooserDefault *impl;
5737
5738   profile_start ("start", NULL);
5739
5740   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5741
5742   profile_msg ("    parent class style_udpated start", NULL);
5743   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->style_updated (widget);
5744   profile_msg ("    parent class style_updated end", NULL);
5745
5746   if (gtk_widget_has_screen (GTK_WIDGET (impl)))
5747     change_icon_theme (impl);
5748
5749   emit_default_size_changed (impl);
5750
5751   profile_end ("end", NULL);
5752 }
5753
5754 static void
5755 gtk_file_chooser_default_screen_changed (GtkWidget *widget,
5756                                          GdkScreen *previous_screen)
5757 {
5758   GtkFileChooserDefault *impl;
5759
5760   profile_start ("start", NULL);
5761
5762   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5763
5764   if (GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->screen_changed)
5765     GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->screen_changed (widget, previous_screen);
5766
5767   remove_settings_signal (impl, previous_screen);
5768   check_icon_theme (impl);
5769
5770   emit_default_size_changed (impl);
5771
5772   profile_end ("end", NULL);
5773 }
5774
5775 static void
5776 gtk_file_chooser_default_size_allocate (GtkWidget     *widget,
5777                                         GtkAllocation *allocation)
5778 {
5779   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->size_allocate (widget, allocation);
5780 }
5781
5782 static void
5783 set_sort_column (GtkFileChooserDefault *impl)
5784 {
5785   GtkTreeSortable *sortable;
5786
5787   sortable = GTK_TREE_SORTABLE (gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view)));
5788
5789   /* can happen when we're still populating the model */
5790   if (sortable == NULL)
5791     return;
5792
5793   gtk_tree_sortable_set_sort_column_id (sortable,
5794                                         impl->sort_column,
5795                                         impl->sort_order);
5796 }
5797
5798 static void
5799 settings_ensure (GtkFileChooserDefault *impl)
5800 {
5801   if (impl->settings != NULL)
5802     return;
5803
5804   impl->settings = g_settings_new_with_path ("org.gtk.Settings.FileChooser",
5805                                              "/org/gtk/settings/file-chooser/");
5806   g_settings_delay (impl->settings);
5807 }
5808
5809 static void
5810 settings_load (GtkFileChooserDefault *impl)
5811 {
5812   LocationMode location_mode;
5813   gboolean show_hidden;
5814   gboolean show_size_column;
5815   gint sort_column;
5816   GtkSortType sort_order;
5817
5818   settings_ensure (impl);
5819
5820   location_mode = g_settings_get_enum (impl->settings, SETTINGS_KEY_LOCATION_MODE);
5821   show_hidden = g_settings_get_boolean (impl->settings, SETTINGS_KEY_SHOW_HIDDEN);
5822   show_size_column = g_settings_get_boolean (impl->settings, SETTINGS_KEY_SHOW_SIZE_COLUMN);
5823   sort_column = g_settings_get_enum (impl->settings, SETTINGS_KEY_SORT_COLUMN);
5824   sort_order = g_settings_get_enum (impl->settings, SETTINGS_KEY_SORT_ORDER);
5825
5826   location_mode_set (impl, location_mode, TRUE);
5827
5828   gtk_file_chooser_set_show_hidden (GTK_FILE_CHOOSER (impl), show_hidden);
5829
5830   impl->show_size_column = show_size_column;
5831   gtk_tree_view_column_set_visible (impl->list_size_column, show_size_column);
5832
5833   impl->sort_column = sort_column;
5834   impl->sort_order = sort_order;
5835   /* We don't call set_sort_column() here as the models may not have been
5836    * created yet.  The individual functions that create and set the models will
5837    * call set_sort_column() themselves.
5838    */
5839 }
5840
5841 static void
5842 save_dialog_geometry (GtkFileChooserDefault *impl)
5843 {
5844   GtkWindow *toplevel;
5845   int x, y, width, height;
5846
5847   toplevel = get_toplevel (GTK_WIDGET (impl));
5848
5849   if (!(toplevel && GTK_IS_FILE_CHOOSER_DIALOG (toplevel)))
5850     return;
5851
5852   gtk_window_get_position (toplevel, &x, &y);
5853   gtk_window_get_size (toplevel, &width, &height);
5854
5855   g_settings_set (impl->settings, "window-position", "(ii)", x, y);
5856   g_settings_set (impl->settings, "window-size", "(ii)", width, height);
5857 }
5858
5859 static void
5860 settings_save (GtkFileChooserDefault *impl)
5861 {
5862   char *current_folder_uri;
5863
5864   settings_ensure (impl);
5865
5866   /* Current folder */
5867
5868   if (impl->current_folder)
5869     current_folder_uri = g_file_get_uri (impl->current_folder);
5870   else
5871     current_folder_uri = "";
5872
5873   g_settings_set_string (impl->settings, SETTINGS_KEY_LAST_FOLDER_URI, current_folder_uri);
5874
5875   if (impl->current_folder)
5876     g_free (current_folder_uri);
5877
5878   /* All the other state */
5879
5880   g_settings_set_enum (impl->settings, SETTINGS_KEY_LOCATION_MODE, impl->location_mode);
5881   g_settings_set_boolean (impl->settings, SETTINGS_KEY_SHOW_HIDDEN,
5882                           gtk_file_chooser_get_show_hidden (GTK_FILE_CHOOSER (impl)));
5883   g_settings_set_boolean (impl->settings, SETTINGS_KEY_SHOW_SIZE_COLUMN, impl->show_size_column);
5884   g_settings_set_enum (impl->settings, SETTINGS_KEY_SORT_COLUMN, impl->sort_column);
5885   g_settings_set_enum (impl->settings, SETTINGS_KEY_SORT_ORDER, impl->sort_order);
5886
5887   save_dialog_geometry (impl);
5888
5889   /* Now apply the settings */
5890   g_settings_apply (impl->settings);
5891
5892   g_object_unref (impl->settings);
5893   impl->settings = NULL;
5894 }
5895
5896 /* GtkWidget::realize method */
5897 static void
5898 gtk_file_chooser_default_realize (GtkWidget *widget)
5899 {
5900   GtkFileChooserDefault *impl;
5901
5902   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5903
5904   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->realize (widget);
5905
5906   emit_default_size_changed (impl);
5907 }
5908
5909 static GFile *
5910 get_file_for_last_folder_opened (GtkFileChooserDefault *impl)
5911 {
5912   char *last_folder_uri;
5913   GFile *file;
5914
5915   settings_ensure (impl);
5916
5917   last_folder_uri = g_settings_get_string (impl->settings, SETTINGS_KEY_LAST_FOLDER_URI);
5918
5919   /* If no last folder is set, we use the user's home directory, since
5920    * this is the starting point for most documents.
5921    */
5922   if (last_folder_uri[0] == '\0')
5923     file = g_file_new_for_path (g_get_home_dir ());
5924   else
5925     file = g_file_new_for_uri (last_folder_uri);
5926
5927   g_free (last_folder_uri);
5928
5929   return file;
5930 }
5931
5932 /* GtkWidget::map method */
5933 static void
5934 gtk_file_chooser_default_map (GtkWidget *widget)
5935 {
5936   GtkFileChooserDefault *impl;
5937
5938   profile_start ("start", NULL);
5939
5940   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5941
5942   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->map (widget);
5943
5944   if (impl->operation_mode == OPERATION_MODE_BROWSE)
5945     {
5946       switch (impl->reload_state)
5947         {
5948         case RELOAD_EMPTY:
5949           recent_shortcut_handler (impl);
5950           break;
5951         
5952         case RELOAD_HAS_FOLDER:
5953           /* Nothing; we are already loading or loaded, so we
5954            * don't need to reload
5955            */
5956           break;
5957
5958         default:
5959           g_assert_not_reached ();
5960       }
5961     }
5962
5963   volumes_bookmarks_changed_cb (impl->file_system, impl);
5964
5965   settings_load (impl);
5966
5967   profile_end ("end", NULL);
5968 }
5969
5970 /* GtkWidget::unmap method */
5971 static void
5972 gtk_file_chooser_default_unmap (GtkWidget *widget)
5973 {
5974   GtkFileChooserDefault *impl;
5975
5976   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
5977
5978   settings_save (impl);
5979
5980   cancel_all_operations (impl);
5981   impl->reload_state = RELOAD_EMPTY;
5982
5983   GTK_WIDGET_CLASS (_gtk_file_chooser_default_parent_class)->unmap (widget);
5984 }
5985
5986 static void
5987 install_list_model_filter (GtkFileChooserDefault *impl)
5988 {
5989   _gtk_file_system_model_set_filter (impl->browse_files_model,
5990                                      impl->current_filter);
5991 }
5992
5993 #define COMPARE_DIRECTORIES                                                                                    \
5994   GtkFileChooserDefault *impl = user_data;                                                                     \
5995   GtkFileSystemModel *fs_model = GTK_FILE_SYSTEM_MODEL (model);                                                \
5996   gboolean dir_a, dir_b;                                                                                       \
5997                                                                                                                \
5998   dir_a = g_value_get_boolean (_gtk_file_system_model_get_value (fs_model, a, MODEL_COL_IS_FOLDER));           \
5999   dir_b = g_value_get_boolean (_gtk_file_system_model_get_value (fs_model, b, MODEL_COL_IS_FOLDER));           \
6000                                                                                                                \
6001   if (dir_a != dir_b)                                                                                          \
6002     return impl->list_sort_ascending ? (dir_a ? -1 : 1) : (dir_a ? 1 : -1) /* Directories *always* go first */
6003
6004 /* Sort callback for the filename column */
6005 static gint
6006 name_sort_func (GtkTreeModel *model,
6007                 GtkTreeIter  *a,
6008                 GtkTreeIter  *b,
6009                 gpointer      user_data)
6010 {
6011   COMPARE_DIRECTORIES;
6012   else
6013     {
6014       const char *key_a, *key_b;
6015       gint result;
6016
6017       key_a = g_value_get_string (_gtk_file_system_model_get_value (fs_model, a, MODEL_COL_NAME_COLLATED));
6018       key_b = g_value_get_string (_gtk_file_system_model_get_value (fs_model, b, MODEL_COL_NAME_COLLATED));
6019
6020       if (key_a && key_b)
6021         result = strcmp (key_a, key_b);
6022       else if (key_a)
6023         result = 1;
6024       else if (key_b)
6025         result = -1;
6026       else
6027         result = 0;
6028
6029       return result;
6030     }
6031 }
6032
6033 /* Sort callback for the size column */
6034 static gint
6035 size_sort_func (GtkTreeModel *model,
6036                 GtkTreeIter  *a,
6037                 GtkTreeIter  *b,
6038                 gpointer      user_data)
6039 {
6040   COMPARE_DIRECTORIES;
6041   else
6042     {
6043       gint64 size_a, size_b;
6044
6045       size_a = g_value_get_int64 (_gtk_file_system_model_get_value (fs_model, a, MODEL_COL_SIZE));
6046       size_b = g_value_get_int64 (_gtk_file_system_model_get_value (fs_model, b, MODEL_COL_SIZE));
6047
6048       return size_a < size_b ? -1 : (size_a == size_b ? 0 : 1);
6049     }
6050 }
6051
6052 /* Sort callback for the mtime column */
6053 static gint
6054 mtime_sort_func (GtkTreeModel *model,
6055                  GtkTreeIter  *a,
6056                  GtkTreeIter  *b,
6057                  gpointer      user_data)
6058 {
6059   COMPARE_DIRECTORIES;
6060   else
6061     {
6062       glong ta, tb;
6063
6064       ta = g_value_get_long (_gtk_file_system_model_get_value (fs_model, a, MODEL_COL_MTIME));
6065       tb = g_value_get_long (_gtk_file_system_model_get_value (fs_model, b, MODEL_COL_MTIME));
6066
6067       return ta < tb ? -1 : (ta == tb ? 0 : 1);
6068     }
6069 }
6070
6071 /* Callback used when the sort column changes.  We cache the sort order for use
6072  * in name_sort_func().
6073  */
6074 static void
6075 list_sort_column_changed_cb (GtkTreeSortable       *sortable,
6076                              GtkFileChooserDefault *impl)
6077 {
6078   gint sort_column_id;
6079   GtkSortType sort_type;
6080
6081   if (gtk_tree_sortable_get_sort_column_id (sortable, &sort_column_id, &sort_type))
6082     {
6083       impl->list_sort_ascending = (sort_type == GTK_SORT_ASCENDING);
6084       impl->sort_column = sort_column_id;
6085       impl->sort_order = sort_type;
6086     }
6087 }
6088
6089 static void
6090 set_busy_cursor (GtkFileChooserDefault *impl,
6091                  gboolean               busy)
6092 {
6093   GtkWidget *widget;
6094   GtkWindow *toplevel;
6095   GdkDisplay *display;
6096   GdkCursor *cursor;
6097
6098   toplevel = get_toplevel (GTK_WIDGET (impl));
6099   widget = GTK_WIDGET (toplevel);
6100   if (!toplevel || !gtk_widget_get_realized (widget))
6101     return;
6102
6103   display = gtk_widget_get_display (widget);
6104
6105   if (busy)
6106     cursor = gdk_cursor_new_for_display (display, GDK_WATCH);
6107   else
6108     cursor = NULL;
6109
6110   gdk_window_set_cursor (gtk_widget_get_window (widget), cursor);
6111   gdk_display_flush (display);
6112
6113   if (cursor)
6114     g_object_unref (cursor);
6115 }
6116
6117 /* Creates a sort model to wrap the file system model and sets it on the tree view */
6118 static void
6119 load_set_model (GtkFileChooserDefault *impl)
6120 {
6121   profile_start ("start", NULL);
6122
6123   g_assert (impl->browse_files_model != NULL);
6124
6125   profile_msg ("    gtk_tree_view_set_model start", NULL);
6126   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
6127                            GTK_TREE_MODEL (impl->browse_files_model));
6128   gtk_tree_view_columns_autosize (GTK_TREE_VIEW (impl->browse_files_tree_view));
6129   gtk_tree_view_set_search_column (GTK_TREE_VIEW (impl->browse_files_tree_view),
6130                                    MODEL_COL_NAME);
6131   set_sort_column (impl);
6132   profile_msg ("    gtk_tree_view_set_model end", NULL);
6133   impl->list_sort_ascending = TRUE;
6134
6135   profile_end ("end", NULL);
6136 }
6137
6138 /* Timeout callback used when the loading timer expires */
6139 static gboolean
6140 load_timeout_cb (gpointer data)
6141 {
6142   GtkFileChooserDefault *impl;
6143
6144   profile_start ("start", NULL);
6145
6146   impl = GTK_FILE_CHOOSER_DEFAULT (data);
6147   g_assert (impl->load_state == LOAD_PRELOAD);
6148   g_assert (impl->load_timeout_id != 0);
6149   g_assert (impl->browse_files_model != NULL);
6150
6151   impl->load_timeout_id = 0;
6152   impl->load_state = LOAD_LOADING;
6153
6154   load_set_model (impl);
6155
6156   profile_end ("end", NULL);
6157
6158   return FALSE;
6159 }
6160
6161 /* Sets up a new load timer for the model and switches to the LOAD_PRELOAD state */
6162 static void
6163 load_setup_timer (GtkFileChooserDefault *impl)
6164 {
6165   g_assert (impl->load_timeout_id == 0);
6166   g_assert (impl->load_state != LOAD_PRELOAD);
6167
6168   impl->load_timeout_id = gdk_threads_add_timeout (MAX_LOADING_TIME, load_timeout_cb, impl);
6169   impl->load_state = LOAD_PRELOAD;
6170 }
6171
6172 /* Removes the load timeout and switches to the LOAD_FINISHED state */
6173 static void
6174 load_remove_timer (GtkFileChooserDefault *impl)
6175 {
6176   if (impl->load_timeout_id != 0)
6177     {
6178       g_assert (impl->load_state == LOAD_PRELOAD);
6179
6180       g_source_remove (impl->load_timeout_id);
6181       impl->load_timeout_id = 0;
6182       impl->load_state = LOAD_EMPTY;
6183     }
6184   else
6185     g_assert (impl->load_state == LOAD_EMPTY ||
6186               impl->load_state == LOAD_LOADING ||
6187               impl->load_state == LOAD_FINISHED);
6188 }
6189
6190 /* Selects the first row in the file list */
6191 static void
6192 browse_files_select_first_row (GtkFileChooserDefault *impl)
6193 {
6194   GtkTreePath *path;
6195   GtkTreeIter dummy_iter;
6196   GtkTreeModel *tree_model;
6197
6198   tree_model = gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view));
6199
6200   if (!tree_model)
6201     return;
6202
6203   path = gtk_tree_path_new_from_indices (0, -1);
6204
6205   /* If the list is empty, do nothing. */
6206   if (gtk_tree_model_get_iter (tree_model, &dummy_iter, path))
6207       gtk_tree_view_set_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view), path, NULL, FALSE);
6208
6209   gtk_tree_path_free (path);
6210 }
6211
6212 struct center_selected_row_closure {
6213   GtkFileChooserDefault *impl;
6214   gboolean already_centered;
6215 };
6216
6217 /* Callback used from gtk_tree_selection_selected_foreach(); centers the
6218  * selected row in the tree view.
6219  */
6220 static void
6221 center_selected_row_foreach_cb (GtkTreeModel      *model,
6222                                 GtkTreePath       *path,
6223                                 GtkTreeIter       *iter,
6224                                 gpointer           data)
6225 {
6226   struct center_selected_row_closure *closure;
6227
6228   closure = data;
6229   if (closure->already_centered)
6230     return;
6231
6232   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (closure->impl->browse_files_tree_view), path, NULL, TRUE, 0.5, 0.0);
6233   closure->already_centered = TRUE;
6234 }
6235
6236 /* Centers the selected row in the tree view */
6237 static void
6238 browse_files_center_selected_row (GtkFileChooserDefault *impl)
6239 {
6240   struct center_selected_row_closure closure;
6241   GtkTreeSelection *selection;
6242
6243   closure.impl = impl;
6244   closure.already_centered = FALSE;
6245
6246   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6247   gtk_tree_selection_selected_foreach (selection, center_selected_row_foreach_cb, &closure);
6248 }
6249
6250 static gboolean
6251 show_and_select_files (GtkFileChooserDefault *impl,
6252                        GSList                *files)
6253 {
6254   GtkTreeSelection *selection;
6255   GtkFileSystemModel *fsmodel;
6256   gboolean enabled_hidden, removed_filters;
6257   gboolean selected_a_file;
6258   GSList *walk;
6259
6260   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6261   fsmodel = GTK_FILE_SYSTEM_MODEL (gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view)));
6262
6263   enabled_hidden = impl->show_hidden;
6264   removed_filters = (impl->current_filter == NULL);
6265
6266   selected_a_file = FALSE;
6267
6268   for (walk = files; walk; walk = walk->next)
6269     {
6270       GFile *file = walk->data;
6271       GtkTreeIter iter;
6272
6273       /* Is it a hidden file? */
6274
6275       if (!_gtk_file_system_model_get_iter_for_file (fsmodel, &iter, file))
6276         continue;
6277
6278       if (!_gtk_file_system_model_iter_is_visible (fsmodel, &iter))
6279         {
6280           GFileInfo *info = _gtk_file_system_model_get_info (fsmodel, &iter);
6281
6282           if (!enabled_hidden &&
6283               (g_file_info_get_is_hidden (info) ||
6284                g_file_info_get_is_backup (info)))
6285             {
6286               g_object_set (impl, "show-hidden", TRUE, NULL);
6287               enabled_hidden = TRUE;
6288             }
6289         }
6290
6291       /* Is it a filtered file? */
6292
6293       if (!_gtk_file_system_model_get_iter_for_file (fsmodel, &iter, file))
6294         continue; /* re-get the iter as it may change when the model refilters */
6295
6296       if (!_gtk_file_system_model_iter_is_visible (fsmodel, &iter))
6297         {
6298           /* Maybe we should have a way to ask the fsmodel if it had filtered a file */
6299           if (!removed_filters)
6300             {
6301               set_current_filter (impl, NULL);
6302               removed_filters = TRUE;
6303             }
6304         }
6305
6306       /* Okay, can we select the file now? */
6307           
6308       if (!_gtk_file_system_model_get_iter_for_file (fsmodel, &iter, file))
6309         continue;
6310
6311       if (_gtk_file_system_model_iter_is_visible (fsmodel, &iter))
6312         {
6313           GtkTreePath *path;
6314
6315           gtk_tree_selection_select_iter (selection, &iter);
6316
6317           path = gtk_tree_model_get_path (GTK_TREE_MODEL (fsmodel), &iter);
6318           gtk_tree_view_set_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view),
6319                                     path, NULL, FALSE);
6320           gtk_tree_path_free (path);
6321
6322           selected_a_file = TRUE;
6323         }
6324     }
6325
6326   browse_files_center_selected_row (impl);
6327
6328   return selected_a_file;
6329 }
6330
6331 /* Processes the pending operation when a folder is finished loading */
6332 static void
6333 pending_select_files_process (GtkFileChooserDefault *impl)
6334 {
6335   g_assert (impl->load_state == LOAD_FINISHED);
6336   g_assert (impl->browse_files_model != NULL);
6337
6338   if (impl->pending_select_files)
6339     {
6340       show_and_select_files (impl, impl->pending_select_files);
6341       pending_select_files_free (impl);
6342       browse_files_center_selected_row (impl);
6343     }
6344   else
6345     {
6346       /* We only select the first row if the chooser is actually mapped ---
6347        * selecting the first row is to help the user when he is interacting with
6348        * the chooser, but sometimes a chooser works not on behalf of the user,
6349        * but rather on behalf of something else like GtkFileChooserButton.  In
6350        * that case, the chooser's selection should be what the caller expects,
6351        * as the user can't see that something else got selected.  See bug #165264.
6352        */
6353       if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN &&
6354           gtk_widget_get_mapped (GTK_WIDGET (impl)))
6355         browse_files_select_first_row (impl);
6356     }
6357
6358   g_assert (impl->pending_select_files == NULL);
6359 }
6360
6361 static void
6362 show_error_on_reading_current_folder (GtkFileChooserDefault *impl, GError *error)
6363 {
6364   GFileInfo *info;
6365   char *msg;
6366
6367   info = g_file_query_info (impl->current_folder,
6368                             G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
6369                             G_FILE_QUERY_INFO_NONE,
6370                             NULL,
6371                             NULL);
6372   if (info)
6373     {
6374       msg = g_strdup_printf (_("Could not read the contents of %s"), g_file_info_get_display_name (info));
6375       g_object_unref (info);
6376     }
6377   else
6378     msg = g_strdup (_("Could not read the contents of the folder"));
6379
6380   error_message (impl, msg, error->message);
6381   g_free (msg);
6382 }
6383
6384 /* Callback used when the file system model finishes loading */
6385 static void
6386 browse_files_model_finished_loading_cb (GtkFileSystemModel    *model,
6387                                         GError                *error,
6388                                         GtkFileChooserDefault *impl)
6389 {
6390   profile_start ("start", NULL);
6391
6392   if (error)
6393     show_error_on_reading_current_folder (impl, error);
6394
6395   if (impl->load_state == LOAD_PRELOAD)
6396     {
6397       load_remove_timer (impl);
6398       load_set_model (impl);
6399     }
6400   else if (impl->load_state == LOAD_LOADING)
6401     {
6402       /* Nothing */
6403     }
6404   else
6405     {
6406       /* We can't g_assert_not_reached(), as something other than us may have
6407        *  initiated a folder reload.  See #165556.
6408        */
6409       profile_end ("end", NULL);
6410       return;
6411     }
6412
6413   g_assert (impl->load_timeout_id == 0);
6414
6415   impl->load_state = LOAD_FINISHED;
6416
6417   pending_select_files_process (impl);
6418   set_busy_cursor (impl, FALSE);
6419 #ifdef PROFILE_FILE_CHOOSER
6420   access ("MARK: *** FINISHED LOADING", F_OK);
6421 #endif
6422
6423   profile_end ("end", NULL);
6424 }
6425
6426 static void
6427 stop_loading_and_clear_list_model (GtkFileChooserDefault *impl,
6428                                    gboolean remove_from_treeview)
6429 {
6430   load_remove_timer (impl); /* This changes the state to LOAD_EMPTY */
6431   
6432   if (impl->browse_files_model)
6433     {
6434       g_object_unref (impl->browse_files_model);
6435       impl->browse_files_model = NULL;
6436     }
6437
6438   if (remove_from_treeview)
6439     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
6440 }
6441
6442 static char *
6443 my_g_format_time_for_display (glong secs)
6444 {
6445   GDate mtime, now;
6446   gint days_diff;
6447   struct tm tm_mtime;
6448   time_t time_mtime, time_now;
6449   const gchar *format;
6450   gchar *locale_format = NULL;
6451   gchar buf[256];
6452   char *date_str = NULL;
6453 #ifdef G_OS_WIN32
6454   const char *locale, *dot = NULL;
6455   gint64 codepage = -1;
6456   char charset[20];
6457 #endif
6458
6459   time_mtime = secs;
6460
6461 #ifdef HAVE_LOCALTIME_R
6462   localtime_r ((time_t *) &time_mtime, &tm_mtime);
6463 #else
6464   {
6465     struct tm *ptm = localtime ((time_t *) &time_mtime);
6466
6467     if (!ptm)
6468       {
6469         g_warning ("ptm != NULL failed");
6470         
6471         return g_strdup (_("Unknown"));
6472       }
6473     else
6474       memcpy ((void *) &tm_mtime, (void *) ptm, sizeof (struct tm));
6475   }
6476 #endif /* HAVE_LOCALTIME_R */
6477
6478   g_date_set_time_t (&mtime, time_mtime);
6479   time_now = time (NULL);
6480   g_date_set_time_t (&now, time_now);
6481
6482   days_diff = g_date_get_julian (&now) - g_date_get_julian (&mtime);
6483
6484   /* Translators: %H means "hours" and %M means "minutes" */
6485   if (days_diff == 0)
6486     format = _("%H:%M");
6487   else if (days_diff == 1)
6488     format = _("Yesterday at %H:%M");
6489   else
6490     {
6491       if (days_diff > 1 && days_diff < 7)
6492         format = "%A"; /* Days from last week */
6493       else
6494         format = "%x"; /* Any other date */
6495     }
6496
6497 #ifdef G_OS_WIN32
6498   /* g_locale_from_utf8() returns a string in the system
6499    * code-page, which is not always the same as that used by the C
6500    * library. For instance when running a GTK+ program with
6501    * LANG=ko on an English version of Windows, the system
6502    * code-page is 1252, but the code-page used by the C library is
6503    * 949. (It's GTK+ itself that sets the C library locale when it
6504    * notices the LANG environment variable. See gtkmain.c The
6505    * Microsoft C library doesn't look at any locale environment
6506    * variables.) We need to pass strftime() a string in the C
6507    * library's code-page. See bug #509885.
6508    */
6509   locale = setlocale (LC_ALL, NULL);
6510   if (locale != NULL)
6511     dot = strchr (locale, '.');
6512   if (dot != NULL)
6513     {
6514       codepage = g_ascii_strtoll (dot+1, NULL, 10);
6515       
6516       /* All codepages should fit in 16 bits AFAIK */
6517       if (codepage > 0 && codepage < 65536)
6518         {
6519           sprintf (charset, "CP%u", (guint) codepage);
6520           locale_format = g_convert (format, -1, charset, "UTF-8", NULL, NULL, NULL);
6521         }
6522     }
6523 #else
6524   locale_format = g_locale_from_utf8 (format, -1, NULL, NULL, NULL);
6525 #endif
6526   if (locale_format != NULL &&
6527       strftime (buf, sizeof (buf), locale_format, &tm_mtime) != 0)
6528     {
6529 #ifdef G_OS_WIN32
6530       /* As above but in opposite direction... */
6531       if (codepage > 0 && codepage < 65536)
6532         date_str = g_convert (buf, -1, "UTF-8", charset, NULL, NULL, NULL);
6533 #else
6534       date_str = g_locale_to_utf8 (buf, -1, NULL, NULL, NULL);
6535 #endif
6536     }
6537
6538   if (date_str == NULL)
6539     date_str = g_strdup (_("Unknown"));
6540
6541   g_free (locale_format);
6542   return date_str;
6543 }
6544
6545 static void
6546 copy_attribute (GFileInfo *to, GFileInfo *from, const char *attribute)
6547 {
6548   GFileAttributeType type;
6549   gpointer value;
6550
6551   if (g_file_info_get_attribute_data (from, attribute, &type, &value, NULL))
6552     g_file_info_set_attribute (to, attribute, type, value);
6553 }
6554
6555 static void
6556 file_system_model_got_thumbnail (GObject *object, GAsyncResult *res, gpointer data)
6557 {
6558   GtkFileSystemModel *model = data; /* might be unreffed if operation was cancelled */
6559   GFile *file = G_FILE (object);
6560   GFileInfo *queried, *info;
6561   GtkTreeIter iter;
6562
6563   queried = g_file_query_info_finish (file, res, NULL);
6564   if (queried == NULL)
6565     return;
6566
6567   GDK_THREADS_ENTER ();
6568
6569   /* now we know model is valid */
6570
6571   /* file was deleted */
6572   if (!_gtk_file_system_model_get_iter_for_file (model, &iter, file))
6573     {
6574       GDK_THREADS_LEAVE ();
6575       return;
6576     }
6577
6578   info = g_file_info_dup (_gtk_file_system_model_get_info (model, &iter));
6579
6580   copy_attribute (info, queried, G_FILE_ATTRIBUTE_THUMBNAIL_PATH);
6581   copy_attribute (info, queried, G_FILE_ATTRIBUTE_THUMBNAILING_FAILED);
6582   copy_attribute (info, queried, G_FILE_ATTRIBUTE_STANDARD_ICON);
6583
6584   _gtk_file_system_model_update_file (model, file, info, FALSE);
6585
6586   g_object_unref (info);
6587
6588   GDK_THREADS_LEAVE ();
6589 }
6590
6591 static gboolean
6592 file_system_model_set (GtkFileSystemModel *model,
6593                        GFile              *file,
6594                        GFileInfo          *info,
6595                        int                 column,
6596                        GValue             *value,
6597                        gpointer            data)
6598 {
6599   GtkFileChooserDefault *impl = data;
6600  
6601   switch (column)
6602     {
6603     case MODEL_COL_FILE:
6604       g_value_set_object (value, file);
6605       break;
6606     case MODEL_COL_NAME:
6607       if (info == NULL)
6608         g_value_set_string (value, DEFAULT_NEW_FOLDER_NAME);
6609       else 
6610         g_value_set_string (value, g_file_info_get_display_name (info));
6611       break;
6612     case MODEL_COL_NAME_COLLATED:
6613       if (info == NULL)
6614         g_value_take_string (value, g_utf8_collate_key_for_filename (DEFAULT_NEW_FOLDER_NAME, -1));
6615       else 
6616         g_value_take_string (value, g_utf8_collate_key_for_filename (g_file_info_get_display_name (info), -1));
6617       break;
6618     case MODEL_COL_IS_FOLDER:
6619       g_value_set_boolean (value, info == NULL || _gtk_file_info_consider_as_directory (info));
6620       break;
6621     case MODEL_COL_PIXBUF:
6622       if (info)
6623         {
6624           if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_ICON))
6625             {
6626               g_value_take_object (value, _gtk_file_info_render_icon (info, GTK_WIDGET (impl), impl->icon_size));
6627             }
6628           else
6629             {
6630               GtkTreeModel *tree_model;
6631               GtkTreePath *path, *start, *end;
6632               GtkTreeIter iter;
6633
6634               if (impl->browse_files_tree_view == NULL ||
6635                   g_file_info_has_attribute (info, "filechooser::queried"))
6636                 return FALSE;
6637
6638               tree_model = gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view));
6639               if (tree_model != GTK_TREE_MODEL (model))
6640                 return FALSE;
6641
6642               if (!_gtk_file_system_model_get_iter_for_file (model,
6643                                                              &iter,
6644                                                              file))
6645                 g_assert_not_reached ();
6646               if (!gtk_tree_view_get_visible_range (GTK_TREE_VIEW (impl->browse_files_tree_view), &start, &end))
6647                 return FALSE;
6648               path = gtk_tree_model_get_path (tree_model, &iter);
6649               if (gtk_tree_path_compare (start, path) != 1 &&
6650                   gtk_tree_path_compare (path, end) != 1)
6651                 {
6652                   g_file_info_set_attribute_boolean (info, "filechooser::queried", TRUE);
6653                   g_file_query_info_async (file,
6654                                            G_FILE_ATTRIBUTE_THUMBNAIL_PATH ","
6655                                            G_FILE_ATTRIBUTE_THUMBNAILING_FAILED ","
6656                                            G_FILE_ATTRIBUTE_STANDARD_ICON,
6657                                            G_FILE_QUERY_INFO_NONE,
6658                                            G_PRIORITY_DEFAULT,
6659                                            _gtk_file_system_model_get_cancellable (model),
6660                                            file_system_model_got_thumbnail,
6661                                            model);
6662                 }
6663               gtk_tree_path_free (path);
6664               gtk_tree_path_free (start);
6665               gtk_tree_path_free (end);
6666               return FALSE;
6667             }
6668         }
6669       else
6670         g_value_set_object (value, NULL);
6671       break;
6672     case MODEL_COL_SIZE:
6673       g_value_set_int64 (value, info ? g_file_info_get_size (info) : 0);
6674       break;
6675     case MODEL_COL_SIZE_TEXT:
6676       if (info == NULL || _gtk_file_info_consider_as_directory (info))
6677         g_value_set_string (value, NULL);
6678       else
6679         g_value_take_string (value, g_format_size_for_display (g_file_info_get_size (info)));
6680       break;
6681     case MODEL_COL_MTIME:
6682     case MODEL_COL_MTIME_TEXT:
6683       {
6684         GTimeVal tv;
6685         if (info == NULL)
6686           break;
6687         g_file_info_get_modification_time (info, &tv);
6688         if (column == MODEL_COL_MTIME)
6689           g_value_set_long (value, tv.tv_sec);
6690         else if (tv.tv_sec == 0)
6691           g_value_set_static_string (value, _("Unknown"));
6692         else
6693           g_value_take_string (value, my_g_format_time_for_display (tv.tv_sec));
6694         break;
6695       }
6696     case MODEL_COL_ELLIPSIZE:
6697       g_value_set_enum (value, info ? PANGO_ELLIPSIZE_END : PANGO_ELLIPSIZE_NONE);
6698       break;
6699     default:
6700       g_assert_not_reached ();
6701       break;
6702     }
6703
6704   return TRUE;
6705 }
6706
6707 /* Gets rid of the old list model and creates a new one for the current folder */
6708 static gboolean
6709 set_list_model (GtkFileChooserDefault *impl,
6710                 GError               **error)
6711 {
6712   g_assert (impl->current_folder != NULL);
6713
6714   profile_start ("start", NULL);
6715
6716   stop_loading_and_clear_list_model (impl, TRUE);
6717
6718   set_busy_cursor (impl, TRUE);
6719
6720   impl->browse_files_model = 
6721     _gtk_file_system_model_new_for_directory (impl->current_folder,
6722                                               MODEL_ATTRIBUTES,
6723                                               file_system_model_set,
6724                                               impl,
6725                                               MODEL_COLUMN_TYPES);
6726
6727   _gtk_file_system_model_set_show_hidden (impl->browse_files_model, impl->show_hidden);
6728
6729   profile_msg ("    set sort function", NULL);
6730   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_NAME, name_sort_func, impl, NULL);
6731   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_SIZE, size_sort_func, impl, NULL);
6732   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_MTIME, mtime_sort_func, impl, NULL);
6733   gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), NULL, NULL, NULL);
6734   set_sort_column (impl);
6735   impl->list_sort_ascending = TRUE;
6736   g_signal_connect (impl->browse_files_model, "sort-column-changed",
6737                     G_CALLBACK (list_sort_column_changed_cb), impl);
6738
6739   load_setup_timer (impl); /* This changes the state to LOAD_PRELOAD */
6740
6741   g_signal_connect (impl->browse_files_model, "finished-loading",
6742                     G_CALLBACK (browse_files_model_finished_loading_cb), impl);
6743
6744   install_list_model_filter (impl);
6745
6746   profile_end ("end", NULL);
6747
6748   return TRUE;
6749 }
6750
6751 struct update_chooser_entry_selected_foreach_closure {
6752   int num_selected;
6753   GtkTreeIter first_selected_iter;
6754 };
6755
6756 static gint
6757 compare_utf8_filenames (const gchar *a,
6758                         const gchar *b)
6759 {
6760   gchar *a_folded, *b_folded;
6761   gint retval;
6762
6763   a_folded = g_utf8_strdown (a, -1);
6764   b_folded = g_utf8_strdown (b, -1);
6765
6766   retval = strcmp (a_folded, b_folded);
6767
6768   g_free (a_folded);
6769   g_free (b_folded);
6770
6771   return retval;
6772 }
6773
6774 static void
6775 update_chooser_entry_selected_foreach (GtkTreeModel *model,
6776                                        GtkTreePath *path,
6777                                        GtkTreeIter *iter,
6778                                        gpointer data)
6779 {
6780   struct update_chooser_entry_selected_foreach_closure *closure;
6781
6782   closure = data;
6783   closure->num_selected++;
6784
6785   if (closure->num_selected == 1)
6786     closure->first_selected_iter = *iter;
6787 }
6788
6789 static void
6790 update_chooser_entry (GtkFileChooserDefault *impl)
6791 {
6792   GtkTreeSelection *selection;
6793   struct update_chooser_entry_selected_foreach_closure closure;
6794
6795   /* no need to update the file chooser's entry if there's no entry */
6796   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
6797       !impl->location_entry)
6798     return;
6799
6800   if (!(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
6801         || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
6802         || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
6803              || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
6804             && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)))
6805     return;
6806
6807   g_assert (impl->location_entry != NULL);
6808
6809   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6810   closure.num_selected = 0;
6811   gtk_tree_selection_selected_foreach (selection, update_chooser_entry_selected_foreach, &closure);
6812
6813   if (closure.num_selected == 0)
6814     {
6815       if (impl->operation_mode == OPERATION_MODE_RECENT)
6816         _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), NULL);
6817       else
6818         goto maybe_clear_entry;
6819     }
6820   else if (closure.num_selected == 1)
6821     {
6822       if (impl->operation_mode == OPERATION_MODE_BROWSE)
6823         {
6824           GFileInfo *info;
6825           gboolean change_entry;
6826
6827           info = _gtk_file_system_model_get_info (impl->browse_files_model, &closure.first_selected_iter);
6828
6829           /* If the cursor moved to the row of the newly created folder,
6830            * retrieving info will return NULL.
6831            */
6832           if (!info)
6833             return;
6834
6835           g_free (impl->browse_files_last_selected_name);
6836           impl->browse_files_last_selected_name =
6837             g_strdup (g_file_info_get_display_name (info));
6838
6839           if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
6840               impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
6841               impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
6842             {
6843               /* Don't change the name when clicking on a folder... */
6844               change_entry = (! _gtk_file_info_consider_as_directory (info));
6845             }
6846           else
6847             change_entry = TRUE; /* ... unless we are in SELECT_FOLDER mode */
6848
6849           if (change_entry)
6850             {
6851               _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->browse_files_last_selected_name);
6852
6853               if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
6854                 _gtk_file_chooser_entry_select_filename (GTK_FILE_CHOOSER_ENTRY (impl->location_entry));
6855             }
6856
6857           return;
6858         }
6859       else if (impl->operation_mode == OPERATION_MODE_RECENT
6860                && impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
6861         {
6862           GFile *folder;
6863
6864           /* Set the base folder on the name entry, so it will do completion relative to the correct recent-folder */
6865
6866           gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &closure.first_selected_iter,
6867                               MODEL_COL_FILE, &folder,
6868                               -1);
6869           _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), folder);
6870           g_object_unref (folder);
6871           return;
6872         }
6873     }
6874   else
6875     {
6876       g_assert (!(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
6877                   impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER));
6878
6879       /* Multiple selection, so just clear the entry. */
6880       g_free (impl->browse_files_last_selected_name);
6881       impl->browse_files_last_selected_name = NULL;
6882
6883       _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
6884       return;
6885     }
6886
6887  maybe_clear_entry:
6888
6889   if ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
6890       && impl->browse_files_last_selected_name)
6891     {
6892       const char *entry_text;
6893       int len;
6894       gboolean clear_entry;
6895
6896       entry_text = gtk_entry_get_text (GTK_ENTRY (impl->location_entry));
6897       len = strlen (entry_text);
6898       if (len != 0)
6899         {
6900           /* The file chooser entry may have appended a "/" to its text.
6901            * So take it out, and compare the result to the old selection.
6902            */
6903           if (entry_text[len - 1] == G_DIR_SEPARATOR)
6904             {
6905               gchar *tmp;
6906
6907               tmp = g_strndup (entry_text, len - 1);
6908               clear_entry = (compare_utf8_filenames (impl->browse_files_last_selected_name, tmp) == 0);
6909               g_free (tmp);
6910             }
6911           else
6912             clear_entry = (compare_utf8_filenames (impl->browse_files_last_selected_name, entry_text) == 0);
6913         }
6914       else
6915         clear_entry = FALSE;
6916
6917       if (clear_entry)
6918         _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
6919     }
6920 }
6921
6922 static gboolean
6923 gtk_file_chooser_default_set_current_folder (GtkFileChooser  *chooser,
6924                                              GFile           *file,
6925                                              GError         **error)
6926 {
6927   return gtk_file_chooser_default_update_current_folder (chooser, file, FALSE, FALSE, error);
6928 }
6929
6930
6931 struct UpdateCurrentFolderData
6932 {
6933   GtkFileChooserDefault *impl;
6934   GFile *file;
6935   gboolean keep_trail;
6936   gboolean clear_entry;
6937   GFile *original_file;
6938   GError *original_error;
6939 };
6940
6941 static void
6942 update_current_folder_mount_enclosing_volume_cb (GCancellable        *cancellable,
6943                                                  GtkFileSystemVolume *volume,
6944                                                  const GError        *error,
6945                                                  gpointer             user_data)
6946 {
6947   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
6948   struct UpdateCurrentFolderData *data = user_data;
6949   GtkFileChooserDefault *impl = data->impl;
6950
6951   if (cancellable != impl->update_current_folder_cancellable)
6952     goto out;
6953
6954   impl->update_current_folder_cancellable = NULL;
6955   set_busy_cursor (impl, FALSE);
6956
6957   if (cancelled)
6958     goto out;
6959
6960   if (error)
6961     {
6962       error_changing_folder_dialog (data->impl, data->file, g_error_copy (error));
6963       impl->reload_state = RELOAD_EMPTY;
6964       goto out;
6965     }
6966
6967   change_folder_and_display_error (impl, data->file, data->clear_entry);
6968
6969 out:
6970   g_object_unref (data->file);
6971   g_free (data);
6972
6973   g_object_unref (cancellable);
6974 }
6975
6976 static void
6977 update_current_folder_get_info_cb (GCancellable *cancellable,
6978                                    GFileInfo    *info,
6979                                    const GError *error,
6980                                    gpointer      user_data)
6981 {
6982   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
6983   struct UpdateCurrentFolderData *data = user_data;
6984   GtkFileChooserDefault *impl = data->impl;
6985
6986   if (cancellable != impl->update_current_folder_cancellable)
6987     goto out;
6988
6989   impl->update_current_folder_cancellable = NULL;
6990   impl->reload_state = RELOAD_EMPTY;
6991
6992   set_busy_cursor (impl, FALSE);
6993
6994   if (cancelled)
6995     goto out;
6996
6997   if (error)
6998     {
6999       GFile *parent_file;
7000
7001       if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_MOUNTED))
7002         {
7003           GMountOperation *mount_operation;
7004           GtkWidget *toplevel;
7005
7006           g_object_unref (cancellable);
7007           toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
7008
7009           mount_operation = gtk_mount_operation_new (GTK_WINDOW (toplevel));
7010
7011           set_busy_cursor (impl, TRUE);
7012
7013           impl->update_current_folder_cancellable =
7014             _gtk_file_system_mount_enclosing_volume (impl->file_system, data->file,
7015                                                      mount_operation,
7016                                                      update_current_folder_mount_enclosing_volume_cb,
7017                                                      data);
7018
7019           return;
7020         }
7021
7022       if (!data->original_file)
7023         {
7024           data->original_file = g_object_ref (data->file);
7025           data->original_error = g_error_copy (error);
7026         }
7027
7028       parent_file = g_file_get_parent (data->file);
7029
7030       /* get parent path and try to change the folder to that */
7031       if (parent_file)
7032         {
7033           g_object_unref (data->file);
7034           data->file = parent_file;
7035
7036           g_object_unref (cancellable);
7037
7038           /* restart the update current folder operation */
7039           impl->reload_state = RELOAD_HAS_FOLDER;
7040
7041           impl->update_current_folder_cancellable =
7042             _gtk_file_system_get_info (impl->file_system, data->file,
7043                                        "standard::type",
7044                                        update_current_folder_get_info_cb,
7045                                        data);
7046
7047           set_busy_cursor (impl, TRUE);
7048
7049           return;
7050         }
7051       else
7052         {
7053           /* Error and bail out, ignoring "not found" errors since they're useless:
7054            * they only happen when a program defaults to a folder that has been (re)moved.
7055            */
7056           if (!g_error_matches (data->original_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
7057             error_changing_folder_dialog (impl, data->original_file, data->original_error);
7058           else
7059             g_error_free (data->original_error);
7060
7061           g_object_unref (data->original_file);
7062
7063           goto out;
7064         }
7065     }
7066
7067   if (data->original_file)
7068     {
7069       /* Error and bail out, ignoring "not found" errors since they're useless:
7070        * they only happen when a program defaults to a folder that has been (re)moved.
7071        */
7072       if (!g_error_matches (data->original_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
7073         error_changing_folder_dialog (impl, data->original_file, data->original_error);
7074       else
7075         g_error_free (data->original_error);
7076
7077       g_object_unref (data->original_file);
7078     }
7079
7080   if (! _gtk_file_info_consider_as_directory (info))
7081     goto out;
7082
7083   if (!_gtk_path_bar_set_file (GTK_PATH_BAR (impl->browse_path_bar), data->file, data->keep_trail, NULL))
7084     goto out;
7085
7086   if (impl->current_folder != data->file)
7087     {
7088       if (impl->current_folder)
7089         g_object_unref (impl->current_folder);
7090
7091       impl->current_folder = g_object_ref (data->file);
7092     }
7093
7094   impl->reload_state = RELOAD_HAS_FOLDER;
7095
7096   /* Update the widgets that may trigger a folder change themselves.  */
7097
7098   if (!impl->changing_folder)
7099     {
7100       impl->changing_folder = TRUE;
7101
7102       shortcuts_update_current_folder (impl);
7103
7104       impl->changing_folder = FALSE;
7105     }
7106
7107   /* Set the folder on the save entry */
7108
7109   if (impl->location_entry)
7110     {
7111       _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry),
7112                                                impl->current_folder);
7113
7114       if (data->clear_entry)
7115         _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
7116     }
7117
7118   /* Create a new list model.  This is slightly evil; we store the result value
7119    * but perform more actions rather than returning immediately even if it
7120    * generates an error.
7121    */
7122   set_list_model (impl, NULL);
7123
7124   /* Refresh controls */
7125
7126   shortcuts_find_current_folder (impl);
7127
7128   g_signal_emit_by_name (impl, "current-folder-changed", 0);
7129
7130   check_preview_change (impl);
7131   bookmarks_check_add_sensitivity (impl);
7132
7133   g_signal_emit_by_name (impl, "selection-changed", 0);
7134
7135 out:
7136   g_object_unref (data->file);
7137   g_free (data);
7138
7139   g_object_unref (cancellable);
7140 }
7141
7142 static gboolean
7143 gtk_file_chooser_default_update_current_folder (GtkFileChooser    *chooser,
7144                                                 GFile             *file,
7145                                                 gboolean           keep_trail,
7146                                                 gboolean           clear_entry,
7147                                                 GError           **error)
7148 {
7149   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7150   struct UpdateCurrentFolderData *data;
7151
7152   profile_start ("start", NULL);
7153
7154   g_object_ref (file);
7155
7156   switch (impl->operation_mode)
7157     {
7158     case OPERATION_MODE_SEARCH:
7159       search_switch_to_browse_mode (impl);
7160       break;
7161     case OPERATION_MODE_RECENT:
7162       recent_switch_to_browse_mode (impl);
7163       break;
7164     case OPERATION_MODE_BROWSE:
7165       break;
7166     }
7167
7168   if (impl->local_only && !g_file_is_native (file))
7169     {
7170       g_set_error_literal (error,
7171                            GTK_FILE_CHOOSER_ERROR,
7172                            GTK_FILE_CHOOSER_ERROR_BAD_FILENAME,
7173                            _("Cannot change to folder because it is not local"));
7174
7175       g_object_unref (file);
7176       profile_end ("end - not local", NULL);
7177       return FALSE;
7178     }
7179
7180   if (impl->update_current_folder_cancellable)
7181     g_cancellable_cancel (impl->update_current_folder_cancellable);
7182
7183   /* Test validity of path here.  */
7184   data = g_new0 (struct UpdateCurrentFolderData, 1);
7185   data->impl = impl;
7186   data->file = g_object_ref (file);
7187   data->keep_trail = keep_trail;
7188   data->clear_entry = clear_entry;
7189
7190   impl->reload_state = RELOAD_HAS_FOLDER;
7191
7192   impl->update_current_folder_cancellable =
7193     _gtk_file_system_get_info (impl->file_system, file,
7194                                "standard::type",
7195                                update_current_folder_get_info_cb,
7196                                data);
7197
7198   set_busy_cursor (impl, TRUE);
7199   g_object_unref (file);
7200
7201   profile_end ("end", NULL);
7202   return TRUE;
7203 }
7204
7205 static GFile *
7206 gtk_file_chooser_default_get_current_folder (GtkFileChooser *chooser)
7207 {
7208   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7209
7210   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7211       impl->operation_mode == OPERATION_MODE_RECENT)
7212     return NULL;
7213  
7214   if (impl->reload_state == RELOAD_EMPTY)
7215     {
7216       /* We are unmapped, or we had an error while loading the last folder.
7217        * We'll return the folder used by the last invocation of the file chooser
7218        * since once we get (re)mapped, we'll load *that* folder anyway unless
7219        * the caller explicitly calls set_current_folder() on us.
7220        */
7221       return get_file_for_last_folder_opened (impl);
7222     }
7223
7224   if (impl->current_folder)
7225     return g_object_ref (impl->current_folder);
7226
7227   return NULL;
7228 }
7229
7230 static void
7231 gtk_file_chooser_default_set_current_name (GtkFileChooser *chooser,
7232                                            const gchar    *name)
7233 {
7234   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7235
7236   g_return_if_fail (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7237                     impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
7238
7239   pending_select_files_free (impl);
7240   _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), name);
7241 }
7242
7243 static gboolean
7244 gtk_file_chooser_default_select_file (GtkFileChooser  *chooser,
7245                                       GFile           *file,
7246                                       GError         **error)
7247 {
7248   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7249   GFile *parent_file;
7250   gboolean same_path;
7251
7252   parent_file = g_file_get_parent (file);
7253
7254   if (!parent_file)
7255     return gtk_file_chooser_set_current_folder_file (chooser, file, error);
7256
7257   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7258       impl->operation_mode == OPERATION_MODE_RECENT ||
7259       impl->load_state == LOAD_EMPTY)
7260     {
7261       same_path = FALSE;
7262     }
7263   else
7264     {
7265       g_assert (impl->current_folder != NULL);
7266
7267       same_path = g_file_equal (parent_file, impl->current_folder);
7268     }
7269
7270   if (same_path && impl->load_state == LOAD_FINISHED)
7271     {
7272       gboolean result;
7273       GSList files;
7274
7275       files.data = (gpointer) file;
7276       files.next = NULL;
7277
7278       result = show_and_select_files (impl, &files);
7279       g_object_unref (parent_file);
7280       return result;
7281     }
7282
7283   pending_select_files_add (impl, file);
7284
7285   if (!same_path)
7286     {
7287       gboolean result;
7288
7289       result = gtk_file_chooser_set_current_folder_file (chooser, parent_file, error);
7290       g_object_unref (parent_file);
7291       return result;
7292     }
7293
7294   g_object_unref (parent_file);
7295   return TRUE;
7296 }
7297
7298 static void
7299 gtk_file_chooser_default_unselect_file (GtkFileChooser *chooser,
7300                                         GFile          *file)
7301 {
7302   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7303   GtkTreeView *tree_view = GTK_TREE_VIEW (impl->browse_files_tree_view);
7304   GtkTreeIter iter;
7305
7306   if (!impl->browse_files_model)
7307     return;
7308
7309   if (!_gtk_file_system_model_get_iter_for_file (impl->browse_files_model,
7310                                                  &iter,
7311                                                  file))
7312     return;
7313
7314   gtk_tree_selection_unselect_iter (gtk_tree_view_get_selection (tree_view),
7315                                     &iter);
7316 }
7317
7318 static gboolean
7319 maybe_select (GtkTreeModel *model, 
7320               GtkTreePath  *path, 
7321               GtkTreeIter  *iter, 
7322               gpointer     data)
7323 {
7324   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (data);
7325   GtkTreeSelection *selection;
7326   gboolean is_folder;
7327   
7328   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7329   
7330   gtk_tree_model_get (model, iter,
7331                       MODEL_COL_IS_FOLDER, &is_folder,
7332                       -1);
7333
7334   if ((is_folder && impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER) ||
7335       (!is_folder && impl->action == GTK_FILE_CHOOSER_ACTION_OPEN))
7336     gtk_tree_selection_select_iter (selection, iter);
7337   else
7338     gtk_tree_selection_unselect_iter (selection, iter);
7339     
7340   return FALSE;
7341 }
7342
7343 static void
7344 gtk_file_chooser_default_select_all (GtkFileChooser *chooser)
7345 {
7346   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7347
7348   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7349       impl->operation_mode == OPERATION_MODE_RECENT)
7350     {
7351       GtkTreeSelection *selection;
7352       
7353       selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7354       gtk_tree_selection_select_all (selection);
7355       return;
7356     }
7357
7358   if (impl->select_multiple)
7359     gtk_tree_model_foreach (GTK_TREE_MODEL (impl->browse_files_model), 
7360                             maybe_select, impl);
7361 }
7362
7363 static void
7364 gtk_file_chooser_default_unselect_all (GtkFileChooser *chooser)
7365 {
7366   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7367   GtkTreeSelection *selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7368
7369   gtk_tree_selection_unselect_all (selection);
7370   pending_select_files_free (impl);
7371 }
7372
7373 /* Checks whether the filename entry for the Save modes contains a well-formed filename.
7374  *
7375  * is_well_formed_ret - whether what the user typed passes gkt_file_system_make_path()
7376  *
7377  * is_empty_ret - whether the file entry is totally empty
7378  *
7379  * is_file_part_empty_ret - whether the file part is empty (will be if user types "foobar/", and
7380  *                          the path will be "$cwd/foobar")
7381  */
7382 static void
7383 check_save_entry (GtkFileChooserDefault *impl,
7384                   GFile                **file_ret,
7385                   gboolean              *is_well_formed_ret,
7386                   gboolean              *is_empty_ret,
7387                   gboolean              *is_file_part_empty_ret,
7388                   gboolean              *is_folder)
7389 {
7390   GtkFileChooserEntry *chooser_entry;
7391   GFile *current_folder;
7392   const char *file_part;
7393   GFile *file;
7394   GError *error;
7395
7396   g_assert (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
7397             || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
7398             || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
7399                  || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
7400                 && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY));
7401
7402   chooser_entry = GTK_FILE_CHOOSER_ENTRY (impl->location_entry);
7403
7404   if (strlen (gtk_entry_get_text (GTK_ENTRY (chooser_entry))) == 0)
7405     {
7406       *file_ret = NULL;
7407       *is_well_formed_ret = TRUE;
7408       *is_empty_ret = TRUE;
7409       *is_file_part_empty_ret = TRUE;
7410       *is_folder = FALSE;
7411
7412       return;
7413     }
7414
7415   *is_empty_ret = FALSE;
7416
7417   current_folder = _gtk_file_chooser_entry_get_current_folder (chooser_entry);
7418   if (!current_folder)
7419     {
7420       *file_ret = NULL;
7421       *is_well_formed_ret = FALSE;
7422       *is_file_part_empty_ret = FALSE;
7423       *is_folder = FALSE;
7424
7425       return;
7426     }
7427
7428   file_part = _gtk_file_chooser_entry_get_file_part (chooser_entry);
7429
7430   if (!file_part || file_part[0] == '\0')
7431     {
7432       *file_ret = g_object_ref (current_folder);
7433       *is_well_formed_ret = TRUE;
7434       *is_file_part_empty_ret = TRUE;
7435       *is_folder = TRUE;
7436
7437       return;
7438     }
7439
7440   *is_file_part_empty_ret = FALSE;
7441
7442   error = NULL;
7443   file = g_file_get_child_for_display_name (current_folder, file_part, &error);
7444
7445   if (!file)
7446     {
7447       error_building_filename_dialog (impl, error);
7448       *file_ret = NULL;
7449       *is_well_formed_ret = FALSE;
7450       *is_folder = FALSE;
7451
7452       return;
7453     }
7454
7455   *file_ret = file;
7456   *is_well_formed_ret = TRUE;
7457   *is_folder = _gtk_file_chooser_entry_get_is_folder (chooser_entry, file);
7458 }
7459
7460 struct get_files_closure {
7461   GtkFileChooserDefault *impl;
7462   GSList *result;
7463   GFile *file_from_entry;
7464 };
7465
7466 static void
7467 get_files_foreach (GtkTreeModel *model,
7468                    GtkTreePath  *path,
7469                    GtkTreeIter  *iter,
7470                    gpointer      data)
7471 {
7472   struct get_files_closure *info;
7473   GFile *file;
7474   GtkFileSystemModel *fs_model;
7475
7476   info = data;
7477   fs_model = info->impl->browse_files_model;
7478
7479   file = _gtk_file_system_model_get_file (fs_model, iter);
7480   if (!file)
7481     return; /* We are on the editable row */
7482
7483   if (!info->file_from_entry || !g_file_equal (info->file_from_entry, file))
7484     info->result = g_slist_prepend (info->result, g_object_ref (file));
7485 }
7486
7487 static GSList *
7488 gtk_file_chooser_default_get_files (GtkFileChooser *chooser)
7489 {
7490   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7491   struct get_files_closure info;
7492   GtkWindow *toplevel;
7493   GtkWidget *current_focus;
7494   gboolean file_list_seen;
7495
7496   info.impl = impl;
7497   info.result = NULL;
7498   info.file_from_entry = NULL;
7499
7500   if (impl->operation_mode == OPERATION_MODE_SEARCH)
7501     return search_get_selected_files (impl);
7502
7503   if (impl->operation_mode == OPERATION_MODE_RECENT)
7504     {
7505       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
7506         {
7507           file_list_seen = TRUE;
7508           goto file_entry;
7509         }
7510       else
7511         return recent_get_selected_files (impl);
7512     }
7513
7514   toplevel = get_toplevel (GTK_WIDGET (impl));
7515   if (toplevel)
7516     current_focus = gtk_window_get_focus (toplevel);
7517   else
7518     current_focus = NULL;
7519
7520   file_list_seen = FALSE;
7521   if (current_focus == impl->browse_files_tree_view)
7522     {
7523       GtkTreeSelection *selection;
7524
7525     file_list:
7526
7527       file_list_seen = TRUE;
7528       selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7529       gtk_tree_selection_selected_foreach (selection, get_files_foreach, &info);
7530
7531       /* If there is no selection in the file list, we probably have this situation:
7532        *
7533        * 1. The user typed a filename in the SAVE filename entry ("foo.txt").
7534        * 2. He then double-clicked on a folder ("bar") in the file list
7535        *
7536        * So we want the selection to be "bar/foo.txt".  Jump to the case for the
7537        * filename entry to see if that is the case.
7538        */
7539       if (info.result == NULL && impl->location_entry)
7540         goto file_entry;
7541     }
7542   else if (impl->location_entry && current_focus == impl->location_entry)
7543     {
7544       gboolean is_well_formed, is_empty, is_file_part_empty, is_folder;
7545
7546     file_entry:
7547
7548       check_save_entry (impl, &info.file_from_entry, &is_well_formed, &is_empty, &is_file_part_empty, &is_folder);
7549
7550       if (is_empty)
7551         goto out;
7552
7553       if (!is_well_formed)
7554         return NULL;
7555
7556       if (is_file_part_empty && impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
7557         {
7558           g_object_unref (info.file_from_entry);
7559           return NULL;
7560         }
7561
7562       if (info.file_from_entry)
7563         info.result = g_slist_prepend (info.result, info.file_from_entry);
7564       else if (!file_list_seen) 
7565         goto file_list;
7566       else
7567         return NULL;
7568     }
7569   else if (impl->toplevel_last_focus_widget == impl->browse_files_tree_view)
7570     goto file_list;
7571   else if (impl->location_entry && impl->toplevel_last_focus_widget == impl->location_entry)
7572     goto file_entry;
7573   else
7574     {
7575       /* The focus is on a dialog's action area button or something else */
7576       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7577           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
7578         goto file_entry;
7579       else
7580         goto file_list; 
7581     }
7582
7583  out:
7584
7585   /* If there's no folder selected, and we're in SELECT_FOLDER mode, then we
7586    * fall back to the current directory */
7587   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER &&
7588       info.result == NULL)
7589     {
7590       GFile *current_folder;
7591
7592       current_folder = gtk_file_chooser_get_current_folder_file (chooser);
7593
7594       if (current_folder)
7595         info.result = g_slist_prepend (info.result, current_folder);
7596     }
7597
7598   return g_slist_reverse (info.result);
7599 }
7600
7601 GFile *
7602 gtk_file_chooser_default_get_preview_file (GtkFileChooser *chooser)
7603 {
7604   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7605
7606   if (impl->preview_file)
7607     return g_object_ref (impl->preview_file);
7608   else
7609     return NULL;
7610 }
7611
7612 static GtkFileSystem *
7613 gtk_file_chooser_default_get_file_system (GtkFileChooser *chooser)
7614 {
7615   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7616
7617   return impl->file_system;
7618 }
7619
7620 /* Shows or hides the filter widgets */
7621 static void
7622 show_filters (GtkFileChooserDefault *impl,
7623               gboolean               show)
7624 {
7625   if (show)
7626     gtk_widget_show (impl->filter_combo_hbox);
7627   else
7628     gtk_widget_hide (impl->filter_combo_hbox);
7629 }
7630
7631 static void
7632 gtk_file_chooser_default_add_filter (GtkFileChooser *chooser,
7633                                      GtkFileFilter  *filter)
7634 {
7635   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7636   const gchar *name;
7637
7638   if (g_slist_find (impl->filters, filter))
7639     {
7640       g_warning ("gtk_file_chooser_add_filter() called on filter already in list\n");
7641       return;
7642     }
7643
7644   g_object_ref_sink (filter);
7645   impl->filters = g_slist_append (impl->filters, filter);
7646
7647   name = gtk_file_filter_get_name (filter);
7648   if (!name)
7649     name = "Untitled filter";   /* Place-holder, doesn't need to be marked for translation */
7650
7651   gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (impl->filter_combo), name);
7652
7653   if (!g_slist_find (impl->filters, impl->current_filter))
7654     set_current_filter (impl, filter);
7655
7656   show_filters (impl, TRUE);
7657 }
7658
7659 static void
7660 gtk_file_chooser_default_remove_filter (GtkFileChooser *chooser,
7661                                         GtkFileFilter  *filter)
7662 {
7663   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7664   GtkTreeModel *model;
7665   GtkTreeIter iter;
7666   gint filter_index;
7667
7668   filter_index = g_slist_index (impl->filters, filter);
7669
7670   if (filter_index < 0)
7671     {
7672       g_warning ("gtk_file_chooser_remove_filter() called on filter not in list\n");
7673       return;
7674     }
7675
7676   impl->filters = g_slist_remove (impl->filters, filter);
7677
7678   if (filter == impl->current_filter)
7679     {
7680       if (impl->filters)
7681         set_current_filter (impl, impl->filters->data);
7682       else
7683         set_current_filter (impl, NULL);
7684     }
7685
7686   /* Remove row from the combo box */
7687   model = gtk_combo_box_get_model (GTK_COMBO_BOX (impl->filter_combo));
7688   if (!gtk_tree_model_iter_nth_child  (model, &iter, NULL, filter_index))
7689     g_assert_not_reached ();
7690
7691   gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
7692
7693   g_object_unref (filter);
7694
7695   if (!impl->filters)
7696     show_filters (impl, FALSE);
7697 }
7698
7699 static GSList *
7700 gtk_file_chooser_default_list_filters (GtkFileChooser *chooser)
7701 {
7702   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7703
7704   return g_slist_copy (impl->filters);
7705 }
7706
7707 /* Returns the position in the shortcuts tree where the nth specified shortcut would appear */
7708 static int
7709 shortcuts_get_pos_for_shortcut_folder (GtkFileChooserDefault *impl,
7710                                        int                    pos)
7711 {
7712   return pos + shortcuts_get_index (impl, SHORTCUTS_SHORTCUTS);
7713 }
7714
7715 struct AddShortcutData
7716 {
7717   GtkFileChooserDefault *impl;
7718   GFile *file;
7719 };
7720
7721 static void
7722 add_shortcut_get_info_cb (GCancellable *cancellable,
7723                           GFileInfo    *info,
7724                           const GError *error,
7725                           gpointer      user_data)
7726 {
7727   int pos;
7728   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
7729   struct AddShortcutData *data = user_data;
7730
7731   if (!g_slist_find (data->impl->loading_shortcuts, cancellable))
7732     goto out;
7733
7734   data->impl->loading_shortcuts = g_slist_remove (data->impl->loading_shortcuts, cancellable);
7735
7736   if (cancelled || error || (! _gtk_file_info_consider_as_directory (info)))
7737     goto out;
7738
7739   pos = shortcuts_get_pos_for_shortcut_folder (data->impl, data->impl->num_shortcuts);
7740
7741   shortcuts_insert_file (data->impl, pos, SHORTCUT_TYPE_FILE, NULL, data->file, NULL, FALSE, SHORTCUTS_SHORTCUTS);
7742
7743 out:
7744   g_object_unref (data->impl);
7745   g_object_unref (data->file);
7746   g_free (data);
7747
7748   g_object_unref (cancellable);
7749 }
7750
7751 static gboolean
7752 gtk_file_chooser_default_add_shortcut_folder (GtkFileChooser  *chooser,
7753                                               GFile           *file,
7754                                               GError         **error)
7755 {
7756   GCancellable *cancellable;
7757   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7758   struct AddShortcutData *data;
7759   GSList *l;
7760   int pos;
7761
7762   /* Avoid adding duplicates */
7763   pos = shortcut_find_position (impl, file);
7764   if (pos >= 0 && pos < shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS_SEPARATOR))
7765     {
7766       gchar *uri;
7767
7768       uri = g_file_get_uri (file);
7769       /* translators, "Shortcut" means "Bookmark" here */
7770       g_set_error (error,
7771                    GTK_FILE_CHOOSER_ERROR,
7772                    GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS,
7773                    _("Shortcut %s already exists"),
7774                    uri);
7775       g_free (uri);
7776
7777       return FALSE;
7778     }
7779
7780   for (l = impl->loading_shortcuts; l; l = l->next)
7781     {
7782       GCancellable *c = l->data;
7783       GFile *f;
7784
7785       f = g_object_get_data (G_OBJECT (c), "add-shortcut-path-key");
7786       if (f && g_file_equal (file, f))
7787         {
7788           gchar *uri;
7789
7790           uri = g_file_get_uri (file);
7791           g_set_error (error,
7792                        GTK_FILE_CHOOSER_ERROR,
7793                        GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS,
7794                        _("Shortcut %s already exists"),
7795                        uri);
7796           g_free (uri);
7797
7798           return FALSE;
7799         }
7800     }
7801
7802   data = g_new0 (struct AddShortcutData, 1);
7803   data->impl = g_object_ref (impl);
7804   data->file = g_object_ref (file);
7805
7806   cancellable = _gtk_file_system_get_info (impl->file_system, file,
7807                                            "standard::type",
7808                                            add_shortcut_get_info_cb, data);
7809
7810   if (!cancellable)
7811     return FALSE;
7812
7813   impl->loading_shortcuts = g_slist_append (impl->loading_shortcuts, cancellable);
7814   g_object_set_data (G_OBJECT (cancellable), "add-shortcut-path-key", data->file);
7815
7816   return TRUE;
7817 }
7818
7819 static gboolean
7820 gtk_file_chooser_default_remove_shortcut_folder (GtkFileChooser  *chooser,
7821                                                  GFile           *file,
7822                                                  GError         **error)
7823 {
7824   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7825   int pos;
7826   GtkTreeIter iter;
7827   GSList *l;
7828   char *uri;
7829   int i;
7830
7831   for (l = impl->loading_shortcuts; l; l = l->next)
7832     {
7833       GCancellable *c = l->data;
7834       GFile *f;
7835
7836       f = g_object_get_data (G_OBJECT (c), "add-shortcut-path-key");
7837       if (f && g_file_equal (file, f))
7838         {
7839           impl->loading_shortcuts = g_slist_remove (impl->loading_shortcuts, c);
7840           g_cancellable_cancel (c);
7841           return TRUE;
7842         }
7843     }
7844
7845   if (impl->num_shortcuts == 0)
7846     goto out;
7847
7848   pos = shortcuts_get_pos_for_shortcut_folder (impl, 0);
7849   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
7850     g_assert_not_reached ();
7851
7852   for (i = 0; i < impl->num_shortcuts; i++)
7853     {
7854       gpointer col_data;
7855       ShortcutType shortcut_type;
7856       GFile *shortcut;
7857
7858       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
7859                           SHORTCUTS_COL_DATA, &col_data,
7860                           SHORTCUTS_COL_TYPE, &shortcut_type,
7861                           -1);
7862       g_assert (col_data != NULL);
7863       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
7864
7865       shortcut = col_data;
7866       if (g_file_equal (shortcut, file))
7867         {
7868           shortcuts_remove_rows (impl, pos + i, 1);
7869           impl->num_shortcuts--;
7870           return TRUE;
7871         }
7872
7873       if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
7874         g_assert_not_reached ();
7875     }
7876
7877  out:
7878
7879   uri = g_file_get_uri (file);
7880   /* translators, "Shortcut" means "Bookmark" here */
7881   g_set_error (error,
7882                GTK_FILE_CHOOSER_ERROR,
7883                GTK_FILE_CHOOSER_ERROR_NONEXISTENT,
7884                _("Shortcut %s does not exist"),
7885                uri);
7886   g_free (uri);
7887
7888   return FALSE;
7889 }
7890
7891 static GSList *
7892 gtk_file_chooser_default_list_shortcut_folders (GtkFileChooser *chooser)
7893 {
7894   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7895   int pos;
7896   GtkTreeIter iter;
7897   int i;
7898   GSList *list;
7899
7900   if (impl->num_shortcuts == 0)
7901     return NULL;
7902
7903   pos = shortcuts_get_pos_for_shortcut_folder (impl, 0);
7904   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
7905     g_assert_not_reached ();
7906
7907   list = NULL;
7908
7909   for (i = 0; i < impl->num_shortcuts; i++)
7910     {
7911       gpointer col_data;
7912       ShortcutType shortcut_type;
7913       GFile *shortcut;
7914
7915       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
7916                           SHORTCUTS_COL_DATA, &col_data,
7917                           SHORTCUTS_COL_TYPE, &shortcut_type,
7918                           -1);
7919       g_assert (col_data != NULL);
7920       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
7921
7922       shortcut = col_data;
7923       list = g_slist_prepend (list, g_object_ref (shortcut));
7924
7925       if (i != impl->num_shortcuts - 1)
7926         {
7927           if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
7928             g_assert_not_reached ();
7929         }
7930     }
7931
7932   return g_slist_reverse (list);
7933 }
7934
7935 /* Guesses a size based upon font sizes */
7936 static void
7937 find_good_size_from_style (GtkWidget *widget,
7938                            gint      *width,
7939                            gint      *height)
7940 {
7941   GtkStyleContext *context;
7942   GtkStateFlags state;
7943   int font_size;
7944   GdkScreen *screen;
7945   double resolution;
7946
7947   context = gtk_widget_get_style_context (widget);
7948   state = gtk_widget_get_state_flags (widget);
7949
7950   screen = gtk_widget_get_screen (widget);
7951   if (screen)
7952     {
7953       resolution = gdk_screen_get_resolution (screen);
7954       if (resolution < 0.0) /* will be -1 if the resolution is not defined in the GdkScreen */
7955         resolution = 96.0;
7956     }
7957   else
7958     resolution = 96.0; /* wheeee */
7959
7960   font_size = pango_font_description_get_size (gtk_style_context_get_font (context, state));
7961   font_size = PANGO_PIXELS (font_size) * resolution / 72.0;
7962
7963   *width = font_size * NUM_CHARS;
7964   *height = font_size * NUM_LINES;
7965 }
7966
7967 static void
7968 gtk_file_chooser_default_get_default_size (GtkFileChooserEmbed *chooser_embed,
7969                                            gint                *default_width,
7970                                            gint                *default_height)
7971 {
7972   GtkFileChooserDefault *impl;
7973   GtkRequisition req;
7974   int x, y, width, height;
7975
7976   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
7977
7978   settings_ensure (impl);
7979
7980   g_settings_get (impl->settings, SETTINGS_KEY_WINDOW_POSITION, "(ii)", &x, &y);
7981   g_settings_get (impl->settings, SETTINGS_KEY_WINDOW_SIZE, "(ii)", &width, &height);
7982
7983   if (x >= 0 && y >= 0 && width > 0 && height > 0)
7984     {
7985       *default_width = width;
7986       *default_height = height;
7987       return;
7988     }
7989
7990   find_good_size_from_style (GTK_WIDGET (chooser_embed), default_width, default_height);
7991
7992   if (impl->preview_widget_active &&
7993       impl->preview_widget &&
7994       gtk_widget_get_visible (impl->preview_widget))
7995     {
7996       gtk_widget_get_preferred_size (impl->preview_box,
7997                                      &req, NULL);
7998       *default_width += PREVIEW_HBOX_SPACING + req.width;
7999     }
8000
8001   if (impl->extra_widget &&
8002       gtk_widget_get_visible (impl->extra_widget))
8003     {
8004       gtk_widget_get_preferred_size (impl->extra_align,
8005                                      &req, NULL);
8006       *default_height += gtk_box_get_spacing (GTK_BOX (chooser_embed)) + req.height;
8007     }
8008 }
8009
8010 struct switch_folder_closure {
8011   GtkFileChooserDefault *impl;
8012   GFile *file;
8013   int num_selected;
8014 };
8015
8016 /* Used from gtk_tree_selection_selected_foreach() in switch_to_selected_folder() */
8017 static void
8018 switch_folder_foreach_cb (GtkTreeModel      *model,
8019                           GtkTreePath       *path,
8020                           GtkTreeIter       *iter,
8021                           gpointer           data)
8022 {
8023   struct switch_folder_closure *closure;
8024
8025   closure = data;
8026
8027   closure->file = _gtk_file_system_model_get_file (closure->impl->browse_files_model, iter);
8028   closure->num_selected++;
8029 }
8030
8031 /* Changes to the selected folder in the list view */
8032 static void
8033 switch_to_selected_folder (GtkFileChooserDefault *impl)
8034 {
8035   GtkTreeSelection *selection;
8036   struct switch_folder_closure closure;
8037
8038   /* We do this with foreach() rather than get_selected() as we may be in
8039    * multiple selection mode
8040    */
8041
8042   closure.impl = impl;
8043   closure.file = NULL;
8044   closure.num_selected = 0;
8045
8046   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8047   gtk_tree_selection_selected_foreach (selection, switch_folder_foreach_cb, &closure);
8048
8049   g_assert (closure.file && closure.num_selected == 1);
8050
8051   change_folder_and_display_error (impl, closure.file, FALSE);
8052 }
8053
8054 /* Gets the GFileInfo for the selected row in the file list; assumes single
8055  * selection mode.
8056  */
8057 static GFileInfo *
8058 get_selected_file_info_from_file_list (GtkFileChooserDefault *impl,
8059                                        gboolean              *had_selection)
8060 {
8061   GtkTreeSelection *selection;
8062   GtkTreeIter iter;
8063   GFileInfo *info;
8064
8065   g_assert (!impl->select_multiple);
8066   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8067   if (!gtk_tree_selection_get_selected (selection, NULL, &iter))
8068     {
8069       *had_selection = FALSE;
8070       return NULL;
8071     }
8072
8073   *had_selection = TRUE;
8074
8075   info = _gtk_file_system_model_get_info (impl->browse_files_model, &iter);
8076   return info;
8077 }
8078
8079 /* Gets the display name of the selected file in the file list; assumes single
8080  * selection mode and that something is selected.
8081  */
8082 static const gchar *
8083 get_display_name_from_file_list (GtkFileChooserDefault *impl)
8084 {
8085   GFileInfo *info;
8086   gboolean had_selection;
8087
8088   info = get_selected_file_info_from_file_list (impl, &had_selection);
8089   g_assert (had_selection);
8090   g_assert (info != NULL);
8091
8092   return g_file_info_get_display_name (info);
8093 }
8094
8095 static void
8096 add_custom_button_to_dialog (GtkDialog   *dialog,
8097                              const gchar *mnemonic_label,
8098                              const gchar *stock_id,
8099                              gint         response_id)
8100 {
8101   GtkWidget *button;
8102
8103   button = gtk_button_new_with_mnemonic (mnemonic_label);
8104   gtk_widget_set_can_default (button, TRUE);
8105   gtk_button_set_image (GTK_BUTTON (button),
8106                         gtk_image_new_from_stock (stock_id, GTK_ICON_SIZE_BUTTON));
8107   gtk_widget_show (button);
8108
8109   gtk_dialog_add_action_widget (GTK_DIALOG (dialog), button, response_id);
8110 }
8111
8112 /* Presents an overwrite confirmation dialog; returns whether we should accept
8113  * the filename.
8114  */
8115 static gboolean
8116 confirm_dialog_should_accept_filename (GtkFileChooserDefault *impl,
8117                                        const gchar           *file_part,
8118                                        const gchar           *folder_display_name)
8119 {
8120   GtkWindow *toplevel;
8121   GtkWidget *dialog;
8122   int response;
8123
8124   toplevel = get_toplevel (GTK_WIDGET (impl));
8125
8126   dialog = gtk_message_dialog_new (toplevel,
8127                                    GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
8128                                    GTK_MESSAGE_QUESTION,
8129                                    GTK_BUTTONS_NONE,
8130                                    _("A file named \"%s\" already exists.  Do you want to replace it?"),
8131                                    file_part);
8132   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
8133                                             _("The file already exists in \"%s\".  Replacing it will "
8134                                               "overwrite its contents."),
8135                                             folder_display_name);
8136
8137   gtk_dialog_add_button (GTK_DIALOG (dialog), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
8138   add_custom_button_to_dialog (GTK_DIALOG (dialog), _("_Replace"),
8139                                GTK_STOCK_SAVE_AS, GTK_RESPONSE_ACCEPT);
8140   gtk_dialog_set_alternative_button_order (GTK_DIALOG (dialog),
8141                                            GTK_RESPONSE_ACCEPT,
8142                                            GTK_RESPONSE_CANCEL,
8143                                            -1);
8144   gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);
8145
8146   if (gtk_window_has_group (toplevel))
8147     gtk_window_group_add_window (gtk_window_get_group (toplevel),
8148                                  GTK_WINDOW (dialog));
8149
8150   response = gtk_dialog_run (GTK_DIALOG (dialog));
8151
8152   gtk_widget_destroy (dialog);
8153
8154   return (response == GTK_RESPONSE_ACCEPT);
8155 }
8156
8157 struct GetDisplayNameData
8158 {
8159   GtkFileChooserDefault *impl;
8160   gchar *file_part;
8161 };
8162
8163 /* Every time we request a response explicitly, we need to save the selection to the recently-used list,
8164  * as requesting a response means, "the dialog is confirmed".
8165  */
8166 static void
8167 request_response_and_add_to_recent_list (GtkFileChooserDefault *impl)
8168 {
8169   g_signal_emit_by_name (impl, "response-requested");
8170   add_selection_to_recent_list (impl);
8171 }
8172
8173 static void
8174 confirmation_confirm_get_info_cb (GCancellable *cancellable,
8175                                   GFileInfo    *info,
8176                                   const GError *error,
8177                                   gpointer      user_data)
8178 {
8179   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8180   gboolean should_respond = FALSE;
8181   struct GetDisplayNameData *data = user_data;
8182
8183   if (cancellable != data->impl->should_respond_get_info_cancellable)
8184     goto out;
8185
8186   data->impl->should_respond_get_info_cancellable = NULL;
8187
8188   if (cancelled)
8189     goto out;
8190
8191   if (error)
8192     /* Huh?  Did the folder disappear?  Let the caller deal with it */
8193     should_respond = TRUE;
8194   else
8195     should_respond = confirm_dialog_should_accept_filename (data->impl, data->file_part, g_file_info_get_display_name (info));
8196
8197   set_busy_cursor (data->impl, FALSE);
8198   if (should_respond)
8199     request_response_and_add_to_recent_list (data->impl);
8200
8201 out:
8202   g_object_unref (data->impl);
8203   g_free (data->file_part);
8204   g_free (data);
8205
8206   g_object_unref (cancellable);
8207 }
8208
8209 /* Does overwrite confirmation if appropriate, and returns whether the dialog
8210  * should respond.  Can get the file part from the file list or the save entry.
8211  */
8212 static gboolean
8213 should_respond_after_confirm_overwrite (GtkFileChooserDefault *impl,
8214                                         const gchar           *file_part,
8215                                         GFile                 *parent_file)
8216 {
8217   GtkFileChooserConfirmation conf;
8218
8219   if (!impl->do_overwrite_confirmation)
8220     return TRUE;
8221
8222   conf = GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM;
8223
8224   g_signal_emit_by_name (impl, "confirm-overwrite", &conf);
8225
8226   switch (conf)
8227     {
8228     case GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM:
8229       {
8230         struct GetDisplayNameData *data;
8231
8232         g_assert (file_part != NULL);
8233
8234         data = g_new0 (struct GetDisplayNameData, 1);
8235         data->impl = g_object_ref (impl);
8236         data->file_part = g_strdup (file_part);
8237
8238         if (impl->should_respond_get_info_cancellable)
8239           g_cancellable_cancel (impl->should_respond_get_info_cancellable);
8240
8241         impl->should_respond_get_info_cancellable =
8242           _gtk_file_system_get_info (impl->file_system, parent_file,
8243                                      "standard::display-name",
8244                                      confirmation_confirm_get_info_cb,
8245                                      data);
8246         set_busy_cursor (data->impl, TRUE);
8247         return FALSE;
8248       }
8249
8250     case GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME:
8251       return TRUE;
8252
8253     case GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN:
8254       return FALSE;
8255
8256     default:
8257       g_assert_not_reached ();
8258       return FALSE;
8259     }
8260 }
8261
8262 struct FileExistsData
8263 {
8264   GtkFileChooserDefault *impl;
8265   gboolean file_exists_and_is_not_folder;
8266   GFile *parent_file;
8267   GFile *file;
8268 };
8269
8270 static void
8271 name_entry_get_parent_info_cb (GCancellable *cancellable,
8272                                GFileInfo    *info,
8273                                const GError *error,
8274                                gpointer      user_data)
8275 {
8276   gboolean parent_is_folder;
8277   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8278   struct FileExistsData *data = user_data;
8279
8280   if (cancellable != data->impl->should_respond_get_info_cancellable)
8281     goto out;
8282
8283   data->impl->should_respond_get_info_cancellable = NULL;
8284
8285   set_busy_cursor (data->impl, FALSE);
8286
8287   if (cancelled)
8288     goto out;
8289
8290   if (!info)
8291     parent_is_folder = FALSE;
8292   else
8293     parent_is_folder = _gtk_file_info_consider_as_directory (info);
8294
8295   if (parent_is_folder)
8296     {
8297       if (data->impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
8298         {
8299           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) */
8300         }
8301       else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8302         {
8303           if (data->file_exists_and_is_not_folder)
8304             {
8305               gboolean retval;
8306               char *file_part;
8307
8308               /* Dup the string because the string may be modified
8309                * depending on what clients do in the confirm-overwrite
8310                * signal and this corrupts the pointer
8311                */
8312               file_part = g_strdup (_gtk_file_chooser_entry_get_file_part (GTK_FILE_CHOOSER_ENTRY (data->impl->location_entry)));
8313               retval = should_respond_after_confirm_overwrite (data->impl, file_part, data->parent_file);
8314               g_free (file_part);
8315
8316               if (retval)
8317                 request_response_and_add_to_recent_list (data->impl);
8318             }
8319           else
8320             request_response_and_add_to_recent_list (data->impl);
8321         }
8322       else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER
8323                || data->impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8324         {
8325           GError *mkdir_error = NULL;
8326
8327           /* In both cases (SELECT_FOLDER and CREATE_FOLDER), if you type
8328            * "/blah/nonexistent" you *will* want a folder created.
8329            */
8330
8331           set_busy_cursor (data->impl, TRUE);
8332           g_file_make_directory (data->file, NULL, &mkdir_error);
8333           set_busy_cursor (data->impl, FALSE);
8334
8335           if (!mkdir_error)
8336             request_response_and_add_to_recent_list (data->impl);
8337           else
8338             error_creating_folder_dialog (data->impl, data->file, mkdir_error);
8339         }
8340       else
8341         g_assert_not_reached ();
8342     }
8343   else
8344     {
8345       if (info)
8346         {
8347           /* The parent exists, but it's not a folder!  Someone probably typed existing_file.txt/subfile.txt */
8348           error_with_file_under_nonfolder (data->impl, data->parent_file);
8349         }
8350       else
8351         {
8352           GError *error_copy;
8353
8354           /* The parent folder is not readable for some reason */
8355
8356           error_copy = g_error_copy (error);
8357           error_changing_folder_dialog (data->impl, data->parent_file, error_copy);
8358         }
8359     }
8360
8361 out:
8362   g_object_unref (data->impl);
8363   g_object_unref (data->file);
8364   g_object_unref (data->parent_file);
8365   g_free (data);
8366
8367   g_object_unref (cancellable);
8368 }
8369
8370 static void
8371 file_exists_get_info_cb (GCancellable *cancellable,
8372                          GFileInfo    *info,
8373                          const GError *error,
8374                          gpointer      user_data)
8375 {
8376   gboolean data_ownership_taken = FALSE;
8377   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8378   gboolean file_exists;
8379   gboolean is_folder;
8380   gboolean needs_parent_check = FALSE;
8381   struct FileExistsData *data = user_data;
8382
8383   if (cancellable != data->impl->file_exists_get_info_cancellable)
8384     goto out;
8385
8386   data->impl->file_exists_get_info_cancellable = NULL;
8387
8388   set_busy_cursor (data->impl, FALSE);
8389
8390   if (cancelled)
8391     goto out;
8392
8393   file_exists = (info != NULL);
8394   is_folder = (file_exists && _gtk_file_info_consider_as_directory (info));
8395
8396   if (data->impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
8397     {
8398       if (is_folder)
8399         change_folder_and_display_error (data->impl, data->file, TRUE);
8400       else
8401         {
8402           if (file_exists)
8403             request_response_and_add_to_recent_list (data->impl); /* user typed an existing filename; we are done */
8404           else
8405             needs_parent_check = TRUE; /* file doesn't exist; see if its parent exists */
8406         }
8407     }
8408   else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8409     {
8410       if (file_exists && !is_folder)
8411         {
8412           /* Oops, the user typed the name of an existing path which is not
8413            * a folder
8414            */
8415           error_creating_folder_over_existing_file_dialog (data->impl, data->file,
8416                                                            g_error_copy (error));
8417         }
8418       else
8419         {
8420           needs_parent_check = TRUE;
8421         }
8422     }
8423   else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8424     {
8425       if (!file_exists)
8426         {
8427           needs_parent_check = TRUE;
8428         }
8429       else
8430         {
8431           if (is_folder)
8432             {
8433               /* User typed a folder; we are done */
8434               request_response_and_add_to_recent_list (data->impl);
8435             }
8436           else
8437             error_selecting_folder_over_existing_file_dialog (data->impl, data->file);
8438         }
8439     }
8440   else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8441     {
8442       if (is_folder)
8443         change_folder_and_display_error (data->impl, data->file, TRUE);
8444       else
8445         needs_parent_check = TRUE;
8446     }
8447   else
8448     {
8449       g_assert_not_reached();
8450     }
8451
8452   if (needs_parent_check) {
8453     /* check that everything up to the last path component exists (i.e. the parent) */
8454
8455     data->file_exists_and_is_not_folder = file_exists && !is_folder;
8456     data_ownership_taken = TRUE;
8457
8458     if (data->impl->should_respond_get_info_cancellable)
8459       g_cancellable_cancel (data->impl->should_respond_get_info_cancellable);
8460
8461       data->impl->should_respond_get_info_cancellable =
8462         _gtk_file_system_get_info (data->impl->file_system,
8463                                    data->parent_file,
8464                                    "standard::type",
8465                                    name_entry_get_parent_info_cb,
8466                                    data);
8467       set_busy_cursor (data->impl, TRUE);
8468     }
8469
8470 out:
8471   if (!data_ownership_taken)
8472     {
8473       g_object_unref (data->impl);
8474       g_object_unref (data->file);
8475       g_object_unref (data->parent_file);
8476       g_free (data);
8477     }
8478
8479   g_object_unref (cancellable);
8480 }
8481
8482 static void
8483 paste_text_received (GtkClipboard          *clipboard,
8484                      const gchar           *text,
8485                      GtkFileChooserDefault *impl)
8486 {
8487   GFile *file;
8488
8489   if (!text)
8490     return;
8491
8492   file = g_file_new_for_uri (text);
8493
8494   if (!gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (impl), file, NULL))
8495     location_popup_handler (impl, text);
8496
8497   g_object_unref (file);
8498 }
8499
8500 /* Handler for the "location-popup-on-paste" keybinding signal */
8501 static void
8502 location_popup_on_paste_handler (GtkFileChooserDefault *impl)
8503 {
8504   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (impl),
8505                                                       GDK_SELECTION_CLIPBOARD);
8506   gtk_clipboard_request_text (clipboard,
8507                               (GtkClipboardTextReceivedFunc) paste_text_received,
8508                               impl);
8509 }
8510
8511 /* Implementation for GtkFileChooserEmbed::should_respond() */
8512 static void
8513 add_selection_to_recent_list (GtkFileChooserDefault *impl)
8514 {
8515   GSList *files;
8516   GSList *l;
8517
8518   files = gtk_file_chooser_default_get_files (GTK_FILE_CHOOSER (impl));
8519
8520   for (l = files; l; l = l->next)
8521     {
8522       GFile *file = l->data;
8523       char *uri;
8524
8525       uri = g_file_get_uri (file);
8526       if (uri)
8527         {
8528           gtk_recent_manager_add_item (impl->recent_manager, uri);
8529           g_free (uri);
8530         }
8531     }
8532
8533   g_slist_foreach (files, (GFunc) g_object_unref, NULL);
8534   g_slist_free (files);
8535 }
8536
8537 static gboolean
8538 gtk_file_chooser_default_should_respond (GtkFileChooserEmbed *chooser_embed)
8539 {
8540   GtkFileChooserDefault *impl;
8541   GtkWidget *toplevel;
8542   GtkWidget *current_focus;
8543   gboolean retval;
8544
8545   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
8546
8547   toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
8548   g_assert (GTK_IS_WINDOW (toplevel));
8549
8550   retval = FALSE;
8551
8552   current_focus = gtk_window_get_focus (GTK_WINDOW (toplevel));
8553
8554   if (current_focus == impl->browse_files_tree_view)
8555     {
8556       /* The following array encodes what we do based on the impl->action and the
8557        * number of files selected.
8558        */
8559       typedef enum {
8560         NOOP,                   /* Do nothing (don't respond) */
8561         RESPOND,                /* Respond immediately */
8562         RESPOND_OR_SWITCH,      /* Respond immediately if the selected item is a file; switch to it if it is a folder */
8563         ALL_FILES,              /* Respond only if everything selected is a file */
8564         ALL_FOLDERS,            /* Respond only if everything selected is a folder */
8565         SAVE_ENTRY,             /* Go to the code for handling the save entry */
8566         NOT_REACHED             /* Sanity check */
8567       } ActionToTake;
8568       static const ActionToTake what_to_do[4][3] = {
8569         /*                                0 selected            1 selected              many selected */
8570         /* ACTION_OPEN */               { NOOP,                 RESPOND_OR_SWITCH,      ALL_FILES   },
8571         /* ACTION_SAVE */               { SAVE_ENTRY,           RESPOND_OR_SWITCH,      NOT_REACHED },
8572         /* ACTION_SELECT_FOLDER */      { RESPOND,              ALL_FOLDERS,            ALL_FOLDERS },
8573         /* ACTION_CREATE_FOLDER */      { SAVE_ENTRY,           ALL_FOLDERS,            NOT_REACHED }
8574       };
8575
8576       int num_selected;
8577       gboolean all_files, all_folders;
8578       int k;
8579       ActionToTake action;
8580
8581     file_list:
8582
8583       g_assert (impl->action >= GTK_FILE_CHOOSER_ACTION_OPEN && impl->action <= GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
8584
8585       if (impl->operation_mode == OPERATION_MODE_SEARCH)
8586         {
8587           retval = search_should_respond (impl);
8588           goto out;
8589         }
8590
8591       if (impl->operation_mode == OPERATION_MODE_RECENT)
8592         {
8593           if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8594             goto save_entry;
8595           else
8596             {
8597               retval = recent_should_respond (impl);
8598               goto out;
8599             }
8600         }
8601
8602       selection_check (impl, &num_selected, &all_files, &all_folders);
8603
8604       if (num_selected > 2)
8605         k = 2;
8606       else
8607         k = num_selected;
8608
8609       action = what_to_do [impl->action] [k];
8610
8611       switch (action)
8612         {
8613         case NOOP:
8614           return FALSE;
8615
8616         case RESPOND:
8617           retval = TRUE;
8618           goto out;
8619
8620         case RESPOND_OR_SWITCH:
8621           g_assert (num_selected == 1);
8622
8623           if (all_folders)
8624             {
8625               switch_to_selected_folder (impl);
8626               return FALSE;
8627             }
8628           else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8629             {
8630               retval = should_respond_after_confirm_overwrite (impl,
8631                                                                get_display_name_from_file_list (impl),
8632                                                                impl->current_folder);
8633               goto out;
8634             }
8635           else
8636             {
8637               retval = TRUE;
8638               goto out;
8639             }
8640
8641         case ALL_FILES:
8642           retval = all_files;
8643           goto out;
8644
8645         case ALL_FOLDERS:
8646           retval = all_folders;
8647           goto out;
8648
8649         case SAVE_ENTRY:
8650           goto save_entry;
8651
8652         default:
8653           g_assert_not_reached ();
8654         }
8655     }
8656   else if ((impl->location_entry != NULL) && (current_focus == impl->location_entry))
8657     {
8658       GFile *file;
8659       gboolean is_well_formed, is_empty, is_file_part_empty;
8660       gboolean is_folder;
8661       GtkFileChooserEntry *entry;
8662       GError *error;
8663
8664     save_entry:
8665
8666       g_assert (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8667                 || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
8668                 || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
8669                      || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8670                     && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY));
8671
8672       entry = GTK_FILE_CHOOSER_ENTRY (impl->location_entry);
8673       check_save_entry (impl, &file, &is_well_formed, &is_empty, &is_file_part_empty, &is_folder);
8674
8675       if (!is_well_formed)
8676         {
8677           if (!is_empty
8678               && impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8679               && impl->operation_mode == OPERATION_MODE_RECENT)
8680             {
8681               path_bar_set_mode (impl, PATH_BAR_ERROR_NO_FOLDER);
8682 #if 0
8683               /* We'll #ifdef this out, as the fucking treeview selects its first row,
8684                * thus changing our assumption that no selection is present - setting
8685                * a selection causes the error message from path_bar_set_mode() to go away,
8686                * but we want the user to see that message!
8687                */
8688               gtk_widget_grab_focus (impl->browse_files_tree_view);
8689 #endif
8690             }
8691           /* FIXME: else show an "invalid filename" error as the pathbar mode? */
8692
8693           return FALSE;
8694         }
8695
8696       if (is_empty)
8697         {
8698           if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8699               || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8700             {
8701               path_bar_set_mode (impl, PATH_BAR_ERROR_NO_FILENAME);
8702               gtk_widget_grab_focus (impl->location_entry);
8703               return FALSE;
8704             }
8705
8706           goto file_list;
8707         }
8708
8709       g_assert (file != NULL);
8710
8711       error = NULL;
8712       if (is_folder)
8713         {
8714           if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8715               impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8716             {
8717               change_folder_and_display_error (impl, file, TRUE);
8718             }
8719           else if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
8720                    impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8721             {
8722               /* The folder already exists, so we do not need to create it.
8723                * Just respond to terminate the dialog.
8724                */
8725               retval = TRUE;
8726             }
8727           else
8728             {
8729               g_assert_not_reached ();
8730             }
8731         }
8732       else
8733         {
8734           struct FileExistsData *data;
8735
8736           /* We need to check whether file exists and whether it is a folder -
8737            * the GtkFileChooserEntry *does* report is_folder==FALSE as a false
8738            * negative (it doesn't know yet if your last path component is a
8739            * folder).
8740            */
8741
8742           data = g_new0 (struct FileExistsData, 1);
8743           data->impl = g_object_ref (impl);
8744           data->file = g_object_ref (file);
8745           data->parent_file = g_object_ref (_gtk_file_chooser_entry_get_current_folder (entry));
8746
8747           if (impl->file_exists_get_info_cancellable)
8748             g_cancellable_cancel (impl->file_exists_get_info_cancellable);
8749
8750           impl->file_exists_get_info_cancellable =
8751             _gtk_file_system_get_info (impl->file_system, file,
8752                                        "standard::type",
8753                                        file_exists_get_info_cb,
8754                                        data);
8755
8756           set_busy_cursor (impl, TRUE);
8757
8758           if (error != NULL)
8759             g_error_free (error);
8760         }
8761
8762       g_object_unref (file);
8763     }
8764   else if (impl->toplevel_last_focus_widget == impl->browse_files_tree_view)
8765     {
8766       /* The focus is on a dialog's action area button, *and* the widget that
8767        * was focused immediately before it is the file list.  
8768        */
8769       goto file_list;
8770     }
8771   else if (impl->operation_mode == OPERATION_MODE_SEARCH && impl->toplevel_last_focus_widget == impl->search_entry)
8772     {
8773       search_entry_activate_cb (GTK_ENTRY (impl->search_entry), impl);
8774       return FALSE;
8775     }
8776   else if (impl->location_entry && impl->toplevel_last_focus_widget == impl->location_entry)
8777     {
8778       /* The focus is on a dialog's action area button, *and* the widget that
8779        * was focused immediately before it is the location entry.
8780        */
8781       goto save_entry;
8782     }
8783   else
8784     /* The focus is on a dialog's action area button or something else */
8785     if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8786         || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8787       goto save_entry;
8788     else
8789       goto file_list; 
8790
8791  out:
8792
8793   if (retval)
8794     add_selection_to_recent_list (impl);
8795
8796   return retval;
8797 }
8798
8799 /* Implementation for GtkFileChooserEmbed::initial_focus() */
8800 static void
8801 gtk_file_chooser_default_initial_focus (GtkFileChooserEmbed *chooser_embed)
8802 {
8803   GtkFileChooserDefault *impl;
8804   GtkWidget *widget;
8805
8806   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
8807
8808   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8809       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8810     {
8811       if (impl->location_mode == LOCATION_MODE_PATH_BAR)
8812         widget = impl->browse_files_tree_view;
8813       else
8814         widget = impl->location_entry;
8815     }
8816   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
8817            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8818     widget = impl->location_entry;
8819   else
8820     {
8821       g_assert_not_reached ();
8822       widget = NULL;
8823     }
8824
8825   g_assert (widget != NULL);
8826   gtk_widget_grab_focus (widget);
8827 }
8828
8829 /* Callback used from gtk_tree_selection_selected_foreach(); gets the selected GFiles */
8830 static void
8831 search_selected_foreach_get_file_cb (GtkTreeModel *model,
8832                                      GtkTreePath  *path,
8833                                      GtkTreeIter  *iter,
8834                                      gpointer      data)
8835 {
8836   GSList **list;
8837   GFile *file;
8838
8839   list = data;
8840
8841   gtk_tree_model_get (model, iter, MODEL_COL_FILE, &file, -1);
8842   *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 */
8843 }
8844
8845 /* Constructs a list of the selected paths in search mode */
8846 static GSList *
8847 search_get_selected_files (GtkFileChooserDefault *impl)
8848 {
8849   GSList *result;
8850   GtkTreeSelection *selection;
8851
8852   result = NULL;
8853
8854   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8855   gtk_tree_selection_selected_foreach (selection, search_selected_foreach_get_file_cb, &result);
8856   result = g_slist_reverse (result);
8857
8858   return result;
8859 }
8860
8861 /* Called from ::should_respond().  We return whether there are selected files
8862  * in the search list.
8863  */
8864 static gboolean
8865 search_should_respond (GtkFileChooserDefault *impl)
8866 {
8867   GtkTreeSelection *selection;
8868
8869   g_assert (impl->operation_mode == OPERATION_MODE_SEARCH);
8870
8871   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8872   return (gtk_tree_selection_count_selected_rows (selection) != 0);
8873 }
8874
8875 /* Adds one hit from the search engine to the search_model */
8876 static void
8877 search_add_hit (GtkFileChooserDefault *impl,
8878                 gchar                 *uri)
8879 {
8880   GFile *file;
8881
8882   file = g_file_new_for_uri (uri);
8883   if (!file)
8884     return;
8885
8886   if (!g_file_is_native (file))
8887     {
8888       g_object_unref (file);
8889       return;
8890     }
8891
8892   _gtk_file_system_model_add_and_query_file (impl->search_model,
8893                                              file,
8894                                              MODEL_ATTRIBUTES);
8895
8896   g_object_unref (file);
8897 }
8898
8899 /* Callback used from GtkSearchEngine when we get new hits */
8900 static void
8901 search_engine_hits_added_cb (GtkSearchEngine *engine,
8902                              GList           *hits,
8903                              gpointer         data)
8904 {
8905   GtkFileChooserDefault *impl;
8906   GList *l;
8907   
8908   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8909
8910   for (l = hits; l; l = l->next)
8911     search_add_hit (impl, (gchar*)l->data);
8912 }
8913
8914 /* Callback used from GtkSearchEngine when the query is done running */
8915 static void
8916 search_engine_finished_cb (GtkSearchEngine *engine,
8917                            gpointer         data)
8918 {
8919   GtkFileChooserDefault *impl;
8920   
8921   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8922   
8923 #if 0
8924   /* EB: setting the model here will avoid loads of row events,
8925    * but it'll make the search look like blocked.
8926    */
8927   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
8928                            GTK_TREE_MODEL (impl->search_model));
8929 #endif
8930
8931   /* FMQ: if search was empty, say that we got no hits */
8932   set_busy_cursor (impl, FALSE);
8933 }
8934
8935 /* Displays a generic error when we cannot create a GtkSearchEngine.  
8936  * It would be better if _gtk_search_engine_new() gave us a GError 
8937  * with a better message, but it doesn't do that right now.
8938  */
8939 static void
8940 search_error_could_not_create_client (GtkFileChooserDefault *impl)
8941 {
8942   error_message (impl,
8943                  _("Could not start the search process"),
8944                  _("The program was not able to create a connection to the indexer "
8945                    "daemon.  Please make sure it is running."));
8946 }
8947
8948 static void
8949 search_engine_error_cb (GtkSearchEngine *engine,
8950                         const gchar     *message,
8951                         gpointer         data)
8952 {
8953   GtkFileChooserDefault *impl;
8954   
8955   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8956
8957   search_stop_searching (impl, TRUE);
8958   error_message (impl, _("Could not send the search request"), message);
8959
8960   set_busy_cursor (impl, FALSE);
8961 }
8962
8963 /* Frees the data in the search_model */
8964 static void
8965 search_clear_model (GtkFileChooserDefault *impl, 
8966                     gboolean               remove_from_treeview)
8967 {
8968   if (!impl->search_model)
8969     return;
8970
8971   g_object_unref (impl->search_model);
8972   impl->search_model = NULL;
8973   
8974   if (remove_from_treeview)
8975     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
8976 }
8977
8978 /* Stops any ongoing searches; does not touch the search_model */
8979 static void
8980 search_stop_searching (GtkFileChooserDefault *impl,
8981                        gboolean               remove_query)
8982 {
8983   if (remove_query && impl->search_query)
8984     {
8985       g_object_unref (impl->search_query);
8986       impl->search_query = NULL;
8987     }
8988   
8989   if (impl->search_engine)
8990     {
8991       _gtk_search_engine_stop (impl->search_engine);
8992       
8993       g_object_unref (impl->search_engine);
8994       impl->search_engine = NULL;
8995     }
8996 }
8997
8998 /* Stops any pending searches, clears the file list, and switches back to OPERATION_MODE_BROWSE */
8999 static void
9000 search_switch_to_browse_mode (GtkFileChooserDefault *impl)
9001 {
9002   g_assert (impl->operation_mode != OPERATION_MODE_BROWSE);
9003
9004   search_stop_searching (impl, FALSE);
9005   search_clear_model (impl, TRUE);
9006
9007   gtk_widget_destroy (impl->search_hbox);
9008   impl->search_hbox = NULL;
9009   impl->search_entry = NULL;
9010
9011   impl->operation_mode = OPERATION_MODE_BROWSE;
9012   path_bar_update (impl);
9013
9014   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9015       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9016     {
9017       gtk_widget_show (impl->location_button);
9018
9019       if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
9020         gtk_widget_show (impl->location_entry_box);
9021     }
9022
9023   file_list_set_sort_column_ids (impl);
9024 }
9025
9026 /* Creates the search_model and puts it in the tree view */
9027 static void
9028 search_setup_model (GtkFileChooserDefault *impl)
9029 {
9030   g_assert (impl->search_model == NULL);
9031
9032   impl->search_model = _gtk_file_system_model_new (file_system_model_set,
9033                                                    impl,
9034                                                    MODEL_COLUMN_TYPES);
9035
9036   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model),
9037                                    MODEL_COL_NAME,
9038                                    name_sort_func,
9039                                    impl, NULL);
9040   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model),
9041                                    MODEL_COL_MTIME,
9042                                    mtime_sort_func,
9043                                    impl, NULL);
9044   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model),
9045                                    MODEL_COL_SIZE,
9046                                    size_sort_func,
9047                                    impl, NULL);
9048   set_sort_column (impl);
9049
9050   /* EB: setting the model here will make the hits list update feel
9051    * more "alive" than setting the model at the end of the search
9052    * run
9053    */
9054   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9055                            GTK_TREE_MODEL (impl->search_model));
9056 }
9057
9058 /* Creates a new query with the specified text and launches it */
9059 static void
9060 search_start_query (GtkFileChooserDefault *impl,
9061                     const gchar           *query_text)
9062 {
9063   search_stop_searching (impl, FALSE);
9064   search_clear_model (impl, TRUE);
9065   search_setup_model (impl);
9066   set_busy_cursor (impl, TRUE);
9067
9068   if (impl->search_engine == NULL)
9069     impl->search_engine = _gtk_search_engine_new ();
9070
9071   if (!impl->search_engine)
9072     {
9073       set_busy_cursor (impl, FALSE);
9074       search_error_could_not_create_client (impl); /* lame; we don't get an error code or anything */
9075       return;
9076     }
9077
9078   if (!impl->search_query)
9079     {
9080       impl->search_query = _gtk_query_new ();
9081       _gtk_query_set_text (impl->search_query, query_text);
9082     }
9083   
9084   _gtk_search_engine_set_query (impl->search_engine, impl->search_query);
9085
9086   g_signal_connect (impl->search_engine, "hits-added",
9087                     G_CALLBACK (search_engine_hits_added_cb), impl);
9088   g_signal_connect (impl->search_engine, "finished",
9089                     G_CALLBACK (search_engine_finished_cb), impl);
9090   g_signal_connect (impl->search_engine, "error",
9091                     G_CALLBACK (search_engine_error_cb), impl);
9092
9093   _gtk_search_engine_start (impl->search_engine);
9094 }
9095
9096 /* Callback used when the user presses Enter while typing on the search
9097  * entry; starts the query
9098  */
9099 static void
9100 search_entry_activate_cb (GtkEntry *entry,
9101                           gpointer data)
9102 {
9103   GtkFileChooserDefault *impl;
9104   const char *text;
9105
9106   impl = GTK_FILE_CHOOSER_DEFAULT (data);
9107
9108   text = gtk_entry_get_text (GTK_ENTRY (impl->search_entry));
9109   if (strlen (text) == 0)
9110     return;
9111
9112   /* reset any existing query object */
9113   if (impl->search_query)
9114     {
9115       g_object_unref (impl->search_query);
9116       impl->search_query = NULL;
9117     }
9118
9119   search_start_query (impl, text);
9120 }
9121
9122 static gboolean
9123 focus_entry_idle_cb (GtkFileChooserDefault *impl)
9124 {
9125   GDK_THREADS_ENTER ();
9126   
9127   g_source_destroy (impl->focus_entry_idle);
9128   impl->focus_entry_idle = NULL;
9129
9130   if (impl->search_entry)
9131     gtk_widget_grab_focus (impl->search_entry);
9132
9133   GDK_THREADS_LEAVE ();
9134
9135   return FALSE;
9136 }
9137
9138 static void
9139 focus_search_entry_in_idle (GtkFileChooserDefault *impl)
9140 {
9141   /* bgo#634558 - When the user clicks on the Search entry in the shortcuts
9142    * pane, we get a selection-changed signal and we set up the search widgets.
9143    * However, gtk_tree_view_button_press() focuses the treeview *after* making
9144    * the change to the selection.  So, we need to re-focus the search entry
9145    * after the treeview has finished doing its work; we'll do that in an idle
9146    * handler.
9147    */
9148
9149   if (!impl->focus_entry_idle)
9150     impl->focus_entry_idle = add_idle_while_impl_is_alive (impl, G_CALLBACK (focus_entry_idle_cb));
9151 }
9152
9153 /* Hides the path bar and creates the search entry */
9154 static void
9155 search_setup_widgets (GtkFileChooserDefault *impl)
9156 {
9157   impl->search_hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
9158
9159   path_bar_update (impl);
9160
9161   impl->search_entry = gtk_entry_new ();
9162   g_signal_connect (impl->search_entry, "activate",
9163                     G_CALLBACK (search_entry_activate_cb),
9164                     impl);
9165   gtk_box_pack_start (GTK_BOX (impl->search_hbox), impl->search_entry, TRUE, TRUE, 0);
9166
9167   /* if there already is a query, restart it */
9168   if (impl->search_query)
9169     {
9170       gchar *query = _gtk_query_get_text (impl->search_query);
9171
9172       if (query)
9173         {
9174           gtk_entry_set_text (GTK_ENTRY (impl->search_entry), query);
9175           search_start_query (impl, query);
9176
9177           g_free (query);
9178         }
9179       else
9180         {
9181           g_object_unref (impl->search_query);
9182           impl->search_query = NULL;
9183         }
9184     }
9185
9186   /* Box for search widgets */
9187   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->search_hbox, TRUE, TRUE, 0);
9188   gtk_widget_show_all (impl->search_hbox);
9189   gtk_size_group_add_widget (GTK_SIZE_GROUP (impl->browse_path_bar_size_group), impl->search_hbox);
9190
9191   /* Hide the location widgets temporarily */
9192
9193   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9194       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9195     {
9196       gtk_widget_hide (impl->location_button);
9197       gtk_widget_hide (impl->location_entry_box);
9198     }
9199
9200   focus_search_entry_in_idle (impl);
9201
9202   /* FMQ: hide the filter combo? */
9203 }
9204
9205 /* Sometimes we need to frob the selection in the shortcuts list manually */
9206 static void
9207 shortcuts_select_item_without_activating (GtkFileChooserDefault *impl, int pos)
9208 {
9209   GtkTreeSelection *selection;
9210   GtkTreePath *path;
9211
9212   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view));
9213
9214   g_signal_handlers_block_by_func (selection, G_CALLBACK (shortcuts_selection_changed_cb), impl);
9215
9216   path = gtk_tree_path_new_from_indices (pos, -1);
9217   gtk_tree_selection_select_path (selection, path);
9218   gtk_tree_path_free (path);
9219
9220   g_signal_handlers_unblock_by_func (selection, G_CALLBACK (shortcuts_selection_changed_cb), impl);
9221 }
9222
9223 /* Main entry point to the searching functions; this gets called when the user
9224  * activates the Search shortcut.
9225  */
9226 static void
9227 search_activate (GtkFileChooserDefault *impl)
9228 {
9229   OperationMode previous_mode;
9230   
9231   if (impl->operation_mode == OPERATION_MODE_SEARCH)
9232     {
9233       focus_search_entry_in_idle (impl);
9234       return;
9235     }
9236
9237   previous_mode = impl->operation_mode;
9238   impl->operation_mode = OPERATION_MODE_SEARCH;
9239
9240   shortcuts_select_item_without_activating (impl, shortcuts_get_index (impl, SHORTCUTS_SEARCH));
9241
9242   operation_mode_stop (impl, previous_mode);
9243
9244   g_assert (impl->search_hbox == NULL);
9245   g_assert (impl->search_entry == NULL);
9246   g_assert (impl->search_model == NULL);
9247
9248   search_setup_widgets (impl);
9249   file_list_set_sort_column_ids (impl);
9250 }
9251
9252 /*
9253  * Recent files support
9254  */
9255
9256 /* Frees the data in the recent_model */
9257 static void
9258 recent_clear_model (GtkFileChooserDefault *impl,
9259                     gboolean               remove_from_treeview)
9260 {
9261   if (!impl->recent_model)
9262     return;
9263
9264   if (remove_from_treeview)
9265     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
9266
9267   g_object_unref (impl->recent_model);
9268   impl->recent_model = NULL;
9269 }
9270
9271 /* Stops any ongoing loading of the recent files list; does
9272  * not touch the recent_model
9273  */
9274 static void
9275 recent_stop_loading (GtkFileChooserDefault *impl)
9276 {
9277   if (impl->load_recent_id)
9278     {
9279       g_source_remove (impl->load_recent_id);
9280       impl->load_recent_id = 0;
9281     }
9282 }
9283
9284 /* Stops any pending load, clears the file list, and switches
9285  * back to OPERATION_MODE_BROWSE
9286  */
9287 static void
9288 recent_switch_to_browse_mode (GtkFileChooserDefault *impl)
9289 {
9290   g_assert (impl->operation_mode != OPERATION_MODE_BROWSE);
9291
9292   recent_stop_loading (impl);
9293   recent_clear_model (impl, TRUE);
9294
9295   impl->operation_mode = OPERATION_MODE_BROWSE;
9296   path_bar_update (impl);
9297
9298   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9299       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9300     {
9301       gtk_widget_show (impl->location_button);
9302
9303       if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
9304         gtk_widget_show (impl->location_entry_box);
9305     }
9306
9307   gtk_tree_view_column_set_visible (impl->list_size_column, impl->show_size_column);
9308
9309   file_list_set_sort_column_ids (impl);
9310 }
9311
9312 static void
9313 recent_setup_model (GtkFileChooserDefault *impl)
9314 {
9315   g_assert (impl->recent_model == NULL);
9316
9317   impl->recent_model = _gtk_file_system_model_new (file_system_model_set,
9318                                                    impl,
9319                                                    MODEL_COLUMN_TYPES);
9320
9321   _gtk_file_system_model_set_filter (impl->recent_model,
9322                                      impl->current_filter);
9323   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model),
9324                                    MODEL_COL_NAME,
9325                                    name_sort_func,
9326                                    impl, NULL);
9327   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model),
9328                                    MODEL_COL_SIZE,
9329                                    size_sort_func,
9330                                    impl, NULL);
9331   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model),
9332                                    MODEL_COL_MTIME,
9333                                    mtime_sort_func,
9334                                    impl, NULL);
9335   set_sort_column (impl);
9336 }
9337
9338 typedef struct
9339 {
9340   GtkFileChooserDefault *impl;
9341   GList *items;
9342   guint needs_sorting : 1;
9343 } RecentLoadData;
9344
9345 static void
9346 recent_idle_cleanup (gpointer data)
9347 {
9348   RecentLoadData *load_data = data;
9349   GtkFileChooserDefault *impl = load_data->impl;
9350
9351   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9352                            GTK_TREE_MODEL (impl->recent_model));
9353
9354   set_busy_cursor (impl, FALSE);
9355   
9356   impl->load_recent_id = 0;
9357   
9358   g_free (load_data);
9359 }
9360
9361 static gint
9362 recent_sort_mru (gconstpointer a,
9363                  gconstpointer b)
9364 {
9365   GtkRecentInfo *info_a = (GtkRecentInfo *) a;
9366   GtkRecentInfo *info_b = (GtkRecentInfo *) b;
9367
9368   return (gtk_recent_info_get_modified (info_b) - gtk_recent_info_get_modified (info_a));
9369 }
9370
9371 static gint
9372 get_recent_files_limit (GtkWidget *widget)
9373 {
9374   GtkSettings *settings;
9375   gint limit;
9376
9377   if (gtk_widget_has_screen (widget))
9378     settings = gtk_settings_get_for_screen (gtk_widget_get_screen (widget));
9379   else
9380     settings = gtk_settings_get_default ();
9381
9382   g_object_get (G_OBJECT (settings), "gtk-recent-files-limit", &limit, NULL);
9383
9384   return limit;
9385 }
9386
9387 /* Populates the file system model with the GtkRecentInfo* items in the provided list; frees the items */
9388 static void
9389 populate_model_with_recent_items (GtkFileChooserDefault *impl, GList *items)
9390 {
9391   gint limit;
9392   GList *l;
9393   int n;
9394
9395   limit = get_recent_files_limit (GTK_WIDGET (impl));
9396
9397   n = 0;
9398
9399   for (l = items; l; l = l->next)
9400     {
9401       GtkRecentInfo *info = l->data;
9402       GFile *file;
9403
9404       file = g_file_new_for_uri (gtk_recent_info_get_uri (info));
9405       _gtk_file_system_model_add_and_query_file (impl->recent_model,
9406                                                  file,
9407                                                  MODEL_ATTRIBUTES);
9408       g_object_unref (file);
9409
9410       n++;
9411       if (limit != -1 && n >= limit)
9412         break;
9413     }
9414 }
9415
9416 static void
9417 populate_model_with_folders (GtkFileChooserDefault *impl, GList *items)
9418 {
9419   GList *folders;
9420   GList *l;
9421
9422   folders = _gtk_file_chooser_extract_recent_folders (items);
9423
9424   for (l = folders; l; l = l->next)
9425     {
9426       GFile *folder = l->data;
9427
9428       _gtk_file_system_model_add_and_query_file (impl->recent_model,
9429                                                  folder,
9430                                                  MODEL_ATTRIBUTES);
9431     }
9432
9433   g_list_foreach (folders, (GFunc) g_object_unref, NULL);
9434   g_list_free (folders);
9435 }
9436
9437 static gboolean
9438 recent_idle_load (gpointer data)
9439 {
9440   RecentLoadData *load_data = data;
9441   GtkFileChooserDefault *impl = load_data->impl;
9442
9443   if (!impl->recent_manager)
9444     return FALSE;
9445
9446   /* first iteration: load all the items */
9447   if (!load_data->items)
9448     {
9449       load_data->items = gtk_recent_manager_get_items (impl->recent_manager);
9450       if (!load_data->items)
9451         return FALSE;
9452
9453       load_data->needs_sorting = TRUE;
9454
9455       return TRUE;
9456     }
9457   
9458   /* second iteration: MRU sorting and clamping, and populating the model */
9459   if (load_data->needs_sorting)
9460     {
9461       load_data->items = g_list_sort (load_data->items, recent_sort_mru);
9462
9463       if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
9464         populate_model_with_recent_items (impl, load_data->items);
9465       else
9466         populate_model_with_folders (impl, load_data->items);
9467
9468       g_list_foreach (load_data->items, (GFunc) gtk_recent_info_unref, NULL);
9469       g_list_free (load_data->items);
9470       load_data->items = NULL;
9471     }
9472
9473   return FALSE;
9474 }
9475
9476 static void
9477 recent_start_loading (GtkFileChooserDefault *impl)
9478 {
9479   RecentLoadData *load_data;
9480
9481   recent_stop_loading (impl);
9482   recent_clear_model (impl, TRUE);
9483   recent_setup_model (impl);
9484   set_busy_cursor (impl, TRUE);
9485
9486   g_assert (impl->load_recent_id == 0);
9487
9488   load_data = g_new (RecentLoadData, 1);
9489   load_data->impl = impl;
9490   load_data->items = NULL;
9491   load_data->needs_sorting = TRUE;
9492
9493   /* begin lazy loading the recent files into the model */
9494   impl->load_recent_id = gdk_threads_add_idle_full (G_PRIORITY_HIGH_IDLE + 30,
9495                                                     recent_idle_load,
9496                                                     load_data,
9497                                                     recent_idle_cleanup);
9498 }
9499
9500 static void
9501 recent_selected_foreach_get_file_cb (GtkTreeModel *model,
9502                                      GtkTreePath  *path,
9503                                      GtkTreeIter  *iter,
9504                                      gpointer      data)
9505 {
9506   GSList **list;
9507   GFile *file;
9508
9509   list = data;
9510
9511   gtk_tree_model_get (model, iter, MODEL_COL_FILE, &file, -1);
9512   *list = g_slist_prepend (*list, file);
9513 }
9514
9515 /* Constructs a list of the selected paths in recent files mode */
9516 static GSList *
9517 recent_get_selected_files (GtkFileChooserDefault *impl)
9518 {
9519   GSList *result;
9520   GtkTreeSelection *selection;
9521
9522   result = NULL;
9523
9524   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9525   gtk_tree_selection_selected_foreach (selection, recent_selected_foreach_get_file_cb, &result);
9526   result = g_slist_reverse (result);
9527
9528   return result;
9529 }
9530
9531 /* Called from ::should_respond().  We return whether there are selected
9532  * files in the recent files list.
9533  */
9534 static gboolean
9535 recent_should_respond (GtkFileChooserDefault *impl)
9536 {
9537   GtkTreeSelection *selection;
9538
9539   g_assert (impl->operation_mode == OPERATION_MODE_RECENT);
9540
9541   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9542   return (gtk_tree_selection_count_selected_rows (selection) != 0);
9543 }
9544
9545 /* Hide the location widgets temporarily */
9546 static void
9547 recent_hide_entry (GtkFileChooserDefault *impl)
9548 {
9549   path_bar_update (impl);
9550
9551   /* Hide the location widgets temporarily */
9552   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9553       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9554     {
9555       gtk_widget_hide (impl->location_button);
9556       gtk_widget_hide (impl->location_entry_box);
9557     }
9558 }
9559
9560 /* Main entry point to the recent files functions; this gets called when
9561  * the user activates the Recently Used shortcut.
9562  */
9563 static void
9564 recent_activate (GtkFileChooserDefault *impl)
9565 {
9566   OperationMode previous_mode;
9567
9568   if (impl->operation_mode == OPERATION_MODE_RECENT)
9569     return;
9570
9571   previous_mode = impl->operation_mode;
9572   impl->operation_mode = OPERATION_MODE_RECENT;
9573
9574   shortcuts_select_item_without_activating (impl, shortcuts_get_index (impl, SHORTCUTS_RECENT));
9575
9576   operation_mode_stop (impl, previous_mode);
9577
9578   recent_hide_entry (impl);
9579
9580   file_list_set_sort_column_ids (impl);
9581   recent_start_loading (impl);
9582 }
9583
9584 static void
9585 set_current_filter (GtkFileChooserDefault *impl,
9586                     GtkFileFilter         *filter)
9587 {
9588   if (impl->current_filter != filter)
9589     {
9590       int filter_index;
9591
9592       /* NULL filters are allowed to reset to non-filtered status
9593        */
9594       filter_index = g_slist_index (impl->filters, filter);
9595       if (impl->filters && filter && filter_index < 0)
9596         return;
9597
9598       if (impl->current_filter)
9599         g_object_unref (impl->current_filter);
9600       impl->current_filter = filter;
9601       if (impl->current_filter)
9602         {
9603           g_object_ref_sink (impl->current_filter);
9604         }
9605
9606       if (impl->filters)
9607         gtk_combo_box_set_active (GTK_COMBO_BOX (impl->filter_combo),
9608                                   filter_index);
9609
9610       if (impl->browse_files_model)
9611         install_list_model_filter (impl);
9612
9613       if (impl->search_model)
9614         _gtk_file_system_model_set_filter (impl->search_model, filter);
9615
9616       if (impl->recent_model)
9617         _gtk_file_system_model_set_filter (impl->recent_model, filter);
9618
9619       g_object_notify (G_OBJECT (impl), "filter");
9620     }
9621 }
9622
9623 static void
9624 filter_combo_changed (GtkComboBox           *combo_box,
9625                       GtkFileChooserDefault *impl)
9626 {
9627   gint new_index = gtk_combo_box_get_active (combo_box);
9628   GtkFileFilter *new_filter = g_slist_nth_data (impl->filters, new_index);
9629
9630   set_current_filter (impl, new_filter);
9631 }
9632
9633 static void
9634 check_preview_change (GtkFileChooserDefault *impl)
9635 {
9636   GtkTreePath *cursor_path;
9637   GFile *new_file;
9638   char *new_display_name;
9639   GtkTreeModel *model;
9640
9641   gtk_tree_view_get_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view), &cursor_path, NULL);
9642   model = gtk_tree_view_get_model (GTK_TREE_VIEW (impl->browse_files_tree_view));
9643   if (cursor_path)
9644     {
9645       GtkTreeIter iter;
9646
9647       gtk_tree_model_get_iter (model, &iter, cursor_path);
9648       gtk_tree_model_get (model, &iter,
9649                           MODEL_COL_FILE, &new_file,
9650                           MODEL_COL_NAME, &new_display_name,
9651                           -1);
9652       
9653       gtk_tree_path_free (cursor_path);
9654     }
9655   else
9656     {
9657       new_file = NULL;
9658       new_display_name = NULL;
9659     }
9660
9661   if (new_file != impl->preview_file &&
9662       !(new_file && impl->preview_file &&
9663         g_file_equal (new_file, impl->preview_file)))
9664     {
9665       if (impl->preview_file)
9666         {
9667           g_object_unref (impl->preview_file);
9668           g_free (impl->preview_display_name);
9669         }
9670
9671       if (new_file)
9672         {
9673           impl->preview_file = new_file;
9674           impl->preview_display_name = new_display_name;
9675         }
9676       else
9677         {
9678           impl->preview_file = NULL;
9679           impl->preview_display_name = NULL;
9680           g_free (new_display_name);
9681         }
9682
9683       if (impl->use_preview_label && impl->preview_label)
9684         gtk_label_set_text (GTK_LABEL (impl->preview_label), impl->preview_display_name);
9685
9686       g_signal_emit_by_name (impl, "update-preview");
9687     }
9688   else
9689     {
9690       if (new_file)
9691         g_object_unref (new_file);
9692
9693       g_free (new_display_name);
9694     }
9695 }
9696
9697 static void
9698 shortcuts_activate_volume_mount_cb (GCancellable        *cancellable,
9699                                     GtkFileSystemVolume *volume,
9700                                     const GError        *error,
9701                                     gpointer             data)
9702 {
9703   GFile *file;
9704   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
9705   GtkFileChooserDefault *impl = data;
9706
9707   if (cancellable != impl->shortcuts_activate_iter_cancellable)
9708     goto out;
9709
9710   impl->shortcuts_activate_iter_cancellable = NULL;
9711
9712   set_busy_cursor (impl, FALSE);
9713
9714   if (cancelled)
9715     goto out;
9716
9717   if (error)
9718     {
9719       if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED))
9720         {
9721           char *msg, *name;
9722
9723           name = _gtk_file_system_volume_get_display_name (volume);
9724           msg = g_strdup_printf (_("Could not mount %s"), name);
9725
9726           error_message (impl, msg, error->message);
9727
9728           g_free (msg);
9729           g_free (name);
9730         }
9731
9732       goto out;
9733     }
9734
9735   file = _gtk_file_system_volume_get_root (volume);
9736   if (file != NULL)
9737     {
9738       change_folder_and_display_error (impl, file, FALSE);
9739       g_object_unref (file);
9740     }
9741
9742 out:
9743   g_object_unref (impl);
9744   g_object_unref (cancellable);
9745 }
9746
9747
9748 /* Activates a volume by mounting it if necessary and then switching to its
9749  * base path.
9750  */
9751 static void
9752 shortcuts_activate_volume (GtkFileChooserDefault *impl,
9753                            GtkFileSystemVolume   *volume)
9754 {
9755   GFile *file;
9756
9757   switch (impl->operation_mode)
9758     {
9759     case OPERATION_MODE_BROWSE:
9760       break;
9761     case OPERATION_MODE_SEARCH:
9762       search_switch_to_browse_mode (impl);
9763       break;
9764     case OPERATION_MODE_RECENT:
9765       recent_switch_to_browse_mode (impl);
9766       break;
9767     }
9768
9769   /* We ref the file chooser since volume_mount() may run a main loop, and the
9770    * user could close the file chooser window in the meantime.
9771    */
9772   g_object_ref (impl);
9773
9774   if (!_gtk_file_system_volume_is_mounted (volume))
9775     {
9776       GMountOperation *mount_op;
9777
9778       set_busy_cursor (impl, TRUE);
9779    
9780       mount_op = gtk_mount_operation_new (get_toplevel (GTK_WIDGET (impl)));
9781       impl->shortcuts_activate_iter_cancellable =
9782         _gtk_file_system_mount_volume (impl->file_system, volume, mount_op,
9783                                        shortcuts_activate_volume_mount_cb,
9784                                        g_object_ref (impl));
9785       g_object_unref (mount_op);
9786     }
9787   else
9788     {
9789       file = _gtk_file_system_volume_get_root (volume);
9790       if (file != NULL)
9791         {
9792           change_folder_and_display_error (impl, file, FALSE);
9793           g_object_unref (file);
9794         }
9795     }
9796
9797   g_object_unref (impl);
9798 }
9799
9800 /* Opens the folder or volume at the specified iter in the shortcuts model */
9801 struct ShortcutsActivateData
9802 {
9803   GtkFileChooserDefault *impl;
9804   GFile *file;
9805 };
9806
9807 static void
9808 shortcuts_activate_get_info_cb (GCancellable *cancellable,
9809                                 GFileInfo    *info,
9810                                 const GError *error,
9811                                 gpointer      user_data)
9812 {
9813   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
9814   struct ShortcutsActivateData *data = user_data;
9815
9816   if (cancellable != data->impl->shortcuts_activate_iter_cancellable)
9817     goto out;
9818
9819   data->impl->shortcuts_activate_iter_cancellable = NULL;
9820
9821   if (cancelled)
9822     goto out;
9823
9824   if (!error && _gtk_file_info_consider_as_directory (info))
9825     change_folder_and_display_error (data->impl, data->file, FALSE);
9826   else
9827     gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (data->impl),
9828                                           data->file,
9829                                           NULL);
9830
9831 out:
9832   g_object_unref (data->impl);
9833   g_object_unref (data->file);
9834   g_free (data);
9835
9836   g_object_unref (cancellable);
9837 }
9838
9839 static void
9840 shortcuts_activate_mount_enclosing_volume (GCancellable        *cancellable,
9841                                            GtkFileSystemVolume *volume,
9842                                            const GError        *error,
9843                                            gpointer             user_data)
9844 {
9845   struct ShortcutsActivateData *data = user_data;
9846
9847   if (error)
9848     {
9849       error_changing_folder_dialog (data->impl, data->file, g_error_copy (error));
9850
9851       g_object_unref (data->impl);
9852       g_object_unref (data->file);
9853       g_free (data);
9854
9855       return;
9856     }
9857
9858   data->impl->shortcuts_activate_iter_cancellable =
9859     _gtk_file_system_get_info (data->impl->file_system, data->file,
9860                                "standard::type",
9861                                shortcuts_activate_get_info_cb, data);
9862
9863   if (volume)
9864     _gtk_file_system_volume_unref (volume);
9865 }
9866
9867 static void
9868 shortcuts_activate_iter (GtkFileChooserDefault *impl,
9869                          GtkTreeIter           *iter)
9870 {
9871   gpointer col_data;
9872   ShortcutType shortcut_type;
9873
9874   if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY
9875       && !(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
9876            || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
9877     _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
9878
9879   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), iter,
9880                       SHORTCUTS_COL_DATA, &col_data,
9881                       SHORTCUTS_COL_TYPE, &shortcut_type,
9882                       -1);
9883
9884   if (impl->shortcuts_activate_iter_cancellable)
9885     {
9886       g_cancellable_cancel (impl->shortcuts_activate_iter_cancellable);
9887       impl->shortcuts_activate_iter_cancellable = NULL;
9888     }
9889
9890   if (shortcut_type == SHORTCUT_TYPE_SEPARATOR)
9891     return;
9892   else if (shortcut_type == SHORTCUT_TYPE_VOLUME)
9893     {
9894       GtkFileSystemVolume *volume;
9895
9896       volume = col_data;
9897
9898       shortcuts_activate_volume (impl, volume);
9899     }
9900   else if (shortcut_type == SHORTCUT_TYPE_FILE)
9901     {
9902       struct ShortcutsActivateData *data;
9903       GtkFileSystemVolume *volume;
9904
9905       volume = _gtk_file_system_get_volume_for_file (impl->file_system, col_data);
9906
9907       data = g_new0 (struct ShortcutsActivateData, 1);
9908       data->impl = g_object_ref (impl);
9909       data->file = g_object_ref (col_data);
9910
9911       if (!volume || !_gtk_file_system_volume_is_mounted (volume))
9912         {
9913           GMountOperation *mount_operation;
9914           GtkWidget *toplevel;
9915
9916           toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
9917
9918           mount_operation = gtk_mount_operation_new (GTK_WINDOW (toplevel));
9919
9920           impl->shortcuts_activate_iter_cancellable =
9921             _gtk_file_system_mount_enclosing_volume (impl->file_system, col_data,
9922                                                      mount_operation,
9923                                                      shortcuts_activate_mount_enclosing_volume,
9924                                                      data);
9925         }
9926       else
9927         {
9928           impl->shortcuts_activate_iter_cancellable =
9929             _gtk_file_system_get_info (impl->file_system, data->file,
9930                                        "standard::type",
9931                                        shortcuts_activate_get_info_cb, data);
9932         }
9933     }
9934   else if (shortcut_type == SHORTCUT_TYPE_SEARCH)
9935     {
9936       search_activate (impl);
9937     }
9938   else if (shortcut_type == SHORTCUT_TYPE_RECENT)
9939     {
9940       recent_activate (impl);
9941     }
9942 }
9943
9944 /* Handler for GtkWidget::key-press-event on the shortcuts list */
9945 static gboolean
9946 shortcuts_key_press_event_cb (GtkWidget             *widget,
9947                               GdkEventKey           *event,
9948                               GtkFileChooserDefault *impl)
9949 {
9950   guint modifiers;
9951
9952   modifiers = gtk_accelerator_get_default_mod_mask ();
9953
9954   if (key_is_left_or_right (event))
9955     {
9956       gtk_widget_grab_focus (impl->browse_files_tree_view);
9957       return TRUE;
9958     }
9959
9960   if ((event->keyval == GDK_KEY_BackSpace
9961       || event->keyval == GDK_KEY_Delete
9962       || event->keyval == GDK_KEY_KP_Delete)
9963       && (event->state & modifiers) == 0)
9964     {
9965       remove_selected_bookmarks (impl);
9966       return TRUE;
9967     }
9968
9969   if ((event->keyval == GDK_KEY_F2)
9970       && (event->state & modifiers) == 0)
9971     {
9972       rename_selected_bookmark (impl);
9973       return TRUE;
9974     }
9975
9976   return FALSE;
9977 }
9978
9979 static gboolean
9980 shortcuts_select_func  (GtkTreeSelection  *selection,
9981                         GtkTreeModel      *model,
9982                         GtkTreePath       *path,
9983                         gboolean           path_currently_selected,
9984                         gpointer           data)
9985 {
9986   GtkFileChooserDefault *impl = data;
9987   GtkTreeIter filter_iter;
9988   ShortcutType shortcut_type;
9989
9990   if (!gtk_tree_model_get_iter (impl->shortcuts_pane_filter_model, &filter_iter, path))
9991     g_assert_not_reached ();
9992
9993   gtk_tree_model_get (impl->shortcuts_pane_filter_model, &filter_iter, SHORTCUTS_COL_TYPE, &shortcut_type, -1);
9994
9995   return shortcut_type != SHORTCUT_TYPE_SEPARATOR;
9996 }
9997
9998 static gboolean
9999 list_select_func  (GtkTreeSelection  *selection,
10000                    GtkTreeModel      *model,
10001                    GtkTreePath       *path,
10002                    gboolean           path_currently_selected,
10003                    gpointer           data)
10004 {
10005   GtkFileChooserDefault *impl = data;
10006
10007   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10008       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10009     {
10010       GtkTreeIter iter;
10011       gboolean is_folder;
10012
10013       if (!gtk_tree_model_get_iter (model, &iter, path))
10014         return FALSE;
10015       gtk_tree_model_get (model, &iter,
10016                           MODEL_COL_IS_FOLDER, &is_folder,
10017                           -1);
10018       if (!is_folder)
10019         return FALSE;
10020     }
10021     
10022   return TRUE;
10023 }
10024
10025 static void
10026 list_selection_changed (GtkTreeSelection      *selection,
10027                         GtkFileChooserDefault *impl)
10028 {
10029   /* See if we are in the new folder editable row for Save mode */
10030   if (impl->operation_mode == OPERATION_MODE_BROWSE &&
10031       impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
10032     {
10033       GFileInfo *info;
10034       gboolean had_selection;
10035
10036       info = get_selected_file_info_from_file_list (impl, &had_selection);
10037       if (!had_selection)
10038         goto out; /* normal processing */
10039
10040       if (!info)
10041         return; /* We are on the editable row for New Folder */
10042     }
10043
10044  out:
10045
10046   if (impl->location_entry)
10047     update_chooser_entry (impl);
10048
10049   path_bar_update (impl);
10050
10051   check_preview_change (impl);
10052   bookmarks_check_add_sensitivity (impl);
10053
10054   g_signal_emit_by_name (impl, "selection-changed", 0);
10055 }
10056
10057 /* Callback used when a row in the file list is activated */
10058 static void
10059 list_row_activated (GtkTreeView           *tree_view,
10060                     GtkTreePath           *path,
10061                     GtkTreeViewColumn     *column,
10062                     GtkFileChooserDefault *impl)
10063 {
10064   GFile *file;
10065   GtkTreeIter iter;
10066   GtkTreeModel *model;
10067   gboolean is_folder;
10068
10069   model = gtk_tree_view_get_model (tree_view);
10070
10071   if (!gtk_tree_model_get_iter (model, &iter, path))
10072     return;
10073
10074   gtk_tree_model_get (model, &iter,
10075                       MODEL_COL_FILE, &file,
10076                       MODEL_COL_IS_FOLDER, &is_folder,
10077                       -1);
10078         
10079   if (is_folder && file)
10080     {
10081       change_folder_and_display_error (impl, file, FALSE);
10082       g_object_unref (file);
10083       goto out;
10084     }
10085
10086   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
10087       impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
10088     g_signal_emit_by_name (impl, "file-activated");
10089
10090  out:
10091
10092   if (file)
10093     g_object_unref (file);
10094 }
10095
10096 static void
10097 path_bar_clicked (GtkPathBar            *path_bar,
10098                   GFile                 *file,
10099                   GFile                 *child_file,
10100                   gboolean               child_is_hidden,
10101                   GtkFileChooserDefault *impl)
10102 {
10103   if (child_file)
10104     pending_select_files_add (impl, child_file);
10105
10106   if (!change_folder_and_display_error (impl, file, FALSE))
10107     return;
10108
10109   /* Say we have "/foo/bar/[.baz]" and the user clicks on "bar".  We should then
10110    * show hidden files so that ".baz" appears in the file list, as it will still
10111    * be shown in the path bar: "/foo/[bar]/.baz"
10112    */
10113   if (child_is_hidden)
10114     g_object_set (impl, "show-hidden", TRUE, NULL);
10115 }
10116
10117 static void
10118 update_cell_renderer_attributes (GtkFileChooserDefault *impl)
10119 {
10120   GtkTreeViewColumn *column;
10121   GtkCellRenderer *renderer;
10122   GList *walk, *list;
10123   gboolean always_sensitive;
10124
10125   always_sensitive = impl->action != GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER &&
10126                      impl->action != GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER;
10127
10128   /* Keep the following column numbers in sync with create_file_list() */
10129
10130   /* name */
10131   column = gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_files_tree_view), 0);
10132   list = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (column));
10133   for (walk = list; walk; walk = walk->next)
10134     {
10135       renderer = walk->data;
10136       if (GTK_IS_CELL_RENDERER_PIXBUF (renderer))
10137         {
10138           gtk_tree_view_column_set_attributes (column, renderer, 
10139                                                "pixbuf", MODEL_COL_PIXBUF,
10140                                                NULL);
10141         }
10142       else
10143         {
10144           gtk_tree_view_column_set_attributes (column, renderer, 
10145                                                "text", MODEL_COL_NAME,
10146                                                "ellipsize", MODEL_COL_ELLIPSIZE,
10147                                                NULL);
10148         }
10149       if (always_sensitive)
10150         g_object_set (renderer, "sensitive", TRUE, NULL);
10151       else
10152         gtk_tree_view_column_add_attribute (column, renderer, "sensitive", MODEL_COL_IS_FOLDER);
10153     }
10154   g_list_free (list);
10155
10156   /* size */
10157   column = gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_files_tree_view), 1);
10158   list = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (column));
10159   renderer = list->data;
10160   gtk_tree_view_column_set_attributes (column, renderer, 
10161                                        "text", MODEL_COL_SIZE_TEXT,
10162                                        NULL);
10163   if (always_sensitive)
10164     g_object_set (renderer, "sensitive", TRUE, NULL);
10165   else
10166     gtk_tree_view_column_add_attribute (column, renderer, "sensitive", MODEL_COL_IS_FOLDER);
10167   g_list_free (list);
10168
10169   /* mtime */
10170   column = gtk_tree_view_get_column (GTK_TREE_VIEW (impl->browse_files_tree_view), 2);
10171   list = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (column));
10172   renderer = list->data;
10173   gtk_tree_view_column_set_attributes (column, renderer, 
10174                                        "text", MODEL_COL_MTIME_TEXT,
10175                                        NULL);
10176   if (always_sensitive)
10177     g_object_set (renderer, "sensitive", TRUE, NULL);
10178   else
10179     gtk_tree_view_column_add_attribute (column, renderer, "sensitive", MODEL_COL_IS_FOLDER);
10180   g_list_free (list);
10181 }
10182
10183 GtkWidget *
10184 _gtk_file_chooser_default_new (void)
10185 {
10186   return g_object_new (GTK_TYPE_FILE_CHOOSER_DEFAULT, NULL);
10187 }
10188
10189 static void
10190 location_set_user_text (GtkFileChooserDefault *impl,
10191                         const gchar           *path)
10192 {
10193   _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), path);
10194   gtk_editable_set_position (GTK_EDITABLE (impl->location_entry), -1);
10195 }
10196
10197 static void
10198 location_popup_handler (GtkFileChooserDefault *impl,
10199                         const gchar           *path)
10200
10201   if (impl->operation_mode != OPERATION_MODE_BROWSE)
10202     {
10203       GtkWidget *widget_to_focus;
10204       
10205       /* This will give us the location widgets back */
10206       switch (impl->operation_mode)
10207         {
10208         case OPERATION_MODE_SEARCH:
10209           search_switch_to_browse_mode (impl);
10210           break;
10211         case OPERATION_MODE_RECENT:
10212           recent_switch_to_browse_mode (impl);
10213           break;
10214         case OPERATION_MODE_BROWSE:
10215           g_assert_not_reached ();
10216           break;
10217         }
10218
10219       if (impl->current_folder)
10220         change_folder_and_display_error (impl, impl->current_folder, FALSE);
10221
10222       if (impl->location_mode == LOCATION_MODE_PATH_BAR)
10223         widget_to_focus = impl->browse_files_tree_view;
10224       else
10225         widget_to_focus = impl->location_entry;
10226
10227       gtk_widget_grab_focus (widget_to_focus);
10228       return; 
10229     }
10230   
10231   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
10232       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
10233     {
10234       LocationMode new_mode;
10235
10236       if (path != NULL)
10237         {
10238           /* since the user typed something, we unconditionally want to turn on the entry */
10239           new_mode = LOCATION_MODE_FILENAME_ENTRY;
10240         }
10241       else if (impl->location_mode == LOCATION_MODE_PATH_BAR)
10242         new_mode = LOCATION_MODE_FILENAME_ENTRY;
10243       else if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
10244         new_mode = LOCATION_MODE_PATH_BAR;
10245       else
10246         {
10247           g_assert_not_reached ();
10248           return;
10249         }
10250
10251       location_mode_set (impl, new_mode, TRUE);
10252       if (new_mode == LOCATION_MODE_FILENAME_ENTRY)
10253         {
10254           if (path != NULL)
10255             location_set_user_text (impl, path);
10256           else
10257             {
10258               location_entry_set_initial_text (impl);
10259               gtk_editable_select_region (GTK_EDITABLE (impl->location_entry), 0, -1);
10260             }
10261         }
10262     }
10263   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
10264            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10265     {
10266       gtk_widget_grab_focus (impl->location_entry);
10267       if (path != NULL)
10268         location_set_user_text (impl, path);
10269     }
10270   else
10271     g_assert_not_reached ();
10272 }
10273
10274 /* Handler for the "up-folder" keybinding signal */
10275 static void
10276 up_folder_handler (GtkFileChooserDefault *impl)
10277 {
10278   _gtk_path_bar_up (GTK_PATH_BAR (impl->browse_path_bar));
10279 }
10280
10281 /* Handler for the "down-folder" keybinding signal */
10282 static void
10283 down_folder_handler (GtkFileChooserDefault *impl)
10284 {
10285   _gtk_path_bar_down (GTK_PATH_BAR (impl->browse_path_bar));
10286 }
10287
10288 /* Switches to the shortcut in the specified index */
10289 static void
10290 switch_to_shortcut (GtkFileChooserDefault *impl,
10291                     int pos)
10292 {
10293   GtkTreeIter iter;
10294
10295   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
10296     g_assert_not_reached ();
10297
10298   shortcuts_activate_iter (impl, &iter);
10299 }
10300
10301 /* Handler for the "home-folder" keybinding signal */
10302 static void
10303 home_folder_handler (GtkFileChooserDefault *impl)
10304 {
10305   if (impl->has_home)
10306     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_HOME));
10307 }
10308
10309 /* Handler for the "desktop-folder" keybinding signal */
10310 static void
10311 desktop_folder_handler (GtkFileChooserDefault *impl)
10312 {
10313   if (impl->has_desktop)
10314     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_DESKTOP));
10315 }
10316
10317 /* Handler for the "search-shortcut" keybinding signal */
10318 static void
10319 search_shortcut_handler (GtkFileChooserDefault *impl)
10320 {
10321   if (impl->has_search)
10322     {
10323       switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_SEARCH));
10324
10325       /* we want the entry widget to grab the focus the first
10326        * time, not the browse_files_tree_view widget.
10327        */
10328       if (impl->search_entry)
10329         gtk_widget_grab_focus (impl->search_entry);
10330     }
10331 }
10332
10333 /* Handler for the "recent-shortcut" keybinding signal */
10334 static void
10335 recent_shortcut_handler (GtkFileChooserDefault *impl)
10336 {
10337   switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_RECENT));
10338 }
10339
10340 static void
10341 quick_bookmark_handler (GtkFileChooserDefault *impl,
10342                         gint bookmark_index)
10343 {
10344   int bookmark_pos;
10345   GtkTreePath *path;
10346
10347   if (bookmark_index < 0 || bookmark_index >= impl->num_bookmarks)
10348     return;
10349
10350   bookmark_pos = shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS) + bookmark_index;
10351
10352   path = gtk_tree_path_new_from_indices (bookmark_pos, -1);
10353   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view),
10354                                 path, NULL,
10355                                 FALSE, 0.0, 0.0);
10356   gtk_tree_path_free (path);
10357
10358   switch_to_shortcut (impl, bookmark_pos);
10359 }
10360
10361 static void
10362 show_hidden_handler (GtkFileChooserDefault *impl)
10363 {
10364   g_object_set (impl,
10365                 "show-hidden", !impl->show_hidden,
10366                 NULL);
10367 }
10368
10369
10370 /* Drag and drop interfaces */
10371
10372 static void
10373 _shortcuts_pane_model_filter_class_init (ShortcutsPaneModelFilterClass *class)
10374 {
10375 }
10376
10377 static void
10378 _shortcuts_pane_model_filter_init (ShortcutsPaneModelFilter *model)
10379 {
10380   model->impl = NULL;
10381 }
10382
10383 /* GtkTreeDragSource::row_draggable implementation for the shortcuts filter model */
10384 static gboolean
10385 shortcuts_pane_model_filter_row_draggable (GtkTreeDragSource *drag_source,
10386                                            GtkTreePath       *path)
10387 {
10388   ShortcutsPaneModelFilter *model;
10389   int pos;
10390   int bookmarks_pos;
10391
10392   model = SHORTCUTS_PANE_MODEL_FILTER (drag_source);
10393
10394   pos = *gtk_tree_path_get_indices (path);
10395   bookmarks_pos = shortcuts_get_index (model->impl, SHORTCUTS_BOOKMARKS);
10396
10397   return (pos >= bookmarks_pos && pos < bookmarks_pos + model->impl->num_bookmarks);
10398 }
10399
10400 /* GtkTreeDragSource::drag_data_get implementation for the shortcuts
10401  * filter model
10402  */
10403 static gboolean
10404 shortcuts_pane_model_filter_drag_data_get (GtkTreeDragSource *drag_source,
10405                                            GtkTreePath       *path,
10406                                            GtkSelectionData  *selection_data)
10407 {
10408   /* FIXME */
10409
10410   return FALSE;
10411 }
10412
10413 /* Fill the GtkTreeDragSourceIface vtable */
10414 static void
10415 shortcuts_pane_model_filter_drag_source_iface_init (GtkTreeDragSourceIface *iface)
10416 {
10417   iface->row_draggable = shortcuts_pane_model_filter_row_draggable;
10418   iface->drag_data_get = shortcuts_pane_model_filter_drag_data_get;
10419 }
10420
10421 #if 0
10422 /* Fill the GtkTreeDragDestIface vtable */
10423 static void
10424 shortcuts_pane_model_filter_drag_dest_iface_init (GtkTreeDragDestIface *iface)
10425 {
10426   iface->drag_data_received = shortcuts_pane_model_filter_drag_data_received;
10427   iface->row_drop_possible = shortcuts_pane_model_filter_row_drop_possible;
10428 }
10429 #endif
10430
10431 static GtkTreeModel *
10432 shortcuts_pane_model_filter_new (GtkFileChooserDefault *impl,
10433                                  GtkTreeModel          *child_model,
10434                                  GtkTreePath           *root)
10435 {
10436   ShortcutsPaneModelFilter *model;
10437
10438   model = g_object_new (SHORTCUTS_PANE_MODEL_FILTER_TYPE,
10439                         "child-model", child_model,
10440                         "virtual-root", root,
10441                         NULL);
10442
10443   model->impl = impl;
10444
10445   return GTK_TREE_MODEL (model);
10446 }
10447