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