diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 346c8b573..b3e3cdab4 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -7586,6 +7586,10 @@ show_and_select_files (GtkFileChooserDefault *impl, g_assert (fsmodel == impl->browse_files_model); + /* The model adds files and filters in the background; the visibility + * checks below need the rows as they are now. */ + _gtk_file_system_model_flush (fsmodel); + enabled_hidden = impl->show_hidden; removed_filters = (impl->current_filter == NULL); @@ -7616,6 +7620,7 @@ show_and_select_files (GtkFileChooserDefault *impl, if (!enabled_hidden && (is_hidden || is_backup)) { g_object_set (impl, "show-hidden", TRUE, NULL); + _gtk_file_system_model_flush (fsmodel); enabled_hidden = TRUE; } } @@ -7631,6 +7636,7 @@ show_and_select_files (GtkFileChooserDefault *impl, if (!removed_filters) { set_current_filter (impl, NULL); + _gtk_file_system_model_flush (fsmodel); removed_filters = TRUE; } } @@ -8185,7 +8191,10 @@ set_list_model (GtkFileChooserDefault *impl, gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_SIZE, size_sort_func, impl, NULL); gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_MTIME, mtime_sort_func, impl, NULL); gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), NULL, NULL, NULL); - set_sort_column (impl); + /* Sort from the start: the model sorts files as it adds them, while + * resorting rows that are already shown takes extra work. */ + gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (impl->browse_files_model), + impl->sort_column, impl->sort_order); impl->list_sort_ascending = TRUE; g_signal_connect (impl->browse_files_model, "sort-column-changed", G_CALLBACK (list_sort_column_changed_cb), impl); diff --git a/gtk/gtkfilesystemmodel.c b/gtk/gtkfilesystemmodel.c index 52fd17a08..16bc2b81e 100644 --- a/gtk/gtkfilesystemmodel.c +++ b/gtk/gtkfilesystemmodel.c @@ -36,89 +36,58 @@ /*** Structure: how GtkFileSystemModel works * - * This is a custom GtkTreeModel used to hold a collection of files for GtkFileChooser. There are two use cases: + * This is a custom GtkTreeModel used to hold a collection of files for + * GtkFileChooser. There are two use cases: * - * 1. The model populates itself from a folder, using the GIO file enumerator API. This happens if you use - * _gtk_file_system_model_new_for_directory(). This is the normal usage for showing the contents of a folder. + * 1. The model populates itself from a folder, using the GIO file + * enumerator API. This happens if you use + * _gtk_file_system_model_new_for_directory(). * - * 2. The caller populates the model by hand, with files not necessarily in the same folder. This happens - * if you use _gtk_file_system_model_new() and then _gtk_file_system_model_add_and_query_file(). This is - * the special kind of usage for "search" and "recent-files", where the file chooser gives the model the - * files to be displayed. + * 2. The caller populates the model by hand, with files not necessarily + * in the same folder ("search" and "recent files"), using + * _gtk_file_system_model_new() and + * _gtk_file_system_model_add_and_query_file(). * - * Internal data structure - * ----------------------- + * Nodes + * ----- * - * Each file is kept in a FileModelNode structure. Each FileModelNode holds a GFile* and other data. All the - * node structures have the same size, determined at runtime, depending on the number of columns that were passed - * to _gtk_file_system_model_new() or _gtk_file_system_model_new_for_directory() (that is, the size of a node is - * not sizeof (FileModelNode), but rather model->node_size). The last field in the FileModelNode structure, - * node->values[], is an array of GValue, used to hold the data for those columns. + * Every file has a FileModelNode in model->files. A node keeps its slot + * (its "ID") for its whole life, so iterators stay valid while rows move; + * a generation number in the iterator detects reused slots. Slot 0 is the + * placeholder row of _gtk_file_system_model_add_editable(). + * model->file_lookup maps each GFile to its ID. * - * The model stores an array of FileModelNode structures in model->files. This is a GArray where each element is - * model->node_size bytes in size (the model computes that node size when initializing itself). There are - * convenience macros, get_node() and node_index(), to access that array based on an array index or a pointer to - * a node inside the array. + * Column values are cached in pages of 64 IDs that are only allocated for + * columns that are actually read, so unused columns cost no memory. * - * The model accesses files through two of its fields: + * Order and rows + * -------------- * - * model->files - GArray of FileModelNode structures. + * model->order lists the IDs in sort order. Its first model->committed + * entries are sorted and filtered; the GtkTreeModel rows are the visible + * ones among them, listed in model->visible_order. Everything after them + * is the "tail": files that were added but are not part of the rows yet. * - * model->file_lookup - hash table that maps a GFile* to an index inside the model->files array. + * All changes to the rows happen in one idle handler (see + * gtk_file_system_model_work()), in short slices so the user interface + * stays responsive on slow machines: * - * The model->file_lookup hash table is populated lazily. It is both accessed and populated with the - * node_get_for_file() function. The invariant is that the files in model->files[n] for n < g_hash_table_size - * (model->file_lookup) are already added to the hash table. The hash table will get cleared when we re-sort the - * files, as the array will be in a different order and the indexes need to be rebuilt. + * - A commit sorts the tail and merges it into the committed part, + * announcing each new row at its final position. While a folder + * loads, commits come at growing intervals; otherwise right away. + * This is the only way rows are added, whether the files come from + * the enumerator, the folder monitor or a query. A commit can also + * filter all committed nodes again (show hidden files, filter change). + * - A resort sorts the committed IDs and applies the new order at once. + * - Removing a file, moving a file whose information changed and + * filtering a single file again are queued per node and done between + * commits. * - * Each FileModelNode has a node->visible field, which indicates whether the node is visible in the GtkTreeView. - * A node may be invisible if, for example, it corresponds to a hidden file and the file chooser is not showing - * hidden files. Also, a file filter may be explicitly set onto the model, for example, to only show files that - * match "*.jpg". In this case, node->filtered_out says whether the node failed the filter. The ultimate - * decision on whether a node is visible or not in the treeview is distilled into the node->visible field. - * The reason for having a separate node->filtered_out field is so that the file chooser can query whether - * a (filtered-out) folder should be made sensitive in the GUI. + * Merges keep the model consistent between slices: the rows announced so + * far are model->merge_vis, followed by the old rows not merged yet. * - * Visible rows vs. possibly-invisible nodes - * ----------------------------------------- - * - * Since not all nodes in the model->files array may be visible, we need a way to map visible row indexes from - * the treeview to array indexes in our array of files. And thus we introduce a bit of terminology: - * - * index - An index in the model->files array. All variables/fields that represent indexes are either called - * "index" or "i_*", or simply "i" for things like loop counters. - * - * row - An index in the GtkTreeView, i.e. the index of a row within the outward-facing API of the - * GtkFileSystemModel. However, note that our rows are 1-based, not 0-based, for the reason explained in the - * following paragraph. Variables/fields that represent visible rows are called "row", or "r_*", or simply - * "r". - * - * Each FileModelNode has a node->row field which is the number of visible rows in the treeview, *before and - * including* that node. This means that node->row is 1-based, instead of 0-based --- this makes some code - * simpler, believe it or not :) This also means that when the calling GtkTreeView gives us a GtkTreePath, we - * turn the 0-based treepath into a 1-based row for our purposes. If a node is not visible, it will have the - * same row number as its closest preceding visible node. - * - * We try to compute the node->row fields lazily. A node is said to be "valid" if its node->row is accurate. - * For this, the model keeps a model->n_nodes_valid field which is the count of valid nodes starting from the - * beginning of the model->files array. When a node changes its information, or when a node gets deleted, that - * node and the following ones get invalidated by simply setting model->n_nodes_valid to the array index of the - * node. If the model happens to need a node's row number and that node is in the model->files array after - * model->n_nodes_valid, then the nodes get re-validated up to the sought node. See node_validate_rows() for - * this logic. - * - * You never access a node->row directly. Instead, call node_get_tree_row(). That function will validate the nodes - * up to the sought one if the node is not valid yet, and it will return a proper 0-based row. - * - * Sorting - * ------- - * - * The model implements the GtkTreeSortable interface. To avoid re-sorting - * every time a node gets added (which would lead to O(n^2) performance during - * the initial population of the model), the model can freeze itself (with - * freeze_updates()) during the intial population process. When the model is - * frozen, sorting will not happen. The model will sort itself when the freeze - * count goes back to zero, via corresponding calls to thaw_updates(). + * Editing (the placeholder row) holds all of this, so the rows do not + * change under the user. */ /*** DEFINES ***/ @@ -131,47 +100,121 @@ /* random number that everyone else seems to use, too */ #define FILES_PER_QUERY 100 +/* Read ahead up to this many entries, so the enumerator thread does not + * wait while the main thread integrates a batch. */ +#define MODEL_READ_AHEAD (2 * FILES_PER_QUERY) + +/* Length of one slice of work in the main loop, and how many items are + * processed between looks at the clock. */ +#define MODEL_SLICE_US 8000 +#define MODEL_CLOCK_GRANULARITY 8 + +/* While a folder loads, the first rows appear after MODEL_FIRST_COMMIT_US; + * later commits come at growing intervals so large folders are not merged + * over and over. */ +#define MODEL_FIRST_COMMIT_US (100 * 1000) +#define MODEL_COMMIT_INTERVAL_US (250 * 1000) +#define MODEL_MAX_COMMIT_INTERVAL_US (1000 * 1000) + +#define VALUE_PAGE_SHIFT 6 +#define VALUE_PAGE_SIZE (1u << VALUE_PAGE_SHIFT) +#define VALUE_PAGE_MASK (VALUE_PAGE_SIZE - 1u) + +enum +{ + PHASE_IDLE, + PHASE_SORT, /* sorting model->sort_buf */ + PHASE_MERGE /* merging the sorted tail into the rows */ +}; + +enum +{ + SORT_FOR_COMMIT, + SORT_FOR_RESORT +}; + typedef struct _FileModelNode FileModelNode; typedef struct _GtkFileSystemModelClass GtkFileSystemModelClass; struct _FileModelNode { - GFile * file; /* file represented by this node or NULL for editable */ - GFileInfo * info; /* info for this file or NULL if unknown */ + GFile * file; /* NULL for the editable row and unused slots */ + GFileInfo * info; /* NULL for the editable row */ - guint row; /* if valid (see model->n_valid_indexes), visible nodes before and including - * this one - see the "Structure" comment above. - */ + guint order_pos; /* index in model->order; next free slot if unused */ + guint visible_pos; /* row, if visible (see node_visible_row()) */ + guint generation; /* changes whenever the slot is reused */ - guint visible :1; /* if the file is currently visible */ - guint filtered_out :1;/* if the file is currently filtered out (i.e. it didn't pass the filters) */ - guint frozen_add :1; /* true if the model was frozen and the entry has not been added yet */ - - GValue values[1]; /* actually n_columns values */ + guint visible :1; /* is a row */ + guint filtered_out :1;/* did not pass the filter */ + guint uncommitted :1; /* in the tail of model->order */ + guint merged_epoch :1;/* see model->merge_epoch */ + guint queued :1; /* in model->node_queue */ + guint want_remove :1; + guint want_reposition :1; + guint want_refilter :1; + guint want_changed :1; /* row-changed held back while editing */ }; +typedef struct +{ + GValue values[VALUE_PAGE_SIZE]; +} ValuePage; + struct _GtkFileSystemModel { GObject parent_instance; GFile * dir; /* directory that's displayed */ - guint dir_thaw_source;/* GSource id for unfreezing the model */ char * attributes; /* attributes the file info must contain, or NULL for all attributes */ GFileMonitor * dir_monitor; /* directory that is monitored, or NULL if monitoring was not supported */ - + GFileEnumerator * dir_enumerator; GCancellable * cancellable; /* cancellable in use for all operations - cancelled on dispose */ - GArray * files; /* array of FileModelNode containing all our files */ - gsize node_size; /* Size of a FileModelNode structure once its ->values field has n_columns */ - guint n_nodes_valid; /* count of valid nodes (i.e. those whose node->row is accurate) */ - GHashTable * file_lookup; /* mapping of GFile => array index in model->files - * This hash table doesn't always have the same number of entries as the files array; - * it can get cleared completely when we resort. - * The hash table gets re-populated in node_get_for_file() if this mismatch is - * detected. - */ + GHashTable * monitor_queries;/* GFile => serial of the latest query for it */ + guint monitor_serial; + GHashTable * deleted_files; /* deleted while the enumerator may still return them */ + + /* Loading */ + GQueue pending_infos; /* GFileInfos from the enumerator, not added yet */ + GError * load_error; + gint64 next_commit_time; + gint64 commit_interval; + guint commit_timer; + + /* Work in the main loop (see gtk_file_system_model_work) */ + guint work_source; + guint phase; + GQueue node_queue; /* IDs of nodes with want_* flags */ + + GArray * sort_buf; /* PHASE_SORT: IDs being sorted */ + GArray * sort_scratch; + guint sort_purpose; + guint sort_width; + guint sort_left; + guint sort_mid; + guint sort_right; + guint sort_i; + guint sort_j; + guint sort_k; + + GArray * merge_tail; /* PHASE_MERGE: sorted tail */ + GArray * merge_order; /* new model->order */ + GArray * merge_vis; /* rows announced so far */ + guint merge_oi; /* next committed node to merge */ + guint merge_ti; /* next tail node to merge */ + guint merge_ovi; /* old rows merged so far */ + guint merge_end; /* model->order length when the commit started */ + + GArray * files; /* FileModelNode by ID */ + GArray * order; /* IDs in sort order: committed part, then the tail */ + GArray * visible_order; /* IDs of the rows */ + guint committed; + guint free_id_head; /* first unused slot, or 0 */ + GHashTable * file_lookup; /* GFile => ID */ guint n_columns; /* number of columns */ GType * column_types; /* types of each column */ + GPtrArray ** value_pages; /* per column: ValuePages by ID / VALUE_PAGE_SIZE */ GtkFileSystemModelGetValue get_func; /* function to call to fill in values in columns */ gpointer get_data; /* data to pass to get_func */ @@ -184,10 +227,15 @@ struct _GtkFileSystemModel gpointer default_sort_data; /* data to pass to default sort func */ GDestroyNotify default_sort_destroy; /* function to call to destroy default_sort_data */ - guint frozen; /* number of times we're frozen */ - - gboolean filter_on_thaw :1;/* set when filtering needs to happen upon thawing */ - gboolean sort_on_thaw :1;/* set when sorting needs to happen upon thawing */ + guint directory_loading :1; + guint enumeration_done :1; + guint next_files_in_flight :1; + guint editing_hold :1; /* the editable row is shown */ + guint resort_pending :1; + guint refilter_pending :1; + guint merge_refilter :1;/* the merge in progress filters committed nodes again */ + guint merge_epoch :1; /* toggles with every merge */ + guint in_merge_step :1; guint show_hidden :1; /* whether to show hidden files */ guint show_folders :1;/* whether to show folders */ @@ -208,8 +256,20 @@ struct _GtkFileSystemModelClass void (*finished_loading) (GtkFileSystemModel *model, GError *error); }; -static void freeze_updates (GtkFileSystemModel *model); -static void thaw_updates (GtkFileSystemModel *model); +/* Signal IDs */ +enum { + FINISHED_LOADING, + LAST_SIGNAL +}; + +static guint file_system_model_signals[LAST_SIGNAL] = { 0 }; + +static void gtk_file_system_model_schedule_work (GtkFileSystemModel *model); +static void gtk_file_system_model_complete_merge (GtkFileSystemModel *model); +static void gtk_file_system_model_request_next_files (GtkFileSystemModel *model); +static void gtk_file_system_model_got_files (GObject *object, + GAsyncResult *res, + gpointer data); static guint node_get_for_file (GtkFileSystemModel *model, GFile *file); @@ -222,88 +282,200 @@ static void remove_file (GtkFileSystemModel *model, /* iter setup: * @user_data: the model - * @user_data2: GUINT_TO_POINTER of array index of current entry - * - * All other fields are unused. Note that the array index does not corrspond - * 1:1 with the path index as entries might not be visible. + * @user_data2: node ID + * @user_data3: node generation */ #define ITER_INDEX(iter) GPOINTER_TO_UINT((iter)->user_data2) -#define ITER_IS_VALID(model, iter) ((model) == (iter)->user_data) -#define ITER_INIT_FROM_INDEX(model, _iter, _index) G_STMT_START {\ - g_assert (_index < (model)->files->len); \ + +#define get_node(_model, _index) \ + (&g_array_index ((_model)->files, FileModelNode, (_index))) + +static gboolean +iter_is_valid (GtkFileSystemModel *model, + GtkTreeIter *iter) +{ + FileModelNode *node; + guint id; + + if (iter == NULL || iter->user_data != model) + return FALSE; + + id = ITER_INDEX (iter); + if (id >= model->files->len) + return FALSE; + + node = get_node (model, id); + return (id == 0 || node->file != NULL) && + node->generation == GPOINTER_TO_UINT (iter->user_data3); +} + +#define ITER_IS_VALID(model, iter) iter_is_valid ((model), (iter)) + +#define ITER_INIT_FROM_INDEX(model, _iter, _index) G_STMT_START { \ + FileModelNode *_node; \ + g_assert ((_index) < (model)->files->len); \ + _node = get_node ((model), (_index)); \ + g_assert ((_index) == 0 || _node->file != NULL); \ (_iter)->user_data = (model); \ (_iter)->user_data2 = GUINT_TO_POINTER (_index); \ -}G_STMT_END + (_iter)->user_data3 = GUINT_TO_POINTER (_node->generation); \ +} G_STMT_END -/*** FileModelNode ***/ +/*** Order and rows ***/ -/* Get a FileModelNode structure given an index in the model->files array of nodes */ -#define get_node(_model, _index) ((FileModelNode *) ((_model)->files->data + (_index) * (_model)->node_size)) - -/* Get an index within the model->files array of nodes, given a FileModelNode* */ -#define node_index(_model, _node) (((gchar *) (_node) - (_model)->files->data) / (_model)->node_size) - -/* @up_to_index: smallest model->files array index that will be valid after this call - * @up_to_row: smallest node->row that will be valid after this call - * - * If you want to validate up to an index or up to a row, specify the index or - * the row you want and specify G_MAXUINT for the other argument. Pass - * G_MAXUINT for both arguments for "validate everything". - */ static void -node_validate_rows (GtkFileSystemModel *model, guint up_to_index, guint up_to_row) +order_update_positions (GtkFileSystemModel *model, + guint first, + guint end) { - guint i, row; + guint i; - if (model->files->len == 0) - return; + for (i = first; i < end; i++) + get_node (model, g_array_index (model->order, guint, i))->order_pos = i; +} - up_to_index = MIN (up_to_index, model->files->len - 1); +static void +visible_update_positions_from (GtkFileSystemModel *model, + guint first) +{ + guint i; - i = model->n_nodes_valid; - if (i != 0) - row = get_node (model, i - 1)->row; - else - row = 0; + for (i = first; i < model->visible_order->len; i++) + get_node (model, g_array_index (model->visible_order, guint, i))->visible_pos = i; +} - while (i <= up_to_index && row <= up_to_row) +/* Index of the first entry of @rows[@lo, len) whose node comes after + * order position @order_pos (or at it, unless @after). */ +static guint +rows_find_order_pos (GtkFileSystemModel *model, + GArray *rows, + guint lo, + guint order_pos, + gboolean after) +{ + guint hi = rows->len; + + while (lo < hi) { - FileModelNode *node = get_node (model, i); - if (node->visible) - row++; - node->row = row; - i++; + guint mid = lo + (hi - lo) / 2; + guint pos = get_node (model, g_array_index (rows, guint, mid))->order_pos; + + if (pos < order_pos || (after && pos == order_pos)) + lo = mid + 1; + else + hi = mid; } - model->n_nodes_valid = i; + + return lo; +} + +/* The editable row, if shown, is always the first row. */ +static guint +rows_first_file (GtkFileSystemModel *model, + GArray *rows) +{ + return rows->len > 0 && g_array_index (rows, guint, 0) == 0 ? 1 : 0; +} + +/* While a merge is in progress, the rows are model->merge_vis (merged, in + * the new order) followed by model->visible_order[merge_ovi..] (not merged + * yet). The functions below see exactly the rows announced so far. */ +#define MODEL_MERGING(model) ((model)->phase == PHASE_MERGE) + +static guint +model_n_visible (GtkFileSystemModel *model) +{ + if (MODEL_MERGING (model)) + return model->merge_vis->len + (model->visible_order->len - model->merge_ovi); + + return model->visible_order->len; } static guint -node_get_tree_row (GtkFileSystemModel *model, guint index) +model_nth_visible (GtkFileSystemModel *model, + guint n) { - if (model->n_nodes_valid <= index) - node_validate_rows (model, index, G_MAXUINT); + if (MODEL_MERGING (model)) + { + if (n < model->merge_vis->len) + return g_array_index (model->merge_vis, guint, n); - return get_node (model, index)->row - 1; + n = n - model->merge_vis->len + model->merge_ovi; + } + + if (n >= model->visible_order->len) + return G_MAXUINT; + + return g_array_index (model->visible_order, guint, n); } -static void -node_invalidate_index (GtkFileSystemModel *model, guint id) +static gboolean +node_is_merged (GtkFileSystemModel *model, + FileModelNode *node) { - model->n_nodes_valid = MIN (model->n_nodes_valid, id); + return MODEL_MERGING (model) && node->merged_epoch == model->merge_epoch; +} + +static guint +node_visible_row (GtkFileSystemModel *model, + FileModelNode *node) +{ + g_assert (node->visible); + + if (MODEL_MERGING (model) && !node_is_merged (model, node)) + return node->visible_pos - model->merge_ovi + model->merge_vis->len; + + return node->visible_pos; +} + +/* Number of rows that come before @node, which is not a row. */ +static guint +node_rows_before (GtkFileSystemModel *model, + FileModelNode *node) +{ + if (node->uncommitted) + return model_n_visible (model); + + if (!MODEL_MERGING (model)) + return rows_find_order_pos (model, model->visible_order, + rows_first_file (model, model->visible_order), + node->order_pos, TRUE); + + if (node_is_merged (model, node)) + return rows_find_order_pos (model, model->merge_vis, + rows_first_file (model, model->merge_vis), + node->order_pos, TRUE); + + return model->merge_vis->len - model->merge_ovi + + rows_find_order_pos (model, model->visible_order, model->merge_ovi, + node->order_pos, TRUE); } static GtkTreePath * -tree_path_new_from_node (GtkFileSystemModel *model, guint id) +tree_path_new_from_node (GtkFileSystemModel *model, + guint id) { - guint r = node_get_tree_row (model, id); + FileModelNode *node = get_node (model, id); + guint row; - g_assert (r < model->files->len); + if (node->visible) + row = node_visible_row (model, node); + else if (id == 0) + row = 0; + else + { + /* Invisible nodes report the closest preceding visible row. */ + row = node_rows_before (model, node); + if (row > 0) + row--; + } - return gtk_tree_path_new_from_indices (r, -1); + return gtk_tree_path_new_from_indices (row, -1); } static void -emit_row_inserted_for_node (GtkFileSystemModel *model, guint id) +emit_row_inserted_for_node (GtkFileSystemModel *model, + guint id) { GtkTreePath *path; GtkTreeIter iter; @@ -314,12 +486,23 @@ emit_row_inserted_for_node (GtkFileSystemModel *model, guint id) gtk_tree_path_free (path); } +static void node_queue (GtkFileSystemModel *model, guint id); + static void -emit_row_changed_for_node (GtkFileSystemModel *model, guint id) +emit_row_changed_for_node (GtkFileSystemModel *model, + guint id) { GtkTreePath *path; GtkTreeIter iter; + /* GtkIconView stops editing on any row change; hold it back. */ + if (model->editing_hold && id != 0) + { + get_node (model, id)->want_changed = TRUE; + node_queue (model, id); + return; + } + path = tree_path_new_from_node (model, id); ITER_INIT_FROM_INDEX (model, &iter, id); gtk_tree_model_row_changed (GTK_TREE_MODEL (model), path, &iter); @@ -327,7 +510,8 @@ emit_row_changed_for_node (GtkFileSystemModel *model, guint id) } static void -emit_row_deleted_for_row (GtkFileSystemModel *model, guint row) +emit_row_deleted_for_row (GtkFileSystemModel *model, + guint row) { GtkTreePath *path; @@ -336,43 +520,139 @@ emit_row_deleted_for_row (GtkFileSystemModel *model, guint row) gtk_tree_path_free (path); } +/*** Value cache ***/ + static void -node_set_visible_and_filtered_out (GtkFileSystemModel *model, guint id, gboolean visible, gboolean filtered_out) +value_page_free (gpointer data) { - FileModelNode *node = get_node (model, id); + ValuePage *page = data; + guint slot; - /* Filteredness */ - - if (node->filtered_out != filtered_out) - { - node->filtered_out = filtered_out; - if (node->visible && visible) - emit_row_changed_for_node (model, id); - } - - /* Visibility */ - - if (node->visible == visible || - node->frozen_add) + if (page == NULL) return; - if (visible) + for (slot = 0; slot < VALUE_PAGE_SIZE; slot++) + if (G_VALUE_TYPE (&page->values[slot]) != G_TYPE_INVALID) + g_value_unset (&page->values[slot]); + + g_free (page); +} + +static GValue * +value_cache_slot (GtkFileSystemModel *model, + guint id, + guint column, + gboolean create) +{ + GPtrArray *pages = model->value_pages[column]; + guint page_index = id >> VALUE_PAGE_SHIFT; + ValuePage *page; + + if (pages == NULL) { - node->visible = TRUE; - node_invalidate_index (model, id); - emit_row_inserted_for_node (model, id); + if (!create) + return NULL; + + pages = g_ptr_array_new_with_free_func (value_page_free); + model->value_pages[column] = pages; + } + + if (page_index >= pages->len) + { + if (!create) + return NULL; + + g_ptr_array_set_size (pages, page_index + 1); + } + + page = pages->pdata[page_index]; + if (page == NULL) + { + if (!create) + return NULL; + + page = g_new0 (ValuePage, 1); + pages->pdata[page_index] = page; + } + + return &page->values[id & VALUE_PAGE_MASK]; +} + +static gboolean +value_cache_clear_slot (GtkFileSystemModel *model, + guint id, + guint column) +{ + GValue *value = value_cache_slot (model, id, column, FALSE); + + if (value == NULL || G_VALUE_TYPE (value) == G_TYPE_INVALID) + return FALSE; + + g_value_unset (value); + return TRUE; +} + +static void +value_cache_clear_node (GtkFileSystemModel *model, + guint id) +{ + guint column; + + for (column = 0; column < model->n_columns; column++) + value_cache_clear_slot (model, id, column); +} + +/*** Nodes ***/ + +static void +file_model_node_clear (gpointer data) +{ + FileModelNode *node = data; + + g_clear_object (&node->file); + g_clear_object (&node->info); +} + +static guint +node_allocate_slot (GtkFileSystemModel *model) +{ + guint id; + + if (model->free_id_head != 0) + { + id = model->free_id_head; + model->free_id_head = get_node (model, id)->order_pos; } else { - guint row; - - row = node_get_tree_row (model, id); - g_assert (row < model->files->len); - - node->visible = FALSE; - node_invalidate_index (model, id); - emit_row_deleted_for_row (model, row); + id = model->files->len; + g_array_set_size (model->files, id + 1); + get_node (model, id)->generation = 1; } + + return id; +} + +static void +node_retire_slot (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + guint generation; + + g_assert (id != 0); + + file_model_node_clear (node); + value_cache_clear_node (model, id); + + generation = node->generation + 1; + if (generation == 0) + generation = 1; + + memset (node, 0, sizeof (*node)); + node->generation = generation; + node->order_pos = model->free_id_head; + model->free_id_head = id; } static gboolean @@ -445,7 +725,6 @@ static gboolean node_should_be_visible (GtkFileSystemModel *model, guint id, gboolean filtered_out) { FileModelNode *node = get_node (model, id); - gboolean result; if (node->info == NULL) return FALSE; @@ -479,9 +758,52 @@ node_should_be_visible (GtkFileSystemModel *model, guint id, gboolean filtered_o return FALSE; } - result = !filtered_out; + return !filtered_out; +} - return result; +/* Shows or hides one committed node. Not used while merging. */ +static void +node_set_visible_and_filtered_out (GtkFileSystemModel *model, + guint id, + gboolean visible, + gboolean filtered_out) +{ + FileModelNode *node = get_node (model, id); + + g_assert (!MODEL_MERGING (model)); + + if (node->filtered_out != filtered_out) + { + node->filtered_out = filtered_out; + if (node->visible && visible) + emit_row_changed_for_node (model, id); + } + + if (node->visible == visible) + return; + + if (visible) + { + guint pos; + + pos = id == 0 ? 0 : + rows_find_order_pos (model, model->visible_order, + rows_first_file (model, model->visible_order), + node->order_pos, FALSE); + g_array_insert_val (model->visible_order, pos, id); + node->visible = TRUE; + visible_update_positions_from (model, pos); + emit_row_inserted_for_node (model, id); + } + else + { + guint row = node->visible_pos; + + g_array_remove_index (model->visible_order, row); + node->visible = FALSE; + visible_update_positions_from (model, row); + emit_row_deleted_for_row (model, row); + } } static void @@ -524,64 +846,23 @@ gtk_file_system_model_get_column_type (GtkTreeModel *tree_model, return model->column_types[i]; } -static int -compare_indices (gconstpointer key, gconstpointer _node) -{ - const FileModelNode *node = _node; - - return GPOINTER_TO_UINT (key) - node->row; -} - static gboolean gtk_file_system_model_iter_nth_child (GtkTreeModel *tree_model, - GtkTreeIter *iter, - GtkTreeIter *parent, - gint n) + GtkTreeIter *iter, + GtkTreeIter *parent, + gint n) { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model); - char *node; guint id; - guint row_to_find; g_return_val_if_fail (n >= 0, FALSE); if (parent != NULL) return FALSE; - row_to_find = n + 1; /* plus one as our node->row numbers are 1-based; see the "Structure" comment at the beginning */ - - if (model->n_nodes_valid > 0 && - get_node (model, model->n_nodes_valid - 1)->row >= row_to_find) - { - /* Fast path - the nodes are valid up to the sought one. - * - * First, find a node with the sought row number...*/ - - node = bsearch (GUINT_TO_POINTER (row_to_find), - model->files->data, - model->n_nodes_valid, - model->node_size, - compare_indices); - if (node == NULL) - return FALSE; - - /* ... Second, back up until we find the first visible node with that row number */ - - id = node_index (model, node); - while (!get_node (model, id)->visible) - id--; - - g_assert (get_node (model, id)->row == row_to_find); - } - else - { - /* Slow path - the nodes need to be validated up to the sought one */ - - node_validate_rows (model, G_MAXUINT, n); /* note that this is really "n", not row_to_find - see node_validate_rows() */ - id = model->n_nodes_valid - 1; - if (model->n_nodes_valid == 0 || get_node (model, id)->row != row_to_find) - return FALSE; - } + id = model_nth_visible (model, n); + if (id == G_MAXUINT) + return FALSE; ITER_INIT_FROM_INDEX (model, iter, id); return TRUE; @@ -616,9 +897,9 @@ gtk_file_system_model_get_path (GtkTreeModel *tree_model, static void gtk_file_system_model_get_value (GtkTreeModel *tree_model, - GtkTreeIter *iter, - gint column, - GValue *value) + GtkTreeIter *iter, + gint column, + GValue *value) { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model); const GValue *original; @@ -641,22 +922,26 @@ gtk_file_system_model_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter) { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model); - guint i; + FileModelNode *node; + guint next, id; g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE); - for (i = ITER_INDEX (iter) + 1; i < model->files->len; i++) - { - FileModelNode *node = get_node (model, i); + node = get_node (model, ITER_INDEX (iter)); - if (node->visible) - { - ITER_INIT_FROM_INDEX (model, iter, i); - return TRUE; - } - } + if (node->visible) + next = node_visible_row (model, node) + 1; + else if (ITER_INDEX (iter) != 0) + next = node_rows_before (model, node); + else + return FALSE; - return FALSE; + id = model_nth_visible (model, next); + if (id == G_MAXUINT) + return FALSE; + + ITER_INIT_FROM_INDEX (model, iter, id); + return TRUE; } static gboolean @@ -683,7 +968,7 @@ gtk_file_system_model_iter_n_children (GtkTreeModel *tree_model, if (iter) return 0; - return node_get_tree_row (model, model->files->len - 1) + 1; + return model_n_visible (model); } static gboolean @@ -727,7 +1012,7 @@ gtk_file_system_model_iface_init (GtkTreeModelIface *iface) iface->unref_node = gtk_file_system_model_unref_node; } -/*** GtkTreeSortable ***/ +/*** Sorting ***/ typedef struct _SortData SortData; struct _SortData { @@ -737,15 +1022,12 @@ struct _SortData { int order; /* -1 to invert sort order or 1 to keep it */ }; -/* returns FALSE if no sort necessary */ +/* returns FALSE if the model is not sorted */ static gboolean sort_data_init (SortData *data, GtkFileSystemModel *model) { GtkTreeDataSortHeader *header; - if (model->files->len <= 2) - return FALSE; - switch (model->sort_column_id) { case GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID: @@ -771,83 +1053,774 @@ sort_data_init (SortData *data, GtkFileSystemModel *model) } static int -compare_array_element (gconstpointer a, gconstpointer b, gpointer user_data) +compare_ids (SortData *data, + guint ida, + guint idb) { - SortData *data = user_data; GtkTreeIter itera, iterb; - ITER_INIT_FROM_INDEX (data->model, &itera, node_index (data->model, a)); - ITER_INIT_FROM_INDEX (data->model, &iterb, node_index (data->model, b)); + ITER_INIT_FROM_INDEX (data->model, &itera, ida); + ITER_INIT_FROM_INDEX (data->model, &iterb, idb); + return data->func (GTK_TREE_MODEL (data->model), &itera, &iterb, data->data) * data->order; } +static gboolean +deadline_passed (gint64 deadline, + guint *counter) +{ + return (++(*counter) % MODEL_CLOCK_GRANULARITY) == 0 && + g_get_monotonic_time () >= deadline; +} + +/* Rebuilds the rows from model->order and announces the new order. */ static void -gtk_file_system_model_sort (GtkFileSystemModel *model) +visible_order_rebuild (GtkFileSystemModel *model) +{ + guint n_rows = model->visible_order->len; + gboolean changed = FALSE; + int *new_order; + guint row, i; + + if (n_rows == 0) + return; + + new_order = g_new (int, n_rows); + row = rows_first_file (model, model->visible_order); + if (row == 1) + new_order[0] = 0; + + for (i = 0; i < model->committed; i++) + { + guint id = g_array_index (model->order, guint, i); + FileModelNode *node = get_node (model, id); + + if (!node->visible) + continue; + + new_order[row] = node->visible_pos; + changed |= node->visible_pos != row; + g_array_index (model->visible_order, guint, row) = id; + node->visible_pos = row++; + } + + g_assert (row == n_rows); + + if (changed) + { + GtkTreePath *path = gtk_tree_path_new (); + gtk_tree_model_rows_reordered (GTK_TREE_MODEL (model), path, NULL, new_order); + gtk_tree_path_free (path); + } + + g_free (new_order); +} + +/* Bottom-up merge sort of model->sort_buf, resumable between slices. */ +static void +sort_prepare_merge (GtkFileSystemModel *model) +{ + guint n = model->sort_buf->len; + + model->sort_mid = MIN (model->sort_left + model->sort_width, n); + model->sort_right = MIN (model->sort_left + 2 * model->sort_width, n); + model->sort_i = model->sort_left; + model->sort_j = model->sort_mid; + model->sort_k = model->sort_left; +} + +static void gtk_file_system_model_sort_done (GtkFileSystemModel *model); + +/* Starts sorting @ids (taking ownership); see gtk_file_system_model_sort_done() */ +static void +gtk_file_system_model_sort_start (GtkFileSystemModel *model, + GArray *ids, + guint purpose) { SortData data; - if (model->frozen) + model->sort_buf = ids; + model->sort_purpose = purpose; + + if (ids->len <= 1 || !sort_data_init (&data, model)) { - model->sort_on_thaw = TRUE; + gtk_file_system_model_sort_done (model); return; } - if (sort_data_init (&data, model)) + model->sort_scratch = g_array_sized_new (FALSE, FALSE, sizeof (guint), ids->len); + g_array_set_size (model->sort_scratch, ids->len); + model->sort_width = 1; + model->sort_left = 0; + sort_prepare_merge (model); + model->phase = PHASE_SORT; +} + +/* Returns TRUE when the sort is done. */ +static gboolean +gtk_file_system_model_sort_step (GtkFileSystemModel *model, + gint64 deadline) +{ + GArray *buf = model->sort_buf; + guint n = buf->len; + guint processed = 0; + SortData data; + + if (!sort_data_init (&data, model)) { - GtkTreePath *path; - guint i; - guint r, n_visible_rows; - - node_validate_rows (model, G_MAXUINT, G_MAXUINT); - n_visible_rows = node_get_tree_row (model, model->files->len - 1) + 1; - model->n_nodes_valid = 0; - g_hash_table_remove_all (model->file_lookup); - _gtk_sort_array (get_node (model, 1), /* start at index 1; don't sort the editable row */ - model->files->len - 1, - model->node_size, - compare_array_element, - &data); - g_assert (model->n_nodes_valid == 0); - g_assert (g_hash_table_size (model->file_lookup) == 0); - if (n_visible_rows) - { - int *new_order = g_new (int, n_visible_rows); - - r = 0; - for (i = 0; i < model->files->len; i++) - { - FileModelNode *node = get_node (model, i); - if (!node->visible) - { - node->row = r; - continue; - } - - new_order[r] = node->row - 1; - r++; - node->row = r; - } - g_assert (r == n_visible_rows); - path = gtk_tree_path_new (); - gtk_tree_model_rows_reordered (GTK_TREE_MODEL (model), - path, - NULL, - new_order); - gtk_tree_path_free (path); - g_free (new_order); - } + gtk_file_system_model_sort_done (model); + return TRUE; } - model->sort_on_thaw = FALSE; + while (TRUE) + { + while (model->sort_k < model->sort_right) + { + guint id; + + if (model->sort_i < model->sort_mid && + (model->sort_j >= model->sort_right || + compare_ids (&data, + g_array_index (buf, guint, model->sort_i), + g_array_index (buf, guint, model->sort_j)) <= 0)) + id = g_array_index (buf, guint, model->sort_i++); + else + id = g_array_index (buf, guint, model->sort_j++); + + g_array_index (model->sort_scratch, guint, model->sort_k++) = id; + + if (deadline_passed (deadline, &processed)) + return FALSE; + } + + model->sort_left = model->sort_right; + if (model->sort_left < n) + { + sort_prepare_merge (model); + continue; + } + + /* Pass complete: the scratch buffer holds the result. */ + model->sort_buf = model->sort_scratch; + model->sort_scratch = buf; + buf = model->sort_buf; + + if (model->sort_width >= n - n / 2) + break; + + model->sort_width *= 2; + model->sort_left = 0; + sort_prepare_merge (model); + } + + gtk_file_system_model_sort_done (model); + return TRUE; } static void -gtk_file_system_model_sort_node (GtkFileSystemModel *model, guint node) +gtk_file_system_model_sort_abort (GtkFileSystemModel *model) { - /* FIXME: improve */ - gtk_file_system_model_sort (model); + g_clear_pointer (&model->sort_buf, g_array_unref); + g_clear_pointer (&model->sort_scratch, g_array_unref); + model->phase = PHASE_IDLE; } +/* Puts the sorted committed nodes in place. */ +static void +gtk_file_system_model_resort_apply (GtkFileSystemModel *model) +{ + g_assert (model->sort_buf->len == model->committed); + + memcpy (model->order->data, model->sort_buf->data, model->committed * sizeof (guint)); + order_update_positions (model, 0, model->committed); + visible_order_rebuild (model); +} + +/* Moves a committed node whose information changed to its new place. */ +static void +node_reposition (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + guint old_pos = node->order_pos; + guint lo, hi; + SortData data; + + if (model->committed <= 1 || !sort_data_init (&data, model)) + return; + + /* Usually the change did not affect the order. */ + if ((old_pos == 0 || + compare_ids (&data, g_array_index (model->order, guint, old_pos - 1), id) <= 0) && + (old_pos + 1 >= model->committed || + compare_ids (&data, id, g_array_index (model->order, guint, old_pos + 1)) <= 0)) + return; + + g_array_remove_index (model->order, old_pos); + + lo = 0; + hi = model->committed - 1; + while (lo < hi) + { + guint mid = lo + (hi - lo) / 2; + + if (compare_ids (&data, id, g_array_index (model->order, guint, mid)) < 0) + hi = mid; + else + lo = mid + 1; + } + + g_array_insert_val (model->order, lo, id); + order_update_positions (model, MIN (lo, old_pos), MAX (lo, old_pos) + 1); + + if (node->visible) + visible_order_rebuild (model); +} + +/*** Commits ***/ + +static void +gtk_file_system_model_merge_init (GtkFileSystemModel *model) +{ + FileModelNode *editable = get_node (model, 0); + + model->merge_tail = model->sort_buf; + model->sort_buf = NULL; + g_clear_pointer (&model->sort_scratch, g_array_unref); + + model->merge_order = g_array_sized_new (FALSE, FALSE, sizeof (guint), model->order->len); + model->merge_vis = g_array_sized_new (FALSE, FALSE, sizeof (guint), + model->visible_order->len + model->merge_tail->len); + model->merge_oi = 0; + model->merge_ti = 0; + model->merge_ovi = 0; + model->merge_end = model->committed + model->merge_tail->len; + model->merge_epoch = !model->merge_epoch; + model->merge_refilter = model->refilter_pending; + model->refilter_pending = FALSE; + model->phase = PHASE_MERGE; + + /* The editable row, if any, stays first. */ + if (editable->visible) + { + guint id = 0; + + g_array_append_val (model->merge_vis, id); + editable->merged_epoch = model->merge_epoch; + model->merge_ovi = 1; + } +} + +static void +gtk_file_system_model_sort_done (GtkFileSystemModel *model) +{ + g_clear_pointer (&model->sort_scratch, g_array_unref); + model->phase = PHASE_IDLE; + + if (model->sort_purpose == SORT_FOR_COMMIT) + gtk_file_system_model_merge_init (model); + else + { + gtk_file_system_model_resort_apply (model); + g_clear_pointer (&model->sort_buf, g_array_unref); + } +} + +static void +gtk_file_system_model_start_commit (GtkFileSystemModel *model) +{ + guint n = model->order->len - model->committed; + GArray *tail; + + tail = g_array_sized_new (FALSE, FALSE, sizeof (guint), n); + g_array_append_vals (tail, &g_array_index (model->order, guint, model->committed), n); + + gtk_file_system_model_sort_start (model, tail, SORT_FOR_COMMIT); +} + +static void +merge_announce (GtkFileSystemModel *model, + guint id, + gboolean inserted) +{ + GtkTreePath *path; + GtkTreeIter iter; + + path = gtk_tree_path_new_from_indices (get_node (model, id)->visible_pos, -1); + ITER_INIT_FROM_INDEX (model, &iter, id); + + model->in_merge_step = TRUE; + if (inserted) + gtk_tree_model_row_inserted (GTK_TREE_MODEL (model), path, &iter); + else + gtk_tree_model_row_changed (GTK_TREE_MODEL (model), path, &iter); + model->in_merge_step = FALSE; + + gtk_tree_path_free (path); +} + +/* Takes the next committed node: keeps it, or with merge_refilter, shows, + * hides or updates it according to the current filter. */ +static void +merge_old_node (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + gboolean was_visible = node->visible; + gboolean was_filtered_out = node->filtered_out; + gboolean visible = was_visible; + + if (was_visible) + { + g_assert (g_array_index (model->visible_order, guint, model->merge_ovi) == id); + model->merge_ovi++; + } + + if (model->merge_refilter) + { + node->filtered_out = node_should_be_filtered_out (model, id); + visible = node_should_be_visible (model, id, node->filtered_out); + } + + if (visible) + { + g_array_append_val (model->merge_vis, id); + node->visible_pos = model->merge_vis->len - 1; + node->visible = TRUE; + + if (!was_visible) + merge_announce (model, id, TRUE); + else if (was_filtered_out != node->filtered_out) + merge_announce (model, id, FALSE); + } + else if (was_visible) + { + node->visible = FALSE; + + model->in_merge_step = TRUE; + emit_row_deleted_for_row (model, model->merge_vis->len); + model->in_merge_step = FALSE; + } +} + +/* Merges the sorted tail into the committed nodes, announcing each new + * row at its final position. Returns TRUE when done. */ +static gboolean +gtk_file_system_model_merge_step (GtkFileSystemModel *model, + gint64 deadline) +{ + guint processed = 0; + gboolean have_sort; + SortData data; + guint i; + + have_sort = sort_data_init (&data, model); + + while (model->merge_oi < model->committed || model->merge_ti < model->merge_tail->len) + { + gboolean from_tail; + FileModelNode *node; + guint id; + + if (model->merge_ti >= model->merge_tail->len) + from_tail = FALSE; + else if (model->merge_oi >= model->committed || !have_sort) + from_tail = model->merge_oi >= model->committed; + else + from_tail = compare_ids (&data, + g_array_index (model->merge_tail, guint, model->merge_ti), + g_array_index (model->order, guint, model->merge_oi)) < 0; + + id = from_tail ? g_array_index (model->merge_tail, guint, model->merge_ti++) + : g_array_index (model->order, guint, model->merge_oi++); + node = get_node (model, id); + + g_array_append_val (model->merge_order, id); + node->order_pos = model->merge_order->len - 1; + node->merged_epoch = model->merge_epoch; + + if (from_tail) + { + node->uncommitted = FALSE; + node->filtered_out = node_should_be_filtered_out (model, id); + if (node_should_be_visible (model, id, node->filtered_out)) + { + g_array_append_val (model->merge_vis, id); + node->visible_pos = model->merge_vis->len - 1; + node->visible = TRUE; + merge_announce (model, id, TRUE); + } + } + else + merge_old_node (model, id); + + if (deadline_passed (deadline, &processed)) + return FALSE; + } + + /* Nodes added during the commit stay in the tail, at the same positions. */ + for (i = model->merge_end; i < model->order->len; i++) + g_array_append_val (model->merge_order, g_array_index (model->order, guint, i)); + + g_array_unref (model->order); + model->order = model->merge_order; + model->merge_order = NULL; + + g_array_unref (model->visible_order); + model->visible_order = model->merge_vis; + model->merge_vis = NULL; + + if (model->merge_tail->len > 0) + { + model->next_commit_time = g_get_monotonic_time () + model->commit_interval; + model->commit_interval = MIN (model->commit_interval * 2, MODEL_MAX_COMMIT_INTERVAL_US); + } + + g_clear_pointer (&model->merge_tail, g_array_unref); + model->committed = model->merge_end; + model->phase = PHASE_IDLE; + + return TRUE; +} + +/* Finishes a commit in progress right away, for operations that need the + * rows in one piece. */ +static void +gtk_file_system_model_complete_merge (GtkFileSystemModel *model) +{ + g_return_if_fail (!model->in_merge_step); + + if (MODEL_MERGING (model)) + gtk_file_system_model_merge_step (model, G_MAXINT64); +} + +static gboolean +gtk_file_system_model_commit_due (GtkFileSystemModel *model) +{ + if (model->refilter_pending) + return TRUE; + + if (model->order->len == model->committed) + return FALSE; + + if (model->directory_loading && + !(model->enumeration_done && g_queue_is_empty (&model->pending_infos))) + return g_get_monotonic_time () >= model->next_commit_time; + + return TRUE; +} + +static gboolean +gtk_file_system_model_commit_timeout (gpointer data) +{ + GtkFileSystemModel *model = data; + + model->commit_timer = 0; + gtk_file_system_model_schedule_work (model); + + return FALSE; +} + +/*** Per node changes ***/ + +static void +node_queue (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + + if (!node->queued) + { + node->queued = TRUE; + g_queue_push_tail (&model->node_queue, GUINT_TO_POINTER (id)); + } + + gtk_file_system_model_schedule_work (model); +} + +static void +node_remove (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + gboolean was_visible = node->visible; + guint row = node->visible_pos; + guint pos = node->order_pos; + + if (was_visible) + { + g_array_remove_index (model->visible_order, row); + visible_update_positions_from (model, row); + } + + g_array_remove_index (model->order, pos); + if (pos < model->committed) + model->committed--; + order_update_positions (model, pos, model->order->len); + + g_hash_table_remove (model->file_lookup, node->file); + node_retire_slot (model, id); + + if (was_visible) + emit_row_deleted_for_row (model, row); +} + +/* Applies the queued per node changes. Returns TRUE when done. */ +static gboolean +gtk_file_system_model_process_node_queue (GtkFileSystemModel *model, + gint64 deadline) +{ + guint processed = 0; + + while (!g_queue_is_empty (&model->node_queue)) + { + guint id = GPOINTER_TO_UINT (g_queue_pop_head (&model->node_queue)); + FileModelNode *node = get_node (model, id); + + node->queued = FALSE; + + if (node->want_remove) + node_remove (model, id); + else if (!node->uncommitted) + { + /* Nodes in the tail are sorted and filtered when committed. */ + if (node->want_changed && node->visible) + emit_row_changed_for_node (model, id); + if (node->want_refilter) + node_compute_visibility_and_filters (model, id); + if (node->want_reposition) + node_reposition (model, id); + } + + node->want_changed = FALSE; + node->want_refilter = FALSE; + node->want_reposition = FALSE; + + if (deadline_passed (deadline, &processed)) + return FALSE; + } + + return TRUE; +} + +/*** Loading ***/ + +/* Adds the entries from the enumerator until @deadline. Returns TRUE when + * all are added. */ +static gboolean +gtk_file_system_model_drain (GtkFileSystemModel *model, + gint64 deadline) +{ + guint processed = 0; + + while (!g_queue_is_empty (&model->pending_infos)) + { + GFileInfo *info = g_queue_pop_head (&model->pending_infos); + const char *name; + + /* Keep the enumerator busy while the main thread works: on a slow + * share the next batch then arrives meanwhile. */ + if (g_queue_get_length (&model->pending_infos) < MODEL_READ_AHEAD) + gtk_file_system_model_request_next_files (model); + + name = g_file_info_get_name (info); + if (name != NULL) + { + GFile *file = g_file_get_child (model->dir, name); + + /* The monitor may have added it already, or reported that it + * was deleted after the enumerator read it. */ + if (model->deleted_files && g_hash_table_remove (model->deleted_files, file)) + ; + else if (node_get_for_file (model, file) == 0) + add_file (model, file, info); + g_object_unref (file); + } + + g_object_unref (info); + + if (deadline_passed (deadline, &processed)) + return FALSE; + } + + return TRUE; +} + +static void +gtk_file_system_model_finish_loading (GtkFileSystemModel *model) +{ + GError *error = model->load_error; + + model->load_error = NULL; + model->directory_loading = FALSE; + g_clear_pointer (&model->deleted_files, g_hash_table_destroy); + + g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error); + + if (error) + g_error_free (error); +} + +enum +{ + ROW_WORK_NONE, /* nothing to do now */ + ROW_WORK_DONE, /* did some; there may be more */ + ROW_WORK_INTERRUPTED /* stopped at the deadline */ +}; + +/* Does the next piece of work on the rows: continues a sort or merge, + * applies the queued per node changes, or starts a resort or a commit + * (with @commit_now, a commit of the files that came in so far even if it + * is not due yet). */ +static int +gtk_file_system_model_row_work (GtkFileSystemModel *model, + gint64 deadline, + gboolean commit_now) +{ + if (model->phase == PHASE_SORT) + return gtk_file_system_model_sort_step (model, deadline) ? ROW_WORK_DONE : ROW_WORK_INTERRUPTED; + + if (model->phase == PHASE_MERGE) + return gtk_file_system_model_merge_step (model, deadline) ? ROW_WORK_DONE : ROW_WORK_INTERRUPTED; + + if (!g_queue_is_empty (&model->node_queue)) + return gtk_file_system_model_process_node_queue (model, deadline) ? ROW_WORK_DONE : ROW_WORK_INTERRUPTED; + + if (model->resort_pending) + { + GArray *ids; + + model->resort_pending = FALSE; + ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), model->committed); + g_array_append_vals (ids, model->order->data, model->committed); + gtk_file_system_model_sort_start (model, ids, SORT_FOR_RESORT); + return ROW_WORK_DONE; + } + + if (commit_now ? (model->refilter_pending || model->order->len > model->committed) + : gtk_file_system_model_commit_due (model)) + { + gtk_file_system_model_start_commit (model); + return ROW_WORK_DONE; + } + + return ROW_WORK_NONE; +} + +/* Does the work of one slice. Returns TRUE if there is more to do now. */ +static gboolean +gtk_file_system_model_work_slice (GtkFileSystemModel *model) +{ + gint64 deadline = g_get_monotonic_time () + MODEL_SLICE_US; + + while (g_get_monotonic_time () < deadline) + { + if (!model->editing_hold) + { + int result = gtk_file_system_model_row_work (model, deadline, FALSE); + + if (result == ROW_WORK_INTERRUPTED) + return TRUE; + if (result == ROW_WORK_DONE) + continue; + } + + if (!g_queue_is_empty (&model->pending_infos)) + { + if (!gtk_file_system_model_drain (model, deadline)) + return TRUE; + continue; + } + + if (model->editing_hold || !model->directory_loading) + break; + + if (model->enumeration_done && model->order->len == model->committed) + { + /* Handlers may ask for more work, e.g. to show hidden files. */ + gtk_file_system_model_finish_loading (model); + continue; + } + + /* Waiting for the enumerator: show what came so far when it is due. */ + if (model->order->len > model->committed && model->commit_timer == 0) + { + gint64 delay = (model->next_commit_time - g_get_monotonic_time ()) / 1000; + + model->commit_timer = + gdk_threads_add_timeout_full (G_PRIORITY_DEFAULT_IDLE, + (guint) CLAMP (delay, 1, MODEL_MAX_COMMIT_INTERVAL_US / 1000), + gtk_file_system_model_commit_timeout, + model, NULL); + } + break; + } + + return g_get_monotonic_time () >= deadline; +} + +/* The single place where rows change (see the comment at the top). */ +static gboolean +gtk_file_system_model_work (gpointer data) +{ + GtkFileSystemModel *model = data; + gboolean more; + + /* Signal handlers may drop the last other reference. */ + g_object_ref (model); + + more = gtk_file_system_model_work_slice (model); + if (!more) + model->work_source = 0; + + g_object_unref (model); + + return more; +} + +static void +gtk_file_system_model_schedule_work (GtkFileSystemModel *model) +{ + if (model->work_source != 0) + return; + + /* Below redraws, so the view repaints between slices. */ + model->work_source = + gdk_threads_add_idle_full (G_PRIORITY_DEFAULT_IDLE, + gtk_file_system_model_work, + model, NULL); +} + +/* Sorting changes need the rows in one piece and no sort in progress. */ +static void +gtk_file_system_model_sort_changing (GtkFileSystemModel *model) +{ + gtk_file_system_model_complete_merge (model); + + if (model->phase == PHASE_SORT) + gtk_file_system_model_sort_abort (model); +} + +static void +gtk_file_system_model_resort (GtkFileSystemModel *model) +{ + model->resort_pending = TRUE; + gtk_file_system_model_schedule_work (model); +} + +static void +gtk_file_system_model_refilter_all (GtkFileSystemModel *model) +{ + /* Files in the tail are filtered when they are committed. */ + if (model->committed == 0 && !MODEL_MERGING (model)) + return; + + model->refilter_pending = TRUE; + gtk_file_system_model_schedule_work (model); +} + +/*** GtkTreeSortable ***/ + static gboolean gtk_file_system_model_get_sort_column_id (GtkTreeSortable *sortable, gint *sort_column_id, @@ -897,13 +1870,14 @@ gtk_file_system_model_set_sort_column_id (GtkTreeSortable *sortable, } } + gtk_file_system_model_sort_changing (model); model->sort_column_id = sort_column_id; model->sort_order = order; gtk_tree_sortable_sort_column_changed (sortable); - gtk_file_system_model_sort (model); + gtk_file_system_model_resort (model); } static void @@ -915,12 +1889,15 @@ gtk_file_system_model_set_sort_func (GtkTreeSortable *sortable, { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable); + if (model->sort_column_id == sort_column_id) + gtk_file_system_model_sort_changing (model); + model->sort_list = _gtk_tree_data_list_set_header (model->sort_list, sort_column_id, func, data, destroy); if (model->sort_column_id == sort_column_id) - gtk_file_system_model_sort (model); + gtk_file_system_model_resort (model); } static void @@ -931,6 +1908,9 @@ gtk_file_system_model_set_default_sort_func (GtkTreeSortable *sortable, { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable); + if (model->sort_column_id == GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID) + gtk_file_system_model_sort_changing (model); + if (model->default_sort_destroy) { GDestroyNotify d = model->default_sort_destroy; @@ -944,7 +1924,7 @@ gtk_file_system_model_set_default_sort_func (GtkTreeSortable *sortable, model->default_sort_destroy = destroy; if (model->sort_column_id == GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID) - gtk_file_system_model_sort (model); + gtk_file_system_model_resort (model); } static gboolean @@ -1015,16 +1995,6 @@ drag_source_iface_init (GtkTreeDragSourceIface *iface) /*** GtkFileSystemModel ***/ -/* Signal IDs */ -enum { - FINISHED_LOADING, - LAST_SIGNAL -}; - -static guint file_system_model_signals[LAST_SIGNAL] = { 0 }; - - - G_DEFINE_TYPE_WITH_CODE (GtkFileSystemModel, _gtk_file_system_model, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_MODEL, gtk_file_system_model_iface_init) @@ -1038,16 +2008,26 @@ gtk_file_system_model_dispose (GObject *object) { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (object); - if (model->dir_thaw_source) + if (model->work_source) { - g_source_remove (model->dir_thaw_source); - model->dir_thaw_source = 0; + g_source_remove (model->work_source); + model->work_source = 0; + } + + if (model->commit_timer) + { + g_source_remove (model->commit_timer); + model->commit_timer = 0; } g_cancellable_cancel (model->cancellable); if (model->dir_monitor) g_file_monitor_cancel (model->dir_monitor); + g_queue_foreach (&model->pending_infos, (GFunc) g_object_unref, NULL); + g_queue_clear (&model->pending_infos); + g_clear_object (&model->dir_enumerator); + G_OBJECT_CLASS (_gtk_file_system_model_parent_class)->dispose (object); } @@ -1058,21 +2038,21 @@ gtk_file_system_model_finalize (GObject *object) GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (object); guint i; - for (i = 0; i < model->files->len; i++) - { - int v; + for (i = 0; i < model->n_columns; i++) + if (model->value_pages[i]) + g_ptr_array_free (model->value_pages[i], TRUE); + g_free (model->value_pages); - FileModelNode *node = get_node (model, i); - if (node->file) - g_object_unref (node->file); - if (node->info) - g_object_unref (node->info); - - for (v = 0; v < model->n_columns; v++) - if (G_VALUE_TYPE (&node->values[v]) != G_TYPE_INVALID) - g_value_unset (&node->values[v]); - } g_array_free (model->files, TRUE); + g_array_free (model->order, TRUE); + g_array_free (model->visible_order, TRUE); + g_clear_pointer (&model->sort_buf, g_array_unref); + g_clear_pointer (&model->sort_scratch, g_array_unref); + g_clear_pointer (&model->merge_tail, g_array_unref); + g_clear_pointer (&model->merge_order, g_array_unref); + g_clear_pointer (&model->merge_vis, g_array_unref); + g_queue_clear (&model->node_queue); + g_clear_error (&model->load_error); g_object_unref (model->cancellable); g_free (model->attributes); @@ -1080,6 +2060,10 @@ gtk_file_system_model_finalize (GObject *object) g_object_unref (model->dir); if (model->dir_monitor) g_object_unref (model->dir_monitor); + if (model->monitor_queries) + g_hash_table_destroy (model->monitor_queries); + if (model->deleted_files) + g_hash_table_destroy (model->deleted_files); g_hash_table_destroy (model->file_lookup); if (model->filter) g_object_unref (model->filter); @@ -1133,93 +2117,104 @@ gtk_file_system_model_closed_enumerator (GObject *object, GAsyncResult *res, gpo g_file_enumerator_close_finish (G_FILE_ENUMERATOR (object), res, NULL); } -static gboolean -thaw_func (gpointer data) +static void +gtk_file_system_model_enumeration_done (GtkFileSystemModel *model, + const GError *error) { - GtkFileSystemModel *model = data; + model->enumeration_done = TRUE; + if (error) + model->load_error = g_error_copy (error); - thaw_updates (model); - model->dir_thaw_source = 0; + gtk_file_system_model_schedule_work (model); +} - return FALSE; +static void +gtk_file_system_model_request_next_files (GtkFileSystemModel *model) +{ + if (model->dir_enumerator == NULL || model->next_files_in_flight) + return; + + model->next_files_in_flight = TRUE; + g_file_enumerator_next_files_async (model->dir_enumerator, + FILES_PER_QUERY, + IO_PRIORITY, + model->cancellable, + gtk_file_system_model_got_files, + model); } static void gtk_file_system_model_got_files (GObject *object, GAsyncResult *res, gpointer data) { GFileEnumerator *enumerator = G_FILE_ENUMERATOR (object); - GtkFileSystemModel *model = data; + GtkFileSystemModel *model = data; /* only a valid pointer if not cancelled */ GList *walk, *files; GError *error = NULL; + files = g_file_enumerator_next_files_finish (enumerator, res, &error); + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + { + g_error_free (error); + return; + } + gdk_threads_enter (); - files = g_file_enumerator_next_files_finish (enumerator, res, &error); + model->next_files_in_flight = FALSE; if (files) { - if (model->dir_thaw_source == 0) - { - freeze_updates (model); - model->dir_thaw_source = gdk_threads_add_timeout_full (IO_PRIORITY + 1, - 50, - thaw_func, - model, - NULL); - } - for (walk = files; walk; walk = walk->next) - { - const char *name; - GFileInfo *info; - GFile *file; - - info = walk->data; - name = g_file_info_get_name (info); - if (name == NULL) - { - /* Shouldn't happen, but the APIs allow it */ - g_object_unref (info); - continue; - } - file = g_file_get_child (model->dir, name); - add_file (model, file, info); - g_object_unref (file); - g_object_unref (info); - } + g_queue_push_tail (&model->pending_infos, walk->data); g_list_free (files); - g_file_enumerator_next_files_async (enumerator, - g_file_is_native (model->dir) ? 50 * FILES_PER_QUERY : FILES_PER_QUERY, - IO_PRIORITY, - model->cancellable, - gtk_file_system_model_got_files, - model); + if (g_queue_get_length (&model->pending_infos) < MODEL_READ_AHEAD) + gtk_file_system_model_request_next_files (model); + + gtk_file_system_model_schedule_work (model); } else { - if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - { - g_file_enumerator_close_async (enumerator, - IO_PRIORITY, - model->cancellable, - gtk_file_system_model_closed_enumerator, - NULL); - if (model->dir_thaw_source != 0) - { - g_source_remove (model->dir_thaw_source); - model->dir_thaw_source = 0; - thaw_updates (model); - } + g_file_enumerator_close_async (enumerator, + IO_PRIORITY, + NULL, + gtk_file_system_model_closed_enumerator, + NULL); + g_clear_object (&model->dir_enumerator); - g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error); - } - - if (error) - g_error_free (error); + gtk_file_system_model_enumeration_done (model, error); } gdk_threads_leave (); + + if (error) + g_error_free (error); +} + +/* A file system query brought new information for @file. */ +static void +gtk_file_system_model_file_queried (GtkFileSystemModel *model, + GFile *file, + GFileInfo *info) +{ + guint id = node_get_for_file (model, file); + FileModelNode *node; + + if (id == 0) + { + add_file (model, file, info); + return; + } + + _gtk_file_system_model_update_file (model, file, info); + + /* The change may move the file or change whether it is shown; a file + * that was about to be removed came back. */ + node = get_node (model, id); + node->want_remove = FALSE; + node->want_reposition = TRUE; + node->want_refilter = TRUE; + node_queue (model, id); } static void @@ -1230,22 +2225,56 @@ gtk_file_system_model_query_done (GObject * object, GtkFileSystemModel *model = data; /* only a valid pointer if not cancelled */ GFile *file = G_FILE (object); GFileInfo *info; - guint id; info = g_file_query_info_finish (file, res, NULL); if (info == NULL) return; gdk_threads_enter (); - - _gtk_file_system_model_update_file (model, file, info); - - id = node_get_for_file (model, file); - gtk_file_system_model_sort_node (model, id); + gtk_file_system_model_file_queried (model, file, info); + gdk_threads_leave (); g_object_unref (info); +} + +typedef struct +{ + GtkFileSystemModel *model; /* only a valid pointer if not cancelled */ + guint serial; +} MonitorQuery; + +static void +gtk_file_system_model_monitor_query_done (GObject *object, + GAsyncResult *res, + gpointer data) +{ + MonitorQuery *query = data; + GtkFileSystemModel *model = query->model; + GFile *file = G_FILE (object); + GError *error = NULL; + GFileInfo *info; + + info = g_file_query_info_finish (file, res, &error); + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + goto out; + + gdk_threads_enter (); + + /* Only the latest query for a file counts; results can arrive out of + * order when a file changes quickly. */ + if (GPOINTER_TO_UINT (g_hash_table_lookup (model->monitor_queries, file)) == query->serial) + { + g_hash_table_remove (model->monitor_queries, file); + if (info) + gtk_file_system_model_file_queried (model, file, info); + } gdk_threads_leave (); + +out: + g_clear_error (&error); + g_clear_object (&info); + g_free (query); } static void @@ -1255,27 +2284,53 @@ gtk_file_system_model_monitor_change (GFileMonitor * monitor, GFileMonitorEvent type, GtkFileSystemModel *model) { + MonitorQuery *query; + switch (type) { case G_FILE_MONITOR_EVENT_CREATED: case G_FILE_MONITOR_EVENT_CHANGED: case G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED: /* We can treat all of these the same way */ + query = g_new (MonitorQuery, 1); + query->model = model; + query->serial = ++model->monitor_serial; + + gdk_threads_enter (); + if (model->deleted_files) + g_hash_table_remove (model->deleted_files, file); + if (model->monitor_queries == NULL) + model->monitor_queries = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, + g_object_unref, NULL); + g_hash_table_replace (model->monitor_queries, g_object_ref (file), + GUINT_TO_POINTER (query->serial)); + gdk_threads_leave (); + g_file_query_info_async (file, model->attributes, G_FILE_QUERY_INFO_NONE, IO_PRIORITY, model->cancellable, - gtk_file_system_model_query_done, - model); + gtk_file_system_model_monitor_query_done, + query); break; case G_FILE_MONITOR_EVENT_DELETED: gdk_threads_enter (); + if (model->monitor_queries) + g_hash_table_remove (model->monitor_queries, file); remove_file (model, file); + if (model->directory_loading) + { + /* The enumerator may have read it already and deliver it + * later, also after the node was removed; drop it then. */ + if (model->deleted_files == NULL) + model->deleted_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, + g_object_unref, NULL); + g_hash_table_add (model->deleted_files, g_object_ref (file)); + } gdk_threads_leave (); break; case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT: - /* FIXME: use freeze/thaw with this somehow? */ case G_FILE_MONITOR_EVENT_PRE_UNMOUNT: case G_FILE_MONITOR_EVENT_UNMOUNTED: default: @@ -1287,39 +2342,38 @@ gtk_file_system_model_monitor_change (GFileMonitor * monitor, static void gtk_file_system_model_got_enumerator (GObject *dir, GAsyncResult *res, gpointer data) { - GtkFileSystemModel *model = data; + GtkFileSystemModel *model = data; /* only a valid pointer if not cancelled */ GFileEnumerator *enumerator; GError *error = NULL; + enumerator = g_file_enumerate_children_finish (G_FILE (dir), res, &error); + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + { + g_error_free (error); + return; + } + gdk_threads_enter (); - enumerator = g_file_enumerate_children_finish (G_FILE (dir), res, &error); if (enumerator == NULL) { - if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - { - g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error); - g_error_free (error); - } + gtk_file_system_model_enumeration_done (model, error); + g_error_free (error); } else { - g_file_enumerator_next_files_async (enumerator, - g_file_is_native (model->dir) ? 50 * FILES_PER_QUERY : FILES_PER_QUERY, - IO_PRIORITY, - model->cancellable, - gtk_file_system_model_got_files, - model); - g_object_unref (enumerator); + model->dir_enumerator = enumerator; + gtk_file_system_model_request_next_files (model); + model->dir_monitor = g_file_monitor_directory (model->dir, - G_FILE_MONITOR_NONE, - model->cancellable, - NULL); /* we don't mind if directory monitoring isn't supported, so the GError is NULL here */ + G_FILE_MONITOR_NONE, + model->cancellable, + NULL); /* we don't mind if directory monitoring isn't supported, so the GError is NULL here */ if (model->dir_monitor) g_signal_connect (model->dir_monitor, - "changed", - G_CALLBACK (gtk_file_system_model_monitor_change), - model); + "changed", + G_CALLBACK (gtk_file_system_model_monitor_change), + model); } gdk_threads_leave (); @@ -1337,15 +2391,14 @@ gtk_file_system_model_set_n_columns (GtkFileSystemModel *model, model->n_columns = n_columns; model->column_types = g_slice_alloc (sizeof (GType) * n_columns); - - model->node_size = sizeof (FileModelNode) + sizeof (GValue) * (n_columns - 1); /* minus 1 because FileModelNode.values[] has a default size of 1 */ + model->value_pages = g_new0 (GPtrArray *, n_columns); for (i = 0; i < (guint) n_columns; i++) { GType type = va_arg (args, GType); if (! _gtk_tree_data_list_check_type (type)) { - g_error ("%s: type %s cannot be a column type for GtkFileSystemModel\n", G_STRLOC, g_type_name (type)); + g_error ("%s: type %s cannot be a column type for GtkFileSystemModel\n", G_STRLOC, g_type_name (type)); return; /* not reached */ } @@ -1354,10 +2407,14 @@ gtk_file_system_model_set_n_columns (GtkFileSystemModel *model, model->sort_list = _gtk_tree_data_list_header_new (n_columns, model->column_types); - model->files = g_array_sized_new (FALSE, FALSE, model->node_size, FILES_PER_QUERY); + model->files = g_array_sized_new (FALSE, TRUE, sizeof (FileModelNode), FILES_PER_QUERY); + g_array_set_clear_func (model->files, file_model_node_clear); + model->order = g_array_sized_new (FALSE, FALSE, sizeof (guint), FILES_PER_QUERY); + model->visible_order = g_array_sized_new (FALSE, FALSE, sizeof (guint), FILES_PER_QUERY); + /* add editable node at start */ g_array_set_size (model->files, 1); - memset (get_node (model, 0), 0, model->node_size); + get_node (model, 0)->generation = 1; } static void @@ -1369,6 +2426,9 @@ gtk_file_system_model_set_directory (GtkFileSystemModel *model, model->dir = g_object_ref (dir); model->attributes = g_strdup (attributes); + model->directory_loading = TRUE; + model->next_commit_time = g_get_monotonic_time () + MODEL_FIRST_COMMIT_US; + model->commit_interval = MODEL_COMMIT_INTERVAL_US; g_file_enumerate_children_async (model->dir, attributes, @@ -1445,6 +2505,8 @@ _gtk_file_system_model_new (GtkFileSystemModelGetValue get_func, * it will also monitor the drectory and update the model's * contents to reflect changes, if the @directory supports monitoring. * + * Files show up as rows while the directory is still being read. + * * Return value: the newly created #GtkFileSystemModel **/ GtkFileSystemModel * @@ -1471,27 +2533,6 @@ _gtk_file_system_model_new_for_directory (GFile * dir, return model; } -static void -gtk_file_system_model_refilter_all (GtkFileSystemModel *model) -{ - guint i; - - if (model->frozen) - { - model->filter_on_thaw = TRUE; - return; - } - - freeze_updates (model); - - /* start at index 1, don't change the editable */ - for (i = 1; i < model->files->len; i++) - node_compute_visibility_and_filters (model, i); - - model->filter_on_thaw = FALSE; - thaw_updates (model); -} - /** * _gtk_file_system_model_set_show_hidden: * @model: a #GtkFileSystemModel @@ -1626,6 +2667,7 @@ _gtk_file_system_model_iter_is_visible (GtkFileSystemModel *model, g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), FALSE); g_return_val_if_fail (iter != NULL, FALSE); + g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE); node = get_node (model, ITER_INDEX (iter)); return node->visible; @@ -1652,6 +2694,7 @@ _gtk_file_system_model_iter_is_filtered_out (GtkFileSystemModel *model, g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), FALSE); g_return_val_if_fail (iter != NULL, FALSE); + g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE); node = get_node (model, ITER_INDEX (iter)); return node->filtered_out; @@ -1682,6 +2725,7 @@ _gtk_file_system_model_get_info (GtkFileSystemModel *model, g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL); g_return_val_if_fail (iter != NULL, NULL); + g_return_val_if_fail (ITER_IS_VALID (model, iter), NULL); node = get_node (model, ITER_INDEX (iter)); g_assert (node->info == NULL || G_IS_FILE_INFO (node->info)); @@ -1707,6 +2751,8 @@ _gtk_file_system_model_get_file (GtkFileSystemModel *model, FileModelNode *node; g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL); + g_return_val_if_fail (iter != NULL, NULL); + g_return_val_if_fail (ITER_IS_VALID (model, iter), NULL); node = get_node (model, ITER_INDEX (iter)); return node->file; @@ -1735,59 +2781,35 @@ _gtk_file_system_model_get_value (GtkFileSystemModel *model, int column) { FileModelNode *node; + GValue *value; + guint id; g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL); g_return_val_if_fail (column >= 0 && (guint) column < model->n_columns, NULL); + g_return_val_if_fail (ITER_IS_VALID (model, iter), NULL); - node = get_node (model, ITER_INDEX (iter)); + id = ITER_INDEX (iter); + node = get_node (model, id); + value = value_cache_slot (model, id, column, TRUE); - if (!G_VALUE_TYPE (&node->values[column])) + if (G_VALUE_TYPE (value) == G_TYPE_INVALID) { - g_value_init (&node->values[column], model->column_types[column]); - if (!model->get_func (model, - node->file, - node->info, - column, - &node->values[column], - model->get_data)) + g_value_init (value, model->column_types[column]); + if (!model->get_func (model, node->file, node->info, column, value, model->get_data)) { - g_value_unset (&node->values[column]); + g_value_unset (value); return NULL; } } - return &node->values[column]; + return value; } static guint node_get_for_file (GtkFileSystemModel *model, - GFile * file) + GFile * file) { - guint i; - - i = GPOINTER_TO_UINT (g_hash_table_lookup (model->file_lookup, file)); - if (i != 0) - return i; - - /* Node 0 is the editable row and has no associated file or entry in the table, so we start counting from 1. - * - * The invariant here is that the files in model->files[n] for n < g_hash_table_size (model->file_lookup) - * are already added to the hash table. The table can get cleared when we re-sort; this loop merely rebuilds - * our (file -> index) mapping on demand. - * - * If we exit the loop, the next pending batch of mappings will be resolved when this function gets called again - * with another file that is not yet in the mapping. - */ - for (i = g_hash_table_size (model->file_lookup) + 1; i < model->files->len; i++) - { - FileModelNode *node = get_node (model, i); - - g_hash_table_insert (model->file_lookup, node->file, GUINT_TO_POINTER (i)); - if (g_file_equal (node->file, file)) - return i; - } - - return 0; + return GPOINTER_TO_UINT (g_hash_table_lookup (model->file_lookup, file)); } /** @@ -1824,41 +2846,14 @@ _gtk_file_system_model_get_iter_for_file (GtkFileSystemModel *model, return TRUE; } -/* When an element is added or removed to the model->files array, we need to - * update the model->file_lookup mappings of (node, index), as the indexes - * change. This function adds the specified increment to the index in that pair - * if the index is equal or after the specified id. We use this to slide the - * mappings up or down when a node is added or removed, respectively. - */ -static void -adjust_file_lookup (GtkFileSystemModel *model, guint id, int increment) -{ - GHashTableIter iter; - gpointer key; - gpointer value; - - g_hash_table_iter_init (&iter, model->file_lookup); - - while (g_hash_table_iter_next (&iter, &key, &value)) - { - guint index = GPOINTER_TO_UINT (value); - - if (index >= id) - { - index += increment; - g_hash_table_iter_replace (&iter, GUINT_TO_POINTER (index)); - } - } -} - /** * add_file: * @model: the model * @file: the file to add * @info: the information to associate with the file * - * Adds the given @file with its associated @info to the @model. - * If the model is frozen, the file will only show up after it is thawn. + * Adds the given @file with its associated @info to the @model. The file + * becomes a row (if it passes the filters) with the next commit. **/ static void add_file (GtkFileSystemModel *model, @@ -1866,24 +2861,23 @@ add_file (GtkFileSystemModel *model, GFileInfo *info) { FileModelNode *node; + guint id; g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (G_IS_FILE (file)); g_return_if_fail (G_IS_FILE_INFO (info)); - node = g_slice_alloc0 (model->node_size); + id = node_allocate_slot (model); + node = get_node (model, id); node->file = g_object_ref (file); - if (info) - node->info = g_object_ref (info); - node->frozen_add = model->frozen ? TRUE : FALSE; + node->info = g_object_ref (info); + node->uncommitted = TRUE; + node->order_pos = model->order->len; + g_array_append_val (model->order, id); - g_array_append_vals (model->files, node, 1); - g_slice_free1 (model->node_size, node); + g_hash_table_insert (model->file_lookup, node->file, GUINT_TO_POINTER (id)); - if (!model->frozen) - node_compute_visibility_and_filters (model, model->files->len -1); - - gtk_file_system_model_sort_node (model, model->files->len -1); + gtk_file_system_model_schedule_work (model); } /** @@ -1892,17 +2886,14 @@ add_file (GtkFileSystemModel *model, * @file: file to remove from the model. The file must have been * added to the model previously * - * Removes the given file from the model. If the file is not part of - * @model, this function does nothing. + * Removes the given file from the model, with the next per node changes. + * If the file is not part of @model, this function does nothing. **/ static void remove_file (GtkFileSystemModel *model, GFile *file) { - FileModelNode *node; - gboolean was_visible; guint id; - guint row; g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (G_IS_FILE (file)); @@ -1911,25 +2902,8 @@ remove_file (GtkFileSystemModel *model, if (id == 0) return; - node = get_node (model, id); - was_visible = node->visible; - row = node_get_tree_row (model, id); - - node_invalidate_index (model, id); - - g_hash_table_remove (model->file_lookup, file); - g_object_unref (node->file); - adjust_file_lookup (model, id, -1); - - if (node->info) - g_object_unref (node->info); - - g_array_remove_index (model->files, id); - - /* We don't need to resort, as removing a row doesn't change the sorting order of the other rows */ - - if (was_visible) - emit_row_deleted_for_row (model, row); + get_node (model, id)->want_remove = TRUE; + node_queue (model, id); } /** @@ -1948,8 +2922,8 @@ _gtk_file_system_model_update_file (GtkFileSystemModel *model, GFileInfo *info) { FileModelNode *node; - guint i, id; GFileInfo *old_info; + guint id; g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (G_IS_FILE (file)); @@ -1959,22 +2933,17 @@ _gtk_file_system_model_update_file (GtkFileSystemModel *model, if (id == 0) { add_file (model, file, info); - id = node_get_for_file (model, file); + return; } node = get_node (model, id); - old_info = node->info; node->info = g_object_ref (info); if (old_info) g_object_unref (old_info); - for (i = 0; i < model->n_columns; i++) - { - if (G_VALUE_TYPE (&node->values[i])) - g_value_unset (&node->values[i]); - } + value_cache_clear_node (model, id); if (node->visible) emit_row_changed_for_node (model, id); @@ -2010,63 +2979,6 @@ _gtk_file_system_model_set_filter (GtkFileSystemModel *model, gtk_file_system_model_refilter_all (model); } -/** - * freeze_updates: - * @model: a #GtkFileSystemModel - * - * Freezes most updates on the model, so that performing multiple operations on - * the files in the model do not cause any events. Use thaw_updates() to resume - * proper operations. It is fine to call this function multiple times as long as - * freeze and thaw calls are balanced. - **/ -static void -freeze_updates (GtkFileSystemModel *model) -{ - g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); - - model->frozen++; -} - -/** - * thaw_updates: - * @model: a #GtkFileSystemModel - * - * Undoes the effect of a previous call to freeze_updates() - **/ -static void -thaw_updates (GtkFileSystemModel *model) -{ - gboolean stuff_added; - - g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); - g_return_if_fail (model->frozen > 0); - - model->frozen--; - if (model->frozen > 0) - return; - - stuff_added = get_node (model, model->files->len - 1)->frozen_add; - - if (model->filter_on_thaw) - gtk_file_system_model_refilter_all (model); - if (model->sort_on_thaw) - gtk_file_system_model_sort (model); - if (stuff_added) - { - guint i; - - for (i = 0; i < model->files->len; i++) - { - FileModelNode *node = get_node (model, i); - - if (!node->frozen_add) - continue; - node->frozen_add = FALSE; - node_compute_visibility_and_filters (model, i); - } - } -} - /** * _gtk_file_system_model_clear_cache: * @model: a #GtkFileSystemModel @@ -2080,16 +2992,15 @@ thaw_updates (GtkFileSystemModel *model) **/ void _gtk_file_system_model_clear_cache (GtkFileSystemModel *model, - int column) + int column) { - guint i; - int start, end; - gboolean changed; + guint8 *changed; + guint start, end, c, i, n; g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); - g_return_if_fail (column >= -1 && (guint) column < model->n_columns); + g_return_if_fail (column >= -1 && column < (int) model->n_columns); - if (column > -1) + if (column >= 0) { start = column; end = column + 1; @@ -2100,65 +3011,88 @@ _gtk_file_system_model_clear_cache (GtkFileSystemModel *model, end = model->n_columns; } - for (i = 0; i < model->files->len; i++) + changed = g_new0 (guint8, model->files->len); + + for (c = start; c < end; c++) { - FileModelNode *node = get_node (model, i); + GPtrArray *pages = model->value_pages[c]; + guint page_index; - changed = FALSE; - for (column = start; column < end; column++) - { - if (!G_VALUE_TYPE (&node->values[column])) - continue; - - g_value_unset (&node->values[column]); - changed = TRUE; - } - - if (changed && node->visible) - emit_row_changed_for_node (model, i); - } - - /* FIXME: resort? */ -} - -void -_gtk_file_system_model_clear_cache_for_iter (GtkFileSystemModel *model, - GtkTreeIter *iter, - int column) -{ - FileModelNode *node; - int start, end; - gboolean changed = FALSE; - - g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); - g_return_if_fail (iter != NULL); - g_return_if_fail (ITER_IS_VALID (model, iter)); - g_return_if_fail (column >= -1 && (guint) column < model->n_columns); - - if (column > -1) - { - start = column; - end = column + 1; - } - else - { - start = 0; - end = model->n_columns; - } - - node = get_node (model, ITER_INDEX (iter)); - - for (column = start; column < end; column++) - { - if (!G_VALUE_TYPE (&node->values[column])) + if (pages == NULL) continue; - g_value_unset (&node->values[column]); - changed = TRUE; + for (page_index = 0; page_index < pages->len; page_index++) + { + ValuePage *page = pages->pdata[page_index]; + guint base = page_index << VALUE_PAGE_SHIFT; + guint slot; + + if (page == NULL) + continue; + + for (slot = 0; slot < VALUE_PAGE_SIZE && base + slot < model->files->len; slot++) + { + GValue *value = &page->values[slot]; + + if (G_VALUE_TYPE (value) != G_TYPE_INVALID) + { + g_value_unset (value); + changed[base + slot] = TRUE; + } + } + } } - if (changed && node->visible) - emit_row_changed_for_node (model, ITER_INDEX (iter)); + /* One change signal per affected row, in row order. */ + n = model_n_visible (model); + for (i = 0; i < n; i++) + { + guint id = model_nth_visible (model, i); + + if (changed[id]) + emit_row_changed_for_node (model, id); + } + + g_free (changed); +} + +/** + * _gtk_file_system_model_clear_cache_for_iter: + * @model: a #GtkFileSystemModel + * @iter: a valid iterator + * @column: the column to clear or -1 for all columns + * + * Like _gtk_file_system_model_clear_cache(), for a single row. + **/ +void +_gtk_file_system_model_clear_cache_for_iter (GtkFileSystemModel *model, + GtkTreeIter *iter, + int column) +{ + gboolean changed = FALSE; + guint start, end, c, id; + + g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); + g_return_if_fail (ITER_IS_VALID (model, iter)); + g_return_if_fail (column >= -1 && column < (int) model->n_columns); + + if (column >= 0) + { + start = column; + end = column + 1; + } + else + { + start = 0; + end = model->n_columns; + } + + id = ITER_INDEX (iter); + for (c = start; c < end; c++) + changed |= value_cache_clear_slot (model, id, c); + + if (changed && get_node (model, id)->visible) + emit_row_changed_for_node (model, id); } /** @@ -2205,13 +3139,15 @@ _gtk_file_system_model_add_editable (GtkFileSystemModel *model, GtkTreeIter *ite g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (!get_node (model, 0)->visible); + gtk_file_system_model_complete_merge (model); + node_set_visible_and_filtered_out (model, 0, TRUE, FALSE); ITER_INIT_FROM_INDEX (model, iter, 0); /* we don't want file system changes to affect the model while * editing is in place */ - freeze_updates (model); + model->editing_hold = TRUE; } /** @@ -2228,7 +3164,30 @@ _gtk_file_system_model_remove_editable (GtkFileSystemModel *model) g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (get_node (model, 0)->visible); - thaw_updates (model); - node_set_visible_and_filtered_out (model, 0, FALSE, FALSE); + + model->editing_hold = FALSE; + gtk_file_system_model_schedule_work (model); +} + +/** + * _gtk_file_system_model_flush: + * @model: a #GtkFileSystemModel + * + * Brings the rows up to date right away: the model normally commits new + * files, filters and sorts again and applies changes to single files in + * the background. For code that needs to look at the rows now, such as + * selecting a file the user asked for after showing hidden files. Does + * nothing while the editable row is shown. + **/ +void +_gtk_file_system_model_flush (GtkFileSystemModel *model) +{ + g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); + + if (model->editing_hold) + return; + + while (gtk_file_system_model_row_work (model, G_MAXINT64, TRUE) != ROW_WORK_NONE) + ; } diff --git a/gtk/gtkfilesystemmodel.h b/gtk/gtkfilesystemmodel.h index 4bdda0c23..639a47af2 100644 --- a/gtk/gtkfilesystemmodel.h +++ b/gtk/gtkfilesystemmodel.h @@ -94,6 +94,7 @@ void _gtk_file_system_model_set_filter (GtkFileSystemModel void _gtk_file_system_model_add_editable (GtkFileSystemModel *model, GtkTreeIter *iter); void _gtk_file_system_model_remove_editable (GtkFileSystemModel *model); +void _gtk_file_system_model_flush (GtkFileSystemModel *model); G_END_DECLS