]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilechooserdefault.c
remove some of the million includes.
[~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
6289   if (!impl->sort_model)
6290     return;
6291
6292   path = gtk_tree_path_new_from_indices (0, -1);
6293   gtk_tree_view_set_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view), path, NULL, FALSE);
6294   gtk_tree_path_free (path);
6295 }
6296
6297 struct center_selected_row_closure {
6298   GtkFileChooserDefault *impl;
6299   gboolean already_centered;
6300 };
6301
6302 /* Callback used from gtk_tree_selection_selected_foreach(); centers the
6303  * selected row in the tree view.
6304  */
6305 static void
6306 center_selected_row_foreach_cb (GtkTreeModel      *model,
6307                                 GtkTreePath       *path,
6308                                 GtkTreeIter       *iter,
6309                                 gpointer           data)
6310 {
6311   struct center_selected_row_closure *closure;
6312
6313   closure = data;
6314   if (closure->already_centered)
6315     return;
6316
6317   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (closure->impl->browse_files_tree_view), path, NULL, TRUE, 0.5, 0.0);
6318   closure->already_centered = TRUE;
6319 }
6320
6321 /* Centers the selected row in the tree view */
6322 static void
6323 browse_files_center_selected_row (GtkFileChooserDefault *impl)
6324 {
6325   struct center_selected_row_closure closure;
6326   GtkTreeSelection *selection;
6327
6328   closure.impl = impl;
6329   closure.already_centered = FALSE;
6330
6331   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6332   gtk_tree_selection_selected_foreach (selection, center_selected_row_foreach_cb, &closure);
6333 }
6334
6335 struct ShowAndSelectPathsData
6336 {
6337   GtkFileChooserDefault *impl;
6338   GSList *files;
6339 };
6340
6341 static void
6342 show_and_select_files_finished_loading (GtkFolder *folder,
6343                                         gpointer   user_data)
6344 {
6345   gboolean have_hidden;
6346   gboolean have_filtered;
6347   GSList *l;
6348   struct ShowAndSelectPathsData *data = user_data;
6349
6350   have_hidden = FALSE;
6351   have_filtered = FALSE;
6352
6353   for (l = data->files; l; l = l->next)
6354     {
6355       GFile *file;
6356       GFileInfo *info;
6357
6358       file = l->data;
6359
6360       info = _gtk_folder_get_info (folder, file);
6361       if (info)
6362         {
6363           if (!have_hidden)
6364             have_hidden = g_file_info_get_is_hidden (info);
6365
6366           if (!have_filtered)
6367             have_filtered = (g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY) &&
6368                              get_is_file_filtered (data->impl, file, info);
6369
6370           g_object_unref (info);
6371
6372           if (have_hidden && have_filtered)
6373             break; /* we now have all the information we need */
6374         }
6375     }
6376
6377   g_signal_handlers_disconnect_by_func (folder,
6378                                         show_and_select_files_finished_loading,
6379                                         user_data);
6380
6381   if (have_hidden)
6382     g_object_set (data->impl, "show-hidden", TRUE, NULL);
6383
6384   if (have_filtered)
6385     set_current_filter (data->impl, NULL);
6386
6387   for (l = data->files; l; l = l->next)
6388     {
6389       GFile *file;
6390
6391       file = l->data;
6392       _gtk_file_system_model_path_do (data->impl->browse_files_model, file,
6393                                       select_func, data->impl);
6394     }
6395
6396   browse_files_center_selected_row (data->impl);
6397
6398   g_object_unref (data->impl);
6399   g_slist_foreach (data->files, (GFunc) g_object_unref, NULL);
6400   g_slist_free (data->files);
6401   g_free (data);
6402 }
6403
6404 static void
6405 show_and_select_files_get_folder_cb (GCancellable *cancellable,
6406                                      GtkFolder    *folder,
6407                                      const GError *error,
6408                                      gpointer      user_data)
6409 {
6410   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
6411   struct ShowAndSelectPathsData *data = user_data;
6412
6413   if (data->impl->show_and_select_files_cancellable != cancellable)
6414     goto out;
6415
6416   data->impl->show_and_select_files_cancellable = NULL;
6417
6418   if (cancelled || error)
6419     goto out;
6420
6421   g_object_unref (cancellable);
6422
6423   if (_gtk_folder_is_finished_loading (folder))
6424     show_and_select_files_finished_loading (folder, user_data);
6425   else
6426     g_signal_connect (folder, "finished-loading",
6427                       G_CALLBACK (show_and_select_files_finished_loading),
6428                       user_data);
6429
6430   return;
6431
6432 out:
6433   g_object_unref (data->impl);
6434   g_slist_foreach (data->files, (GFunc) g_object_unref, NULL);
6435   g_slist_free (data->files);
6436   g_free (data);
6437
6438   g_object_unref (cancellable);
6439 }
6440
6441 static gboolean
6442 show_and_select_files (GtkFileChooserDefault *impl,
6443                        GFile                 *parent_file,
6444                        GSList                *files,
6445                        GError                **error)
6446 {
6447   struct ShowAndSelectPathsData *info;
6448
6449   profile_start ("start", NULL);
6450
6451   if (!files)
6452     {
6453       profile_end ("end", NULL);
6454       return TRUE;
6455     }
6456
6457   info = g_new (struct ShowAndSelectPathsData, 1);
6458   info->impl = g_object_ref (impl);
6459   info->files = g_slist_copy (files);
6460   g_slist_foreach (info->files, (GFunc) g_object_ref, NULL);
6461
6462   if (impl->show_and_select_files_cancellable)
6463     g_cancellable_cancel (impl->show_and_select_files_cancellable);
6464
6465   impl->show_and_select_files_cancellable =
6466     _gtk_file_system_get_folder (impl->file_system, parent_file,
6467                                  "standard::is-hidden,standard::type,standard::name",
6468                                  show_and_select_files_get_folder_cb, info);
6469
6470   profile_end ("end", NULL);
6471   return TRUE;
6472 }
6473
6474 /* Processes the pending operation when a folder is finished loading */
6475 static void
6476 pending_select_files_process (GtkFileChooserDefault *impl)
6477 {
6478   g_assert (impl->load_state == LOAD_FINISHED);
6479   g_assert (impl->browse_files_model != NULL);
6480   g_assert (impl->sort_model != NULL);
6481
6482   if (impl->pending_select_files)
6483     {
6484       /* NULL GError */
6485       show_and_select_files (impl, impl->current_folder, impl->pending_select_files, NULL);
6486       pending_select_files_free (impl);
6487       browse_files_center_selected_row (impl);
6488     }
6489   else
6490     {
6491       /* We only select the first row if the chooser is actually mapped ---
6492        * selecting the first row is to help the user when he is interacting with
6493        * the chooser, but sometimes a chooser works not on behalf of the user,
6494        * but rather on behalf of something else like GtkFileChooserButton.  In
6495        * that case, the chooser's selection should be what the caller expects,
6496        * as the user can't see that something else got selected.  See bug #165264.
6497        */
6498       if (GTK_WIDGET_MAPPED (impl) && impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
6499         browse_files_select_first_row (impl);
6500     }
6501
6502   g_assert (impl->pending_select_files == NULL);
6503 }
6504
6505 /* Callback used when the file system model finishes loading */
6506 static void
6507 browse_files_model_finished_loading_cb (GtkFileSystemModel    *model,
6508                                         GtkFileChooserDefault *impl)
6509 {
6510   profile_start ("start", NULL);
6511
6512   if (impl->load_state == LOAD_PRELOAD)
6513     {
6514       load_remove_timer (impl);
6515       load_set_model (impl);
6516     }
6517   else if (impl->load_state == LOAD_LOADING)
6518     {
6519       /* Nothing */
6520     }
6521   else
6522     {
6523       /* We can't g_assert_not_reached(), as something other than us may have
6524        *  initiated a folder reload.  See #165556.
6525        */
6526       profile_end ("end", NULL);
6527       return;
6528     }
6529
6530   g_assert (impl->load_timeout_id == 0);
6531
6532   impl->load_state = LOAD_FINISHED;
6533
6534   pending_select_files_process (impl);
6535   set_busy_cursor (impl, FALSE);
6536 #ifdef PROFILE_FILE_CHOOSER
6537   access ("MARK: *** FINISHED LOADING", F_OK);
6538 #endif
6539
6540   profile_end ("end", NULL);
6541 }
6542
6543 static void
6544 stop_loading_and_clear_list_model (GtkFileChooserDefault *impl)
6545 {
6546   load_remove_timer (impl); /* This changes the state to LOAD_EMPTY */
6547   
6548   if (impl->browse_files_model)
6549     {
6550       g_object_unref (impl->browse_files_model);
6551       impl->browse_files_model = NULL;
6552     }
6553
6554   if (impl->sort_model)
6555     {
6556       g_object_unref (impl->sort_model);
6557       impl->sort_model = NULL;
6558     }
6559   
6560   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
6561 }
6562
6563 /* Gets rid of the old list model and creates a new one for the current folder */
6564 static gboolean
6565 set_list_model (GtkFileChooserDefault *impl,
6566                 GError               **error)
6567 {
6568   g_assert (impl->current_folder != NULL);
6569
6570   profile_start ("start", NULL);
6571
6572   stop_loading_and_clear_list_model (impl);
6573
6574   set_busy_cursor (impl, TRUE);
6575   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
6576
6577   impl->browse_files_model = _gtk_file_system_model_new (impl->file_system,
6578                                                          impl->current_folder, 0,
6579                                                          "standard,time,thumbnail::*",
6580                                                          error);
6581   if (!impl->browse_files_model)
6582     {
6583       set_busy_cursor (impl, FALSE);
6584       profile_end ("end", NULL);
6585       return FALSE;
6586     }
6587
6588   load_setup_timer (impl); /* This changes the state to LOAD_PRELOAD */
6589
6590   g_signal_connect (impl->browse_files_model, "finished-loading",
6591                     G_CALLBACK (browse_files_model_finished_loading_cb), impl);
6592
6593   _gtk_file_system_model_set_show_hidden (impl->browse_files_model, impl->show_hidden);
6594
6595   install_list_model_filter (impl);
6596
6597   profile_end ("end", NULL);
6598
6599   return TRUE;
6600 }
6601
6602 struct update_chooser_entry_selected_foreach_closure {
6603   int num_selected;
6604   GtkTreeIter first_selected_iter;
6605 };
6606
6607 static gint
6608 compare_utf8_filenames (const gchar *a,
6609                         const gchar *b)
6610 {
6611   gchar *a_folded, *b_folded;
6612   gint retval;
6613
6614   a_folded = g_utf8_strdown (a, -1);
6615   b_folded = g_utf8_strdown (b, -1);
6616
6617   retval = strcmp (a_folded, b_folded);
6618
6619   g_free (a_folded);
6620   g_free (b_folded);
6621
6622   return retval;
6623 }
6624
6625 static void
6626 update_chooser_entry_selected_foreach (GtkTreeModel *model,
6627                                        GtkTreePath *path,
6628                                        GtkTreeIter *iter,
6629                                        gpointer data)
6630 {
6631   struct update_chooser_entry_selected_foreach_closure *closure;
6632
6633   closure = data;
6634   closure->num_selected++;
6635
6636   if (closure->num_selected == 1)
6637     closure->first_selected_iter = *iter;
6638 }
6639
6640 static void
6641 update_chooser_entry (GtkFileChooserDefault *impl)
6642 {
6643   GtkTreeSelection *selection;
6644   struct update_chooser_entry_selected_foreach_closure closure;
6645   const char *file_part;
6646
6647   /* no need to update the file chooser's entry if there's no entry */
6648   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
6649       impl->operation_mode == OPERATION_MODE_RECENT ||
6650       !impl->location_entry)
6651     return;
6652
6653   if (!(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
6654         || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
6655         || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
6656              || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
6657             && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)))
6658     return;
6659
6660   g_assert (impl->location_entry != NULL);
6661
6662   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
6663   closure.num_selected = 0;
6664   gtk_tree_selection_selected_foreach (selection, update_chooser_entry_selected_foreach, &closure);
6665
6666   file_part = NULL;
6667
6668   if (closure.num_selected == 0)
6669     {
6670       goto maybe_clear_entry;
6671     }
6672   else if (closure.num_selected == 1)
6673     {
6674       GtkTreeIter child_iter;
6675       
6676       if (impl->operation_mode == OPERATION_MODE_BROWSE)
6677         {
6678           GFileInfo *info;
6679           gboolean change_entry;
6680
6681           gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
6682                                                           &child_iter,
6683                                                           &closure.first_selected_iter);
6684
6685           info = _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
6686
6687           /* If the cursor moved to the row of the newly created folder, 
6688            * retrieving info will return NULL.
6689            */
6690           if (!info)
6691             return;
6692
6693           g_free (impl->browse_files_last_selected_name);
6694           impl->browse_files_last_selected_name =
6695             g_strdup (g_file_info_get_display_name (info));
6696
6697           if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
6698               impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
6699               impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
6700             {
6701               /* We don't want the name to change when clicking on a folder... */
6702               change_entry = (g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY);
6703             }
6704           else
6705             change_entry = TRUE; /* ... unless we are in SELECT_FOLDER mode */
6706
6707           if (change_entry)
6708             {
6709               _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), impl->browse_files_last_selected_name);
6710
6711               if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
6712                 _gtk_file_chooser_entry_select_filename (GTK_FILE_CHOOSER_ENTRY (impl->location_entry));
6713             }
6714
6715           return;
6716         }
6717     }
6718   else
6719     {
6720       g_assert (!(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
6721                   impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER));
6722
6723       /* Multiple selection, so just clear the entry. */
6724
6725       g_free (impl->browse_files_last_selected_name);
6726       impl->browse_files_last_selected_name = NULL;
6727
6728       _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
6729       return;
6730     }
6731
6732  maybe_clear_entry:
6733
6734   if ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
6735       && impl->browse_files_last_selected_name)
6736     {
6737       const char *entry_text;
6738       int len;
6739       gboolean clear_entry;
6740
6741       entry_text = gtk_entry_get_text (GTK_ENTRY (impl->location_entry));
6742       len = strlen (entry_text);
6743       if (len != 0)
6744         {
6745           /* The file chooser entry may have appended a "/" to its text.  So
6746            * take it out, and compare the result to the old selection.
6747            */
6748           if (entry_text[len - 1] == G_DIR_SEPARATOR)
6749             {
6750               char *tmp;
6751
6752               tmp = g_strndup (entry_text, len - 1);
6753               clear_entry = (compare_utf8_filenames (impl->browse_files_last_selected_name, tmp) == 0);
6754               g_free (tmp);
6755             }
6756           else
6757             clear_entry = (compare_utf8_filenames (impl->browse_files_last_selected_name, entry_text) == 0);
6758         }
6759       else
6760         clear_entry = FALSE;
6761
6762       if (clear_entry)
6763         _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
6764     }
6765 }
6766
6767 static gboolean
6768 gtk_file_chooser_default_set_current_folder (GtkFileChooser  *chooser,
6769                                              GFile           *file,
6770                                              GError         **error)
6771 {
6772   return gtk_file_chooser_default_update_current_folder (chooser, file, FALSE, FALSE, error);
6773 }
6774
6775
6776 struct UpdateCurrentFolderData
6777 {
6778   GtkFileChooserDefault *impl;
6779   GFile *file;
6780   gboolean keep_trail;
6781   gboolean clear_entry;
6782   GFile *original_file;
6783   GError *original_error;
6784 };
6785
6786 static void
6787 update_current_folder_get_info_cb (GCancellable *cancellable,
6788                                    GFileInfo    *info,
6789                                    const GError *error,
6790                                    gpointer      user_data)
6791 {
6792   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
6793   struct UpdateCurrentFolderData *data = user_data;
6794   GtkFileChooserDefault *impl = data->impl;
6795
6796   if (cancellable != impl->update_current_folder_cancellable)
6797     goto out;
6798
6799   impl->update_current_folder_cancellable = NULL;
6800   impl->reload_state = RELOAD_EMPTY;
6801
6802   set_busy_cursor (impl, FALSE);
6803
6804   if (cancelled)
6805     goto out;
6806
6807   if (error)
6808     {
6809       GFile *parent_file;
6810
6811       if (!data->original_file)
6812         {
6813           data->original_file = g_object_ref (data->file);
6814           data->original_error = g_error_copy (error);
6815         }
6816
6817       parent_file = g_file_get_parent (data->file);
6818
6819       /* get parent path and try to change the folder to that */
6820       if (parent_file)
6821         {
6822           g_object_unref (data->file);
6823           data->file = parent_file;
6824
6825           g_object_unref (cancellable);
6826
6827           /* restart the update current folder operation */
6828           impl->reload_state = RELOAD_HAS_FOLDER;
6829
6830           impl->update_current_folder_cancellable =
6831             _gtk_file_system_get_info (impl->file_system, data->file,
6832                                        "standard::type",
6833                                        update_current_folder_get_info_cb,
6834                                        data);
6835
6836           set_busy_cursor (impl, TRUE);
6837
6838           return;
6839         }
6840       else
6841         {
6842           /* error and bail out */
6843           error_changing_folder_dialog (impl, data->original_file, data->original_error);
6844           g_object_unref (data->original_file);
6845
6846           goto out;
6847         }
6848     }
6849
6850   if (data->original_file)
6851     {
6852       error_changing_folder_dialog (impl, data->original_file, data->original_error);
6853
6854       g_object_unref (data->original_file);
6855     }
6856
6857   if (g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY)
6858     goto out;
6859
6860   if (!_gtk_path_bar_set_file (GTK_PATH_BAR (impl->browse_path_bar), data->file, data->keep_trail, NULL))
6861     goto out;
6862
6863   if (impl->current_folder != data->file)
6864     {
6865       if (impl->current_folder)
6866         g_object_unref (impl->current_folder);
6867
6868       impl->current_folder = g_object_ref (data->file);
6869
6870       impl->reload_state = RELOAD_HAS_FOLDER;
6871     }
6872
6873   /* Update the widgets that may trigger a folder change themselves.  */
6874
6875   if (!impl->changing_folder)
6876     {
6877       impl->changing_folder = TRUE;
6878
6879       shortcuts_update_current_folder (impl);
6880
6881       impl->changing_folder = FALSE;
6882     }
6883
6884   /* Set the folder on the save entry */
6885
6886   if (impl->location_entry)
6887     {
6888       _gtk_file_chooser_entry_set_base_folder (GTK_FILE_CHOOSER_ENTRY (impl->location_entry),
6889                                                impl->current_folder);
6890
6891       if (data->clear_entry)
6892         _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
6893     }
6894
6895   /* Create a new list model.  This is slightly evil; we store the result value
6896    * but perform more actions rather than returning immediately even if it
6897    * generates an error.
6898    */
6899   set_list_model (impl, NULL);
6900
6901   /* Refresh controls */
6902
6903   shortcuts_find_current_folder (impl);
6904
6905   g_signal_emit_by_name (impl, "current-folder-changed", 0);
6906
6907   check_preview_change (impl);
6908   bookmarks_check_add_sensitivity (impl);
6909
6910   g_signal_emit_by_name (impl, "selection-changed", 0);
6911
6912 out:
6913   g_object_unref (data->file);
6914   g_free (data);
6915
6916   g_object_unref (cancellable);
6917 }
6918
6919 static gboolean
6920 gtk_file_chooser_default_update_current_folder (GtkFileChooser    *chooser,
6921                                                 GFile             *file,
6922                                                 gboolean           keep_trail,
6923                                                 gboolean           clear_entry,
6924                                                 GError           **error)
6925 {
6926   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
6927   struct UpdateCurrentFolderData *data;
6928
6929   profile_start ("start", NULL);
6930
6931   g_object_ref (file);
6932
6933   switch (impl->operation_mode)
6934     {
6935     case OPERATION_MODE_SEARCH:
6936       search_switch_to_browse_mode (impl);
6937       break;
6938     case OPERATION_MODE_RECENT:
6939       recent_switch_to_browse_mode (impl);
6940       break;
6941     case OPERATION_MODE_BROWSE:
6942       break;
6943     }
6944
6945   if (impl->local_only && !g_file_is_native (file))
6946     {
6947       g_set_error_literal (error,
6948                            GTK_FILE_CHOOSER_ERROR,
6949                            GTK_FILE_CHOOSER_ERROR_BAD_FILENAME,
6950                            _("Cannot change to folder because it is not local"));
6951
6952       g_object_unref (file);
6953       profile_end ("end - not local", NULL);
6954       return FALSE;
6955     }
6956
6957   if (impl->update_current_folder_cancellable)
6958     g_cancellable_cancel (impl->update_current_folder_cancellable);
6959
6960   /* Test validity of path here.  */
6961   data = g_new0 (struct UpdateCurrentFolderData, 1);
6962   data->impl = impl;
6963   data->file = g_object_ref (file);
6964   data->keep_trail = keep_trail;
6965   data->clear_entry = clear_entry;
6966
6967   impl->reload_state = RELOAD_HAS_FOLDER;
6968
6969   impl->update_current_folder_cancellable =
6970     _gtk_file_system_get_info (impl->file_system, file,
6971                                "standard::type",
6972                                update_current_folder_get_info_cb,
6973                                data);
6974
6975   set_busy_cursor (impl, TRUE);
6976   g_object_unref (file);
6977
6978   profile_end ("end", NULL);
6979   return TRUE;
6980 }
6981
6982 static GFile *
6983 gtk_file_chooser_default_get_current_folder (GtkFileChooser *chooser)
6984 {
6985   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
6986
6987   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
6988       impl->operation_mode == OPERATION_MODE_RECENT)
6989     return NULL;
6990  
6991   if (impl->reload_state == RELOAD_EMPTY)
6992     {
6993       char *current_working_dir;
6994       GFile *file;
6995
6996       /* We are unmapped, or we had an error while loading the last folder.  We'll return
6997        * the $cwd since once we get (re)mapped, we'll load $cwd anyway unless the caller
6998        * explicitly calls set_current_folder() on us.
6999        */
7000       current_working_dir = g_get_current_dir ();
7001       file = g_file_new_for_path (current_working_dir);
7002       g_free (current_working_dir);
7003       return file;
7004     }
7005
7006   if (impl->current_folder)
7007     return g_object_ref (impl->current_folder);
7008
7009   return NULL;
7010 }
7011
7012 static void
7013 gtk_file_chooser_default_set_current_name (GtkFileChooser *chooser,
7014                                            const gchar    *name)
7015 {
7016   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7017
7018   g_return_if_fail (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7019                     impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
7020
7021   pending_select_files_free (impl);
7022   _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), name);
7023 }
7024
7025 static void
7026 select_func (GtkFileSystemModel *model,
7027              GtkTreePath        *path,
7028              GtkTreeIter        *iter,
7029              gpointer            user_data)
7030 {
7031   GtkFileChooserDefault *impl = user_data;
7032   GtkTreeSelection *selection;
7033   GtkTreeIter sorted_iter;
7034
7035   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7036
7037   gtk_tree_model_sort_convert_child_iter_to_iter (impl->sort_model, &sorted_iter, iter);
7038   gtk_tree_selection_select_iter (selection, &sorted_iter);
7039 }
7040
7041 static gboolean
7042 gtk_file_chooser_default_select_file (GtkFileChooser  *chooser,
7043                                       GFile           *file,
7044                                       GError         **error)
7045 {
7046   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7047   GFile *parent_file;
7048   gboolean same_path;
7049
7050   parent_file = g_file_get_parent (file);
7051
7052   if (!parent_file)
7053     return _gtk_file_chooser_set_current_folder_file (chooser, file, error);
7054
7055   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7056       impl->operation_mode == OPERATION_MODE_RECENT ||
7057       impl->load_state == LOAD_EMPTY)
7058     {
7059       same_path = FALSE;
7060     }
7061   else
7062     {
7063       g_assert (impl->current_folder != NULL);
7064
7065       same_path = g_file_equal (parent_file, impl->current_folder);
7066     }
7067
7068   if (same_path && impl->load_state == LOAD_FINISHED)
7069     {
7070       gboolean result;
7071       GSList files;
7072
7073       files.data = (gpointer) file;
7074       files.next = NULL;
7075
7076       result = show_and_select_files (impl, parent_file, &files, error);
7077       g_object_unref (parent_file);
7078       return result;
7079     }
7080
7081   pending_select_files_add (impl, file);
7082
7083   if (!same_path)
7084     {
7085       gboolean result;
7086
7087       result = _gtk_file_chooser_set_current_folder_file (chooser, parent_file, error);
7088       g_object_unref (parent_file);
7089       return result;
7090     }
7091
7092   g_object_unref (parent_file);
7093   return TRUE;
7094 }
7095
7096 static void
7097 unselect_func (GtkFileSystemModel *model,
7098                GtkTreePath        *path,
7099                GtkTreeIter        *iter,
7100                gpointer            user_data)
7101 {
7102   GtkFileChooserDefault *impl = user_data;
7103   GtkTreeView *tree_view = GTK_TREE_VIEW (impl->browse_files_tree_view);
7104   GtkTreePath *sorted_path;
7105
7106   sorted_path = gtk_tree_model_sort_convert_child_path_to_path (impl->sort_model,
7107                                                                 path);
7108   gtk_tree_selection_unselect_path (gtk_tree_view_get_selection (tree_view),
7109                                     sorted_path);
7110   gtk_tree_path_free (sorted_path);
7111 }
7112
7113 static void
7114 gtk_file_chooser_default_unselect_file (GtkFileChooser *chooser,
7115                                         GFile          *file)
7116 {
7117   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7118
7119   if (!impl->browse_files_model)
7120     return;
7121
7122   _gtk_file_system_model_path_do (impl->browse_files_model, file,
7123                                   unselect_func, impl);
7124 }
7125
7126 static gboolean
7127 maybe_select (GtkTreeModel *model, 
7128               GtkTreePath  *path, 
7129               GtkTreeIter  *iter, 
7130               gpointer     data)
7131 {
7132   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (data);
7133   GtkTreeSelection *selection;
7134   GFileInfo *info;
7135   gboolean is_folder;
7136   
7137   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7138   
7139   info = get_list_file_info (impl, iter);
7140   is_folder = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
7141
7142   if ((is_folder && impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER) ||
7143       (!is_folder && impl->action == GTK_FILE_CHOOSER_ACTION_OPEN))
7144     gtk_tree_selection_select_iter (selection, iter);
7145   else
7146     gtk_tree_selection_unselect_iter (selection, iter);
7147     
7148   return FALSE;
7149 }
7150
7151 static void
7152 gtk_file_chooser_default_select_all (GtkFileChooser *chooser)
7153 {
7154   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7155
7156   if (impl->operation_mode == OPERATION_MODE_SEARCH ||
7157       impl->operation_mode == OPERATION_MODE_RECENT)
7158     {
7159       GtkTreeSelection *selection;
7160       
7161       selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7162       gtk_tree_selection_select_all (selection);
7163       return;
7164     }
7165
7166   if (impl->select_multiple)
7167     gtk_tree_model_foreach (GTK_TREE_MODEL (impl->sort_model), 
7168                             maybe_select, impl);
7169 }
7170
7171 static void
7172 gtk_file_chooser_default_unselect_all (GtkFileChooser *chooser)
7173 {
7174   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7175   GtkTreeSelection *selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7176
7177   gtk_tree_selection_unselect_all (selection);
7178   pending_select_files_free (impl);
7179 }
7180
7181 /* Checks whether the filename entry for the Save modes contains a well-formed filename.
7182  *
7183  * is_well_formed_ret - whether what the user typed passes gkt_file_system_make_path()
7184  *
7185  * is_empty_ret - whether the file entry is totally empty
7186  *
7187  * is_file_part_empty_ret - whether the file part is empty (will be if user types "foobar/", and
7188  *                          the path will be "$cwd/foobar")
7189  */
7190 static void
7191 check_save_entry (GtkFileChooserDefault *impl,
7192                   GFile                **file_ret,
7193                   gboolean              *is_well_formed_ret,
7194                   gboolean              *is_empty_ret,
7195                   gboolean              *is_file_part_empty_ret,
7196                   gboolean              *is_folder)
7197 {
7198   GtkFileChooserEntry *chooser_entry;
7199   GFile *current_folder;
7200   const char *file_part;
7201   GFile *file;
7202   GError *error;
7203
7204   g_assert (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
7205             || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
7206             || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
7207                  || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
7208                 && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY));
7209
7210   chooser_entry = GTK_FILE_CHOOSER_ENTRY (impl->location_entry);
7211
7212   if (strlen (gtk_entry_get_text (GTK_ENTRY (chooser_entry))) == 0)
7213     {
7214       *file_ret = NULL;
7215       *is_well_formed_ret = TRUE;
7216       *is_empty_ret = TRUE;
7217       *is_file_part_empty_ret = TRUE;
7218       *is_folder = FALSE;
7219
7220       return;
7221     }
7222
7223   *is_empty_ret = FALSE;
7224
7225   current_folder = _gtk_file_chooser_entry_get_current_folder (chooser_entry);
7226   if (!current_folder)
7227     {
7228       *file_ret = NULL;
7229       *is_well_formed_ret = FALSE;
7230       *is_file_part_empty_ret = FALSE;
7231       *is_folder = FALSE;
7232
7233       return;
7234     }
7235
7236   file_part = _gtk_file_chooser_entry_get_file_part (chooser_entry);
7237
7238   if (!file_part || file_part[0] == '\0')
7239     {
7240       *file_ret = g_object_ref (current_folder);
7241       *is_well_formed_ret = TRUE;
7242       *is_file_part_empty_ret = TRUE;
7243       *is_folder = TRUE;
7244
7245       return;
7246     }
7247
7248   *is_file_part_empty_ret = FALSE;
7249
7250   error = NULL;
7251   file = g_file_get_child_for_display_name (current_folder, file_part, &error);
7252
7253   if (!file)
7254     {
7255       error_building_filename_dialog (impl, error);
7256       *file_ret = NULL;
7257       *is_well_formed_ret = FALSE;
7258       *is_folder = FALSE;
7259
7260       return;
7261     }
7262
7263   *file_ret = file;
7264   *is_well_formed_ret = TRUE;
7265   *is_folder = _gtk_file_chooser_entry_get_is_folder (chooser_entry, file);
7266 }
7267
7268 struct get_files_closure {
7269   GtkFileChooserDefault *impl;
7270   GSList *result;
7271   GFile *file_from_entry;
7272 };
7273
7274 static void
7275 get_files_foreach (GtkTreeModel *model,
7276                    GtkTreePath  *path,
7277                    GtkTreeIter  *iter,
7278                    gpointer      data)
7279 {
7280   struct get_files_closure *info;
7281   GFile *file;
7282   GtkFileSystemModel *fs_model;
7283   GtkTreeIter sel_iter;
7284
7285   info = data;
7286   fs_model = info->impl->browse_files_model;
7287   gtk_tree_model_sort_convert_iter_to_child_iter (info->impl->sort_model, &sel_iter, iter);
7288
7289   file = _gtk_file_system_model_get_file (fs_model, &sel_iter);
7290   if (!file)
7291     return; /* We are on the editable row */
7292
7293   if (!info->file_from_entry || !g_file_equal (info->file_from_entry, file))
7294     info->result = g_slist_prepend (info->result, g_object_ref (file));
7295 }
7296
7297 static GSList *
7298 gtk_file_chooser_default_get_files (GtkFileChooser *chooser)
7299 {
7300   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7301   struct get_files_closure info;
7302   GtkWindow *toplevel;
7303   GtkWidget *current_focus;
7304   gboolean file_list_seen;
7305
7306   if (impl->operation_mode == OPERATION_MODE_SEARCH)
7307     return search_get_selected_files (impl);
7308
7309   if (impl->operation_mode == OPERATION_MODE_RECENT)
7310     return recent_get_selected_files (impl);
7311
7312   info.impl = impl;
7313   info.result = NULL;
7314   info.file_from_entry = NULL;
7315
7316   toplevel = get_toplevel (GTK_WIDGET (impl));
7317   if (toplevel)
7318     current_focus = gtk_window_get_focus (toplevel);
7319   else
7320     current_focus = NULL;
7321
7322   file_list_seen = FALSE;
7323   if (current_focus == impl->browse_files_tree_view)
7324     {
7325       GtkTreeSelection *selection;
7326
7327     file_list:
7328
7329       file_list_seen = TRUE;
7330       selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7331       gtk_tree_selection_selected_foreach (selection, get_files_foreach, &info);
7332
7333       /* If there is no selection in the file list, we probably have this situation:
7334        *
7335        * 1. The user typed a filename in the SAVE filename entry ("foo.txt").
7336        * 2. He then double-clicked on a folder ("bar") in the file list
7337        *
7338        * So we want the selection to be "bar/foo.txt".  Jump to the case for the
7339        * filename entry to see if that is the case.
7340        */
7341       if (info.result == NULL && impl->location_entry)
7342         goto file_entry;
7343     }
7344   else if (impl->location_entry && current_focus == impl->location_entry)
7345     {
7346       gboolean is_well_formed, is_empty, is_file_part_empty, is_folder;
7347
7348     file_entry:
7349
7350       check_save_entry (impl, &info.file_from_entry, &is_well_formed, &is_empty, &is_file_part_empty, &is_folder);
7351
7352       if (is_empty)
7353         goto out;
7354
7355       if (!is_well_formed)
7356         return NULL;
7357
7358       if (is_file_part_empty && impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
7359         {
7360           g_object_unref (info.file_from_entry);
7361           return NULL;
7362         }
7363
7364       if (info.file_from_entry)
7365         info.result = g_slist_prepend (info.result, info.file_from_entry);
7366       else if (!file_list_seen) 
7367         goto file_list;
7368       else
7369         return NULL;
7370     }
7371   else if (impl->toplevel_last_focus_widget == impl->browse_files_tree_view)
7372     goto file_list;
7373   else if (impl->location_entry && impl->toplevel_last_focus_widget == impl->location_entry)
7374     goto file_entry;
7375   else
7376     {
7377       /* The focus is on a dialog's action area button or something else */
7378       if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
7379           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
7380         goto file_entry;
7381       else
7382         goto file_list; 
7383     }
7384
7385  out:
7386
7387   /* If there's no folder selected, and we're in SELECT_FOLDER mode, then we
7388    * fall back to the current directory */
7389   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER &&
7390       info.result == NULL)
7391     {
7392       GFile *current_folder;
7393
7394       current_folder = _gtk_file_chooser_get_current_folder_file (chooser);
7395
7396       if (current_folder)
7397         info.result = g_slist_prepend (info.result, current_folder);
7398     }
7399
7400   return g_slist_reverse (info.result);
7401 }
7402
7403 static GFile *
7404 gtk_file_chooser_default_get_preview_file (GtkFileChooser *chooser)
7405 {
7406   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7407
7408   if (impl->preview_file)
7409     return g_object_ref (impl->preview_file);
7410   else
7411     return NULL;
7412 }
7413
7414 static GtkFileSystem *
7415 gtk_file_chooser_default_get_file_system (GtkFileChooser *chooser)
7416 {
7417   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7418
7419   return impl->file_system;
7420 }
7421
7422 /* Shows or hides the filter widgets */
7423 static void
7424 show_filters (GtkFileChooserDefault *impl,
7425               gboolean               show)
7426 {
7427   if (show)
7428     gtk_widget_show (impl->filter_combo_hbox);
7429   else
7430     gtk_widget_hide (impl->filter_combo_hbox);
7431 }
7432
7433 static void
7434 gtk_file_chooser_default_add_filter (GtkFileChooser *chooser,
7435                                      GtkFileFilter  *filter)
7436 {
7437   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7438   const gchar *name;
7439
7440   if (g_slist_find (impl->filters, filter))
7441     {
7442       g_warning ("gtk_file_chooser_add_filter() called on filter already in list\n");
7443       return;
7444     }
7445
7446   g_object_ref_sink (filter);
7447   impl->filters = g_slist_append (impl->filters, filter);
7448
7449   name = gtk_file_filter_get_name (filter);
7450   if (!name)
7451     name = "Untitled filter";   /* Place-holder, doesn't need to be marked for translation */
7452
7453   gtk_combo_box_append_text (GTK_COMBO_BOX (impl->filter_combo), name);
7454
7455   if (!g_slist_find (impl->filters, impl->current_filter))
7456     set_current_filter (impl, filter);
7457
7458   show_filters (impl, TRUE);
7459 }
7460
7461 static void
7462 gtk_file_chooser_default_remove_filter (GtkFileChooser *chooser,
7463                                         GtkFileFilter  *filter)
7464 {
7465   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7466   GtkTreeModel *model;
7467   GtkTreeIter iter;
7468   gint filter_index;
7469
7470   filter_index = g_slist_index (impl->filters, filter);
7471
7472   if (filter_index < 0)
7473     {
7474       g_warning ("gtk_file_chooser_remove_filter() called on filter not in list\n");
7475       return;
7476     }
7477
7478   impl->filters = g_slist_remove (impl->filters, filter);
7479
7480   if (filter == impl->current_filter)
7481     {
7482       if (impl->filters)
7483         set_current_filter (impl, impl->filters->data);
7484       else
7485         set_current_filter (impl, NULL);
7486     }
7487
7488   /* Remove row from the combo box */
7489   model = gtk_combo_box_get_model (GTK_COMBO_BOX (impl->filter_combo));
7490   if (!gtk_tree_model_iter_nth_child  (model, &iter, NULL, filter_index))
7491     g_assert_not_reached ();
7492
7493   gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
7494
7495   g_object_unref (filter);
7496
7497   if (!impl->filters)
7498     show_filters (impl, FALSE);
7499 }
7500
7501 static GSList *
7502 gtk_file_chooser_default_list_filters (GtkFileChooser *chooser)
7503 {
7504   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7505
7506   return g_slist_copy (impl->filters);
7507 }
7508
7509 /* Returns the position in the shortcuts tree where the nth specified shortcut would appear */
7510 static int
7511 shortcuts_get_pos_for_shortcut_folder (GtkFileChooserDefault *impl,
7512                                        int                    pos)
7513 {
7514   return pos + shortcuts_get_index (impl, SHORTCUTS_SHORTCUTS);
7515 }
7516
7517 struct AddShortcutData
7518 {
7519   GtkFileChooserDefault *impl;
7520   GFile *file;
7521 };
7522
7523 static void
7524 add_shortcut_get_info_cb (GCancellable *cancellable,
7525                           GFileInfo    *info,
7526                           const GError *error,
7527                           gpointer      user_data)
7528 {
7529   int pos;
7530   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
7531   struct AddShortcutData *data = user_data;
7532
7533   if (!g_slist_find (data->impl->loading_shortcuts, cancellable))
7534     goto out;
7535
7536   data->impl->loading_shortcuts = g_slist_remove (data->impl->loading_shortcuts, cancellable);
7537
7538   if (cancelled || error || g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY)
7539     goto out;
7540
7541   pos = shortcuts_get_pos_for_shortcut_folder (data->impl, data->impl->num_shortcuts);
7542
7543   shortcuts_insert_file (data->impl, pos, SHORTCUT_TYPE_FILE, NULL, data->file, NULL, FALSE, SHORTCUTS_SHORTCUTS);
7544
7545 out:
7546   g_object_unref (data->impl);
7547   g_object_unref (data->file);
7548   g_free (data);
7549
7550   g_object_unref (cancellable);
7551 }
7552
7553 static gboolean
7554 gtk_file_chooser_default_add_shortcut_folder (GtkFileChooser  *chooser,
7555                                               GFile           *file,
7556                                               GError         **error)
7557 {
7558   GCancellable *cancellable;
7559   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7560   struct AddShortcutData *data;
7561   GSList *l;
7562   int pos;
7563
7564   /* Avoid adding duplicates */
7565   pos = shortcut_find_position (impl, file);
7566   if (pos >= 0 && pos < shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS_SEPARATOR))
7567     {
7568       gchar *uri;
7569
7570       uri = g_file_get_uri (file);
7571       /* translators, "Shortcut" means "Bookmark" here */
7572       g_set_error (error,
7573                    GTK_FILE_CHOOSER_ERROR,
7574                    GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS,
7575                    _("Shortcut %s already exists"),
7576                    uri);
7577       g_free (uri);
7578
7579       return FALSE;
7580     }
7581
7582   for (l = impl->loading_shortcuts; l; l = l->next)
7583     {
7584       GCancellable *c = l->data;
7585       GFile *f;
7586
7587       f = g_object_get_data (G_OBJECT (c), "add-shortcut-path-key");
7588       if (f && g_file_equal (file, f))
7589         {
7590           gchar *uri;
7591
7592           uri = g_file_get_uri (file);
7593           g_set_error (error,
7594                        GTK_FILE_CHOOSER_ERROR,
7595                        GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS,
7596                        _("Shortcut %s already exists"),
7597                        uri);
7598           g_free (uri);
7599
7600           return FALSE;
7601         }
7602     }
7603
7604   data = g_new0 (struct AddShortcutData, 1);
7605   data->impl = g_object_ref (impl);
7606   data->file = g_object_ref (file);
7607
7608   cancellable = _gtk_file_system_get_info (impl->file_system, file,
7609                                            "standard::type",
7610                                            add_shortcut_get_info_cb, data);
7611
7612   if (!cancellable)
7613     return FALSE;
7614
7615   impl->loading_shortcuts = g_slist_append (impl->loading_shortcuts, cancellable);
7616   g_object_set_data (G_OBJECT (cancellable), "add-shortcut-path-key", data->file);
7617
7618   return TRUE;
7619 }
7620
7621 static gboolean
7622 gtk_file_chooser_default_remove_shortcut_folder (GtkFileChooser  *chooser,
7623                                                  GFile           *file,
7624                                                  GError         **error)
7625 {
7626   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7627   int pos;
7628   GtkTreeIter iter;
7629   GSList *l;
7630   char *uri;
7631   int i;
7632
7633   for (l = impl->loading_shortcuts; l; l = l->next)
7634     {
7635       GCancellable *c = l->data;
7636       GFile *f;
7637
7638       f = g_object_get_data (G_OBJECT (c), "add-shortcut-path-key");
7639       if (f && g_file_equal (file, f))
7640         {
7641           impl->loading_shortcuts = g_slist_remove (impl->loading_shortcuts, c);
7642           g_cancellable_cancel (c);
7643           return TRUE;
7644         }
7645     }
7646
7647   if (impl->num_shortcuts == 0)
7648     goto out;
7649
7650   pos = shortcuts_get_pos_for_shortcut_folder (impl, 0);
7651   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
7652     g_assert_not_reached ();
7653
7654   for (i = 0; i < impl->num_shortcuts; i++)
7655     {
7656       gpointer col_data;
7657       ShortcutType shortcut_type;
7658       GFile *shortcut;
7659
7660       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
7661                           SHORTCUTS_COL_DATA, &col_data,
7662                           SHORTCUTS_COL_TYPE, &shortcut_type,
7663                           -1);
7664       g_assert (col_data != NULL);
7665       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
7666
7667       shortcut = col_data;
7668       if (g_file_equal (shortcut, file))
7669         {
7670           shortcuts_remove_rows (impl, pos + i, 1);
7671           impl->num_shortcuts--;
7672           return TRUE;
7673         }
7674
7675       if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
7676         g_assert_not_reached ();
7677     }
7678
7679  out:
7680
7681   uri = g_file_get_uri (file);
7682   /* translators, "Shortcut" means "Bookmark" here */
7683   g_set_error (error,
7684                GTK_FILE_CHOOSER_ERROR,
7685                GTK_FILE_CHOOSER_ERROR_NONEXISTENT,
7686                _("Shortcut %s does not exist"),
7687                uri);
7688   g_free (uri);
7689
7690   return FALSE;
7691 }
7692
7693 static GSList *
7694 gtk_file_chooser_default_list_shortcut_folders (GtkFileChooser *chooser)
7695 {
7696   GtkFileChooserDefault *impl = GTK_FILE_CHOOSER_DEFAULT (chooser);
7697   int pos;
7698   GtkTreeIter iter;
7699   int i;
7700   GSList *list;
7701
7702   if (impl->num_shortcuts == 0)
7703     return NULL;
7704
7705   pos = shortcuts_get_pos_for_shortcut_folder (impl, 0);
7706   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
7707     g_assert_not_reached ();
7708
7709   list = NULL;
7710
7711   for (i = 0; i < impl->num_shortcuts; i++)
7712     {
7713       gpointer col_data;
7714       ShortcutType shortcut_type;
7715       GFile *shortcut;
7716
7717       gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), &iter,
7718                           SHORTCUTS_COL_DATA, &col_data,
7719                           SHORTCUTS_COL_TYPE, &shortcut_type,
7720                           -1);
7721       g_assert (col_data != NULL);
7722       g_assert (shortcut_type == SHORTCUT_TYPE_FILE);
7723
7724       shortcut = col_data;
7725       list = g_slist_prepend (list, g_object_ref (shortcut));
7726
7727       if (i != impl->num_shortcuts - 1)
7728         {
7729           if (!gtk_tree_model_iter_next (GTK_TREE_MODEL (impl->shortcuts_model), &iter))
7730             g_assert_not_reached ();
7731         }
7732     }
7733
7734   return g_slist_reverse (list);
7735 }
7736
7737 /* Guesses a size based upon font sizes */
7738 static void
7739 find_good_size_from_style (GtkWidget *widget,
7740                            gint      *width,
7741                            gint      *height)
7742 {
7743   GtkFileChooserDefault *impl;
7744   int font_size;
7745   GdkScreen *screen;
7746   double resolution;
7747
7748   g_assert (widget->style != NULL);
7749   impl = GTK_FILE_CHOOSER_DEFAULT (widget);
7750
7751   if (impl->default_width == 0 &&
7752       impl->default_height == 0)
7753     {
7754       screen = gtk_widget_get_screen (widget);
7755       if (screen)
7756         {
7757           resolution = gdk_screen_get_resolution (screen);
7758           if (resolution < 0.0) /* will be -1 if the resolution is not defined in the GdkScreen */
7759             resolution = 96.0;
7760         }
7761       else
7762         resolution = 96.0; /* wheeee */
7763
7764       font_size = pango_font_description_get_size (widget->style->font_desc);
7765       font_size = PANGO_PIXELS (font_size) * resolution / 72.0;
7766
7767       impl->default_width = font_size * NUM_CHARS;
7768       impl->default_height = font_size * NUM_LINES;
7769     }
7770
7771   *width = impl->default_width;
7772   *height = impl->default_height;
7773 }
7774
7775 static void
7776 gtk_file_chooser_default_get_default_size (GtkFileChooserEmbed *chooser_embed,
7777                                            gint                *default_width,
7778                                            gint                *default_height)
7779 {
7780   GtkFileChooserDefault *impl;
7781   GtkRequisition req;
7782
7783   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
7784   find_good_size_from_style (GTK_WIDGET (chooser_embed), default_width, default_height);
7785
7786   if (impl->preview_widget_active &&
7787       impl->preview_widget &&
7788       GTK_WIDGET_VISIBLE (impl->preview_widget))
7789     {
7790       gtk_widget_size_request (impl->preview_box, &req);
7791       *default_width += PREVIEW_HBOX_SPACING + req.width;
7792     }
7793
7794   if (impl->extra_widget &&
7795       GTK_WIDGET_VISIBLE (impl->extra_widget))
7796     {
7797       gtk_widget_size_request (impl->extra_align, &req);
7798       *default_height += GTK_BOX (chooser_embed)->spacing + req.height;
7799     }
7800 }
7801
7802 struct switch_folder_closure {
7803   GtkFileChooserDefault *impl;
7804   GFile *file;
7805   int num_selected;
7806 };
7807
7808 /* Used from gtk_tree_selection_selected_foreach() in switch_to_selected_folder() */
7809 static void
7810 switch_folder_foreach_cb (GtkTreeModel      *model,
7811                           GtkTreePath       *path,
7812                           GtkTreeIter       *iter,
7813                           gpointer           data)
7814 {
7815   struct switch_folder_closure *closure;
7816   GtkTreeIter child_iter;
7817
7818   closure = data;
7819
7820   gtk_tree_model_sort_convert_iter_to_child_iter (closure->impl->sort_model, &child_iter, iter);
7821
7822   closure->file = _gtk_file_system_model_get_file (closure->impl->browse_files_model, &child_iter);
7823   closure->num_selected++;
7824 }
7825
7826 /* Changes to the selected folder in the list view */
7827 static void
7828 switch_to_selected_folder (GtkFileChooserDefault *impl)
7829 {
7830   GtkTreeSelection *selection;
7831   struct switch_folder_closure closure;
7832
7833   /* We do this with foreach() rather than get_selected() as we may be in
7834    * multiple selection mode
7835    */
7836
7837   closure.impl = impl;
7838   closure.file = NULL;
7839   closure.num_selected = 0;
7840
7841   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7842   gtk_tree_selection_selected_foreach (selection, switch_folder_foreach_cb, &closure);
7843
7844   g_assert (closure.file && closure.num_selected == 1);
7845
7846   change_folder_and_display_error (impl, closure.file, FALSE);
7847 }
7848
7849 /* Gets the GFileInfo for the selected row in the file list; assumes single
7850  * selection mode.
7851  */
7852 static GFileInfo *
7853 get_selected_file_info_from_file_list (GtkFileChooserDefault *impl,
7854                                        gboolean              *had_selection)
7855 {
7856   GtkTreeSelection *selection;
7857   GtkTreeIter iter, child_iter;
7858   GFileInfo *info;
7859
7860   g_assert (!impl->select_multiple);
7861   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
7862   if (!gtk_tree_selection_get_selected (selection, NULL, &iter))
7863     {
7864       *had_selection = FALSE;
7865       return NULL;
7866     }
7867
7868   *had_selection = TRUE;
7869
7870   gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
7871                                                   &child_iter,
7872                                                   &iter);
7873
7874   info = _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
7875   return info;
7876 }
7877
7878 /* Gets the display name of the selected file in the file list; assumes single
7879  * selection mode and that something is selected.
7880  */
7881 static const gchar *
7882 get_display_name_from_file_list (GtkFileChooserDefault *impl)
7883 {
7884   GFileInfo *info;
7885   gboolean had_selection;
7886
7887   info = get_selected_file_info_from_file_list (impl, &had_selection);
7888   g_assert (had_selection);
7889   g_assert (info != NULL);
7890
7891   return g_file_info_get_display_name (info);
7892 }
7893
7894 static void
7895 add_custom_button_to_dialog (GtkDialog   *dialog,
7896                              const gchar *mnemonic_label,
7897                              const gchar *stock_id,
7898                              gint         response_id)
7899 {
7900   GtkWidget *button;
7901
7902   button = gtk_button_new_with_mnemonic (mnemonic_label);
7903   GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
7904   gtk_button_set_image (GTK_BUTTON (button),
7905                         gtk_image_new_from_stock (stock_id, GTK_ICON_SIZE_BUTTON));
7906   gtk_widget_show (button);
7907
7908   gtk_dialog_add_action_widget (GTK_DIALOG (dialog), button, response_id);
7909 }
7910
7911 /* Presents an overwrite confirmation dialog; returns whether we should accept
7912  * the filename.
7913  */
7914 static gboolean
7915 confirm_dialog_should_accept_filename (GtkFileChooserDefault *impl,
7916                                        const gchar           *file_part,
7917                                        const gchar           *folder_display_name)
7918 {
7919   GtkWindow *toplevel;
7920   GtkWidget *dialog;
7921   int response;
7922
7923   toplevel = get_toplevel (GTK_WIDGET (impl));
7924
7925   dialog = gtk_message_dialog_new (toplevel,
7926                                    GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
7927                                    GTK_MESSAGE_QUESTION,
7928                                    GTK_BUTTONS_NONE,
7929                                    _("A file named \"%s\" already exists.  Do you want to replace it?"),
7930                                    file_part);
7931   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
7932                                             _("The file already exists in \"%s\".  Replacing it will "
7933                                               "overwrite its contents."),
7934                                             folder_display_name);
7935
7936   gtk_dialog_add_button (GTK_DIALOG (dialog), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
7937   add_custom_button_to_dialog (GTK_DIALOG (dialog), _("_Replace"),
7938                                GTK_STOCK_SAVE_AS, GTK_RESPONSE_ACCEPT);
7939   gtk_dialog_set_alternative_button_order (GTK_DIALOG (dialog),
7940                                            GTK_RESPONSE_ACCEPT,
7941                                            GTK_RESPONSE_CANCEL,
7942                                            -1);
7943   gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);
7944
7945   if (toplevel->group)
7946     gtk_window_group_add_window (toplevel->group, GTK_WINDOW (dialog));
7947
7948   response = gtk_dialog_run (GTK_DIALOG (dialog));
7949
7950   gtk_widget_destroy (dialog);
7951
7952   return (response == GTK_RESPONSE_ACCEPT);
7953 }
7954
7955 struct GetDisplayNameData
7956 {
7957   GtkFileChooserDefault *impl;
7958   gchar *file_part;
7959 };
7960
7961 static void
7962 confirmation_confirm_get_info_cb (GCancellable *cancellable,
7963                                   GFileInfo    *info,
7964                                   const GError *error,
7965                                   gpointer      user_data)
7966 {
7967   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
7968   gboolean should_respond = FALSE;
7969   struct GetDisplayNameData *data = user_data;
7970
7971   if (cancellable != data->impl->should_respond_get_info_cancellable)
7972     goto out;
7973
7974   data->impl->should_respond_get_info_cancellable = NULL;
7975
7976   if (cancelled)
7977     goto out;
7978
7979   if (error)
7980     /* Huh?  Did the folder disappear?  Let the caller deal with it */
7981     should_respond = TRUE;
7982   else
7983     should_respond = confirm_dialog_should_accept_filename (data->impl, data->file_part, g_file_info_get_display_name (info));
7984
7985   set_busy_cursor (data->impl, FALSE);
7986   if (should_respond)
7987     g_signal_emit_by_name (data->impl, "response-requested");
7988
7989 out:
7990   g_object_unref (data->impl);
7991   g_free (data->file_part);
7992   g_free (data);
7993
7994   g_object_unref (cancellable);
7995 }
7996
7997 /* Does overwrite confirmation if appropriate, and returns whether the dialog
7998  * should respond.  Can get the file part from the file list or the save entry.
7999  */
8000 static gboolean
8001 should_respond_after_confirm_overwrite (GtkFileChooserDefault *impl,
8002                                         const gchar           *file_part,
8003                                         GFile                 *parent_file)
8004 {
8005   GtkFileChooserConfirmation conf;
8006
8007   if (!impl->do_overwrite_confirmation)
8008     return TRUE;
8009
8010   conf = GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM;
8011
8012   g_signal_emit_by_name (impl, "confirm-overwrite", &conf);
8013
8014   switch (conf)
8015     {
8016     case GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM:
8017       {
8018         struct GetDisplayNameData *data;
8019
8020         g_assert (file_part != NULL);
8021
8022         data = g_new0 (struct GetDisplayNameData, 1);
8023         data->impl = g_object_ref (impl);
8024         data->file_part = g_strdup (file_part);
8025
8026         if (impl->should_respond_get_info_cancellable)
8027           g_cancellable_cancel (impl->should_respond_get_info_cancellable);
8028
8029         impl->should_respond_get_info_cancellable =
8030           _gtk_file_system_get_info (impl->file_system, parent_file,
8031                                      "standard::display-name",
8032                                      confirmation_confirm_get_info_cb,
8033                                      data);
8034         set_busy_cursor (data->impl, TRUE);
8035         return FALSE;
8036       }
8037
8038     case GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME:
8039       return TRUE;
8040
8041     case GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN:
8042       return FALSE;
8043
8044     default:
8045       g_assert_not_reached ();
8046       return FALSE;
8047     }
8048 }
8049
8050 struct FileExistsData
8051 {
8052   GtkFileChooserDefault *impl;
8053   gboolean file_exists_and_is_not_folder;
8054   GFile *parent_file;
8055   GFile *file;
8056 };
8057
8058 static void
8059 save_entry_get_info_cb (GCancellable *cancellable,
8060                         GFileInfo    *info,
8061                         const GError *error,
8062                         gpointer      user_data)
8063 {
8064   gboolean parent_is_folder;
8065   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8066   struct FileExistsData *data = user_data;
8067
8068   if (cancellable != data->impl->should_respond_get_info_cancellable)
8069     goto out;
8070
8071   data->impl->should_respond_get_info_cancellable = NULL;
8072
8073   set_busy_cursor (data->impl, FALSE);
8074
8075   if (cancelled)
8076     goto out;
8077
8078   if (!info)
8079     parent_is_folder = FALSE;
8080   else
8081     parent_is_folder = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
8082
8083   if (parent_is_folder)
8084     {
8085       if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8086         {
8087           if (data->file_exists_and_is_not_folder)
8088             {
8089               gboolean retval;
8090               const char *file_part;
8091
8092               file_part = _gtk_file_chooser_entry_get_file_part (GTK_FILE_CHOOSER_ENTRY (data->impl->location_entry));
8093               retval = should_respond_after_confirm_overwrite (data->impl, file_part, data->parent_file);
8094
8095               if (retval)
8096                 g_signal_emit_by_name (data->impl, "response-requested");
8097             }
8098           else
8099             g_signal_emit_by_name (data->impl, "response-requested");
8100         }
8101       else /* GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER */
8102         {
8103           GError *error = NULL;
8104
8105           set_busy_cursor (data->impl, TRUE);
8106           g_file_make_directory (data->file, NULL, &error);
8107           set_busy_cursor (data->impl, FALSE);
8108
8109           if (!error)
8110             g_signal_emit_by_name (data->impl, "response-requested");
8111           else
8112             error_creating_folder_dialog (data->impl, data->file, error);
8113         }
8114     }
8115   else
8116     {
8117       /* This will display an error, which is what we want */
8118       change_folder_and_display_error (data->impl, data->parent_file, FALSE);
8119     }
8120
8121 out:
8122   g_object_unref (data->impl);
8123   g_object_unref (data->file);
8124   g_object_unref (data->parent_file);
8125   g_free (data);
8126
8127   g_object_unref (cancellable);
8128 }
8129
8130 static void
8131 file_exists_get_info_cb (GCancellable *cancellable,
8132                          GFileInfo    *info,
8133                          const GError *error,
8134                          gpointer      user_data)
8135 {
8136   gboolean data_ownership_taken = FALSE;
8137   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8138   gboolean file_exists_and_is_not_folder;
8139   struct FileExistsData *data = user_data;
8140
8141   if (cancellable != data->impl->file_exists_get_info_cancellable)
8142     goto out;
8143
8144   data->impl->file_exists_get_info_cancellable = NULL;
8145
8146   set_busy_cursor (data->impl, FALSE);
8147
8148   if (cancelled)
8149     goto out;
8150
8151   file_exists_and_is_not_folder = info && (g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY);
8152
8153   if (data->impl->action == GTK_FILE_CHOOSER_ACTION_OPEN)
8154     /* user typed a filename; we are done */
8155     g_signal_emit_by_name (data->impl, "response-requested");
8156   else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
8157            && file_exists_and_is_not_folder)
8158     {
8159       /* Oops, the user typed the name of an existing path which is not
8160        * a folder
8161        */
8162       error_creating_folder_over_existing_file_dialog (data->impl, data->file,
8163                                                        g_error_copy (error));
8164     }
8165   else
8166     {
8167       /* check that everything up to the last component exists */
8168
8169       data->file_exists_and_is_not_folder = file_exists_and_is_not_folder;
8170       data_ownership_taken = TRUE;
8171
8172       if (data->impl->should_respond_get_info_cancellable)
8173         g_cancellable_cancel (data->impl->should_respond_get_info_cancellable);
8174
8175       data->impl->should_respond_get_info_cancellable =
8176         _gtk_file_system_get_info (data->impl->file_system,
8177                                    data->parent_file,
8178                                    "standard::type",
8179                                    save_entry_get_info_cb,
8180                                    data);
8181       set_busy_cursor (data->impl, TRUE);
8182     }
8183
8184 out:
8185   if (!data_ownership_taken)
8186     {
8187       g_object_unref (data->impl);
8188       g_object_unref (data->file);
8189       g_object_unref (data->parent_file);
8190       g_free (data);
8191     }
8192
8193   g_object_unref (cancellable);
8194 }
8195
8196 static void
8197 paste_text_received (GtkClipboard          *clipboard,
8198                      const gchar           *text,
8199                      GtkFileChooserDefault *impl)
8200 {
8201   GFile *file;
8202
8203   if (!text)
8204     return;
8205
8206   file = g_file_new_for_uri (text);
8207
8208   if (!gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (impl), file, NULL))
8209     location_popup_handler (impl, text);
8210
8211   g_object_unref (file);
8212 }
8213
8214 /* Handler for the "location-popup-on-paste" keybinding signal */
8215 static void
8216 location_popup_on_paste_handler (GtkFileChooserDefault *impl)
8217 {
8218   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (impl),
8219                                                       GDK_SELECTION_CLIPBOARD);
8220   gtk_clipboard_request_text (clipboard,
8221                               (GtkClipboardTextReceivedFunc) paste_text_received,
8222                               impl);
8223 }
8224
8225
8226 /* Implementation for GtkFileChooserEmbed::should_respond() */
8227 static gboolean
8228 gtk_file_chooser_default_should_respond (GtkFileChooserEmbed *chooser_embed)
8229 {
8230   GtkFileChooserDefault *impl;
8231   GtkWidget *toplevel;
8232   GtkWidget *current_focus;
8233
8234   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
8235
8236   toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
8237   g_assert (GTK_IS_WINDOW (toplevel));
8238
8239   current_focus = gtk_window_get_focus (GTK_WINDOW (toplevel));
8240
8241   if (current_focus == impl->browse_files_tree_view)
8242     {
8243       /* The following array encodes what we do based on the impl->action and the
8244        * number of files selected.
8245        */
8246       typedef enum {
8247         NOOP,                   /* Do nothing (don't respond) */
8248         RESPOND,                /* Respond immediately */
8249         RESPOND_OR_SWITCH,      /* Respond immediately if the selected item is a file; switch to it if it is a folder */
8250         ALL_FILES,              /* Respond only if everything selected is a file */
8251         ALL_FOLDERS,            /* Respond only if everything selected is a folder */
8252         SAVE_ENTRY,             /* Go to the code for handling the save entry */
8253         NOT_REACHED             /* Sanity check */
8254       } ActionToTake;
8255       static const ActionToTake what_to_do[4][3] = {
8256         /*                                0 selected            1 selected              many selected */
8257         /* ACTION_OPEN */               { NOOP,                 RESPOND_OR_SWITCH,      ALL_FILES   },
8258         /* ACTION_SAVE */               { SAVE_ENTRY,           RESPOND_OR_SWITCH,      NOT_REACHED },
8259         /* ACTION_SELECT_FOLDER */      { RESPOND,              ALL_FOLDERS,            ALL_FOLDERS },
8260         /* ACTION_CREATE_FOLDER */      { SAVE_ENTRY,           ALL_FOLDERS,            NOT_REACHED }
8261       };
8262
8263       int num_selected;
8264       gboolean all_files, all_folders;
8265       int k;
8266       ActionToTake action;
8267
8268     file_list:
8269
8270       g_assert (impl->action >= GTK_FILE_CHOOSER_ACTION_OPEN && impl->action <= GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
8271
8272       if (impl->operation_mode == OPERATION_MODE_SEARCH)
8273         return search_should_respond (impl);
8274
8275       if (impl->operation_mode == OPERATION_MODE_RECENT)
8276         return recent_should_respond (impl);
8277
8278       selection_check (impl, &num_selected, &all_files, &all_folders);
8279
8280       if (num_selected > 2)
8281         k = 2;
8282       else
8283         k = num_selected;
8284
8285       action = what_to_do [impl->action] [k];
8286
8287       switch (action)
8288         {
8289         case NOOP:
8290           return FALSE;
8291
8292         case RESPOND:
8293           return TRUE;
8294
8295         case RESPOND_OR_SWITCH:
8296           g_assert (num_selected == 1);
8297
8298           if (all_folders)
8299             {
8300               switch_to_selected_folder (impl);
8301               return FALSE;
8302             }
8303           else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8304             return should_respond_after_confirm_overwrite (impl,
8305                                                            get_display_name_from_file_list (impl),
8306                                                            impl->current_folder);
8307           else
8308             return TRUE;
8309
8310         case ALL_FILES:
8311           return all_files;
8312
8313         case ALL_FOLDERS:
8314           return all_folders;
8315
8316         case SAVE_ENTRY:
8317           goto save_entry;
8318
8319         default:
8320           g_assert_not_reached ();
8321         }
8322     }
8323   else if ((impl->location_entry != NULL) && (current_focus == impl->location_entry))
8324     {
8325       GFile *file;
8326       gboolean is_well_formed, is_empty, is_file_part_empty;
8327       gboolean is_folder;
8328       gboolean retval;
8329       GtkFileChooserEntry *entry;
8330       GError *error;
8331
8332     save_entry:
8333
8334       g_assert (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8335                 || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
8336                 || ((impl->action == GTK_FILE_CHOOSER_ACTION_OPEN
8337                      || impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8338                     && impl->location_mode == LOCATION_MODE_FILENAME_ENTRY));
8339
8340       entry = GTK_FILE_CHOOSER_ENTRY (impl->location_entry);
8341       check_save_entry (impl, &file, &is_well_formed, &is_empty, &is_file_part_empty, &is_folder);
8342
8343       if (is_empty || !is_well_formed)
8344         return FALSE;
8345
8346       g_assert (file != NULL);
8347
8348       error = NULL;
8349       if (is_folder)
8350         {
8351           if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8352               impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
8353             {
8354               change_folder_and_display_error (impl, file, TRUE);
8355               retval = FALSE;
8356             }
8357           else if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
8358                    impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8359             {
8360               /* The folder already exists, so we do not need to create it.
8361                * Just respond to terminate the dialog.
8362                */
8363               retval = TRUE;
8364             }
8365           else
8366             {
8367               g_assert_not_reached ();
8368               retval = FALSE;
8369             }
8370         }
8371       else
8372         {
8373           struct FileExistsData *data;
8374
8375           /* We need to check whether file exists and is not a folder */
8376
8377           data = g_new0 (struct FileExistsData, 1);
8378           data->impl = g_object_ref (impl);
8379           data->file = g_object_ref (file);
8380           data->parent_file = g_object_ref (_gtk_file_chooser_entry_get_current_folder (entry));
8381
8382           if (impl->file_exists_get_info_cancellable)
8383             g_cancellable_cancel (impl->file_exists_get_info_cancellable);
8384
8385           impl->file_exists_get_info_cancellable =
8386             _gtk_file_system_get_info (impl->file_system, file,
8387                                        "standard::type",
8388                                        file_exists_get_info_cb,
8389                                        data);
8390
8391           set_busy_cursor (impl, TRUE);
8392           retval = FALSE;
8393
8394           if (error != NULL)
8395             g_error_free (error);
8396         }
8397
8398       g_object_unref (file);
8399       return retval;
8400     }
8401   else if (impl->toplevel_last_focus_widget == impl->browse_files_tree_view)
8402     {
8403       /* The focus is on a dialog's action area button, *and* the widget that
8404        * was focused immediately before it is the file list.  
8405        */
8406       goto file_list;
8407     }
8408   else if (impl->operation_mode == OPERATION_MODE_SEARCH && impl->toplevel_last_focus_widget == impl->search_entry)
8409     {
8410       search_entry_activate_cb (GTK_ENTRY (impl->search_entry), impl);
8411       return FALSE;
8412     }
8413   else if (impl->location_entry && impl->toplevel_last_focus_widget == impl->location_entry)
8414     {
8415       /* The focus is on a dialog's action area button, *and* the widget that
8416        * was focused immediately before it is the location entry.
8417        */
8418       goto save_entry;
8419     }
8420   else
8421     /* The focus is on a dialog's action area button or something else */
8422     if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
8423         || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8424       goto save_entry;
8425     else
8426       goto file_list; 
8427   
8428   g_assert_not_reached ();
8429   return FALSE;
8430 }
8431
8432 /* Implementation for GtkFileChooserEmbed::initial_focus() */
8433 static void
8434 gtk_file_chooser_default_initial_focus (GtkFileChooserEmbed *chooser_embed)
8435 {
8436   GtkFileChooserDefault *impl;
8437   GtkWidget *widget;
8438
8439   impl = GTK_FILE_CHOOSER_DEFAULT (chooser_embed);
8440
8441   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8442       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8443     {
8444       if (impl->location_mode == LOCATION_MODE_PATH_BAR)
8445         widget = impl->browse_files_tree_view;
8446       else
8447         widget = impl->location_entry;
8448     }
8449   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
8450            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
8451     widget = impl->location_entry;
8452   else
8453     {
8454       g_assert_not_reached ();
8455       widget = NULL;
8456     }
8457
8458   g_assert (widget != NULL);
8459   gtk_widget_grab_focus (widget);
8460 }
8461
8462 /* Callback used from gtk_tree_selection_selected_foreach(); gets the selected GFiles */
8463 static void
8464 search_selected_foreach_get_file_cb (GtkTreeModel *model,
8465                                      GtkTreePath  *path,
8466                                      GtkTreeIter  *iter,
8467                                      gpointer      data)
8468 {
8469   GSList **list;
8470   GFile *file;
8471
8472   list = data;
8473
8474   gtk_tree_model_get (model, iter, SEARCH_MODEL_COL_FILE, &file, -1);
8475   *list = g_slist_prepend (*list, file);
8476 }
8477
8478 /* Constructs a list of the selected paths in search mode */
8479 static GSList *
8480 search_get_selected_files (GtkFileChooserDefault *impl)
8481 {
8482   GSList *result;
8483   GtkTreeSelection *selection;
8484
8485   result = NULL;
8486
8487   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8488   gtk_tree_selection_selected_foreach (selection, search_selected_foreach_get_file_cb, &result);
8489   result = g_slist_reverse (result);
8490
8491   return result;
8492 }
8493
8494 /* Called from ::should_respond().  We return whether there are selected files
8495  * in the search list.
8496  */
8497 static gboolean
8498 search_should_respond (GtkFileChooserDefault *impl)
8499 {
8500   GtkTreeSelection *selection;
8501
8502   g_assert (impl->operation_mode == OPERATION_MODE_SEARCH);
8503
8504   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
8505   return (gtk_tree_selection_count_selected_rows (selection) != 0);
8506 }
8507
8508 struct SearchHitInsertRequest
8509 {
8510   GtkFileChooserDefault *impl;
8511   GFile *file;
8512   GtkTreeRowReference *row_ref;
8513 };
8514
8515 static void
8516 search_hit_get_info_cb (GCancellable *cancellable,
8517                         GFileInfo    *info,
8518                         const GError *error,
8519                         gpointer      data)
8520 {
8521   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
8522   GdkPixbuf *pixbuf = NULL;
8523   GtkTreePath *path;
8524   GtkTreeIter iter;
8525   GCancellable *model_cancellable;
8526   gboolean is_folder = FALSE;
8527   char *mime_type;
8528   char *display_name;
8529   struct SearchHitInsertRequest *request = data;
8530
8531   if (!request->impl->search_model)
8532     goto out;
8533
8534   path = gtk_tree_row_reference_get_path (request->row_ref);
8535   if (!path)
8536     goto out;
8537
8538   gtk_tree_model_get_iter (GTK_TREE_MODEL (request->impl->search_model),
8539                            &iter, path);
8540   gtk_tree_path_free (path);
8541
8542   gtk_tree_model_get (GTK_TREE_MODEL (request->impl->search_model), &iter,
8543                       SEARCH_MODEL_COL_CANCELLABLE, &model_cancellable,
8544                       -1);
8545   if (cancellable != model_cancellable)
8546     goto out;
8547
8548   /* set the cancellable to NULL in the model */
8549   gtk_list_store_set (request->impl->search_model, &iter,
8550                       SEARCH_MODEL_COL_CANCELLABLE, NULL,
8551                       -1);
8552
8553   if (cancelled)
8554     goto out;
8555
8556   if (!info)
8557     {
8558       gtk_list_store_remove (request->impl->search_model, &iter);
8559       goto out;
8560     }
8561
8562   display_name = g_strdup (g_file_info_get_display_name (info));
8563   mime_type = g_strdup (g_file_info_get_content_type (info));
8564   is_folder = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
8565   pixbuf = _gtk_file_info_render_icon (info, GTK_WIDGET (request->impl),
8566                                        request->impl->icon_size);
8567
8568   gtk_list_store_set (request->impl->search_model, &iter,
8569                       SEARCH_MODEL_COL_PIXBUF, pixbuf,
8570                       SEARCH_MODEL_COL_DISPLAY_NAME, display_name,
8571                       SEARCH_MODEL_COL_MIME_TYPE, mime_type,
8572                       SEARCH_MODEL_COL_IS_FOLDER, is_folder,
8573                       -1);
8574
8575   if (pixbuf)
8576     g_object_unref (pixbuf);
8577
8578 out:
8579   g_object_unref (request->impl);
8580   g_object_unref (request->file);
8581   gtk_tree_row_reference_free (request->row_ref);
8582   g_free (request);
8583
8584   g_object_unref (cancellable);
8585 }
8586
8587 /* Adds one hit from the search engine to the search_model */
8588 static void
8589 search_add_hit (GtkFileChooserDefault *impl,
8590                 gchar                 *uri)
8591 {
8592   GFile *file;
8593   char *filename;
8594   char *tmp;
8595   char *collation_key;
8596   struct stat statbuf;
8597   struct stat *statbuf_copy;
8598   GtkTreeIter iter;
8599   GtkTreePath *p;
8600   GCancellable *cancellable;
8601   struct SearchHitInsertRequest *request;
8602
8603   file = g_file_new_for_uri (uri);
8604
8605   if (!g_file_is_native (file))
8606     {
8607       g_object_unref (file);
8608       return;
8609     }
8610
8611   filename = g_file_get_path (file);
8612
8613   if (stat (filename, &statbuf) != 0)
8614     {
8615       g_object_unref (file);
8616       g_free (filename);
8617       return;
8618     }
8619
8620   statbuf_copy = g_new (struct stat, 1);
8621   *statbuf_copy = statbuf;
8622
8623   tmp = g_file_get_parse_name (file);
8624   collation_key = g_utf8_collate_key_for_filename (tmp, -1);
8625   g_free (tmp);
8626
8627   request = g_new0 (struct SearchHitInsertRequest, 1);
8628   request->impl = g_object_ref (impl);
8629   request->file = g_object_ref (file);
8630
8631   gtk_list_store_append (impl->search_model, &iter);
8632   p = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->search_model), &iter);
8633   
8634   request->row_ref = gtk_tree_row_reference_new (GTK_TREE_MODEL (impl->search_model), p);
8635   gtk_tree_path_free (p);
8636
8637   cancellable = _gtk_file_system_get_info (impl->file_system, file,
8638                                            "standard::type,standard::icon,"
8639                                            "standard::content-type,standard::display-name",
8640                                            search_hit_get_info_cb,
8641                                            request);
8642
8643   gtk_list_store_set (impl->search_model, &iter,
8644                       SEARCH_MODEL_COL_FILE, file,
8645                       SEARCH_MODEL_COL_COLLATION_KEY, collation_key,
8646                       SEARCH_MODEL_COL_STAT, statbuf_copy,
8647                       SEARCH_MODEL_COL_CANCELLABLE, cancellable,
8648                       -1);
8649
8650   g_object_unref (file);
8651   g_free (filename);
8652 }
8653
8654 /* Callback used from GtkSearchEngine when we get new hits */
8655 static void
8656 search_engine_hits_added_cb (GtkSearchEngine *engine,
8657                              GList           *hits,
8658                              gpointer         data)
8659 {
8660   GtkFileChooserDefault *impl;
8661   GList *l;
8662   
8663   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8664
8665   for (l = hits; l; l = l->next)
8666     search_add_hit (impl, (gchar*)l->data);
8667 }
8668
8669 /* Callback used from GtkSearchEngine when the query is done running */
8670 static void
8671 search_engine_finished_cb (GtkSearchEngine *engine,
8672                            gpointer         data)
8673 {
8674   GtkFileChooserDefault *impl;
8675   
8676   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8677   
8678 #if 0
8679   /* EB: setting the model here will avoid loads of row events,
8680    * but it'll make the search look like blocked.
8681    */
8682   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
8683                            GTK_TREE_MODEL (impl->search_model_filter));
8684 #endif
8685
8686   /* FMQ: if search was empty, say that we got no hits */
8687   set_busy_cursor (impl, FALSE);
8688 }
8689
8690 /* Displays a generic error when we cannot create a GtkSearchEngine.  
8691  * It would be better if _gtk_search_engine_new() gave us a GError 
8692  * with a better message, but it doesn't do that right now.
8693  */
8694 static void
8695 search_error_could_not_create_client (GtkFileChooserDefault *impl)
8696 {
8697   error_message (impl,
8698                  _("Could not start the search process"),
8699                  _("The program was not able to create a connection to the indexer "
8700                    "daemon.  Please make sure it is running."));
8701 }
8702
8703 static void
8704 search_engine_error_cb (GtkSearchEngine *engine,
8705                         const gchar     *message,
8706                         gpointer         data)
8707 {
8708   GtkFileChooserDefault *impl;
8709   
8710   impl = GTK_FILE_CHOOSER_DEFAULT (data);
8711
8712   search_stop_searching (impl, TRUE);
8713   error_message (impl, _("Could not send the search request"), message);
8714
8715   set_busy_cursor (impl, FALSE);
8716 }
8717
8718 /* Frees the data in the search_model */
8719 static void
8720 search_clear_model (GtkFileChooserDefault *impl, 
8721                     gboolean               remove_from_treeview)
8722 {
8723   GtkTreeModel *model;
8724   GtkTreeIter iter;
8725
8726   if (!impl->search_model)
8727     return;
8728
8729   model = GTK_TREE_MODEL (impl->search_model);
8730
8731   if (gtk_tree_model_get_iter_first (model, &iter))
8732     do
8733       {
8734         GCancellable *cancellable;
8735
8736         gtk_tree_model_get (model, &iter,
8737                             SEARCH_MODEL_COL_CANCELLABLE, &cancellable,
8738                             -1);
8739
8740         if (cancellable)
8741           g_cancellable_cancel (cancellable);
8742       }
8743     while (gtk_tree_model_iter_next (model, &iter));
8744
8745   g_object_unref (impl->search_model);
8746   impl->search_model = NULL;
8747   
8748   g_object_unref (impl->search_model_filter);
8749   impl->search_model_filter = NULL;
8750   
8751   g_object_unref (impl->search_model_sort);
8752   impl->search_model_sort = NULL;
8753
8754   if (remove_from_treeview)
8755     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
8756 }
8757
8758 /* Stops any ongoing searches; does not touch the search_model */
8759 static void
8760 search_stop_searching (GtkFileChooserDefault *impl,
8761                        gboolean               remove_query)
8762 {
8763   if (remove_query && impl->search_query)
8764     {
8765       g_object_unref (impl->search_query);
8766       impl->search_query = NULL;
8767     }
8768   
8769   if (impl->search_engine)
8770     {
8771       _gtk_search_engine_stop (impl->search_engine);
8772       
8773       g_object_unref (impl->search_engine);
8774       impl->search_engine = NULL;
8775     }
8776 }
8777
8778 /* Stops any pending searches, clears the file list, and switches back to OPERATION_MODE_BROWSE */
8779 static void
8780 search_switch_to_browse_mode (GtkFileChooserDefault *impl)
8781 {
8782   g_assert (impl->operation_mode != OPERATION_MODE_BROWSE);
8783
8784   search_stop_searching (impl, FALSE);
8785   search_clear_model (impl, TRUE);
8786
8787   gtk_widget_destroy (impl->search_hbox);
8788   impl->search_hbox = NULL;
8789   impl->search_entry = NULL;
8790
8791   gtk_widget_show (impl->browse_path_bar);
8792   gtk_widget_show (impl->browse_new_folder_button);
8793
8794   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
8795       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
8796     {
8797       gtk_widget_show (impl->location_button);
8798
8799       if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
8800         gtk_widget_show (impl->location_entry_box);
8801     }
8802
8803   impl->operation_mode = OPERATION_MODE_BROWSE;
8804
8805   file_list_set_sort_column_ids (impl);
8806 }
8807
8808 /* Sort callback from the path column */
8809 static gint
8810 search_column_path_sort_func (GtkTreeModel *model,
8811                               GtkTreeIter  *a,
8812                               GtkTreeIter  *b,
8813                               gpointer      user_data)
8814 {
8815   GtkFileChooserDefault *impl = user_data;
8816   GtkTreeIter child_a, child_b;
8817   const char *collation_key_a, *collation_key_b;
8818   gboolean is_folder_a, is_folder_b;
8819
8820   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_a, a);
8821   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_b, b);
8822
8823   gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_a,
8824                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder_a,
8825                       SEARCH_MODEL_COL_COLLATION_KEY, &collation_key_a,
8826                       -1);
8827   gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_b,
8828                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder_b,
8829                       SEARCH_MODEL_COL_COLLATION_KEY, &collation_key_b,
8830                       -1);
8831
8832   if (!collation_key_a)
8833     return 1;
8834
8835   if (!collation_key_b)
8836     return -1;
8837
8838   /* always show folders first */
8839   if (is_folder_a != is_folder_b)
8840     return is_folder_a ? 1 : -1;
8841
8842   return strcmp (collation_key_a, collation_key_b);
8843 }
8844
8845 /* Sort callback from the modification time column */
8846 static gint
8847 search_column_mtime_sort_func (GtkTreeModel *model,
8848                                GtkTreeIter  *a,
8849                                GtkTreeIter  *b,
8850                                gpointer      user_data)
8851 {
8852   GtkFileChooserDefault *impl = user_data;
8853   GtkTreeIter child_a, child_b;
8854   const struct stat *statbuf_a, *statbuf_b;
8855   gboolean is_folder_a, is_folder_b;
8856
8857   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_a, a);
8858   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_b, b);
8859
8860   /* Note that although we store a whole struct stat in the model, we only
8861    * compare the mtime here.  If we add another column relative to a struct stat
8862    * (e.g. a file size column), we'll want another sort callback similar to this
8863    * one as well.
8864    */
8865   gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_a,
8866                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder_a,
8867                       SEARCH_MODEL_COL_STAT, &statbuf_a,
8868                       -1);
8869   gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_b,
8870                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder_b,
8871                       SEARCH_MODEL_COL_STAT, &statbuf_b,
8872                       -1);
8873   
8874   if (!statbuf_a)
8875     return 1;
8876
8877   if (!statbuf_b)
8878     return -1;
8879
8880   if (is_folder_a != is_folder_b)
8881     return is_folder_a ? 1 : -1;
8882
8883   if (statbuf_a->st_mtime < statbuf_b->st_mtime)
8884     return -1;
8885   else if (statbuf_a->st_mtime > statbuf_b->st_mtime)
8886     return 1;
8887   else
8888     return 0;
8889 }
8890
8891 static gboolean
8892 search_get_is_filtered (GtkFileChooserDefault *impl,
8893                         GFile                 *file,
8894                         const gchar           *display_name,
8895                         const gchar           *mime_type)
8896 {
8897   GtkFileFilterInfo filter_info;
8898   GtkFileFilterFlags needed;
8899   gboolean result;
8900
8901   if (!impl->current_filter)
8902     return FALSE;
8903
8904   filter_info.contains = GTK_FILE_FILTER_DISPLAY_NAME | GTK_FILE_FILTER_MIME_TYPE;
8905   needed = gtk_file_filter_get_needed (impl->current_filter);
8906
8907   filter_info.display_name = display_name;
8908   filter_info.mime_type = mime_type;
8909
8910   if (needed & GTK_FILE_FILTER_FILENAME)
8911     {
8912       filter_info.filename = g_file_get_path (file);
8913       if (filter_info.filename)
8914         filter_info.contains |= GTK_FILE_FILTER_FILENAME;
8915     }
8916   else
8917     filter_info.filename = NULL;
8918
8919   if (needed & GTK_FILE_FILTER_URI)
8920     {
8921       filter_info.uri = g_file_get_uri (file);
8922       if (filter_info.uri)
8923         filter_info.contains |= GTK_FILE_FILTER_URI;
8924     }
8925   else
8926     filter_info.uri = NULL;
8927
8928   result = gtk_file_filter_filter (impl->current_filter, &filter_info);
8929
8930   if (filter_info.filename)
8931     g_free ((gchar *) filter_info.filename);
8932   if (filter_info.uri)
8933     g_free ((gchar *) filter_info.uri);
8934
8935   return !result;
8936
8937 }
8938
8939 /* Visibility function for the recent filter model */
8940 static gboolean
8941 search_model_visible_func (GtkTreeModel *model,
8942                            GtkTreeIter  *iter,
8943                            gpointer      user_data)
8944 {
8945   GtkFileChooserDefault *impl = user_data;
8946   GFile *file;
8947   gchar *display_name, *mime_type;
8948   gboolean is_folder;
8949
8950   if (!impl->current_filter)
8951     return TRUE;
8952
8953   gtk_tree_model_get (model, iter,
8954                       SEARCH_MODEL_COL_FILE, &file,
8955                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
8956                       SEARCH_MODEL_COL_DISPLAY_NAME, &display_name,
8957                       SEARCH_MODEL_COL_MIME_TYPE, &mime_type,
8958                       -1);
8959
8960   if (!display_name)
8961     return TRUE;
8962
8963   if (is_folder)
8964     return TRUE;
8965
8966   return !search_get_is_filtered (impl, file, display_name, mime_type);
8967 }
8968
8969 /* Creates the search_model and puts it in the tree view */
8970 static void
8971 search_setup_model (GtkFileChooserDefault *impl)
8972 {
8973   g_assert (impl->search_model == NULL);
8974   g_assert (impl->search_model_filter == NULL);
8975   g_assert (impl->search_model_sort == NULL);
8976
8977   /* We store these columns in the search model:
8978    *
8979    * SEARCH_MODEL_COL_FILE - a GFile for the hit's URI, stored
8980    *   as a pointer not as a G_TYPE_FILE
8981    * SEARCH_MODEL_COL_DISPLAY_NAME - a string with the display name, stored
8982    *   as a pointer not as a G_TYPE_STRING
8983    * SEARCH_MODEL_COL_COLLATION_KEY - collation key for the filename, stored
8984    *   as a pointer not as a G_TYPE_STRING
8985    * SEARCH_MODEL_COL_STAT - pointer to a struct stat
8986    * SEARCH_MODEL_COL_CANCELLABLE - cancellable used when getting the hit's info
8987    * SEARCH_MODEL_COL_PIXBUF - GdkPixbuf for the hit's icon
8988    * SEARCH_MODEL_COL_MIME_TYPE - a string with the hit's MIME type
8989    * SEARCH_MODEL_COL_IS_FOLDER - a boolean flag for folders
8990    *
8991    * Keep this in sync with the enumeration defined near the beginning
8992    * of this file.
8993    */
8994   impl->search_model = gtk_list_store_new (SEARCH_MODEL_COL_NUM_COLUMNS,
8995                                            G_TYPE_POINTER,
8996                                            G_TYPE_POINTER,
8997                                            G_TYPE_POINTER,
8998                                            G_TYPE_POINTER,
8999                                            G_TYPE_POINTER,
9000                                            GDK_TYPE_PIXBUF,
9001                                            G_TYPE_POINTER,
9002                                            G_TYPE_BOOLEAN);
9003   
9004   impl->search_model_filter =
9005     GTK_TREE_MODEL_FILTER (gtk_tree_model_filter_new (GTK_TREE_MODEL (impl->search_model), NULL));
9006   gtk_tree_model_filter_set_visible_func (impl->search_model_filter,
9007                                           search_model_visible_func,
9008                                           impl, NULL);
9009
9010   impl->search_model_sort =
9011     GTK_TREE_MODEL_SORT (search_model_sort_new (impl, GTK_TREE_MODEL (impl->search_model_filter)));
9012   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model_sort),
9013                                    SEARCH_MODEL_COL_FILE,
9014                                    search_column_path_sort_func,
9015                                    impl, NULL);
9016   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->search_model_sort),
9017                                    SEARCH_MODEL_COL_STAT,
9018                                    search_column_mtime_sort_func,
9019                                    impl, NULL);
9020   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (impl->search_model_sort),
9021                                         SEARCH_MODEL_COL_STAT,
9022                                         GTK_SORT_DESCENDING);
9023
9024   /* EB: setting the model here will make the hits list update feel
9025    * more "alive" than setting the model at the end of the search
9026    * run
9027    */
9028   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9029                            GTK_TREE_MODEL (impl->search_model_sort));
9030 }
9031
9032 static void
9033 search_get_valid_child_iter (GtkFileChooserDefault *impl,
9034                              GtkTreeIter           *child_iter,
9035                              GtkTreeIter           *iter)
9036 {
9037   GtkTreeIter middle;
9038
9039   if (!impl->search_model)
9040     return;
9041
9042   if (!impl->search_model_filter || !impl->search_model_sort)
9043     return;
9044
9045   /* pass 1: get the iterator in the filter model */
9046   gtk_tree_model_sort_convert_iter_to_child_iter (impl->search_model_sort,
9047                                                   &middle, iter);
9048   
9049   /* pass 2: get the iterator in the real model */
9050   gtk_tree_model_filter_convert_iter_to_child_iter (impl->search_model_filter,
9051                                                     child_iter, &middle);
9052 }
9053
9054 /* Creates a new query with the specified text and launches it */
9055 static void
9056 search_start_query (GtkFileChooserDefault *impl,
9057                     const gchar           *query_text)
9058 {
9059   search_stop_searching (impl, FALSE);
9060   search_clear_model (impl, TRUE);
9061   search_setup_model (impl);
9062   set_busy_cursor (impl, TRUE);
9063
9064   if (impl->search_engine == NULL)
9065     impl->search_engine = _gtk_search_engine_new ();
9066
9067   if (!impl->search_engine)
9068     {
9069       set_busy_cursor (impl, FALSE);
9070       search_error_could_not_create_client (impl); /* lame; we don't get an error code or anything */
9071       return;
9072     }
9073
9074   if (!impl->search_query)
9075     {
9076       impl->search_query = _gtk_query_new ();
9077       _gtk_query_set_text (impl->search_query, query_text);
9078     }
9079   
9080   _gtk_search_engine_set_query (impl->search_engine, impl->search_query);
9081
9082   g_signal_connect (impl->search_engine, "hits-added",
9083                     G_CALLBACK (search_engine_hits_added_cb), impl);
9084   g_signal_connect (impl->search_engine, "finished",
9085                     G_CALLBACK (search_engine_finished_cb), impl);
9086   g_signal_connect (impl->search_engine, "error",
9087                     G_CALLBACK (search_engine_error_cb), impl);
9088
9089   _gtk_search_engine_start (impl->search_engine);
9090 }
9091
9092 /* Callback used when the user presses Enter while typing on the search
9093  * entry; starts the query
9094  */
9095 static void
9096 search_entry_activate_cb (GtkEntry *entry,
9097                           gpointer data)
9098 {
9099   GtkFileChooserDefault *impl;
9100   const char *text;
9101
9102   impl = GTK_FILE_CHOOSER_DEFAULT (data);
9103
9104   text = gtk_entry_get_text (GTK_ENTRY (impl->search_entry));
9105   if (strlen (text) == 0)
9106     return;
9107
9108   /* reset any existing query object */
9109   if (impl->search_query)
9110     {
9111       g_object_unref (impl->search_query);
9112       impl->search_query = NULL;
9113     }
9114
9115   search_start_query (impl, text);
9116 }
9117
9118 /* Hides the path bar and creates the search entry */
9119 static void
9120 search_setup_widgets (GtkFileChooserDefault *impl)
9121 {
9122   GtkWidget *label;
9123
9124   impl->search_hbox = gtk_hbox_new (FALSE, 12);
9125
9126   /* Label */
9127
9128   label = gtk_label_new_with_mnemonic (_("_Search:"));
9129   gtk_box_pack_start (GTK_BOX (impl->search_hbox), label, FALSE, FALSE, 0);
9130
9131   /* Entry */
9132
9133   impl->search_entry = gtk_entry_new ();
9134   gtk_label_set_mnemonic_widget (GTK_LABEL (label), impl->search_entry);
9135   g_signal_connect (impl->search_entry, "activate",
9136                     G_CALLBACK (search_entry_activate_cb),
9137                     impl);
9138   gtk_box_pack_start (GTK_BOX (impl->search_hbox), impl->search_entry, TRUE, TRUE, 0);
9139
9140   /* if there already is a query, restart it */
9141   if (impl->search_query)
9142     {
9143       gchar *query = _gtk_query_get_text (impl->search_query);
9144
9145       if (query)
9146         {
9147           gtk_entry_set_text (GTK_ENTRY (impl->search_entry), query);
9148           search_start_query (impl, query);
9149
9150           g_free (query);
9151         }
9152       else
9153         {
9154           g_object_unref (impl->search_query);
9155           impl->search_query = NULL;
9156         }
9157     }
9158
9159   gtk_widget_hide (impl->browse_path_bar);
9160   gtk_widget_hide (impl->browse_new_folder_button);
9161
9162   /* Box for search widgets */
9163   gtk_box_pack_start (GTK_BOX (impl->browse_path_bar_hbox), impl->search_hbox, TRUE, TRUE, 0);
9164   gtk_widget_show_all (impl->search_hbox);
9165
9166   /* Hide the location widgets temporarily */
9167
9168   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9169       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9170     {
9171       gtk_widget_hide (impl->location_button);
9172       gtk_widget_hide (impl->location_entry_box);
9173     }
9174
9175   gtk_widget_grab_focus (impl->search_entry);
9176
9177   /* FMQ: hide the filter combo? */
9178 }
9179
9180 /* Main entry point to the searching functions; this gets called when the user
9181  * activates the Search shortcut.
9182  */
9183 static void
9184 search_activate (GtkFileChooserDefault *impl)
9185 {
9186   OperationMode previous_mode;
9187   
9188   if (impl->operation_mode == OPERATION_MODE_SEARCH)
9189     {
9190       gtk_widget_grab_focus (impl->search_entry);
9191       return;
9192     }
9193
9194   previous_mode = impl->operation_mode;
9195   impl->operation_mode = OPERATION_MODE_SEARCH;
9196
9197   switch (previous_mode)
9198     {
9199     case OPERATION_MODE_RECENT:
9200       recent_stop_loading (impl);
9201       recent_clear_model (impl, TRUE);
9202       break;
9203
9204     case OPERATION_MODE_BROWSE:
9205       stop_loading_and_clear_list_model (impl);
9206       break;
9207
9208     case OPERATION_MODE_SEARCH:
9209       g_assert_not_reached ();
9210       break;
9211     }
9212
9213   g_assert (impl->search_hbox == NULL);
9214   g_assert (impl->search_entry == NULL);
9215   g_assert (impl->search_model == NULL);
9216   g_assert (impl->search_model_filter == NULL);
9217
9218   search_setup_widgets (impl);
9219   file_list_set_sort_column_ids (impl);
9220 }
9221
9222 /*
9223  * Recent files support
9224  */
9225
9226 /* Frees the data in the recent_model */
9227 static void
9228 recent_clear_model (GtkFileChooserDefault *impl,
9229                     gboolean               remove_from_treeview)
9230 {
9231   GtkTreeModel *model;
9232   GtkTreeIter iter;
9233
9234   if (!impl->recent_model)
9235     return;
9236
9237   model = GTK_TREE_MODEL (impl->recent_model);
9238   
9239   if (remove_from_treeview)
9240     gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view), NULL);
9241
9242   if (gtk_tree_model_get_iter_first (model, &iter))
9243     {
9244       do
9245         {
9246           GFile *file;
9247           GCancellable *cancellable;
9248           GtkRecentInfo *recent_info;
9249           gchar *display_name;
9250
9251           gtk_tree_model_get (model, &iter,
9252                               RECENT_MODEL_COL_DISPLAY_NAME, &display_name,
9253                               RECENT_MODEL_COL_FILE, &file,
9254                               RECENT_MODEL_COL_CANCELLABLE, &cancellable,
9255                               RECENT_MODEL_COL_INFO, &recent_info,
9256                               -1);
9257
9258           if (cancellable)
9259             g_cancellable_cancel (cancellable);
9260
9261           g_object_unref (file);
9262           gtk_recent_info_unref (recent_info);
9263           g_free (display_name);
9264         }
9265       while (gtk_tree_model_iter_next (model, &iter));
9266     }
9267
9268   g_object_unref (impl->recent_model);
9269   impl->recent_model = NULL;
9270
9271   g_object_unref (impl->recent_model_filter);
9272   impl->recent_model_filter = NULL;
9273
9274   g_object_unref (impl->recent_model_sort);
9275   impl->recent_model_sort = NULL;
9276 }
9277
9278 /* Stops any ongoing loading of the recent files list; does
9279  * not touch the recent_model
9280  */
9281 static void
9282 recent_stop_loading (GtkFileChooserDefault *impl)
9283 {
9284   if (impl->load_recent_id)
9285     {
9286       g_source_remove (impl->load_recent_id);
9287       impl->load_recent_id = 0;
9288     }
9289 }
9290
9291 /* Stops any pending load, clears the file list, and switches
9292  * back to OPERATION_MODE_BROWSE
9293  */
9294 static void
9295 recent_switch_to_browse_mode (GtkFileChooserDefault *impl)
9296 {
9297   g_assert (impl->operation_mode != OPERATION_MODE_BROWSE);
9298
9299   recent_stop_loading (impl);
9300   recent_clear_model (impl, TRUE);
9301
9302   gtk_widget_show (impl->browse_path_bar);
9303   gtk_widget_show (impl->browse_new_folder_button);
9304
9305   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9306       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9307     {
9308       gtk_widget_show (impl->location_button);
9309
9310       if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
9311         gtk_widget_show (impl->location_entry_box);
9312     }
9313
9314   impl->operation_mode = OPERATION_MODE_BROWSE;
9315
9316   file_list_set_sort_column_ids (impl);
9317 }
9318
9319 /* Sort callback from the modification time column */
9320 static gint
9321 recent_column_mtime_sort_func (GtkTreeModel *model,
9322                                GtkTreeIter  *a,
9323                                GtkTreeIter  *b,
9324                                gpointer      user_data)
9325 {
9326   GtkFileChooserDefault *impl = user_data;
9327   GtkTreeIter child_a, child_b;
9328   GtkRecentInfo *info_a, *info_b;
9329   gboolean is_folder_a, is_folder_b;
9330
9331   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_a, a);
9332   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_b, b);
9333
9334   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_a,
9335                       RECENT_MODEL_COL_IS_FOLDER, &is_folder_a,
9336                       RECENT_MODEL_COL_INFO, &info_a,
9337                       -1);
9338   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_b,
9339                       RECENT_MODEL_COL_IS_FOLDER, &is_folder_b,
9340                       RECENT_MODEL_COL_INFO, &info_b,
9341                       -1);
9342   
9343   if (!info_a)
9344     return 1;
9345
9346   if (!info_b)
9347     return -1;
9348
9349   /* folders always go first */
9350   if (is_folder_a != is_folder_b)
9351     return is_folder_a ? 1 : -1;
9352
9353   if (gtk_recent_info_get_modified (info_a) < gtk_recent_info_get_modified (info_b))
9354     return -1;
9355   else if (gtk_recent_info_get_modified (info_a) > gtk_recent_info_get_modified (info_b))
9356     return 1;
9357   else
9358     return 0;
9359 }
9360
9361 static gint
9362 recent_column_path_sort_func (GtkTreeModel *model,
9363                               GtkTreeIter  *a,
9364                               GtkTreeIter  *b,
9365                               gpointer      user_data)
9366 {
9367   GtkFileChooserDefault *impl = user_data;
9368   GtkTreeIter child_a, child_b;
9369   gboolean is_folder_a, is_folder_b;
9370   gchar *name_a, *name_b;
9371
9372   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_a, a);
9373   gtk_tree_model_filter_convert_iter_to_child_iter (GTK_TREE_MODEL_FILTER (model), &child_b, b);
9374
9375   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_a,
9376                       RECENT_MODEL_COL_IS_FOLDER, &is_folder_a,
9377                       RECENT_MODEL_COL_DISPLAY_NAME, &name_a,
9378                       -1);
9379   gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_b,
9380                       RECENT_MODEL_COL_IS_FOLDER, &is_folder_b,
9381                       RECENT_MODEL_COL_DISPLAY_NAME, &name_b,
9382                       -1);
9383
9384   if (!name_a)
9385     return 1;
9386
9387   if (!name_b)
9388     return -1;
9389
9390   if (is_folder_a != is_folder_b)
9391     return is_folder_a ? 1 : -1;
9392
9393   return strcmp (name_a, name_b);
9394 }
9395
9396 static gboolean
9397 recent_get_is_filtered (GtkFileChooserDefault *impl,
9398                         GFile                 *file,
9399                         GtkRecentInfo         *recent_info)
9400 {
9401   GtkFileFilterInfo filter_info;
9402   GtkFileFilterFlags needed;
9403   gboolean result;
9404
9405   if (!impl->current_filter)
9406     return FALSE;
9407
9408   filter_info.contains = GTK_FILE_FILTER_DISPLAY_NAME | GTK_FILE_FILTER_MIME_TYPE;
9409   needed = gtk_file_filter_get_needed (impl->current_filter);
9410
9411   filter_info.display_name = gtk_recent_info_get_display_name (recent_info);
9412   filter_info.mime_type = gtk_recent_info_get_mime_type (recent_info);
9413
9414   if (needed & GTK_FILE_FILTER_FILENAME)
9415     {
9416       filter_info.filename = g_file_get_path (file);
9417       if (filter_info.filename)
9418         filter_info.contains |= GTK_FILE_FILTER_FILENAME;
9419     }
9420   else
9421     filter_info.filename = NULL;
9422
9423   if (needed & GTK_FILE_FILTER_URI)
9424     {
9425       filter_info.uri = g_file_get_uri (file);
9426       if (filter_info.uri)
9427         filter_info.contains |= GTK_FILE_FILTER_URI;
9428     }
9429   else
9430     filter_info.uri = NULL;
9431
9432   result = gtk_file_filter_filter (impl->current_filter, &filter_info);
9433
9434   if (filter_info.filename)
9435     g_free ((gchar *) filter_info.filename);
9436   if (filter_info.uri)
9437     g_free ((gchar *) filter_info.uri);
9438
9439   return !result;
9440 }
9441
9442 /* Visibility function for the recent filter model */
9443 static gboolean
9444 recent_model_visible_func (GtkTreeModel *model,
9445                            GtkTreeIter  *iter,
9446                            gpointer      user_data)
9447 {
9448   GtkFileChooserDefault *impl = user_data;
9449   GFile *file;
9450   GtkRecentInfo *recent_info;
9451   gboolean is_folder;
9452
9453   if (!impl->current_filter)
9454     return TRUE;
9455
9456   gtk_tree_model_get (model, iter,
9457                       RECENT_MODEL_COL_INFO, &recent_info,
9458                       RECENT_MODEL_COL_FILE, &file,
9459                       RECENT_MODEL_COL_IS_FOLDER, &is_folder,
9460                       -1);
9461
9462   if (!recent_info)
9463     return TRUE;
9464
9465   if (is_folder)
9466     return TRUE;
9467
9468   return !recent_get_is_filtered (impl, file, recent_info);
9469 }
9470
9471 static void
9472 recent_setup_model (GtkFileChooserDefault *impl)
9473 {
9474   g_assert (impl->recent_model == NULL);
9475   g_assert (impl->recent_model_filter == NULL);
9476   g_assert (impl->recent_model_sort == NULL);
9477
9478   /* We store these columns in the search model:
9479    *
9480    * RECENT_MODEL_COL_FILE - a pointer to GFile for the hit's URI,
9481    *   stored as a pointer and not as a G_TYPE_FILE;
9482    * RECENT_MODEL_COL_DISPLAY_NAME - a string with the display name,
9483    *   stored as a pointer and not as a G_TYPE_STRING;
9484    * RECENT_MODEL_COL_INFO - GtkRecentInfo, stored as a pointer and not
9485    *   as a GTK_TYPE_RECENT_INFO;
9486    * RECENT_MODEL_COL_IS_FOLDER - boolean flag;
9487    * RECENT_MODEL_COL_CANCELLABLE - GCancellable, stored as a pointer
9488    *   and not as a G_TYPE_CANCELLABLE;
9489    *
9490    * Keep this in sync with the enumeration defined near the beginning of
9491    * this file.
9492    */
9493   impl->recent_model = gtk_list_store_new (RECENT_MODEL_COL_NUM_COLUMNS,
9494                                            G_TYPE_POINTER,
9495                                            G_TYPE_POINTER,
9496                                            G_TYPE_POINTER,
9497                                            G_TYPE_BOOLEAN,
9498                                            G_TYPE_POINTER);
9499
9500   impl->recent_model_filter =
9501     GTK_TREE_MODEL_FILTER (gtk_tree_model_filter_new (GTK_TREE_MODEL (impl->recent_model), NULL));
9502   gtk_tree_model_filter_set_visible_func (impl->recent_model_filter,
9503                                           recent_model_visible_func,
9504                                           impl,
9505                                           NULL);
9506   
9507   /* this is the model that will actually be added to
9508    * the browse_files_tree_view widget; remember: we are
9509    * stuffing the real model into a filter model and then
9510    * into a sort model; this means we'll have to translate
9511    * the child iterator *twice* to get from a path or an
9512    * iterator coming from the tree view widget to the
9513    * real data inside the model.
9514    */
9515   impl->recent_model_sort =
9516     GTK_TREE_MODEL_SORT (recent_model_sort_new (impl, GTK_TREE_MODEL (impl->recent_model_filter)));
9517   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model_sort),
9518                                    RECENT_MODEL_COL_FILE,
9519                                    recent_column_path_sort_func,
9520                                    impl, NULL);
9521   gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->recent_model_sort),
9522                                    RECENT_MODEL_COL_INFO,
9523                                    recent_column_mtime_sort_func,
9524                                    impl, NULL);
9525   gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (impl->recent_model_sort),
9526                                         RECENT_MODEL_COL_INFO,
9527                                         GTK_SORT_DESCENDING);
9528 }
9529
9530 typedef struct
9531 {
9532   GtkFileChooserDefault *impl;
9533   GList *items;
9534   gint n_items;
9535   gint n_loaded_items;
9536   guint needs_sorting : 1;
9537 } RecentLoadData;
9538
9539 static void
9540 recent_idle_cleanup (gpointer data)
9541 {
9542   RecentLoadData *load_data = data;
9543   GtkFileChooserDefault *impl = load_data->impl;
9544
9545   gtk_tree_view_set_model (GTK_TREE_VIEW (impl->browse_files_tree_view),
9546                            GTK_TREE_MODEL (impl->recent_model_sort));
9547
9548   set_busy_cursor (impl, FALSE);
9549   
9550   impl->load_recent_id = 0;
9551   
9552   if (load_data->items)
9553     {
9554       g_list_foreach (load_data->items, (GFunc) gtk_recent_info_unref, NULL);
9555       g_list_free (load_data->items);
9556     }
9557
9558   g_free (load_data);
9559 }
9560
9561 struct RecentItemInsertRequest
9562 {
9563   GtkFileChooserDefault *impl;
9564   GFile *file;
9565   GtkTreeRowReference *row_ref;
9566 };
9567
9568 static void
9569 recent_item_get_info_cb (GCancellable *cancellable,
9570                          GFileInfo    *info,
9571                          const GError *error,
9572                          gpointer      data)
9573 {
9574   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
9575   GtkTreePath *path;
9576   GtkTreeIter iter;
9577   GCancellable *model_cancellable;
9578   gboolean is_folder = FALSE;
9579   struct RecentItemInsertRequest *request = data;
9580
9581   if (!request->impl->recent_model)
9582     goto out;
9583
9584   path = gtk_tree_row_reference_get_path (request->row_ref);
9585   if (!path)
9586     goto out;
9587
9588   gtk_tree_model_get_iter (GTK_TREE_MODEL (request->impl->recent_model),
9589                            &iter, path);
9590   gtk_tree_path_free (path);
9591
9592   gtk_tree_model_get (GTK_TREE_MODEL (request->impl->recent_model), &iter,
9593                       RECENT_MODEL_COL_CANCELLABLE, &model_cancellable,
9594                       -1);
9595   if (cancellable != model_cancellable)
9596     goto out;
9597
9598   gtk_list_store_set (request->impl->recent_model, &iter,
9599                       RECENT_MODEL_COL_CANCELLABLE, NULL,
9600                       -1);
9601
9602   if (cancelled)
9603     goto out;
9604
9605   if (!info)
9606     {
9607       gtk_list_store_remove (request->impl->recent_model, &iter);
9608       goto out;
9609     }
9610
9611   is_folder = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
9612
9613   gtk_list_store_set (request->impl->recent_model, &iter,
9614                       RECENT_MODEL_COL_IS_FOLDER, is_folder,
9615                       -1);
9616
9617 out:
9618   g_object_unref (request->impl);
9619   g_object_unref (request->file);
9620   gtk_tree_row_reference_free (request->row_ref);
9621   g_free (request);
9622
9623   g_object_unref (cancellable);
9624 }
9625
9626 static gint
9627 recent_sort_mru (gconstpointer a,
9628                  gconstpointer b)
9629 {
9630   GtkRecentInfo *info_a = (GtkRecentInfo *) a;
9631   GtkRecentInfo *info_b = (GtkRecentInfo *) b;
9632
9633   return (gtk_recent_info_get_modified (info_b) - gtk_recent_info_get_modified (info_a));
9634 }
9635
9636 static gint
9637 get_recent_files_limit (GtkWidget *widget)
9638 {
9639   GtkSettings *settings;
9640   gint limit;
9641
9642   if (gtk_widget_has_screen (widget))
9643     settings = gtk_settings_get_for_screen (gtk_widget_get_screen (widget));
9644   else
9645     settings = gtk_settings_get_default ();
9646
9647   g_object_get (G_OBJECT (settings), "gtk-recent-files-limit", &limit, NULL);
9648
9649   return limit;
9650 }
9651
9652 static gboolean
9653 recent_idle_load (gpointer data)
9654 {
9655   RecentLoadData *load_data = data;
9656   GtkFileChooserDefault *impl = load_data->impl;
9657   GtkTreeIter iter;
9658   GtkTreePath *p;
9659   GtkRecentInfo *info;
9660   const gchar *uri, *display_name;
9661   GFile *file;
9662   GCancellable *cancellable;
9663   struct RecentItemInsertRequest *request;
9664
9665   if (!impl->recent_manager)
9666     return FALSE;
9667
9668   /* first iteration: load all the items */
9669   if (!load_data->items)
9670     {
9671       load_data->items = gtk_recent_manager_get_items (impl->recent_manager);
9672       if (!load_data->items)
9673         return FALSE;
9674
9675       load_data->needs_sorting = TRUE;
9676
9677       return TRUE;
9678     }
9679   
9680   /* second iteration: preliminary MRU sorting and clamping */
9681   if (load_data->needs_sorting)
9682     {
9683       gint limit;
9684
9685       load_data->items = g_list_sort (load_data->items, recent_sort_mru);
9686       load_data->n_items = g_list_length (load_data->items);
9687
9688       limit = get_recent_files_limit (GTK_WIDGET (impl));
9689       
9690       if (limit != -1 && (load_data->n_items > limit))
9691         {
9692           GList *clamp, *l;
9693
9694           clamp = g_list_nth (load_data->items, limit - 1);
9695           if (G_LIKELY (clamp))
9696             {
9697               l = clamp->next;
9698               clamp->next = NULL;
9699
9700               g_list_foreach (l, (GFunc) gtk_recent_info_unref, NULL);
9701               g_list_free (l);
9702
9703               load_data->n_items = limit;
9704             }
9705          }
9706
9707       load_data->n_loaded_items = 0;
9708       load_data->needs_sorting = FALSE;
9709
9710       return TRUE;
9711     }
9712
9713   info = g_list_nth_data (load_data->items, load_data->n_loaded_items);
9714   g_assert (info != NULL);
9715
9716   uri = gtk_recent_info_get_uri (info);
9717   display_name = gtk_recent_info_get_display_name (info);
9718   file = g_file_new_for_uri (uri);
9719
9720   gtk_list_store_append (impl->recent_model, &iter);
9721   p = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->recent_model), &iter);
9722
9723   request = g_new0 (struct RecentItemInsertRequest, 1);
9724   request->impl = g_object_ref (impl);
9725   request->file = g_object_ref (file);
9726   request->row_ref = gtk_tree_row_reference_new (GTK_TREE_MODEL (impl->recent_model), p);
9727   gtk_tree_path_free (p);
9728
9729   cancellable = _gtk_file_system_get_info (impl->file_system, file,
9730                                            "standard::type",
9731                                            recent_item_get_info_cb,
9732                                            request);
9733
9734   gtk_list_store_set (impl->recent_model, &iter,
9735                       RECENT_MODEL_COL_FILE, file,
9736                       RECENT_MODEL_COL_DISPLAY_NAME, g_strdup (display_name),
9737                       RECENT_MODEL_COL_INFO, gtk_recent_info_ref (info),
9738                       RECENT_MODEL_COL_CANCELLABLE, cancellable,
9739                       -1);
9740
9741   load_data->n_loaded_items += 1;
9742
9743   /* finished loading items */
9744   if (load_data->n_loaded_items == load_data->n_items)
9745     {
9746       g_list_foreach (load_data->items, (GFunc) gtk_recent_info_unref, NULL);
9747       g_list_free (load_data->items);
9748       load_data->items = NULL;
9749
9750       return FALSE;
9751     }
9752
9753   return TRUE;
9754 }
9755
9756 static void
9757 recent_start_loading (GtkFileChooserDefault *impl)
9758 {
9759   RecentLoadData *load_data;
9760
9761   recent_stop_loading (impl);
9762   recent_clear_model (impl, TRUE);
9763   recent_setup_model (impl);
9764   set_busy_cursor (impl, TRUE);
9765
9766   g_assert (impl->load_recent_id == 0);
9767
9768   load_data = g_new (RecentLoadData, 1);
9769   load_data->impl = impl;
9770   load_data->items = NULL;
9771   load_data->n_items = 0;
9772   load_data->n_loaded_items = 0;
9773   load_data->needs_sorting = TRUE;
9774
9775   /* begin lazy loading the recent files into the model */
9776   impl->load_recent_id = gdk_threads_add_idle_full (G_PRIORITY_HIGH_IDLE + 30,
9777                                                     recent_idle_load,
9778                                                     load_data,
9779                                                     recent_idle_cleanup);
9780 }
9781
9782 static void
9783 recent_selected_foreach_get_file_cb (GtkTreeModel *model,
9784                                      GtkTreePath  *path,
9785                                      GtkTreeIter  *iter,
9786                                      gpointer      data)
9787 {
9788   GSList **list;
9789   GFile *file;
9790
9791   list = data;
9792
9793   gtk_tree_model_get (model, iter, RECENT_MODEL_COL_FILE, &file, -1);
9794   *list = g_slist_prepend (*list, g_object_ref (file));
9795 }
9796
9797 /* Constructs a list of the selected paths in recent files mode */
9798 static GSList *
9799 recent_get_selected_files (GtkFileChooserDefault *impl)
9800 {
9801   GSList *result;
9802   GtkTreeSelection *selection;
9803
9804   result = NULL;
9805
9806   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9807   gtk_tree_selection_selected_foreach (selection, recent_selected_foreach_get_file_cb, &result);
9808   result = g_slist_reverse (result);
9809
9810   return result;
9811 }
9812
9813 /* Called from ::should_respond().  We return whether there are selected
9814  * files in the recent files list.
9815  */
9816 static gboolean
9817 recent_should_respond (GtkFileChooserDefault *impl)
9818 {
9819   GtkTreeSelection *selection;
9820
9821   g_assert (impl->operation_mode == OPERATION_MODE_RECENT);
9822
9823   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (impl->browse_files_tree_view));
9824   return (gtk_tree_selection_count_selected_rows (selection) != 0);
9825 }
9826
9827 /* Hide the location widgets temporarily */
9828 static void
9829 recent_hide_entry (GtkFileChooserDefault *impl)
9830 {
9831   gtk_widget_hide (impl->browse_path_bar);
9832   gtk_widget_hide (impl->browse_new_folder_button);
9833   
9834   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
9835       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
9836     {
9837       gtk_widget_hide (impl->location_button);
9838       gtk_widget_hide (impl->location_entry_box);
9839     }
9840 }
9841
9842 /* Main entry point to the recent files functions; this gets called when
9843  * the user activates the Recently Used shortcut.
9844  */
9845 static void
9846 recent_activate (GtkFileChooserDefault *impl)
9847 {
9848   OperationMode previous_mode;
9849
9850   if (impl->operation_mode == OPERATION_MODE_RECENT)
9851     return;
9852
9853   previous_mode = impl->operation_mode;
9854   impl->operation_mode = OPERATION_MODE_RECENT;
9855
9856   switch (previous_mode)
9857     {
9858     case OPERATION_MODE_SEARCH:
9859       search_stop_searching (impl, FALSE);
9860       search_clear_model (impl, TRUE);
9861
9862       gtk_widget_destroy (impl->search_hbox);
9863       impl->search_hbox = NULL;
9864       impl->search_entry = NULL;
9865       break;
9866
9867     case OPERATION_MODE_BROWSE:
9868       stop_loading_and_clear_list_model (impl);
9869       break;
9870
9871     case OPERATION_MODE_RECENT:
9872       g_assert_not_reached ();
9873       break;
9874     }
9875
9876   recent_hide_entry (impl);
9877   file_list_set_sort_column_ids (impl);
9878   recent_start_loading (impl);
9879 }
9880
9881 /* convert an iterator coming from the model bound to 
9882  * browse_files_tree_view to an interator inside the
9883  * real recent_model
9884  */
9885 static void
9886 recent_get_valid_child_iter (GtkFileChooserDefault *impl,
9887                              GtkTreeIter           *child_iter,
9888                              GtkTreeIter           *iter)
9889 {
9890   GtkTreeIter middle;
9891
9892   if (!impl->recent_model)
9893     return;
9894
9895   if (!impl->recent_model_filter || !impl->recent_model_sort)
9896     return;
9897
9898   /* pass 1: get the iterator in the filter model */
9899   gtk_tree_model_sort_convert_iter_to_child_iter (impl->recent_model_sort,
9900                                                   &middle, iter);
9901   
9902   /* pass 2: get the iterator in the real model */
9903   gtk_tree_model_filter_convert_iter_to_child_iter (impl->recent_model_filter,
9904                                                     child_iter,
9905                                                     &middle);
9906 }
9907
9908
9909 static void
9910 set_current_filter (GtkFileChooserDefault *impl,
9911                     GtkFileFilter         *filter)
9912 {
9913   if (impl->current_filter != filter)
9914     {
9915       int filter_index;
9916
9917       /* NULL filters are allowed to reset to non-filtered status
9918        */
9919       filter_index = g_slist_index (impl->filters, filter);
9920       if (impl->filters && filter && filter_index < 0)
9921         return;
9922
9923       if (impl->current_filter)
9924         g_object_unref (impl->current_filter);
9925       impl->current_filter = filter;
9926       if (impl->current_filter)
9927         {
9928           g_object_ref_sink (impl->current_filter);
9929         }
9930
9931       if (impl->filters)
9932         gtk_combo_box_set_active (GTK_COMBO_BOX (impl->filter_combo),
9933                                   filter_index);
9934
9935       if (impl->browse_files_model)
9936         install_list_model_filter (impl);
9937
9938       if (impl->search_model_filter)
9939         gtk_tree_model_filter_refilter (impl->search_model_filter);
9940
9941       if (impl->recent_model_filter)
9942         gtk_tree_model_filter_refilter (impl->recent_model_filter);
9943
9944       g_object_notify (G_OBJECT (impl), "filter");
9945     }
9946 }
9947
9948 static void
9949 filter_combo_changed (GtkComboBox           *combo_box,
9950                       GtkFileChooserDefault *impl)
9951 {
9952   gint new_index = gtk_combo_box_get_active (combo_box);
9953   GtkFileFilter *new_filter = g_slist_nth_data (impl->filters, new_index);
9954
9955   set_current_filter (impl, new_filter);
9956 }
9957
9958 static void
9959 check_preview_change (GtkFileChooserDefault *impl)
9960 {
9961   GtkTreePath *cursor_path;
9962   GFile *new_file;
9963   const char *new_display_name;
9964
9965   gtk_tree_view_get_cursor (GTK_TREE_VIEW (impl->browse_files_tree_view), &cursor_path, NULL);
9966   new_file = NULL;
9967   new_display_name = NULL;
9968   if (cursor_path)
9969     {
9970       GtkTreeIter child_iter;
9971
9972       if (impl->operation_mode == OPERATION_MODE_BROWSE)
9973         {
9974           if (impl->sort_model)
9975             {
9976               GtkTreeIter iter;
9977               GFileInfo *new_info;
9978
9979               gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->sort_model), &iter, cursor_path);
9980               gtk_tree_path_free (cursor_path);
9981
9982               gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model, &child_iter, &iter);
9983
9984               new_file = _gtk_file_system_model_get_file (impl->browse_files_model, &child_iter);
9985               new_info = _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
9986               if (new_info)
9987                 new_display_name = g_file_info_get_display_name (new_info);
9988             }
9989         }
9990       else if (impl->operation_mode == OPERATION_MODE_SEARCH)
9991         {
9992           GtkTreeIter iter;
9993
9994           gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->search_model_sort),
9995                                    &iter, cursor_path);
9996           gtk_tree_path_free (cursor_path);
9997
9998           search_get_valid_child_iter (impl, &child_iter, &iter);
9999           gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10000                               SEARCH_MODEL_COL_FILE, &new_file,
10001                               SEARCH_MODEL_COL_DISPLAY_NAME, &new_display_name,
10002                               -1);
10003         }
10004       else if (impl->operation_mode == OPERATION_MODE_RECENT)
10005         {
10006           GtkTreeIter iter;
10007
10008           gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->recent_model_sort),
10009                                    &iter, cursor_path);
10010           gtk_tree_path_free (cursor_path);
10011
10012           recent_get_valid_child_iter (impl, &child_iter, &iter);
10013           gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10014                               RECENT_MODEL_COL_FILE, &new_file,
10015                               RECENT_MODEL_COL_DISPLAY_NAME, &new_display_name,
10016                               -1);
10017         }
10018     }
10019
10020   if (new_file != impl->preview_file &&
10021       !(new_file && impl->preview_file &&
10022         g_file_equal (new_file, impl->preview_file)))
10023     {
10024       if (impl->preview_file)
10025         {
10026           g_object_unref (impl->preview_file);
10027           g_free (impl->preview_display_name);
10028         }
10029
10030       if (new_file)
10031         {
10032           impl->preview_file = g_object_ref (new_file);
10033           impl->preview_display_name = g_strdup (new_display_name);
10034         }
10035       else
10036         {
10037           impl->preview_file = NULL;
10038           impl->preview_display_name = NULL;
10039         }
10040
10041       if (impl->use_preview_label && impl->preview_label)
10042         gtk_label_set_text (GTK_LABEL (impl->preview_label), impl->preview_display_name);
10043
10044       g_signal_emit_by_name (impl, "update-preview");
10045     }
10046 }
10047
10048 static void
10049 shortcuts_activate_volume_mount_cb (GCancellable        *cancellable,
10050                                     GtkFileSystemVolume *volume,
10051                                     const GError        *error,
10052                                     gpointer             data)
10053 {
10054   GFile *file;
10055   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
10056   GtkFileChooserDefault *impl = data;
10057
10058   if (cancellable != impl->shortcuts_activate_iter_cancellable)
10059     goto out;
10060
10061   impl->shortcuts_activate_iter_cancellable = NULL;
10062
10063   set_busy_cursor (impl, FALSE);
10064
10065   if (cancelled)
10066     goto out;
10067
10068   if (error)
10069     {
10070       if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED))
10071         {
10072           char *msg, *name;
10073
10074           name = _gtk_file_system_volume_get_display_name (volume);
10075           msg = g_strdup_printf (_("Could not mount %s"), name);
10076
10077           error_message (impl, msg, error->message);
10078
10079           g_free (msg);
10080           g_free (name);
10081         }
10082
10083       goto out;
10084     }
10085
10086   file = _gtk_file_system_volume_get_root (volume);
10087   if (file != NULL)
10088     {
10089       change_folder_and_display_error (impl, file, FALSE);
10090       g_object_unref (file);
10091     }
10092
10093 out:
10094   g_object_unref (impl);
10095   g_object_unref (cancellable);
10096 }
10097
10098
10099 /* Activates a volume by mounting it if necessary and then switching to its
10100  * base path.
10101  */
10102 static void
10103 shortcuts_activate_volume (GtkFileChooserDefault *impl,
10104                            GtkFileSystemVolume   *volume)
10105 {
10106   GFile *file;
10107
10108   switch (impl->operation_mode)
10109     {
10110     case OPERATION_MODE_BROWSE:
10111       break;
10112     case OPERATION_MODE_SEARCH:
10113       search_switch_to_browse_mode (impl);
10114       break;
10115     case OPERATION_MODE_RECENT:
10116       recent_switch_to_browse_mode (impl);
10117       break;
10118     }
10119
10120   /* We ref the file chooser since volume_mount() may run a main loop, and the
10121    * user could close the file chooser window in the meantime.
10122    */
10123   g_object_ref (impl);
10124
10125   if (!_gtk_file_system_volume_is_mounted (volume))
10126     {
10127       set_busy_cursor (impl, TRUE);
10128
10129       impl->shortcuts_activate_iter_cancellable =
10130         _gtk_file_system_mount_volume (impl->file_system, volume, NULL,
10131                                        shortcuts_activate_volume_mount_cb,
10132                                        g_object_ref (impl));
10133     }
10134   else
10135     {
10136       file = _gtk_file_system_volume_get_root (volume);
10137       if (file != NULL)
10138         {
10139           change_folder_and_display_error (impl, file, FALSE);
10140           g_object_unref (file);
10141         }
10142     }
10143
10144   g_object_unref (impl);
10145 }
10146
10147 /* Opens the folder or volume at the specified iter in the shortcuts model */
10148 struct ShortcutsActivateData
10149 {
10150   GtkFileChooserDefault *impl;
10151   GFile *file;
10152 };
10153
10154 static void
10155 shortcuts_activate_get_info_cb (GCancellable *cancellable,
10156                                 GFileInfo    *info,
10157                                 const GError *error,
10158                                 gpointer      user_data)
10159 {
10160   gboolean cancelled = g_cancellable_is_cancelled (cancellable);
10161   struct ShortcutsActivateData *data = user_data;
10162
10163   if (cancellable != data->impl->shortcuts_activate_iter_cancellable)
10164     goto out;
10165
10166   data->impl->shortcuts_activate_iter_cancellable = NULL;
10167
10168   if (cancelled)
10169     goto out;
10170
10171   if (!error && g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
10172     change_folder_and_display_error (data->impl, data->file, FALSE);
10173   else
10174     gtk_file_chooser_default_select_file (GTK_FILE_CHOOSER (data->impl),
10175                                           data->file,
10176                                           NULL);
10177
10178 out:
10179   g_object_unref (data->impl);
10180   g_object_unref (data->file);
10181   g_free (data);
10182
10183   g_object_unref (cancellable);
10184 }
10185
10186 static void
10187 shortcuts_activate_mount_enclosing_volume (GCancellable        *cancellable,
10188                                            GtkFileSystemVolume *volume,
10189                                            const GError        *error,
10190                                            gpointer             user_data)
10191 {
10192   struct ShortcutsActivateData *data = user_data;
10193
10194   if (error)
10195     {
10196       error_changing_folder_dialog (data->impl, data->file, g_error_copy (error));
10197
10198       g_object_unref (data->impl);
10199       g_object_unref (data->file);
10200       g_free (data);
10201
10202       return;
10203     }
10204
10205   data->impl->shortcuts_activate_iter_cancellable =
10206     _gtk_file_system_get_info (data->impl->file_system, data->file,
10207                                "standard::type",
10208                                shortcuts_activate_get_info_cb, data);
10209 }
10210
10211 static void
10212 shortcuts_activate_iter (GtkFileChooserDefault *impl,
10213                          GtkTreeIter           *iter)
10214 {
10215   gpointer col_data;
10216   ShortcutType shortcut_type;
10217
10218   if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY
10219       && !(impl->action == GTK_FILE_CHOOSER_ACTION_SAVE
10220            || impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
10221     _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), "");
10222
10223   gtk_tree_model_get (GTK_TREE_MODEL (impl->shortcuts_model), iter,
10224                       SHORTCUTS_COL_DATA, &col_data,
10225                       SHORTCUTS_COL_TYPE, &shortcut_type,
10226                       -1);
10227
10228   if (impl->shortcuts_activate_iter_cancellable)
10229     {
10230       g_cancellable_cancel (impl->shortcuts_activate_iter_cancellable);
10231       impl->shortcuts_activate_iter_cancellable = NULL;
10232     }
10233
10234   if (shortcut_type == SHORTCUT_TYPE_SEPARATOR)
10235     return;
10236   else if (shortcut_type == SHORTCUT_TYPE_VOLUME)
10237     {
10238       GtkFileSystemVolume *volume;
10239
10240       volume = col_data;
10241
10242       shortcuts_activate_volume (impl, volume);
10243     }
10244   else if (shortcut_type == SHORTCUT_TYPE_FILE)
10245     {
10246       struct ShortcutsActivateData *data;
10247       GtkFileSystemVolume *volume;
10248
10249       volume = _gtk_file_system_get_volume_for_file (impl->file_system, col_data);
10250
10251       data = g_new0 (struct ShortcutsActivateData, 1);
10252       data->impl = g_object_ref (impl);
10253       data->file = g_object_ref (col_data);
10254
10255       if (!volume || !_gtk_file_system_volume_is_mounted (volume))
10256         {
10257           GMountOperation *mount_operation;
10258           GtkWidget *toplevel;
10259
10260           toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl));
10261
10262           mount_operation = gtk_mount_operation_new (GTK_WINDOW (toplevel));
10263
10264           impl->shortcuts_activate_iter_cancellable =
10265             _gtk_file_system_mount_enclosing_volume (impl->file_system, col_data,
10266                                                      mount_operation,
10267                                                      shortcuts_activate_mount_enclosing_volume,
10268                                                      data);
10269         }
10270       else
10271         {
10272           impl->shortcuts_activate_iter_cancellable =
10273             _gtk_file_system_get_info (impl->file_system, data->file,
10274                                        "standard::type",
10275                                        shortcuts_activate_get_info_cb, data);
10276         }
10277     }
10278   else if (shortcut_type == SHORTCUT_TYPE_SEARCH)
10279     {
10280       search_activate (impl);
10281     }
10282   else if (shortcut_type == SHORTCUT_TYPE_RECENT)
10283     {
10284       recent_activate (impl);
10285     }
10286 }
10287
10288 /* Handler for GtkWidget::key-press-event on the shortcuts list */
10289 static gboolean
10290 shortcuts_key_press_event_cb (GtkWidget             *widget,
10291                               GdkEventKey           *event,
10292                               GtkFileChooserDefault *impl)
10293 {
10294   guint modifiers;
10295
10296   modifiers = gtk_accelerator_get_default_mod_mask ();
10297
10298   if ((event->keyval == GDK_BackSpace
10299       || event->keyval == GDK_Delete
10300       || event->keyval == GDK_KP_Delete)
10301       && (event->state & modifiers) == 0)
10302     {
10303       remove_selected_bookmarks (impl);
10304       return TRUE;
10305     }
10306
10307   if ((event->keyval == GDK_F2)
10308       && (event->state & modifiers) == 0)
10309     {
10310       rename_selected_bookmark (impl);
10311       return TRUE;
10312     }
10313
10314   return FALSE;
10315 }
10316
10317 static gboolean
10318 shortcuts_select_func  (GtkTreeSelection  *selection,
10319                         GtkTreeModel      *model,
10320                         GtkTreePath       *path,
10321                         gboolean           path_currently_selected,
10322                         gpointer           data)
10323 {
10324   GtkFileChooserDefault *impl = data;
10325   GtkTreeIter filter_iter;
10326   ShortcutType shortcut_type;
10327
10328   if (!gtk_tree_model_get_iter (impl->shortcuts_pane_filter_model, &filter_iter, path))
10329     g_assert_not_reached ();
10330
10331   gtk_tree_model_get (impl->shortcuts_pane_filter_model, &filter_iter, SHORTCUTS_COL_TYPE, &shortcut_type, -1);
10332
10333   return shortcut_type != SHORTCUT_TYPE_SEPARATOR;
10334 }
10335
10336 static gboolean
10337 list_select_func  (GtkTreeSelection  *selection,
10338                    GtkTreeModel      *model,
10339                    GtkTreePath       *path,
10340                    gboolean           path_currently_selected,
10341                    gpointer           data)
10342 {
10343   GtkFileChooserDefault *impl = data;
10344
10345   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10346       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10347     {
10348       GtkTreeIter iter, child_iter;
10349
10350       switch (impl->operation_mode)
10351         {
10352         case OPERATION_MODE_SEARCH:
10353           {
10354             gboolean is_folder;
10355
10356             if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->search_model_sort), &iter, path))
10357               return FALSE;
10358
10359             search_get_valid_child_iter (impl, &child_iter, &iter);
10360             gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10361                                 SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10362                                 -1);
10363             if (!is_folder)
10364               return FALSE;
10365           }
10366           break;
10367
10368         case OPERATION_MODE_RECENT:
10369           {
10370             gboolean is_folder;
10371
10372             if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->recent_model_sort), &iter, path))
10373               return FALSE;
10374
10375             recent_get_valid_child_iter (impl, &child_iter, &iter);
10376             gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10377                                 RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10378                                 -1);
10379             if (!is_folder)
10380               return FALSE;
10381           }
10382           break;
10383
10384         case OPERATION_MODE_BROWSE:
10385           {
10386             GFileInfo *info;
10387
10388             if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->sort_model), &iter, path))
10389               return FALSE;
10390
10391             gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model, &child_iter, &iter);
10392             info = _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
10393             if (info && g_file_info_get_file_type (info) != G_FILE_TYPE_DIRECTORY)
10394               return FALSE;
10395           }
10396           break;
10397         }
10398     }
10399     
10400   return TRUE;
10401 }
10402
10403 static void
10404 list_selection_changed (GtkTreeSelection      *selection,
10405                         GtkFileChooserDefault *impl)
10406 {
10407   /* See if we are in the new folder editable row for Save mode */
10408   if (impl->operation_mode == OPERATION_MODE_BROWSE &&
10409       impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
10410     {
10411       GFileInfo *info;
10412       gboolean had_selection;
10413
10414       info = get_selected_file_info_from_file_list (impl, &had_selection);
10415       if (!had_selection)
10416         goto out; /* normal processing */
10417
10418       if (!info)
10419         return; /* We are on the editable row for New Folder */
10420     }
10421
10422  out:
10423
10424   if (impl->location_entry)
10425     update_chooser_entry (impl);
10426
10427   check_preview_change (impl);
10428   bookmarks_check_add_sensitivity (impl);
10429
10430   g_signal_emit_by_name (impl, "selection-changed", 0);
10431 }
10432
10433 /* Callback used when a row in the file list is activated */
10434 static void
10435 list_row_activated (GtkTreeView           *tree_view,
10436                     GtkTreePath           *path,
10437                     GtkTreeViewColumn     *column,
10438                     GtkFileChooserDefault *impl)
10439 {
10440   GtkTreeIter iter;
10441   GtkTreeIter child_iter;
10442
10443   switch (impl->operation_mode)
10444     {
10445     case OPERATION_MODE_SEARCH:
10446       {
10447         GFile *file;
10448         gboolean is_folder;
10449
10450         if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->search_model_sort), &iter, path))
10451           return;
10452
10453         search_get_valid_child_iter (impl, &child_iter, &iter);
10454         gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10455                             SEARCH_MODEL_COL_FILE, &file,
10456                             SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10457                             -1);
10458         
10459         if (is_folder)
10460           {
10461             change_folder_and_display_error (impl, file, FALSE);
10462             return;
10463           }
10464
10465         g_signal_emit_by_name (impl, "file-activated");
10466       }
10467       break;
10468
10469     case OPERATION_MODE_RECENT:
10470       {
10471         GFile *file;
10472         gboolean is_folder;
10473
10474         if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->recent_model_sort), &iter, path))
10475           return;
10476         
10477         recent_get_valid_child_iter (impl, &child_iter, &iter);
10478         gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10479                             RECENT_MODEL_COL_FILE, &file,
10480                             RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10481                             -1);
10482
10483         if (is_folder)
10484           {
10485             change_folder_and_display_error (impl, file, FALSE);
10486             return;
10487           }
10488         
10489         g_signal_emit_by_name (impl, "file-activated");
10490       }
10491       break;
10492     
10493     case OPERATION_MODE_BROWSE:
10494       {
10495         GFileInfo *info;
10496
10497         if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (impl->sort_model), &iter, path))
10498           return;
10499         
10500         gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
10501                                                         &child_iter, &iter);
10502         info = _gtk_file_system_model_get_info (impl->browse_files_model,
10503                                                 &child_iter);
10504
10505         if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
10506           {
10507             GFile *file;
10508
10509             file = _gtk_file_system_model_get_file (impl->browse_files_model, &child_iter);
10510             change_folder_and_display_error (impl, file, FALSE);
10511             return;
10512           }
10513
10514         if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
10515             impl->action == GTK_FILE_CHOOSER_ACTION_SAVE)
10516           g_signal_emit_by_name (impl, "file-activated");
10517       }
10518       break;
10519     }
10520 }
10521
10522 static void
10523 path_bar_clicked (GtkPathBar            *path_bar,
10524                   GFile                 *file,
10525                   GFile                 *child_file,
10526                   gboolean               child_is_hidden,
10527                   GtkFileChooserDefault *impl)
10528 {
10529   if (child_file)
10530     pending_select_files_add (impl, child_file);
10531
10532   if (!change_folder_and_display_error (impl, file, FALSE))
10533     return;
10534
10535   /* Say we have "/foo/bar/[.baz]" and the user clicks on "bar".  We should then
10536    * show hidden files so that ".baz" appears in the file list, as it will still
10537    * be shown in the path bar: "/foo/[bar]/.baz"
10538    */
10539   if (child_is_hidden)
10540     g_object_set (impl, "show-hidden", TRUE, NULL);
10541 }
10542
10543 static GFileInfo *
10544 get_list_file_info (GtkFileChooserDefault *impl,
10545                     GtkTreeIter           *iter)
10546 {
10547   GtkTreeIter child_iter;
10548
10549   gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
10550                                                   &child_iter,
10551                                                   iter);
10552
10553   return _gtk_file_system_model_get_info (impl->browse_files_model, &child_iter);
10554 }
10555
10556 static void
10557 list_icon_data_func (GtkTreeViewColumn *tree_column,
10558                      GtkCellRenderer   *cell,
10559                      GtkTreeModel      *tree_model,
10560                      GtkTreeIter       *iter,
10561                      gpointer           data)
10562 {
10563   GtkFileChooserDefault *impl = data;
10564   GtkTreeIter child_iter;
10565   GdkPixbuf *pixbuf = NULL;
10566   gboolean sensitive = TRUE;
10567
10568   profile_start ("start", NULL);
10569   
10570   switch (impl->operation_mode)
10571     {
10572     case OPERATION_MODE_SEARCH:
10573       {
10574         GtkTreeIter child_iter;
10575         gboolean is_folder;
10576
10577         search_get_valid_child_iter (impl, &child_iter, iter);
10578         gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10579                             SEARCH_MODEL_COL_PIXBUF, &pixbuf,
10580                             SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10581                             -1);
10582         
10583         if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10584             impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10585           sensitive = is_folder;
10586       }
10587       break;
10588
10589     case OPERATION_MODE_RECENT:
10590       {
10591         GtkTreeIter child_iter;
10592         GtkRecentInfo *info;
10593         gboolean is_folder;
10594
10595         recent_get_valid_child_iter (impl, &child_iter, iter);
10596         gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10597                             RECENT_MODEL_COL_INFO, &info,
10598                             RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10599                             -1);
10600         
10601         pixbuf = gtk_recent_info_get_icon (info, impl->icon_size);
10602       
10603         if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER || 
10604             impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10605           sensitive = is_folder;
10606       }
10607       break;
10608     
10609     case OPERATION_MODE_BROWSE:
10610       {
10611         GFileInfo *info;
10612         GFile *file;
10613
10614         info = get_list_file_info (impl, iter);
10615
10616         gtk_tree_model_sort_convert_iter_to_child_iter (impl->sort_model,
10617                                                         &child_iter,
10618                                                         iter);
10619         file = _gtk_file_system_model_get_file (impl->browse_files_model, &child_iter);
10620         if (file)
10621           {
10622             if (info)
10623               {
10624                 /* FIXME: NULL GError */
10625                 pixbuf = _gtk_file_info_render_icon (info, GTK_WIDGET (impl), impl->icon_size);
10626               }
10627           }
10628         else
10629           {
10630             /* We are on the editable row */
10631             pixbuf = NULL;
10632           }
10633
10634         if (info &&
10635             (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10636              impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER))
10637           sensitive = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
10638       }
10639       break;
10640     }
10641     
10642   g_object_set (cell,
10643                 "pixbuf", pixbuf,
10644                 "sensitive", sensitive,
10645                 NULL);
10646     
10647   if (pixbuf)
10648     g_object_unref (pixbuf);
10649
10650   profile_end ("end", NULL);
10651 }
10652
10653 static void
10654 list_name_data_func (GtkTreeViewColumn *tree_column,
10655                      GtkCellRenderer   *cell,
10656                      GtkTreeModel      *tree_model,
10657                      GtkTreeIter       *iter,
10658                      gpointer           data)
10659 {
10660   GtkFileChooserDefault *impl = data;
10661   GFileInfo *info;
10662   gboolean sensitive = TRUE;
10663
10664   if (impl->operation_mode == OPERATION_MODE_SEARCH)
10665     {
10666       GtkTreeIter child_iter;
10667       gchar *display_name;
10668       gboolean is_folder;
10669
10670       search_get_valid_child_iter (impl, &child_iter, iter);
10671       gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10672                           SEARCH_MODEL_COL_DISPLAY_NAME, &display_name,
10673                           SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10674                           -1);
10675
10676       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10677           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10678         {
10679           sensitive = is_folder;
10680         }
10681
10682       g_object_set (cell,
10683                     "text", display_name,
10684                     "sensitive", sensitive,
10685                     "ellipsize", PANGO_ELLIPSIZE_END,
10686                     NULL);
10687       
10688       return;
10689     }
10690
10691   if (impl->operation_mode == OPERATION_MODE_RECENT)
10692     {
10693       GtkTreeIter child_iter;
10694       GtkRecentInfo *recent_info;
10695       gchar *display_name;
10696       gboolean is_folder;
10697
10698       recent_get_valid_child_iter (impl, &child_iter, iter);
10699       gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10700                           RECENT_MODEL_COL_INFO, &recent_info,
10701                           RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10702                           -1);
10703       
10704       display_name = gtk_recent_info_get_short_name (recent_info);
10705
10706       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10707           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10708         {
10709           sensitive = is_folder;
10710         }
10711
10712       g_object_set (cell,
10713                     "text", display_name,
10714                     "sensitive", sensitive,
10715                     "ellipsize", PANGO_ELLIPSIZE_END,
10716                     NULL);
10717
10718       g_free (display_name);
10719
10720       return;
10721     }
10722
10723   info = get_list_file_info (impl, iter);
10724   sensitive = TRUE;
10725
10726   if (!info)
10727     {
10728       g_object_set (cell,
10729                     "text", _("Type name of new folder"),
10730                     "sensitive", TRUE,
10731                     "ellipsize", PANGO_ELLIPSIZE_NONE,
10732                     NULL);
10733
10734       return;
10735     }
10736
10737
10738   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10739       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10740     {
10741       sensitive = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
10742     }
10743
10744   g_object_set (cell,
10745                 "text", g_file_info_get_display_name (info),
10746                 "sensitive", sensitive,
10747                 "ellipsize", PANGO_ELLIPSIZE_END,
10748                 NULL);
10749 }
10750
10751 #if 0
10752 static void
10753 list_size_data_func (GtkTreeViewColumn *tree_column,
10754                      GtkCellRenderer   *cell,
10755                      GtkTreeModel      *tree_model,
10756                      GtkTreeIter       *iter,
10757                      gpointer           data)
10758 {
10759   GtkFileChooserDefault *impl = data;
10760   GFileInfo *info = get_list_file_info (impl, iter);
10761   gint64 size;
10762   gchar *str;
10763   gboolean sensitive = TRUE;
10764
10765   if (!info || g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
10766     {
10767       g_object_set (cell,
10768                     "text", NULL,
10769                     "sensitive", sensitive,
10770                     NULL);
10771       return;
10772     }
10773
10774   size = gtk_file_info_get_size (info);
10775 #if 0
10776   if (size < (gint64)1024)
10777     str = g_strdup_printf (g_dngettext (GETTEXT_DOMAIN, "%d byte", "%d bytes", (gint)size), (gint)size);
10778   else if (size < (gint64)1024*1024)
10779     str = g_strdup_printf (_("%.1f KB"), size / (1024.));
10780   else if (size < (gint64)1024*1024*1024)
10781     str = g_strdup_printf (_("%.1f MB"), size / (1024.*1024.));
10782   else
10783     str = g_strdup_printf (_("%.1f GB"), size / (1024.*1024.*1024.));
10784 #endif
10785   str = g_strdup_printf ("%" G_GINT64_FORMAT, size);
10786   if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10787       impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10788     sensitive = FALSE;
10789
10790   g_object_set (cell,
10791                 "text", str,
10792                 "sensitive", sensitive,
10793                 "alignment", PANGO_ALIGN_RIGHT,
10794                 NULL);
10795
10796   g_free (str);
10797 }
10798 #endif
10799
10800 /* Tree column data callback for the file list; fetches the mtime of a file */
10801 static void
10802 list_mtime_data_func (GtkTreeViewColumn *tree_column,
10803                       GtkCellRenderer   *cell,
10804                       GtkTreeModel      *tree_model,
10805                       GtkTreeIter       *iter,
10806                       gpointer           data)
10807 {
10808   GtkFileChooserDefault *impl;
10809   GTimeVal timeval = { 0, };
10810   time_t time_mtime;
10811   gchar *date_str = NULL;
10812   gboolean sensitive = TRUE;
10813 #ifdef G_OS_WIN32
10814   const char *locale, *dot = NULL;
10815   gint64 codepage = -1;
10816   char charset[20];
10817 #endif
10818
10819   impl = data;
10820
10821   if (impl->operation_mode == OPERATION_MODE_SEARCH)
10822     {
10823       GtkTreeIter child_iter;
10824       struct stat *statbuf;
10825       gboolean is_folder;
10826
10827       search_get_valid_child_iter (impl, &child_iter, iter);
10828       gtk_tree_model_get (GTK_TREE_MODEL (impl->search_model), &child_iter,
10829                           SEARCH_MODEL_COL_STAT, &statbuf,
10830                           SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
10831                           -1);
10832       if (statbuf)
10833         time_mtime = statbuf->st_mtime;
10834       else
10835         time_mtime = 0;
10836
10837
10838       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10839           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10840         sensitive = is_folder;
10841     }
10842   else if (impl->operation_mode == OPERATION_MODE_RECENT)
10843     {
10844       GtkTreeIter child_iter;
10845       GtkRecentInfo *info;
10846       gboolean is_folder;
10847
10848       recent_get_valid_child_iter (impl, &child_iter, iter);
10849       gtk_tree_model_get (GTK_TREE_MODEL (impl->recent_model), &child_iter,
10850                           RECENT_MODEL_COL_INFO, &info,
10851                           RECENT_MODEL_COL_IS_FOLDER, &is_folder,
10852                           -1);
10853
10854       if (info)
10855         time_mtime = gtk_recent_info_get_modified (info);
10856       else
10857         time_mtime = 0;
10858
10859       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10860           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10861         sensitive = is_folder;
10862     }
10863   else
10864     {
10865       GFileInfo *info;
10866
10867       info = get_list_file_info (impl, iter);
10868       if (!info)
10869         {
10870           g_object_set (cell,
10871                         "text", "",
10872                         "sensitive", TRUE,
10873                         NULL);
10874           return;
10875         }
10876
10877       g_file_info_get_modification_time (info, &timeval);
10878       time_mtime = timeval.tv_sec;
10879
10880       if (impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER ||
10881           impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
10882         sensitive = (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
10883     }
10884
10885   if (G_UNLIKELY (time_mtime == 0))
10886     date_str = g_strdup (_("Unknown"));
10887   else
10888     {
10889       GDate mtime, now;
10890       gint days_diff;
10891       struct tm tm_mtime;
10892       time_t time_now;
10893       const gchar *format;
10894       gchar *locale_format = NULL;
10895       gchar buf[256];
10896
10897 #ifdef HAVE_LOCALTIME_R
10898       localtime_r ((time_t *) &time_mtime, &tm_mtime);
10899 #else
10900       {
10901         struct tm *ptm = localtime ((time_t *) &timeval.tv_sec);
10902
10903         if (!ptm)
10904           {
10905             g_warning ("ptm != NULL failed");
10906             
10907             g_object_set (cell,
10908                           "text", _("Unknown"),
10909                           "sensitive", sensitive,
10910                           NULL);
10911             return;
10912           }
10913         else
10914           memcpy ((void *) &tm_mtime, (void *) ptm, sizeof (struct tm));
10915       }
10916 #endif /* HAVE_LOCALTIME_R */
10917
10918       g_date_set_time_t (&mtime, time_mtime);
10919       time_now = time (NULL);
10920       g_date_set_time_t (&now, time_now);
10921
10922       days_diff = g_date_get_julian (&now) - g_date_get_julian (&mtime);
10923
10924       /* Translators: %H means "hours" and %M means "minutes" */
10925       if (days_diff == 0)
10926         format = _("%H:%M");
10927       else if (days_diff == 1)
10928         format = _("Yesterday at %H:%M");
10929       else
10930         {
10931           if (days_diff > 1 && days_diff < 7)
10932             format = "%A"; /* Days from last week */
10933           else
10934             format = "%x"; /* Any other date */
10935         }
10936
10937 #ifdef G_OS_WIN32
10938       /* g_locale_from_utf8() returns a string in the system
10939        * code-page, which is not always the same as that used by the C
10940        * library. For instance when running a GTK+ program with
10941        * LANG=ko on an English version of Windows, the system
10942        * code-page is 1252, but the code-page used by the C library is
10943        * 949. (It's GTK+ itself that sets the C library locale when it
10944        * notices the LANG environment variable. See gtkmain.c The
10945        * Microsoft C library doesn't look at any locale environment
10946        * variables.) We need to pass strftime() a string in the C
10947        * library's code-page. See bug #509885.
10948        */
10949       locale = setlocale (LC_ALL, NULL);
10950       if (locale != NULL)
10951         dot = strchr (locale, '.');
10952       if (dot != NULL)
10953         {
10954           codepage = g_ascii_strtoll (dot+1, NULL, 10);
10955           
10956           /* All codepages should fit in 16 bits AFAIK */
10957           if (codepage > 0 && codepage < 65536)
10958             {
10959               sprintf (charset, "CP%u", (guint) codepage);
10960               locale_format = g_convert (format, -1, charset, "UTF-8", NULL, NULL, NULL);
10961             }
10962         }
10963 #else
10964       locale_format = g_locale_from_utf8 (format, -1, NULL, NULL, NULL);
10965 #endif
10966       if (locale_format != NULL &&
10967           strftime (buf, sizeof (buf), locale_format, &tm_mtime) != 0)
10968         {
10969 #ifdef G_OS_WIN32
10970           /* As above but in opposite direction... */
10971           if (codepage > 0 && codepage < 65536)
10972             date_str = g_convert (buf, -1, "UTF-8", charset, NULL, NULL, NULL);
10973 #else
10974           date_str = g_locale_to_utf8 (buf, -1, NULL, NULL, NULL);
10975 #endif
10976         }
10977
10978       if (date_str == NULL)
10979         date_str = g_strdup (_("Unknown"));
10980
10981       g_free (locale_format);
10982     }
10983
10984   g_object_set (cell,
10985                 "text", date_str,
10986                 "sensitive", sensitive,
10987                 NULL);
10988   g_free (date_str);
10989 }
10990
10991 GtkWidget *
10992 _gtk_file_chooser_default_new (const char *file_system)
10993 {
10994   return  g_object_new (GTK_TYPE_FILE_CHOOSER_DEFAULT,
10995                         "file-system-backend", file_system,
10996                         NULL);
10997 }
10998
10999 static void
11000 location_set_user_text (GtkFileChooserDefault *impl,
11001                         const gchar           *path)
11002 {
11003   _gtk_file_chooser_entry_set_file_part (GTK_FILE_CHOOSER_ENTRY (impl->location_entry), path);
11004   gtk_editable_set_position (GTK_EDITABLE (impl->location_entry), -1);
11005 }
11006
11007 static void
11008 location_popup_handler (GtkFileChooserDefault *impl,
11009                         const gchar           *path)
11010
11011   if (impl->operation_mode != OPERATION_MODE_BROWSE)
11012     {
11013       GtkWidget *widget_to_focus;
11014       
11015       /* This will give us the location widgets back */
11016       switch (impl->operation_mode)
11017         {
11018         case OPERATION_MODE_SEARCH:
11019           search_switch_to_browse_mode (impl);
11020           break;
11021         case OPERATION_MODE_RECENT:
11022           recent_switch_to_browse_mode (impl);
11023           break;
11024         case OPERATION_MODE_BROWSE:
11025           g_assert_not_reached ();
11026           break;
11027         }
11028
11029       if (impl->current_folder)
11030         change_folder_and_display_error (impl, impl->current_folder, FALSE);
11031
11032       if (impl->location_mode == LOCATION_MODE_PATH_BAR)
11033         widget_to_focus = impl->browse_files_tree_view;
11034       else
11035         widget_to_focus = impl->location_entry;
11036
11037       gtk_widget_grab_focus (widget_to_focus);
11038       return; 
11039     }
11040   
11041   if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN ||
11042       impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER)
11043     {
11044       LocationMode new_mode;
11045
11046       if (path != NULL)
11047         {
11048           /* since the user typed something, we unconditionally want to turn on the entry */
11049           new_mode = LOCATION_MODE_FILENAME_ENTRY;
11050         }
11051       else if (impl->location_mode == LOCATION_MODE_PATH_BAR)
11052         new_mode = LOCATION_MODE_FILENAME_ENTRY;
11053       else if (impl->location_mode == LOCATION_MODE_FILENAME_ENTRY)
11054         new_mode = LOCATION_MODE_PATH_BAR;
11055       else
11056         {
11057           g_assert_not_reached ();
11058           return;
11059         }
11060
11061       location_mode_set (impl, new_mode, TRUE);
11062       if (new_mode == LOCATION_MODE_FILENAME_ENTRY)
11063         {
11064           if (path != NULL)
11065             location_set_user_text (impl, path);
11066           else
11067             {
11068               location_entry_set_initial_text (impl);
11069               gtk_editable_select_region (GTK_EDITABLE (impl->location_entry), 0, -1);
11070             }
11071         }
11072     }
11073   else if (impl->action == GTK_FILE_CHOOSER_ACTION_SAVE ||
11074            impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER)
11075     {
11076       gtk_widget_grab_focus (impl->location_entry);
11077       if (path != NULL)
11078         location_set_user_text (impl, path);
11079     }
11080   else
11081     g_assert_not_reached ();
11082 }
11083
11084 /* Handler for the "up-folder" keybinding signal */
11085 static void
11086 up_folder_handler (GtkFileChooserDefault *impl)
11087 {
11088   _gtk_path_bar_up (GTK_PATH_BAR (impl->browse_path_bar));
11089 }
11090
11091 /* Handler for the "down-folder" keybinding signal */
11092 static void
11093 down_folder_handler (GtkFileChooserDefault *impl)
11094 {
11095   _gtk_path_bar_down (GTK_PATH_BAR (impl->browse_path_bar));
11096 }
11097
11098 /* Switches to the shortcut in the specified index */
11099 static void
11100 switch_to_shortcut (GtkFileChooserDefault *impl,
11101                     int pos)
11102 {
11103   GtkTreeIter iter;
11104
11105   if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (impl->shortcuts_model), &iter, NULL, pos))
11106     g_assert_not_reached ();
11107
11108   shortcuts_activate_iter (impl, &iter);
11109 }
11110
11111 /* Handler for the "home-folder" keybinding signal */
11112 static void
11113 home_folder_handler (GtkFileChooserDefault *impl)
11114 {
11115   if (impl->has_home)
11116     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_HOME));
11117 }
11118
11119 /* Handler for the "desktop-folder" keybinding signal */
11120 static void
11121 desktop_folder_handler (GtkFileChooserDefault *impl)
11122 {
11123   if (impl->has_desktop)
11124     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_DESKTOP));
11125 }
11126
11127 /* Handler for the "search-shortcut" keybinding signal */
11128 static void
11129 search_shortcut_handler (GtkFileChooserDefault *impl)
11130 {
11131   if (impl->has_search)
11132     {
11133       switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_SEARCH));
11134
11135       /* we want the entry widget to grab the focus the first
11136        * time, not the browse_files_tree_view widget.
11137        */
11138       if (impl->search_entry)
11139         gtk_widget_grab_focus (impl->search_entry);
11140     }
11141 }
11142
11143 /* Handler for the "recent-shortcut" keybinding signal */
11144 static void
11145 recent_shortcut_handler (GtkFileChooserDefault *impl)
11146 {
11147   if (impl->has_recent)
11148     switch_to_shortcut (impl, shortcuts_get_index (impl, SHORTCUTS_RECENT));
11149 }
11150
11151 static void
11152 quick_bookmark_handler (GtkFileChooserDefault *impl,
11153                         gint bookmark_index)
11154 {
11155   int bookmark_pos;
11156   GtkTreePath *path;
11157
11158   if (bookmark_index < 0 || bookmark_index >= impl->num_bookmarks)
11159     return;
11160
11161   bookmark_pos = shortcuts_get_index (impl, SHORTCUTS_BOOKMARKS) + bookmark_index;
11162
11163   path = gtk_tree_path_new_from_indices (bookmark_pos, -1);
11164   gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (impl->browse_shortcuts_tree_view),
11165                                 path, NULL,
11166                                 FALSE, 0.0, 0.0);
11167   gtk_tree_path_free (path);
11168
11169   switch_to_shortcut (impl, bookmark_pos);
11170 }
11171
11172 static void
11173 show_hidden_handler (GtkFileChooserDefault *impl)
11174 {
11175   g_object_set (impl,
11176                 "show-hidden", !impl->show_hidden,
11177                 NULL);
11178 }
11179
11180
11181 /* Drag and drop interfaces */
11182
11183 static void
11184 _shortcuts_pane_model_filter_class_init (ShortcutsPaneModelFilterClass *class)
11185 {
11186 }
11187
11188 static void
11189 _shortcuts_pane_model_filter_init (ShortcutsPaneModelFilter *model)
11190 {
11191   model->impl = NULL;
11192 }
11193
11194 /* GtkTreeDragSource::row_draggable implementation for the shortcuts filter model */
11195 static gboolean
11196 shortcuts_pane_model_filter_row_draggable (GtkTreeDragSource *drag_source,
11197                                            GtkTreePath       *path)
11198 {
11199   ShortcutsPaneModelFilter *model;
11200   int pos;
11201   int bookmarks_pos;
11202
11203   model = SHORTCUTS_PANE_MODEL_FILTER (drag_source);
11204
11205   pos = *gtk_tree_path_get_indices (path);
11206   bookmarks_pos = shortcuts_get_index (model->impl, SHORTCUTS_BOOKMARKS);
11207
11208   return (pos >= bookmarks_pos && pos < bookmarks_pos + model->impl->num_bookmarks);
11209 }
11210
11211 /* GtkTreeDragSource::drag_data_get implementation for the shortcuts filter model */
11212 static gboolean
11213 shortcuts_pane_model_filter_drag_data_get (GtkTreeDragSource *drag_source,
11214                                            GtkTreePath       *path,
11215                                            GtkSelectionData  *selection_data)
11216 {
11217   ShortcutsPaneModelFilter *model;
11218
11219   model = SHORTCUTS_PANE_MODEL_FILTER (drag_source);
11220
11221   /* FIXME */
11222
11223   return FALSE;
11224 }
11225
11226 /* Fill the GtkTreeDragSourceIface vtable */
11227 static void
11228 shortcuts_pane_model_filter_drag_source_iface_init (GtkTreeDragSourceIface *iface)
11229 {
11230   iface->row_draggable = shortcuts_pane_model_filter_row_draggable;
11231   iface->drag_data_get = shortcuts_pane_model_filter_drag_data_get;
11232 }
11233
11234 #if 0
11235 /* Fill the GtkTreeDragDestIface vtable */
11236 static void
11237 shortcuts_pane_model_filter_drag_dest_iface_init (GtkTreeDragDestIface *iface)
11238 {
11239   iface->drag_data_received = shortcuts_pane_model_filter_drag_data_received;
11240   iface->row_drop_possible = shortcuts_pane_model_filter_row_drop_possible;
11241 }
11242 #endif
11243
11244 static GtkTreeModel *
11245 shortcuts_pane_model_filter_new (GtkFileChooserDefault *impl,
11246                                  GtkTreeModel          *child_model,
11247                                  GtkTreePath           *root)
11248 {
11249   ShortcutsPaneModelFilter *model;
11250
11251   model = g_object_new (SHORTCUTS_PANE_MODEL_FILTER_TYPE,
11252                         "child-model", child_model,
11253                         "virtual-root", root,
11254                         NULL);
11255
11256   model->impl = impl;
11257
11258   return GTK_TREE_MODEL (model);
11259 }
11260
11261 \f
11262
11263 static gboolean
11264 recent_model_sort_row_draggable (GtkTreeDragSource *drag_source,
11265                                  GtkTreePath       *path)
11266 {
11267   RecentModelSort *model;
11268   GtkTreeIter iter, child_iter;
11269   gboolean is_folder;
11270
11271   model = RECENT_MODEL_SORT (drag_source);
11272   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
11273     return FALSE;
11274
11275   recent_get_valid_child_iter (model->impl, &child_iter, &iter);
11276   gtk_tree_model_get (GTK_TREE_MODEL (model->impl->recent_model), &child_iter,
11277                       RECENT_MODEL_COL_IS_FOLDER, &is_folder,
11278                       -1);
11279
11280   return is_folder;
11281 }
11282
11283 static gboolean
11284 recent_model_sort_drag_data_get (GtkTreeDragSource *drag_source,
11285                                  GtkTreePath       *path,
11286                                  GtkSelectionData  *selection_data)
11287 {
11288   RecentModelSort *model;
11289   GtkTreeIter iter, child_iter;
11290   GFile *file;
11291   gchar *uris[2];
11292
11293   model = RECENT_MODEL_SORT (drag_source);
11294   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
11295     return FALSE;
11296
11297   recent_get_valid_child_iter (model->impl, &child_iter, &iter);
11298   gtk_tree_model_get (GTK_TREE_MODEL (model->impl->recent_model), &child_iter,
11299                       RECENT_MODEL_COL_FILE, &file,
11300                       -1);
11301   g_assert (file != NULL);
11302
11303   uris[0] = g_file_get_uri (file);
11304   uris[1] = NULL;
11305
11306   gtk_selection_data_set_uris (selection_data, uris);
11307
11308   g_free (uris[0]);
11309
11310   return TRUE;
11311 }
11312
11313 static void
11314 recent_model_sort_drag_source_iface_init (GtkTreeDragSourceIface *iface)
11315 {
11316   iface->row_draggable = recent_model_sort_row_draggable;
11317   iface->drag_data_get = recent_model_sort_drag_data_get;
11318 }
11319
11320 static void
11321 _recent_model_sort_class_init (RecentModelSortClass *klass)
11322 {
11323
11324 }
11325
11326 static void
11327 _recent_model_sort_init (RecentModelSort *model)
11328 {
11329   model->impl = NULL;
11330 }
11331
11332 static GtkTreeModel *
11333 recent_model_sort_new (GtkFileChooserDefault *impl,
11334                        GtkTreeModel          *child_model)
11335 {
11336   RecentModelSort *model;
11337
11338   model = g_object_new (RECENT_MODEL_SORT_TYPE,
11339                         "model", child_model,
11340                         NULL);
11341   model->impl = impl;
11342
11343   return GTK_TREE_MODEL (model);
11344 }
11345
11346 \f
11347
11348 static gboolean
11349 search_model_sort_row_draggable (GtkTreeDragSource *drag_source,
11350                                  GtkTreePath       *path)
11351 {
11352   SearchModelSort *model;
11353   GtkTreeIter iter, child_iter;
11354   gboolean is_folder;
11355
11356   model = SEARCH_MODEL_SORT (drag_source);
11357   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
11358     return FALSE;
11359
11360   search_get_valid_child_iter (model->impl, &child_iter, &iter);
11361   gtk_tree_model_get (GTK_TREE_MODEL (model->impl->search_model), &child_iter,
11362                       SEARCH_MODEL_COL_IS_FOLDER, &is_folder,
11363                       -1);
11364
11365   return is_folder;
11366 }
11367
11368 static gboolean
11369 search_model_sort_drag_data_get (GtkTreeDragSource *drag_source,
11370                                  GtkTreePath       *path,
11371                                  GtkSelectionData  *selection_data)
11372 {
11373   SearchModelSort *model;
11374   GtkTreeIter iter, child_iter;
11375   GFile *file;
11376   gchar *uris[2];
11377
11378   model = SEARCH_MODEL_SORT (drag_source);
11379   if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
11380     return FALSE;
11381
11382   search_get_valid_child_iter (model->impl, &child_iter, &iter);
11383   gtk_tree_model_get (GTK_TREE_MODEL (model->impl->search_model), &child_iter,
11384                       RECENT_MODEL_COL_FILE, &file,
11385                       -1);
11386   g_assert (file != NULL);
11387
11388   uris[0] = g_file_get_uri (file);
11389   uris[1] = NULL;
11390
11391   gtk_selection_data_set_uris (selection_data, uris);
11392
11393   g_free (uris[0]);
11394
11395   return TRUE;
11396 }
11397
11398 static void
11399 search_model_sort_drag_source_iface_init (GtkTreeDragSourceIface *iface)
11400 {
11401   iface->row_draggable = search_model_sort_row_draggable;
11402   iface->drag_data_get = search_model_sort_drag_data_get;
11403 }
11404
11405 static void
11406 _search_model_sort_class_init (SearchModelSortClass *klass)
11407 {
11408
11409 }
11410
11411 static void
11412 _search_model_sort_init (SearchModelSort *model)
11413 {
11414   model->impl = NULL;
11415 }
11416
11417 static GtkTreeModel *
11418 search_model_sort_new (GtkFileChooserDefault *impl,
11419                        GtkTreeModel          *child_model)
11420 {
11421   SearchModelSort *model;
11422
11423   model = g_object_new (SEARCH_MODEL_SORT_TYPE,
11424                         "model", child_model,
11425                         NULL);
11426   model->impl = impl;
11427
11428   return GTK_TREE_MODEL (model);
11429 }