From 2d8c88972db6fb3a12f73e5cac48bf451a8537ef Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 15:37:12 +0200 Subject: [PATCH 01/12] filechooser: create the icon view zoom scale on demand --- gtk/gtkfilechooserdefault.c | 98 +++++++++++++++++++++---------------- gtk/gtkfilechooserprivate.h | 4 +- 2 files changed, 57 insertions(+), 45 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 2ce2d6c8f..35f305945 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -410,6 +410,7 @@ static void load_remove_timer (GtkFileChooserDefault *impl, LoadState new_load_s static void browse_files_center_selected_row (GtkFileChooserDefault *impl); static void view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode); +static void icon_view_scale_create (GtkFileChooserDefault *impl); static void view_mode_combo_box_changed_cb (GtkComboBox *combo, GtkFileChooserDefault *impl); @@ -5214,6 +5215,14 @@ view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode) /* Creating the target view */ if (view_mode == VIEW_MODE_ICON) { + /* The zoom scale is only needed once the icon view is used. */ + if (!impl->icon_view_scale_hbox) + { + icon_view_scale_create (impl); + gtk_box_pack_end (GTK_BOX (impl->browse_path_bar_hbox), + impl->icon_view_scale_hbox, FALSE, FALSE, 0); + } + create_browse_files_icon_view (impl); impl->browse_files_current_view = impl->browse_files_icon_view; old_view = impl->browse_files_tree_view; @@ -5246,7 +5255,8 @@ view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode) impl->browse_files_icon_view = NULL; impl->list_icon_renderer = NULL; impl->list_name_renderer = NULL; - gtk_widget_hide (impl->icon_view_scale_hbox); + if (impl->icon_view_scale_hbox) + gtk_widget_hide (impl->icon_view_scale_hbox); } else g_assert_not_reached (); @@ -5714,51 +5724,55 @@ view_mode_combo_box_create (GtkFileChooserDefault *impl) G_CALLBACK (view_mode_combo_box_changed_cb), impl); } +/* Creates one of the clickable zoom icons next to the icon view scale. */ +static GtkWidget * +icon_view_zoom_icon_new (GtkFileChooserDefault *impl, + const gchar *stock_id, + gint direction, + const gchar *tooltip) +{ + GtkWidget *event_box; + GtkWidget *image; + + event_box = gtk_event_box_new (); + gtk_event_box_set_visible_window (GTK_EVENT_BOX (event_box), FALSE); + image = gtk_image_new_from_stock (stock_id, GTK_ICON_SIZE_BUTTON); + gtk_container_add (GTK_CONTAINER (event_box), image); + gtk_widget_show (image); + g_object_set_data (G_OBJECT (event_box), + "gtk-file-chooser-zoom-direction", + GINT_TO_POINTER (direction)); + gtk_widget_set_tooltip_text (event_box, tooltip); + g_signal_connect (event_box, "button-press-event", + G_CALLBACK (icon_view_zoom_button_press_cb), impl); + gtk_size_group_add_widget (impl->browse_path_bar_size_group, event_box); + gtk_widget_show (event_box); + + return event_box; +} + /* Creates a hscale for the icon view. */ static void icon_view_scale_create (GtkFileChooserDefault *impl) { GtkObject *adj; - GtkWidget *image; impl->icon_view_scale_hbox = gtk_hbox_new (FALSE, 12); - impl->icon_view_scale_zoom_out_icon = gtk_event_box_new (); - gtk_event_box_set_visible_window (GTK_EVENT_BOX (impl->icon_view_scale_zoom_out_icon), FALSE); - image = gtk_image_new_from_stock (GTK_STOCK_ZOOM_OUT, GTK_ICON_SIZE_BUTTON); - gtk_container_add (GTK_CONTAINER (impl->icon_view_scale_zoom_out_icon), image); - gtk_widget_show (image); - g_object_set_data (G_OBJECT (impl->icon_view_scale_zoom_out_icon), - "gtk-file-chooser-zoom-direction", - GINT_TO_POINTER (-1)); - gtk_widget_set_tooltip_text (impl->icon_view_scale_zoom_out_icon, _("Zoom out")); - g_signal_connect (impl->icon_view_scale_zoom_out_icon, "button-press-event", - G_CALLBACK (icon_view_zoom_button_press_cb), impl); - gtk_size_group_add_widget (impl->browse_path_bar_size_group, impl->icon_view_scale_zoom_out_icon); - gtk_box_pack_start (GTK_BOX (impl->icon_view_scale_hbox), impl->icon_view_scale_zoom_out_icon, FALSE, FALSE, 0); - gtk_widget_show (impl->icon_view_scale_zoom_out_icon); + gtk_box_pack_start (GTK_BOX (impl->icon_view_scale_hbox), + icon_view_zoom_icon_new (impl, GTK_STOCK_ZOOM_OUT, -1, _("Zoom out")), + FALSE, FALSE, 0); - adj = gtk_adjustment_new (32, 32, 256, 16, 16, 0); + adj = gtk_adjustment_new (impl->icon_view_icon_size, 32, 256, 16, 16, 0); impl->icon_view_scale = gtk_hscale_new (GTK_ADJUSTMENT (adj)); gtk_scale_set_draw_value (GTK_SCALE (impl->icon_view_scale), FALSE); gtk_widget_set_size_request (impl->icon_view_scale, 100, -1); gtk_box_pack_start (GTK_BOX (impl->icon_view_scale_hbox), impl->icon_view_scale, FALSE, FALSE, 0); gtk_widget_show (impl->icon_view_scale); - impl->icon_view_scale_zoom_in_icon = gtk_event_box_new (); - gtk_event_box_set_visible_window (GTK_EVENT_BOX (impl->icon_view_scale_zoom_in_icon), FALSE); - image = gtk_image_new_from_stock (GTK_STOCK_ZOOM_IN, GTK_ICON_SIZE_BUTTON); - gtk_container_add (GTK_CONTAINER (impl->icon_view_scale_zoom_in_icon), image); - gtk_widget_show (image); - g_object_set_data (G_OBJECT (impl->icon_view_scale_zoom_in_icon), - "gtk-file-chooser-zoom-direction", - GINT_TO_POINTER (1)); - gtk_widget_set_tooltip_text (impl->icon_view_scale_zoom_in_icon, _("Zoom in")); - g_signal_connect (impl->icon_view_scale_zoom_in_icon, "button-press-event", - G_CALLBACK (icon_view_zoom_button_press_cb), impl); - gtk_size_group_add_widget (impl->browse_path_bar_size_group, impl->icon_view_scale_zoom_in_icon); - gtk_box_pack_start (GTK_BOX (impl->icon_view_scale_hbox), impl->icon_view_scale_zoom_in_icon, FALSE, FALSE, 0); - gtk_widget_show (impl->icon_view_scale_zoom_in_icon); + gtk_box_pack_start (GTK_BOX (impl->icon_view_scale_hbox), + icon_view_zoom_icon_new (impl, GTK_STOCK_ZOOM_IN, 1, _("Zoom in")), + FALSE, FALSE, 0); g_signal_connect (impl->icon_view_scale, "value-changed", G_CALLBACK (icon_view_scale_value_changed_cb), impl); @@ -5908,10 +5922,6 @@ path_bar_widgets_create (GtkFileChooserDefault *impl) /* Widgets for special modes (recently-used in Open mode, Search mode) */ special_mode_widgets_create (impl); - /* Icon view scale */ - icon_view_scale_create (impl); - gtk_box_pack_end (GTK_BOX (impl->browse_path_bar_hbox), impl->icon_view_scale_hbox, FALSE, FALSE, 0); - /* Create Folder */ impl->browse_new_folder_button = gtk_button_new_with_mnemonic (_("Create Fo_lder")); g_signal_connect (impl->browse_new_folder_button, "clicked", @@ -7043,13 +7053,17 @@ settings_load (GtkFileChooserDefault *impl) location_mode_set (impl, location_mode, TRUE); - g_signal_handlers_block_by_func (impl->icon_view_scale, - G_CALLBACK (icon_view_scale_value_changed_cb), - impl); - gtk_range_set_value (GTK_RANGE (impl->icon_view_scale), icon_view_scale); - g_signal_handlers_unblock_by_func (impl->icon_view_scale, - G_CALLBACK (icon_view_scale_value_changed_cb), - impl); + /* The scale may not exist yet; it is created with icon_view_icon_size. */ + if (impl->icon_view_scale) + { + g_signal_handlers_block_by_func (impl->icon_view_scale, + G_CALLBACK (icon_view_scale_value_changed_cb), + impl); + gtk_range_set_value (GTK_RANGE (impl->icon_view_scale), icon_view_scale); + g_signal_handlers_unblock_by_func (impl->icon_view_scale, + G_CALLBACK (icon_view_scale_value_changed_cb), + impl); + } view_mode_set (impl, view_mode); diff --git a/gtk/gtkfilechooserprivate.h b/gtk/gtkfilechooserprivate.h index 193dea2e3..22f8fc0fa 100644 --- a/gtk/gtkfilechooserprivate.h +++ b/gtk/gtkfilechooserprivate.h @@ -228,10 +228,8 @@ struct _GtkFileChooserDefault GtkWidget *extra_widget; GtkWidget *view_mode_combo_box; - GtkWidget *icon_view_scale_hbox; + GtkWidget *icon_view_scale_hbox; /* created when the icon view is first used */ GtkWidget *icon_view_scale; - GtkWidget *icon_view_scale_zoom_in_icon; - GtkWidget *icon_view_scale_zoom_out_icon; guint icon_view_scale_timeout_id; guint icon_view_scale_visible_timeout_id; guint icon_view_scale_after_layout_id; From 810008f25e8cf550917548e4d702c4b3900609fd Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 13:08:31 +0200 Subject: [PATCH 02/12] filechooser: add "Copy Location" to the context menu --- gtk/gtkfilechooserdefault.c | 61 +++++++++++++++++++++++++++++++++++++ gtk/gtkfilechooserprivate.h | 1 + 2 files changed, 62 insertions(+) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 35f305945..796c2c200 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -3938,6 +3938,7 @@ popup_menu_detach_cb (GtkWidget *attach_widget, impl->browse_files_popup_menu = NULL; impl->browse_files_popup_menu_add_shortcut_item = NULL; + impl->browse_files_popup_menu_copy_location_item = NULL; impl->browse_files_popup_menu_hidden_files_item = NULL; } @@ -3949,6 +3950,54 @@ add_to_shortcuts_cb (GtkMenuItem *item, bookmarks_add_selected_folder (impl); } +static void +copy_location_foreach_cb (GtkTreeModel *model, + GtkTreePath *path, + GtkTreeIter *iter, + gpointer data) +{ + GString *locations = data; + GFile *file; + gchar *location; + + gtk_tree_model_get (model, iter, MODEL_COL_FILE, &file, -1); + if (file == NULL) + return; + + /* Prefer a local path; fall back to the URI for remote files. */ + location = g_file_get_path (file); + if (location == NULL) + location = g_file_get_uri (file); + + if (location != NULL) + { + if (locations->len != 0) + g_string_append_c (locations, '\n'); + g_string_append (locations, location); + g_free (location); + } + + g_object_unref (file); +} + +/* Callback used when the "Copy Location" menu item is activated: puts the + * locations of the selected files on the clipboard, one per line. */ +static void +copy_location_cb (GtkMenuItem *item, + GtkFileChooserDefault *impl) +{ + GString *locations = g_string_new (NULL); + + current_selection_selected_foreach (impl, copy_location_foreach_cb, locations); + + if (locations->len != 0) + gtk_clipboard_set_text (gtk_widget_get_clipboard (impl->browse_files_current_view, + GDK_SELECTION_CLIPBOARD), + locations->str, locations->len); + + g_string_free (locations, TRUE); +} + /* Callback used when the "Show Hidden Files" menu item is toggled */ static void show_hidden_toggled_cb (GtkCheckMenuItem *item, @@ -4298,6 +4347,15 @@ file_list_build_popup_menu (GtkFileChooserDefault *impl) gtk_widget_show (item); gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item); + item = gtk_image_menu_item_new_with_mnemonic (_("_Copy Location")); + impl->browse_files_popup_menu_copy_location_item = item; + gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), + gtk_image_new_from_stock (GTK_STOCK_COPY, GTK_ICON_SIZE_MENU)); + g_signal_connect (item, "activate", + G_CALLBACK (copy_location_cb), impl); + gtk_widget_show (item); + gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item); + item = gtk_separator_menu_item_new (); gtk_widget_show (item); gtk_menu_shell_append (GTK_MENU_SHELL (impl->browse_files_popup_menu), item); @@ -4391,6 +4449,9 @@ file_list_update_popup_menu (GtkFileChooserDefault *impl) * bookmarks_check_add_sensitivity() */ + gtk_widget_set_sensitive (impl->browse_files_popup_menu_copy_location_item, + current_selection_count_selected_rows (impl) > 0); + /* 'Show Hidden Files' */ g_signal_handlers_block_by_func (impl->browse_files_popup_menu_hidden_files_item, G_CALLBACK (show_hidden_toggled_cb), impl); diff --git a/gtk/gtkfilechooserprivate.h b/gtk/gtkfilechooserprivate.h index 22f8fc0fa..46bf0a604 100644 --- a/gtk/gtkfilechooserprivate.h +++ b/gtk/gtkfilechooserprivate.h @@ -182,6 +182,7 @@ struct _GtkFileChooserDefault GtkWidget *browse_files_icon_view; GtkWidget *browse_files_popup_menu; GtkWidget *browse_files_popup_menu_add_shortcut_item; + GtkWidget *browse_files_popup_menu_copy_location_item; GtkWidget *browse_files_popup_menu_hidden_files_item; GtkWidget *browse_files_popup_menu_size_column_item; GtkWidget *browse_files_popup_menu_sort_by_name_item; From 0663c0f616518f105649347a86cb5665e3fbebe7 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 13:09:51 +0200 Subject: [PATCH 03/12] filechooser: select the row under the pointer on right click --- gtk/gtkfilechooserdefault.c | 41 +++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 796c2c200..346c8b573 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -4584,20 +4584,43 @@ list_popup_menu_cb (GtkWidget *widget, */ static gboolean list_button_press_event_cb (GtkWidget *widget, - GdkEventButton *event, - GtkFileChooserDefault *impl) + GdkEventButton *event, + GtkFileChooserDefault *impl) { - static gboolean in_press = FALSE; - - if (in_press) - return FALSE; + GtkTreePath *path = NULL; if (!_gtk_button_event_triggers_context_menu (event)) return FALSE; - in_press = TRUE; - gtk_widget_event (widget, (GdkEvent *) event); - in_press = FALSE; + gtk_widget_grab_focus (widget); + + /* As in file managers: a right click on a row that is not selected + * selects just that row and moves the cursor there; on a selected row + * the selection is kept, so the menu acts on all selected files. */ + if (GTK_IS_TREE_VIEW (widget)) + { + GtkTreeView *tree_view = GTK_TREE_VIEW (widget); + + if (gtk_tree_view_get_path_at_pos (tree_view, event->x, event->y, + &path, NULL, NULL, NULL) && + !gtk_tree_selection_path_is_selected (gtk_tree_view_get_selection (tree_view), path)) + gtk_tree_view_set_cursor (tree_view, path, NULL, FALSE); + } + else + { + GtkIconView *icon_view = GTK_ICON_VIEW (widget); + + path = gtk_icon_view_get_path_at_pos (icon_view, event->x, event->y); + if (path && !gtk_icon_view_path_is_selected (icon_view, path)) + { + gtk_icon_view_unselect_all (icon_view); + gtk_icon_view_select_path (icon_view, path); + gtk_icon_view_set_cursor (icon_view, path, NULL, FALSE); + } + } + + if (path) + gtk_tree_path_free (path); file_list_popup_menu (impl, event); return TRUE; From 76887647a12241a34d0d3a9dfe24883e85e5d4ca Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 13:53:28 +0200 Subject: [PATCH 04/12] gtkfilesystemmodel: keep nodes by stable ID and show files while loading Files go to an unsorted tail and are merged into the sorted rows in short slices, so a folder shows up while it is still loading. Filtering and sorting run in the background as well; _gtk_file_system_model_flush() brings the rows up to date where the chooser needs them right away. --- gtk/gtkfilechooserdefault.c | 11 +- gtk/gtkfilesystemmodel.c | 2307 +++++++++++++++++++++++++---------- gtk/gtkfilesystemmodel.h | 1 + 3 files changed, 1644 insertions(+), 675 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 346c8b573..b3e3cdab4 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -7586,6 +7586,10 @@ show_and_select_files (GtkFileChooserDefault *impl, g_assert (fsmodel == impl->browse_files_model); + /* The model adds files and filters in the background; the visibility + * checks below need the rows as they are now. */ + _gtk_file_system_model_flush (fsmodel); + enabled_hidden = impl->show_hidden; removed_filters = (impl->current_filter == NULL); @@ -7616,6 +7620,7 @@ show_and_select_files (GtkFileChooserDefault *impl, if (!enabled_hidden && (is_hidden || is_backup)) { g_object_set (impl, "show-hidden", TRUE, NULL); + _gtk_file_system_model_flush (fsmodel); enabled_hidden = TRUE; } } @@ -7631,6 +7636,7 @@ show_and_select_files (GtkFileChooserDefault *impl, if (!removed_filters) { set_current_filter (impl, NULL); + _gtk_file_system_model_flush (fsmodel); removed_filters = TRUE; } } @@ -8185,7 +8191,10 @@ set_list_model (GtkFileChooserDefault *impl, gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_SIZE, size_sort_func, impl, NULL); gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), MODEL_COL_MTIME, mtime_sort_func, impl, NULL); gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (impl->browse_files_model), NULL, NULL, NULL); - set_sort_column (impl); + /* Sort from the start: the model sorts files as it adds them, while + * resorting rows that are already shown takes extra work. */ + gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (impl->browse_files_model), + impl->sort_column, impl->sort_order); impl->list_sort_ascending = TRUE; g_signal_connect (impl->browse_files_model, "sort-column-changed", G_CALLBACK (list_sort_column_changed_cb), impl); diff --git a/gtk/gtkfilesystemmodel.c b/gtk/gtkfilesystemmodel.c index 52fd17a08..16bc2b81e 100644 --- a/gtk/gtkfilesystemmodel.c +++ b/gtk/gtkfilesystemmodel.c @@ -36,89 +36,58 @@ /*** Structure: how GtkFileSystemModel works * - * This is a custom GtkTreeModel used to hold a collection of files for GtkFileChooser. There are two use cases: + * This is a custom GtkTreeModel used to hold a collection of files for + * GtkFileChooser. There are two use cases: * - * 1. The model populates itself from a folder, using the GIO file enumerator API. This happens if you use - * _gtk_file_system_model_new_for_directory(). This is the normal usage for showing the contents of a folder. + * 1. The model populates itself from a folder, using the GIO file + * enumerator API. This happens if you use + * _gtk_file_system_model_new_for_directory(). * - * 2. The caller populates the model by hand, with files not necessarily in the same folder. This happens - * if you use _gtk_file_system_model_new() and then _gtk_file_system_model_add_and_query_file(). This is - * the special kind of usage for "search" and "recent-files", where the file chooser gives the model the - * files to be displayed. + * 2. The caller populates the model by hand, with files not necessarily + * in the same folder ("search" and "recent files"), using + * _gtk_file_system_model_new() and + * _gtk_file_system_model_add_and_query_file(). * - * Internal data structure - * ----------------------- + * Nodes + * ----- * - * Each file is kept in a FileModelNode structure. Each FileModelNode holds a GFile* and other data. All the - * node structures have the same size, determined at runtime, depending on the number of columns that were passed - * to _gtk_file_system_model_new() or _gtk_file_system_model_new_for_directory() (that is, the size of a node is - * not sizeof (FileModelNode), but rather model->node_size). The last field in the FileModelNode structure, - * node->values[], is an array of GValue, used to hold the data for those columns. + * Every file has a FileModelNode in model->files. A node keeps its slot + * (its "ID") for its whole life, so iterators stay valid while rows move; + * a generation number in the iterator detects reused slots. Slot 0 is the + * placeholder row of _gtk_file_system_model_add_editable(). + * model->file_lookup maps each GFile to its ID. * - * The model stores an array of FileModelNode structures in model->files. This is a GArray where each element is - * model->node_size bytes in size (the model computes that node size when initializing itself). There are - * convenience macros, get_node() and node_index(), to access that array based on an array index or a pointer to - * a node inside the array. + * Column values are cached in pages of 64 IDs that are only allocated for + * columns that are actually read, so unused columns cost no memory. * - * The model accesses files through two of its fields: + * Order and rows + * -------------- * - * model->files - GArray of FileModelNode structures. + * model->order lists the IDs in sort order. Its first model->committed + * entries are sorted and filtered; the GtkTreeModel rows are the visible + * ones among them, listed in model->visible_order. Everything after them + * is the "tail": files that were added but are not part of the rows yet. * - * model->file_lookup - hash table that maps a GFile* to an index inside the model->files array. + * All changes to the rows happen in one idle handler (see + * gtk_file_system_model_work()), in short slices so the user interface + * stays responsive on slow machines: * - * The model->file_lookup hash table is populated lazily. It is both accessed and populated with the - * node_get_for_file() function. The invariant is that the files in model->files[n] for n < g_hash_table_size - * (model->file_lookup) are already added to the hash table. The hash table will get cleared when we re-sort the - * files, as the array will be in a different order and the indexes need to be rebuilt. + * - A commit sorts the tail and merges it into the committed part, + * announcing each new row at its final position. While a folder + * loads, commits come at growing intervals; otherwise right away. + * This is the only way rows are added, whether the files come from + * the enumerator, the folder monitor or a query. A commit can also + * filter all committed nodes again (show hidden files, filter change). + * - A resort sorts the committed IDs and applies the new order at once. + * - Removing a file, moving a file whose information changed and + * filtering a single file again are queued per node and done between + * commits. * - * Each FileModelNode has a node->visible field, which indicates whether the node is visible in the GtkTreeView. - * A node may be invisible if, for example, it corresponds to a hidden file and the file chooser is not showing - * hidden files. Also, a file filter may be explicitly set onto the model, for example, to only show files that - * match "*.jpg". In this case, node->filtered_out says whether the node failed the filter. The ultimate - * decision on whether a node is visible or not in the treeview is distilled into the node->visible field. - * The reason for having a separate node->filtered_out field is so that the file chooser can query whether - * a (filtered-out) folder should be made sensitive in the GUI. + * Merges keep the model consistent between slices: the rows announced so + * far are model->merge_vis, followed by the old rows not merged yet. * - * Visible rows vs. possibly-invisible nodes - * ----------------------------------------- - * - * Since not all nodes in the model->files array may be visible, we need a way to map visible row indexes from - * the treeview to array indexes in our array of files. And thus we introduce a bit of terminology: - * - * index - An index in the model->files array. All variables/fields that represent indexes are either called - * "index" or "i_*", or simply "i" for things like loop counters. - * - * row - An index in the GtkTreeView, i.e. the index of a row within the outward-facing API of the - * GtkFileSystemModel. However, note that our rows are 1-based, not 0-based, for the reason explained in the - * following paragraph. Variables/fields that represent visible rows are called "row", or "r_*", or simply - * "r". - * - * Each FileModelNode has a node->row field which is the number of visible rows in the treeview, *before and - * including* that node. This means that node->row is 1-based, instead of 0-based --- this makes some code - * simpler, believe it or not :) This also means that when the calling GtkTreeView gives us a GtkTreePath, we - * turn the 0-based treepath into a 1-based row for our purposes. If a node is not visible, it will have the - * same row number as its closest preceding visible node. - * - * We try to compute the node->row fields lazily. A node is said to be "valid" if its node->row is accurate. - * For this, the model keeps a model->n_nodes_valid field which is the count of valid nodes starting from the - * beginning of the model->files array. When a node changes its information, or when a node gets deleted, that - * node and the following ones get invalidated by simply setting model->n_nodes_valid to the array index of the - * node. If the model happens to need a node's row number and that node is in the model->files array after - * model->n_nodes_valid, then the nodes get re-validated up to the sought node. See node_validate_rows() for - * this logic. - * - * You never access a node->row directly. Instead, call node_get_tree_row(). That function will validate the nodes - * up to the sought one if the node is not valid yet, and it will return a proper 0-based row. - * - * Sorting - * ------- - * - * The model implements the GtkTreeSortable interface. To avoid re-sorting - * every time a node gets added (which would lead to O(n^2) performance during - * the initial population of the model), the model can freeze itself (with - * freeze_updates()) during the intial population process. When the model is - * frozen, sorting will not happen. The model will sort itself when the freeze - * count goes back to zero, via corresponding calls to thaw_updates(). + * Editing (the placeholder row) holds all of this, so the rows do not + * change under the user. */ /*** DEFINES ***/ @@ -131,47 +100,121 @@ /* random number that everyone else seems to use, too */ #define FILES_PER_QUERY 100 +/* Read ahead up to this many entries, so the enumerator thread does not + * wait while the main thread integrates a batch. */ +#define MODEL_READ_AHEAD (2 * FILES_PER_QUERY) + +/* Length of one slice of work in the main loop, and how many items are + * processed between looks at the clock. */ +#define MODEL_SLICE_US 8000 +#define MODEL_CLOCK_GRANULARITY 8 + +/* While a folder loads, the first rows appear after MODEL_FIRST_COMMIT_US; + * later commits come at growing intervals so large folders are not merged + * over and over. */ +#define MODEL_FIRST_COMMIT_US (100 * 1000) +#define MODEL_COMMIT_INTERVAL_US (250 * 1000) +#define MODEL_MAX_COMMIT_INTERVAL_US (1000 * 1000) + +#define VALUE_PAGE_SHIFT 6 +#define VALUE_PAGE_SIZE (1u << VALUE_PAGE_SHIFT) +#define VALUE_PAGE_MASK (VALUE_PAGE_SIZE - 1u) + +enum +{ + PHASE_IDLE, + PHASE_SORT, /* sorting model->sort_buf */ + PHASE_MERGE /* merging the sorted tail into the rows */ +}; + +enum +{ + SORT_FOR_COMMIT, + SORT_FOR_RESORT +}; + typedef struct _FileModelNode FileModelNode; typedef struct _GtkFileSystemModelClass GtkFileSystemModelClass; struct _FileModelNode { - GFile * file; /* file represented by this node or NULL for editable */ - GFileInfo * info; /* info for this file or NULL if unknown */ + GFile * file; /* NULL for the editable row and unused slots */ + GFileInfo * info; /* NULL for the editable row */ - guint row; /* if valid (see model->n_valid_indexes), visible nodes before and including - * this one - see the "Structure" comment above. - */ + guint order_pos; /* index in model->order; next free slot if unused */ + guint visible_pos; /* row, if visible (see node_visible_row()) */ + guint generation; /* changes whenever the slot is reused */ - guint visible :1; /* if the file is currently visible */ - guint filtered_out :1;/* if the file is currently filtered out (i.e. it didn't pass the filters) */ - guint frozen_add :1; /* true if the model was frozen and the entry has not been added yet */ - - GValue values[1]; /* actually n_columns values */ + guint visible :1; /* is a row */ + guint filtered_out :1;/* did not pass the filter */ + guint uncommitted :1; /* in the tail of model->order */ + guint merged_epoch :1;/* see model->merge_epoch */ + guint queued :1; /* in model->node_queue */ + guint want_remove :1; + guint want_reposition :1; + guint want_refilter :1; + guint want_changed :1; /* row-changed held back while editing */ }; +typedef struct +{ + GValue values[VALUE_PAGE_SIZE]; +} ValuePage; + struct _GtkFileSystemModel { GObject parent_instance; GFile * dir; /* directory that's displayed */ - guint dir_thaw_source;/* GSource id for unfreezing the model */ char * attributes; /* attributes the file info must contain, or NULL for all attributes */ GFileMonitor * dir_monitor; /* directory that is monitored, or NULL if monitoring was not supported */ - + GFileEnumerator * dir_enumerator; GCancellable * cancellable; /* cancellable in use for all operations - cancelled on dispose */ - GArray * files; /* array of FileModelNode containing all our files */ - gsize node_size; /* Size of a FileModelNode structure once its ->values field has n_columns */ - guint n_nodes_valid; /* count of valid nodes (i.e. those whose node->row is accurate) */ - GHashTable * file_lookup; /* mapping of GFile => array index in model->files - * This hash table doesn't always have the same number of entries as the files array; - * it can get cleared completely when we resort. - * The hash table gets re-populated in node_get_for_file() if this mismatch is - * detected. - */ + GHashTable * monitor_queries;/* GFile => serial of the latest query for it */ + guint monitor_serial; + GHashTable * deleted_files; /* deleted while the enumerator may still return them */ + + /* Loading */ + GQueue pending_infos; /* GFileInfos from the enumerator, not added yet */ + GError * load_error; + gint64 next_commit_time; + gint64 commit_interval; + guint commit_timer; + + /* Work in the main loop (see gtk_file_system_model_work) */ + guint work_source; + guint phase; + GQueue node_queue; /* IDs of nodes with want_* flags */ + + GArray * sort_buf; /* PHASE_SORT: IDs being sorted */ + GArray * sort_scratch; + guint sort_purpose; + guint sort_width; + guint sort_left; + guint sort_mid; + guint sort_right; + guint sort_i; + guint sort_j; + guint sort_k; + + GArray * merge_tail; /* PHASE_MERGE: sorted tail */ + GArray * merge_order; /* new model->order */ + GArray * merge_vis; /* rows announced so far */ + guint merge_oi; /* next committed node to merge */ + guint merge_ti; /* next tail node to merge */ + guint merge_ovi; /* old rows merged so far */ + guint merge_end; /* model->order length when the commit started */ + + GArray * files; /* FileModelNode by ID */ + GArray * order; /* IDs in sort order: committed part, then the tail */ + GArray * visible_order; /* IDs of the rows */ + guint committed; + guint free_id_head; /* first unused slot, or 0 */ + GHashTable * file_lookup; /* GFile => ID */ guint n_columns; /* number of columns */ GType * column_types; /* types of each column */ + GPtrArray ** value_pages; /* per column: ValuePages by ID / VALUE_PAGE_SIZE */ GtkFileSystemModelGetValue get_func; /* function to call to fill in values in columns */ gpointer get_data; /* data to pass to get_func */ @@ -184,10 +227,15 @@ struct _GtkFileSystemModel gpointer default_sort_data; /* data to pass to default sort func */ GDestroyNotify default_sort_destroy; /* function to call to destroy default_sort_data */ - guint frozen; /* number of times we're frozen */ - - gboolean filter_on_thaw :1;/* set when filtering needs to happen upon thawing */ - gboolean sort_on_thaw :1;/* set when sorting needs to happen upon thawing */ + guint directory_loading :1; + guint enumeration_done :1; + guint next_files_in_flight :1; + guint editing_hold :1; /* the editable row is shown */ + guint resort_pending :1; + guint refilter_pending :1; + guint merge_refilter :1;/* the merge in progress filters committed nodes again */ + guint merge_epoch :1; /* toggles with every merge */ + guint in_merge_step :1; guint show_hidden :1; /* whether to show hidden files */ guint show_folders :1;/* whether to show folders */ @@ -208,8 +256,20 @@ struct _GtkFileSystemModelClass void (*finished_loading) (GtkFileSystemModel *model, GError *error); }; -static void freeze_updates (GtkFileSystemModel *model); -static void thaw_updates (GtkFileSystemModel *model); +/* Signal IDs */ +enum { + FINISHED_LOADING, + LAST_SIGNAL +}; + +static guint file_system_model_signals[LAST_SIGNAL] = { 0 }; + +static void gtk_file_system_model_schedule_work (GtkFileSystemModel *model); +static void gtk_file_system_model_complete_merge (GtkFileSystemModel *model); +static void gtk_file_system_model_request_next_files (GtkFileSystemModel *model); +static void gtk_file_system_model_got_files (GObject *object, + GAsyncResult *res, + gpointer data); static guint node_get_for_file (GtkFileSystemModel *model, GFile *file); @@ -222,88 +282,200 @@ static void remove_file (GtkFileSystemModel *model, /* iter setup: * @user_data: the model - * @user_data2: GUINT_TO_POINTER of array index of current entry - * - * All other fields are unused. Note that the array index does not corrspond - * 1:1 with the path index as entries might not be visible. + * @user_data2: node ID + * @user_data3: node generation */ #define ITER_INDEX(iter) GPOINTER_TO_UINT((iter)->user_data2) -#define ITER_IS_VALID(model, iter) ((model) == (iter)->user_data) -#define ITER_INIT_FROM_INDEX(model, _iter, _index) G_STMT_START {\ - g_assert (_index < (model)->files->len); \ + +#define get_node(_model, _index) \ + (&g_array_index ((_model)->files, FileModelNode, (_index))) + +static gboolean +iter_is_valid (GtkFileSystemModel *model, + GtkTreeIter *iter) +{ + FileModelNode *node; + guint id; + + if (iter == NULL || iter->user_data != model) + return FALSE; + + id = ITER_INDEX (iter); + if (id >= model->files->len) + return FALSE; + + node = get_node (model, id); + return (id == 0 || node->file != NULL) && + node->generation == GPOINTER_TO_UINT (iter->user_data3); +} + +#define ITER_IS_VALID(model, iter) iter_is_valid ((model), (iter)) + +#define ITER_INIT_FROM_INDEX(model, _iter, _index) G_STMT_START { \ + FileModelNode *_node; \ + g_assert ((_index) < (model)->files->len); \ + _node = get_node ((model), (_index)); \ + g_assert ((_index) == 0 || _node->file != NULL); \ (_iter)->user_data = (model); \ (_iter)->user_data2 = GUINT_TO_POINTER (_index); \ -}G_STMT_END + (_iter)->user_data3 = GUINT_TO_POINTER (_node->generation); \ +} G_STMT_END -/*** FileModelNode ***/ +/*** Order and rows ***/ -/* Get a FileModelNode structure given an index in the model->files array of nodes */ -#define get_node(_model, _index) ((FileModelNode *) ((_model)->files->data + (_index) * (_model)->node_size)) - -/* Get an index within the model->files array of nodes, given a FileModelNode* */ -#define node_index(_model, _node) (((gchar *) (_node) - (_model)->files->data) / (_model)->node_size) - -/* @up_to_index: smallest model->files array index that will be valid after this call - * @up_to_row: smallest node->row that will be valid after this call - * - * If you want to validate up to an index or up to a row, specify the index or - * the row you want and specify G_MAXUINT for the other argument. Pass - * G_MAXUINT for both arguments for "validate everything". - */ static void -node_validate_rows (GtkFileSystemModel *model, guint up_to_index, guint up_to_row) +order_update_positions (GtkFileSystemModel *model, + guint first, + guint end) { - guint i, row; + guint i; - if (model->files->len == 0) - return; + for (i = first; i < end; i++) + get_node (model, g_array_index (model->order, guint, i))->order_pos = i; +} - up_to_index = MIN (up_to_index, model->files->len - 1); +static void +visible_update_positions_from (GtkFileSystemModel *model, + guint first) +{ + guint i; - i = model->n_nodes_valid; - if (i != 0) - row = get_node (model, i - 1)->row; - else - row = 0; + for (i = first; i < model->visible_order->len; i++) + get_node (model, g_array_index (model->visible_order, guint, i))->visible_pos = i; +} - while (i <= up_to_index && row <= up_to_row) +/* Index of the first entry of @rows[@lo, len) whose node comes after + * order position @order_pos (or at it, unless @after). */ +static guint +rows_find_order_pos (GtkFileSystemModel *model, + GArray *rows, + guint lo, + guint order_pos, + gboolean after) +{ + guint hi = rows->len; + + while (lo < hi) { - FileModelNode *node = get_node (model, i); - if (node->visible) - row++; - node->row = row; - i++; + guint mid = lo + (hi - lo) / 2; + guint pos = get_node (model, g_array_index (rows, guint, mid))->order_pos; + + if (pos < order_pos || (after && pos == order_pos)) + lo = mid + 1; + else + hi = mid; } - model->n_nodes_valid = i; + + return lo; +} + +/* The editable row, if shown, is always the first row. */ +static guint +rows_first_file (GtkFileSystemModel *model, + GArray *rows) +{ + return rows->len > 0 && g_array_index (rows, guint, 0) == 0 ? 1 : 0; +} + +/* While a merge is in progress, the rows are model->merge_vis (merged, in + * the new order) followed by model->visible_order[merge_ovi..] (not merged + * yet). The functions below see exactly the rows announced so far. */ +#define MODEL_MERGING(model) ((model)->phase == PHASE_MERGE) + +static guint +model_n_visible (GtkFileSystemModel *model) +{ + if (MODEL_MERGING (model)) + return model->merge_vis->len + (model->visible_order->len - model->merge_ovi); + + return model->visible_order->len; } static guint -node_get_tree_row (GtkFileSystemModel *model, guint index) +model_nth_visible (GtkFileSystemModel *model, + guint n) { - if (model->n_nodes_valid <= index) - node_validate_rows (model, index, G_MAXUINT); + if (MODEL_MERGING (model)) + { + if (n < model->merge_vis->len) + return g_array_index (model->merge_vis, guint, n); - return get_node (model, index)->row - 1; + n = n - model->merge_vis->len + model->merge_ovi; + } + + if (n >= model->visible_order->len) + return G_MAXUINT; + + return g_array_index (model->visible_order, guint, n); } -static void -node_invalidate_index (GtkFileSystemModel *model, guint id) +static gboolean +node_is_merged (GtkFileSystemModel *model, + FileModelNode *node) { - model->n_nodes_valid = MIN (model->n_nodes_valid, id); + return MODEL_MERGING (model) && node->merged_epoch == model->merge_epoch; +} + +static guint +node_visible_row (GtkFileSystemModel *model, + FileModelNode *node) +{ + g_assert (node->visible); + + if (MODEL_MERGING (model) && !node_is_merged (model, node)) + return node->visible_pos - model->merge_ovi + model->merge_vis->len; + + return node->visible_pos; +} + +/* Number of rows that come before @node, which is not a row. */ +static guint +node_rows_before (GtkFileSystemModel *model, + FileModelNode *node) +{ + if (node->uncommitted) + return model_n_visible (model); + + if (!MODEL_MERGING (model)) + return rows_find_order_pos (model, model->visible_order, + rows_first_file (model, model->visible_order), + node->order_pos, TRUE); + + if (node_is_merged (model, node)) + return rows_find_order_pos (model, model->merge_vis, + rows_first_file (model, model->merge_vis), + node->order_pos, TRUE); + + return model->merge_vis->len - model->merge_ovi + + rows_find_order_pos (model, model->visible_order, model->merge_ovi, + node->order_pos, TRUE); } static GtkTreePath * -tree_path_new_from_node (GtkFileSystemModel *model, guint id) +tree_path_new_from_node (GtkFileSystemModel *model, + guint id) { - guint r = node_get_tree_row (model, id); + FileModelNode *node = get_node (model, id); + guint row; - g_assert (r < model->files->len); + if (node->visible) + row = node_visible_row (model, node); + else if (id == 0) + row = 0; + else + { + /* Invisible nodes report the closest preceding visible row. */ + row = node_rows_before (model, node); + if (row > 0) + row--; + } - return gtk_tree_path_new_from_indices (r, -1); + return gtk_tree_path_new_from_indices (row, -1); } static void -emit_row_inserted_for_node (GtkFileSystemModel *model, guint id) +emit_row_inserted_for_node (GtkFileSystemModel *model, + guint id) { GtkTreePath *path; GtkTreeIter iter; @@ -314,12 +486,23 @@ emit_row_inserted_for_node (GtkFileSystemModel *model, guint id) gtk_tree_path_free (path); } +static void node_queue (GtkFileSystemModel *model, guint id); + static void -emit_row_changed_for_node (GtkFileSystemModel *model, guint id) +emit_row_changed_for_node (GtkFileSystemModel *model, + guint id) { GtkTreePath *path; GtkTreeIter iter; + /* GtkIconView stops editing on any row change; hold it back. */ + if (model->editing_hold && id != 0) + { + get_node (model, id)->want_changed = TRUE; + node_queue (model, id); + return; + } + path = tree_path_new_from_node (model, id); ITER_INIT_FROM_INDEX (model, &iter, id); gtk_tree_model_row_changed (GTK_TREE_MODEL (model), path, &iter); @@ -327,7 +510,8 @@ emit_row_changed_for_node (GtkFileSystemModel *model, guint id) } static void -emit_row_deleted_for_row (GtkFileSystemModel *model, guint row) +emit_row_deleted_for_row (GtkFileSystemModel *model, + guint row) { GtkTreePath *path; @@ -336,43 +520,139 @@ emit_row_deleted_for_row (GtkFileSystemModel *model, guint row) gtk_tree_path_free (path); } +/*** Value cache ***/ + static void -node_set_visible_and_filtered_out (GtkFileSystemModel *model, guint id, gboolean visible, gboolean filtered_out) +value_page_free (gpointer data) { - FileModelNode *node = get_node (model, id); + ValuePage *page = data; + guint slot; - /* Filteredness */ - - if (node->filtered_out != filtered_out) - { - node->filtered_out = filtered_out; - if (node->visible && visible) - emit_row_changed_for_node (model, id); - } - - /* Visibility */ - - if (node->visible == visible || - node->frozen_add) + if (page == NULL) return; - if (visible) + for (slot = 0; slot < VALUE_PAGE_SIZE; slot++) + if (G_VALUE_TYPE (&page->values[slot]) != G_TYPE_INVALID) + g_value_unset (&page->values[slot]); + + g_free (page); +} + +static GValue * +value_cache_slot (GtkFileSystemModel *model, + guint id, + guint column, + gboolean create) +{ + GPtrArray *pages = model->value_pages[column]; + guint page_index = id >> VALUE_PAGE_SHIFT; + ValuePage *page; + + if (pages == NULL) { - node->visible = TRUE; - node_invalidate_index (model, id); - emit_row_inserted_for_node (model, id); + if (!create) + return NULL; + + pages = g_ptr_array_new_with_free_func (value_page_free); + model->value_pages[column] = pages; + } + + if (page_index >= pages->len) + { + if (!create) + return NULL; + + g_ptr_array_set_size (pages, page_index + 1); + } + + page = pages->pdata[page_index]; + if (page == NULL) + { + if (!create) + return NULL; + + page = g_new0 (ValuePage, 1); + pages->pdata[page_index] = page; + } + + return &page->values[id & VALUE_PAGE_MASK]; +} + +static gboolean +value_cache_clear_slot (GtkFileSystemModel *model, + guint id, + guint column) +{ + GValue *value = value_cache_slot (model, id, column, FALSE); + + if (value == NULL || G_VALUE_TYPE (value) == G_TYPE_INVALID) + return FALSE; + + g_value_unset (value); + return TRUE; +} + +static void +value_cache_clear_node (GtkFileSystemModel *model, + guint id) +{ + guint column; + + for (column = 0; column < model->n_columns; column++) + value_cache_clear_slot (model, id, column); +} + +/*** Nodes ***/ + +static void +file_model_node_clear (gpointer data) +{ + FileModelNode *node = data; + + g_clear_object (&node->file); + g_clear_object (&node->info); +} + +static guint +node_allocate_slot (GtkFileSystemModel *model) +{ + guint id; + + if (model->free_id_head != 0) + { + id = model->free_id_head; + model->free_id_head = get_node (model, id)->order_pos; } else { - guint row; - - row = node_get_tree_row (model, id); - g_assert (row < model->files->len); - - node->visible = FALSE; - node_invalidate_index (model, id); - emit_row_deleted_for_row (model, row); + id = model->files->len; + g_array_set_size (model->files, id + 1); + get_node (model, id)->generation = 1; } + + return id; +} + +static void +node_retire_slot (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + guint generation; + + g_assert (id != 0); + + file_model_node_clear (node); + value_cache_clear_node (model, id); + + generation = node->generation + 1; + if (generation == 0) + generation = 1; + + memset (node, 0, sizeof (*node)); + node->generation = generation; + node->order_pos = model->free_id_head; + model->free_id_head = id; } static gboolean @@ -445,7 +725,6 @@ static gboolean node_should_be_visible (GtkFileSystemModel *model, guint id, gboolean filtered_out) { FileModelNode *node = get_node (model, id); - gboolean result; if (node->info == NULL) return FALSE; @@ -479,9 +758,52 @@ node_should_be_visible (GtkFileSystemModel *model, guint id, gboolean filtered_o return FALSE; } - result = !filtered_out; + return !filtered_out; +} - return result; +/* Shows or hides one committed node. Not used while merging. */ +static void +node_set_visible_and_filtered_out (GtkFileSystemModel *model, + guint id, + gboolean visible, + gboolean filtered_out) +{ + FileModelNode *node = get_node (model, id); + + g_assert (!MODEL_MERGING (model)); + + if (node->filtered_out != filtered_out) + { + node->filtered_out = filtered_out; + if (node->visible && visible) + emit_row_changed_for_node (model, id); + } + + if (node->visible == visible) + return; + + if (visible) + { + guint pos; + + pos = id == 0 ? 0 : + rows_find_order_pos (model, model->visible_order, + rows_first_file (model, model->visible_order), + node->order_pos, FALSE); + g_array_insert_val (model->visible_order, pos, id); + node->visible = TRUE; + visible_update_positions_from (model, pos); + emit_row_inserted_for_node (model, id); + } + else + { + guint row = node->visible_pos; + + g_array_remove_index (model->visible_order, row); + node->visible = FALSE; + visible_update_positions_from (model, row); + emit_row_deleted_for_row (model, row); + } } static void @@ -524,64 +846,23 @@ gtk_file_system_model_get_column_type (GtkTreeModel *tree_model, return model->column_types[i]; } -static int -compare_indices (gconstpointer key, gconstpointer _node) -{ - const FileModelNode *node = _node; - - return GPOINTER_TO_UINT (key) - node->row; -} - static gboolean gtk_file_system_model_iter_nth_child (GtkTreeModel *tree_model, - GtkTreeIter *iter, - GtkTreeIter *parent, - gint n) + GtkTreeIter *iter, + GtkTreeIter *parent, + gint n) { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model); - char *node; guint id; - guint row_to_find; g_return_val_if_fail (n >= 0, FALSE); if (parent != NULL) return FALSE; - row_to_find = n + 1; /* plus one as our node->row numbers are 1-based; see the "Structure" comment at the beginning */ - - if (model->n_nodes_valid > 0 && - get_node (model, model->n_nodes_valid - 1)->row >= row_to_find) - { - /* Fast path - the nodes are valid up to the sought one. - * - * First, find a node with the sought row number...*/ - - node = bsearch (GUINT_TO_POINTER (row_to_find), - model->files->data, - model->n_nodes_valid, - model->node_size, - compare_indices); - if (node == NULL) - return FALSE; - - /* ... Second, back up until we find the first visible node with that row number */ - - id = node_index (model, node); - while (!get_node (model, id)->visible) - id--; - - g_assert (get_node (model, id)->row == row_to_find); - } - else - { - /* Slow path - the nodes need to be validated up to the sought one */ - - node_validate_rows (model, G_MAXUINT, n); /* note that this is really "n", not row_to_find - see node_validate_rows() */ - id = model->n_nodes_valid - 1; - if (model->n_nodes_valid == 0 || get_node (model, id)->row != row_to_find) - return FALSE; - } + id = model_nth_visible (model, n); + if (id == G_MAXUINT) + return FALSE; ITER_INIT_FROM_INDEX (model, iter, id); return TRUE; @@ -616,9 +897,9 @@ gtk_file_system_model_get_path (GtkTreeModel *tree_model, static void gtk_file_system_model_get_value (GtkTreeModel *tree_model, - GtkTreeIter *iter, - gint column, - GValue *value) + GtkTreeIter *iter, + gint column, + GValue *value) { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model); const GValue *original; @@ -641,22 +922,26 @@ gtk_file_system_model_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter) { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (tree_model); - guint i; + FileModelNode *node; + guint next, id; g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE); - for (i = ITER_INDEX (iter) + 1; i < model->files->len; i++) - { - FileModelNode *node = get_node (model, i); + node = get_node (model, ITER_INDEX (iter)); - if (node->visible) - { - ITER_INIT_FROM_INDEX (model, iter, i); - return TRUE; - } - } + if (node->visible) + next = node_visible_row (model, node) + 1; + else if (ITER_INDEX (iter) != 0) + next = node_rows_before (model, node); + else + return FALSE; - return FALSE; + id = model_nth_visible (model, next); + if (id == G_MAXUINT) + return FALSE; + + ITER_INIT_FROM_INDEX (model, iter, id); + return TRUE; } static gboolean @@ -683,7 +968,7 @@ gtk_file_system_model_iter_n_children (GtkTreeModel *tree_model, if (iter) return 0; - return node_get_tree_row (model, model->files->len - 1) + 1; + return model_n_visible (model); } static gboolean @@ -727,7 +1012,7 @@ gtk_file_system_model_iface_init (GtkTreeModelIface *iface) iface->unref_node = gtk_file_system_model_unref_node; } -/*** GtkTreeSortable ***/ +/*** Sorting ***/ typedef struct _SortData SortData; struct _SortData { @@ -737,15 +1022,12 @@ struct _SortData { int order; /* -1 to invert sort order or 1 to keep it */ }; -/* returns FALSE if no sort necessary */ +/* returns FALSE if the model is not sorted */ static gboolean sort_data_init (SortData *data, GtkFileSystemModel *model) { GtkTreeDataSortHeader *header; - if (model->files->len <= 2) - return FALSE; - switch (model->sort_column_id) { case GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID: @@ -771,83 +1053,774 @@ sort_data_init (SortData *data, GtkFileSystemModel *model) } static int -compare_array_element (gconstpointer a, gconstpointer b, gpointer user_data) +compare_ids (SortData *data, + guint ida, + guint idb) { - SortData *data = user_data; GtkTreeIter itera, iterb; - ITER_INIT_FROM_INDEX (data->model, &itera, node_index (data->model, a)); - ITER_INIT_FROM_INDEX (data->model, &iterb, node_index (data->model, b)); + ITER_INIT_FROM_INDEX (data->model, &itera, ida); + ITER_INIT_FROM_INDEX (data->model, &iterb, idb); + return data->func (GTK_TREE_MODEL (data->model), &itera, &iterb, data->data) * data->order; } +static gboolean +deadline_passed (gint64 deadline, + guint *counter) +{ + return (++(*counter) % MODEL_CLOCK_GRANULARITY) == 0 && + g_get_monotonic_time () >= deadline; +} + +/* Rebuilds the rows from model->order and announces the new order. */ static void -gtk_file_system_model_sort (GtkFileSystemModel *model) +visible_order_rebuild (GtkFileSystemModel *model) +{ + guint n_rows = model->visible_order->len; + gboolean changed = FALSE; + int *new_order; + guint row, i; + + if (n_rows == 0) + return; + + new_order = g_new (int, n_rows); + row = rows_first_file (model, model->visible_order); + if (row == 1) + new_order[0] = 0; + + for (i = 0; i < model->committed; i++) + { + guint id = g_array_index (model->order, guint, i); + FileModelNode *node = get_node (model, id); + + if (!node->visible) + continue; + + new_order[row] = node->visible_pos; + changed |= node->visible_pos != row; + g_array_index (model->visible_order, guint, row) = id; + node->visible_pos = row++; + } + + g_assert (row == n_rows); + + if (changed) + { + GtkTreePath *path = gtk_tree_path_new (); + gtk_tree_model_rows_reordered (GTK_TREE_MODEL (model), path, NULL, new_order); + gtk_tree_path_free (path); + } + + g_free (new_order); +} + +/* Bottom-up merge sort of model->sort_buf, resumable between slices. */ +static void +sort_prepare_merge (GtkFileSystemModel *model) +{ + guint n = model->sort_buf->len; + + model->sort_mid = MIN (model->sort_left + model->sort_width, n); + model->sort_right = MIN (model->sort_left + 2 * model->sort_width, n); + model->sort_i = model->sort_left; + model->sort_j = model->sort_mid; + model->sort_k = model->sort_left; +} + +static void gtk_file_system_model_sort_done (GtkFileSystemModel *model); + +/* Starts sorting @ids (taking ownership); see gtk_file_system_model_sort_done() */ +static void +gtk_file_system_model_sort_start (GtkFileSystemModel *model, + GArray *ids, + guint purpose) { SortData data; - if (model->frozen) + model->sort_buf = ids; + model->sort_purpose = purpose; + + if (ids->len <= 1 || !sort_data_init (&data, model)) { - model->sort_on_thaw = TRUE; + gtk_file_system_model_sort_done (model); return; } - if (sort_data_init (&data, model)) + model->sort_scratch = g_array_sized_new (FALSE, FALSE, sizeof (guint), ids->len); + g_array_set_size (model->sort_scratch, ids->len); + model->sort_width = 1; + model->sort_left = 0; + sort_prepare_merge (model); + model->phase = PHASE_SORT; +} + +/* Returns TRUE when the sort is done. */ +static gboolean +gtk_file_system_model_sort_step (GtkFileSystemModel *model, + gint64 deadline) +{ + GArray *buf = model->sort_buf; + guint n = buf->len; + guint processed = 0; + SortData data; + + if (!sort_data_init (&data, model)) { - GtkTreePath *path; - guint i; - guint r, n_visible_rows; - - node_validate_rows (model, G_MAXUINT, G_MAXUINT); - n_visible_rows = node_get_tree_row (model, model->files->len - 1) + 1; - model->n_nodes_valid = 0; - g_hash_table_remove_all (model->file_lookup); - _gtk_sort_array (get_node (model, 1), /* start at index 1; don't sort the editable row */ - model->files->len - 1, - model->node_size, - compare_array_element, - &data); - g_assert (model->n_nodes_valid == 0); - g_assert (g_hash_table_size (model->file_lookup) == 0); - if (n_visible_rows) - { - int *new_order = g_new (int, n_visible_rows); - - r = 0; - for (i = 0; i < model->files->len; i++) - { - FileModelNode *node = get_node (model, i); - if (!node->visible) - { - node->row = r; - continue; - } - - new_order[r] = node->row - 1; - r++; - node->row = r; - } - g_assert (r == n_visible_rows); - path = gtk_tree_path_new (); - gtk_tree_model_rows_reordered (GTK_TREE_MODEL (model), - path, - NULL, - new_order); - gtk_tree_path_free (path); - g_free (new_order); - } + gtk_file_system_model_sort_done (model); + return TRUE; } - model->sort_on_thaw = FALSE; + while (TRUE) + { + while (model->sort_k < model->sort_right) + { + guint id; + + if (model->sort_i < model->sort_mid && + (model->sort_j >= model->sort_right || + compare_ids (&data, + g_array_index (buf, guint, model->sort_i), + g_array_index (buf, guint, model->sort_j)) <= 0)) + id = g_array_index (buf, guint, model->sort_i++); + else + id = g_array_index (buf, guint, model->sort_j++); + + g_array_index (model->sort_scratch, guint, model->sort_k++) = id; + + if (deadline_passed (deadline, &processed)) + return FALSE; + } + + model->sort_left = model->sort_right; + if (model->sort_left < n) + { + sort_prepare_merge (model); + continue; + } + + /* Pass complete: the scratch buffer holds the result. */ + model->sort_buf = model->sort_scratch; + model->sort_scratch = buf; + buf = model->sort_buf; + + if (model->sort_width >= n - n / 2) + break; + + model->sort_width *= 2; + model->sort_left = 0; + sort_prepare_merge (model); + } + + gtk_file_system_model_sort_done (model); + return TRUE; } static void -gtk_file_system_model_sort_node (GtkFileSystemModel *model, guint node) +gtk_file_system_model_sort_abort (GtkFileSystemModel *model) { - /* FIXME: improve */ - gtk_file_system_model_sort (model); + g_clear_pointer (&model->sort_buf, g_array_unref); + g_clear_pointer (&model->sort_scratch, g_array_unref); + model->phase = PHASE_IDLE; } +/* Puts the sorted committed nodes in place. */ +static void +gtk_file_system_model_resort_apply (GtkFileSystemModel *model) +{ + g_assert (model->sort_buf->len == model->committed); + + memcpy (model->order->data, model->sort_buf->data, model->committed * sizeof (guint)); + order_update_positions (model, 0, model->committed); + visible_order_rebuild (model); +} + +/* Moves a committed node whose information changed to its new place. */ +static void +node_reposition (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + guint old_pos = node->order_pos; + guint lo, hi; + SortData data; + + if (model->committed <= 1 || !sort_data_init (&data, model)) + return; + + /* Usually the change did not affect the order. */ + if ((old_pos == 0 || + compare_ids (&data, g_array_index (model->order, guint, old_pos - 1), id) <= 0) && + (old_pos + 1 >= model->committed || + compare_ids (&data, id, g_array_index (model->order, guint, old_pos + 1)) <= 0)) + return; + + g_array_remove_index (model->order, old_pos); + + lo = 0; + hi = model->committed - 1; + while (lo < hi) + { + guint mid = lo + (hi - lo) / 2; + + if (compare_ids (&data, id, g_array_index (model->order, guint, mid)) < 0) + hi = mid; + else + lo = mid + 1; + } + + g_array_insert_val (model->order, lo, id); + order_update_positions (model, MIN (lo, old_pos), MAX (lo, old_pos) + 1); + + if (node->visible) + visible_order_rebuild (model); +} + +/*** Commits ***/ + +static void +gtk_file_system_model_merge_init (GtkFileSystemModel *model) +{ + FileModelNode *editable = get_node (model, 0); + + model->merge_tail = model->sort_buf; + model->sort_buf = NULL; + g_clear_pointer (&model->sort_scratch, g_array_unref); + + model->merge_order = g_array_sized_new (FALSE, FALSE, sizeof (guint), model->order->len); + model->merge_vis = g_array_sized_new (FALSE, FALSE, sizeof (guint), + model->visible_order->len + model->merge_tail->len); + model->merge_oi = 0; + model->merge_ti = 0; + model->merge_ovi = 0; + model->merge_end = model->committed + model->merge_tail->len; + model->merge_epoch = !model->merge_epoch; + model->merge_refilter = model->refilter_pending; + model->refilter_pending = FALSE; + model->phase = PHASE_MERGE; + + /* The editable row, if any, stays first. */ + if (editable->visible) + { + guint id = 0; + + g_array_append_val (model->merge_vis, id); + editable->merged_epoch = model->merge_epoch; + model->merge_ovi = 1; + } +} + +static void +gtk_file_system_model_sort_done (GtkFileSystemModel *model) +{ + g_clear_pointer (&model->sort_scratch, g_array_unref); + model->phase = PHASE_IDLE; + + if (model->sort_purpose == SORT_FOR_COMMIT) + gtk_file_system_model_merge_init (model); + else + { + gtk_file_system_model_resort_apply (model); + g_clear_pointer (&model->sort_buf, g_array_unref); + } +} + +static void +gtk_file_system_model_start_commit (GtkFileSystemModel *model) +{ + guint n = model->order->len - model->committed; + GArray *tail; + + tail = g_array_sized_new (FALSE, FALSE, sizeof (guint), n); + g_array_append_vals (tail, &g_array_index (model->order, guint, model->committed), n); + + gtk_file_system_model_sort_start (model, tail, SORT_FOR_COMMIT); +} + +static void +merge_announce (GtkFileSystemModel *model, + guint id, + gboolean inserted) +{ + GtkTreePath *path; + GtkTreeIter iter; + + path = gtk_tree_path_new_from_indices (get_node (model, id)->visible_pos, -1); + ITER_INIT_FROM_INDEX (model, &iter, id); + + model->in_merge_step = TRUE; + if (inserted) + gtk_tree_model_row_inserted (GTK_TREE_MODEL (model), path, &iter); + else + gtk_tree_model_row_changed (GTK_TREE_MODEL (model), path, &iter); + model->in_merge_step = FALSE; + + gtk_tree_path_free (path); +} + +/* Takes the next committed node: keeps it, or with merge_refilter, shows, + * hides or updates it according to the current filter. */ +static void +merge_old_node (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + gboolean was_visible = node->visible; + gboolean was_filtered_out = node->filtered_out; + gboolean visible = was_visible; + + if (was_visible) + { + g_assert (g_array_index (model->visible_order, guint, model->merge_ovi) == id); + model->merge_ovi++; + } + + if (model->merge_refilter) + { + node->filtered_out = node_should_be_filtered_out (model, id); + visible = node_should_be_visible (model, id, node->filtered_out); + } + + if (visible) + { + g_array_append_val (model->merge_vis, id); + node->visible_pos = model->merge_vis->len - 1; + node->visible = TRUE; + + if (!was_visible) + merge_announce (model, id, TRUE); + else if (was_filtered_out != node->filtered_out) + merge_announce (model, id, FALSE); + } + else if (was_visible) + { + node->visible = FALSE; + + model->in_merge_step = TRUE; + emit_row_deleted_for_row (model, model->merge_vis->len); + model->in_merge_step = FALSE; + } +} + +/* Merges the sorted tail into the committed nodes, announcing each new + * row at its final position. Returns TRUE when done. */ +static gboolean +gtk_file_system_model_merge_step (GtkFileSystemModel *model, + gint64 deadline) +{ + guint processed = 0; + gboolean have_sort; + SortData data; + guint i; + + have_sort = sort_data_init (&data, model); + + while (model->merge_oi < model->committed || model->merge_ti < model->merge_tail->len) + { + gboolean from_tail; + FileModelNode *node; + guint id; + + if (model->merge_ti >= model->merge_tail->len) + from_tail = FALSE; + else if (model->merge_oi >= model->committed || !have_sort) + from_tail = model->merge_oi >= model->committed; + else + from_tail = compare_ids (&data, + g_array_index (model->merge_tail, guint, model->merge_ti), + g_array_index (model->order, guint, model->merge_oi)) < 0; + + id = from_tail ? g_array_index (model->merge_tail, guint, model->merge_ti++) + : g_array_index (model->order, guint, model->merge_oi++); + node = get_node (model, id); + + g_array_append_val (model->merge_order, id); + node->order_pos = model->merge_order->len - 1; + node->merged_epoch = model->merge_epoch; + + if (from_tail) + { + node->uncommitted = FALSE; + node->filtered_out = node_should_be_filtered_out (model, id); + if (node_should_be_visible (model, id, node->filtered_out)) + { + g_array_append_val (model->merge_vis, id); + node->visible_pos = model->merge_vis->len - 1; + node->visible = TRUE; + merge_announce (model, id, TRUE); + } + } + else + merge_old_node (model, id); + + if (deadline_passed (deadline, &processed)) + return FALSE; + } + + /* Nodes added during the commit stay in the tail, at the same positions. */ + for (i = model->merge_end; i < model->order->len; i++) + g_array_append_val (model->merge_order, g_array_index (model->order, guint, i)); + + g_array_unref (model->order); + model->order = model->merge_order; + model->merge_order = NULL; + + g_array_unref (model->visible_order); + model->visible_order = model->merge_vis; + model->merge_vis = NULL; + + if (model->merge_tail->len > 0) + { + model->next_commit_time = g_get_monotonic_time () + model->commit_interval; + model->commit_interval = MIN (model->commit_interval * 2, MODEL_MAX_COMMIT_INTERVAL_US); + } + + g_clear_pointer (&model->merge_tail, g_array_unref); + model->committed = model->merge_end; + model->phase = PHASE_IDLE; + + return TRUE; +} + +/* Finishes a commit in progress right away, for operations that need the + * rows in one piece. */ +static void +gtk_file_system_model_complete_merge (GtkFileSystemModel *model) +{ + g_return_if_fail (!model->in_merge_step); + + if (MODEL_MERGING (model)) + gtk_file_system_model_merge_step (model, G_MAXINT64); +} + +static gboolean +gtk_file_system_model_commit_due (GtkFileSystemModel *model) +{ + if (model->refilter_pending) + return TRUE; + + if (model->order->len == model->committed) + return FALSE; + + if (model->directory_loading && + !(model->enumeration_done && g_queue_is_empty (&model->pending_infos))) + return g_get_monotonic_time () >= model->next_commit_time; + + return TRUE; +} + +static gboolean +gtk_file_system_model_commit_timeout (gpointer data) +{ + GtkFileSystemModel *model = data; + + model->commit_timer = 0; + gtk_file_system_model_schedule_work (model); + + return FALSE; +} + +/*** Per node changes ***/ + +static void +node_queue (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + + if (!node->queued) + { + node->queued = TRUE; + g_queue_push_tail (&model->node_queue, GUINT_TO_POINTER (id)); + } + + gtk_file_system_model_schedule_work (model); +} + +static void +node_remove (GtkFileSystemModel *model, + guint id) +{ + FileModelNode *node = get_node (model, id); + gboolean was_visible = node->visible; + guint row = node->visible_pos; + guint pos = node->order_pos; + + if (was_visible) + { + g_array_remove_index (model->visible_order, row); + visible_update_positions_from (model, row); + } + + g_array_remove_index (model->order, pos); + if (pos < model->committed) + model->committed--; + order_update_positions (model, pos, model->order->len); + + g_hash_table_remove (model->file_lookup, node->file); + node_retire_slot (model, id); + + if (was_visible) + emit_row_deleted_for_row (model, row); +} + +/* Applies the queued per node changes. Returns TRUE when done. */ +static gboolean +gtk_file_system_model_process_node_queue (GtkFileSystemModel *model, + gint64 deadline) +{ + guint processed = 0; + + while (!g_queue_is_empty (&model->node_queue)) + { + guint id = GPOINTER_TO_UINT (g_queue_pop_head (&model->node_queue)); + FileModelNode *node = get_node (model, id); + + node->queued = FALSE; + + if (node->want_remove) + node_remove (model, id); + else if (!node->uncommitted) + { + /* Nodes in the tail are sorted and filtered when committed. */ + if (node->want_changed && node->visible) + emit_row_changed_for_node (model, id); + if (node->want_refilter) + node_compute_visibility_and_filters (model, id); + if (node->want_reposition) + node_reposition (model, id); + } + + node->want_changed = FALSE; + node->want_refilter = FALSE; + node->want_reposition = FALSE; + + if (deadline_passed (deadline, &processed)) + return FALSE; + } + + return TRUE; +} + +/*** Loading ***/ + +/* Adds the entries from the enumerator until @deadline. Returns TRUE when + * all are added. */ +static gboolean +gtk_file_system_model_drain (GtkFileSystemModel *model, + gint64 deadline) +{ + guint processed = 0; + + while (!g_queue_is_empty (&model->pending_infos)) + { + GFileInfo *info = g_queue_pop_head (&model->pending_infos); + const char *name; + + /* Keep the enumerator busy while the main thread works: on a slow + * share the next batch then arrives meanwhile. */ + if (g_queue_get_length (&model->pending_infos) < MODEL_READ_AHEAD) + gtk_file_system_model_request_next_files (model); + + name = g_file_info_get_name (info); + if (name != NULL) + { + GFile *file = g_file_get_child (model->dir, name); + + /* The monitor may have added it already, or reported that it + * was deleted after the enumerator read it. */ + if (model->deleted_files && g_hash_table_remove (model->deleted_files, file)) + ; + else if (node_get_for_file (model, file) == 0) + add_file (model, file, info); + g_object_unref (file); + } + + g_object_unref (info); + + if (deadline_passed (deadline, &processed)) + return FALSE; + } + + return TRUE; +} + +static void +gtk_file_system_model_finish_loading (GtkFileSystemModel *model) +{ + GError *error = model->load_error; + + model->load_error = NULL; + model->directory_loading = FALSE; + g_clear_pointer (&model->deleted_files, g_hash_table_destroy); + + g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error); + + if (error) + g_error_free (error); +} + +enum +{ + ROW_WORK_NONE, /* nothing to do now */ + ROW_WORK_DONE, /* did some; there may be more */ + ROW_WORK_INTERRUPTED /* stopped at the deadline */ +}; + +/* Does the next piece of work on the rows: continues a sort or merge, + * applies the queued per node changes, or starts a resort or a commit + * (with @commit_now, a commit of the files that came in so far even if it + * is not due yet). */ +static int +gtk_file_system_model_row_work (GtkFileSystemModel *model, + gint64 deadline, + gboolean commit_now) +{ + if (model->phase == PHASE_SORT) + return gtk_file_system_model_sort_step (model, deadline) ? ROW_WORK_DONE : ROW_WORK_INTERRUPTED; + + if (model->phase == PHASE_MERGE) + return gtk_file_system_model_merge_step (model, deadline) ? ROW_WORK_DONE : ROW_WORK_INTERRUPTED; + + if (!g_queue_is_empty (&model->node_queue)) + return gtk_file_system_model_process_node_queue (model, deadline) ? ROW_WORK_DONE : ROW_WORK_INTERRUPTED; + + if (model->resort_pending) + { + GArray *ids; + + model->resort_pending = FALSE; + ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), model->committed); + g_array_append_vals (ids, model->order->data, model->committed); + gtk_file_system_model_sort_start (model, ids, SORT_FOR_RESORT); + return ROW_WORK_DONE; + } + + if (commit_now ? (model->refilter_pending || model->order->len > model->committed) + : gtk_file_system_model_commit_due (model)) + { + gtk_file_system_model_start_commit (model); + return ROW_WORK_DONE; + } + + return ROW_WORK_NONE; +} + +/* Does the work of one slice. Returns TRUE if there is more to do now. */ +static gboolean +gtk_file_system_model_work_slice (GtkFileSystemModel *model) +{ + gint64 deadline = g_get_monotonic_time () + MODEL_SLICE_US; + + while (g_get_monotonic_time () < deadline) + { + if (!model->editing_hold) + { + int result = gtk_file_system_model_row_work (model, deadline, FALSE); + + if (result == ROW_WORK_INTERRUPTED) + return TRUE; + if (result == ROW_WORK_DONE) + continue; + } + + if (!g_queue_is_empty (&model->pending_infos)) + { + if (!gtk_file_system_model_drain (model, deadline)) + return TRUE; + continue; + } + + if (model->editing_hold || !model->directory_loading) + break; + + if (model->enumeration_done && model->order->len == model->committed) + { + /* Handlers may ask for more work, e.g. to show hidden files. */ + gtk_file_system_model_finish_loading (model); + continue; + } + + /* Waiting for the enumerator: show what came so far when it is due. */ + if (model->order->len > model->committed && model->commit_timer == 0) + { + gint64 delay = (model->next_commit_time - g_get_monotonic_time ()) / 1000; + + model->commit_timer = + gdk_threads_add_timeout_full (G_PRIORITY_DEFAULT_IDLE, + (guint) CLAMP (delay, 1, MODEL_MAX_COMMIT_INTERVAL_US / 1000), + gtk_file_system_model_commit_timeout, + model, NULL); + } + break; + } + + return g_get_monotonic_time () >= deadline; +} + +/* The single place where rows change (see the comment at the top). */ +static gboolean +gtk_file_system_model_work (gpointer data) +{ + GtkFileSystemModel *model = data; + gboolean more; + + /* Signal handlers may drop the last other reference. */ + g_object_ref (model); + + more = gtk_file_system_model_work_slice (model); + if (!more) + model->work_source = 0; + + g_object_unref (model); + + return more; +} + +static void +gtk_file_system_model_schedule_work (GtkFileSystemModel *model) +{ + if (model->work_source != 0) + return; + + /* Below redraws, so the view repaints between slices. */ + model->work_source = + gdk_threads_add_idle_full (G_PRIORITY_DEFAULT_IDLE, + gtk_file_system_model_work, + model, NULL); +} + +/* Sorting changes need the rows in one piece and no sort in progress. */ +static void +gtk_file_system_model_sort_changing (GtkFileSystemModel *model) +{ + gtk_file_system_model_complete_merge (model); + + if (model->phase == PHASE_SORT) + gtk_file_system_model_sort_abort (model); +} + +static void +gtk_file_system_model_resort (GtkFileSystemModel *model) +{ + model->resort_pending = TRUE; + gtk_file_system_model_schedule_work (model); +} + +static void +gtk_file_system_model_refilter_all (GtkFileSystemModel *model) +{ + /* Files in the tail are filtered when they are committed. */ + if (model->committed == 0 && !MODEL_MERGING (model)) + return; + + model->refilter_pending = TRUE; + gtk_file_system_model_schedule_work (model); +} + +/*** GtkTreeSortable ***/ + static gboolean gtk_file_system_model_get_sort_column_id (GtkTreeSortable *sortable, gint *sort_column_id, @@ -897,13 +1870,14 @@ gtk_file_system_model_set_sort_column_id (GtkTreeSortable *sortable, } } + gtk_file_system_model_sort_changing (model); model->sort_column_id = sort_column_id; model->sort_order = order; gtk_tree_sortable_sort_column_changed (sortable); - gtk_file_system_model_sort (model); + gtk_file_system_model_resort (model); } static void @@ -915,12 +1889,15 @@ gtk_file_system_model_set_sort_func (GtkTreeSortable *sortable, { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable); + if (model->sort_column_id == sort_column_id) + gtk_file_system_model_sort_changing (model); + model->sort_list = _gtk_tree_data_list_set_header (model->sort_list, sort_column_id, func, data, destroy); if (model->sort_column_id == sort_column_id) - gtk_file_system_model_sort (model); + gtk_file_system_model_resort (model); } static void @@ -931,6 +1908,9 @@ gtk_file_system_model_set_default_sort_func (GtkTreeSortable *sortable, { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (sortable); + if (model->sort_column_id == GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID) + gtk_file_system_model_sort_changing (model); + if (model->default_sort_destroy) { GDestroyNotify d = model->default_sort_destroy; @@ -944,7 +1924,7 @@ gtk_file_system_model_set_default_sort_func (GtkTreeSortable *sortable, model->default_sort_destroy = destroy; if (model->sort_column_id == GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID) - gtk_file_system_model_sort (model); + gtk_file_system_model_resort (model); } static gboolean @@ -1015,16 +1995,6 @@ drag_source_iface_init (GtkTreeDragSourceIface *iface) /*** GtkFileSystemModel ***/ -/* Signal IDs */ -enum { - FINISHED_LOADING, - LAST_SIGNAL -}; - -static guint file_system_model_signals[LAST_SIGNAL] = { 0 }; - - - G_DEFINE_TYPE_WITH_CODE (GtkFileSystemModel, _gtk_file_system_model, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_MODEL, gtk_file_system_model_iface_init) @@ -1038,16 +2008,26 @@ gtk_file_system_model_dispose (GObject *object) { GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (object); - if (model->dir_thaw_source) + if (model->work_source) { - g_source_remove (model->dir_thaw_source); - model->dir_thaw_source = 0; + g_source_remove (model->work_source); + model->work_source = 0; + } + + if (model->commit_timer) + { + g_source_remove (model->commit_timer); + model->commit_timer = 0; } g_cancellable_cancel (model->cancellable); if (model->dir_monitor) g_file_monitor_cancel (model->dir_monitor); + g_queue_foreach (&model->pending_infos, (GFunc) g_object_unref, NULL); + g_queue_clear (&model->pending_infos); + g_clear_object (&model->dir_enumerator); + G_OBJECT_CLASS (_gtk_file_system_model_parent_class)->dispose (object); } @@ -1058,21 +2038,21 @@ gtk_file_system_model_finalize (GObject *object) GtkFileSystemModel *model = GTK_FILE_SYSTEM_MODEL (object); guint i; - for (i = 0; i < model->files->len; i++) - { - int v; + for (i = 0; i < model->n_columns; i++) + if (model->value_pages[i]) + g_ptr_array_free (model->value_pages[i], TRUE); + g_free (model->value_pages); - FileModelNode *node = get_node (model, i); - if (node->file) - g_object_unref (node->file); - if (node->info) - g_object_unref (node->info); - - for (v = 0; v < model->n_columns; v++) - if (G_VALUE_TYPE (&node->values[v]) != G_TYPE_INVALID) - g_value_unset (&node->values[v]); - } g_array_free (model->files, TRUE); + g_array_free (model->order, TRUE); + g_array_free (model->visible_order, TRUE); + g_clear_pointer (&model->sort_buf, g_array_unref); + g_clear_pointer (&model->sort_scratch, g_array_unref); + g_clear_pointer (&model->merge_tail, g_array_unref); + g_clear_pointer (&model->merge_order, g_array_unref); + g_clear_pointer (&model->merge_vis, g_array_unref); + g_queue_clear (&model->node_queue); + g_clear_error (&model->load_error); g_object_unref (model->cancellable); g_free (model->attributes); @@ -1080,6 +2060,10 @@ gtk_file_system_model_finalize (GObject *object) g_object_unref (model->dir); if (model->dir_monitor) g_object_unref (model->dir_monitor); + if (model->monitor_queries) + g_hash_table_destroy (model->monitor_queries); + if (model->deleted_files) + g_hash_table_destroy (model->deleted_files); g_hash_table_destroy (model->file_lookup); if (model->filter) g_object_unref (model->filter); @@ -1133,93 +2117,104 @@ gtk_file_system_model_closed_enumerator (GObject *object, GAsyncResult *res, gpo g_file_enumerator_close_finish (G_FILE_ENUMERATOR (object), res, NULL); } -static gboolean -thaw_func (gpointer data) +static void +gtk_file_system_model_enumeration_done (GtkFileSystemModel *model, + const GError *error) { - GtkFileSystemModel *model = data; + model->enumeration_done = TRUE; + if (error) + model->load_error = g_error_copy (error); - thaw_updates (model); - model->dir_thaw_source = 0; + gtk_file_system_model_schedule_work (model); +} - return FALSE; +static void +gtk_file_system_model_request_next_files (GtkFileSystemModel *model) +{ + if (model->dir_enumerator == NULL || model->next_files_in_flight) + return; + + model->next_files_in_flight = TRUE; + g_file_enumerator_next_files_async (model->dir_enumerator, + FILES_PER_QUERY, + IO_PRIORITY, + model->cancellable, + gtk_file_system_model_got_files, + model); } static void gtk_file_system_model_got_files (GObject *object, GAsyncResult *res, gpointer data) { GFileEnumerator *enumerator = G_FILE_ENUMERATOR (object); - GtkFileSystemModel *model = data; + GtkFileSystemModel *model = data; /* only a valid pointer if not cancelled */ GList *walk, *files; GError *error = NULL; + files = g_file_enumerator_next_files_finish (enumerator, res, &error); + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + { + g_error_free (error); + return; + } + gdk_threads_enter (); - files = g_file_enumerator_next_files_finish (enumerator, res, &error); + model->next_files_in_flight = FALSE; if (files) { - if (model->dir_thaw_source == 0) - { - freeze_updates (model); - model->dir_thaw_source = gdk_threads_add_timeout_full (IO_PRIORITY + 1, - 50, - thaw_func, - model, - NULL); - } - for (walk = files; walk; walk = walk->next) - { - const char *name; - GFileInfo *info; - GFile *file; - - info = walk->data; - name = g_file_info_get_name (info); - if (name == NULL) - { - /* Shouldn't happen, but the APIs allow it */ - g_object_unref (info); - continue; - } - file = g_file_get_child (model->dir, name); - add_file (model, file, info); - g_object_unref (file); - g_object_unref (info); - } + g_queue_push_tail (&model->pending_infos, walk->data); g_list_free (files); - g_file_enumerator_next_files_async (enumerator, - g_file_is_native (model->dir) ? 50 * FILES_PER_QUERY : FILES_PER_QUERY, - IO_PRIORITY, - model->cancellable, - gtk_file_system_model_got_files, - model); + if (g_queue_get_length (&model->pending_infos) < MODEL_READ_AHEAD) + gtk_file_system_model_request_next_files (model); + + gtk_file_system_model_schedule_work (model); } else { - if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - { - g_file_enumerator_close_async (enumerator, - IO_PRIORITY, - model->cancellable, - gtk_file_system_model_closed_enumerator, - NULL); - if (model->dir_thaw_source != 0) - { - g_source_remove (model->dir_thaw_source); - model->dir_thaw_source = 0; - thaw_updates (model); - } + g_file_enumerator_close_async (enumerator, + IO_PRIORITY, + NULL, + gtk_file_system_model_closed_enumerator, + NULL); + g_clear_object (&model->dir_enumerator); - g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error); - } - - if (error) - g_error_free (error); + gtk_file_system_model_enumeration_done (model, error); } gdk_threads_leave (); + + if (error) + g_error_free (error); +} + +/* A file system query brought new information for @file. */ +static void +gtk_file_system_model_file_queried (GtkFileSystemModel *model, + GFile *file, + GFileInfo *info) +{ + guint id = node_get_for_file (model, file); + FileModelNode *node; + + if (id == 0) + { + add_file (model, file, info); + return; + } + + _gtk_file_system_model_update_file (model, file, info); + + /* The change may move the file or change whether it is shown; a file + * that was about to be removed came back. */ + node = get_node (model, id); + node->want_remove = FALSE; + node->want_reposition = TRUE; + node->want_refilter = TRUE; + node_queue (model, id); } static void @@ -1230,22 +2225,56 @@ gtk_file_system_model_query_done (GObject * object, GtkFileSystemModel *model = data; /* only a valid pointer if not cancelled */ GFile *file = G_FILE (object); GFileInfo *info; - guint id; info = g_file_query_info_finish (file, res, NULL); if (info == NULL) return; gdk_threads_enter (); - - _gtk_file_system_model_update_file (model, file, info); - - id = node_get_for_file (model, file); - gtk_file_system_model_sort_node (model, id); + gtk_file_system_model_file_queried (model, file, info); + gdk_threads_leave (); g_object_unref (info); +} + +typedef struct +{ + GtkFileSystemModel *model; /* only a valid pointer if not cancelled */ + guint serial; +} MonitorQuery; + +static void +gtk_file_system_model_monitor_query_done (GObject *object, + GAsyncResult *res, + gpointer data) +{ + MonitorQuery *query = data; + GtkFileSystemModel *model = query->model; + GFile *file = G_FILE (object); + GError *error = NULL; + GFileInfo *info; + + info = g_file_query_info_finish (file, res, &error); + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + goto out; + + gdk_threads_enter (); + + /* Only the latest query for a file counts; results can arrive out of + * order when a file changes quickly. */ + if (GPOINTER_TO_UINT (g_hash_table_lookup (model->monitor_queries, file)) == query->serial) + { + g_hash_table_remove (model->monitor_queries, file); + if (info) + gtk_file_system_model_file_queried (model, file, info); + } gdk_threads_leave (); + +out: + g_clear_error (&error); + g_clear_object (&info); + g_free (query); } static void @@ -1255,27 +2284,53 @@ gtk_file_system_model_monitor_change (GFileMonitor * monitor, GFileMonitorEvent type, GtkFileSystemModel *model) { + MonitorQuery *query; + switch (type) { case G_FILE_MONITOR_EVENT_CREATED: case G_FILE_MONITOR_EVENT_CHANGED: case G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED: /* We can treat all of these the same way */ + query = g_new (MonitorQuery, 1); + query->model = model; + query->serial = ++model->monitor_serial; + + gdk_threads_enter (); + if (model->deleted_files) + g_hash_table_remove (model->deleted_files, file); + if (model->monitor_queries == NULL) + model->monitor_queries = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, + g_object_unref, NULL); + g_hash_table_replace (model->monitor_queries, g_object_ref (file), + GUINT_TO_POINTER (query->serial)); + gdk_threads_leave (); + g_file_query_info_async (file, model->attributes, G_FILE_QUERY_INFO_NONE, IO_PRIORITY, model->cancellable, - gtk_file_system_model_query_done, - model); + gtk_file_system_model_monitor_query_done, + query); break; case G_FILE_MONITOR_EVENT_DELETED: gdk_threads_enter (); + if (model->monitor_queries) + g_hash_table_remove (model->monitor_queries, file); remove_file (model, file); + if (model->directory_loading) + { + /* The enumerator may have read it already and deliver it + * later, also after the node was removed; drop it then. */ + if (model->deleted_files == NULL) + model->deleted_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, + g_object_unref, NULL); + g_hash_table_add (model->deleted_files, g_object_ref (file)); + } gdk_threads_leave (); break; case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT: - /* FIXME: use freeze/thaw with this somehow? */ case G_FILE_MONITOR_EVENT_PRE_UNMOUNT: case G_FILE_MONITOR_EVENT_UNMOUNTED: default: @@ -1287,39 +2342,38 @@ gtk_file_system_model_monitor_change (GFileMonitor * monitor, static void gtk_file_system_model_got_enumerator (GObject *dir, GAsyncResult *res, gpointer data) { - GtkFileSystemModel *model = data; + GtkFileSystemModel *model = data; /* only a valid pointer if not cancelled */ GFileEnumerator *enumerator; GError *error = NULL; + enumerator = g_file_enumerate_children_finish (G_FILE (dir), res, &error); + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + { + g_error_free (error); + return; + } + gdk_threads_enter (); - enumerator = g_file_enumerate_children_finish (G_FILE (dir), res, &error); if (enumerator == NULL) { - if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - { - g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error); - g_error_free (error); - } + gtk_file_system_model_enumeration_done (model, error); + g_error_free (error); } else { - g_file_enumerator_next_files_async (enumerator, - g_file_is_native (model->dir) ? 50 * FILES_PER_QUERY : FILES_PER_QUERY, - IO_PRIORITY, - model->cancellable, - gtk_file_system_model_got_files, - model); - g_object_unref (enumerator); + model->dir_enumerator = enumerator; + gtk_file_system_model_request_next_files (model); + model->dir_monitor = g_file_monitor_directory (model->dir, - G_FILE_MONITOR_NONE, - model->cancellable, - NULL); /* we don't mind if directory monitoring isn't supported, so the GError is NULL here */ + G_FILE_MONITOR_NONE, + model->cancellable, + NULL); /* we don't mind if directory monitoring isn't supported, so the GError is NULL here */ if (model->dir_monitor) g_signal_connect (model->dir_monitor, - "changed", - G_CALLBACK (gtk_file_system_model_monitor_change), - model); + "changed", + G_CALLBACK (gtk_file_system_model_monitor_change), + model); } gdk_threads_leave (); @@ -1337,15 +2391,14 @@ gtk_file_system_model_set_n_columns (GtkFileSystemModel *model, model->n_columns = n_columns; model->column_types = g_slice_alloc (sizeof (GType) * n_columns); - - model->node_size = sizeof (FileModelNode) + sizeof (GValue) * (n_columns - 1); /* minus 1 because FileModelNode.values[] has a default size of 1 */ + model->value_pages = g_new0 (GPtrArray *, n_columns); for (i = 0; i < (guint) n_columns; i++) { GType type = va_arg (args, GType); if (! _gtk_tree_data_list_check_type (type)) { - g_error ("%s: type %s cannot be a column type for GtkFileSystemModel\n", G_STRLOC, g_type_name (type)); + g_error ("%s: type %s cannot be a column type for GtkFileSystemModel\n", G_STRLOC, g_type_name (type)); return; /* not reached */ } @@ -1354,10 +2407,14 @@ gtk_file_system_model_set_n_columns (GtkFileSystemModel *model, model->sort_list = _gtk_tree_data_list_header_new (n_columns, model->column_types); - model->files = g_array_sized_new (FALSE, FALSE, model->node_size, FILES_PER_QUERY); + model->files = g_array_sized_new (FALSE, TRUE, sizeof (FileModelNode), FILES_PER_QUERY); + g_array_set_clear_func (model->files, file_model_node_clear); + model->order = g_array_sized_new (FALSE, FALSE, sizeof (guint), FILES_PER_QUERY); + model->visible_order = g_array_sized_new (FALSE, FALSE, sizeof (guint), FILES_PER_QUERY); + /* add editable node at start */ g_array_set_size (model->files, 1); - memset (get_node (model, 0), 0, model->node_size); + get_node (model, 0)->generation = 1; } static void @@ -1369,6 +2426,9 @@ gtk_file_system_model_set_directory (GtkFileSystemModel *model, model->dir = g_object_ref (dir); model->attributes = g_strdup (attributes); + model->directory_loading = TRUE; + model->next_commit_time = g_get_monotonic_time () + MODEL_FIRST_COMMIT_US; + model->commit_interval = MODEL_COMMIT_INTERVAL_US; g_file_enumerate_children_async (model->dir, attributes, @@ -1445,6 +2505,8 @@ _gtk_file_system_model_new (GtkFileSystemModelGetValue get_func, * it will also monitor the drectory and update the model's * contents to reflect changes, if the @directory supports monitoring. * + * Files show up as rows while the directory is still being read. + * * Return value: the newly created #GtkFileSystemModel **/ GtkFileSystemModel * @@ -1471,27 +2533,6 @@ _gtk_file_system_model_new_for_directory (GFile * dir, return model; } -static void -gtk_file_system_model_refilter_all (GtkFileSystemModel *model) -{ - guint i; - - if (model->frozen) - { - model->filter_on_thaw = TRUE; - return; - } - - freeze_updates (model); - - /* start at index 1, don't change the editable */ - for (i = 1; i < model->files->len; i++) - node_compute_visibility_and_filters (model, i); - - model->filter_on_thaw = FALSE; - thaw_updates (model); -} - /** * _gtk_file_system_model_set_show_hidden: * @model: a #GtkFileSystemModel @@ -1626,6 +2667,7 @@ _gtk_file_system_model_iter_is_visible (GtkFileSystemModel *model, g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), FALSE); g_return_val_if_fail (iter != NULL, FALSE); + g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE); node = get_node (model, ITER_INDEX (iter)); return node->visible; @@ -1652,6 +2694,7 @@ _gtk_file_system_model_iter_is_filtered_out (GtkFileSystemModel *model, g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), FALSE); g_return_val_if_fail (iter != NULL, FALSE); + g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE); node = get_node (model, ITER_INDEX (iter)); return node->filtered_out; @@ -1682,6 +2725,7 @@ _gtk_file_system_model_get_info (GtkFileSystemModel *model, g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL); g_return_val_if_fail (iter != NULL, NULL); + g_return_val_if_fail (ITER_IS_VALID (model, iter), NULL); node = get_node (model, ITER_INDEX (iter)); g_assert (node->info == NULL || G_IS_FILE_INFO (node->info)); @@ -1707,6 +2751,8 @@ _gtk_file_system_model_get_file (GtkFileSystemModel *model, FileModelNode *node; g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL); + g_return_val_if_fail (iter != NULL, NULL); + g_return_val_if_fail (ITER_IS_VALID (model, iter), NULL); node = get_node (model, ITER_INDEX (iter)); return node->file; @@ -1735,59 +2781,35 @@ _gtk_file_system_model_get_value (GtkFileSystemModel *model, int column) { FileModelNode *node; + GValue *value; + guint id; g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL); g_return_val_if_fail (column >= 0 && (guint) column < model->n_columns, NULL); + g_return_val_if_fail (ITER_IS_VALID (model, iter), NULL); - node = get_node (model, ITER_INDEX (iter)); + id = ITER_INDEX (iter); + node = get_node (model, id); + value = value_cache_slot (model, id, column, TRUE); - if (!G_VALUE_TYPE (&node->values[column])) + if (G_VALUE_TYPE (value) == G_TYPE_INVALID) { - g_value_init (&node->values[column], model->column_types[column]); - if (!model->get_func (model, - node->file, - node->info, - column, - &node->values[column], - model->get_data)) + g_value_init (value, model->column_types[column]); + if (!model->get_func (model, node->file, node->info, column, value, model->get_data)) { - g_value_unset (&node->values[column]); + g_value_unset (value); return NULL; } } - return &node->values[column]; + return value; } static guint node_get_for_file (GtkFileSystemModel *model, - GFile * file) + GFile * file) { - guint i; - - i = GPOINTER_TO_UINT (g_hash_table_lookup (model->file_lookup, file)); - if (i != 0) - return i; - - /* Node 0 is the editable row and has no associated file or entry in the table, so we start counting from 1. - * - * The invariant here is that the files in model->files[n] for n < g_hash_table_size (model->file_lookup) - * are already added to the hash table. The table can get cleared when we re-sort; this loop merely rebuilds - * our (file -> index) mapping on demand. - * - * If we exit the loop, the next pending batch of mappings will be resolved when this function gets called again - * with another file that is not yet in the mapping. - */ - for (i = g_hash_table_size (model->file_lookup) + 1; i < model->files->len; i++) - { - FileModelNode *node = get_node (model, i); - - g_hash_table_insert (model->file_lookup, node->file, GUINT_TO_POINTER (i)); - if (g_file_equal (node->file, file)) - return i; - } - - return 0; + return GPOINTER_TO_UINT (g_hash_table_lookup (model->file_lookup, file)); } /** @@ -1824,41 +2846,14 @@ _gtk_file_system_model_get_iter_for_file (GtkFileSystemModel *model, return TRUE; } -/* When an element is added or removed to the model->files array, we need to - * update the model->file_lookup mappings of (node, index), as the indexes - * change. This function adds the specified increment to the index in that pair - * if the index is equal or after the specified id. We use this to slide the - * mappings up or down when a node is added or removed, respectively. - */ -static void -adjust_file_lookup (GtkFileSystemModel *model, guint id, int increment) -{ - GHashTableIter iter; - gpointer key; - gpointer value; - - g_hash_table_iter_init (&iter, model->file_lookup); - - while (g_hash_table_iter_next (&iter, &key, &value)) - { - guint index = GPOINTER_TO_UINT (value); - - if (index >= id) - { - index += increment; - g_hash_table_iter_replace (&iter, GUINT_TO_POINTER (index)); - } - } -} - /** * add_file: * @model: the model * @file: the file to add * @info: the information to associate with the file * - * Adds the given @file with its associated @info to the @model. - * If the model is frozen, the file will only show up after it is thawn. + * Adds the given @file with its associated @info to the @model. The file + * becomes a row (if it passes the filters) with the next commit. **/ static void add_file (GtkFileSystemModel *model, @@ -1866,24 +2861,23 @@ add_file (GtkFileSystemModel *model, GFileInfo *info) { FileModelNode *node; + guint id; g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (G_IS_FILE (file)); g_return_if_fail (G_IS_FILE_INFO (info)); - node = g_slice_alloc0 (model->node_size); + id = node_allocate_slot (model); + node = get_node (model, id); node->file = g_object_ref (file); - if (info) - node->info = g_object_ref (info); - node->frozen_add = model->frozen ? TRUE : FALSE; + node->info = g_object_ref (info); + node->uncommitted = TRUE; + node->order_pos = model->order->len; + g_array_append_val (model->order, id); - g_array_append_vals (model->files, node, 1); - g_slice_free1 (model->node_size, node); + g_hash_table_insert (model->file_lookup, node->file, GUINT_TO_POINTER (id)); - if (!model->frozen) - node_compute_visibility_and_filters (model, model->files->len -1); - - gtk_file_system_model_sort_node (model, model->files->len -1); + gtk_file_system_model_schedule_work (model); } /** @@ -1892,17 +2886,14 @@ add_file (GtkFileSystemModel *model, * @file: file to remove from the model. The file must have been * added to the model previously * - * Removes the given file from the model. If the file is not part of - * @model, this function does nothing. + * Removes the given file from the model, with the next per node changes. + * If the file is not part of @model, this function does nothing. **/ static void remove_file (GtkFileSystemModel *model, GFile *file) { - FileModelNode *node; - gboolean was_visible; guint id; - guint row; g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (G_IS_FILE (file)); @@ -1911,25 +2902,8 @@ remove_file (GtkFileSystemModel *model, if (id == 0) return; - node = get_node (model, id); - was_visible = node->visible; - row = node_get_tree_row (model, id); - - node_invalidate_index (model, id); - - g_hash_table_remove (model->file_lookup, file); - g_object_unref (node->file); - adjust_file_lookup (model, id, -1); - - if (node->info) - g_object_unref (node->info); - - g_array_remove_index (model->files, id); - - /* We don't need to resort, as removing a row doesn't change the sorting order of the other rows */ - - if (was_visible) - emit_row_deleted_for_row (model, row); + get_node (model, id)->want_remove = TRUE; + node_queue (model, id); } /** @@ -1948,8 +2922,8 @@ _gtk_file_system_model_update_file (GtkFileSystemModel *model, GFileInfo *info) { FileModelNode *node; - guint i, id; GFileInfo *old_info; + guint id; g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (G_IS_FILE (file)); @@ -1959,22 +2933,17 @@ _gtk_file_system_model_update_file (GtkFileSystemModel *model, if (id == 0) { add_file (model, file, info); - id = node_get_for_file (model, file); + return; } node = get_node (model, id); - old_info = node->info; node->info = g_object_ref (info); if (old_info) g_object_unref (old_info); - for (i = 0; i < model->n_columns; i++) - { - if (G_VALUE_TYPE (&node->values[i])) - g_value_unset (&node->values[i]); - } + value_cache_clear_node (model, id); if (node->visible) emit_row_changed_for_node (model, id); @@ -2010,63 +2979,6 @@ _gtk_file_system_model_set_filter (GtkFileSystemModel *model, gtk_file_system_model_refilter_all (model); } -/** - * freeze_updates: - * @model: a #GtkFileSystemModel - * - * Freezes most updates on the model, so that performing multiple operations on - * the files in the model do not cause any events. Use thaw_updates() to resume - * proper operations. It is fine to call this function multiple times as long as - * freeze and thaw calls are balanced. - **/ -static void -freeze_updates (GtkFileSystemModel *model) -{ - g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); - - model->frozen++; -} - -/** - * thaw_updates: - * @model: a #GtkFileSystemModel - * - * Undoes the effect of a previous call to freeze_updates() - **/ -static void -thaw_updates (GtkFileSystemModel *model) -{ - gboolean stuff_added; - - g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); - g_return_if_fail (model->frozen > 0); - - model->frozen--; - if (model->frozen > 0) - return; - - stuff_added = get_node (model, model->files->len - 1)->frozen_add; - - if (model->filter_on_thaw) - gtk_file_system_model_refilter_all (model); - if (model->sort_on_thaw) - gtk_file_system_model_sort (model); - if (stuff_added) - { - guint i; - - for (i = 0; i < model->files->len; i++) - { - FileModelNode *node = get_node (model, i); - - if (!node->frozen_add) - continue; - node->frozen_add = FALSE; - node_compute_visibility_and_filters (model, i); - } - } -} - /** * _gtk_file_system_model_clear_cache: * @model: a #GtkFileSystemModel @@ -2080,16 +2992,15 @@ thaw_updates (GtkFileSystemModel *model) **/ void _gtk_file_system_model_clear_cache (GtkFileSystemModel *model, - int column) + int column) { - guint i; - int start, end; - gboolean changed; + guint8 *changed; + guint start, end, c, i, n; g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); - g_return_if_fail (column >= -1 && (guint) column < model->n_columns); + g_return_if_fail (column >= -1 && column < (int) model->n_columns); - if (column > -1) + if (column >= 0) { start = column; end = column + 1; @@ -2100,65 +3011,88 @@ _gtk_file_system_model_clear_cache (GtkFileSystemModel *model, end = model->n_columns; } - for (i = 0; i < model->files->len; i++) + changed = g_new0 (guint8, model->files->len); + + for (c = start; c < end; c++) { - FileModelNode *node = get_node (model, i); + GPtrArray *pages = model->value_pages[c]; + guint page_index; - changed = FALSE; - for (column = start; column < end; column++) - { - if (!G_VALUE_TYPE (&node->values[column])) - continue; - - g_value_unset (&node->values[column]); - changed = TRUE; - } - - if (changed && node->visible) - emit_row_changed_for_node (model, i); - } - - /* FIXME: resort? */ -} - -void -_gtk_file_system_model_clear_cache_for_iter (GtkFileSystemModel *model, - GtkTreeIter *iter, - int column) -{ - FileModelNode *node; - int start, end; - gboolean changed = FALSE; - - g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); - g_return_if_fail (iter != NULL); - g_return_if_fail (ITER_IS_VALID (model, iter)); - g_return_if_fail (column >= -1 && (guint) column < model->n_columns); - - if (column > -1) - { - start = column; - end = column + 1; - } - else - { - start = 0; - end = model->n_columns; - } - - node = get_node (model, ITER_INDEX (iter)); - - for (column = start; column < end; column++) - { - if (!G_VALUE_TYPE (&node->values[column])) + if (pages == NULL) continue; - g_value_unset (&node->values[column]); - changed = TRUE; + for (page_index = 0; page_index < pages->len; page_index++) + { + ValuePage *page = pages->pdata[page_index]; + guint base = page_index << VALUE_PAGE_SHIFT; + guint slot; + + if (page == NULL) + continue; + + for (slot = 0; slot < VALUE_PAGE_SIZE && base + slot < model->files->len; slot++) + { + GValue *value = &page->values[slot]; + + if (G_VALUE_TYPE (value) != G_TYPE_INVALID) + { + g_value_unset (value); + changed[base + slot] = TRUE; + } + } + } } - if (changed && node->visible) - emit_row_changed_for_node (model, ITER_INDEX (iter)); + /* One change signal per affected row, in row order. */ + n = model_n_visible (model); + for (i = 0; i < n; i++) + { + guint id = model_nth_visible (model, i); + + if (changed[id]) + emit_row_changed_for_node (model, id); + } + + g_free (changed); +} + +/** + * _gtk_file_system_model_clear_cache_for_iter: + * @model: a #GtkFileSystemModel + * @iter: a valid iterator + * @column: the column to clear or -1 for all columns + * + * Like _gtk_file_system_model_clear_cache(), for a single row. + **/ +void +_gtk_file_system_model_clear_cache_for_iter (GtkFileSystemModel *model, + GtkTreeIter *iter, + int column) +{ + gboolean changed = FALSE; + guint start, end, c, id; + + g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); + g_return_if_fail (ITER_IS_VALID (model, iter)); + g_return_if_fail (column >= -1 && column < (int) model->n_columns); + + if (column >= 0) + { + start = column; + end = column + 1; + } + else + { + start = 0; + end = model->n_columns; + } + + id = ITER_INDEX (iter); + for (c = start; c < end; c++) + changed |= value_cache_clear_slot (model, id, c); + + if (changed && get_node (model, id)->visible) + emit_row_changed_for_node (model, id); } /** @@ -2205,13 +3139,15 @@ _gtk_file_system_model_add_editable (GtkFileSystemModel *model, GtkTreeIter *ite g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (!get_node (model, 0)->visible); + gtk_file_system_model_complete_merge (model); + node_set_visible_and_filtered_out (model, 0, TRUE, FALSE); ITER_INIT_FROM_INDEX (model, iter, 0); /* we don't want file system changes to affect the model while * editing is in place */ - freeze_updates (model); + model->editing_hold = TRUE; } /** @@ -2228,7 +3164,30 @@ _gtk_file_system_model_remove_editable (GtkFileSystemModel *model) g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); g_return_if_fail (get_node (model, 0)->visible); - thaw_updates (model); - node_set_visible_and_filtered_out (model, 0, FALSE, FALSE); + + model->editing_hold = FALSE; + gtk_file_system_model_schedule_work (model); +} + +/** + * _gtk_file_system_model_flush: + * @model: a #GtkFileSystemModel + * + * Brings the rows up to date right away: the model normally commits new + * files, filters and sorts again and applies changes to single files in + * the background. For code that needs to look at the rows now, such as + * selecting a file the user asked for after showing hidden files. Does + * nothing while the editable row is shown. + **/ +void +_gtk_file_system_model_flush (GtkFileSystemModel *model) +{ + g_return_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model)); + + if (model->editing_hold) + return; + + while (gtk_file_system_model_row_work (model, G_MAXINT64, TRUE) != ROW_WORK_NONE) + ; } diff --git a/gtk/gtkfilesystemmodel.h b/gtk/gtkfilesystemmodel.h index 4bdda0c23..639a47af2 100644 --- a/gtk/gtkfilesystemmodel.h +++ b/gtk/gtkfilesystemmodel.h @@ -94,6 +94,7 @@ void _gtk_file_system_model_set_filter (GtkFileSystemModel void _gtk_file_system_model_add_editable (GtkFileSystemModel *model, GtkTreeIter *iter); void _gtk_file_system_model_remove_editable (GtkFileSystemModel *model); +void _gtk_file_system_model_flush (GtkFileSystemModel *model); G_END_DECLS From 7453c733c72ce0ffbb8bc41fed1484a227ca5b49 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 13:56:26 +0200 Subject: [PATCH 05/12] filechooser: show the files of a folder while it is still loading --- gtk/gtkfilechooserdefault.c | 100 ++++++++++-------------------------- gtk/gtkfilechooserprivate.h | 4 +- 2 files changed, 28 insertions(+), 76 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index b3e3cdab4..2ba1f9dff 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -147,7 +147,6 @@ typedef struct _GtkFileChooserDefaultClass GtkFileChooserDefaultClass; #define GTK_IS_FILE_CHOOSER_DEFAULT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_FILE_CHOOSER_DEFAULT)) #define GTK_FILE_CHOOSER_DEFAULT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_FILE_CHOOSER_DEFAULT, GtkFileChooserDefaultClass)) -#define MAX_LOADING_TIME 500 #define DEFAULT_NEW_FOLDER_NAME _("Type name of new folder") @@ -406,7 +405,7 @@ static void remove_bookmark_button_clicked_cb (GtkButton *button, static void update_cell_renderer_attributes (GtkFileChooserDefault *impl); -static void load_remove_timer (GtkFileChooserDefault *impl, LoadState new_load_state); +static void load_set_model (GtkFileChooserDefault *impl); static void browse_files_center_selected_row (GtkFileChooserDefault *impl); static void view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode); @@ -918,9 +917,6 @@ gtk_file_chooser_default_finalize (GObject *object) search_clear_model (impl, FALSE); recent_clear_model (impl, FALSE); - /* stopping the load above should have cleared this */ - g_assert (impl->load_timeout_id == 0); - g_free (impl->preview_display_name); g_free (impl->edited_new_text); @@ -2353,6 +2349,11 @@ 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 in the view, or editing never starts and ends. */ + 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); @@ -5320,6 +5321,11 @@ view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode) else g_assert_not_reached (); + /* While a folder loads, only the list view shows it (see set_list_model()). */ + if (impl->load_state == LOAD_LOADING && + impl->operation_mode == OPERATION_MODE_BROWSE) + impl->current_model = view_mode == VIEW_MODE_LIST ? GTK_TREE_MODEL (impl->browse_files_model) : NULL; + /* Set model and selection */ current_view_set_file_model (impl, impl->current_model); current_view_set_select_multiple (impl, impl->select_multiple); @@ -7450,62 +7456,6 @@ load_set_model (GtkFileChooserDefault *impl) profile_end ("end", NULL); } -/* Timeout callback used when the loading timer expires */ -static gboolean -load_timeout_cb (gpointer data) -{ - GtkFileChooserDefault *impl; - - profile_start ("start", NULL); - - impl = GTK_FILE_CHOOSER_DEFAULT (data); - g_assert (impl->load_state == LOAD_PRELOAD); - g_assert (impl->load_timeout_id != 0); - g_assert (impl->browse_files_model != NULL); - - impl->load_timeout_id = 0; - impl->load_state = LOAD_LOADING; - - load_set_model (impl); - - profile_end ("end", NULL); - - return FALSE; -} - -/* Sets up a new load timer for the model and switches to the LOAD_PRELOAD state */ -static void -load_setup_timer (GtkFileChooserDefault *impl) -{ - g_assert (impl->load_timeout_id == 0); - g_assert (impl->load_state != LOAD_PRELOAD); - - impl->load_timeout_id = gdk_threads_add_timeout (MAX_LOADING_TIME, load_timeout_cb, impl); - impl->load_state = LOAD_PRELOAD; -} - -/* Removes the load timeout; changes the impl->load_state to the specified value. */ -static void -load_remove_timer (GtkFileChooserDefault *impl, LoadState new_load_state) -{ - if (impl->load_timeout_id != 0) - { - g_assert (impl->load_state == LOAD_PRELOAD); - - g_source_remove (impl->load_timeout_id); - impl->load_timeout_id = 0; - } - else - g_assert (impl->load_state == LOAD_EMPTY || - impl->load_state == LOAD_LOADING || - impl->load_state == LOAD_FINISHED); - - g_assert (new_load_state == LOAD_EMPTY || - new_load_state == LOAD_LOADING || - new_load_state == LOAD_FINISHED); - impl->load_state = new_load_state; -} - /* Selects the first row in the file list */ static void browse_files_select_first_row (GtkFileChooserDefault *impl) @@ -7686,9 +7636,13 @@ pending_select_files_process (GtkFileChooserDefault *impl) * but rather on behalf of something else like GtkFileChooserButton. In * 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 what the user + * selected meanwhile. */ 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); } @@ -7729,14 +7683,11 @@ browse_files_model_finished_loading_cb (GtkFileSystemModel *model, if (error) show_error_on_reading_current_folder (impl, error); - if (impl->load_state == LOAD_PRELOAD) + if (impl->load_state == LOAD_LOADING) { - load_remove_timer (impl, LOAD_FINISHED); - load_set_model (impl); - } - else if (impl->load_state == LOAD_LOADING) - { - /* Nothing */ + /* The icon view only gets the model now (see set_list_model()). */ + if (impl->current_model != GTK_TREE_MODEL (impl->browse_files_model)) + load_set_model (impl); } else { @@ -7747,8 +7698,6 @@ browse_files_model_finished_loading_cb (GtkFileSystemModel *model, return; } - g_assert (impl->load_timeout_id == 0); - impl->load_state = LOAD_FINISHED; pending_select_files_process (impl); @@ -7764,7 +7713,7 @@ static void stop_loading_and_clear_list_model (GtkFileChooserDefault *impl, gboolean remove_from_treeview) { - load_remove_timer (impl, LOAD_EMPTY); + impl->load_state = LOAD_EMPTY; if (impl->browse_files_model) { @@ -8199,13 +8148,18 @@ set_list_model (GtkFileChooserDefault *impl, g_signal_connect (impl->browse_files_model, "sort-column-changed", G_CALLBACK (list_sort_column_changed_cb), impl); - load_setup_timer (impl); /* This changes the state to LOAD_PRELOAD */ + impl->load_state = LOAD_LOADING; g_signal_connect (impl->browse_files_model, "finished-loading", G_CALLBACK (browse_files_model_finished_loading_cb), impl); install_list_model_filter (impl); + /* The list shows the files as they come in. GtkIconView inserts each + * row in O(n), so it gets the model once loading is done. */ + if (impl->view_mode == VIEW_MODE_LIST) + load_set_model (impl); + profile_end ("end", NULL); return TRUE; diff --git a/gtk/gtkfilechooserprivate.h b/gtk/gtkfilechooserprivate.h index 46bf0a604..1154003fd 100644 --- a/gtk/gtkfilechooserprivate.h +++ b/gtk/gtkfilechooserprivate.h @@ -122,8 +122,7 @@ struct _GtkFileChooserWidgetPrivate typedef enum { LOAD_EMPTY, /* There is no model */ - LOAD_PRELOAD, /* Model is loading and a timer is running; model isn't inserted into the tree yet */ - LOAD_LOADING, /* Timeout expired, model is inserted into the tree, but not fully loaded yet */ + LOAD_LOADING, /* Model is loading; the list view shows it, the icon view gets it when loading is done */ LOAD_FINISHED /* Model is fully loaded and inserted into the tree */ } LoadState; @@ -263,7 +262,6 @@ struct _GtkFileChooserDefault LoadState load_state; ReloadState reload_state; - guint load_timeout_id; OperationMode operation_mode; From e98b38f46eaaeebf2f8eb7436eb4eee1eb17309c Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 13:57:55 +0200 Subject: [PATCH 06/12] filechooser: use fast-content-type, read files only for MIME filters --- gtk/gtkfilechooserdefault.c | 2 +- gtk/gtkfilesystemmodel.c | 125 +++++++++++++++++++++++++++++++++++- 2 files changed, 125 insertions(+), 2 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 2ba1f9dff..e295980a1 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -196,7 +196,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 16bc2b81e..f7bf1bb13 100644 --- a/gtk/gtkfilesystemmodel.c +++ b/gtk/gtkfilesystemmodel.c @@ -116,6 +116,11 @@ #define MODEL_COMMIT_INTERVAL_US (250 * 1000) #define MODEL_MAX_COMMIT_INTERVAL_US (1000 * 1000) +/* Reading file contents to find out its type is slow on a slow disk or + * share; only a few such reads run at a time. */ +#define MODEL_MAX_SNIFFS 2 +#define MODEL_SNIFFED_ATTRIBUTE "gtk-fsmodel::sniffed" + #define VALUE_PAGE_SHIFT 6 #define VALUE_PAGE_SIZE (1u << VALUE_PAGE_SHIFT) #define VALUE_PAGE_MASK (VALUE_PAGE_SIZE - 1u) @@ -174,6 +179,12 @@ struct _GtkFileSystemModel guint monitor_serial; GHashTable * deleted_files; /* deleted while the enumerator may still return them */ + /* Content type detection for files whose name does not tell the type + * (see node_get_content_type()) */ + GQueue sniff_queue; /* GFiles waiting */ + GHashTable * sniff_pending; /* GFiles waiting or running */ + guint sniff_running; + /* Loading */ GQueue pending_infos; /* GFileInfos from the enumerator, not added yet */ GError * load_error; @@ -655,6 +666,115 @@ node_retire_slot (GtkFileSystemModel *model, model->free_id_head = id; } +static void gtk_file_system_model_sniff_next (GtkFileSystemModel *model); + +static void +gtk_file_system_model_sniff_done (GObject *object, + GAsyncResult *res, + gpointer data) +{ + GtkFileSystemModel *model = data; /* only a valid pointer if not cancelled */ + GFile *file = G_FILE (object); + GError *error = NULL; + GFileInfo *sniffed; + 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--; + + id = node_get_for_file (model, file); + if (id != 0) + { + FileModelNode *node = get_node (model, id); + GFileInfo *info = g_file_info_dup (node->info); + + /* Failures are remembered too, so the file is not read 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)); + + _gtk_file_system_model_update_file (model, file, info); + g_object_unref (info); + + /* The type decides whether the filter lets the file pass. */ + node->want_refilter = TRUE; + node_queue (model, id); + } + + g_hash_table_remove (model->sniff_pending, file); /* drops the last ref of @file */ + gtk_file_system_model_sniff_next (model); + + gdk_threads_leave (); + + if (sniffed) + g_object_unref (sniffed); +} + +static void +gtk_file_system_model_sniff_next (GtkFileSystemModel *model) +{ + while (model->sniff_running < MODEL_MAX_SNIFFS && + !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); + } +} + +/* Returns the content type of a node for filtering. The file chooser + * lists folders with standard::fast-content-type, which only looks at the + * file name: reading every file is far too slow on a slow disk or share. + * If the name does not tell the type, the content is read in the + * background and the node filtered again when the type is known. */ +static const char * +node_get_content_type (GtkFileSystemModel *model, + FileModelNode *node) +{ + const char *type; + + /* Ask for attributes only if they were queried; GLib warns otherwise. */ + 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_has_attribute (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); + + if (!g_hash_table_contains (model->sniff_pending, node->file)) + { + g_hash_table_add (model->sniff_pending, g_object_ref (node->file)); + g_queue_push_tail (&model->sniff_queue, node->file); + gtk_file_system_model_sniff_next (model); + } + + return type; +} + static gboolean node_should_be_filtered_out (GtkFileSystemModel *model, guint id) { @@ -680,7 +800,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); @@ -2064,6 +2184,9 @@ gtk_file_system_model_finalize (GObject *object) g_hash_table_destroy (model->monitor_queries); if (model->deleted_files) g_hash_table_destroy (model->deleted_files); + g_queue_clear (&model->sniff_queue); + if (model->sniff_pending) + g_hash_table_destroy (model->sniff_pending); g_hash_table_destroy (model->file_lookup); if (model->filter) g_object_unref (model->filter); From 32175fcd808aa567080363051dc366b01c2b41ef Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 14:02:04 +0200 Subject: [PATCH 07/12] filechooser: use fixed-height mode for the file list --- gtk/gtkfilechooserdefault.c | 147 ++++++++++++++++++++++++++++++++++-- 1 file changed, 139 insertions(+), 8 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index e295980a1..1dc106df7 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -4791,6 +4791,136 @@ update_icon_view_cell_layout (GtkFileChooserDefault *impl) } } +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)); + /* 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 = file_list_measure_texts (tree_view, texts) + + 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: all rows have the same height and + * the columns fixed widths, so the tree view does not measure every row of + * a large folder. The size and date columns get the width of the widest + * strings they can show in this locale; the name column takes the rest. */ +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; + + /* Size column: the longest strings g_format_size() gives 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, + * 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); + + 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); +} + +/* The widths depend on the font. */ +static void +file_list_style_set_cb (GtkWidget *widget, + GtkStyle *previous_style, + GtkFileChooserDefault *impl) +{ + file_list_update_fixed_sizing (impl); +} + /* Creates the list view */ static GtkWidget * create_browse_files_tree_view (GtkFileChooserDefault *impl) @@ -4883,9 +5013,10 @@ 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_column_pack_start (column, renderer, TRUE); gtk_tree_view_append_column (GTK_TREE_VIEW (impl->browse_files_tree_view), column); impl->list_size_column = column; @@ -4896,6 +5027,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; @@ -4903,6 +5035,10 @@ create_browse_files_tree_view (GtkFileChooserDefault *impl) file_list_set_sort_column_ids (impl); update_cell_renderer_attributes (impl); + 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; } @@ -7443,7 +7579,6 @@ load_set_model (GtkFileChooserDefault *impl) if (impl->view_mode == VIEW_MODE_LIST) { - gtk_tree_view_columns_autosize (GTK_TREE_VIEW (impl->browse_files_tree_view)); gtk_tree_view_set_search_column (GTK_TREE_VIEW (impl->browse_files_tree_view), MODEL_COL_NAME); file_list_set_sort_column_ids (impl); @@ -8059,11 +8194,7 @@ file_system_model_set (GtkFileSystemModel *model, if (info == NULL || _gtk_file_info_consider_as_directory (info)) g_value_set_string (value, NULL); else -#if GLIB_CHECK_VERSION(2,30,0) - g_value_take_string (value, g_format_size (g_file_info_get_size (info))); -#else - g_value_take_string (value, g_format_size_for_display (g_file_info_get_size (info))); -#endif + g_value_take_string (value, file_list_format_size (g_file_info_get_size (info))); break; case MODEL_COL_MTIME: case MODEL_COL_MTIME_TEXT: From da49e7bb796784c92274a9b80c8651340823d83d Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 14:05:13 +0200 Subject: [PATCH 08/12] gtkiconview: reuse cell layouts across relayouts, avoid O(n) walks per row The cached cell layout is dropped together with the item size, so changes still have to come with a row-changed, just like for the item size. --- gtk/gtkiconview.c | 152 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 150 insertions(+), 2 deletions(-) diff --git a/gtk/gtkiconview.c b/gtk/gtkiconview.c index 618f7132d..78e415478 100644 --- a/gtk/gtkiconview.c +++ b/gtk/gtkiconview.c @@ -74,6 +74,15 @@ struct _GtkIconViewItem guint selected : 1; guint selected_before_rubberbanding : 1; + /* The result of the last gtk_icon_view_calculate_item_size2() and its + * inputs: the item geometry before the call, the per-cell maximum + * heights of the row and the text direction. Invalidated together with + * the item size (see gtk_icon_view_item_invalidate_size()). */ + 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 +115,14 @@ struct _GtkIconViewPrivate { gint width, height; + /* The item last looked up by index, so that row-changed for consecutive + * rows is O(1) instead of O(n) each. Reset when items are removed or + * reordered. */ + GList *nth_cache_link; + + /* The text cell's wrap width at the last layout (see adjust_wrap_width()) */ + gint last_wrap_width; + GtkSelectionMode selection_mode; GdkWindow *bin_window; @@ -1425,6 +1442,9 @@ gtk_icon_view_style_set (GtkWidget *widget, gdk_window_set_background (icon_view->priv->bin_window, &widget->style->base[widget->state]); } + /* Fonts and spacing may have changed: measure the items again. */ + gtk_icon_view_invalidate_sizes (icon_view); + gtk_widget_queue_resize (widget); } @@ -1590,6 +1610,10 @@ gtk_icon_view_expose (GtkWidget *widget, GtkIconViewItem *item = icons->data; GdkRectangle area; + /* Rows are laid out top to bottom; nothing after this is 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 +2711,69 @@ gtk_icon_view_adjustment_changed (GtkAdjustment *adjustment, } } +/* Makes the next layout measure the cells of all items again, as + * gtk_icon_view_calculate_item_size2() always did before its results were + * kept: for changes to the cells that do not invalidate the item sizes. */ +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_calculate_item_size2(), but if nothing it depends on + * changed except the item position, the cell boxes of the last call are + * moved instead of measuring all cells again. Measuring text is by far + * the most expensive part of a relayout, and every model change relayouts + * all items, 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 (item->layout_valid && + item->n_cells == n_cells && + 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; + + 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 GList * gtk_icon_view_layout_single_row (GtkIconView *icon_view, GList *first_item, @@ -2771,7 +2858,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) @@ -2986,6 +3073,12 @@ adjust_wrap_width (GtkIconView *icon_view, wrap_width -= icon_view->priv->item_padding * 2; + if (wrap_width != icon_view->priv->last_wrap_width) + { + icon_view->priv->last_wrap_width = wrap_width; + gtk_icon_view_invalidate_cell_layouts (icon_view); + } + g_object_set (text_info->cell, "wrap-width", wrap_width, NULL); g_object_set (text_info->cell, "width", wrap_width, NULL); } @@ -3011,6 +3104,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 +3254,7 @@ gtk_icon_view_item_invalidate_size (GtkIconViewItem *item) { item->width = -1; item->height = -1; + item->layout_valid = FALSE; } static void @@ -3478,6 +3576,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); } @@ -3586,6 +3685,8 @@ gtk_icon_view_unselect_item (GtkIconView *icon_view, static void verify_items (GtkIconView *icon_view) { + /* O(n) for every inserted or deleted row: debug builds only */ +#ifdef G_ENABLE_DEBUG GList *items; int i = 0; @@ -3599,6 +3700,28 @@ verify_items (GtkIconView *icon_view) i++; } +#endif +} + +/* g_list_nth_data() on the items, O(1) when called for consecutive rows */ +static GtkIconViewItem * +gtk_icon_view_nth_item (GtkIconView *icon_view, + gint index) +{ + GtkIconViewPrivate *priv = icon_view->priv; + GList *link = priv->nth_cache_link; + + /* Inserting rows keeps the cached link valid but shifts indices. */ + if (link && ((GtkIconViewItem *) link->data)->index == index) + ; + else if (link && ((GtkIconViewItem *) link->data)->index == index - 1 && link->next) + link = link->next; + else + link = g_list_nth (priv->items, index); + + priv->nth_cache_link = link; + + return link ? link->data : NULL; } static void @@ -3616,7 +3739,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); @@ -3689,6 +3812,8 @@ gtk_icon_view_row_deleted (GtkTreeModel *model, gtk_icon_view_stop_editing (icon_view, TRUE); + icon_view->priv->nth_cache_link = NULL; + if (item == icon_view->priv->anchor_item) icon_view->priv->anchor_item = NULL; @@ -3735,6 +3860,8 @@ gtk_icon_view_rows_reordered (GtkTreeModel *model, gtk_icon_view_stop_editing (icon_view, TRUE); + icon_view->priv->nth_cache_link = NULL; + length = gtk_tree_model_iter_n_children (model, NULL); order = g_new (gint, length); @@ -4603,6 +4730,8 @@ gtk_icon_view_cell_layout_pack_start (GtkCellLayout *layout, icon_view->priv->cell_list = g_list_append (icon_view->priv->cell_list, info); icon_view->priv->n_cells++; + + gtk_icon_view_invalidate_cell_layouts (icon_view); } static void @@ -4626,6 +4755,8 @@ gtk_icon_view_cell_layout_pack_end (GtkCellLayout *layout, icon_view->priv->cell_list = g_list_append (icon_view->priv->cell_list, info); icon_view->priv->n_cells++; + + gtk_icon_view_invalidate_cell_layouts (icon_view); } static void @@ -4644,6 +4775,8 @@ gtk_icon_view_cell_layout_add_attribute (GtkCellLayout *layout, GINT_TO_POINTER (column)); info->attributes = g_slist_prepend (info->attributes, g_strdup (attribute)); + + gtk_icon_view_invalidate_cell_layouts (icon_view); } static void @@ -4660,6 +4793,8 @@ gtk_icon_view_cell_layout_clear (GtkCellLayout *layout) } icon_view->priv->n_cells = 0; + + gtk_icon_view_invalidate_cell_layouts (icon_view); } static void @@ -4686,6 +4821,8 @@ gtk_icon_view_cell_layout_set_cell_data_func (GtkCellLayout *layout, info->func = func; info->func_data = func_data; info->destroy = destroy; + + gtk_icon_view_invalidate_cell_layouts (icon_view); } static void @@ -4697,6 +4834,8 @@ gtk_icon_view_cell_layout_clear_attributes (GtkCellLayout *layout, info = gtk_icon_view_get_cell_info (GTK_ICON_VIEW (layout), renderer); if (info != NULL) free_cell_attributes (info); + + gtk_icon_view_invalidate_cell_layouts (GTK_ICON_VIEW (layout)); } static void @@ -4734,6 +4873,8 @@ gtk_icon_view_cell_layout_reorder (GtkCellLayout *layout, info->position = i; } + gtk_icon_view_invalidate_cell_layouts (icon_view); + gtk_widget_queue_draw (GTK_WIDGET (icon_view)); } @@ -5207,6 +5348,12 @@ gtk_icon_view_get_visible_range (GtkIconView *icon_view, { GtkIconViewItem *item = icons->data; + /* Items are laid out row by row: once one starts below the visible + * area, all following ones do too. */ + 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)) && @@ -5383,6 +5530,7 @@ gtk_icon_view_set_model (GtkIconView *icon_view, g_list_foreach (icon_view->priv->items, (GFunc)gtk_icon_view_item_free, NULL); g_list_free (icon_view->priv->items); icon_view->priv->items = NULL; + icon_view->priv->nth_cache_link = NULL; icon_view->priv->anchor_item = NULL; icon_view->priv->cursor_item = NULL; icon_view->priv->last_single_clicked = NULL; From 6cf67e8b7c4c3e76226f6dff9340b6d5c966fff1 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 15:36:38 +0200 Subject: [PATCH 09/12] filechooser: give all names in the icon view the same height --- gtk/gtkfilechooserdefault.c | 141 ++++++++++++++++++++++++++++++++---- 1 file changed, 128 insertions(+), 13 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 1dc106df7..5e7f83b48 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -4782,13 +4782,8 @@ update_icon_view_cell_layout (GtkFileChooserDefault *impl) } if (impl->list_name_renderer) - { - g_object_set (G_OBJECT (impl->list_name_renderer), - "wrap-width", item_width, - NULL); - gtk_cell_renderer_set_fixed_size (GTK_CELL_RENDERER (impl->list_name_renderer), - item_width, -1); - } + gtk_cell_renderer_set_fixed_size (GTK_CELL_RENDERER (impl->list_name_renderer), + item_width, -1); } static char *my_g_format_time_for_display (gint64 secs); @@ -5043,6 +5038,131 @@ create_browse_files_tree_view (GtkFileChooserDefault *impl) } /* Creates icon view (alternative for the list view) */ +/* The file names in the icon view. GtkIconView measures every item at + * every layout, and a GtkCellRendererText lays out its text with Pango for + * that, which makes laying out a large folder take seconds. This renderer + * has the same height for every name (NAME_RENDERER_LINES lines, longer + * names are ellipsized), so its size is known without laying out any text; + * Pango only runs for the names that are drawn. */ +#define NAME_RENDERER_LINES 3 + +typedef struct +{ + GtkCellRendererText parent; + GtkStyle *metrics_style; /* style line_height was computed for, not a reference */ + gint line_height; +} NameRenderer; + +typedef GtkCellRendererTextClass NameRendererClass; + +static GType name_renderer_get_type (void); +G_DEFINE_TYPE (NameRenderer, name_renderer, GTK_TYPE_CELL_RENDERER_TEXT) + +static PangoLayout * +name_renderer_create_layout (GtkCellRenderer *cell, + GtkWidget *widget, + gint width) +{ + PangoLayout *layout; + + layout = gtk_widget_create_pango_layout (widget, GTK_CELL_RENDERER_TEXT (cell)->text); + pango_layout_set_width (layout, MAX (width, 1) * PANGO_SCALE); + pango_layout_set_wrap (layout, PANGO_WRAP_WORD_CHAR); + pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER); + pango_layout_set_ellipsize (layout, PANGO_ELLIPSIZE_END); + pango_layout_set_height (layout, -NAME_RENDERER_LINES); + + return layout; +} + +static void +name_renderer_get_size (GtkCellRenderer *cell, + GtkWidget *widget, + GdkRectangle *cell_area, + gint *x_offset, + gint *y_offset, + gint *width, + gint *height) +{ + NameRenderer *renderer = (NameRenderer *) cell; + + /* Without a fixed width the text decides it. */ + if (width) + { + GTK_CELL_RENDERER_CLASS (name_renderer_parent_class)->get_size (cell, widget, cell_area, + x_offset, y_offset, + width, height); + return; + } + + if (renderer->metrics_style != widget->style) + { + PangoContext *context = gtk_widget_get_pango_context (widget); + PangoFontMetrics *metrics; + + metrics = pango_context_get_metrics (context, widget->style->font_desc, + pango_context_get_language (context)); + renderer->line_height = PANGO_PIXELS (pango_font_metrics_get_ascent (metrics) + + pango_font_metrics_get_descent (metrics)); + pango_font_metrics_unref (metrics); + renderer->metrics_style = widget->style; + } + + if (height) + *height = 2 * cell->ypad + NAME_RENDERER_LINES * renderer->line_height; + if (x_offset) + *x_offset = 0; + if (y_offset) + *y_offset = 0; +} + +static void +name_renderer_render (GtkCellRenderer *cell, + GdkDrawable *window, + GtkWidget *widget, + GdkRectangle *background_area, + GdkRectangle *cell_area, + GdkRectangle *expose_area, + GtkCellRendererState flags) +{ + PangoLayout *layout; + GtkStateType state; + + if (GTK_CELL_RENDERER_TEXT (cell)->text == NULL) + return; + + if (!cell->sensitive) + state = GTK_STATE_INSENSITIVE; + else if (flags & GTK_CELL_RENDERER_SELECTED) + state = gtk_widget_has_focus (widget) ? GTK_STATE_SELECTED : GTK_STATE_ACTIVE; + else if (flags & GTK_CELL_RENDERER_PRELIT && gtk_widget_get_state (widget) == GTK_STATE_PRELIGHT) + state = GTK_STATE_PRELIGHT; + else + state = gtk_widget_get_state (widget) == GTK_STATE_INSENSITIVE ? GTK_STATE_INSENSITIVE : GTK_STATE_NORMAL; + + /* As wide as the item, like the wrap width a text renderer gets here. */ + layout = name_renderer_create_layout (cell, widget, cell_area->width); + gtk_paint_layout (widget->style, window, state, TRUE, expose_area, widget, + "cellrenderertext", + cell_area->x, cell_area->y + cell->ypad, + layout); + g_object_unref (layout); +} + +static void +name_renderer_class_init (NameRendererClass *class) +{ + GtkCellRendererClass *cell_class = GTK_CELL_RENDERER_CLASS (class); + + cell_class->get_size = name_renderer_get_size; + cell_class->render = name_renderer_render; +} + +static void +name_renderer_init (NameRenderer *renderer) +{ +} + static GtkWidget * create_browse_files_icon_view (GtkFileChooserDefault *impl) { @@ -5097,12 +5217,7 @@ create_browse_files_icon_view (GtkFileChooserDefault *impl) gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (impl->browse_files_icon_view), impl->list_icon_renderer, "pixbuf", MODEL_COL_ICON_PIXBUF); - impl->list_name_renderer = gtk_cell_renderer_text_new (); - g_object_set (G_OBJECT (impl->list_name_renderer), - "alignment", PANGO_ALIGN_CENTER, - "wrap-mode", PANGO_WRAP_WORD_CHAR, - "yalign", 0.0f, - NULL); + impl->list_name_renderer = g_object_new (name_renderer_get_type (), NULL); update_icon_view_cell_layout (impl); g_signal_connect (impl->list_name_renderer, "edited", From 89850b36029f22582a05ab1d4e2a1757a8b6de80 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 14:11:56 +0200 Subject: [PATCH 10/12] filechooser: query icons only for the rows on screen --- gtk/gtkfilechooserdefault.c | 300 +++++++++++++++++++++++++++++------- gtk/gtkfilechooserprivate.h | 5 + gtk/gtkfilesystemmodel.c | 19 --- gtk/gtkfilesystemmodel.h | 1 - 4 files changed, 248 insertions(+), 77 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 5e7f83b48..51eaba8d3 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -406,6 +406,10 @@ static void remove_bookmark_button_clicked_cb (GtkButton *button, static void update_cell_renderer_attributes (GtkFileChooserDefault *impl); static void load_set_model (GtkFileChooserDefault *impl); +static gboolean icons_queue_update (GtkWidget *view, + GdkEventExpose *event, + GtkFileChooserDefault *impl); +static void icon_queries_cancel_all (GtkFileChooserDefault *impl); static void browse_files_center_selected_row (GtkFileChooserDefault *impl); static void view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode); @@ -4973,6 +4977,8 @@ create_browse_files_tree_view (GtkFileChooserDefault *impl) g_signal_connect (selection, "changed", G_CALLBACK (list_selection_changed), impl); + g_signal_connect (impl->browse_files_tree_view, "expose-event", + G_CALLBACK (icons_queue_update), impl); /* Keep the column order in sync with update_cell_renderer_attributes() */ @@ -5179,6 +5185,8 @@ create_browse_files_icon_view (GtkFileChooserDefault *impl) G_CALLBACK (browse_files_key_press_event_cb), impl); g_signal_connect (impl->browse_files_icon_view, "selection-changed", G_CALLBACK (list_selection_changed), impl); + g_signal_connect (impl->browse_files_icon_view, "expose-event", + G_CALLBACK (icons_queue_update), impl); g_signal_connect (impl->browse_files_icon_view, "popup-menu", G_CALLBACK (list_popup_menu_cb), impl); g_signal_connect (impl->browse_files_icon_view, "button-press-event", @@ -7089,6 +7097,8 @@ cancel_all_operations (GtkFileChooserDefault *impl) impl->shortcuts_activate_iter_cancellable = NULL; } + icon_queries_cancel_all (impl); + search_stop_searching (impl, TRUE); recent_stop_loading (impl); } @@ -7967,6 +7977,11 @@ stop_loading_and_clear_list_model (GtkFileChooserDefault *impl, if (impl->browse_files_model) { + /* Icon queries keep the model alive; drop them so it is disposed + * and stops loading now, and do not hear from it any more. */ + icon_queries_cancel_all (impl); + g_signal_handlers_disconnect_by_data (impl->browse_files_model, impl); + if (impl->current_model == GTK_TREE_MODEL (impl->browse_files_model)) impl->current_model = NULL; g_object_unref (impl->browse_files_model); @@ -8105,44 +8120,250 @@ 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 in the background, only for the + * rows on screen: after the view was drawn, icons_update() looks at the + * visible rows once, queries those without an icon from top to bottom and + * cancels the queries for rows that were scrolled away, which matters on + * slow shares where each query takes a while. */ +#define ICON_QUERIES_MAX_RUNNING 16 +#define ICON_QUERIED_ATTRIBUTE "filechooser::icon_queried" + +typedef struct { - GtkFileSystemModel *model = data; /* might be unreffed if operation was cancelled */ + GtkFileChooserDefault *impl; /* owns a reference */ + GtkFileSystemModel *model; /* owns a reference; NULL once cancelled */ + GFile *file; + GCancellable *cancellable; +} IconQuery; + +static void +icon_query_free (IconQuery *query) +{ + if (query->model) + g_object_unref (query->model); + g_object_unref (query->cancellable); + g_object_unref (query->file); + g_object_unref (query->impl); + g_slice_free (IconQuery, query); +} + +/* Cancels @query; its row may be queried again when it is shown. */ +static void +icon_query_cancel (IconQuery *query) +{ + GtkTreeIter iter; + + if (query->model == NULL) + return; + + if (_gtk_file_system_model_get_iter_for_file (query->model, &iter, query->file)) + { + GFileInfo *info = _gtk_file_system_model_get_info (query->model, &iter); + + if (info) + g_file_info_remove_attribute (info, ICON_QUERIED_ATTRIBUTE); + } + + g_cancellable_cancel (query->cancellable); + g_clear_object (&query->model); +} + +static void icon_queries_start (GtkFileChooserDefault *impl); + +static void +icon_query_done (GObject *object, + GAsyncResult *res, + gpointer data) +{ + IconQuery *query = data; + GtkFileChooserDefault *impl = query->impl; GFile *file = G_FILE (object); - GFileInfo *queried, *info; + GFileInfo *queried; GtkTreeIter iter; queried = g_file_query_info_finish (file, res, NULL); - if (queried == NULL) - return; GDK_THREADS_ENTER (); - /* now we know model is valid */ + impl->icon_queries_running = g_list_remove (impl->icon_queries_running, query); - /* file was deleted */ - if (!_gtk_file_system_model_get_iter_for_file (model, &iter, file)) + /* Failed queries are not repeated; the file may have been removed. */ + if (queried && query->model && + _gtk_file_system_model_get_iter_for_file (query->model, &iter, file)) { - g_object_unref (queried); - GDK_THREADS_LEAVE (); - return; + GFileInfo *info = g_file_info_dup (_gtk_file_system_model_get_info (query->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 (query->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); - - _gtk_file_system_model_update_file (model, file, info); - - g_object_unref (info); - g_object_unref (queried); + /* The query may hold the last reference to @impl. */ + icon_queries_start (impl); + icon_query_free (query); GDK_THREADS_LEAVE (); } +static void +icon_queries_start (GtkFileChooserDefault *impl) +{ + while (g_list_length (impl->icon_queries_running) < ICON_QUERIES_MAX_RUNNING && + !g_queue_is_empty (&impl->icon_queries_waiting)) + { + IconQuery *query = g_queue_pop_head (&impl->icon_queries_waiting); + + impl->icon_queries_running = g_list_prepend (impl->icon_queries_running, query); + g_file_query_info_async (query->file, + G_FILE_ATTRIBUTE_THUMBNAIL_PATH "," + G_FILE_ATTRIBUTE_THUMBNAILING_FAILED "," + G_FILE_ATTRIBUTE_STANDARD_ICON, + G_FILE_QUERY_INFO_NONE, + G_PRIORITY_DEFAULT, + query->cancellable, + icon_query_done, + query); + } +} + +static void +icon_queries_cancel_all (GtkFileChooserDefault *impl) +{ + GList *l; + + if (impl->icons_update_id) + { + g_source_remove (impl->icons_update_id); + impl->icons_update_id = 0; + } + + while (!g_queue_is_empty (&impl->icon_queries_waiting)) + { + IconQuery *query = g_queue_pop_head (&impl->icon_queries_waiting); + + icon_query_cancel (query); + icon_query_free (query); + } + + /* Running queries free themselves when they complete. */ + for (l = impl->icon_queries_running; l; l = l->next) + icon_query_cancel (l->data); +} + +static gboolean +icons_update_cb (gpointer data) +{ + GtkFileChooserDefault *impl = data; + GtkFileSystemModel *model; + GtkTreePath *start, *end; + gint first = 0, last = -1, margin = 0; + GList *l; + gint row; + + GDK_THREADS_ENTER (); + + impl->icons_update_id = 0; + + if (!GTK_IS_FILE_SYSTEM_MODEL (impl->current_model)) + { + icon_queries_cancel_all (impl); + goto out; + } + + model = GTK_FILE_SYSTEM_MODEL (impl->current_model); + + if (get_visible_range (&start, &end, impl)) + { + /* Like GTK 3, also query the rows just outside the view. */ + first = MAX (0, gtk_tree_path_get_indices (start)[0] - 1); + last = gtk_tree_path_get_indices (end)[0] + 1; + margin = last - first + 1; + gtk_tree_path_free (start); + gtk_tree_path_free (end); + } + + /* The waiting queries are replaced by the rows on screen now. */ + while (!g_queue_is_empty (&impl->icon_queries_waiting)) + { + IconQuery *query = g_queue_pop_head (&impl->icon_queries_waiting); + + icon_query_cancel (query); + icon_query_free (query); + } + + /* Running ones may finish if their row is still within a page. */ + for (l = impl->icon_queries_running; l; l = l->next) + { + IconQuery *query = l->data; + GtkTreeIter iter; + + if (query->model != model || + !_gtk_file_system_model_get_iter_for_file (model, &iter, query->file)) + icon_query_cancel (query); + else + { + GtkTreePath *path = gtk_tree_model_get_path (impl->current_model, &iter); + + row = gtk_tree_path_get_indices (path)[0]; + gtk_tree_path_free (path); + if (row < first - margin || row > last + margin) + icon_query_cancel (query); + } + } + + for (row = first; row <= last; row++) + { + GtkTreeIter iter; + GFileInfo *info; + IconQuery *query; + + if (!gtk_tree_model_iter_nth_child (impl->current_model, &iter, NULL, row)) + break; + + info = _gtk_file_system_model_get_info (model, &iter); + if (info == NULL || + g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_ICON) || + g_file_info_has_attribute (info, ICON_QUERIED_ATTRIBUTE)) + continue; + + g_file_info_set_attribute_boolean (info, ICON_QUERIED_ATTRIBUTE, TRUE); + + query = g_slice_new (IconQuery); + query->impl = g_object_ref (impl); + query->model = g_object_ref (model); + query->file = g_object_ref (_gtk_file_system_model_get_file (model, &iter)); + query->cancellable = g_cancellable_new (); + g_queue_push_tail (&impl->icon_queries_waiting, query); + } + + icon_queries_start (impl); + +out: + GDK_THREADS_LEAVE (); + + return FALSE; +} + +/* Called when the file view is drawn: whatever changed what is on screen + * (scrolling, resizing, new rows, another model), it ends with a redraw. */ +static gboolean +icons_queue_update (GtkWidget *view, + GdkEventExpose *event, + GtkFileChooserDefault *impl) +{ + if (impl->icons_update_id == 0) + impl->icons_update_id = gdk_threads_add_idle (icons_update_cb, impl); + + return FALSE; +} + static gboolean get_visible_range (GtkTreePath **start, GtkTreePath **end, GtkFileChooserDefault *impl) @@ -8216,9 +8437,6 @@ file_system_model_set (GtkFileSystemModel *model, if (info) { GtkTreeModel *tree_model; - GtkTreePath *path, *start, *end; - GtkTreeIter iter; - gboolean file_visible; /* not loading icon view's icon in the list view */ if (column == MODEL_COL_ICON_PIXBUF && impl->view_mode == VIEW_MODE_LIST) @@ -8252,39 +8470,7 @@ file_system_model_set (GtkFileSystemModel *model, return TRUE; } - if (!get_visible_range (&start, &end, impl)) - return FALSE; - - if (!_gtk_file_system_model_get_iter_for_file (model, - &iter, - file)) - 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); - - gtk_tree_path_free (path); - gtk_tree_path_free (start); - gtk_tree_path_free (end); - - if (file_visible) - { - /* #2 start loading standard icon (callback will be handled by #1) */ - if (!g_file_info_has_attribute (info, "filechooser::icon_queried")) - { - 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); - } - } + /* Not known yet: icons_update() queries it once the row is shown. */ return FALSE; } else diff --git a/gtk/gtkfilechooserprivate.h b/gtk/gtkfilechooserprivate.h index 1154003fd..887e31400 100644 --- a/gtk/gtkfilechooserprivate.h +++ b/gtk/gtkfilechooserprivate.h @@ -234,6 +234,11 @@ struct _GtkFileChooserDefault guint icon_view_scale_visible_timeout_id; guint icon_view_scale_after_layout_id; gint pending_icon_view_icon_size; + + /* Icon queries for the rows on screen (see icons_update_cb()) */ + GQueue icon_queries_waiting; + GList *icon_queries_running; + guint icons_update_id; gint icon_view_scale_visible_overscan; ViewMode view_mode; diff --git a/gtk/gtkfilesystemmodel.c b/gtk/gtkfilesystemmodel.c index f7bf1bb13..426650ff0 100644 --- a/gtk/gtkfilesystemmodel.c +++ b/gtk/gtkfilesystemmodel.c @@ -2750,25 +2750,6 @@ _gtk_file_system_model_set_filter_folders (GtkFileSystemModel *model, } } -/** - * _gtk_file_system_model_get_cancellable: - * @model: the model - * - * Gets the cancellable used by the @model. This is the cancellable used - * internally by the @model that will be cancelled when @model is - * disposed. So you can use it for operations that should be cancelled - * when the model goes away. - * - * Returns: The cancellable used by @model - **/ -GCancellable * -_gtk_file_system_model_get_cancellable (GtkFileSystemModel *model) -{ - g_return_val_if_fail (GTK_IS_FILE_SYSTEM_MODEL (model), NULL); - - return model->cancellable; -} - /** * _gtk_file_system_model_iter_is_visible: * @model: the model diff --git a/gtk/gtkfilesystemmodel.h b/gtk/gtkfilesystemmodel.h index 639a47af2..1f00d1f14 100644 --- a/gtk/gtkfilesystemmodel.h +++ b/gtk/gtkfilesystemmodel.h @@ -52,7 +52,6 @@ GtkFileSystemModel *_gtk_file_system_model_new_for_directory(GFile * gpointer get_data, guint n_columns, ...); -GCancellable * _gtk_file_system_model_get_cancellable (GtkFileSystemModel *model); gboolean _gtk_file_system_model_iter_is_visible (GtkFileSystemModel *model, GtkTreeIter *iter); gboolean _gtk_file_system_model_iter_is_filtered_out (GtkFileSystemModel *model, From 21087a40098cc3558521f5aeafc27bb61dd3dda0 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 14:18:34 +0200 Subject: [PATCH 11/12] filechooser: no blocking file system calls when changing folders --- gtk/gtkfilechooserdefault.c | 330 ++++++++++++++++++++++++++---------- gtk/gtkfilechooserprivate.h | 2 + gtk/gtkfilesystem.c | 71 ++++++-- gtk/gtkfilesystem.h | 2 + 4 files changed, 295 insertions(+), 110 deletions(-) diff --git a/gtk/gtkfilechooserdefault.c b/gtk/gtkfilechooserdefault.c index 51eaba8d3..6b5239d85 100644 --- a/gtk/gtkfilechooserdefault.c +++ b/gtk/gtkfilechooserdefault.c @@ -410,6 +410,12 @@ static gboolean icons_queue_update (GtkWidget *view, GdkEventExpose *event, GtkFileChooserDefault *impl); static void icon_queries_cancel_all (GtkFileChooserDefault *impl); +static void create_folder (GtkFileChooserDefault *impl, + GFile *file, + gboolean respond); +static void set_busy_cursor (GtkFileChooserDefault *impl, + gboolean busy); +static void request_response_and_add_to_recent_list (GtkFileChooserDefault *impl); static void browse_files_center_selected_row (GtkFileChooserDefault *impl); static void view_mode_set (GtkFileChooserDefault *impl, ViewMode view_mode); @@ -2176,42 +2182,99 @@ shortcuts_add_bookmarks (GtkFileChooserDefault *impl) profile_end ("end", NULL); } -/* 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_cb (GObject *source, + GAsyncResult *result, + gpointer user_data) +{ + struct CurrentFolderVolumeData *data = user_data; + GtkFileChooserDefault *impl = data->impl; + GtkFileSystemVolume *volume; + GError *error = NULL; + GFile *base_file; + GMount *mount; + int pos; + + mount = g_file_find_enclosing_mount_finish (G_FILE (source), result, &error); + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + goto out; + + GDK_THREADS_ENTER (); + + 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 (data->file, mount); + if (volume) + base_file = _gtk_file_system_volume_get_root (volume); + else + base_file = NULL; + + if (base_file && g_file_equal (base_file, data->file)) + 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, data->file, NULL, FALSE, SHORTCUTS_CURRENT_FOLDER); + if (volume) + _gtk_file_system_volume_unref (volume); + } + + if (base_file) + g_object_unref (base_file); + + GDK_THREADS_LEAVE (); + +out: + g_clear_error (&error); + g_object_unref (data->impl); + g_object_unref (data->file); + g_free (data); +} + +/* Appends a separator and a row to the shortcuts list for the current + * folder. Finding the volume of the folder stats the folder and its + * parents, which can block for a long time on a slow or hung share, so the + * row is added once the answer comes in. */ 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_cb, + data); } /* Updates the current folder row in the shortcuts model */ @@ -2396,6 +2459,85 @@ add_idle_while_impl_is_alive (GtkFileChooserDefault *impl, GCallback callback) return source; } +struct CreateFolderData +{ + GtkFileChooserDefault *impl; + GFile *file; + gboolean respond; +}; + +static void +create_folder_cb (GObject *source, + GAsyncResult *result, + gpointer user_data) +{ + struct CreateFolderData *data = user_data; + GtkFileChooserDefault *impl = data->impl; + GError *error = NULL; + gboolean created; + + created = g_file_make_directory_finish (G_FILE (source), result, &error); + + GDK_THREADS_ENTER (); + + if (data->respond) + set_busy_cursor (impl, FALSE); + + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + g_error_free (error); + else + { + GFile *parent = g_file_get_parent (data->file); + + g_clear_object (&impl->create_folder_cancellable); + + if (!created) + error_creating_folder_dialog (impl, data->file, error); + else if (data->respond) + request_response_and_add_to_recent_list (impl); + /* Show the new folder, unless the user went elsewhere meanwhile. */ + else if (impl->current_folder && parent && g_file_equal (impl->current_folder, parent)) + change_folder_and_display_error (impl, data->file, FALSE); + + if (parent) + g_object_unref (parent); + } + + GDK_THREADS_LEAVE (); + + g_object_unref (data->impl); + g_object_unref (data->file); + g_free (data); +} + +/* Creates the folder @file; on a slow share this can take a while. Then + * either responds (the folder was typed in a "select folder" dialog) or + * shows the new folder. */ +static void +create_folder (GtkFileChooserDefault *impl, + GFile *file, + gboolean respond) +{ + struct CreateFolderData *data; + + if (impl->create_folder_cancellable) + g_cancellable_cancel (impl->create_folder_cancellable); + g_clear_object (&impl->create_folder_cancellable); + impl->create_folder_cancellable = g_cancellable_new (); + + data = g_new (struct CreateFolderData, 1); + data->impl = g_object_ref (impl); + data->file = g_object_ref (file); + data->respond = respond; + + if (respond) + set_busy_cursor (impl, TRUE); + + g_file_make_directory_async (file, G_PRIORITY_DEFAULT, + impl->create_folder_cancellable, + create_folder_cb, data); +} + /* Idle handler for creating a new folder after editing its name cell, or for * canceling the editing. */ @@ -2424,13 +2566,7 @@ 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); - + create_folder (impl, file, FALSE); g_object_unref (file); } else @@ -7097,6 +7233,18 @@ 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); + } + + if (impl->create_folder_cancellable) + { + g_cancellable_cancel (impl->create_folder_cancellable); + g_clear_object (&impl->create_folder_cancellable); + } + icon_queries_cancel_all (impl); search_stop_searching (impl, TRUE); @@ -7912,24 +8060,17 @@ 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); - } - else - msg = g_strdup (_("Could not read the contents of the folder")); + /* Reading the folder just failed; asking it for its display name would + * block a hung network share again. The parse name needs no I/O. */ + name = g_file_get_parse_name (impl->current_folder); + msg = g_strdup_printf (_("Could not read the contents of %s"), name); error_message (impl, msg, error->message); g_free (msg); + g_free (name); } /* Callback used when the file system model finishes loading */ @@ -10162,20 +10303,10 @@ name_entry_get_parent_info_cb (GCancellable *cancellable, else if (data->impl->action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER || data->impl->action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER) { - GError *mkdir_error = NULL; - /* In both cases (SELECT_FOLDER and CREATE_FOLDER), if you type * "/blah/nonexistent" you *will* want a folder created. */ - - set_busy_cursor (data->impl, TRUE); - g_file_make_directory (data->file, NULL, &mkdir_error); - set_busy_cursor (data->impl, FALSE); - - if (!mkdir_error) - request_response_and_add_to_recent_list (data->impl); - else - error_creating_folder_dialog (data->impl, data->file, mkdir_error); + create_folder (data->impl, data->file, TRUE); } else g_assert_not_reached (); @@ -11466,8 +11597,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, @@ -11485,6 +11622,22 @@ shortcuts_activate_get_info_cb (GCancellable *cancellable, if (cancelled) goto out; + /* The location is on a volume that is not mounted: mount it and ask + * again (see shortcuts_activate_mount_enclosing_volume()). */ + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_MOUNTED) && !data->tried_mount) + { + GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (data->impl)); + + data->tried_mount = TRUE; + data->impl->shortcuts_activate_iter_cancellable = + _gtk_file_system_mount_enclosing_volume (data->impl->file_system, data->file, + gtk_mount_operation_new (GTK_WINDOW (toplevel)), + 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 @@ -11507,25 +11660,34 @@ shortcuts_activate_mount_enclosing_volume (GCancellable *cancellable, gpointer user_data) { struct ShortcutsActivateData *data = user_data; + GtkFileChooserDefault *impl = data->impl; + + /* Another location was activated meanwhile, or the dialog went away. */ + if (cancellable != impl->shortcuts_activate_iter_cancellable || + g_cancellable_is_cancelled (cancellable)) + goto out; + + impl->shortcuts_activate_iter_cancellable = NULL; if (error) { - error_changing_folder_dialog (data->impl, data->file, g_error_copy (error)); - - g_object_unref (data->impl); - g_object_unref (data->file); - g_free (data); - - return; + error_changing_folder_dialog (impl, data->file, g_error_copy (error)); + goto out; } - data->impl->shortcuts_activate_iter_cancellable = - _gtk_file_system_get_info (data->impl->file_system, data->file, + impl->shortcuts_activate_iter_cancellable = + _gtk_file_system_get_info (impl->file_system, data->file, "standard::type", shortcuts_activate_get_info_cb, data); + g_object_unref (cancellable); + return; - if (volume) - _gtk_file_system_volume_unref (volume); +out: + g_object_unref (data->impl); + g_object_unref (data->file); + g_free (data); + + g_object_unref (cancellable); } static void @@ -11569,38 +11731,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); - } + /* Ask the location directly instead of looking up its volume first, + * which blocks on a slow share; if it is on a volume that is not + * mounted, the answer says so and the volume is mounted then. */ + 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 887e31400..bebb17687 100644 --- a/gtk/gtkfilechooserprivate.h +++ b/gtk/gtkfilechooserprivate.h @@ -264,6 +264,8 @@ struct _GtkFileChooserDefault GCancellable *file_exists_get_info_cancellable; GCancellable *update_from_entry_cancellable; GCancellable *shortcuts_activate_iter_cancellable; + GCancellable *shortcuts_current_folder_cancellable; + GCancellable *create_folder_cancellable; LoadState load_state; ReloadState reload_state; diff --git a/gtk/gtkfilesystem.c b/gtk/gtkfilesystem.c index 4d78102b7..5ca274d43 100644 --- a/gtk/gtkfilesystem.c +++ b/gtk/gtkfilesystem.c @@ -840,33 +840,62 @@ _gtk_file_system_mount_volume (GtkFileSystem *file_system, return cancellable; } +static void +enclosing_volume_found_cb (GObject *source_object, + GAsyncResult *result, + gpointer user_data) +{ + AsyncFuncData *async_data = user_data; + GtkFileSystemVolume *volume; + GMount *mount; + + mount = g_file_find_enclosing_mount_finish (G_FILE (source_object), result, NULL); + volume = _gtk_file_system_volume_for_mount (G_FILE (source_object), mount); + + gdk_threads_enter (); + ((GtkFileSystemVolumeMountCallback) async_data->callback) (async_data->cancellable, volume, + NULL, async_data->data); + gdk_threads_leave (); + + _gtk_file_system_volume_unref (volume); + free_async_data (async_data); +} + static void enclosing_volume_mount_cb (GObject *source_object, GAsyncResult *result, gpointer user_data) { - GtkFileSystemVolume *volume; AsyncFuncData *async_data; GError *error = NULL; async_data = (AsyncFuncData *) user_data; g_file_mount_enclosing_volume_finish (G_FILE (source_object), result, &error); - volume = _gtk_file_system_get_volume_for_file (async_data->file_system, G_FILE (source_object)); /* Silently drop G_IO_ERROR_ALREADY_MOUNTED error for gvfs backends without visible mounts. */ /* Better than doing query_info with additional I/O every time. */ if (error && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_ALREADY_MOUNTED)) g_clear_error (&error); - gdk_threads_enter (); - ((GtkFileSystemVolumeMountCallback) async_data->callback) (async_data->cancellable, volume, - error, async_data->data); - gdk_threads_leave (); - if (error) - g_error_free (error); + { + gdk_threads_enter (); + ((GtkFileSystemVolumeMountCallback) async_data->callback) (async_data->cancellable, NULL, + error, async_data->data); + gdk_threads_leave (); - _gtk_file_system_volume_unref (volume); + g_error_free (error); + free_async_data (async_data); + return; + } + + /* Finding the volume stats @file and its parents on the share that was + * just mounted, which can take a while. */ + g_file_find_enclosing_mount_async (G_FILE (source_object), + G_PRIORITY_DEFAULT, + async_data->cancellable, + enclosing_volume_found_cb, + async_data); } GCancellable * @@ -1077,22 +1106,30 @@ _gtk_file_system_set_bookmark_label (GtkFileSystem *file_system, g_signal_emit_by_name (file_system, "bookmarks-changed", 0); } +/* The volume for the result of g_file_find_enclosing_mount() (or its + * async variant) for @file; takes ownership of @mount. */ GtkFileSystemVolume * -_gtk_file_system_get_volume_for_file (GtkFileSystem *file_system, - GFile *file) +_gtk_file_system_volume_for_mount (GFile *file, + GMount *mount) { - GMount *mount; - - DEBUG ("get_volume_for_file"); - - mount = g_file_find_enclosing_mount (file, NULL, NULL); - if (!mount && g_file_is_native (file)) return (GtkFileSystemVolume *) root_volume_token; return (GtkFileSystemVolume *) mount; } +/* Blocks while @file and its parents are examined; code on the main thread + * should use g_file_find_enclosing_mount_async() and + * _gtk_file_system_volume_for_mount() instead. */ +GtkFileSystemVolume * +_gtk_file_system_get_volume_for_file (GtkFileSystem *file_system, + GFile *file) +{ + DEBUG ("get_volume_for_file"); + + return _gtk_file_system_volume_for_mount (file, g_file_find_enclosing_mount (file, NULL, NULL)); +} + /* GtkFolder methods */ static void gtk_folder_set_property (GObject *object, diff --git a/gtk/gtkfilesystem.h b/gtk/gtkfilesystem.h index 7fc539ec1..75f1c97e8 100644 --- a/gtk/gtkfilesystem.h +++ b/gtk/gtkfilesystem.h @@ -130,6 +130,8 @@ void _gtk_file_system_set_bookmark_label (GtkFileSystem *file_system, GFile *file, const gchar *label); +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 9a491e585a1083454fa7edd6c0648f30ec2b75a6 Mon Sep 17 00:00:00 2001 From: Daemonratte Date: Tue, 13 Oct 2026 14:19:38 +0200 Subject: [PATCH 12/12] gtkfilesystem: bound the shared file icon cache --- gtk/gtkfilesystem.c | 117 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 103 insertions(+), 14 deletions(-) diff --git a/gtk/gtkfilesystem.c b/gtk/gtkfilesystem.c index 5ca274d43..9834033ed 100644 --- a/gtk/gtkfilesystem.c +++ b/gtk/gtkfilesystem.c @@ -1663,18 +1663,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"); @@ -1682,14 +1769,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), @@ -1708,7 +1797,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; @@ -1732,7 +1821,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); } @@ -1758,7 +1847,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;