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