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