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