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