From 37de69513090bea01f1be2396869e3511fdb0782 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:07 +0200 Subject: [PATCH 1/9] gtkfilesystemmodel: detect known files correctly and coalesce re-sorts query_done used "files->len did not grow" to decide whether a queried file was already part of the model. Node slots of removed files are reused, so a new file can take a free slot without growing the array; it was then treated as a changed file and triggered a full sort. Look the file up before updating it instead. Changed files (from late queries and from the directory monitor) can change position when sorting by size or modification time. The monitor path never re-sorted, the query path sorted immediately for every file. Both now queue one sort after 100 ms, so a burst of changes costs a single sort. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilesystemmodel.c | 58 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 5 deletions(-) diff --git a/gtk/gtkfilesystemmodel.c b/gtk/gtkfilesystemmodel.c index 6adc1c37a..0147a306a 100644 --- a/gtk/gtkfilesystemmodel.c +++ b/gtk/gtkfilesystemmodel.c @@ -62,6 +62,10 @@ #define MODEL_DRAIN_CLOCK_GRANULARITY 4 #define MODEL_FINALIZE_CLOCK_GRANULARITY 8 +/* Coalesce re-sorts caused by changed file information (monitor events, + * late queries). A burst of changes then costs one sort, not one each. */ +#define MODEL_RESORT_DELAY_MS 100 + enum { MODEL_FINALIZE_NONE, @@ -114,6 +118,7 @@ struct _GtkFileSystemModel GCancellable * cancellable; GList * pending_files; guint drain_source; + guint resort_source; GArray * sort_scratch; guint sort_width; @@ -979,6 +984,30 @@ gtk_file_system_model_sort (GtkFileSystemModel *model) model->resort_pending = FALSE; } +static gboolean +gtk_file_system_model_resort_timeout (gpointer data) +{ + GtkFileSystemModel *model = data; + + model->resort_source = 0; + gtk_file_system_model_sort (model); + + return FALSE; +} + +static void +gtk_file_system_model_queue_resort (GtkFileSystemModel *model) +{ + if (model->resort_source != 0) + return; + + model->resort_source = + gdk_threads_add_timeout_full (G_PRIORITY_DEFAULT_IDLE, + MODEL_RESORT_DELAY_MS, + gtk_file_system_model_resort_timeout, + model, NULL); +} + static gboolean gtk_file_system_model_get_sort_column_id (GtkTreeSortable *sortable, @@ -1450,6 +1479,12 @@ gtk_file_system_model_dispose (GObject *object) model->drain_source = 0; } + if (model->resort_source != 0) + { + g_source_remove (model->resort_source); + model->resort_source = 0; + } + g_cancellable_cancel (model->cancellable); g_clear_pointer (&model->pending_monitor_queries, g_hash_table_destroy); @@ -1667,7 +1702,7 @@ 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 n_files; + gboolean file_known; info = g_file_query_info_finish (file, res, NULL); if (info == NULL) @@ -1675,12 +1710,16 @@ gtk_file_system_model_query_done (GObject * object, gdk_threads_enter (); - n_files = model->files->len; + /* Slots of removed files are reused, so the array length does not tell + * whether this file was already part of the model. New files are + * inserted at their sorted position by add_file(); only changed files + * may need to move. */ + file_known = node_get_for_file (model, file) != 0; _gtk_file_system_model_update_file (model, file, info); - if (model->files->len == n_files) - gtk_file_system_model_sort (model); + if (file_known) + gtk_file_system_model_queue_resort (model); g_object_unref (info); @@ -1708,7 +1747,16 @@ gtk_file_system_model_monitor_query_done (GObject *object, g_hash_table_remove (model->pending_monitor_queries, G_FILE (object)); if (info) - _gtk_file_system_model_update_file (model, G_FILE (object), info); + { + gboolean file_known = + node_get_for_file (model, G_FILE (object)) != 0; + + _gtk_file_system_model_update_file (model, G_FILE (object), info); + + /* Size or modification time may have changed the order. */ + if (file_known) + gtk_file_system_model_queue_resort (model); + } } gdk_threads_leave (); From 2413f8bf13c9b178f564742fac96afe44100fe6f Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:08 +0200 Subject: [PATCH 2/9] filechooser, gtkiconview: stop quadratic work in the icon view Opening a folder with 100000 files in icon view did not finish within 10 minutes, and with 20000 files every scroll step blocked for seconds. - The file chooser computed the visible range for every icon cell it was asked for. For GtkIconView that is a walk over all items, and the view asks for every item while laying out, so a layout was O(n^2). The chooser now caches the visible index range and recomputes it only after scrolling, resizing or a model change. - gtk_icon_view_get_visible_range() and the expose handler stop at the first item below the visible area. Items are laid out row by row, so the result is unchanged. - Every relayout measured the cells of every item again in gtk_icon_view_calculate_item_size2(), and every loaded icon caused a relayout. An icon view can now reuse a measured cell layout and just move it when only the item position changed. This is internal and opt-in (_gtk_icon_view_set_cache_cell_layout), so applications keep the old behaviour; the file chooser enables it and invalidates the cache when zooming. The cache is also dropped on style changes. - Sequential row-changed notifications looked up their item with g_list_nth_data() and then walked the whole list in verify_items(). Lookups now continue from the previous item, and verify_items() only runs in --enable-debug=yes builds. Measured with 100000 files in icon view: longest main loop stall while scrolling went from 5059 ms to 40 ms. No public API or structure changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilechooserdefault.c | 134 ++++++++++++++++++------ gtk/gtkfilechooserprivate.h | 6 ++ gtk/gtkiconview.c | 196 +++++++++++++++++++++++++++++++++++- gtk/gtkprivate.h | 7 ++ 4 files changed, 310 insertions(+), 33 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 9f9aac514..f909f6837 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -407,6 +407,15 @@ static void update_cell_renderer_attributes (GtkFileChooserDefault *impl); static void browse_files_center_selected_row (GtkFileChooserDefault *impl); static void view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode); +static void visible_range_invalidate (GtkFileChooserDefault *impl); +static gboolean visible_range_get (GtkFileChooserDefault *impl, + gint *first, + gint *last); +static void visible_range_adjustment_cb (GtkAdjustment *adjustment, + GtkFileChooserDefault *impl); +static void visible_range_size_allocate_cb (GtkWidget *widget, + GtkAllocation *allocation, + GtkFileChooserDefault *impl); static void icon_view_scale_create (GtkFileChooserDefault *impl); static void view_mode_toggle_button_toggled_cb (GtkToggleButton *toggle, GtkFileChooserDefault *impl); @@ -4817,6 +4826,8 @@ update_icon_view_cell_layout (GtkFileChooserDefault *impl) gtk_cell_renderer_set_fixed_size (GTK_CELL_RENDERER (impl->list_name_renderer), item_width, -1); } + + _gtk_icon_view_invalidate_cell_layout (impl->browse_files_icon_view); } /* Creates the list view */ @@ -4940,6 +4951,10 @@ create_browse_files_icon_view (GtkFileChooserDefault *impl) { impl->browse_files_icon_view = gtk_icon_view_new (); + /* Reuse measured cell layouts across relayouts; update_icon_view_cell_layout() + * invalidates them when the zoom changes the renderer sizes. */ + _gtk_icon_view_set_cache_cell_layout (impl->browse_files_icon_view, TRUE); + g_object_set_data (G_OBJECT (impl->browse_files_icon_view), I_("GtkFileChooserDefault"), impl); gtk_icon_view_set_item_padding (GTK_ICON_VIEW (impl->browse_files_icon_view), 0); gtk_icon_view_set_item_width (GTK_ICON_VIEW (impl->browse_files_icon_view), @@ -5022,6 +5037,16 @@ create_file_list (GtkFileChooserDefault *impl) impl->browse_files_scrolled_window = swin; gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (swin), GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); + + /* The scrolled window keeps its adjustments when the view is swapped. */ + g_signal_connect (gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (swin)), + "value-changed", G_CALLBACK (visible_range_adjustment_cb), impl); + g_signal_connect (gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (swin)), + "changed", G_CALLBACK (visible_range_adjustment_cb), impl); + g_signal_connect (gtk_scrolled_window_get_hadjustment (GTK_SCROLLED_WINDOW (swin)), + "value-changed", G_CALLBACK (visible_range_adjustment_cb), impl); + g_signal_connect (swin, "size-allocate", + G_CALLBACK (visible_range_size_allocate_cb), impl); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (swin), GTK_SHADOW_IN); @@ -5385,6 +5410,7 @@ view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode) gtk_container_add (GTK_CONTAINER (impl->browse_files_scrolled_window), impl->browse_files_current_view); gtk_widget_show (impl->browse_files_current_view); + visible_range_invalidate (impl); browse_files_center_selected_row (impl); } @@ -5490,10 +5516,8 @@ icon_view_scale_clear_visible_model_cache (GtkFileChooserDefault *impl, gboolean include_overscan) { GtkTreeModel *tree_model; - GtkTreePath *start, *end, *path; + GtkTreePath *path; GtkTreeIter iter; - gint *start_indices; - gint *end_indices; gint first; gint last; gint i; @@ -5508,20 +5532,11 @@ icon_view_scale_clear_visible_model_cache (GtkFileChooserDefault *impl, * When shrinking icons, the new layout can make rows visible that were just * outside the old visible range. Only in that case do we add a small margin. */ - if (!get_visible_range (&start, &end, impl)) - { - _gtk_file_system_model_clear_cache (GTK_FILE_SYSTEM_MODEL (impl->current_model), - MODEL_COL_ICON_PIXBUF); - return; - } + /* The zoom may have changed the layout since the range was cached. */ + visible_range_invalidate (impl); - start_indices = gtk_tree_path_get_indices (start); - end_indices = gtk_tree_path_get_indices (end); - - if (!start_indices || !end_indices) + if (!visible_range_get (impl, &first, &last)) { - gtk_tree_path_free (start); - gtk_tree_path_free (end); _gtk_file_system_model_clear_cache (GTK_FILE_SYSTEM_MODEL (impl->current_model), MODEL_COL_ICON_PIXBUF); return; @@ -5537,13 +5552,8 @@ icon_view_scale_clear_visible_model_cache (GtkFileChooserDefault *impl, overscan = MIN (overscan, ICON_VIEW_SCALE_MAX_VISIBLE_OVERSCAN); - first = MAX (0, start_indices[0] - overscan); - last = end_indices[0] + overscan; - } - else - { - first = start_indices[0]; - last = end_indices[0]; + first = MAX (0, first - overscan); + last = last + overscan; } tree_model = impl->current_model; @@ -5562,8 +5572,6 @@ icon_view_scale_clear_visible_model_cache (GtkFileChooserDefault *impl, } gtk_tree_path_free (path); - gtk_tree_path_free (start); - gtk_tree_path_free (end); } static gboolean @@ -7912,6 +7920,67 @@ get_visible_range (GtkTreePath **start, GtkTreePath **end, g_assert_not_reached (); } +static void +visible_range_invalidate (GtkFileChooserDefault *impl) +{ + impl->visible_range_valid = FALSE; +} + +/* Returns the cached index range of the visible rows of the current view. + * The range is recomputed lazily after scrolling, resizing or a model + * change, so callers that run once per cell stay O(1). */ +static gboolean +visible_range_get (GtkFileChooserDefault *impl, + gint *first, + gint *last) +{ + if (!impl->visible_range_valid) + { + GtkTreePath *start, *end; + + impl->visible_range_first = -1; + impl->visible_range_last = -1; + impl->visible_range_valid = TRUE; + + if (get_visible_range (&start, &end, impl)) + { + gint *start_indices = gtk_tree_path_get_indices (start); + gint *end_indices = gtk_tree_path_get_indices (end); + + if (start_indices && end_indices) + { + impl->visible_range_first = start_indices[0]; + impl->visible_range_last = end_indices[0]; + } + + gtk_tree_path_free (start); + gtk_tree_path_free (end); + } + } + + if (impl->visible_range_first < 0) + return FALSE; + + *first = impl->visible_range_first; + *last = impl->visible_range_last; + return TRUE; +} + +static void +visible_range_adjustment_cb (GtkAdjustment *adjustment, + GtkFileChooserDefault *impl) +{ + visible_range_invalidate (impl); +} + +static void +visible_range_size_allocate_cb (GtkWidget *widget, + GtkAllocation *allocation, + GtkFileChooserDefault *impl) +{ + visible_range_invalidate (impl); +} + static gboolean file_system_model_set (GtkFileSystemModel *model, GFile *file, @@ -7974,9 +8043,10 @@ file_system_model_set (GtkFileSystemModel *model, if (info) { GtkTreeModel *tree_model; - GtkTreePath *path, *start, *end; + GtkTreePath *path; GtkTreeIter iter; gboolean file_visible; + gint first, last, row; /* not loading icon view's icon in the list view */ if (column == MODEL_COL_ICON_PIXBUF && impl->view_mode == VIEW_MODE_LIST) @@ -8010,7 +8080,9 @@ file_system_model_set (GtkFileSystemModel *model, return TRUE; } - if (!get_visible_range (&start, &end, impl)) + /* This runs for every cell the view lays out, so it must not + * compute the visible range itself (O(n) for GtkIconView). */ + if (!visible_range_get (impl, &first, &last)) return FALSE; if (!_gtk_file_system_model_get_iter_for_file (model, @@ -8019,12 +8091,11 @@ file_system_model_set (GtkFileSystemModel *model, g_assert_not_reached (); path = gtk_tree_model_get_path (tree_model, &iter); - file_visible = (gtk_tree_path_compare (start, path) != 1 && - gtk_tree_path_compare (path, end) != 1); - + row = gtk_tree_path_get_indices (path)[0]; gtk_tree_path_free (path); - gtk_tree_path_free (start); - gtk_tree_path_free (end); + + /* Like GTK 3: also prefetch the row just outside the view. */ + file_visible = row >= first - 1 && row <= last + 1; if (file_visible) { @@ -11873,6 +11944,7 @@ current_view_set_file_model (GtkFileChooserDefault *impl, GtkTreeModel *model) g_assert_not_reached (); g_object_set (view, "model", impl->current_model, NULL); + visible_range_invalidate (impl); /* * If an icon-view scale change has queued a delayed full cache clear, a model diff --git a/gtk/gtkfilechooserprivate.h b/gtk/gtkfilechooserprivate.h index 40466c68a..124ab90d9 100644 --- a/gtk/gtkfilechooserprivate.h +++ b/gtk/gtkfilechooserprivate.h @@ -234,6 +234,12 @@ struct _GtkFileChooserDefault guint icon_view_scale_visible_timeout_id; guint icon_view_scale_after_layout_id; gint pending_icon_view_icon_size; + + /* Cached index range of the rows shown in the current view. Computing + * it is O(n) for GtkIconView, so it must not be done per cell. */ + gint visible_range_first; + gint visible_range_last; + guint visible_range_valid : 1; gint icon_view_scale_visible_overscan; ViewMode view_mode; diff --git a/gtk/gtkiconview.c b/gtk/gtkiconview.c index acd2e6f49..d9c65e808 100644 --- a/gtk/gtkiconview.c +++ b/gtk/gtkiconview.c @@ -74,6 +74,16 @@ struct _GtkIconViewItem guint selected : 1; guint selected_before_rubberbanding : 1; + /* Cached result of gtk_icon_view_calculate_item_size2(), only used when + * the view caches cell layouts (see _gtk_icon_view_set_cache_cell_layout). + * The inputs are the item geometry before the call and the row's + * per-cell maximum heights; the outputs are box/before/after plus the + * final width and height. */ + guint layout_valid : 1; + guint layout_rtl : 1; + gint layout_x, layout_y, layout_width; + gint layout_out_width, layout_out_height; + gint *layout_max_height; }; typedef struct _GtkIconViewCellInfo GtkIconViewCellInfo; @@ -106,6 +116,15 @@ struct _GtkIconViewPrivate { gint width, height; + /* Reuse per-item cell layouts across relayouts (internal, opt-in). */ + guint cache_cell_layout : 1; + + /* Last item looked up by index; makes sequential row-changed + * notifications O(1) instead of O(n) each. Reset whenever the item + * list changes. */ + GList *nth_cache_link; + gint nth_cache_index; + GtkSelectionMode selection_mode; GdkWindow *bin_window; @@ -305,6 +324,7 @@ static void gtk_icon_view_queue_draw_path (GtkIco static void gtk_icon_view_queue_draw_item (GtkIconView *icon_view, GtkIconViewItem *item); static void gtk_icon_view_queue_layout (GtkIconView *icon_view); +static void gtk_icon_view_invalidate_cell_layouts (GtkIconView *icon_view); static void gtk_icon_view_set_cursor_item (GtkIconView *icon_view, GtkIconViewItem *item, gint cursor_cell); @@ -1425,6 +1445,9 @@ gtk_icon_view_style_set (GtkWidget *widget, gdk_window_set_background (icon_view->priv->bin_window, &widget->style->base[widget->state]); } + /* Cell sizes depend on the style; never reuse layouts measured before. */ + gtk_icon_view_invalidate_cell_layouts (icon_view); + gtk_widget_queue_resize (widget); } @@ -1590,6 +1613,10 @@ gtk_icon_view_expose (GtkWidget *widget, GtkIconViewItem *item = icons->data; GdkRectangle area; + /* Rows are laid out top to bottom; nothing after this can be exposed. */ + if (item->y > expose->area.y + expose->area.height) + break; + area.x = item->x; area.y = item->y; area.width = item->width; @@ -2687,6 +2714,115 @@ gtk_icon_view_adjustment_changed (GtkAdjustment *adjustment, } } +/* Same result as gtk_icon_view_calculate_item_size2(), but when cell + * layout caching is enabled and nothing that the calculation depends on + * has changed except the item position, the cached cell boxes are moved + * instead of measuring all cell renderers again. Measuring text cells is + * by far the most expensive part of a relayout, and relayouts happen for + * every model change, so this keeps large views responsive. */ +static void +gtk_icon_view_calculate_item_size2_cached (GtkIconView *icon_view, + GtkIconViewItem *item, + gint *max_height, + gboolean rtl) +{ + gint n_cells = icon_view->priv->n_cells; + gint i; + + if (!icon_view->priv->cache_cell_layout) + { + gtk_icon_view_calculate_item_size2 (icon_view, item, max_height); + return; + } + + if (item->layout_valid && + item->n_cells == n_cells && + item->layout_max_height != NULL && + item->layout_rtl == (rtl != FALSE) && + item->layout_width == item->width && + memcmp (item->layout_max_height, max_height, n_cells * sizeof (gint)) == 0) + { + gint dx = item->x - item->layout_x; + gint dy = item->y - item->layout_y; + + if (dx != 0 || dy != 0) + { + for (i = 0; i < n_cells; i++) + { + item->box[i].x += dx; + item->box[i].y += dy; + } + } + + item->layout_x = item->x; + item->layout_y = item->y; + item->width = item->layout_out_width; + item->height = item->layout_out_height; + return; + } + + item->layout_x = item->x; + item->layout_y = item->y; + item->layout_width = item->width; + item->layout_rtl = rtl != FALSE; + + gtk_icon_view_calculate_item_size2 (icon_view, item, max_height); + + if (item->layout_max_height == NULL) + item->layout_max_height = g_new (gint, n_cells); + memcpy (item->layout_max_height, max_height, n_cells * sizeof (gint)); + item->layout_out_width = item->width; + item->layout_out_height = item->height; + item->layout_valid = item->n_cells == n_cells; +} + +static void +gtk_icon_view_invalidate_cell_layouts (GtkIconView *icon_view) +{ + GList *l; + + for (l = icon_view->priv->items; l; l = l->next) + ((GtkIconViewItem *) l->data)->layout_valid = FALSE; +} + +/* + * _gtk_icon_view_set_cache_cell_layout: + * + * Internal. Lets an icon view reuse measured cell layouts across + * relayouts. Only for views whose owner invalidates the layout itself + * (with _gtk_icon_view_invalidate_cell_layout() or by changing the model + * row) whenever cell renderer sizes change outside the icon view's + * knowledge. Off by default, so applications see no behaviour change. + */ +void +_gtk_icon_view_set_cache_cell_layout (GtkWidget *widget, + gboolean cache) +{ + GtkIconView *icon_view; + + g_return_if_fail (GTK_IS_ICON_VIEW (widget)); + icon_view = GTK_ICON_VIEW (widget); + + cache = cache != FALSE; + if (icon_view->priv->cache_cell_layout == cache) + return; + + icon_view->priv->cache_cell_layout = cache; + gtk_icon_view_invalidate_cell_layouts (icon_view); +} + +void +_gtk_icon_view_invalidate_cell_layout (GtkWidget *widget) +{ + GtkIconView *icon_view; + + g_return_if_fail (GTK_IS_ICON_VIEW (widget)); + icon_view = GTK_ICON_VIEW (widget); + + gtk_icon_view_invalidate_cell_layouts (icon_view); + gtk_icon_view_queue_layout (icon_view); +} + static GList * gtk_icon_view_layout_single_row (GtkIconView *icon_view, GList *first_item, @@ -2771,7 +2907,7 @@ gtk_icon_view_layout_single_row (GtkIconView *icon_view, item->col = col - 1 - item->col; } - gtk_icon_view_calculate_item_size2 (icon_view, item, max_height); + gtk_icon_view_calculate_item_size2_cached (icon_view, item, max_height, rtl); /* We may want to readjust the new y coordinate. */ if (item->y + item->height + focus_width + icon_view->priv->row_spacing > *y) @@ -3011,6 +3147,10 @@ gtk_icon_view_calculate_item_size (GtkIconView *icon_view, item->after = g_new0 (gint, icon_view->priv->n_cells); item->box = g_new0 (GdkRectangle, icon_view->priv->n_cells); + g_free (item->layout_max_height); + item->layout_max_height = NULL; + item->layout_valid = FALSE; + item->n_cells = icon_view->priv->n_cells; } @@ -3157,6 +3297,7 @@ gtk_icon_view_item_invalidate_size (GtkIconViewItem *item) { item->width = -1; item->height = -1; + item->layout_valid = FALSE; } static void @@ -3480,6 +3621,7 @@ gtk_icon_view_item_free (GtkIconViewItem *item) g_free (item->before); g_free (item->after); g_free (item->box); + g_free (item->layout_max_height); g_free (item); } @@ -3588,6 +3730,7 @@ gtk_icon_view_unselect_item (GtkIconView *icon_view, static void verify_items (GtkIconView *icon_view) { +#ifdef G_ENABLE_DEBUG GList *items; int i = 0; @@ -3601,6 +3744,38 @@ verify_items (GtkIconView *icon_view) i++; } +#endif +} + +static void +gtk_icon_view_reset_nth_cache (GtkIconView *icon_view) +{ + icon_view->priv->nth_cache_link = NULL; + icon_view->priv->nth_cache_index = -1; +} + +static GtkIconViewItem * +gtk_icon_view_nth_item (GtkIconView *icon_view, + gint index) +{ + GtkIconViewPrivate *priv = icon_view->priv; + GList *link = NULL; + + if (priv->nth_cache_link != NULL) + { + if (index == priv->nth_cache_index) + link = priv->nth_cache_link; + else if (index == priv->nth_cache_index + 1) + link = priv->nth_cache_link->next; + } + + if (link == NULL) + link = g_list_nth (priv->items, index); + + priv->nth_cache_link = link; + priv->nth_cache_index = link ? index : -1; + + return link ? link->data : NULL; } static void @@ -3618,7 +3793,7 @@ gtk_icon_view_row_changed (GtkTreeModel *model, gtk_icon_view_stop_editing (icon_view, TRUE); index = gtk_tree_path_get_indices(path)[0]; - item = g_list_nth_data (icon_view->priv->items, index); + item = gtk_icon_view_nth_item (icon_view, index); gtk_icon_view_item_invalidate_size (item); gtk_icon_view_queue_layout (icon_view); @@ -3640,6 +3815,8 @@ gtk_icon_view_row_inserted (GtkTreeModel *model, icon_view = GTK_ICON_VIEW (data); + gtk_icon_view_reset_nth_cache (icon_view); + iters_persist = gtk_tree_model_get_flags (icon_view->priv->model) & GTK_TREE_MODEL_ITERS_PERSIST; index = gtk_tree_path_get_indices(path)[0]; @@ -3684,6 +3861,8 @@ gtk_icon_view_row_deleted (GtkTreeModel *model, icon_view = GTK_ICON_VIEW (data); + gtk_icon_view_reset_nth_cache (icon_view); + index = gtk_tree_path_get_indices(path)[0]; list = g_list_nth (icon_view->priv->items, index); @@ -3735,6 +3914,8 @@ gtk_icon_view_rows_reordered (GtkTreeModel *model, icon_view = GTK_ICON_VIEW (data); + gtk_icon_view_reset_nth_cache (icon_view); + gtk_icon_view_stop_editing (icon_view, TRUE); length = gtk_tree_model_iter_n_children (model, NULL); @@ -3771,6 +3952,8 @@ gtk_icon_view_build_items (GtkIconView *icon_view) gboolean iters_persist; GList *items = NULL; + gtk_icon_view_reset_nth_cache (icon_view); + iters_persist = gtk_tree_model_get_flags (icon_view->priv->model) & GTK_TREE_MODEL_ITERS_PERSIST; if (!gtk_tree_model_get_iter_first (icon_view->priv->model, @@ -5209,6 +5392,13 @@ gtk_icon_view_get_visible_range (GtkIconView *icon_view, { GtkIconViewItem *item = icons->data; + /* Items are laid out row by row, so once an item starts below the + * visible area, all following items do too. Stop here instead of + * walking the rest of a possibly huge list. */ + if (start_index != -1 && + item->y > (int) (icon_view->priv->vadjustment->value + icon_view->priv->vadjustment->page_size)) + break; + if ((item->x + item->width >= (int)icon_view->priv->hadjustment->value) && (item->y + item->height >= (int)icon_view->priv->vadjustment->value) && (item->x <= (int) (icon_view->priv->hadjustment->value + icon_view->priv->hadjustment->page_size)) && @@ -5322,6 +5512,8 @@ gtk_icon_view_set_model (GtkIconView *icon_view, g_return_if_fail (GTK_IS_ICON_VIEW (icon_view)); g_return_if_fail (model == NULL || GTK_IS_TREE_MODEL (model)); + gtk_icon_view_reset_nth_cache (icon_view); + if (icon_view->priv->model == model) return; diff --git a/gtk/gtkprivate.h b/gtk/gtkprivate.h index cc1b50dfa..6485a9f07 100644 --- a/gtk/gtkprivate.h +++ b/gtk/gtkprivate.h @@ -141,6 +141,13 @@ const gchar *_gtk_font_style_name_translate (const gchar *name); #define _gtk_font_style_name_translate(name) (name) #endif +/* GtkIconView internals used by the file chooser */ +G_GNUC_INTERNAL +void _gtk_icon_view_set_cache_cell_layout (GtkWidget *icon_view, + gboolean cache); +G_GNUC_INTERNAL +void _gtk_icon_view_invalidate_cell_layout (GtkWidget *icon_view); + gboolean _gtk_fnmatch (const char *pattern, const char *string, gboolean no_leading_period); From f830c3bac3144594c6a4cbcee6527cbb5aac1c5b Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:08 +0200 Subject: [PATCH 3/9] filechooser: use fixed-height mode with fixed column widths in the list GtkTreeView measures every row of the model to size its columns and to compute row heights. For a large folder that means formatting and measuring the size and date of every file, even of rows that are never shown. The file list now uses gtk_tree_view_set_fixed_height_mode() through the public API. For that all columns are switched to fixed sizing: - Size and Modified get a width that fits the widest string the column can show in the current locale: g_format_size() for each unit, and the date formatter for today, yesterday, every weekday and one date in every month. The column title (plus room for the sort arrow) is also taken into account. Widths are recomputed on style changes, and the columns stay resizable. - The name column keeps expanding into the remaining space. - Size is right-aligned and both columns ellipsize instead of clipping. Unlike forcing fixed-height mode on columns that still size themselves, this does not clip sizes or dates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilechooserdefault.c | 143 ++++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index f909f6837..db87ffed7 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -4831,6 +4831,141 @@ update_icon_view_cell_layout (GtkFileChooserDefault *impl) } /* Creates the list view */ +static char *my_g_format_time_for_display (gint64 secs); + +static gchar * +file_list_format_size (goffset size) +{ +#if GLIB_CHECK_VERSION(2,30,0) + return g_format_size (size); +#else + return g_format_size_for_display (size); +#endif +} + +/* Widest pixel width of @texts rendered with @widget's font. */ +static gint +file_list_measure_texts (GtkWidget *widget, + GPtrArray *texts) +{ + PangoLayout *layout; + gint max_width = 0; + guint i; + + layout = gtk_widget_create_pango_layout (widget, NULL); + + for (i = 0; i < texts->len; i++) + { + gint width; + + pango_layout_set_text (layout, g_ptr_array_index (texts, i), -1); + pango_layout_get_pixel_size (layout, &width, NULL); + max_width = MAX (max_width, width); + } + + g_object_unref (layout); + + return max_width; +} + +/* Gives @column a fixed width that fits its title and every string in + * @texts, so the tree view never has to measure rows to size it. */ +static void +file_list_set_fixed_column_width (GtkWidget *tree_view, + GtkTreeViewColumn *column, + GPtrArray *texts) +{ + GPtrArray *title; + gint text_width, title_width; + gint focus_width, focus_pad, separator; + + gtk_widget_style_get (tree_view, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, + "horizontal-separator", &separator, + NULL); + + title = g_ptr_array_new (); + g_ptr_array_add (title, (gpointer) gtk_tree_view_column_get_title (column)); + + text_width = file_list_measure_texts (tree_view, texts); + /* Leave room for the sort arrow next to the title. */ + title_width = file_list_measure_texts (tree_view, title) + 24; + + g_ptr_array_free (title, TRUE); + + /* Cell renderer padding (xpad 2 on each side) plus tree view spacing. */ + text_width += 2 * 2 + 2 * (focus_width + focus_pad) + separator + 4; + + gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_FIXED); + gtk_tree_view_column_set_fixed_width (column, MAX (text_width, title_width)); +} + +/* The file list uses fixed-height mode: every row has the same height + * and columns have fixed widths, so the tree view does not have to + * measure every row of a large folder. Size and date columns get a + * width that fits the widest strings they can show in this locale. */ +static void +file_list_update_fixed_sizing (GtkFileChooserDefault *impl) +{ + GtkWidget *tree_view = impl->browse_files_tree_view; + GPtrArray *texts; + GDateTime *now; + gint64 now_secs; + gint i; + + if (!tree_view || !impl->list_size_column || !impl->list_mtime_column) + return; + + /* Size column: the longest strings g_format_size() produces per unit. */ + texts = g_ptr_array_new_with_free_func (g_free); + g_ptr_array_add (texts, file_list_format_size (999)); + g_ptr_array_add (texts, file_list_format_size (999949)); + g_ptr_array_add (texts, file_list_format_size (G_GOFFSET_CONSTANT (999949999))); + g_ptr_array_add (texts, file_list_format_size (G_GOFFSET_CONSTANT (999949999999))); + g_ptr_array_add (texts, file_list_format_size (G_GOFFSET_CONSTANT (999949999999999))); + file_list_set_fixed_column_width (tree_view, impl->list_size_column, texts); + g_ptr_array_free (texts, TRUE); + + /* Date column: today, yesterday, every weekday and one date per month, + * all formatted exactly like the column does. */ + texts = g_ptr_array_new_with_free_func (g_free); + now = g_date_time_new_now_local (); + now_secs = g_date_time_to_unix (now); + for (i = 0; i < 7; i++) + g_ptr_array_add (texts, my_g_format_time_for_display (now_secs - i * 24 * 3600)); + for (i = 1; i <= 12; i++) + { + GDateTime *date; + + date = g_date_time_new_local (g_date_time_get_year (now) - 1, i, 28, 23, 59, 0); + if (date) + { + g_ptr_array_add (texts, my_g_format_time_for_display (g_date_time_to_unix (date))); + g_date_time_unref (date); + } + } + g_ptr_array_add (texts, g_strdup (_("Unknown"))); + g_date_time_unref (now); + file_list_set_fixed_column_width (tree_view, impl->list_mtime_column, texts); + g_ptr_array_free (texts, TRUE); + + /* The name column takes the remaining space. */ + gtk_tree_view_column_set_sizing (impl->list_name_column, GTK_TREE_VIEW_COLUMN_FIXED); + if (gtk_tree_view_column_get_fixed_width (impl->list_name_column) <= 0) + gtk_tree_view_column_set_fixed_width (impl->list_name_column, 200); + + gtk_tree_view_set_fixed_height_mode (GTK_TREE_VIEW (tree_view), TRUE); +} + +static void +file_list_style_set_cb (GtkWidget *widget, + GtkStyle *previous_style, + GtkFileChooserDefault *impl) +{ + file_list_update_fixed_sizing (impl); +} + static GtkWidget * create_browse_files_tree_view (GtkFileChooserDefault *impl) { @@ -4923,6 +5058,8 @@ create_browse_files_tree_view (GtkFileChooserDefault *impl) renderer = gtk_cell_renderer_text_new (); g_object_set (renderer, "alignment", PANGO_ALIGN_RIGHT, + "xalign", 1.0, + "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_tree_view_column_pack_start (column, renderer, TRUE); /* bug: it doesn't expand */ gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), column); @@ -4935,6 +5072,7 @@ create_browse_files_tree_view (GtkFileChooserDefault *impl) gtk_tree_view_column_set_title (column, _("Modified")); renderer = gtk_cell_renderer_text_new (); + g_object_set (renderer, "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_tree_view_column_pack_start (column, renderer, TRUE); gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), column); impl->list_mtime_column = column; @@ -4942,6 +5080,11 @@ create_browse_files_tree_view (GtkFileChooserDefault *impl) file_list_set_sort_column_ids (impl); update_cell_renderer_attributes (impl); + /* Fonts change the widths; recompute them whenever the style does. */ + file_list_update_fixed_sizing (impl); + g_signal_connect (impl->browse_files_tree_view, "style-set", + G_CALLBACK (file_list_style_set_cb), impl); + return impl->browse_files_tree_view; } From 1f16f4e43cf7ed45761621b42763399f0bb39d5b Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:09 +0200 Subject: [PATCH 4/9] filechooser: list folders with fast-content-type, sniff only when needed The folder was enumerated with standard::content-type. For every file whose type GIO cannot tell from its name, that opens the file and reads its first bytes. On a slow disk or a high-latency NFS share this costs several round trips per file, while the content type is only used by MIME-type file filters. The folder is now listed with standard::fast-content-type, which only looks at the name. When a MIME filter needs the type of a file whose name did not reveal it, the model detects the content type asynchronously (at most two requests in flight, low priority) and filters that file again once the result arrives. Files sniffed while the folder is still loading are filtered again when loading finishes. Content types are read with g_file_info_has_attribute() first, so GLib does not warn about attributes that were not queried. With 20000 files and 1 ms emulated latency per file system call, the folder now loads in 24.1 s instead of 31.6 s (21519 instead of 28105 calls). An extensionless PDF still passes an application/pdf filter. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilechooserdefault.c | 2 +- gtk/gtkfilesystemmodel.c | 158 +++++++++++++++++++++++++++++++++++- 2 files changed, 158 insertions(+), 2 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index db87ffed7..7ecf5f18e 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -195,7 +195,7 @@ typedef enum { #define MODEL_ATTRIBUTES "standard::name,standard::type,standard::display-name," \ "standard::is-hidden,standard::is-backup,standard::size," \ - "standard::content-type,time::modified" + "standard::fast-content-type,time::modified" enum { /* the first 3 must be these due to settings caching sort column */ MODEL_COL_NAME, diff --git a/gtk/gtkfilesystemmodel.c b/gtk/gtkfilesystemmodel.c index 0147a306a..128904a16 100644 --- a/gtk/gtkfilesystemmodel.c +++ b/gtk/gtkfilesystemmodel.c @@ -66,6 +66,11 @@ * late queries). A burst of changes then costs one sort, not one each. */ #define MODEL_RESORT_DELAY_MS 100 +/* Content sniffing reads file data; keep only a few reads in flight so a + * slow or remote folder is not flooded with requests. */ +#define MODEL_MAX_SNIFFS 2 +#define MODEL_SNIFFED_ATTRIBUTE "gtk-fsmodel::sniffed" + enum { MODEL_FINALIZE_NONE, @@ -134,6 +139,14 @@ struct _GtkFileSystemModel GQueue * pending_monitor_changes; GHashTable * pending_monitor_queries; + /* Files whose type could not be guessed from the name and that a MIME + * filter needs: their content type is detected lazily (see + * node_get_content_type). */ + GQueue * sniff_queue; + GHashTable * sniff_pending; + guint sniff_running; + GSList * sniffed_during_load; + GArray * files; GArray * order; GArray * visible_order; @@ -540,6 +553,131 @@ node_set_visible_and_filtered_out (GtkFileSystemModel *model, } } +static void gtk_file_system_model_sniff_pump (GtkFileSystemModel *model); +static void node_compute_visibility_and_filters (GtkFileSystemModel *model, guint id); + +static void +gtk_file_system_model_sniff_done (GObject *object, + GAsyncResult *res, + gpointer data) +{ + GFile *file = G_FILE (object); + GFileInfo *sniffed; + GError *error = NULL; + GtkFileSystemModel *model = data; /* only valid if not cancelled */ + guint id; + + sniffed = g_file_query_info_finish (file, res, &error); + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + { + g_error_free (error); + return; + } + g_clear_error (&error); + + gdk_threads_enter (); + + model->sniff_running--; + g_hash_table_remove (model->sniff_pending, file); /* drops the key's ref */ + + id = node_get_for_file (model, file); + if (id != 0) + { + FileModelNode *node = get_node (model, id); + GFileInfo *info = g_file_info_dup (node->info); + + /* Remember failures too, so the file is not queued again. */ + g_file_info_set_attribute_boolean (info, MODEL_SNIFFED_ATTRIBUTE, TRUE); + if (sniffed && + g_file_info_has_attribute (sniffed, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE)) + g_file_info_set_content_type (info, g_file_info_get_content_type (sniffed)); + + g_object_unref (node->info); + node->info = info; + value_cache_clear_node (model, id); + + /* The new type may change whether the filter lets the file pass. + * While loading, the visibility pass may already have seen the + * node; filter it again once loading is done. */ + if (model->directory_loading) + model->sniffed_during_load = + g_slist_prepend (model->sniffed_during_load, g_object_ref (file)); + else if (!node->held_add) + node_compute_visibility_and_filters (model, id); + } + + if (sniffed) + g_object_unref (sniffed); + + gtk_file_system_model_sniff_pump (model); + + gdk_threads_leave (); +} + +static void +gtk_file_system_model_sniff_pump (GtkFileSystemModel *model) +{ + while (model->sniff_running < MODEL_MAX_SNIFFS && + model->sniff_queue != NULL && + !g_queue_is_empty (model->sniff_queue)) + { + GFile *file = g_queue_pop_head (model->sniff_queue); + + model->sniff_running++; + g_file_query_info_async (file, + G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, + G_FILE_QUERY_INFO_NONE, + G_PRIORITY_LOW, + model->cancellable, + gtk_file_system_model_sniff_done, + model); + g_object_unref (file); + } +} + +/* Returns the content type of a node for filtering. The directory is + * listed with standard::fast-content-type, which only looks at the file + * name and never reads file data -- on a slow disk or NFS share reading + * every file is far too expensive. If the name did not tell the type, + * the content is checked asynchronously and the node is filtered again + * once the result is known. */ +static const char * +node_get_content_type (GtkFileSystemModel *model, + FileModelNode *node) +{ + const char *type; + + /* Use the typed getter only when the attribute exists; GLib warns + * about reading attributes that were not queried. */ + if (g_file_info_has_attribute (node->info, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE)) + return g_file_info_get_content_type (node->info); + + type = g_file_info_get_attribute_string (node->info, + G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE); + if (type == NULL || !g_content_type_is_unknown (type) || + _gtk_file_info_consider_as_directory (node->info) || + g_file_info_get_attribute_boolean (node->info, MODEL_SNIFFED_ATTRIBUTE)) + return type; + + if (model->sniff_pending == NULL) + { + model->sniff_pending = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, + g_object_unref, NULL); + model->sniff_queue = g_queue_new (); + } + + if (!g_hash_table_lookup (model->sniff_pending, node->file)) + { + GFile *file = g_object_ref (node->file); + + g_hash_table_insert (model->sniff_pending, file, file); + g_queue_push_tail (model->sniff_queue, g_object_ref (file)); + gtk_file_system_model_sniff_pump (model); + } + + return type; +} + static gboolean node_should_be_filtered_out (GtkFileSystemModel *model, guint id) { @@ -565,7 +703,7 @@ node_should_be_filtered_out (GtkFileSystemModel *model, guint id) if (required & GTK_FILE_FILTER_MIME_TYPE) { - const char *s = g_file_info_get_content_type (node->info); + const char *s = node_get_content_type (model, node); if (s) { mime_type = g_content_type_get_mime_type (s); @@ -1425,6 +1563,19 @@ gtk_file_system_model_finalize_load (gpointer data) if (model->finalize_phase == MODEL_FINALIZE_REPLAY) { + while (model->sniffed_during_load != NULL) + { + GFile *file = model->sniffed_during_load->data; + guint sniffed_id = node_get_for_file (model, file); + + model->sniffed_during_load = + g_slist_delete_link (model->sniffed_during_load, + model->sniffed_during_load); + if (sniffed_id != 0) + node_compute_visibility_and_filters (model, sniffed_id); + g_object_unref (file); + } + while (model->pending_monitor_changes != NULL && !g_queue_is_empty (model->pending_monitor_changes)) { @@ -1521,6 +1672,11 @@ gtk_file_system_model_finalize (GObject *object) if (model->pending_monitor_changes) g_queue_free_full (model->pending_monitor_changes, pending_monitor_change_free); + if (model->sniff_queue) + g_queue_free_full (model->sniff_queue, g_object_unref); + if (model->sniff_pending) + g_hash_table_destroy (model->sniff_pending); + g_slist_free_full (model->sniffed_during_load, g_object_unref); g_clear_pointer (&model->order, g_array_unref); g_clear_pointer (&model->visible_order, g_array_unref); From b1f87233c20977f661692bbfca6f9f26818bdc2e Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:09 +0200 Subject: [PATCH 5/9] filechooser: no blocking file system calls on folder changes Opening a folder ran g_file_find_enclosing_mount() on the main thread to decide how to show it in the shortcuts list. That stats the folder and its parents; on a slow or hung NFS share it freezes the whole dialog, including the Cancel button. Similar synchronous calls ran when activating a bookmark, when reporting that a folder could not be read (exactly when the share has problems) and when creating a new folder. - The current-folder shortcut is added once an asynchronous g_file_find_enclosing_mount_async() finishes; a newer folder change cancels the pending lookup. _gtk_file_system_volume_for_mount() maps the result to the same volume as before. - Activating a file bookmark queries the location directly and only mounts the enclosing volume when the query reports G_IO_ERROR_NOT_MOUNTED, instead of looking up the volume synchronously first. - The "could not read the contents" message uses g_file_get_parse_name() instead of querying the folder again. - New folders are created with g_file_make_directory_async(). With the latency emulation, the main thread no longer touches the folder at all (previously one blocking lstat per folder change). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilechooserdefault.c | 232 +++++++++++++++++++++++++----------- gtk/gtkfilechooserprivate.h | 1 + gtk/gtkfilesystem.c | 13 ++ gtk/gtkfilesystem.h | 5 + 4 files changed, 183 insertions(+), 68 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 7ecf5f18e..a9394f9d0 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -2180,41 +2180,108 @@ shortcuts_add_bookmarks (GtkFileChooserDefault *impl) } /* Appends a separator and a row to the shortcuts list for the current folder */ +struct CurrentFolderVolumeData +{ + GtkFileChooserDefault *impl; + GFile *file; +}; + +static void +shortcuts_add_current_folder_volume_cb (GObject *source, + GAsyncResult *result, + gpointer user_data) +{ + struct CurrentFolderVolumeData *data = user_data; + GtkFileChooserDefault *impl = data->impl; + GtkFileSystemVolume *volume; + GMount *mount; + GFile *base_file; + int pos; + + mount = g_file_find_enclosing_mount_finish (G_FILE (source), result, NULL); + + GDK_THREADS_ENTER (); + + /* Superseded by another folder change, or the chooser went away. */ + if (impl->shortcuts_current_folder_cancellable == NULL || + g_cancellable_is_cancelled (impl->shortcuts_current_folder_cancellable) || + impl->current_folder == NULL || + !g_file_equal (impl->current_folder, data->file) || + impl->shortcuts_current_folder_active || + shortcut_find_position (impl, impl->current_folder) != -1) + { + if (mount) + g_object_unref (mount); + goto out; + } + + g_clear_object (&impl->shortcuts_current_folder_cancellable); + + /* Separator */ + shortcuts_insert_separator (impl, SHORTCUTS_CURRENT_FOLDER_SEPARATOR); + + /* Item */ + pos = shortcuts_get_index (impl, SHORTCUTS_CURRENT_FOLDER); + + volume = _gtk_file_system_volume_for_mount (impl->current_folder, mount); + if (volume) + base_file = _gtk_file_system_volume_get_root (volume); + else + base_file = NULL; + + if (base_file && g_file_equal (base_file, impl->current_folder)) + shortcuts_insert_file (impl, pos, SHORTCUT_TYPE_VOLUME, volume, NULL, NULL, FALSE, SHORTCUTS_CURRENT_FOLDER); + else + { + shortcuts_insert_file (impl, pos, SHORTCUT_TYPE_FILE, NULL, impl->current_folder, NULL, FALSE, SHORTCUTS_CURRENT_FOLDER); + if (volume) + _gtk_file_system_volume_unref (volume); + } + + if (base_file) + g_object_unref (base_file); + +out: + GDK_THREADS_LEAVE (); + + g_object_unref (data->impl); + g_object_unref (data->file); + g_free (data); +} + +/* Adds the current folder to the shortcuts list if it is not already there. + * Finding the enclosing mount stats the folder and its parents, which can + * block for a long time on a slow or hung network share, so it is done + * asynchronously and the item appears once the answer is known. */ static void shortcuts_add_current_folder (GtkFileChooserDefault *impl) { - int pos; + struct CurrentFolderVolumeData *data; g_assert (!impl->shortcuts_current_folder_active); g_assert (impl->current_folder != NULL); - pos = shortcut_find_position (impl, impl->current_folder); - if (pos == -1) + if (impl->shortcuts_current_folder_cancellable) { - GtkFileSystemVolume *volume; - GFile *base_file; - - /* Separator */ - shortcuts_insert_separator (impl, SHORTCUTS_CURRENT_FOLDER_SEPARATOR); - - /* Item */ - pos = shortcuts_get_index (impl, SHORTCUTS_CURRENT_FOLDER); - - volume = _gtk_file_system_get_volume_for_file (impl->file_system, impl->current_folder); - if (volume) - base_file = _gtk_file_system_volume_get_root (volume); - else - base_file = NULL; - - if (base_file && g_file_equal (base_file, impl->current_folder)) - shortcuts_insert_file (impl, pos, SHORTCUT_TYPE_VOLUME, volume, NULL, NULL, FALSE, SHORTCUTS_CURRENT_FOLDER); - else - shortcuts_insert_file (impl, pos, SHORTCUT_TYPE_FILE, NULL, impl->current_folder, NULL, FALSE, SHORTCUTS_CURRENT_FOLDER); - - if (base_file) - g_object_unref (base_file); + g_cancellable_cancel (impl->shortcuts_current_folder_cancellable); + g_clear_object (&impl->shortcuts_current_folder_cancellable); } + + if (shortcut_find_position (impl, impl->current_folder) != -1) + return; + + impl->shortcuts_current_folder_cancellable = g_cancellable_new (); + + data = g_new (struct CurrentFolderVolumeData, 1); + data->impl = g_object_ref (impl); + data->file = g_object_ref (impl->current_folder); + + g_file_find_enclosing_mount_async (impl->current_folder, + G_PRIORITY_DEFAULT, + impl->shortcuts_current_folder_cancellable, + shortcuts_add_current_folder_volume_cb, + data); } /* Updates the current folder row in the shortcuts model */ @@ -2394,6 +2461,27 @@ add_idle_while_impl_is_alive (GtkFileChooserDefault *impl, GCallback callback) return source; } +static void +new_folder_created_cb (GObject *source, + GAsyncResult *result, + gpointer user_data) +{ + GtkFileChooserDefault *impl = user_data; + GFile *file = G_FILE (source); + GError *error = NULL; + + GDK_THREADS_ENTER (); + + if (g_file_make_directory_finish (file, result, &error)) + change_folder_and_display_error (impl, file, FALSE); + else + error_creating_folder_dialog (impl, file, error); + + GDK_THREADS_LEAVE (); + + g_object_unref (impl); +} + /* Idle handler for creating a new folder after editing its name cell, or for * canceling the editing. */ @@ -2422,13 +2510,10 @@ edited_idle_cb (GtkFileChooserDefault *impl) &error); if (file) { - GError *error = NULL; - - if (g_file_make_directory (file, NULL, &error)) - change_folder_and_display_error (impl, file, FALSE); - else - error_creating_folder_dialog (impl, file, error); - + /* Creating the folder can take long on a slow share. */ + g_file_make_directory_async (file, G_PRIORITY_DEFAULT, NULL, + new_folder_created_cb, + g_object_ref (impl)); g_object_unref (file); } else @@ -7009,6 +7094,12 @@ cancel_all_operations (GtkFileChooserDefault *impl) impl->shortcuts_activate_iter_cancellable = NULL; } + if (impl->shortcuts_current_folder_cancellable) + { + g_cancellable_cancel (impl->shortcuts_current_folder_cancellable); + g_clear_object (&impl->shortcuts_current_folder_cancellable); + } + search_stop_searching (impl, TRUE); recent_stop_loading (impl); } @@ -7815,24 +7906,20 @@ pending_select_files_process (GtkFileChooserDefault *impl) static void show_error_on_reading_current_folder (GtkFileChooserDefault *impl, GError *error) { - GFileInfo *info; + char *name; char *msg; - info = g_file_query_info (impl->current_folder, - G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, - G_FILE_QUERY_INFO_NONE, - NULL, - NULL); - if (info) - { - msg = g_strdup_printf (_("Could not read the contents of %s"), g_file_info_get_display_name (info)); - g_object_unref (info); - } + /* Do not query the folder again here: reading it just failed, and on a + * hung network share a synchronous query would freeze the dialog. */ + name = g_file_get_parse_name (impl->current_folder); + if (name) + msg = g_strdup_printf (_("Could not read the contents of %s"), name); else msg = g_strdup (_("Could not read the contents of the folder")); error_message (impl, msg, error->message); g_free (msg); + g_free (name); } /* Callback used when the file system model finishes loading */ @@ -11251,8 +11338,14 @@ struct ShortcutsActivateData { GtkFileChooserDefault *impl; GFile *file; + gboolean tried_mount; }; +static void shortcuts_activate_mount_enclosing_volume (GCancellable *cancellable, + GtkFileSystemVolume *volume, + const GError *error, + gpointer user_data); + static void shortcuts_activate_get_info_cb (GCancellable *cancellable, GFileInfo *info, @@ -11270,6 +11363,27 @@ shortcuts_activate_get_info_cb (GCancellable *cancellable, if (cancelled) goto out; + /* The location lives on a volume that is not mounted yet: mount it and + * query again (see shortcuts_activate_mount_enclosing_volume). */ + if (error && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_MOUNTED) && + !data->tried_mount) + { + GMountOperation *mount_operation; + GtkWidget *toplevel; + + data->tried_mount = TRUE; + toplevel = gtk_widget_get_toplevel (GTK_WIDGET (data->impl)); + mount_operation = gtk_mount_operation_new (GTK_WINDOW (toplevel)); + + data->impl->shortcuts_activate_iter_cancellable = + _gtk_file_system_mount_enclosing_volume (data->impl->file_system, data->file, + mount_operation, + shortcuts_activate_mount_enclosing_volume, + data); + g_object_unref (cancellable); + return; + } + if (!error && _gtk_file_info_consider_as_directory (info)) change_folder_and_display_error (data->impl, data->file, FALSE); else @@ -11354,38 +11468,20 @@ shortcuts_activate_iter (GtkFileChooserDefault *impl, else if (shortcut_type == SHORTCUT_TYPE_FILE) { struct ShortcutsActivateData *data; - GtkFileSystemVolume *volume; operation_mode_set (impl, OPERATION_MODE_BROWSE); - volume = _gtk_file_system_get_volume_for_file (impl->file_system, col_data); - data = g_new0 (struct ShortcutsActivateData, 1); data->impl = g_object_ref (impl); data->file = g_object_ref (col_data); - if (!volume || !_gtk_file_system_volume_is_mounted (volume)) - { - GMountOperation *mount_operation; - GtkWidget *toplevel; - - toplevel = gtk_widget_get_toplevel (GTK_WIDGET (impl)); - - mount_operation = gtk_mount_operation_new (GTK_WINDOW (toplevel)); - - impl->shortcuts_activate_iter_cancellable = - _gtk_file_system_mount_enclosing_volume (impl->file_system, col_data, - mount_operation, - shortcuts_activate_mount_enclosing_volume, - data); - } - else - { - impl->shortcuts_activate_iter_cancellable = - _gtk_file_system_get_info (impl->file_system, data->file, - "standard::type", - shortcuts_activate_get_info_cb, data); - } + /* Query the location directly instead of looking up its volume + * first (which blocks on a slow share); the callback mounts the + * volume if the query reports that it is not mounted. */ + impl->shortcuts_activate_iter_cancellable = + _gtk_file_system_get_info (impl->file_system, data->file, + "standard::type", + shortcuts_activate_get_info_cb, data); } else if (shortcut_type == SHORTCUT_TYPE_SEARCH) { diff --git a/gtk/gtkfilechooserprivate.h b/gtk/gtkfilechooserprivate.h index 124ab90d9..b5963b4d4 100644 --- a/gtk/gtkfilechooserprivate.h +++ b/gtk/gtkfilechooserprivate.h @@ -265,6 +265,7 @@ struct _GtkFileChooserDefault GCancellable *file_exists_get_info_cancellable; GCancellable *update_from_entry_cancellable; GCancellable *shortcuts_activate_iter_cancellable; + GCancellable *shortcuts_current_folder_cancellable; LoadState load_state; ReloadState reload_state; diff --git a/gtk/gtkfilesystem.c b/gtk/gtkfilesystem.c index 4d78102b7..6234f2879 100644 --- a/gtk/gtkfilesystem.c +++ b/gtk/gtkfilesystem.c @@ -1077,6 +1077,19 @@ _gtk_file_system_set_bookmark_label (GtkFileSystem *file_system, g_signal_emit_by_name (file_system, "bookmarks-changed", 0); } +GtkFileSystemVolume * +_gtk_file_system_volume_for_mount (GFile *file, + GMount *mount) +{ + if (!mount && g_file_is_native (file)) + return (GtkFileSystemVolume *) root_volume_token; + + return (GtkFileSystemVolume *) mount; +} + +/* Note: this blocks (it stats @file and its parents); prefer + * g_file_find_enclosing_mount_async() plus _gtk_file_system_volume_for_mount() + * in code that runs on the main thread. */ GtkFileSystemVolume * _gtk_file_system_get_volume_for_file (GtkFileSystem *file_system, GFile *file) diff --git a/gtk/gtkfilesystem.h b/gtk/gtkfilesystem.h index 7fc539ec1..1c3399138 100644 --- a/gtk/gtkfilesystem.h +++ b/gtk/gtkfilesystem.h @@ -130,6 +130,11 @@ void _gtk_file_system_set_bookmark_label (GtkFileSystem *file_system, GFile *file, const gchar *label); +/* Turns the result of g_file_find_enclosing_mount{,_async}() for @file into + * the volume _gtk_file_system_get_volume_for_file() would return. Takes + * ownership of @mount. */ +GtkFileSystemVolume * _gtk_file_system_volume_for_mount (GFile *file, + GMount *mount); GtkFileSystemVolume * _gtk_file_system_get_volume_for_file (GtkFileSystem *file_system, GFile *file); From 5ce6b4c10443dcaf073279a4c847e967f229d568 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:09 +0200 Subject: [PATCH 6/9] gtkfilesystemmodel: read the next batch while integrating the current one The next batch of directory entries was only requested after the current batch had been integrated on the main thread. The enumerator thread idled while the main thread worked, and the main thread waited for I/O afterwards, so I/O and CPU never overlapped. That costs most on slow CPUs, where integrating a batch takes a noticeable share of the time. Now one further batch is requested as soon as fewer than one batch of entries is queued, so at most two batches are in memory. When the enumerator reports the end of the folder (or an error) while entries are still queued, loading finishes once they have been integrated. 100000 local files: 1718 ms instead of 1989 ms until the list is ready. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilesystemmodel.c | 66 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/gtk/gtkfilesystemmodel.c b/gtk/gtkfilesystemmodel.c index 128904a16..2e958492e 100644 --- a/gtk/gtkfilesystemmodel.c +++ b/gtk/gtkfilesystemmodel.c @@ -122,6 +122,11 @@ struct _GtkFileSystemModel GFileEnumerator * dir_enumerator; GCancellable * cancellable; GList * pending_files; + GList * pending_files_tail; + guint n_pending_files; + guint next_files_in_flight : 1; + guint enumeration_done : 1; + GError * enumeration_error; guint drain_source; guint resort_source; @@ -1644,6 +1649,9 @@ gtk_file_system_model_dispose (GObject *object) g_list_free_full (model->pending_files, g_object_unref); model->pending_files = NULL; + model->pending_files_tail = NULL; + model->n_pending_files = 0; + g_clear_error (&model->enumeration_error); g_clear_object (&model->dir_enumerator); @@ -1748,9 +1756,12 @@ static void gtk_file_system_model_request_next_files (GtkFileSystemModel *model) { if (model->dir_enumerator == NULL || + model->next_files_in_flight || + model->enumeration_done || g_cancellable_is_cancelled (model->cancellable)) return; + model->next_files_in_flight = TRUE; g_file_enumerator_next_files_async (model->dir_enumerator, FILES_PER_QUERY, IO_PRIORITY, @@ -1782,6 +1793,16 @@ gtk_file_system_model_drain (gpointer data) model->pending_files = g_list_delete_link (model->pending_files, link); + if (model->pending_files == NULL) + model->pending_files_tail = NULL; + model->n_pending_files--; + + /* Keep the enumerator busy while this batch is integrated: on a + * high-latency share the next batch then arrives while the main + * thread is still working, instead of only being requested once + * the queue ran dry. */ + if (model->n_pending_files < FILES_PER_QUERY) + gtk_file_system_model_request_next_files (model); name = g_file_info_get_name (info); if (name != NULL) @@ -1803,7 +1824,20 @@ gtk_file_system_model_drain (gpointer data) return TRUE; model->drain_source = 0; - gtk_file_system_model_request_next_files (model); + + /* All batches are in and integrated: finish loading. */ + if (model->enumeration_done && model->finalize_phase == MODEL_FINALIZE_NONE && + model->directory_loading) + { + GError *error = model->enumeration_error; + + model->enumeration_error = NULL; + gtk_file_system_model_begin_finalize_load (model, error); + g_clear_error (&error); + } + else + gtk_file_system_model_request_next_files (model); + return FALSE; } @@ -1821,9 +1855,25 @@ gtk_file_system_model_got_files (GObject *object, if (files != NULL) { + GList *tail = g_list_last (files); + gdk_threads_enter (); - g_assert (model->pending_files == NULL); - model->pending_files = files; + model->next_files_in_flight = FALSE; + + if (model->pending_files_tail) + { + model->pending_files_tail->next = files; + files->prev = model->pending_files_tail; + } + else + model->pending_files = files; + model->pending_files_tail = tail; + model->n_pending_files += g_list_length (files); + + /* Read ahead by one batch at most, so memory stays bounded. */ + if (model->n_pending_files < FILES_PER_QUERY) + gtk_file_system_model_request_next_files (model); + gtk_file_system_model_schedule_work (model); gdk_threads_leave (); return; @@ -1833,6 +1883,9 @@ gtk_file_system_model_got_files (GObject *object, { gdk_threads_enter (); + model->next_files_in_flight = FALSE; + model->enumeration_done = TRUE; + g_file_enumerator_close_async (enumerator, IO_PRIORITY, model->cancellable, @@ -1841,7 +1894,12 @@ gtk_file_system_model_got_files (GObject *object, g_clear_object (&model->dir_enumerator); - gtk_file_system_model_begin_finalize_load (model, error); + /* Batches that are still queued must be integrated first. */ + if (model->pending_files == NULL) + gtk_file_system_model_begin_finalize_load (model, error); + else if (error) + model->enumeration_error = g_error_copy (error); + gdk_threads_leave (); } From d5175e2f26472381c5b414ed06928a62579ced3b Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:09 +0200 Subject: [PATCH 7/9] filechooser: show files while a folder is still loading The file list stayed empty until the whole folder had been read, sorted and filtered. On a high-latency NFS share that can take many seconds (20000 files at 1 ms per call: 24 s) with nothing to see. GtkFileSystemModel now commits loaded entries incrementally when asked to (_gtk_file_system_model_set_incremental): - New entries collect in an unsorted tail. The first commit happens after 100 ms, later ones at growing intervals up to once per second. - A commit sorts the tail (resumable bottom-up merge sort) and merges it into the committed, sorted part in one O(n) pass, announcing new rows with row-inserted in ascending order. Both steps run in short main loop slices; between slices, every GtkTreeModel query answers from the merged prefix plus the not yet merged old rows, so views stay consistent. Operations that need one array (editable row, removals, cache clearing) finish a running merge first. - Sorting or filtering changes during loading are applied to the rows already shown; up to two batches are read ahead. - The old loading code was the same sort without the merge, so a folder that is not loaded incrementally takes the same path with a single final commit. The file chooser uses this for the list view and attaches the model right away. GtkIconView inserts rows in O(n), so it keeps getting the model when loading is done (switching views during loading follows this). This also fixes "Create Folder" during loading: it used to put the model on hold while the view had no model, so editing never started and the folder never finished loading. The view now gets the model first. A selection made during loading is no longer replaced by the first row when loading finishes. Invisible nodes without a preceding visible row now report row 0 instead of hitting an assertion. Measured (list view): 20000 files with 1 ms emulated latency: first rows after 0.13 s instead of 24 s; 100000 local files: first rows after 0.14 s, complete after 2.4 s, longest main loop stall 18 ms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilechooserdefault.c | 49 +- gtk/gtkfilesystemmodel.c | 894 ++++++++++++++++++++++++------------ gtk/gtkfilesystemmodel.h | 2 + 3 files changed, 662 insertions(+), 283 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index a9394f9d0..95f962555 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -407,6 +407,7 @@ static void update_cell_renderer_attributes (GtkFileChooserDefault *impl); static void browse_files_center_selected_row (GtkFileChooserDefault *impl); static void view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode); +static void load_set_model (GtkFileChooserDefault *impl); static void visible_range_invalidate (GtkFileChooserDefault *impl); static gboolean visible_range_get (GtkFileChooserDefault *impl, gint *first, @@ -2423,6 +2424,12 @@ new_folder_button_clicked (GtkButton *button, /* Prevent button from being clicked twice */ gtk_widget_set_sensitive (impl->browse_new_folder_button, FALSE); + /* While a folder loads, the icon view does not have the model yet. The + * new row must be editable in the view, otherwise editing never ends and + * the model stays on hold. */ + if (impl->current_model != GTK_TREE_MODEL (impl->browse_files_model)) + load_set_model (impl); + _gtk_file_system_model_add_editable (impl->browse_files_model, &iter); path = gtk_tree_model_get_path (GTK_TREE_MODEL (impl->browse_files_model), &iter); @@ -5604,11 +5611,33 @@ view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode) else g_assert_not_reached (); + /* A folder that is still loading is shown incrementally only in the + * list view (see set_list_model()). */ + if (impl->load_state == LOAD_LOADING && + impl->operation_mode == OPERATION_MODE_BROWSE && + impl->browse_files_model != NULL && + view_mode == VIEW_MODE_ICON && + impl->current_model == GTK_TREE_MODEL (impl->browse_files_model)) + { + _gtk_file_system_model_set_incremental (impl->browse_files_model, FALSE); + impl->current_model = NULL; + } + /* Set model and selection */ current_view_set_file_model (impl, impl->current_model); current_view_set_select_multiple (impl, impl->select_multiple); copy_old_selection_to_current_view (impl, old_view_mode); + if (impl->load_state == LOAD_LOADING && + impl->operation_mode == OPERATION_MODE_BROWSE && + impl->browse_files_model != NULL && + view_mode == VIEW_MODE_LIST && + impl->current_model != GTK_TREE_MODEL (impl->browse_files_model)) + { + _gtk_file_system_model_set_incremental (impl->browse_files_model, TRUE); + load_set_model (impl); + } + /* Destroy the old view */ if (view_mode == VIEW_MODE_ICON) { @@ -7895,8 +7924,11 @@ pending_select_files_process (GtkFileChooserDefault *impl) * that case, the chooser's selection should be what the caller expects, * as the user can't see that something else got selected. See bug #165264. */ + /* The list can be used while the folder loads; keep any selection + * the user made in the meantime. */ if (impl->action == GTK_FILE_CHOOSER_ACTION_OPEN && - gtk_widget_get_mapped (GTK_WIDGET (impl))) + gtk_widget_get_mapped (GTK_WIDGET (impl)) && + current_selection_count_selected_rows (impl) == 0) browse_files_select_first_row (impl); } @@ -7934,7 +7966,11 @@ browse_files_model_finished_loading_cb (GtkFileSystemModel *model, show_error_on_reading_current_folder (impl, error); if (impl->load_state == LOAD_LOADING) - load_set_model (impl); + { + /* The list view already shows the model. */ + if (impl->current_model != GTK_TREE_MODEL (impl->browse_files_model)) + load_set_model (impl); + } else { /* We can't g_assert_not_reached(), as something other than us may have @@ -8464,6 +8500,15 @@ set_list_model (GtkFileChooserDefault *impl, install_list_model_filter (impl); + /* The list shows files while the folder is still loading. GtkIconView + * inserts rows in O(n) each, so it only gets the model once loading is + * done (see browse_files_model_finished_loading_cb). */ + if (impl->view_mode == VIEW_MODE_LIST) + { + _gtk_file_system_model_set_incremental (impl->browse_files_model, TRUE); + load_set_model (impl); + } + profile_end ("end", NULL); return TRUE; diff --git a/gtk/gtkfilesystemmodel.c b/gtk/gtkfilesystemmodel.c index 2e958492e..d9029695f 100644 --- a/gtk/gtkfilesystemmodel.c +++ b/gtk/gtkfilesystemmodel.c @@ -59,6 +59,13 @@ /* random number that everyone else seems to use, too */ #define FILES_PER_QUERY 100 #define MODEL_DRAIN_SLICE_US 2000 +/* Committing announces rows, and every slice that announces rows makes the + * view redraw before the next slice runs. Longer slices (still well below + * one frame) mean far fewer redraws while a large folder is merged. */ +#define MODEL_COMMIT_SLICE_US 8000 +/* Read ahead up to this many entries so the enumerator thread never idles + * while the main thread integrates a batch. */ +#define MODEL_MAX_READ_AHEAD (2 * FILES_PER_QUERY) #define MODEL_DRAIN_CLOCK_GRANULARITY 4 #define MODEL_FINALIZE_CLOCK_GRANULARITY 8 @@ -71,14 +78,27 @@ #define MODEL_MAX_SNIFFS 2 #define MODEL_SNIFFED_ATTRIBUTE "gtk-fsmodel::sniffed" +/* Loading phases (model->finalize_phase). While a folder loads, new + * entries collect in an unsorted tail of model->order. From time to time + * the tail is "committed": sorted (MODEL_PHASE_SORT) and merged into the + * sorted, visible part (MODEL_PHASE_MERGE), announcing new rows in order. + * Both run in short main loop slices. MODEL_PHASE_REPLAY applies the + * changes that arrived while loading and emits ::finished-loading. */ enum { - MODEL_FINALIZE_NONE, - MODEL_FINALIZE_MERGE, - MODEL_FINALIZE_VISIBLE, - MODEL_FINALIZE_REPLAY + MODEL_PHASE_IDLE, + MODEL_PHASE_SORT, + MODEL_PHASE_MERGE, + MODEL_PHASE_REPLAY }; +/* When committing incrementally, the first rows appear after this delay; + * 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) @@ -98,6 +118,7 @@ struct _FileModelNode guint visible :1; guint filtered_out :1; guint held_add :1; + guint merged_epoch :1; /* see model->merge_epoch */ }; typedef struct @@ -141,6 +162,22 @@ struct _GtkFileSystemModel guint finalize_phase; GError * load_error; + /* Incremental loading (see MODEL_PHASE_*) */ + guint committed; /* order[0, committed) is sorted and filtered */ + GArray * tail; /* commit in progress: the new nodes */ + GArray * merge_order; /* merge in progress: new model->order */ + GArray * merge_vis; /* merge in progress: new visible rows */ + guint merge_oi; /* next old node to merge */ + guint merge_ti; /* next tail node to merge */ + guint merge_ovi; /* old visible rows already merged */ + gint64 load_start_time; + gint64 next_commit_time; + gint64 commit_interval; + guint commit_timer; + guint merge_epoch :1; + guint in_merge_step :1; + guint incremental :1; + GQueue * pending_monitor_changes; GHashTable * pending_monitor_queries; @@ -200,11 +237,16 @@ struct _GtkFileSystemModelClass static void gtk_file_system_model_got_files (GObject *object, GAsyncResult *res, gpointer data); -static gboolean gtk_file_system_model_drain (gpointer data); +static gboolean gtk_file_system_model_work (gpointer data); +static void gtk_file_system_model_request_next_files (GtkFileSystemModel *model); +static void gtk_file_system_model_apply_monitor_change (GtkFileSystemModel *model, + GFile *file, + GFileMonitorEvent type); static void gtk_file_system_model_schedule_work (GtkFileSystemModel *model); -static gboolean gtk_file_system_model_finalize_load (gpointer data); -static void gtk_file_system_model_begin_finalize_load (GtkFileSystemModel *model, - GError *error); +static void gtk_file_system_model_enumeration_finished (GtkFileSystemModel *model, + const GError *error); +static void gtk_file_system_model_complete_merge (GtkFileSystemModel *model); +static void gtk_file_system_model_refilter_all (GtkFileSystemModel *model); static void gtk_file_system_model_apply_monitor_change (GtkFileSystemModel *model, GFile *file, GFileMonitorEvent type); @@ -308,23 +350,79 @@ visible_find_order_pos (GtkFileSystemModel *model, return lo; } +/* While a commit merges new nodes into the visible rows, the rows are + * split between two arrays: model->merge_vis holds the already merged + * prefix (in new order), model->visible_order[merge_ovi..] the old rows + * not merged yet. Every query below sees exactly the rows announced so + * far, so listeners stay consistent between merge slices. */ +#define MODEL_MERGING(model) ((model)->merge_vis != NULL) + +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 +model_nth_visible (GtkFileSystemModel *model, + guint n) +{ + if (MODEL_MERGING (model)) + { + if (n < model->merge_vis->len) + return g_array_index (model->merge_vis, guint, n); + + 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); +} + +/* Row of a visible node. */ +static guint +node_visible_row (GtkFileSystemModel *model, + FileModelNode *node) +{ + if (MODEL_MERGING (model) && node->merged_epoch != model->merge_epoch) + return node->visible_pos - model->merge_ovi + model->merge_vis->len; + + return node->visible_pos; +} + static GtkTreePath * tree_path_new_from_node (GtkFileSystemModel *model, guint id) { FileModelNode *node = get_node (model, id); - guint row = G_MAXUINT; + guint row = 0; if (node->visible) - row = node->visible_pos; + row = node_visible_row (model, node); + else if (MODEL_MERGING (model) && model->in_merge_step) + { + /* Asked from a handler of a row we are announcing: there is no + * meaningful row for an invisible node yet. */ + row = model_n_visible (model) > 0 ? model_n_visible (model) - 1 : 0; + } else if (id != 0) { - guint pos = visible_find_order_pos (model, node->order_pos, TRUE); + guint pos; + + if (MODEL_MERGING (model)) + gtk_file_system_model_complete_merge (model); + + /* Invisible nodes report the closest preceding visible row. */ + pos = visible_find_order_pos (model, node->order_pos, TRUE); if (pos > 0) row = pos - 1; } - g_assert (row != G_MAXUINT); return gtk_tree_path_new_from_indices (row, -1); } @@ -528,6 +626,9 @@ node_set_visible_and_filtered_out (GtkFileSystemModel *model, { FileModelNode *node = get_node (model, id); + if (MODEL_MERGING (model)) + gtk_file_system_model_complete_merge (model); + if (node->filtered_out != filtered_out) { node->filtered_out = filtered_out; @@ -843,10 +944,13 @@ gtk_file_system_model_iter_nth_child (GtkTreeModel *tree_model, g_return_val_if_fail (n >= 0, FALSE); - if (parent != NULL || (guint) n >= model->visible_order->len) + if (parent != NULL) + return FALSE; + + id = model_nth_visible (model, n); + if (id == G_MAXUINT) return FALSE; - id = g_array_index (model->visible_order, guint, n); ITER_INIT_FROM_INDEX (model, iter, id); return TRUE; } @@ -905,24 +1009,32 @@ gtk_file_system_model_iter_next (GtkTreeModel *tree_model, { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model); FileModelNode *node; - guint pos; + guint pos, id; g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE); node = get_node (model, ITER_INDEX (iter)); if (node->visible) - pos = node->visible_pos + 1; + pos = node_visible_row (model, node) + 1; else if (ITER_INDEX (iter) != 0) - pos = visible_find_order_pos (model, node->order_pos, TRUE); + { + if (MODEL_MERGING (model)) + { + if (model->in_merge_step) + return FALSE; + gtk_file_system_model_complete_merge (model); + } + pos = visible_find_order_pos (model, node->order_pos, TRUE); + } else return FALSE; - if (pos >= model->visible_order->len) + id = model_nth_visible (model, pos); + if (id == G_MAXUINT) return FALSE; - ITER_INIT_FROM_INDEX (model, iter, - g_array_index (model->visible_order, guint, pos)); + ITER_INIT_FROM_INDEX (model, iter, id); return TRUE; } @@ -950,7 +1062,7 @@ gtk_file_system_model_iter_n_children (GtkTreeModel *tree_model, if (iter) return 0; - return model->visible_order->len; + return model_n_visible (model); } static gboolean @@ -1110,6 +1222,7 @@ gtk_file_system_model_sort (GtkFileSystemModel *model) if (model->directory_loading || model->editing_hold) { model->resort_pending = TRUE; + gtk_file_system_model_schedule_work (model); return; } @@ -1336,10 +1449,21 @@ pending_monitor_change_free (gpointer data) g_free (change); } +/* ---- Incremental loading ---------------------------------------------- */ + +static gboolean +deadline_passed (gint64 deadline, + guint *counter, + guint granularity) +{ + return (++(*counter) % granularity) == 0 && g_get_monotonic_time () >= deadline; +} + +/* Bottom-up merge sort of model->tail, resumable between main loop slices. */ static void gtk_file_system_model_prepare_merge (GtkFileSystemModel *model) { - guint n = model->order->len; + guint n = model->tail->len; model->sort_mid = MIN (model->sort_left + model->sort_width, n); model->sort_right = MIN (model->sort_left + 2 * model->sort_width, n); @@ -1349,273 +1473,513 @@ gtk_file_system_model_prepare_merge (GtkFileSystemModel *model) } static void -gtk_file_system_model_prepare_visible (GtkFileSystemModel *model) +gtk_file_system_model_merge_init (GtkFileSystemModel *model) { FileModelNode *editable = get_node (model, 0); - g_array_set_size (model->visible_order, 0); + model->finalize_phase = MODEL_PHASE_MERGE; + 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->tail->len); + model->merge_oi = 0; + model->merge_ti = 0; + model->merge_ovi = 0; + model->merge_epoch = !model->merge_epoch; + + /* The editable row, if any, stays first. */ if (editable->visible) { guint id = 0; + g_assert (g_array_index (model->visible_order, guint, 0) == 0); + g_array_append_val (model->merge_vis, id); editable->visible_pos = 0; - g_array_append_val (model->visible_order, id); + editable->merged_epoch = model->merge_epoch; + model->merge_ovi = 1; } - - model->sort_left = 0; - model->finalize_phase = MODEL_FINALIZE_VISIBLE; - model->refilter_pending = FALSE; } static void -gtk_file_system_model_restart_initial_sort (GtkFileSystemModel *model) +gtk_file_system_model_apply_pending_resort_refilter (GtkFileSystemModel *model) { SortData data; - guint n = model->order->len; + guint i; - model->resort_pending = FALSE; + /* Only the committed part is visible; the tail is sorted and filtered + * when it is committed. */ + if (model->resort_pending) + { + model->resort_pending = FALSE; + if (model->committed > 1 && sort_data_init (&data, model)) + { + _gtk_sort_array (model->order->data, model->committed, sizeof (guint), + compare_order_element, &data); + order_update_positions_from (model, 0); + visible_order_rebuild_after_sort (model); + } + } - if (sort_data_init (&data, model)) + if (model->refilter_pending) + { + model->refilter_pending = FALSE; + for (i = 0; i < model->committed; i++) + node_compute_visibility_and_filters (model, g_array_index (model->order, guint, i)); + } +} + +static void +gtk_file_system_model_start_commit (GtkFileSystemModel *model) +{ + SortData data; + guint n; + + g_assert (model->finalize_phase == MODEL_PHASE_IDLE); + + gtk_file_system_model_apply_pending_resort_refilter (model); + + n = model->order->len - model->committed; + model->tail = g_array_sized_new (FALSE, FALSE, sizeof (guint), n); + g_array_append_vals (model->tail, + &g_array_index (model->order, guint, model->committed), n); + + if (n > 1 && sort_data_init (&data, model)) { if (model->sort_scratch == NULL) - model->sort_scratch = - g_array_sized_new (FALSE, FALSE, sizeof (guint), n); + model->sort_scratch = g_array_sized_new (FALSE, FALSE, sizeof (guint), n); g_array_set_size (model->sort_scratch, n); model->sort_width = 1; model->sort_left = 0; gtk_file_system_model_prepare_merge (model); - model->finalize_phase = MODEL_FINALIZE_MERGE; + model->finalize_phase = MODEL_PHASE_SORT; } else - gtk_file_system_model_prepare_visible (model); + gtk_file_system_model_merge_init (model); +} + +/* Returns TRUE once the tail is sorted. */ +static gboolean +gtk_file_system_model_commit_sort_step (GtkFileSystemModel *model, + gint64 deadline) +{ + SortData data; + guint processed = 0; + guint n = model->tail->len; + + if (!sort_data_init (&data, model)) + { + gtk_file_system_model_merge_init (model); + return TRUE; + } + + 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_order_element (&g_array_index (model->tail, guint, model->sort_i), + &g_array_index (model->tail, guint, model->sort_j), + &data) <= 0)) + id = g_array_index (model->tail, guint, model->sort_i++); + else + id = g_array_index (model->tail, guint, model->sort_j++); + + g_array_index (model->sort_scratch, guint, model->sort_k++) = id; + + if (deadline_passed (deadline, &processed, MODEL_FINALIZE_CLOCK_GRANULARITY)) + return FALSE; + } + + model->sort_left = model->sort_right; + if (model->sort_left < n) + { + gtk_file_system_model_prepare_merge (model); + continue; + } + + /* Pass complete: the scratch buffer becomes the tail. */ + { + GArray *tmp = model->tail; + + model->tail = model->sort_scratch; + model->sort_scratch = tmp; + } + + if (model->sort_width >= n / 2 + n % 2) + break; + + model->sort_width *= 2; + model->sort_left = 0; + gtk_file_system_model_prepare_merge (model); + } + + g_clear_pointer (&model->sort_scratch, g_array_unref); + gtk_file_system_model_merge_init (model); + return TRUE; +} + +/* Merges the sorted tail into the committed nodes, announcing each new + * visible row at its final position. Returns TRUE when done. */ +static gboolean +gtk_file_system_model_commit_merge_step (GtkFileSystemModel *model, + gint64 deadline) +{ + SortData data; + gboolean have_sort; + guint processed = 0; + + have_sort = sort_data_init (&data, model); + + while (model->merge_oi < model->committed || model->merge_ti < model->tail->len) + { + gboolean from_tail; + FileModelNode *node; + guint id; + + if (model->merge_ti >= model->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_order_element (&g_array_index (model->tail, guint, model->merge_ti), + &g_array_index (model->order, guint, model->merge_oi), + &data) < 0; + + id = from_tail ? g_array_index (model->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) + { + if (node->visible) + { + g_assert (g_array_index (model->visible_order, guint, model->merge_ovi) == id); + model->merge_ovi++; + g_array_append_val (model->merge_vis, id); + node->visible_pos = model->merge_vis->len - 1; + } + } + else + { + node->filtered_out = node_should_be_filtered_out (model, id); + node->visible = node_should_be_visible (model, id, node->filtered_out); + + if (node->visible) + { + GtkTreePath *path; + GtkTreeIter iter; + + g_array_append_val (model->merge_vis, id); + node->visible_pos = model->merge_vis->len - 1; + + path = gtk_tree_path_new_from_indices (node->visible_pos, -1); + ITER_INIT_FROM_INDEX (model, &iter, id); + model->in_merge_step = TRUE; + gtk_tree_model_row_inserted (GTK_TREE_MODEL (model), path, &iter); + model->in_merge_step = FALSE; + gtk_tree_path_free (path); + } + } + + if (deadline_passed (deadline, &processed, MODEL_FINALIZE_CLOCK_GRANULARITY)) + return FALSE; + } + + 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; + + g_clear_pointer (&model->tail, g_array_unref); + model->committed = model->order->len; + model->finalize_phase = MODEL_PHASE_IDLE; + + model->next_commit_time = g_get_monotonic_time () + model->commit_interval; + model->commit_interval = MIN (model->commit_interval * 2, MODEL_MAX_COMMIT_INTERVAL_US); + + return TRUE; +} + +/* Finishes a commit in progress right away. Used before operations that + * need a single, consistent visible array. */ +static void +gtk_file_system_model_complete_merge (GtkFileSystemModel *model) +{ + g_return_if_fail (!model->in_merge_step); + + if (model->finalize_phase == MODEL_PHASE_SORT) + gtk_file_system_model_commit_sort_step (model, G_MAXINT64); + if (model->finalize_phase == MODEL_PHASE_MERGE) + gtk_file_system_model_commit_merge_step (model, G_MAXINT64); +} + +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; +} + +static gboolean +gtk_file_system_model_commit_due (GtkFileSystemModel *model) +{ + return model->incremental && + model->order->len > model->committed && + g_get_monotonic_time () >= model->next_commit_time; +} + +/* Waiting for the enumerator: make sure queued entries still show up. */ +static void +gtk_file_system_model_arm_commit_timer (GtkFileSystemModel *model) +{ + gint64 delay; + + if (!model->incremental || model->commit_timer != 0 || + model->order->len == model->committed) + return; + + 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); } static void gtk_file_system_model_schedule_work (GtkFileSystemModel *model) { - GSourceFunc func; - if (model->drain_source != 0 || model->editing_hold) return; - if (model->pending_files != NULL) - func = gtk_file_system_model_drain; - else if (model->finalize_phase != MODEL_FINALIZE_NONE) - func = gtk_file_system_model_finalize_load; - else + if (model->pending_files == NULL && + model->finalize_phase == MODEL_PHASE_IDLE && + !(model->directory_loading && + (model->enumeration_done || model->order->len > model->committed || + model->resort_pending || model->refilter_pending))) return; model->drain_source = gdk_threads_add_idle_full (G_PRIORITY_DEFAULT_IDLE, - func, + gtk_file_system_model_work, g_object_ref (model), g_object_unref); } +/* Called when the enumerator reports the end of the folder or an error. */ static void -gtk_file_system_model_begin_finalize_load (GtkFileSystemModel *model, - GError *error) +gtk_file_system_model_enumeration_finished (GtkFileSystemModel *model, + const GError *error) { - g_assert (model->directory_loading); - g_assert (model->finalize_phase == MODEL_FINALIZE_NONE); - g_assert (model->pending_files == NULL); + model->enumeration_done = TRUE; + g_clear_error (&model->enumeration_error); + if (error) + model->enumeration_error = g_error_copy (error); - g_clear_error (&model->load_error); - model->load_error = error ? g_error_copy (error) : NULL; - - gtk_file_system_model_restart_initial_sort (model); gtk_file_system_model_schedule_work (model); } +/* Integrates queued directory entries until @deadline. New nodes go to + * the unsorted tail of model->order (see add_file()). */ static gboolean -gtk_file_system_model_finalize_load (gpointer data) +gtk_file_system_model_drain_some (GtkFileSystemModel *model, + gint64 deadline) { - GtkFileSystemModel *model = data; - gint64 deadline = g_get_monotonic_time () + MODEL_DRAIN_SLICE_US; guint processed = 0; - if (model->editing_hold && model->directory_loading) + while (model->pending_files != NULL) + { + GList *link = model->pending_files; + GFileInfo *info = link->data; + const char *name; + + model->pending_files = + g_list_delete_link (model->pending_files, link); + if (model->pending_files == NULL) + model->pending_files_tail = NULL; + model->n_pending_files--; + + /* Keep the enumerator busy while this batch is integrated: on a + * high-latency share the next batch then arrives while the main + * thread is still working, instead of only being requested once + * the queue ran dry. */ + if (model->n_pending_files < MODEL_MAX_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); + add_file (model, file, info); + g_object_unref (file); + } + + g_object_unref (info); + + if (deadline_passed (deadline, &processed, MODEL_DRAIN_CLOCK_GRANULARITY)) + return FALSE; + } + + return TRUE; +} + +/* Applies what arrived while loading and announces the end of loading. + * Returns TRUE when done. */ +static gboolean +gtk_file_system_model_replay_step (GtkFileSystemModel *model, + gint64 deadline) +{ + guint processed = 0; + + while (model->sniffed_during_load != NULL) + { + GFile *file = model->sniffed_during_load->data; + guint sniffed_id = node_get_for_file (model, file); + + model->sniffed_during_load = + g_slist_delete_link (model->sniffed_during_load, + model->sniffed_during_load); + if (sniffed_id != 0) + node_compute_visibility_and_filters (model, sniffed_id); + g_object_unref (file); + } + + while (model->pending_monitor_changes != NULL && + !g_queue_is_empty (model->pending_monitor_changes)) + { + PendingMonitorChange *change; + + change = g_queue_pop_head (model->pending_monitor_changes); + + gtk_file_system_model_apply_monitor_change (model, + change->file, + change->type); + pending_monitor_change_free (change); + + if (deadline_passed (deadline, &processed, MODEL_DRAIN_CLOCK_GRANULARITY)) + return FALSE; + } + + model->finalize_phase = MODEL_PHASE_IDLE; + + g_signal_emit (model, + file_system_model_signals[FINISHED_LOADING], + 0, model->load_error); + g_clear_error (&model->load_error); + + return TRUE; +} + +static gboolean +gtk_file_system_model_work (gpointer data) +{ + GtkFileSystemModel *model = data; + gint64 now = g_get_monotonic_time (); + gint64 deadline = now + MODEL_DRAIN_SLICE_US; + gint64 commit_deadline = now + MODEL_COMMIT_SLICE_US; + + if (model->editing_hold) { model->drain_source = 0; return FALSE; } - if (model->resort_pending) - gtk_file_system_model_restart_initial_sort (model); - while (TRUE) { - guint n = model->order->len; - - if (model->finalize_phase == MODEL_FINALIZE_MERGE) + switch (model->finalize_phase) { - SortData data; + case MODEL_PHASE_SORT: + if (!gtk_file_system_model_commit_sort_step (model, commit_deadline)) + return TRUE; + continue; - if (!sort_data_init (&data, model)) - { - gtk_file_system_model_prepare_visible (model); - continue; - } + case MODEL_PHASE_MERGE: + if (!gtk_file_system_model_commit_merge_step (model, commit_deadline)) + return TRUE; + continue; - while (model->sort_k < model->sort_right) - { - guint id; + case MODEL_PHASE_REPLAY: + if (!gtk_file_system_model_replay_step (model, deadline)) + return TRUE; + model->drain_source = 0; + return FALSE; - if (model->sort_i < model->sort_mid && - (model->sort_j >= model->sort_right || - compare_order_element - (&g_array_index (model->order, guint, model->sort_i), - &g_array_index (model->order, guint, model->sort_j), - &data) <= 0)) - id = g_array_index (model->order, guint, model->sort_i++); - else - id = g_array_index (model->order, guint, model->sort_j++); + default: + break; + } - g_array_index (model->sort_scratch, guint, model->sort_k++) = id; + if (!model->directory_loading) + break; - if ((++processed % MODEL_FINALIZE_CLOCK_GRANULARITY) == 0 && - g_get_monotonic_time () >= deadline) - return TRUE; - } + if (g_get_monotonic_time () >= deadline) + return TRUE; - model->sort_left = model->sort_right; - if (model->sort_left < n) - { - gtk_file_system_model_prepare_merge (model); - continue; - } - - /* Make the completed pass canonical and reuse the old buffer. */ - { - GArray *tmp = model->order; - - model->order = model->sort_scratch; - model->sort_scratch = tmp; - } - - if (model->resort_pending) - { - gtk_file_system_model_restart_initial_sort (model); - continue; - } - - if (model->sort_width >= n / 2 + n % 2) - { - gtk_file_system_model_prepare_visible (model); - continue; - } - - model->sort_width *= 2; - model->sort_left = 0; - gtk_file_system_model_prepare_merge (model); + if (gtk_file_system_model_commit_due (model)) + { + gtk_file_system_model_start_commit (model); continue; } - if (model->finalize_phase == MODEL_FINALIZE_VISIBLE) + if (model->pending_files != NULL) { - if (model->refilter_pending) - gtk_file_system_model_prepare_visible (model); - - while (model->sort_left < n) - { - guint pos = model->sort_left++; - guint id = g_array_index (model->order, guint, pos); - FileModelNode *node = get_node (model, id); - gboolean filtered_out; - gboolean visible; - - node->order_pos = pos; - filtered_out = node_should_be_filtered_out (model, id); - visible = node_should_be_visible (model, id, filtered_out); - - node->filtered_out = filtered_out; - node->visible = visible; - - if (visible) - { - node->visible_pos = model->visible_order->len; - g_array_append_val (model->visible_order, id); - } - - if ((++processed % MODEL_FINALIZE_CLOCK_GRANULARITY) == 0 && - g_get_monotonic_time () >= deadline) - return TRUE; - } - - if (model->resort_pending) - { - gtk_file_system_model_restart_initial_sort (model); - continue; - } - - if (model->refilter_pending) - { - gtk_file_system_model_prepare_visible (model); - continue; - } - - model->directory_loading = FALSE; - model->refilter_pending = FALSE; - model->resort_pending = FALSE; - g_clear_pointer (&model->sort_scratch, g_array_unref); - - model->finalize_phase = MODEL_FINALIZE_REPLAY; - if (g_get_monotonic_time () >= deadline) + if (!gtk_file_system_model_drain_some (model, deadline)) return TRUE; continue; } - if (model->finalize_phase == MODEL_FINALIZE_REPLAY) + if (model->enumeration_done) { - while (model->sniffed_during_load != NULL) + if (model->order->len > model->committed) { - GFile *file = model->sniffed_during_load->data; - guint sniffed_id = node_get_for_file (model, file); - - model->sniffed_during_load = - g_slist_delete_link (model->sniffed_during_load, - model->sniffed_during_load); - if (sniffed_id != 0) - node_compute_visibility_and_filters (model, sniffed_id); - g_object_unref (file); + gtk_file_system_model_start_commit (model); + continue; } - while (model->pending_monitor_changes != NULL && - !g_queue_is_empty (model->pending_monitor_changes)) + /* Everything is committed: loading is done. */ + model->directory_loading = FALSE; + if (model->commit_timer != 0) { - PendingMonitorChange *change; - - change = g_queue_pop_head (model->pending_monitor_changes); - - gtk_file_system_model_apply_monitor_change (model, - change->file, - change->type); - pending_monitor_change_free (change); - - if ((++processed % MODEL_DRAIN_CLOCK_GRANULARITY) == 0 && - g_get_monotonic_time () >= deadline) - return TRUE; + g_source_remove (model->commit_timer); + model->commit_timer = 0; } + if (model->resort_pending) + gtk_file_system_model_sort (model); + if (model->refilter_pending) + gtk_file_system_model_refilter_all (model); - model->finalize_phase = MODEL_FINALIZE_NONE; - model->drain_source = 0; - - g_signal_emit (model, - file_system_model_signals[FINISHED_LOADING], - 0, model->load_error); g_clear_error (&model->load_error); - - return FALSE; + model->load_error = model->enumeration_error; + model->enumeration_error = NULL; + model->finalize_phase = MODEL_PHASE_REPLAY; + continue; } - g_assert_not_reached (); + /* Waiting for the enumerator. Apply a sort or filter change to the + * rows already shown, and show queued entries when they are due. */ + if (model->resort_pending || model->refilter_pending) + gtk_file_system_model_apply_pending_resort_refilter (model); + gtk_file_system_model_arm_commit_timer (model); + break; } + + model->drain_source = 0; + return FALSE; } - - - 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) @@ -1641,6 +2005,12 @@ gtk_file_system_model_dispose (GObject *object) model->resort_source = 0; } + if (model->commit_timer != 0) + { + g_source_remove (model->commit_timer); + model->commit_timer = 0; + } + g_cancellable_cancel (model->cancellable); g_clear_pointer (&model->pending_monitor_queries, g_hash_table_destroy); @@ -1676,6 +2046,9 @@ gtk_file_system_model_finalize (GObject *object) g_clear_pointer (&model->files, g_array_unref); g_clear_pointer (&model->sort_scratch, g_array_unref); + g_clear_pointer (&model->tail, g_array_unref); + g_clear_pointer (&model->merge_order, g_array_unref); + g_clear_pointer (&model->merge_vis, g_array_unref); g_clear_error (&model->load_error); if (model->pending_monitor_changes) g_queue_free_full (model->pending_monitor_changes, @@ -1770,76 +2143,6 @@ gtk_file_system_model_request_next_files (GtkFileSystemModel *model) model); } -static gboolean -gtk_file_system_model_drain (gpointer data) -{ - GtkFileSystemModel *model = data; - gint64 deadline; - guint processed = 0; - - if (model->editing_hold) - { - model->drain_source = 0; - return FALSE; - } - - deadline = g_get_monotonic_time () + MODEL_DRAIN_SLICE_US; - - while (model->pending_files != NULL) - { - GList *link = model->pending_files; - GFileInfo *info = link->data; - const char *name; - - model->pending_files = - g_list_delete_link (model->pending_files, link); - if (model->pending_files == NULL) - model->pending_files_tail = NULL; - model->n_pending_files--; - - /* Keep the enumerator busy while this batch is integrated: on a - * high-latency share the next batch then arrives while the main - * thread is still working, instead of only being requested once - * the queue ran dry. */ - if (model->n_pending_files < FILES_PER_QUERY) - 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); - add_file (model, file, info); - g_object_unref (file); - } - - g_object_unref (info); - processed++; - - if ((processed % MODEL_DRAIN_CLOCK_GRANULARITY) == 0 && - g_get_monotonic_time () >= deadline) - break; - } - - if (model->pending_files != NULL) - return TRUE; - - model->drain_source = 0; - - /* All batches are in and integrated: finish loading. */ - if (model->enumeration_done && model->finalize_phase == MODEL_FINALIZE_NONE && - model->directory_loading) - { - GError *error = model->enumeration_error; - - model->enumeration_error = NULL; - gtk_file_system_model_begin_finalize_load (model, error); - g_clear_error (&error); - } - else - gtk_file_system_model_request_next_files (model); - - return FALSE; -} static void gtk_file_system_model_got_files (GObject *object, @@ -1870,8 +2173,8 @@ gtk_file_system_model_got_files (GObject *object, model->pending_files_tail = tail; model->n_pending_files += g_list_length (files); - /* Read ahead by one batch at most, so memory stays bounded. */ - if (model->n_pending_files < FILES_PER_QUERY) + /* Read ahead, but keep memory bounded. */ + if (model->n_pending_files < MODEL_MAX_READ_AHEAD) gtk_file_system_model_request_next_files (model); gtk_file_system_model_schedule_work (model); @@ -1894,11 +2197,8 @@ gtk_file_system_model_got_files (GObject *object, g_clear_object (&model->dir_enumerator); - /* Batches that are still queued must be integrated first. */ - if (model->pending_files == NULL) - gtk_file_system_model_begin_finalize_load (model, error); - else if (error) - model->enumeration_error = g_error_copy (error); + /* Queued batches are integrated before loading finishes. */ + gtk_file_system_model_enumeration_finished (model, error); gdk_threads_leave (); } @@ -2081,7 +2381,7 @@ gtk_file_system_model_got_enumerator (GObject *object, if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { gdk_threads_enter (); - gtk_file_system_model_begin_finalize_load (model, error); + gtk_file_system_model_enumeration_finished (model, error); gdk_threads_leave (); } @@ -2160,6 +2460,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->load_start_time = g_get_monotonic_time (); + model->next_commit_time = model->load_start_time + MODEL_FIRST_COMMIT_US; + model->commit_interval = MODEL_COMMIT_INTERVAL_US; g_file_enumerate_children_async (model->dir, attributes, @@ -2270,6 +2573,7 @@ gtk_file_system_model_refilter_all (GtkFileSystemModel *model) if (model->directory_loading || model->editing_hold) { model->refilter_pending = TRUE; + gtk_file_system_model_schedule_work (model); return; } @@ -2377,6 +2681,26 @@ _gtk_file_system_model_set_filter_folders (GtkFileSystemModel *model, } } +/** + * _gtk_file_system_model_set_incremental: + * @model: a #GtkFileSystemModel + * @incremental: whether to show files while the folder is still loading + * + * If %TRUE, rows appear while the folder loads: entries are sorted and + * merged into the model at growing intervals (first after 100 ms, then up + * to once per second). Otherwise all rows appear at the end. Views + * whose row insertion is expensive should not use incremental mode. + **/ +void +_gtk_file_system_model_set_incremental (GtkFileSystemModel *model, + gboolean incremental) +{ + g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); + + model->incremental = incremental != FALSE; + gtk_file_system_model_schedule_work (model); +} + /** * _gtk_file_system_model_get_cancellable: * @model: the model @@ -2708,6 +3032,9 @@ remove_file (GtkFileSystemModel *model, if (id == 0) return; + if (MODEL_MERGING (model)) + gtk_file_system_model_complete_merge (model); + node = get_node (model, id); was_visible = node->visible; @@ -2879,6 +3206,8 @@ _gtk_file_system_model_clear_cache (GtkFileSystemModel *model, } /* Emit at most one change signal for each visible row, in row order. */ + if (MODEL_MERGING (model)) + gtk_file_system_model_complete_merge (model); for (i = 0; i < model->visible_order->len; i++) { guint id = g_array_index (model->visible_order, guint, i); @@ -2975,6 +3304,9 @@ _gtk_file_system_model_add_editable (GtkFileSystemModel *model, g_return_if_fail (iter != NULL); g_return_if_fail (!get_node (model, 0)->visible); + /* A commit in progress must not be paused half way. */ + gtk_file_system_model_complete_merge (model); + node_set_visible_and_filtered_out (model, 0, TRUE, FALSE); ITER_INIT_FROM_INDEX (model, iter, 0); diff --git a/gtk/gtkfilesystemmodel.h b/gtk/gtkfilesystemmodel.h index 4bdda0c23..6ea413901 100644 --- a/gtk/gtkfilesystemmodel.h +++ b/gtk/gtkfilesystemmodel.h @@ -53,6 +53,8 @@ GtkFileSystemModel *_gtk_file_system_model_new_for_directory(GFile * guint n_columns, ...); GCancellable * _gtk_file_system_model_get_cancellable (GtkFileSystemModel *model); +void _gtk_file_system_model_set_incremental (GtkFileSystemModel *model, + gboolean incremental); gboolean _gtk_file_system_model_iter_is_visible (GtkFileSystemModel *model, GtkTreeIter *iter); gboolean _gtk_file_system_model_iter_is_filtered_out (GtkFileSystemModel *model, From 3ebf5c36894675053a6d637030a68322cd45ab69 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:10 +0200 Subject: [PATCH 8/9] filechooser: schedule icon queries for visible rows, newest first Each row that became visible started its own icon/thumbnail query right away, without limit and without cancellation. Scrolling through a large folder queued hundreds of queries in GIO's shared thread pool; rows scrolled past were still served before the rows now on screen. On a hung network share every such query blocks a pool thread, so after some scrolling even listing a different folder had to wait for free threads. Icon queries now go through a small scheduler: - at most 16 queries run at a time (enough to serve a screenful in one round on a high-latency share, see below), further requests wait; - waiting requests are served newest first, so rows on screen win over rows that were scrolled past; - after scrolling (coalesced per main loop iteration) waiting requests for rows more than one page away are dropped and running ones are cancelled; such rows are queried again when they are shown; - the queue holds at most 256 requests, and requests end when their model goes away (weak reference) or the chooser is disposed. With 20 ms emulated latency per file system call, the visible rows after fast scrolling get their icons as quickly as before (51 ms); lower limits of 4 or 8 parallel queries made that 152 ms and 102 ms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilechooserdefault.c | 299 ++++++++++++++++++++++++++++++++---- gtk/gtkfilechooserprivate.h | 5 + 2 files changed, 272 insertions(+), 32 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 95f962555..c2ded85dc 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -408,6 +408,7 @@ static void browse_files_center_selected_row (GtkFileChooserDefault *impl); static void view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode); static void load_set_model (GtkFileChooserDefault *impl); +static void icon_requests_cancel_all (GtkFileChooserDefault *impl); static void visible_range_invalidate (GtkFileChooserDefault *impl); static gboolean visible_range_get (GtkFileChooserDefault *impl, gint *first, @@ -7129,6 +7130,8 @@ cancel_all_operations (GtkFileChooserDefault *impl) g_clear_object (&impl->shortcuts_current_folder_cancellable); } + icon_requests_cancel_all (impl); + search_stop_searching (impl, TRUE); recent_stop_loading (impl); } @@ -8137,44 +8140,281 @@ copy_attribute (GFileInfo *to, GFileInfo *from, const char *attribute) g_file_info_set_attribute (to, attribute, type, value); } -static void -file_system_model_got_thumbnail (GObject *object, GAsyncResult *res, gpointer data) +/* Icons and thumbnail paths are queried lazily, only for rows that are + * (nearly) visible. At most ICON_REQUESTS_MAX_RUNNING queries run at a + * time and the newest request is served first, so after scrolling the rows + * on screen get their icons before rows that were passed over. Requests + * for rows that left the view are dropped or cancelled, which matters on + * slow shares where each query takes a while. */ +#define ICON_REQUESTS_MAX_RUNNING 16 +#define ICON_REQUESTS_MAX_QUEUED 256 +#define ICON_QUERIED_ATTRIBUTE "filechooser::icon_queried" + +typedef struct +{ + GtkFileChooserDefault *impl; /* owns a reference */ + GtkFileSystemModel *model; /* weak; NULL once the model is disposed */ + GFile *file; + GCancellable *cancellable; +} IconRequest; + +static void icon_requests_pump (GtkFileChooserDefault *impl); + +static void +icon_request_model_gone (gpointer data, + GObject *where_the_model_was) +{ + IconRequest *req = data; + + req->model = NULL; + g_cancellable_cancel (req->cancellable); +} + +static void +icon_request_free (IconRequest *req) +{ + if (req->model) + g_object_weak_unref (G_OBJECT (req->model), icon_request_model_gone, req); + g_object_unref (req->cancellable); + g_object_unref (req->file); + g_object_unref (req->impl); + g_slice_free (IconRequest, req); +} + +/* Allows the row to be queried again later. */ +static void +icon_request_forget (IconRequest *req) { - GtkFileSystemModel *model = data; /* might be unreffed if operation was cancelled */ - GFile *file = G_FILE (object); - GFileInfo *queried, *info; GtkTreeIter iter; + if (req->model && + _gtk_file_system_model_get_iter_for_file (req->model, &iter, req->file)) + { + GFileInfo *info = _gtk_file_system_model_get_info (req->model, &iter); + + if (info) + g_file_info_remove_attribute (info, ICON_QUERIED_ATTRIBUTE); + } +} + +static void +icon_request_done (GObject *object, + GAsyncResult *res, + gpointer data) +{ + IconRequest *req = data; + GtkFileChooserDefault *impl = req->impl; + GFile *file = G_FILE (object); + GFileInfo *queried; + queried = g_file_query_info_finish (file, res, NULL); - if (queried == NULL) - return; GDK_THREADS_ENTER (); - /* now we know model is valid */ + impl->icon_requests_running = g_list_remove (impl->icon_requests_running, req); - /* file was deleted */ - if (!_gtk_file_system_model_get_iter_for_file (model, &iter, file)) + if (req->model == NULL) + ; + else if (g_cancellable_is_cancelled (req->cancellable) || queried == NULL) { - g_object_unref (queried); - GDK_THREADS_LEAVE (); - return; + /* Cancelled because the row left the view: query again when it is + * shown. Failed queries are not repeated. */ + if (g_cancellable_is_cancelled (req->cancellable)) + icon_request_forget (req); + } + else + { + GtkTreeIter iter; + + /* The file may have been removed meanwhile. */ + if (_gtk_file_system_model_get_iter_for_file (req->model, &iter, file)) + { + GFileInfo *info; + + info = g_file_info_dup (_gtk_file_system_model_get_info (req->model, &iter)); + + copy_attribute (info, queried, G_FILE_ATTRIBUTE_THUMBNAIL_PATH); + copy_attribute (info, queried, G_FILE_ATTRIBUTE_THUMBNAILING_FAILED); + copy_attribute (info, queried, G_FILE_ATTRIBUTE_STANDARD_ICON); + + _gtk_file_system_model_update_file (req->model, file, info); + + g_object_unref (info); + } } - info = g_file_info_dup (_gtk_file_system_model_get_info (model, &iter)); + if (queried) + g_object_unref (queried); - copy_attribute (info, queried, G_FILE_ATTRIBUTE_THUMBNAIL_PATH); - copy_attribute (info, queried, G_FILE_ATTRIBUTE_THUMBNAILING_FAILED); - copy_attribute (info, queried, G_FILE_ATTRIBUTE_STANDARD_ICON); + icon_request_free (req); - _gtk_file_system_model_update_file (model, file, info); - - g_object_unref (info); - g_object_unref (queried); + if (impl->icon_requests) + icon_requests_pump (impl); GDK_THREADS_LEAVE (); } +static void +icon_requests_pump (GtkFileChooserDefault *impl) +{ + while (g_list_length (impl->icon_requests_running) < ICON_REQUESTS_MAX_RUNNING && + !g_queue_is_empty (impl->icon_requests)) + { + IconRequest *req = g_queue_pop_head (impl->icon_requests); + + if (req->model == NULL) + { + icon_request_free (req); + continue; + } + + impl->icon_requests_running = g_list_prepend (impl->icon_requests_running, req); + g_file_query_info_async (req->file, + G_FILE_ATTRIBUTE_THUMBNAIL_PATH "," + G_FILE_ATTRIBUTE_THUMBNAILING_FAILED "," + G_FILE_ATTRIBUTE_STANDARD_ICON, + G_FILE_QUERY_INFO_NONE, + G_PRIORITY_DEFAULT, + req->cancellable, + icon_request_done, + req); + } +} + +static void +icon_request_add (GtkFileChooserDefault *impl, + GtkFileSystemModel *model, + GFile *file) +{ + IconRequest *req; + + if (impl->icon_requests == NULL) + impl->icon_requests = g_queue_new (); + + req = g_slice_new (IconRequest); + req->impl = g_object_ref (impl); + req->model = model; + req->file = g_object_ref (file); + req->cancellable = g_cancellable_new (); + g_object_weak_ref (G_OBJECT (model), icon_request_model_gone, req); + + g_queue_push_head (impl->icon_requests, req); + + /* Bound the queue; the oldest requests are the least likely to still + * be on screen. */ + while (g_queue_get_length (impl->icon_requests) > ICON_REQUESTS_MAX_QUEUED) + { + IconRequest *old = g_queue_pop_tail (impl->icon_requests); + + icon_request_forget (old); + icon_request_free (old); + } + + icon_requests_pump (impl); +} + +/* Is the row of @req's file within the visible rows plus one page? */ +static gboolean +icon_request_still_wanted (GtkFileChooserDefault *impl, + IconRequest *req) +{ + GtkTreeIter iter; + GtkTreePath *path; + gint first, last, margin, row; + + if (req->model == NULL || + GTK_TREE_MODEL (req->model) != impl->current_model || + !_gtk_file_system_model_get_iter_for_file (req->model, &iter, req->file)) + return FALSE; + + if (!visible_range_get (impl, &first, &last)) + return TRUE; + + path = gtk_tree_model_get_path (impl->current_model, &iter); + row = gtk_tree_path_get_indices (path)[0]; + gtk_tree_path_free (path); + + margin = last - first + 1; + return row >= first - margin && row <= last + margin; +} + +static gboolean +icon_requests_prune_cb (gpointer data) +{ + GtkFileChooserDefault *impl = data; + GList *l, *next; + + GDK_THREADS_ENTER (); + + impl->icon_requests_prune_id = 0; + + if (impl->icon_requests) + { + for (l = impl->icon_requests->head; l; l = next) + { + IconRequest *req = l->data; + + next = l->next; + if (!icon_request_still_wanted (impl, req)) + { + icon_request_forget (req); + g_queue_delete_link (impl->icon_requests, l); + icon_request_free (req); + } + } + } + + for (l = impl->icon_requests_running; l; l = l->next) + { + IconRequest *req = l->data; + + if (!icon_request_still_wanted (impl, req)) + g_cancellable_cancel (req->cancellable); + } + + GDK_THREADS_LEAVE (); + + return FALSE; +} + +static void +icon_requests_queue_prune (GtkFileChooserDefault *impl) +{ + if (impl->icon_requests_prune_id != 0) + return; + + if ((impl->icon_requests == NULL || g_queue_is_empty (impl->icon_requests)) && + impl->icon_requests_running == NULL) + return; + + /* Coalesce all scroll events of one main loop iteration. */ + impl->icon_requests_prune_id = + gdk_threads_add_idle_full (G_PRIORITY_DEFAULT_IDLE, + icon_requests_prune_cb, impl, NULL); +} + +static void +icon_requests_cancel_all (GtkFileChooserDefault *impl) +{ + GList *l; + + if (impl->icon_requests_prune_id != 0) + { + g_source_remove (impl->icon_requests_prune_id); + impl->icon_requests_prune_id = 0; + } + + if (impl->icon_requests) + { + g_queue_free_full (impl->icon_requests, (GDestroyNotify) icon_request_free); + impl->icon_requests = NULL; + } + + /* Running requests free themselves when they complete. */ + for (l = impl->icon_requests_running; l; l = l->next) + g_cancellable_cancel (((IconRequest *) l->data)->cancellable); +} + static gboolean get_visible_range (GtkTreePath **start, GtkTreePath **end, GtkFileChooserDefault *impl) @@ -8232,11 +8472,14 @@ visible_range_get (GtkFileChooserDefault *impl, return TRUE; } +static void icon_requests_queue_prune (GtkFileChooserDefault *impl); + static void visible_range_adjustment_cb (GtkAdjustment *adjustment, GtkFileChooserDefault *impl) { visible_range_invalidate (impl); + icon_requests_queue_prune (impl); } static void @@ -8366,18 +8609,10 @@ file_system_model_set (GtkFileSystemModel *model, if (file_visible) { /* #2 start loading standard icon (callback will be handled by #1) */ - if (!g_file_info_has_attribute (info, "filechooser::icon_queried")) + if (!g_file_info_has_attribute (info, ICON_QUERIED_ATTRIBUTE)) { - g_file_info_set_attribute_boolean (info, "filechooser::icon_queried", TRUE); - g_file_query_info_async (file, - G_FILE_ATTRIBUTE_THUMBNAIL_PATH "," - G_FILE_ATTRIBUTE_THUMBNAILING_FAILED "," - G_FILE_ATTRIBUTE_STANDARD_ICON, - G_FILE_QUERY_INFO_NONE, - G_PRIORITY_DEFAULT, - _gtk_file_system_model_get_cancellable (model), - file_system_model_got_thumbnail, - model); + g_file_info_set_attribute_boolean (info, ICON_QUERIED_ATTRIBUTE, TRUE); + icon_request_add (impl, model, file); } } return FALSE; diff --git a/gtk/gtkfilechooserprivate.h b/gtk/gtkfilechooserprivate.h index b5963b4d4..7c42010b8 100644 --- a/gtk/gtkfilechooserprivate.h +++ b/gtk/gtkfilechooserprivate.h @@ -240,6 +240,11 @@ struct _GtkFileChooserDefault gint visible_range_first; gint visible_range_last; guint visible_range_valid : 1; + + /* Icon/thumbnail queries for visible rows (see icon_request_add) */ + GQueue *icon_requests; /* waiting, newest first */ + GList *icon_requests_running; + guint icon_requests_prune_id; gint icon_view_scale_visible_overscan; ViewMode view_mode; From d666cf3f03f952547f569ff85fb3784a75b9d757 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 12:48:10 +0200 Subject: [PATCH 9/9] gtkfilesystem: bound the shared file icon cache The per-icon-theme pixbuf cache used for themed file icons was never evicted, so zooming through the icon view kept a rendered copy of every icon at every size alive for the lifetime of the process. Keep it as an LRU instead: at most 64 entries and 4 MiB of pixel data, least recently used entries are dropped first, and the whole cache is still cleared when the icon theme changes. 64 entries comfortably hold the icons of one folder at two zoom levels, so scrolling and zooming keep hitting the cache while memory stays bounded on small machines. Valgrind zoom stress (icon view, all zoom levels, folder switches) reports no errors in the new code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F6aiMGWu4tXHcuSSC9DHi2 --- gtk/gtkfilesystem.c | 117 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 103 insertions(+), 14 deletions(-) diff --git a/gtk/gtkfilesystem.c b/gtk/gtkfilesystem.c index 6234f2879..ec7167343 100644 --- a/gtk/gtkfilesystem.c +++ b/gtk/gtkfilesystem.c @@ -1639,18 +1639,105 @@ file_icon_cache_key_free (FileIconCacheKey *key) g_slice_free (FileIconCacheKey, key); } -static void -file_icon_cache_theme_changed_cb (GtkIconTheme *icon_theme, - GHashTable *cache) +/* The cache is bounded (least recently used entries go first) so zooming + * through many icon sizes does not keep every rendered size alive. */ +#define FILE_ICON_CACHE_MAX_ENTRIES 64 +#define FILE_ICON_CACHE_MAX_BYTES (4 * 1024 * 1024) + +typedef struct { - g_hash_table_remove_all (cache); + GHashTable *table; /* FileIconCacheKey -> FileIconCacheEntry */ + GQueue lru; /* keys, most recently used first */ + gsize bytes; +} FileIconCache; + +typedef struct +{ + GdkPixbuf *pixbuf; + GList *link; /* in FileIconCache.lru */ + gsize bytes; +} FileIconCacheEntry; + +static void +file_icon_cache_entry_free (FileIconCacheEntry *entry) +{ + g_object_unref (entry->pixbuf); + g_slice_free (FileIconCacheEntry, entry); } -static GHashTable * +static void +file_icon_cache_free (FileIconCache *cache) +{ + g_queue_clear (&cache->lru); + g_hash_table_destroy (cache->table); + g_slice_free (FileIconCache, cache); +} + +static void +file_icon_cache_theme_changed_cb (GtkIconTheme *icon_theme, + FileIconCache *cache) +{ + g_queue_clear (&cache->lru); + g_hash_table_remove_all (cache->table); + cache->bytes = 0; +} + +static GdkPixbuf * +file_icon_cache_lookup (FileIconCache *cache, + const FileIconCacheKey *key) +{ + FileIconCacheEntry *entry = g_hash_table_lookup (cache->table, key); + + if (entry == NULL) + return NULL; + + /* Mark as most recently used. */ + g_queue_unlink (&cache->lru, entry->link); + g_queue_push_head_link (&cache->lru, entry->link); + + return entry->pixbuf; +} + +static void +file_icon_cache_insert (FileIconCache *cache, + FileIconCacheKey *key, + GdkPixbuf *pixbuf) +{ + FileIconCacheEntry *entry; + + /* g_hash_table_insert() would free @key and keep the old one, leaving a + * dangling pointer in the LRU queue; keep the existing entry instead. */ + if (g_hash_table_lookup (cache->table, key) != NULL) + { + file_icon_cache_key_free (key); + return; + } + + entry = g_slice_new (FileIconCacheEntry); + entry->pixbuf = g_object_ref (pixbuf); + entry->bytes = (gsize) gdk_pixbuf_get_rowstride (pixbuf) * gdk_pixbuf_get_height (pixbuf); + g_queue_push_head (&cache->lru, key); + entry->link = cache->lru.head; + g_hash_table_insert (cache->table, key, entry); + cache->bytes += entry->bytes; + + while (cache->lru.length > 1 && + (cache->lru.length > FILE_ICON_CACHE_MAX_ENTRIES || + cache->bytes > FILE_ICON_CACHE_MAX_BYTES)) + { + FileIconCacheKey *old_key = g_queue_pop_tail (&cache->lru); + FileIconCacheEntry *old = g_hash_table_lookup (cache->table, old_key); + + cache->bytes -= old->bytes; + g_hash_table_remove (cache->table, old_key); + } +} + +static FileIconCache * file_icon_cache_get_for_icon_theme (GtkIconTheme *icon_theme) { static GQuark quark_file_icon_cache = 0; - GHashTable *cache; + FileIconCache *cache; if (G_UNLIKELY (quark_file_icon_cache == 0)) quark_file_icon_cache = g_quark_from_static_string ("gtk-file-icon-cache"); @@ -1658,14 +1745,16 @@ file_icon_cache_get_for_icon_theme (GtkIconTheme *icon_theme) cache = g_object_get_qdata (G_OBJECT (icon_theme), quark_file_icon_cache); if (!cache) { - cache = g_hash_table_new_full (file_icon_cache_key_hash, - file_icon_cache_key_equal, - (GDestroyNotify) file_icon_cache_key_free, - g_object_unref); + cache = g_slice_new0 (FileIconCache); + cache->table = g_hash_table_new_full (file_icon_cache_key_hash, + file_icon_cache_key_equal, + (GDestroyNotify) file_icon_cache_key_free, + (GDestroyNotify) file_icon_cache_entry_free); + g_queue_init (&cache->lru); g_object_set_qdata_full (G_OBJECT (icon_theme), quark_file_icon_cache, cache, - (GDestroyNotify) g_hash_table_destroy); + (GDestroyNotify) file_icon_cache_free); g_signal_connect (icon_theme, "changed", G_CALLBACK (file_icon_cache_theme_changed_cb), @@ -1684,7 +1773,7 @@ get_pixbuf_from_gicon (GIcon *icon, GdkScreen *screen; GtkIconTheme *icon_theme; GtkIconInfo *icon_info; - GHashTable *cache; + FileIconCache *cache; FileIconCacheKey lookup_key; FileIconCacheKey *cache_key; GdkPixbuf *pixbuf; @@ -1708,7 +1797,7 @@ get_pixbuf_from_gicon (GIcon *icon, lookup_key.icon = icon; lookup_key.icon_size = icon_size; - pixbuf = g_hash_table_lookup (cache, &lookup_key); + pixbuf = file_icon_cache_lookup (cache, &lookup_key); if (pixbuf) return g_object_ref (pixbuf); } @@ -1734,7 +1823,7 @@ get_pixbuf_from_gicon (GIcon *icon, if (cache) { cache_key = file_icon_cache_key_new (screen, icon, icon_size); - g_hash_table_insert (cache, cache_key, g_object_ref (pixbuf)); + file_icon_cache_insert (cache, cache_key, pixbuf); } return pixbuf;