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