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