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