]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilesystemmodel.c
s/get_is_visible/iter_is_visible for clarity
[~andy/gtk] / gtk / gtkfilesystemmodel.c
1 /* GTK - The GIMP Toolkit
2  * gtkfilesystemmodel.c: GtkTreeModel wrapping a GtkFileSystem
3  * Copyright (C) 2003, Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "gtkfilesystemmodel.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "gtkfilesystem.h"
29 #include "gtkintl.h"
30 #include "gtkmarshalers.h"
31 #include "gtktreedatalist.h"
32 #include "gtktreednd.h"
33 #include "gtktreemodel.h"
34 #include "gtkalias.h"
35
36 /*** Structure: how GtkFileSystemModel works
37  *
38  * This is a custom GtkTreeModel used to hold a collection of files for GtkFileChooser.  There are two use cases:
39  *
40  *   1. The model populates itself from a folder, using the GIO file enumerator API.  This happens if you use
41  *      _gtk_file_system_model_new_for_directory().  This is the normal usage for showing the contents of a folder.
42  *
43  *   2. The caller populates the model by hand, with files not necessarily in the same folder.  This happens
44  *      if you use _gtk_file_system_model_new() and then _gtk_file_system_model_add_and_query_file().  This is
45  *      the special kind of usage for "search" and "recent-files", where the file chooser gives the model the
46  *      files to be displayed.
47  *
48  * Each file is kept in a FileModelNode structure.  Each FileModelNode holds a GFile* and other data.  All the
49  * node structures have the same size, determined at runtime, depending on the number of columns that were passed
50  * to _gtk_file_system_model_new() or _gtk_file_system_model_new_for_directory() (that is, the size of a node is
51  * not sizeof (FileModelNode), but rather model->node_size).  The last field in the FileModelNode structure,
52  * node->values[], is an array of GValue, used to hold the data for those columns.
53  *
54  * The model stores an array of FileModelNode structures in model->files.  This is a GArray where each element is
55  * model->node_size bytes in size (the model computes that node size when initializing itself).  There are
56  * convenience macros, get_node() and node_index(), to access that array based on an array index or a pointer to
57  * a node inside the array.
58  *
59  * The model accesses files through two of its fields:
60  *
61  *   model->files - GArray of FileModelNode structures.
62  *
63  *   model->file_lookup - hash table that maps a GFile* to an index inside the model->files array.
64  *
65  * The model->file_lookup hash table is populated lazily.  It is both accessed and populated with the
66  * node_get_for_file() function.  The invariant is that the files in model->files[n] for n < g_hash_table_size
67  * (model->file_lookup) are already added to the hash table. The hash table will get cleared when we re-sort the
68  * files, as the array will be in a different order and the indexes need to be rebuilt.
69  *
70  * Each FileModelNode has a node->visible field, which indicates whether the node is visible in the GtkTreeView.
71  * A node may be invisible if, for example, it corresponds to a hidden file and the file chooser is not showing
72  * hidden files.
73  *
74  * Since not all nodes in the model->files array may be visible, we need a way to map visible row indexes from
75  * the treeview to array indexes in our array of files.  And thus we introduce a bit of terminology:
76  *
77  *   index - An index in the model->files array.  All variables/fields that represent indexes are either called
78  *   "index" or "i_*", or simply "i" for things like loop counters.
79  *
80  *   row - An index in the GtkTreeView, i.e. the index of a row within the outward-facing API of the
81  *   GtkFileSystemModel.  However, note that our rows are 1-based, not 0-based, for the reason explained in the
82  *   following paragraph.  Variables/fields that represent visible rows are called "row", or "r_*", or simply
83  *   "r".
84  *
85  * Each FileModelNode has a node->row field which is the number of visible rows in the treeview, *before and
86  * including* that node.  This means that node->row is 1-based, instead of 0-based --- this makes some code
87  * simpler, believe it or not :)  This also means that when the calling GtkTreeView gives us a GtkTreePath, we
88  * turn the 0-based treepath into a 1-based row for our purposes.  If a node is not visible, it will have the
89  * same row number as its closest preceding visible node.
90  *
91  * We try to compute the node->row fields lazily.  A node is said to be "valid" if its node->row is accurate.
92  * For this, the model keeps a model->n_nodes_valid field which is the count of valid nodes starting from the
93  * beginning of the model->files array.  When a node changes its information, or when a node gets deleted, that
94  * node and the following ones get invalidated by simply setting model->n_nodes_valid to the array index of the
95  * node.  If the model happens to need a node's row number and that node is in the model->files array after
96  * model->n_nodes_valid, then the nodes get re-validated up to the sought node.  See node_validate_rows() for
97  * this logic.
98  *
99  * You never access a node->row directly.  Instead, call node_get_tree_row().  That function will validate the nodes
100  * up to the sought one if the node is not valid yet, and it will return a proper 0-based row.
101  */
102
103 /*** DEFINES ***/
104
105 /* priority used for all async callbacks in the main loop
106  * This should be higher than redraw priorities so multiple callbacks
107  * firing can be handled without intermediate redraws */
108 #define IO_PRIORITY G_PRIORITY_DEFAULT
109
110 /* random number that everyone else seems to use, too */
111 #define FILES_PER_QUERY 100
112
113 typedef struct _FileModelNode           FileModelNode;
114 typedef struct _GtkFileSystemModelClass GtkFileSystemModelClass;
115
116 struct _FileModelNode
117 {
118   GFile *               file;           /* file represented by this node or NULL for editable */
119   GFileInfo *           info;           /* info for this file or NULL if unknown */
120
121   guint                 row;            /* if valid (see model->n_valid_indexes), visible nodes before and including
122                                          * this one - see the "Structure" comment above.
123                                          */
124
125   guint                 visible :1;     /* if the file is currently visible */
126   guint                 frozen_add :1;  /* true if the model was frozen and the entry has not been added yet */
127
128   GValue                values[1];      /* actually n_columns values */
129 };
130
131 struct _GtkFileSystemModel
132 {
133   GObject               parent_instance;
134
135   GFile *               dir;            /* directory that's displayed */
136   guint                 dir_thaw_source;/* GSource id for unfreezing the model */
137   char *                attributes;     /* attributes the file info must contain, or NULL for all attributes */
138   GFileMonitor *        dir_monitor;    /* directory that is monitored, or NULL if monitoring was not supported */
139
140   GCancellable *        cancellable;    /* cancellable in use for all operations - cancelled on dispose */
141   GArray *              files;          /* array of FileModelNode containing all our files */
142   GSize                 node_size;      /* Size of a FileModelNode structure once its ->values field has n_columns */
143   guint                 n_nodes_valid;  /* count of valid nodes (i.e. those whose node->row is accurate) */
144   GHashTable *          file_lookup;    /* mapping of GFile => array index in model->files
145                                          * This hash table doesn't always have the same number of entries as the files array;
146                                          * it can get cleared completely when we resort.
147                                          * The hash table gets re-populated in node_get_for_file() if this mismatch is
148                                          * detected.
149                                          */
150
151   guint                 n_columns;      /* number of columns */
152   GType *               column_types;   /* types of each column */
153   GtkFileSystemModelGetValue get_func;  /* function to call to fill in values in columns */
154   gpointer              get_data;       /* data to pass to get_func */
155
156   GtkFileFilter *       filter;         /* filter to use for deciding which nodes are visible */
157
158   int                   sort_column_id; /* current sorting column */
159   GtkSortType           sort_order;     /* current sorting order */
160   GList *               sort_list;      /* list of sorting functions */
161   GtkTreeIterCompareFunc default_sort_func; /* default sort function */
162   gpointer              default_sort_data; /* data to pass to default sort func */
163   GDestroyNotify        default_sort_destroy; /* function to call to destroy default_sort_data */
164
165   guint                 frozen;         /* number of times we're frozen */
166
167   gboolean              filter_on_thaw :1;/* set when filtering needs to happen upon thawing */
168   gboolean              sort_on_thaw :1;/* set when sorting needs to happen upon thawing */
169
170   guint                 show_hidden :1; /* whether to show hidden files */
171   guint                 show_folders :1;/* whether to show folders */
172   guint                 show_files :1;  /* whether to show files */
173 };
174
175 #define GTK_FILE_SYSTEM_MODEL_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_FILE_SYSTEM_MODEL, GtkFileSystemModelClass))
176 #define GTK_IS_FILE_SYSTEM_MODEL_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_FILE_SYSTEM_MODEL))
177 #define GTK_FILE_SYSTEM_MODEL_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_FILE_SYSTEM_MODEL, GtkFileSystemModelClass))
178
179 struct _GtkFileSystemModelClass
180 {
181   GObjectClass parent_class;
182
183   /* Signals */
184
185   void (*finished_loading) (GtkFileSystemModel *model, GError *error);
186 };
187
188 static void add_file (GtkFileSystemModel *model,
189                       GFile              *file,
190                       GFileInfo          *info);
191 static void remove_file (GtkFileSystemModel *model,
192                          GFile              *file);
193
194 /* iter setup:
195  * @user_data: the model
196  * @user_data2: GUINT_TO_POINTER of array index of current entry
197  *
198  * All other fields are unused. Note that the array index does not corrspond
199  * 1:1 with the path index as entries might not be visible.
200  */
201 #define ITER_INDEX(iter) GPOINTER_TO_UINT((iter)->user_data2)
202 #define ITER_IS_VALID(model, iter) ((model) == (iter)->user_data)
203 #define ITER_INIT_FROM_INDEX(model, _iter, _index) G_STMT_START {\
204   g_assert (_index < (model)->files->len); \
205   (_iter)->user_data = (model); \
206   (_iter)->user_data2 = GUINT_TO_POINTER (_index); \
207 }G_STMT_END
208
209 /*** FileModelNode ***/
210
211 /* Get a FileModelNode structure given an index in the model->files array of nodes */
212 #define get_node(_model, _index) ((FileModelNode *) ((_model)->files->data + (_index) * (_model)->node_size))
213
214 /* Get an index within the model->files array of nodes, given a FileModelNode* */
215 #define node_index(_model, _node) (((gchar *) (_node) - (_model)->files->data) / (_model)->node_size)
216
217 /* @up_to_index: smallest model->files array index that will be valid after this call
218  * @up_to_row: smallest node->row that will be valid after this call
219  *
220  * If you want to validate up to an index or up to a row, specify the index or
221  * the row you want and specify G_MAXUINT for the other argument.  Pass
222  * G_MAXUINT for both arguments for "validate everything".
223  */
224 static void
225 node_validate_rows (GtkFileSystemModel *model, guint up_to_index, guint up_to_row)
226 {
227   guint i, row;
228
229   if (model->files->len == 0)
230     return;
231
232   up_to_index = MIN (up_to_index, model->files->len - 1);
233
234   i = model->n_nodes_valid;
235   if (i != 0)
236     row = get_node (model, i - 1)->row;
237   else
238     row = 0;
239
240   while (i <= up_to_index && row <= up_to_row)
241     {
242       FileModelNode *node = get_node (model, i);
243       if (node->visible)
244         row++;
245       node->row = row;
246       i++;
247     }
248   model->n_nodes_valid = i;
249 }
250
251 static guint
252 node_get_tree_row (GtkFileSystemModel *model, guint index)
253 {
254   if (model->n_nodes_valid <= index)
255     node_validate_rows (model, index, G_MAXUINT);
256
257   return get_node (model, index)->row - 1;
258 }
259
260 static void 
261 node_invalidate_index (GtkFileSystemModel *model, guint id)
262 {
263   model->n_nodes_valid = MIN (model->n_nodes_valid, id);
264 }
265
266 static GtkTreePath *
267 gtk_tree_path_new_from_node (GtkFileSystemModel *model, guint id)
268 {
269   guint i = node_get_tree_row (model, id);
270
271   g_assert (i < model->files->len);
272
273   return gtk_tree_path_new_from_indices (i, -1);
274 }
275
276 static void
277 emit_row_inserted_for_node (GtkFileSystemModel *model, guint id)
278 {
279   GtkTreePath *path;
280   GtkTreeIter iter;
281
282   path = gtk_tree_path_new_from_node (model, id);
283   ITER_INIT_FROM_INDEX (model, &iter, id);
284   gtk_tree_model_row_inserted (GTK_TREE_MODEL (model), path, &iter);
285   gtk_tree_path_free (path);
286 }
287
288 static void
289 emit_row_changed_for_node (GtkFileSystemModel *model, guint id)
290 {
291   GtkTreePath *path;
292   GtkTreeIter iter;
293
294   path = gtk_tree_path_new_from_node (model, id);
295   ITER_INIT_FROM_INDEX (model, &iter, id);
296   gtk_tree_model_row_changed (GTK_TREE_MODEL (model), path, &iter);
297   gtk_tree_path_free (path);
298 }
299
300 static void
301 emit_row_deleted_for_row (GtkFileSystemModel *model, guint row)
302 {
303   GtkTreePath *path;
304
305   path = gtk_tree_path_new_from_indices (row, -1);
306   gtk_tree_model_row_deleted (GTK_TREE_MODEL (model), path);
307   gtk_tree_path_free (path);
308 }
309
310 static void
311 node_set_visible (GtkFileSystemModel *model, guint id, gboolean visible)
312 {
313   FileModelNode *node = get_node (model, id);
314
315   if (node->visible == visible ||
316       node->frozen_add)
317     return;
318
319   if (visible)
320     {
321       node->visible = TRUE;
322       node_invalidate_index (model, id);
323       emit_row_inserted_for_node (model, id);
324     }
325   else
326     {
327       guint row;
328
329       row = node_get_tree_row (model, id);
330       g_assert (row < model->files->len);
331
332       node->visible = FALSE;
333       node_invalidate_index (model, id);
334       emit_row_deleted_for_row (model, row);
335     }
336 }
337
338 static gboolean
339 node_should_be_visible (GtkFileSystemModel *model, guint id)
340 {
341   FileModelNode *node = get_node (model, id);
342   GtkFileFilterInfo filter_info = { 0, };
343   GtkFileFilterFlags required;
344   gboolean is_folder, result;
345   char *mime_type = NULL;
346   char *filename = NULL;
347   char *uri = NULL;
348
349   if (node->info == NULL)
350     return FALSE;
351
352   if (!model->show_hidden &&
353       (g_file_info_get_is_hidden (node->info) || g_file_info_get_is_backup (node->info)))
354     return FALSE;
355
356   is_folder = _gtk_file_info_consider_as_directory (node->info);
357   
358   /* wtf? */
359   if (model->show_folders != model->show_files &&
360       model->show_folders != is_folder)
361     return FALSE;
362
363   if (is_folder)
364     return TRUE;
365
366   if (model->filter == NULL)
367     return TRUE;
368
369   /* fill info */
370   required = gtk_file_filter_get_needed (model->filter);
371
372   filter_info.contains = GTK_FILE_FILTER_DISPLAY_NAME;
373   filter_info.display_name = g_file_info_get_display_name (node->info);
374
375   if (required & GTK_FILE_FILTER_MIME_TYPE)
376     {
377       const char *s = g_file_info_get_content_type (node->info);
378       if (s)
379         {
380           mime_type = g_content_type_get_mime_type (s);
381           if (mime_type)
382             {
383               filter_info.mime_type = mime_type;
384               filter_info.contains |= GTK_FILE_FILTER_MIME_TYPE;
385             }
386         }
387     }
388
389   if (required & GTK_FILE_FILTER_FILENAME)
390     {
391       filename = g_file_get_path (node->file);
392       if (filename)
393         {
394           filter_info.filename = filename;
395           filter_info.contains |= GTK_FILE_FILTER_FILENAME;
396         }
397     }
398
399   if (required & GTK_FILE_FILTER_URI)
400     {
401       uri = g_file_get_uri (node->file);
402       if (uri)
403         {
404           filter_info.uri = uri;
405           filter_info.contains |= GTK_FILE_FILTER_URI;
406         }
407     }
408
409   result = gtk_file_filter_filter (model->filter, &filter_info);
410
411   g_free (mime_type);
412   g_free (filename);
413   g_free (uri);
414
415   return result;
416 }
417
418 /*** GtkTreeModel ***/
419
420 static GtkTreeModelFlags
421 gtk_file_system_model_get_flags (GtkTreeModel *tree_model)
422 {
423   /* GTK_TREE_MODEL_ITERS_PERSIST doesn't work with arrays :( */
424   return GTK_TREE_MODEL_LIST_ONLY;
425 }
426
427 static gint
428 gtk_file_system_model_get_n_columns (GtkTreeModel *tree_model)
429 {
430   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model);
431   
432   return model->n_columns;
433 }
434
435 static GType
436 gtk_file_system_model_get_column_type (GtkTreeModel *tree_model,
437                                        gint          i)
438 {
439   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model);
440   
441   g_return_val_if_fail (i >= 0 && (guint) i < model->n_columns, G_TYPE_NONE);
442
443   return model->column_types[i];
444 }
445
446 static int
447 compare_indices (gconstpointer key, gconstpointer _node)
448 {
449   const FileModelNode *node = _node;
450
451   return GPOINTER_TO_UINT (key) - node->row;
452 }
453
454 static gboolean
455 gtk_file_system_model_iter_nth_child (GtkTreeModel *tree_model,
456                                       GtkTreeIter  *iter,
457                                       GtkTreeIter  *parent,
458                                       gint          n)
459 {
460   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model);
461   char *node;
462   guint id;
463   guint row_to_find;
464
465   g_return_val_if_fail (n >= 0, FALSE);
466
467   if (parent != NULL)
468     return FALSE;
469
470   row_to_find = n + 1; /* plus one as our node->row numbers are 1-based; see the "Structure" comment at the beginning */
471
472   if (model->n_nodes_valid > 0 &&
473       get_node (model, model->n_nodes_valid - 1)->row >= row_to_find)
474     {
475       /* Fast path - the nodes are valid up to the sought one.
476        *
477        * First, find a node with the sought row number...*/
478
479       node = bsearch (GUINT_TO_POINTER (row_to_find), 
480                       model->files->data,
481                       model->n_nodes_valid,
482                       model->node_size,
483                       compare_indices);
484       if (node == NULL)
485         return FALSE;
486
487       /* ... Second, back up until we find the first visible node with that row number */
488
489       id = node_index (model, node);
490       while (!get_node (model, id)->visible)
491         id--;
492
493       g_assert (get_node (model, id)->row == row_to_find);
494     }
495   else
496     {
497       /* Slow path - the nodes need to be validated up to the sought one */
498
499       node_validate_rows (model, G_MAXUINT, n); /* note that this is really "n", not row_to_find - see node_validate_rows() */
500       id = model->n_nodes_valid - 1;
501       if (model->n_nodes_valid == 0 || get_node (model, id)->row != row_to_find)
502         return FALSE;
503     }
504
505   ITER_INIT_FROM_INDEX (model, iter, id);
506   return TRUE;
507 }
508
509 static gboolean
510 gtk_file_system_model_get_iter (GtkTreeModel *tree_model,
511                                 GtkTreeIter  *iter,
512                                 GtkTreePath  *path)
513 {
514   g_return_val_if_fail (gtk_tree_path_get_depth (path) > 0, FALSE);
515
516   return gtk_file_system_model_iter_nth_child (tree_model, 
517                                                iter,
518                                                NULL, 
519                                                gtk_tree_path_get_indices (path)[0]);
520 }
521
522 static GtkTreePath *
523 gtk_file_system_model_get_path (GtkTreeModel *tree_model,
524                                 GtkTreeIter  *iter)
525 {
526   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model);
527       
528   g_return_val_if_fail (ITER_IS_VALID (model, iter), NULL);
529
530   return gtk_tree_path_new_from_node (model, ITER_INDEX (iter));
531 }
532
533 static void
534 gtk_file_system_model_get_value (GtkTreeModel *tree_model,
535                                  GtkTreeIter  *iter,
536                                  gint          column,
537                                  GValue       *value)
538 {
539   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model);
540   const GValue *original;
541   
542   g_return_if_fail ((guint) column < model->n_columns);
543   g_return_if_fail (ITER_IS_VALID (model, iter));
544
545   original = _gtk_file_system_model_get_value (model, iter, column);
546   if (original)
547     {
548       g_value_init (value, G_VALUE_TYPE (original));
549       g_value_copy (original, value);
550     }
551   else
552     g_value_init (value, model->column_types[column]);
553 }
554
555 static gboolean
556 gtk_file_system_model_iter_next (GtkTreeModel *tree_model,
557                                  GtkTreeIter  *iter)
558 {
559   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model);
560   guint i;
561
562   g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE);
563
564   for (i = ITER_INDEX (iter) + 1; i < model->files->len; i++) 
565     {
566       FileModelNode *node = get_node (model, i);
567
568       if (node->visible)
569         {
570           ITER_INIT_FROM_INDEX (model, iter, i);
571           return TRUE;
572         }
573     }
574       
575   return FALSE;
576 }
577
578 static gboolean
579 gtk_file_system_model_iter_children (GtkTreeModel *tree_model,
580                                      GtkTreeIter  *iter,
581                                      GtkTreeIter  *parent)
582 {
583   return FALSE;
584 }
585
586 static gboolean
587 gtk_file_system_model_iter_has_child (GtkTreeModel *tree_model,
588                                       GtkTreeIter  *iter)
589 {
590   return FALSE;
591 }
592
593 static gint
594 gtk_file_system_model_iter_n_children (GtkTreeModel *tree_model,
595                                        GtkTreeIter  *iter)
596 {
597   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model);
598
599   if (iter)
600     return 0;
601
602   return node_get_tree_row (model, model->files->len - 1) + 1;
603 }
604
605 static gboolean
606 gtk_file_system_model_iter_parent (GtkTreeModel *tree_model,
607                                    GtkTreeIter  *iter,
608                                    GtkTreeIter  *child)
609 {
610   return FALSE;
611 }
612
613 static void
614 gtk_file_system_model_ref_node (GtkTreeModel *tree_model,
615                                 GtkTreeIter  *iter)
616 {
617   /* nothing to do */
618 }
619
620 static void
621 gtk_file_system_model_unref_node (GtkTreeModel *tree_model,
622                                   GtkTreeIter  *iter)
623 {
624   /* nothing to do */
625 }
626
627 static void
628 gtk_file_system_model_iface_init (GtkTreeModelIface *iface)
629 {
630   iface->get_flags =       gtk_file_system_model_get_flags;
631   iface->get_n_columns =   gtk_file_system_model_get_n_columns;
632   iface->get_column_type = gtk_file_system_model_get_column_type;
633   iface->get_iter =        gtk_file_system_model_get_iter;
634   iface->get_path =        gtk_file_system_model_get_path;
635   iface->get_value =       gtk_file_system_model_get_value;
636   iface->iter_next =       gtk_file_system_model_iter_next;
637   iface->iter_children =   gtk_file_system_model_iter_children;
638   iface->iter_has_child =  gtk_file_system_model_iter_has_child;
639   iface->iter_n_children = gtk_file_system_model_iter_n_children;
640   iface->iter_nth_child =  gtk_file_system_model_iter_nth_child;
641   iface->iter_parent =     gtk_file_system_model_iter_parent;
642   iface->ref_node =        gtk_file_system_model_ref_node;
643   iface->unref_node =      gtk_file_system_model_unref_node;
644 }
645
646 /*** GtkTreeSortable ***/
647
648 typedef struct _SortData SortData;
649 struct _SortData {
650   GtkFileSystemModel *    model;
651   GtkTreeIterCompareFunc  func;
652   gpointer                data;
653   int                     order;        /* -1 to invert sort order or 1 to keep it */
654 };
655
656 /* returns FALSE if no sort necessary */
657 static gboolean
658 sort_data_init (SortData *data, GtkFileSystemModel *model)
659 {
660   GtkTreeDataSortHeader *header;
661
662   if (model->files->len <= 2)
663     return FALSE;
664
665   switch (model->sort_column_id)
666     {
667     case GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID:
668       if (!model->default_sort_func)
669         return FALSE;
670       data->func = model->default_sort_func;
671       data->data = model->default_sort_data;
672       break;
673     case GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID:
674       return FALSE;
675     default:
676       header = _gtk_tree_data_list_get_header (model->sort_list, model->sort_column_id);
677       if (header == NULL)
678         return FALSE;
679       data->func = header->func;
680       data->data = header->data;
681       break;
682     }
683
684   data->order = model->sort_order == GTK_SORT_DESCENDING ? -1 : 1;
685   data->model = model;
686   return TRUE;
687 }
688
689 static int
690 compare_array_element (gconstpointer a, gconstpointer b, gpointer user_data)
691 {
692   SortData *data = user_data;
693   GtkTreeIter itera, iterb;
694
695   ITER_INIT_FROM_INDEX (data->model, &itera, node_index (data->model, a));
696   ITER_INIT_FROM_INDEX (data->model, &iterb, node_index (data->model, b));
697   return data->func (GTK_TREE_MODEL (data->model), &itera, &iterb, data->data) * data->order;
698 }
699
700 static void
701 gtk_file_system_model_sort (GtkFileSystemModel *model)
702 {
703   SortData data;
704
705   if (model->frozen)
706     {
707       model->sort_on_thaw = TRUE;
708       return;
709     }
710
711   if (sort_data_init (&data, model))
712     {
713       GtkTreePath *path;
714       guint i;
715       guint r, n_visible_rows;
716
717       node_validate_rows (model, G_MAXUINT, G_MAXUINT);
718       n_visible_rows = node_get_tree_row (model, model->files->len - 1) + 1;
719       model->n_nodes_valid = 0;
720       g_hash_table_remove_all (model->file_lookup);
721       g_qsort_with_data (get_node (model, 1), /* start at index 1; don't sort the editable row */
722                          model->files->len - 1,
723                          model->node_size,
724                          compare_array_element,
725                          &data);
726       g_assert (model->n_nodes_valid == 0);
727       g_assert (g_hash_table_size (model->file_lookup) == 0);
728       if (n_visible_rows)
729         {
730           int *new_order = g_new (int, n_visible_rows);
731         
732           r = 0;
733           for (i = 0; i < model->files->len; i++)
734             {
735               FileModelNode *node = get_node (model, i);
736               if (!node->visible)
737                 {
738                   node->row = r;
739                   continue;
740                 }
741
742               new_order[r] = node->row;
743               r++;
744               node->row = r;
745             }
746           g_assert (r == n_visible_rows);
747           path = gtk_tree_path_new ();
748           gtk_tree_model_rows_reordered (GTK_TREE_MODEL (model),
749                                          path,
750                                          NULL,
751                                          new_order);
752           gtk_tree_path_free (path);
753           g_free (new_order);
754         }
755     }
756
757   model->sort_on_thaw = FALSE;
758 }
759
760 static void
761 gtk_file_system_model_sort_node (GtkFileSystemModel *model, guint node)
762 {
763   /* FIXME: improve */
764   gtk_file_system_model_sort (model);
765 }
766
767 static gboolean
768 gtk_file_system_model_get_sort_column_id (GtkTreeSortable  *sortable,
769                                           gint             *sort_column_id,
770                                           GtkSortType      *order)
771 {
772   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable);
773
774   if (sort_column_id)
775     *sort_column_id = model->sort_column_id;
776   if (order)
777     *order = model->sort_order;
778
779   if (model->sort_column_id == GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID ||
780       model->sort_column_id == GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID)
781     return FALSE;
782
783   return TRUE;
784 }
785
786 static void
787 gtk_file_system_model_set_sort_column_id (GtkTreeSortable  *sortable,
788                                           gint              sort_column_id,
789                                           GtkSortType       order)
790 {
791   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable);
792
793   if ((model->sort_column_id == sort_column_id) &&
794       (model->sort_order == order))
795     return;
796
797   if (sort_column_id != GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID)
798     {
799       if (sort_column_id != GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID)
800         {
801           GtkTreeDataSortHeader *header = NULL;
802
803           header = _gtk_tree_data_list_get_header (model->sort_list, 
804                                                    sort_column_id);
805
806           /* We want to make sure that we have a function */
807           g_return_if_fail (header != NULL);
808           g_return_if_fail (header->func != NULL);
809         }
810       else
811         {
812           g_return_if_fail (model->default_sort_func != NULL);
813         }
814     }
815
816
817   model->sort_column_id = sort_column_id;
818   model->sort_order = order;
819
820   gtk_tree_sortable_sort_column_changed (sortable);
821
822   gtk_file_system_model_sort (model);
823 }
824
825 static void
826 gtk_file_system_model_set_sort_func (GtkTreeSortable        *sortable,
827                                      gint                    sort_column_id,
828                                      GtkTreeIterCompareFunc  func,
829                                      gpointer                data,
830                                      GDestroyNotify          destroy)
831 {
832   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable);
833
834   model->sort_list = _gtk_tree_data_list_set_header (model->sort_list, 
835                                                      sort_column_id, 
836                                                      func, data, destroy);
837
838   if (model->sort_column_id == sort_column_id)
839     gtk_file_system_model_sort (model);
840 }
841
842 static void
843 gtk_file_system_model_set_default_sort_func (GtkTreeSortable        *sortable,
844                                              GtkTreeIterCompareFunc  func,
845                                              gpointer                data,
846                                              GDestroyNotify          destroy)
847 {
848   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable);
849
850   if (model->default_sort_destroy)
851     {
852       GDestroyNotify d = model->default_sort_destroy;
853
854       model->default_sort_destroy = NULL;
855       d (model->default_sort_data);
856     }
857
858   model->default_sort_func = func;
859   model->default_sort_data = data;
860   model->default_sort_destroy = destroy;
861
862   if (model->sort_column_id == GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID)
863     gtk_file_system_model_sort (model);
864 }
865
866 static gboolean
867 gtk_file_system_model_has_default_sort_func (GtkTreeSortable *sortable)
868 {
869   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable);
870
871   return (model->default_sort_func != NULL);
872 }
873
874 static void
875 gtk_file_system_model_sortable_init (GtkTreeSortableIface *iface)
876 {
877   iface->get_sort_column_id = gtk_file_system_model_get_sort_column_id;
878   iface->set_sort_column_id = gtk_file_system_model_set_sort_column_id;
879   iface->set_sort_func = gtk_file_system_model_set_sort_func;
880   iface->set_default_sort_func = gtk_file_system_model_set_default_sort_func;
881   iface->has_default_sort_func = gtk_file_system_model_has_default_sort_func;
882 }
883
884 /*** GtkTreeDragSource ***/
885
886 static gboolean
887 drag_source_row_draggable (GtkTreeDragSource *drag_source,
888                            GtkTreePath       *path)
889 {
890   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (drag_source);
891   GtkTreeIter iter;
892
893   if (!gtk_file_system_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
894     return FALSE;
895
896   return ITER_INDEX (&iter) != 0;
897 }
898
899 static gboolean
900 drag_source_drag_data_get (GtkTreeDragSource *drag_source,
901                            GtkTreePath       *path,
902                            GtkSelectionData  *selection_data)
903 {
904   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (drag_source);
905   FileModelNode *node;
906   GtkTreeIter iter;
907   char *uris[2]; 
908
909   if (!gtk_file_system_model_get_iter (GTK_TREE_MODEL (model), &iter, path))
910     return FALSE;
911
912   node = get_node (model, ITER_INDEX (&iter));
913   if (node->file == NULL)
914     return FALSE;
915
916   uris[0] = g_file_get_uri (node->file);
917   uris[1] = NULL;
918   gtk_selection_data_set_uris (selection_data, uris);
919   g_free (uris[0]);
920
921   return TRUE;
922 }
923
924 static void
925 drag_source_iface_init (GtkTreeDragSourceIface *iface)
926 {
927   iface->row_draggable = drag_source_row_draggable;
928   iface->drag_data_get = drag_source_drag_data_get;
929   iface->drag_data_delete = NULL;
930 }
931
932 /*** GtkFileSystemModel ***/
933
934 /* Signal IDs */
935 enum {
936   FINISHED_LOADING,
937   LAST_SIGNAL
938 };
939
940 static guint file_system_model_signals[LAST_SIGNAL] = { 0 };
941
942 \f
943
944 G_DEFINE_TYPE_WITH_CODE (GtkFileSystemModel, _gtk_file_system_model, G_TYPE_OBJECT,
945                          G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_MODEL,
946                                                 gtk_file_system_model_iface_init)
947                          G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_SORTABLE,
948                                                 gtk_file_system_model_sortable_init)
949                          G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_DRAG_SOURCE,
950                                                 drag_source_iface_init))
951
952 static void
953 gtk_file_system_model_dispose (GObject *object)
954 {
955   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (object);
956
957   if (model->dir_thaw_source)
958     {
959       g_source_remove (model->dir_thaw_source);
960       model->dir_thaw_source = 0;
961     }
962
963   g_cancellable_cancel (model->cancellable);
964   if (model->dir_monitor)
965     g_file_monitor_cancel (model->dir_monitor);
966
967   G_OBJECT_CLASS (_gtk_file_system_model_parent_class)->dispose (object);
968 }
969
970
971 static void
972 gtk_file_system_model_finalize (GObject *object)
973 {
974   GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (object);
975   guint i;
976
977   for (i = 0; i < model->files->len; i++)
978     {
979       int v;
980
981       FileModelNode *node = get_node (model, i);
982       if (node->file)
983         g_object_unref (node->file);
984       if (node->info)
985         g_object_unref (node->info);
986
987       for (v = 0; v < model->column_types; v++)
988         if (G_VALUE_TYPE (node->values[v]) != G_TYPE_INVALID)
989           g_value_unset (&node->values[v]);
990     }
991   g_array_free (model->files, TRUE);
992
993   g_object_unref (model->cancellable);
994   g_free (model->attributes);
995   if (model->dir)
996     g_object_unref (model->dir);
997   if (model->dir_monitor)
998     g_object_unref (model->dir_monitor);
999   g_hash_table_destroy (model->file_lookup);
1000   if (model->filter)
1001     g_object_unref (model->filter);
1002
1003   g_slice_free1 (sizeof (GType) * n_columns, model->column_types);
1004
1005   _gtk_tree_data_list_header_free (model->sort_list);
1006   if (model->default_sort_destroy)
1007     model->default_sort_destroy (model->default_sort_data);
1008
1009   G_OBJECT_CLASS (_gtk_file_system_model_parent_class)->finalize (object);
1010 }
1011
1012 static void
1013 _gtk_file_system_model_class_init (GtkFileSystemModelClass *class)
1014 {
1015   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
1016
1017   gobject_class->finalize = gtk_file_system_model_finalize;
1018   gobject_class->dispose = gtk_file_system_model_dispose;
1019
1020   file_system_model_signals[FINISHED_LOADING] =
1021     g_signal_new (I_("finished-loading"),
1022                   G_OBJECT_CLASS_TYPE (gobject_class),
1023                   G_SIGNAL_RUN_LAST,
1024                   G_STRUCT_OFFSET (GtkFileSystemModelClass, finished_loading),
1025                   NULL, NULL,
1026                   _gtk_marshal_VOID__POINTER,
1027                   G_TYPE_NONE, 1, G_TYPE_POINTER);
1028 }
1029
1030 static void
1031 _gtk_file_system_model_init (GtkFileSystemModel *model)
1032 {
1033   model->show_files = TRUE;
1034   model->show_folders = TRUE;
1035   model->show_hidden = FALSE;
1036
1037   model->sort_column_id = GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID;
1038
1039   model->file_lookup = g_hash_table_new (g_file_hash, (GEqualFunc) g_file_equal);
1040   model->cancellable = g_cancellable_new ();
1041 }
1042
1043 /*** API ***/
1044
1045 static void
1046 gtk_file_system_model_closed_enumerator (GObject *object, GAsyncResult *res, gpointer data)
1047 {
1048   g_file_enumerator_close_finish (G_FILE_ENUMERATOR (object), res, NULL);
1049 }
1050
1051 static gboolean
1052 thaw_func (gpointer data)
1053 {
1054   GtkFileSystemModel *model = data;
1055
1056   _gtk_file_system_model_thaw_updates (model);
1057   model->dir_thaw_source = 0;
1058
1059   return FALSE;
1060 }
1061
1062 static void
1063 gtk_file_system_model_got_files (GObject *object, GAsyncResult *res, gpointer data)
1064 {
1065   GFileEnumerator *enumerator = G_FILE_ENUMERATOR (object);
1066   GtkFileSystemModel *model = data;
1067   GList *walk, *files;
1068   GError *error = NULL;
1069
1070   gdk_threads_enter ();
1071
1072   files = g_file_enumerator_next_files_finish (enumerator, res, &error);
1073
1074   if (files)
1075     {
1076       if (model->dir_thaw_source == 0)
1077         {
1078           _gtk_file_system_model_freeze_updates (model);
1079           model->dir_thaw_source = gdk_threads_add_timeout_full (IO_PRIORITY + 1,
1080                                                                  50,
1081                                                                  thaw_func,
1082                                                                  model,
1083                                                                  NULL);
1084         }
1085
1086       for (walk = files; walk; walk = walk->next)
1087         {
1088           const char *name;
1089           GFileInfo *info;
1090           GFile *file;
1091           
1092           info = walk->data;
1093           name = g_file_info_get_name (info);
1094           if (name == NULL)
1095             {
1096               /* Shouldn't happen, but the APIs allow it */
1097               g_object_unref (info);
1098               continue;
1099             }
1100           file = g_file_get_child (model->dir, name);
1101           add_file (model, file, info);
1102           g_object_unref (file);
1103           g_object_unref (info);
1104         }
1105       g_list_free (files);
1106
1107       g_file_enumerator_next_files_async (enumerator,
1108                                           g_file_is_native (model->dir) ? 50 * FILES_PER_QUERY : FILES_PER_QUERY,
1109                                           IO_PRIORITY,
1110                                           model->cancellable,
1111                                           gtk_file_system_model_got_files,
1112                                           model);
1113     }
1114   else
1115     {
1116       g_file_enumerator_close_async (enumerator, 
1117                                      IO_PRIORITY,
1118                                      model->cancellable,
1119                                      gtk_file_system_model_closed_enumerator,
1120                                      model);
1121       if (model->dir_thaw_source != 0)
1122         {
1123           g_source_remove (model->dir_thaw_source);
1124           model->dir_thaw_source = 0;
1125           _gtk_file_system_model_thaw_updates (model);
1126         }
1127
1128       g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error);
1129
1130       if (error)
1131         g_error_free (error);
1132
1133       g_object_unref (model);
1134     }
1135
1136   gdk_threads_leave ();
1137 }
1138
1139 static void
1140 gtk_file_system_model_query_done (GObject *     object,
1141                                   GAsyncResult *res,
1142                                   gpointer      data)
1143 {
1144   GtkFileSystemModel *model = data; /* only a valid pointer if not cancelled */
1145   GFile *file = G_FILE (object);
1146   GFileInfo *info;
1147
1148   info = g_file_query_info_finish (file, res, NULL);
1149   if (info == NULL)
1150     return;
1151
1152   _gtk_file_system_model_update_file (model, file, info, TRUE);
1153 }
1154
1155 static void
1156 gtk_file_system_model_monitor_change (GFileMonitor *      monitor,
1157                                       GFile *             file,
1158                                       GFile *             other_file,
1159                                       GFileMonitorEvent   type,
1160                                       GtkFileSystemModel *model)
1161 {
1162   switch (type)
1163     {
1164       case G_FILE_MONITOR_EVENT_CREATED:
1165       case G_FILE_MONITOR_EVENT_CHANGED:
1166       case G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED:
1167         /* We can treat all of these the same way */
1168         g_file_query_info_async (file,
1169                                  model->attributes,
1170                                  G_FILE_QUERY_INFO_NONE,
1171                                  IO_PRIORITY,
1172                                  model->cancellable,
1173                                  gtk_file_system_model_query_done,
1174                                  model);
1175         break;
1176       case G_FILE_MONITOR_EVENT_DELETED:
1177         remove_file (model, file);
1178         break;
1179       case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
1180         /* FIXME: use freeze/thaw with this somehow? */
1181       case G_FILE_MONITOR_EVENT_PRE_UNMOUNT:
1182       case G_FILE_MONITOR_EVENT_UNMOUNTED:
1183       default:
1184         /* ignore these */
1185         break;
1186     }
1187 }
1188
1189 static void
1190 gtk_file_system_model_got_enumerator (GObject *dir, GAsyncResult *res, gpointer data)
1191 {
1192   GtkFileSystemModel *model = data;
1193   GFileEnumerator *enumerator;
1194   GError *error = NULL;
1195
1196   gdk_threads_enter ();
1197
1198   enumerator = g_file_enumerate_children_finish (G_FILE (dir), res, &error);
1199   if (enumerator == NULL)
1200     {
1201       g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error);
1202       g_object_unref (model);
1203       g_error_free (error);
1204     }
1205   else
1206     {
1207       g_file_enumerator_next_files_async (enumerator,
1208                                           g_file_is_native (model->dir) ? 50 * FILES_PER_QUERY : FILES_PER_QUERY,
1209                                           IO_PRIORITY,
1210                                           model->cancellable,
1211                                           gtk_file_system_model_got_files,
1212                                           model);
1213       g_object_unref (enumerator);
1214       model->dir_monitor = g_file_monitor_directory (model->dir,
1215                                                      G_FILE_MONITOR_NONE,
1216                                                      model->cancellable,
1217                                                      NULL); /* we don't mind if directory monitoring isn't supported, so the GError is NULL here */
1218       if (model->dir_monitor)
1219         g_signal_connect (model->dir_monitor,
1220                           "changed",
1221                           G_CALLBACK (gtk_file_system_model_monitor_change),
1222                           model);
1223     }
1224
1225   gdk_threads_leave ();
1226 }
1227
1228 static void
1229 gtk_file_system_model_set_n_columns (GtkFileSystemModel *model,
1230                                      gint                n_columns,
1231                                      va_list             args)
1232 {
1233   guint i;
1234
1235   g_assert (model->files == NULL);
1236   g_assert (n_columns > 0);
1237
1238   model->n_columns = n_columns;
1239   model->column_types = g_slice_alloc (sizeof (GType) * n_columns);
1240
1241   model->node_size = sizeof (FileModelNode) + sizeof (GValue) * (n_columns - 1); /* minus 1 because FileModelNode.values[] has a default size of 1 */
1242
1243   for (i = 0; i < (guint) n_columns; i++)
1244     {
1245       GType type = va_arg (args, GType);
1246       if (! _gtk_tree_data_list_check_type (type))
1247         {
1248           g_error ("%s: type %s cannot be a column type for GtkFileSystemModel\n", G_STRLOC, g_type_name (type));
1249           return; /* not reached */
1250         }
1251
1252       model->column_types[i] = type;
1253     }
1254
1255   model->sort_list = _gtk_tree_data_list_header_new (n_columns, model->column_types);
1256
1257   model->files = g_array_sized_new (FALSE, FALSE, model->node_size, FILES_PER_QUERY);
1258   /* add editable node at start */
1259   g_array_set_size (model->files, 1);
1260   memset (get_node (model, 0), 0, model->node_size);
1261 }
1262
1263 static void
1264 gtk_file_system_model_set_directory (GtkFileSystemModel *model,
1265                                      GFile *             dir,
1266                                      const gchar *       attributes)
1267 {
1268   g_assert (G_IS_FILE (dir));
1269
1270   model->dir = g_object_ref (dir);
1271   model->attributes = g_strdup (attributes);
1272
1273   g_object_ref (model);
1274   g_file_enumerate_children_async (model->dir,
1275                                    attributes,
1276                                    G_FILE_QUERY_INFO_NONE,
1277                                    IO_PRIORITY,
1278                                    model->cancellable,
1279                                    gtk_file_system_model_got_enumerator,
1280                                    model);
1281
1282 }
1283
1284 static GtkFileSystemModel *
1285 _gtk_file_system_model_new_valist (GtkFileSystemModelGetValue get_func,
1286                                    gpointer            get_data,
1287                                    guint               n_columns,
1288                                    va_list             args)
1289 {
1290   GtkFileSystemModel *model;
1291
1292   model = g_object_new (GTK_TYPE_FILE_SYSTEM_MODEL, NULL);
1293   model->get_func = get_func;
1294   model->get_data = get_data;
1295
1296   gtk_file_system_model_set_n_columns (model, n_columns, args);
1297
1298   return model;
1299 }
1300
1301 /**
1302  * _gtk_file_system_model_new:
1303  * @get_func: function to call for getting a value
1304  * @get_data: user data argument passed to @get_func
1305  * @n_columns: number of columns
1306  * @...: @n_columns #GType types for the columns
1307  *
1308  * Creates a new #GtkFileSystemModel object. You need to add files
1309  * to the list using _gtk_file_system_model_add_and_query_file()
1310  * or _gtk_file_system_model_update_file().
1311  *
1312  * Return value: the newly created #GtkFileSystemModel
1313  **/
1314 GtkFileSystemModel *
1315 _gtk_file_system_model_new (GtkFileSystemModelGetValue get_func,
1316                             gpointer            get_data,
1317                             guint               n_columns,
1318                             ...)
1319 {
1320   GtkFileSystemModel *model;
1321   va_list args;
1322
1323   g_return_val_if_fail (get_func != NULL, NULL);
1324   g_return_val_if_fail (n_columns > 0, NULL);
1325
1326   va_start (args, n_columns);
1327   model = _gtk_file_system_model_new_valist (get_func, get_data, n_columns, args);
1328   va_end (args);
1329
1330   return model;
1331 }
1332
1333 /**
1334  * _gtk_file_system_model_new_for_directory:
1335  * @directory: the directory to show.
1336  * @attributes: attributes to immediately load or %NULL for all
1337  * @get_func: function that the model should call to query data about a file
1338  * @get_data: user data to pass to the @get_func
1339  * @n_columns: number of columns
1340  * @...: @n_columns #GType types for the columns
1341  *
1342  * Creates a new #GtkFileSystemModel object. The #GtkFileSystemModel
1343  * object wraps the given @directory as a #GtkTreeModel.
1344  * The model will query the given directory with the given @attributes
1345  * and add all files inside the directory automatically. If supported,
1346  * it will also monitor the drectory and update the model's
1347  * contents to reflect changes, if the @directory supports monitoring.
1348  * 
1349  * Return value: the newly created #GtkFileSystemModel
1350  **/
1351 GtkFileSystemModel *
1352 _gtk_file_system_model_new_for_directory (GFile *                    dir,
1353                                           const gchar *              attributes,
1354                                           GtkFileSystemModelGetValue get_func,
1355                                           gpointer                   get_data,
1356                                           guint                      n_columns,
1357                                           ...)
1358 {
1359   GtkFileSystemModel *model;
1360   va_list args;
1361
1362   g_return_val_if_fail (G_IS_FILE (dir), NULL);
1363   g_return_val_if_fail (get_func != NULL, NULL);
1364   g_return_val_if_fail (n_columns > 0, NULL);
1365
1366   va_start (args, n_columns);
1367   model = _gtk_file_system_model_new_valist (get_func, get_data, n_columns, args);
1368   va_end (args);
1369
1370   gtk_file_system_model_set_directory (model, dir, attributes);
1371
1372   return model;
1373 }
1374
1375 static void
1376 gtk_file_system_model_refilter_all (GtkFileSystemModel *model)
1377 {
1378   guint i;
1379
1380   if (model->frozen)
1381     {
1382       model->filter_on_thaw = TRUE;
1383       return;
1384     }
1385
1386   _gtk_file_system_model_freeze_updates (model);
1387
1388   /* start at index 1, don't change the editable */
1389   for (i = 1; i < model->files->len; i++)
1390     {
1391       node_set_visible (model, i, node_should_be_visible (model, i));
1392     }
1393
1394   model->filter_on_thaw = FALSE;
1395   _gtk_file_system_model_thaw_updates (model);
1396 }
1397
1398 /**
1399  * _gtk_file_system_model_set_show_hidden:
1400  * @model: a #GtkFileSystemModel
1401  * @show_hidden: whether hidden files should be displayed
1402  * 
1403  * Sets whether hidden files should be included in the #GtkTreeModel
1404  * for display.
1405  **/
1406 void
1407 _gtk_file_system_model_set_show_hidden (GtkFileSystemModel *model,
1408                                         gboolean            show_hidden)
1409 {
1410   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1411
1412   show_hidden = show_hidden != FALSE;
1413
1414   if (show_hidden != model->show_hidden)
1415     {
1416       model->show_hidden = show_hidden;
1417       gtk_file_system_model_refilter_all (model);
1418     }
1419 }
1420
1421 /**
1422  * _gtk_file_system_model_set_show_folders:
1423  * @model: a #GtkFileSystemModel
1424  * @show_folders: whether folders should be displayed
1425  * 
1426  * Sets whether folders should be included in the #GtkTreeModel for
1427  * display.
1428  **/
1429 void
1430 _gtk_file_system_model_set_show_folders (GtkFileSystemModel *model,
1431                                          gboolean            show_folders)
1432 {
1433   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1434
1435   show_folders = show_folders != FALSE;
1436
1437   if (show_folders != model->show_folders)
1438     {
1439       model->show_folders = show_folders;
1440       gtk_file_system_model_refilter_all (model);
1441     }
1442 }
1443
1444 /**
1445  * _gtk_file_system_model_set_show_files:
1446  * @model: a #GtkFileSystemModel
1447  * @show_files: whether files (as opposed to folders) should
1448  *              be displayed.
1449  * 
1450  * Sets whether files (as opposed to folders) should be included
1451  * in the #GtkTreeModel for display.
1452  **/
1453 void
1454 _gtk_file_system_model_set_show_files (GtkFileSystemModel *model,
1455                                        gboolean            show_files)
1456 {
1457   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1458
1459   show_files = show_files != FALSE;
1460
1461   if (show_files != model->show_files)
1462     {
1463       model->show_files = show_files;
1464       gtk_file_system_model_refilter_all (model);
1465     }
1466 }
1467
1468 /**
1469  * _gtk_file_system_model_get_cancellable:
1470  * @model: the model
1471  *
1472  * Gets the cancellable used by the @model. This is the cancellable used
1473  * internally by the @model that will be cancelled when @model is 
1474  * disposed. So you can use it for operations that should be cancelled
1475  * when the model goes away.
1476  *
1477  * Returns: The cancellable used by @model
1478  **/
1479 GCancellable *
1480 _gtk_file_system_model_get_cancellable (GtkFileSystemModel *model)
1481 {
1482   g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL);
1483
1484   return model->cancellable;
1485 }
1486
1487 /**
1488  * _gtk_file_system_model_iter_is_visible:
1489  * @model: the model
1490  * @iter: a valid iterator
1491  *
1492  * Checks if the iterator is visible. A visible iterator references
1493  * a row that is currently exposed using the #GtkTreeModel API. If
1494  * the iterator is invisible, it references a file that is not shown
1495  * for some reason, such as being filtered by the current filter or
1496  * being a hidden file.
1497  *
1498  * Returns: %TRUE if the iterator is visible
1499  **/
1500 gboolean
1501 _gtk_file_system_model_iter_is_visible (GtkFileSystemModel *model,
1502                                         GtkTreeIter        *iter)
1503 {
1504   FileModelNode *node;
1505
1506   g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), FALSE);
1507   g_return_val_if_fail (iter != NULL, FALSE);
1508
1509   node = get_node (model, ITER_INDEX (iter));
1510   return node->visible;
1511 }
1512
1513 /**
1514  * _gtk_file_system_model_get_info:
1515  * @model: a #GtkFileSystemModel
1516  * @iter: a #GtkTreeIter pointing to a row of @model
1517  * 
1518  * Gets the #GFileInfo structure for a particular row
1519  * of @model.
1520  * 
1521  * Return value: a #GFileInfo structure. This structure
1522  *   is owned by @model and must not be modified or freed.
1523  *   If you want to keep the information for later use,
1524  *   you must take a reference, since the structure may be
1525  *   freed on later changes to the file system.  If you have
1526  *   called _gtk_file_system_model_add_editable() and the @iter
1527  *   corresponds to the row that this function returned, the
1528  *   return value will be NULL.
1529  **/
1530 GFileInfo *
1531 _gtk_file_system_model_get_info (GtkFileSystemModel *model,
1532                                  GtkTreeIter        *iter)
1533 {
1534   FileModelNode *node;
1535
1536   g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL);
1537   g_return_val_if_fail (iter != NULL, NULL);
1538
1539   node = get_node (model, ITER_INDEX (iter));
1540   g_assert (node->info == NULL || G_IS_FILE_INFO (node->info));
1541   return node->info;
1542 }
1543
1544 /**
1545  * _gtk_file_system_model_get_file:
1546  * @model: a #GtkFileSystemModel
1547  * @iter: a #GtkTreeIter pointing to a row of @model
1548  * 
1549  * Gets the file for a particular row in @model. 
1550  *
1551  * Return value: the file. This object is owned by @model and
1552  *   or freed. If you want to save the path for later use,
1553  *   you must take a ref, since the object may be freed
1554  *   on later changes to the file system.
1555  **/
1556 GFile *
1557 _gtk_file_system_model_get_file (GtkFileSystemModel *model,
1558                                  GtkTreeIter        *iter)
1559 {
1560   FileModelNode *node;
1561
1562   g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL);
1563
1564   node = get_node (model, ITER_INDEX (iter));
1565   return node->file;
1566 }
1567
1568 /**
1569  * _gtk_file_system_model_get_value:
1570  * @model: a #GtkFileSystemModel
1571  * @iter: a #GtkTreeIter pointing to a row of @model
1572  * @column: the column to get the value for
1573  *
1574  * Gets the value associated with the given row @iter and @column.
1575  * If no value is available yet and the default value should be used,
1576  * %NULL is returned.
1577  * This is a performance optimization for the calls 
1578  * gtk_tree_model_get() or gtk_tree_model_get_value(), which copy 
1579  * the value and spend a considerable amount of time in iterator 
1580  * lookups. Both of which are slow.
1581  *
1582  * Returns: a pointer to the actual value as stored in @model or %NULL
1583  *          if no value available yet.
1584  **/
1585 const GValue *
1586 _gtk_file_system_model_get_value (GtkFileSystemModel *model,
1587                                   GtkTreeIter *       iter,
1588                                   int                 column)
1589 {
1590   FileModelNode *node;
1591
1592   g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL);
1593   g_return_val_if_fail (column >= 0 && (guint) column < model->n_columns, NULL);
1594
1595   node = get_node (model, ITER_INDEX (iter));
1596     
1597   if (!G_VALUE_TYPE (&node->values[column]))
1598     {
1599       g_value_init (&node->values[column], model->column_types[column]);
1600       if (!model->get_func (model, 
1601                             node->file, 
1602                             node->info, 
1603                             column, 
1604                             &node->values[column],
1605                             model->get_data))
1606         {
1607           g_value_unset (&node->values[column]);
1608           return NULL;
1609         }
1610     }
1611   
1612   return &node->values[column];
1613 }
1614
1615 static guint
1616 node_get_for_file (GtkFileSystemModel *model,
1617                    GFile *             file)
1618 {
1619   guint i;
1620
1621   i = GPOINTER_TO_UINT (g_hash_table_lookup (model->file_lookup, file));
1622   if (i != 0)
1623     return i;
1624
1625   /* Node 0 is the editable row and has no associated file or entry in the table, so we start counting from 1.
1626    *
1627    * The invariant here is that the files in model->files[n] for n < g_hash_table_size (model->file_lookup)
1628    * are already added to the hash table. The table can get cleared when we re-sort; this loop merely rebuilds
1629    * our (file -> index) mapping on demand.
1630    *
1631    * If we exit the loop, the next pending batch of mappings will be resolved when this function gets called again
1632    * with another file that is not yet in the mapping.
1633    */
1634   for (i = g_hash_table_size (model->file_lookup) + 1; i < model->files->len; i++)
1635     {
1636       FileModelNode *node = get_node (model, i);
1637
1638       g_hash_table_insert (model->file_lookup, node->file, GUINT_TO_POINTER (i));
1639       if (g_file_equal (node->file, file))
1640         return i;
1641     }
1642
1643   return 0;
1644 }
1645
1646 /**
1647  * _gtk_file_system_model_get_iter_for_file:
1648  * @model: the model
1649  * @iter: the iterator to be initialized
1650  * @file: the file to look up
1651  *
1652  * Initializes @iter to point to the row used for @file, if @file is part 
1653  * of the model. Note that upon successful return, @iter may point to an 
1654  * invisible row in the @model. Use 
1655  * _gtk_file_system_model_iter_is_visible() to make sure it is visible to
1656  * the tree view.
1657  *
1658  * Returns: %TRUE if file is part of the model and @iter was initialized
1659  **/
1660 gboolean
1661 _gtk_file_system_model_get_iter_for_file (GtkFileSystemModel *model,
1662                                           GtkTreeIter        *iter,
1663                                           GFile *             file)
1664 {
1665   guint i;
1666
1667   g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), FALSE);
1668   g_return_val_if_fail (iter != NULL, FALSE);
1669   g_return_val_if_fail (G_IS_FILE (file), FALSE);
1670
1671   i = node_get_for_file (model, file);
1672
1673   if (i == 0)
1674     return FALSE;
1675
1676   ITER_INIT_FROM_INDEX (model, iter, i);
1677   return TRUE;
1678 }
1679
1680 /**
1681  * add_file:
1682  * @model: the model
1683  * @file: the file to add
1684  * @info: the information to associate with the file
1685  *
1686  * Adds the given @file with its associated @info to the @model. 
1687  * If the model is frozen, the file will only show up after it is thawn.
1688  **/
1689 static void
1690 add_file (GtkFileSystemModel *model,
1691           GFile              *file,
1692           GFileInfo          *info)
1693 {
1694   FileModelNode *node;
1695   
1696   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1697   g_return_if_fail (G_IS_FILE (file));
1698   g_return_if_fail (G_IS_FILE_INFO (info));
1699
1700   node = g_slice_alloc0 (model->node_size);
1701   node->file = g_object_ref (file);
1702   if (info)
1703     node->info = g_object_ref (info);
1704   node->frozen_add = model->frozen ? TRUE : FALSE;
1705
1706   g_array_append_vals (model->files, node, 1);
1707   g_slice_free1 (model->node_size, node);
1708
1709   if (!model->frozen)
1710     node_set_visible (model, model->files->len -1,
1711                       node_should_be_visible (model, model->files->len - 1));
1712   gtk_file_system_model_sort_node (model, model->files->len -1);
1713 }
1714
1715 /**
1716  * remove_file:
1717  * @model: the model
1718  * @file: file to remove from the model. The file must have been 
1719  *        added to the model previously
1720  *
1721  * Removes the given file from the model. If the file is not part of 
1722  * @model, this function does nothing.
1723  **/
1724 static void
1725 remove_file (GtkFileSystemModel *model,
1726              GFile              *file)
1727 {
1728   FileModelNode *node;
1729   guint id;
1730
1731   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1732   g_return_if_fail (G_IS_FILE (file));
1733
1734   id = node_get_for_file (model, file);
1735   if (id == 0)
1736     return;
1737
1738   node = get_node (model, id);
1739   node_set_visible (model, id, FALSE);
1740
1741   g_hash_table_remove (model->file_lookup, file);
1742   g_object_unref (node->file);
1743
1744   if (node->info)
1745     g_object_unref (node->info);
1746
1747   g_array_remove_index (model->files, id);
1748   /* We don't need to resort, as removing a row doesn't change the sorting order */
1749 }
1750
1751 /**
1752  * _gtk_file_system_model_update_file:
1753  * @model: the model
1754  * @file: the file
1755  * @info: the new file info
1756  * @requires_resort: FIXME: get rid of this argument
1757  *
1758  * Tells the file system model that the file changed and that the 
1759  * new @info should be used for it now.  If the file is not part of 
1760  * @model, it will get added automatically.
1761  **/
1762 void
1763 _gtk_file_system_model_update_file (GtkFileSystemModel *model,
1764                                     GFile              *file,
1765                                     GFileInfo          *info,
1766                                     gboolean            requires_resort)
1767 {
1768   FileModelNode *node;
1769   guint i, id;
1770   GFileInfo *old_info;
1771
1772   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1773   g_return_if_fail (G_IS_FILE (file));
1774   g_return_if_fail (G_IS_FILE_INFO (info));
1775
1776   id = node_get_for_file (model, file);
1777   if (id == 0)
1778     add_file (model, file, info);
1779
1780   node = get_node (model, id);
1781
1782   old_info = node->info;
1783   node->info = g_object_ref (info);
1784   if (old_info)
1785     g_object_unref (old_info);
1786
1787   for (i = 0; i < model->n_columns; i++)
1788     {
1789       if (G_VALUE_TYPE (&node->values[i]))
1790         g_value_unset (&node->values[i]);
1791     }
1792
1793   if (node->visible)
1794     emit_row_changed_for_node (model, id);
1795
1796   if (requires_resort)
1797     gtk_file_system_model_sort_node (model, id);
1798 }
1799
1800 /**
1801  * _gtk_file_system_model_set_filter:
1802  * @mode: a #GtkFileSystemModel
1803  * @filter: %NULL or filter to use
1804  * 
1805  * Sets a filter to be used for deciding if a row should be visible or not.
1806  * Directories are always visible.
1807  **/
1808 void
1809 _gtk_file_system_model_set_filter (GtkFileSystemModel      *model,
1810                                    GtkFileFilter *          filter)
1811 {
1812   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1813   g_return_if_fail (filter == NULL || GTK_IS_FILE_FILTER (filter));
1814   
1815   if (filter)
1816     g_object_ref (filter);
1817   if (model->filter)
1818     g_object_unref (model->filter);
1819   model->filter = filter;
1820
1821   gtk_file_system_model_refilter_all (model);
1822 }
1823
1824 /**
1825  * _gtk_file_system_model_add_editable:
1826  * @model: a #GtkFileSystemModel
1827  * @iter: Location to return the iter corresponding to the editable row
1828  * 
1829  * Adds an "empty" row at the beginning of the model.  This does not refer to
1830  * any file, but is a temporary placeholder for a file name that the user will
1831  * type when a corresponding cell is made editable.  When your code is done
1832  * using this temporary row, call _gtk_file_system_model_remove_editable().
1833  **/
1834 void
1835 _gtk_file_system_model_add_editable (GtkFileSystemModel *model, GtkTreeIter *iter)
1836 {
1837   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1838   g_return_if_fail (!get_node (model, 0)->visible);
1839
1840   node_set_visible (model, 0, TRUE);
1841   ITER_INIT_FROM_INDEX (model, iter, 0);
1842 }
1843
1844 /**
1845  * _gtk_file_system_model_remove_editable:
1846  * @model: a #GtkFileSystemModel
1847  * 
1848  * Removes the "empty" row at the beginning of the model that was
1849  * created with _gtk_file_system_model_add_editable().  You should call
1850  * this function when your code is finished editing this temporary row.
1851  **/
1852 void
1853 _gtk_file_system_model_remove_editable (GtkFileSystemModel *model)
1854 {
1855   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1856   g_return_if_fail (get_node (model, 0)->visible);
1857
1858   node_set_visible (model, 0, FALSE);
1859 }
1860
1861 /**
1862  * _gtk_file_system_model_freeze_updates:
1863  * @model: a #GtkFileSystemModel
1864  *
1865  * Freezes most updates on the model, so that performing multiple 
1866  * operations on the files in the model do not cause any events.
1867  * Use _gtk_file_system_model_thaw_updates() to resume proper 
1868  * operations. It is fine to call this function multiple times as
1869  * long as freeze and thaw calls are balanced.
1870  **/
1871 void
1872 _gtk_file_system_model_freeze_updates (GtkFileSystemModel *model)
1873 {
1874   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1875
1876   model->frozen++;
1877 }
1878
1879 /**
1880  * _gtk_file_system_model_thaw_updates:
1881  * @model: a #GtkFileSystemModel
1882  *
1883  * Undoes the effect of a previous call to
1884  * _gtk_file_system_model_freeze_updates() 
1885  **/
1886 void
1887 _gtk_file_system_model_thaw_updates (GtkFileSystemModel *model)
1888 {
1889   gboolean stuff_added;
1890
1891   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1892   g_return_if_fail (model->frozen > 0);
1893
1894   model->frozen--;
1895   if (model->frozen > 0)
1896     return;
1897
1898   stuff_added = get_node (model, model->files->len - 1)->frozen_add;
1899
1900   if (model->filter_on_thaw)
1901     gtk_file_system_model_refilter_all (model);
1902   if (model->sort_on_thaw)
1903     gtk_file_system_model_sort (model);
1904   if (stuff_added)
1905     {
1906       guint i;
1907
1908       for (i = 0; i < model->files->len; i++)
1909         {
1910           FileModelNode *node = get_node (model, i);
1911
1912           if (!node->frozen_add)
1913             continue;
1914           node->frozen_add = FALSE;
1915           node_set_visible (model, i, node_should_be_visible (model, i));
1916         }
1917     }
1918 }
1919
1920 /**
1921  * _gtk_file_system_model_clear_cache:
1922  * @model: a #GtkFileSystemModel
1923  * @column: the column to clear or -1 for all columns
1924  *
1925  * Clears the cached values in the model for the given @column. Use 
1926  * this function whenever your get_value function would return different
1927  * values for a column.
1928  * The file chooser uses this for example when the icon theme changes to 
1929  * invalidate the cached pixbufs.
1930  **/
1931 void
1932 _gtk_file_system_model_clear_cache (GtkFileSystemModel *model,
1933                                     int                 column)
1934 {
1935   guint i;
1936   int start, end;
1937   gboolean changed;
1938
1939   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1940   g_return_if_fail (column >= -1 && (guint) column < model->n_columns);
1941
1942   if (column > -1)
1943     {
1944       start = column;
1945       end = column + 1;
1946     }
1947   else
1948     {
1949       start = 0;
1950       end = model->n_columns;
1951     }
1952
1953   for (i = 0; i < model->files->len; i++)
1954     {
1955       FileModelNode *node = get_node (model, i);
1956       changed = FALSE;
1957       for (column = start; column < end; column++)
1958         {
1959           if (!G_VALUE_TYPE (&node->values[column]))
1960             continue;
1961           
1962           g_value_unset (&node->values[column]);
1963           changed = TRUE;
1964         }
1965
1966       if (changed && node->visible)
1967         emit_row_changed_for_node (model, i);
1968     }
1969
1970   /* FIXME: resort? */
1971 }
1972
1973 /**
1974  * _gtk_file_system_model_add_and_query_file:
1975  * @model: a #GtkFileSystemModel
1976  * @file: the file to add
1977  * @attributes: attributes to query before adding the file
1978  *
1979  * This is a conenience function that calls g_file_query_info_async() on 
1980  * the given file, and when successful, adds it to the model.
1981  * Upon failure, the @file is discarded.
1982  **/
1983 void
1984 _gtk_file_system_model_add_and_query_file (GtkFileSystemModel *model,
1985                                            GFile *             file,
1986                                            const char *        attributes)
1987 {
1988   g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model));
1989   g_return_if_fail (G_IS_FILE (file));
1990   g_return_if_fail (attributes != NULL);
1991
1992   g_file_query_info_async (file,
1993                            attributes,
1994                            G_FILE_QUERY_INFO_NONE,
1995                            IO_PRIORITY,
1996                            model->cancellable,
1997                            gtk_file_system_model_query_done,
1998                            model);
1999 }