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