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