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