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