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