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