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