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