diff --git a/linux/changelog.d/4110.fixed.md b/linux/changelog.d/4110.fixed.md new file mode 100644 index 0000000000..3588c3b708 --- /dev/null +++ b/linux/changelog.d/4110.fixed.md @@ -0,0 +1 @@ +Row numbers scrolled out of view when columns were scrolled sideways. diff --git a/linux/crates/app/src/test_support/key_injection_error.rs b/linux/crates/app/src/test_support/key_injection_error.rs index 1bef1ff368..6e9d5fe845 100644 --- a/linux/crates/app/src/test_support/key_injection_error.rs +++ b/linux/crates/app/src/test_support/key_injection_error.rs @@ -6,8 +6,12 @@ pub(crate) enum KeyInjectionError { Connection(#[from] x11rb::errors::ConnectionError), #[error("the X server refused a request: {0}")] Reply(#[from] x11rb::errors::ReplyError), + #[error("could not allocate an X resource: {0}")] + Resource(#[from] x11rb::errors::ReplyOrIdError), #[error("no keycode carries keysym {0:#x}")] KeysymNotMapped(u32), + #[error("pointer target ({x}, {y}) is outside the {width} by {height} X screen")] + PointerOutsideScreen { x: i16, y: i16, width: u16, height: u16 }, #[error("the widget is not on screen")] NotShown, /// XTEST reaches GDK only through an X11 display; set GDK_BACKEND=x11. diff --git a/linux/crates/app/src/test_support/key_injector.rs b/linux/crates/app/src/test_support/key_injector.rs index cc52b9a88e..625466290d 100644 --- a/linux/crates/app/src/test_support/key_injector.rs +++ b/linux/crates/app/src/test_support/key_injector.rs @@ -3,8 +3,8 @@ use gtk4::prelude::*; use gtk4::{gdk, graphene}; use x11rb::connection::Connection; use x11rb::protocol::xproto::{ - BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, ConnectionExt as _, KEY_PRESS_EVENT, KEY_RELEASE_EVENT, - MOTION_NOTIFY_EVENT, + BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, ConnectionExt as _, CreateWindowAux, KEY_PRESS_EVENT, KEY_RELEASE_EVENT, + MOTION_NOTIFY_EVENT, Window, WindowClass, }; use x11rb::protocol::xtest::ConnectionExt as _; use x11rb::rust_connection::RustConnection; @@ -89,15 +89,101 @@ impl KeyInjector { Ok(()) } - /// Click the primary button `count` times at `at` in `widget`'s own - /// coordinates, in the window that has the keyboard. A widget not laid - /// out yet sits at the window's corner, so it is refused. pub(crate) fn click( &self, widget: &impl IsA, at: (f32, f32), count: u8, ) -> Result<(), KeyInjectionError> { + self.button(widget, at, 1, count) + } + + pub(crate) fn button( + &self, + widget: &impl IsA, + at: (f32, f32), + button: u8, + count: u8, + ) -> Result<(), KeyInjectionError> { + self.move_pointer(widget, at)?; + for _ in 0..count { + self.fake(BUTTON_PRESS_EVENT, button)?; + self.fake(BUTTON_RELEASE_EVENT, button)?; + } + self.connection.flush()?; + self.connection.get_input_focus()?.reply()?; + Ok(()) + } + + pub(crate) fn drag( + &self, + widget: &impl IsA, + from: (f32, f32), + to: (f32, f32), + ) -> Result<(), KeyInjectionError> { + self.move_pointer(widget, from)?; + self.fake(BUTTON_PRESS_EVENT, 1)?; + self.connection.flush()?; + self.connection.get_input_focus()?.reply()?; + super::drain_main_context(); + for step in 1..=10 { + let fraction = step as f32 / 10.0; + let point = (from.0 + (to.0 - from.0) * fraction, from.1 + (to.1 - from.1) * fraction); + self.move_pointer(widget, point)?; + self.connection.flush()?; + self.connection.get_input_focus()?.reply()?; + super::drain_main_context(); + } + self.fake(BUTTON_RELEASE_EVENT, 1)?; + self.connection.flush()?; + self.connection.get_input_focus()?.reply()?; + Ok(()) + } + + pub(crate) fn hover(&self, widget: &impl IsA, at: (f32, f32)) -> Result<(), KeyInjectionError> { + self.move_pointer(widget, at)?; + self.connection.flush()?; + self.connection.get_input_focus()?.reply()?; + Ok(()) + } + + pub(crate) fn cover_pointer(&self) -> Result, KeyInjectionError> { + let root = self + .connection + .setup() + .roots + .first() + .map(|screen| screen.root) + .ok_or(KeyInjectionError::NotShown)?; + let pointer = self.connection.query_pointer(root)?.reply()?; + let window = self.connection.generate_id()?; + // A native cover triggers crossing events without pointer motion or a keyboard grab. + self.connection + .create_window( + 0, + window, + root, + pointer.root_x.saturating_sub(8), + pointer.root_y.saturating_sub(8), + 16, + 16, + 0, + WindowClass::INPUT_ONLY, + 0, + &CreateWindowAux::new().override_redirect(1), + )? + .check()?; + let cover = PointerCover { keys: self, window }; + self.connection.map_window(window)?.check()?; + Ok(cover) + } + + fn uncover_pointer(&self, window: Window) -> Result<(), KeyInjectionError> { + self.connection.destroy_window(window)?.check()?; + Ok(()) + } + + fn move_pointer(&self, widget: &impl IsA, at: (f32, f32)) -> Result<(), KeyInjectionError> { let widget = widget.as_ref(); if !widget.is_mapped() || widget.width() <= 0 { return Err(KeyInjectionError::NotShown); @@ -109,25 +195,31 @@ impl KeyInjector { let (left, top) = native.surface_transform(); let scale = f64::from(native.surface().map_or(1, |surface| surface.scale_factor())); let window = self.connection.get_input_focus()?.reply()?.focus; - let root = self + let screen = self .connection .setup() .roots .first() - .map(|screen| screen.root) .ok_or(KeyInjectionError::NotShown)?; + let root = screen.root; let origin = self.connection.translate_coordinates(window, root, 0, 0)?.reply()?; let on_root = |origin: i16, logical: f64| origin.saturating_add((logical * scale).round() as i16); let x = on_root(origin.dst_x, f64::from(point.x()) + left); let y = on_root(origin.dst_y, f64::from(point.y()) + top); + if x < 0 + || y < 0 + || i32::from(x) >= i32::from(screen.width_in_pixels) + || i32::from(y) >= i32::from(screen.height_in_pixels) + { + return Err(KeyInjectionError::PointerOutsideScreen { + x, + y, + width: screen.width_in_pixels, + height: screen.height_in_pixels, + }); + } self.connection .xtest_fake_input(MOTION_NOTIFY_EVENT, 0, x11rb::CURRENT_TIME, root, x, y, 0)?; - for _ in 0..count { - self.fake(BUTTON_PRESS_EVENT, 1)?; - self.fake(BUTTON_RELEASE_EVENT, 1)?; - } - self.connection.flush()?; - self.connection.get_input_focus()?.reply()?; Ok(()) } @@ -158,6 +250,19 @@ impl KeyInjector { } } +pub(crate) struct PointerCover<'a> { + keys: &'a KeyInjector, + window: Window, +} + +impl Drop for PointerCover<'_> { + fn drop(&mut self) { + if let Err(error) = self.keys.uncover_pointer(self.window) { + tracing::error!(%error, "a pointer cover was not removed"); + } + } +} + pub(crate) struct Held<'a> { keys: &'a KeyInjector, keycode: u8, diff --git a/linux/crates/app/src/ui/data_grid/columns.rs b/linux/crates/app/src/ui/data_grid/columns.rs index 4a7ffe816d..1825de79d9 100644 --- a/linux/crates/app/src/ui/data_grid/columns.rs +++ b/linux/crates/app/src/ui/data_grid/columns.rs @@ -166,9 +166,12 @@ impl DataGrid { } built.row_numbers = Some(row_number_column::build(self)); let names: Vec<&str> = columns.iter().map(|column| column.name.as_str()).collect(); + if let Some(column) = &built.row_numbers { + view.append_column(column); + } for placement in built.layout.arrange(&names) { let column = match placement { - Placement::RowNumbers => built.row_numbers.clone(), + Placement::RowNumbers => None, Placement::Column { index, visible, width } => { built.view_columns.get(index).cloned().inspect(|column| { column.set_visible(visible); @@ -448,14 +451,37 @@ impl DataGrid { self.imp().columns.borrow_mut().handlers.extend(handlers); } - /// A column moved, went or came back: the layout keeps it, and a - /// search counts only the columns on screen, in their order. fn columns_moved(&self) { self.keep_filler_last(); + self.keep_numbers_first(); self.record_layout(); self.find_rows_changed(); } + fn keep_numbers_first(&self) { + let Some(column) = self.row_numbers_column() else { + return; + }; + let view = self.column_view(); + if view.columns().item(0).as_ref() == Some(column.upcast_ref()) { + return; + } + // GTK finishes moving the header after it announces the column change. + glib::idle_add_local_once(glib::clone!( + #[weak] + view, + #[weak] + column, + move || { + if column.column_view().as_ref() == Some(&view) + && view.columns().item(0).as_ref() != Some(column.upcast_ref()) + { + view.insert_column(0, &column); + } + } + )); + } + // GTK drops a header dragged onto the filler after it, and lets the // filler's own header be dragged. fn keep_filler_last(&self) { @@ -865,9 +891,8 @@ fn same_names(layout: &ColumnLayout, columns: &[GridColumn]) -> bool { names.len() == columns.len() && names.iter().zip(columns).all(|(name, column)| *name == column.name) } -/// The font a cell draws its value in: libadwaita's `monospace` class -/// sets only the family and size of the desktop's monospace font. -fn value_font(context: &pango::Context) -> pango::FontDescription { +// Libadwaita's monospace class overrides only family and size. +pub(super) fn value_font(context: &pango::Context) -> pango::FontDescription { let mut monospace = pango::FontDescription::from_string(&adw::StyleManager::default().monospace_font_name()); monospace.unset_fields(!(pango::FontMask::FAMILY | pango::FontMask::SIZE)); let mut font = context.font_description().unwrap_or_default(); diff --git a/linux/crates/app/src/ui/data_grid/edit/cell_editor.rs b/linux/crates/app/src/ui/data_grid/edit/cell_editor.rs index 39263f33d8..0c1aaec229 100644 --- a/linux/crates/app/src/ui/data_grid/edit/cell_editor.rs +++ b/linux/crates/app/src/ui/data_grid/edit/cell_editor.rs @@ -177,6 +177,12 @@ impl EditController { } } + pub(crate) fn queue_editor_allocate(&self) { + if let Some(cell) = self.open_cell() { + cell.queue_allocate(); + } + } + pub fn cancel_open_edit(&self) { let held = self.editor_has_focus(); let cell = self.open_cell(); diff --git a/linux/crates/app/src/ui/data_grid/grid_cell.rs b/linux/crates/app/src/ui/data_grid/grid_cell.rs index dd0b69b1b0..b5e3b57db4 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -107,7 +107,6 @@ mod imp { type ParentType = gtk::Widget; fn class_init(klass: &mut Self::Class) { - klass.set_layout_manager_type::(); klass.set_css_name("tp-grid-cell"); } } @@ -125,6 +124,42 @@ mod imp { } impl WidgetImpl for GridCell { + fn measure(&self, orientation: gtk::Orientation, for_size: i32) -> (i32, i32, i32, i32) { + let mut size = (0, 0, -1, -1); + let mut child = self.obj().first_child(); + while let Some(widget) = child { + if widget.should_layout() { + let measured = widget.measure(orientation, for_size); + size = ( + size.0.max(measured.0), + size.1.max(measured.1), + size.2.max(measured.2), + size.3.max(measured.3), + ); + } + child = widget.next_sibling(); + } + size + } + + fn size_allocate(&self, width: i32, height: i32, baseline: i32) { + let cell = self.obj(); + let mut child = cell.first_child(); + while let Some(widget) = child { + if widget.should_layout() { + let (offset, available) = if self.editor.borrow().as_ref() == Some(&widget) { + cell.editor_space(width) + } else { + (0, width) + }; + let transform = + gtk::gsk::Transform::new().translate(>k::graphene::Point::new(offset as f32, 0.0)); + widget.allocate(available, height, baseline, Some(transform)); + } + child = widget.next_sibling(); + } + } + fn unroot(&self) { let cell = self.obj(); if let Some(grid) = cell.grid() { @@ -147,6 +182,7 @@ glib::wrapper! { impl GridCell { pub fn new(paint: Rc) -> Self { let cell: Self = glib::Object::new(); + cell.set_overflow(gtk::Overflow::Hidden); let display = gtk::Inscription::new(None); display.set_hexpand(true); // An ellipsized Inscription draws from its top edge, so it is kept @@ -162,6 +198,27 @@ impl GridCell { cell } + fn editor_space(&self, width: i32) -> (i32, i32) { + let Some(grid) = self.grid() else { + return (0, width); + }; + let Some(edge) = super::pinned_numbers::covered_edge(&grid) else { + return (0, width); + }; + let Some(origin) = self.compute_point(&grid.column_view(), >k::graphene::Point::new(0.0, 0.0)) else { + return (0, width); + }; + // GTK picks descendants before their parent's contains method. Allocate + // the editor in the uncovered part so its native gestures cannot reach the gutter. + match grid.column_view().direction() { + gtk::TextDirection::Rtl => (0, ((edge - origin.x()).floor() as i32).clamp(0, width)), + _ => { + let offset = ((edge - origin.x()).ceil() as i32).clamp(0, width); + (offset, width - offset) + } + } + } + pub fn attach(&self, list_item: >k::ColumnViewCell) { self.imp().list_item.set(Some(list_item)); } @@ -287,7 +344,6 @@ impl GridCell { } } - /// Lay `editor` over the cell's text until `close_editor`. pub(crate) fn open_editor(&self, editor: &impl IsA) { self.close_editor(); if let Some(closed) = self.imp().closed.take() { @@ -296,14 +352,17 @@ impl GridCell { if let Some(display) = self.display() { display.set_visible(false); } - editor.as_ref().set_parent(self); - self.imp().editor.replace(Some(editor.as_ref().clone())); + // A viewport clips a fully covered editor without allocating GtkText + // below its minimum size or changing its text and cursor state. + let viewport = gtk::Viewport::new(None::<>k::Adjustment>, None::<>k::Adjustment>); + viewport.set_child(Some(editor)); + viewport.set_scroll_to_focus(true); + viewport.set_parent(self); + self.imp().editor.replace(Some(viewport.upcast())); } - /// The editor goes and the text shows again. GTK 4.22 loops forever - /// ending a focus change from a widget that lost its parent, so an - /// editor that still holds the focus is only hidden until the next - /// edit. + // GTK 4.22 loops when focus leaves a widget that lost its parent. + // Keep an editor that holds focus parented until the next edit. pub(crate) fn close_editor(&self) { if let Some(editor) = self.imp().editor.take() { match holds_window_focus(&editor) { diff --git a/linux/crates/app/src/ui/data_grid/grid_menu.rs b/linux/crates/app/src/ui/data_grid/grid_menu.rs index a245acb32c..17a54897ae 100644 --- a/linux/crates/app/src/ui/data_grid/grid_menu.rs +++ b/linux/crates/app/src/ui/data_grid/grid_menu.rs @@ -12,6 +12,7 @@ use crate::services::grid::GridColumn; #[derive(Debug)] pub struct GridMenus { pub cell: gtk::PopoverMenu, + pub row_numbers: gtk::PopoverMenu, /// Below the last row, for a grid that takes new rows. pub empty: Option, /// Filled from the table's foreign keys as a menu opens. @@ -71,6 +72,7 @@ impl GridMenus { let reference_chooser = popover(grid, &gio::Menu::new()); let choices = editable.then(|| popover(grid, &gio::Menu::new())); Self { + row_numbers: popover(grid, &row_numbers_header_menu()), cell, empty, references, @@ -84,6 +86,7 @@ impl GridMenus { /// the grid lets go of itself. pub fn unparent(&self) { self.cell.unparent(); + self.row_numbers.unparent(); if let Some(empty) = &self.empty { empty.unparent(); } diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index 1b043907fd..cdf684bc73 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -51,6 +51,12 @@ pub struct DataGrid { #[template_child] pub column_view: TemplateChild, #[template_child] + pub viewport: TemplateChild, + #[template_child] + pub gutter_backing: TemplateChild, + #[template_child] + pub gutter_header: TemplateChild, + #[template_child] pub empty_page: TemplateChild, #[template_child] pub detail_pane: TemplateChild, @@ -98,6 +104,7 @@ impl ObjectSubclass for DataGrid { fn class_init(klass: &mut Self::Class) { RowDetailPane::ensure_type(); + super::pinned_numbers::PinnedNumbers::ensure_type(); klass.bind_template(); } diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index f1b2db8c4b..233d573213 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -17,6 +17,7 @@ mod grid_store; mod imp; mod keys; mod layout_binding; +mod pinned_numbers; mod pointer; mod references; mod reversed_list; @@ -86,6 +87,7 @@ impl DataGrid { keys::install(&grid); pointer::install(&grid); row_number_column::install_row_factory(&grid); + pinned_numbers::install(&grid); find_bar::install(&grid); imp.detail_pane.attach(&grid); grid.set_columns(columns, sorting, rules); diff --git a/linux/crates/app/src/ui/data_grid/pinned_numbers.rs b/linux/crates/app/src/ui/data_grid/pinned_numbers.rs new file mode 100644 index 0000000000..f056782c04 --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/pinned_numbers.rs @@ -0,0 +1,359 @@ +use std::cell::{Cell, OnceCell, RefCell}; + +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use gtk4::{self as gtk, glib}; +use libadwaita as adw; +use libadwaita::prelude::BinExt; +use libadwaita::subclass::prelude::*; + +use super::{DataGrid, GridCell}; + +mod imp { + use super::*; + + #[derive(glib::Properties)] + #[properties(wrapper_type = super::PinnedNumbers)] + pub struct PinnedNumbers { + #[property(override_interface = gtk::Scrollable, get, set = Self::set_hadjustment)] + hadjustment: RefCell>, + #[property(override_interface = gtk::Scrollable, get, set = Self::set_vadjustment)] + vadjustment: RefCell>, + #[property(override_interface = gtk::Scrollable, get, set = Self::set_hscroll_policy)] + hscroll_policy: Cell, + #[property(override_interface = gtk::Scrollable, get, set = Self::set_vscroll_policy)] + vscroll_policy: Cell, + pub view: OnceCell, + pub grid: glib::WeakRef, + pub focus: RefCell>>, + } + + impl Default for PinnedNumbers { + fn default() -> Self { + Self { + hadjustment: RefCell::default(), + vadjustment: RefCell::default(), + hscroll_policy: Cell::new(gtk::ScrollablePolicy::Minimum), + vscroll_policy: Cell::new(gtk::ScrollablePolicy::Minimum), + view: OnceCell::new(), + grid: glib::WeakRef::new(), + focus: RefCell::default(), + } + } + } + + #[glib::object_subclass] + impl ObjectSubclass for PinnedNumbers { + const NAME: &'static str = "TableProPinnedNumbers"; + type Type = super::PinnedNumbers; + type ParentType = adw::Bin; + type Interfaces = (gtk::Scrollable,); + } + + #[glib::derived_properties] + impl ObjectImpl for PinnedNumbers { + fn constructed(&self) { + self.parent_constructed(); + self.obj().set_layout_manager(None::); + } + } + + impl WidgetImpl for PinnedNumbers { + fn measure(&self, orientation: gtk::Orientation, for_size: i32) -> (i32, i32, i32, i32) { + self.obj() + .child() + .map_or((0, 0, -1, -1), |child| child.measure(orientation, for_size)) + } + + fn size_allocate(&self, width: i32, height: i32, baseline: i32) { + let Some(child) = self.obj().child() else { + return; + }; + child.allocate(width, height, baseline, None); + // Native keyboard navigation updates the adjustment before allocation. + // Correct its reveal only after the new cell geometry is available. + let pending = self.focus.borrow_mut().take(); + if let Some(cell) = pending.and_then(|cell| cell.upgrade()) + && let Some(grid) = self.grid.upgrade() + && grid.focused_cell().as_ref() == Some(&cell) + && super::reveal_allocated(&grid, &cell) + { + child.allocate(width, height, baseline, None); + } + if let Some(grid) = self.grid.upgrade() { + super::sync_header_state(&grid); + } + } + + fn snapshot(&self, snapshot: >k::Snapshot) { + self.parent_snapshot(snapshot); + if let Some(grid) = self.grid.upgrade() { + super::snapshot_numbers(&grid, snapshot); + } + } + } + + impl BinImpl for PinnedNumbers {} + impl ScrollableImpl for PinnedNumbers { + fn border(&self) -> Option { + self.view.get().and_then(|view| view.border()) + } + } + + impl PinnedNumbers { + fn set_hadjustment(&self, adjustment: Option) { + self.hadjustment.replace(adjustment); + if let Some(view) = self.view.get() { + view.set_hadjustment(self.hadjustment.borrow().as_ref()); + } + } + + fn set_vadjustment(&self, adjustment: Option) { + self.vadjustment.replace(adjustment); + if let Some(view) = self.view.get() { + view.set_vadjustment(self.vadjustment.borrow().as_ref()); + } + } + + fn set_hscroll_policy(&self, policy: gtk::ScrollablePolicy) { + self.hscroll_policy.set(policy); + if let Some(view) = self.view.get() { + view.set_hscroll_policy(policy); + } + } + + fn set_vscroll_policy(&self, policy: gtk::ScrollablePolicy) { + self.vscroll_policy.set(policy); + if let Some(view) = self.view.get() { + view.set_vscroll_policy(policy); + } + } + } +} + +glib::wrapper! { + pub struct PinnedNumbers(ObjectSubclass) + @extends adw::Bin, gtk::Widget, + @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget, gtk::Scrollable; +} + +pub(super) fn install(grid: &DataGrid) { + let imp = grid.imp(); + let viewport = &imp.viewport; + let view = grid.column_view(); + viewport.imp().grid.set(Some(grid)); + let _ = viewport.imp().view.set(view.clone()); + view.set_hadjustment(viewport.hadjustment().as_ref()); + view.set_vadjustment(viewport.vadjustment().as_ref()); + view.set_hscroll_policy(viewport.hscroll_policy()); + view.set_vscroll_policy(viewport.vscroll_policy()); + imp.gutter_header.set_cursor_from_name(Some("default")); + imp.gutter_header.connect_state_flags_changed(glib::clone!( + #[weak] + grid, + move |proxy, previous| { + let current = proxy.state_flags(); + if (previous ^ current).contains(gtk::StateFlags::PRELIGHT) { + set_header_hover(&grid, current.contains(gtk::StateFlags::PRELIGHT)); + } + } + )); + if let Some(overlay) = viewport.child().and_downcast::() { + overlay.connect_get_child_position(glib::clone!( + #[weak] + grid, + #[upgrade_or] + None, + move |overlay, child| { + if child != grid.imp().gutter_header.upcast_ref::() { + return None; + } + let area = header(&grid.column_view()).and_then(|header| header.compute_bounds(overlay)); + let Some((area, column)) = area.zip(grid.row_numbers_column()) else { + return Some(gtk::gdk::Rectangle::new(0, 0, 0, 0)); + }; + let width = column.fixed_width(); + let x = match overlay.direction() { + gtk::TextDirection::Rtl => overlay.width() - width, + _ => 0, + }; + Some(gtk::gdk::Rectangle::new( + x, + area.y() as i32, + width, + area.height() as i32, + )) + } + )); + } + imp.scrolled.hadjustment().connect_value_changed(glib::clone!( + #[weak] + grid, + move |_| { + cancel_reveal(&grid); + sync(&grid); + } + )); +} + +pub(super) fn sync(grid: &DataGrid) { + let imp = grid.imp(); + if let Some(column) = grid.row_numbers_column() { + imp.gutter_backing.set_width_request(column.fixed_width()); + } + let visible = imp.scrolled.hadjustment().value() > 0.0; + imp.gutter_backing.set_visible(visible); + // Keep one pointer target while scrolling schedules a new native header allocation. + imp.gutter_header.set_visible(grid.row_numbers_column().is_some()); + imp.viewport.queue_draw(); + grid.edit().queue_editor_allocate(); +} + +pub(super) fn bounds(grid: &DataGrid) -> Option { + let gutter = &grid.imp().gutter_backing; + gutter + .is_visible() + .then(|| gutter.compute_bounds(&grid.column_view())) + .flatten() +} + +pub(super) fn covered_edge(grid: &DataGrid) -> Option { + if !grid.imp().gutter_backing.is_visible() { + return None; + } + let width = grid.row_numbers_column()?.fixed_width() as f32; + let view = grid.column_view(); + // The backing is allocated after the view, so its previous bounds can be stale. + Some(match view.direction() { + gtk::TextDirection::Rtl => view.width() as f32 - width, + _ => width, + }) +} + +pub(super) fn covers(grid: &DataGrid, x: f64) -> bool { + bounds(grid).is_some_and(|rect| x >= f64::from(rect.x()) && x < f64::from(rect.x() + rect.width())) +} + +pub(super) fn cancel_reveal(grid: &DataGrid) { + grid.imp().viewport.imp().focus.take(); +} + +pub(super) fn reveal_focus(grid: &DataGrid) { + if let Some(cell) = grid.focused_cell() { + grid.imp().viewport.imp().focus.replace(Some(cell.downgrade())); + grid.imp().viewport.queue_allocate(); + } +} + +fn reveal_allocated(grid: &DataGrid, cell: &GridCell) -> bool { + let Some(cell) = cell.compute_bounds(&grid.column_view()) else { + return false; + }; + let Some(gutter) = bounds(grid) else { + return false; + }; + let covered = match grid.column_view().direction() { + gtk::TextDirection::Rtl => cell.x() + cell.width() - gutter.x(), + _ => gutter.x() + gutter.width() - cell.x(), + }; + if covered <= 0.0 { + return false; + } + let adjustment = grid.imp().scrolled.hadjustment(); + let before = adjustment.value(); + adjustment.set_value(before - f64::from(covered)); + adjustment.value() != before +} + +fn header(view: >k::ColumnView) -> Option { + let mut child = view.first_child(); + while let Some(widget) = child { + if widget.css_name() == "header" { + return Some(widget); + } + child = widget.next_sibling(); + } + None +} + +fn sync_header_state(grid: &DataGrid) { + let proxy = &grid.imp().gutter_header; + if proxy.is_visible() { + set_header_hover(grid, proxy.state_flags().contains(gtk::StateFlags::PRELIGHT)); + } +} + +fn set_header_hover(grid: &DataGrid, hovered: bool) { + if let Some(title) = header(&grid.column_view()).and_then(|header| header.first_child()) { + if hovered { + title.set_state_flags(gtk::StateFlags::PRELIGHT, false); + } else { + title.unset_state_flags(gtk::StateFlags::PRELIGHT); + } + } +} + +fn snapshot_numbers(grid: &DataGrid, snapshot: >k::Snapshot) { + let Some(gutter) = bounds(grid) else { + return; + }; + let view = grid.column_view(); + let mut child = view.first_child(); + while let Some(widget) = child { + child = widget.next_sibling(); + let Some(area) = widget.compute_bounds(&view) else { + continue; + }; + snapshot.push_clip(>k::graphene::Rect::new( + gutter.x(), + area.y(), + gutter.width(), + area.height(), + )); + if widget.css_name() == "header" { + if let Some(column) = widget.first_child() { + snapshot_column(&view, &widget, &column, gutter.x(), snapshot); + } + } else if widget.is::() { + let mut row = widget.first_child(); + while let Some(current) = row { + row = current.next_sibling(); + if let Some(column) = current.first_child() + && let Some(content) = column.first_child() + && content.has_css_class("row-number-cell") + && let Some(rect) = current.compute_bounds(&view) + && rect.y() < view.height() as f32 + && rect.y() + rect.height() > area.y() + { + snapshot_column(&view, ¤t, &column, gutter.x(), snapshot); + } + } + } + snapshot.pop(); + } +} + +fn snapshot_column( + view: >k::ColumnView, + row: >k::Widget, + column: >k::Widget, + target_x: f32, + snapshot: >k::Snapshot, +) { + let Some(parent) = row.parent() else { + return; + }; + let (Some(source), Some(parent_bounds)) = (column.compute_bounds(&parent), parent.compute_bounds(view)) else { + return; + }; + // snapshot_child requires the actual parent and an untransformed snapshot. + // Reusing the native row keeps selection, stripes, icons and CSS in one model. + let native = gtk::Snapshot::new(); + parent.snapshot_child(row, &native); + if let Some(node) = native.to_node() { + snapshot.save(); + snapshot.translate(>k::graphene::Point::new(target_x - source.x(), parent_bounds.y())); + snapshot.append_node(&node); + snapshot.restore(); + } +} diff --git a/linux/crates/app/src/ui/data_grid/pointer.rs b/linux/crates/app/src/ui/data_grid/pointer.rs index defc278e3e..7bd9e01b93 100644 --- a/linux/crates/app/src/ui/data_grid/pointer.rs +++ b/linux/crates/app/src/ui/data_grid/pointer.rs @@ -1,5 +1,6 @@ use gtk4::prelude::*; -use gtk4::{self as gtk, gdk}; +use gtk4::subclass::prelude::*; +use gtk4::{self as gtk, gdk, glib}; use super::{DataGrid, GridCell, GridRow}; @@ -13,16 +14,14 @@ enum Hit { Empty, /// The header, which GTK handles itself. Header, + NumberHeader, /// An open inline editor, whose own menu cuts, copies and pastes. Editor, } -/// One gesture per button on the view for every cell, resolving the cell -/// under the pointer when a click lands: a gesture per cell adds a quarter -/// or more to every scroll at a hundred columns. Capture phase, so each -/// runs before the list's own row gesture. A double click reaches the grid -/// as the view's own `activate`. +// Capture precedes the native row gesture, which retains selection and dragging. pub fn install(grid: &DataGrid) { + install_pinned_header(grid); grid.column_view().add_controller(focus_on_click(grid)); let gesture = gtk::GestureClick::builder().button(gdk::BUTTON_SECONDARY).build(); gesture.set_propagation_phase(gtk::PropagationPhase::Capture); @@ -37,23 +36,75 @@ pub fn install(grid: &DataGrid) { } }); grid.column_view().add_controller(gesture); - grid.column_view() - .connect_query_tooltip(|view, x, y, _, tooltip| cut_text_tooltip(view, x, y, tooltip)); + grid.column_view().connect_query_tooltip(glib::clone!( + #[weak] + grid, + #[upgrade_or] + false, + move |view, x, y, _, tooltip| { + if super::pinned_numbers::covers(&grid, f64::from(x)) { + if let Hit::Row(row, _) = hit_at(&grid, f64::from(x), f64::from(y)) + && let Some(text) = grid.tracked().row_state(&row).text() + { + tooltip.set_text(Some(&text)); + return true; + } + return false; + } + cut_text_tooltip(view, x, y, tooltip) + } + )); +} + +fn install_pinned_header(grid: &DataGrid) { + let gesture = gtk::GestureClick::builder().button(0).build(); + // Native titles consume middle clicks too, before the scroller can act. + gesture.connect_pressed(|gesture, _, _, _| { + gesture.set_state(gtk::EventSequenceState::Claimed); + }); + gesture.connect_released(glib::clone!( + #[weak] + grid, + move |gesture, _, x, y| { + if gesture.current_button() != gdk::BUTTON_SECONDARY { + return; + } + let header = &grid.imp().gutter_header; + let Some(point) = header.compute_point(&grid.column_view(), >k::graphene::Point::new(x as f32, y as f32)) + else { + return; + }; + grid.menu_at_pointer(Hit::NumberHeader, f64::from(point.x()), f64::from(point.y())); + } + )); + grid.imp().gutter_header.add_controller(gesture); } -/// GTK gives a column view cell no click of its own, so a click focuses -/// the row, on the column focused before. The clicked cell takes the -/// focus first, as a focusable widget in it would, and the row's gesture -/// then keeps it there and selects. The sequence stays the list's. +// Native row selection keeps the focus that capture places on the clicked cell. fn focus_on_click(grid: &DataGrid) -> gtk::GestureClick { let gesture = gtk::GestureClick::builder().button(gdk::BUTTON_PRIMARY).build(); gesture.set_propagation_phase(gtk::PropagationPhase::Capture); let weak = grid.downgrade(); - gesture.connect_pressed(move |_, _, x, y| { - if let Some(grid) = weak.upgrade() - && let Hit::Cell(cell) = hit_at(&grid, x, y) - && let Some(focusable) = cell.parent() - { + gesture.connect_pressed(move |gesture, _, x, y| { + let Some(grid) = weak.upgrade() else { + return; + }; + if matches!(hit_at(&grid, x, y), Hit::NumberHeader) { + gesture.set_state(gtk::EventSequenceState::Claimed); + return; + } + let cell = match hit_at(&grid, x, y) { + Hit::Cell(cell) => Some(cell), + Hit::Row(_, position) => { + let column = grid + .focused_cell() + .map(|cell| cell.column()) + .or_else(|| grid.shown_columns().first().copied()); + column.and_then(|column| grid.focus_cell(position, column)) + } + _ => None, + }; + if let Some(focusable) = cell.and_then(|cell| cell.parent()) { focusable.grab_focus(); } }); @@ -100,8 +151,22 @@ fn hit_at(grid: &DataGrid, x: f64, y: f64) -> Hit { .ancestor(gtk::ListView::static_type()) .or_else(|| picked.downcast_ref::().map(|list| list.clone().upcast())) else { - return Hit::Header; + return if super::pinned_numbers::covers(grid, x) { + Hit::NumberHeader + } else { + Hit::Header + }; }; + if super::pinned_numbers::covers(grid, x) { + let mut widget = Some(picked); + while let Some(current) = widget { + if current.parent().as_ref() == Some(&list) { + return row_of(¤t).map_or(Hit::Empty, |(row, position)| Hit::Row(row, position)); + } + widget = current.parent(); + } + return Hit::Empty; + } if picked.is::() || picked.ancestor(gtk::Text::static_type()).is_some() { return Hit::Editor; } @@ -141,6 +206,13 @@ impl DataGrid { Hit::Cell(cell) => self.open_cell_menu(&cell, Some(at)), Hit::Row(row, position) => self.open_row_menu(&row, position, at), Hit::Empty => self.open_empty_menu(at), + Hit::NumberHeader => { + let Some(menus) = self.menus() else { + return false; + }; + self.show_popover(&menus.row_numbers, Some(at)); + true + } Hit::Header | Hit::Editor => false, } } diff --git a/linux/crates/app/src/ui/data_grid/row_number_column.rs b/linux/crates/app/src/ui/data_grid/row_number_column.rs index 1ce4720d78..be50ece427 100644 --- a/linux/crates/app/src/ui/data_grid/row_number_column.rs +++ b/linux/crates/app/src/ui/data_grid/row_number_column.rs @@ -8,15 +8,10 @@ use gtk4::{self as gtk, glib, pango}; use super::tracked_values::RowPendingState; use super::{DataGrid, GridRow, grid_menu}; -/// Icon, spacing and the cell's padding beside the digits. const CHROME_PX: i32 = 16 + 4 + 13; -/// The handlers a bound gutter cell or row keeps, dropped at unbind. -type Watches = Rc, glib::SignalHandlerId)>>>>; +pub(super) type Watches = Rc, glib::SignalHandlerId)>>>>; -/// The first column: each row's number and the icon of its pending -/// change. GtkColumnView has no row headers, so it is a column like the -/// others, scrolled and dragged with them. pub fn build(grid: &DataGrid) -> gtk::ColumnViewColumn { let factory = gtk::SignalListItemFactory::new(); factory.connect_setup(|_, item| { @@ -33,8 +28,11 @@ pub fn build(grid: &DataGrid) -> gtk::ColumnViewColumn { .valign(gtk::Align::Center) .build(); number.add_css_class("numeric"); + number.add_css_class("monospace"); number.add_css_class("dimmed"); let content = gtk::Box::new(gtk::Orientation::Horizontal, 4); + // Pending icons should not change the row height. + content.add_css_class("row-number-cell"); content.append(&icon); content.append(&number); cell.set_child(Some(&content)); @@ -54,7 +52,9 @@ pub fn build(grid: &DataGrid) -> gtk::ColumnViewColumn { bind_cell(&grid, cell, &row, &watches); }); } - factory.connect_unbind(move |_, item| unwatch(&watches, item.upcast_ref())); + factory.connect_unbind(move |_, item| { + unwatch(&watches, item.upcast_ref()); + }); let column = gtk::ColumnViewColumn::builder() .title(crate::i18n::pgettext("row number column", "#")) .factory(&factory) @@ -89,8 +89,6 @@ fn bind_cell(grid: &DataGrid, cell: >k::ColumnViewCell, row: &GridRow, watches ); } -/// The tracked values are read each time, since the grid's rules follow -/// its column set. fn show_cell(grid: &DataGrid, cell: >k::ColumnViewCell) { let Some(row) = cell.item().and_downcast::() else { return; @@ -115,8 +113,7 @@ fn show_cell(grid: &DataGrid, cell: >k::ColumnViewCell) { ); } -/// A saved row's number counts from the first row read; a draft has none. -fn row_number(grid: &DataGrid, row: &GridRow, position: u32) -> Option { +pub(super) fn row_number(grid: &DataGrid, row: &GridRow, position: u32) -> Option { if row.draft_id().is_some() || position == gtk::INVALID_LIST_POSITION { return None; } @@ -124,7 +121,7 @@ fn row_number(grid: &DataGrid, row: &GridRow, position: u32) -> Option { Some(grid.row_base() + u64::from(position.saturating_sub(drafts)) + 1) } -fn unwatch(watches: &Watches, item: &glib::Object) { +pub(super) fn unwatch(watches: &Watches, item: &glib::Object) { if let Some(handlers) = watches.borrow_mut().remove(item) { for (object, handler) in handlers { if let Some(object) = object.upgrade() { @@ -134,7 +131,6 @@ fn unwatch(watches: &Watches, item: &glib::Object) { } } -/// As wide as the largest number the rows held reach, in tabular digits. pub fn fit(grid: &DataGrid) { let Some(column) = grid.row_numbers_column() else { return; @@ -143,13 +139,13 @@ pub fn fit(grid: &DataGrid) { let digits = largest.max(1).ilog10() as i32 + 1; // A fresh context, since the view's own follows a font change only at // the next frame. - let metrics = grid.column_view().create_pango_context().metrics(None, None); + let context = grid.column_view().create_pango_context(); + let metrics = context.metrics(Some(&super::columns::value_font(&context)), None); let digit_px = pango::units_to_double(metrics.approximate_digit_width()); column.set_fixed_width((f64::from(digits.max(2)) * digit_px).ceil() as i32 + CHROME_PX); + super::pinned_numbers::sync(grid); } -/// Each row names itself and its pending change to a screen reader, and -/// takes no focus of its own, so the focus always lands on a cell. pub fn install_row_factory(grid: &DataGrid) { let factory = gtk::SignalListItemFactory::new(); factory.connect_setup(|_, item| { @@ -201,7 +197,6 @@ pub fn install_row_factory(grid: &DataGrid) { grid.column_view().set_row_factory(Some(&factory)); } -/// Through the properties, since their setters take no NULL to clear. fn describe_row(grid: &DataGrid, list_row: >k::ColumnViewRow) { let Some(row) = list_row.item().and_downcast::() else { return; diff --git a/linux/crates/app/src/ui/data_grid/selection.rs b/linux/crates/app/src/ui/data_grid/selection.rs index a676ddd190..b3e06238e6 100644 --- a/linux/crates/app/src/ui/data_grid/selection.rs +++ b/linux/crates/app/src/ui/data_grid/selection.rs @@ -176,8 +176,6 @@ impl DataGrid { }); } - /// Move the focus to the cell at `position` in data column `column`, - /// scrolling it into view. pub(crate) fn focus_cell(&self, position: u32, column: usize) -> Option { let view = self.column_view(); let view_column = self.data_view_column(column)?; @@ -192,7 +190,12 @@ impl DataGrid { if !self.focused_cell().is_some_and(|cell| landed(&cell)) { view.grab_focus(); } - self.focused_cell().filter(landed) + let cell = self.focused_cell().filter(landed); + if cell.is_some() { + // GTK may change the adjustment after its focus notification. + super::pinned_numbers::reveal_focus(self); + } + cell } /// Give the focus back to `cell` once its editor closed, since the @@ -226,10 +229,12 @@ impl DataGrid { fn focus_moved(&self) { if self.focused_cell().is_none() { + super::pinned_numbers::cancel_reveal(self); return; } self.refresh_actions(); self.imp().detail_pane.follow_focus(); + super::pinned_numbers::reveal_focus(self); } } diff --git a/linux/crates/app/src/ui/data_grid/stripes.rs b/linux/crates/app/src/ui/data_grid/stripes.rs index b190b95f60..dbae138e59 100644 --- a/linux/crates/app/src/ui/data_grid/stripes.rs +++ b/linux/crates/app/src/ui/data_grid/stripes.rs @@ -35,7 +35,9 @@ impl DataGrid { glib::clone!( #[weak] view, - move |settings, key| set_class(&view, STRIPED, settings.boolean(key)) + move |settings, key| { + set_class(&view, STRIPED, settings.boolean(key)); + } ), ); self.imp() diff --git a/linux/crates/app/src/ui/data_grid/test_grid.rs b/linux/crates/app/src/ui/data_grid/test_grid.rs index 8393abd3de..5947359510 100644 --- a/linux/crates/app/src/ui/data_grid/test_grid.rs +++ b/linux/crates/app/src/ui/data_grid/test_grid.rs @@ -154,6 +154,7 @@ pub(crate) struct Grid { pub tracker: TabTrackerHandle, pub columns: Arc<[GridColumn]>, requests: Rc>>, + style: gtk::CssProvider, _settings: MemorySettings, _runtime: AppRuntime, } @@ -166,9 +167,15 @@ impl Grid { pub(crate) fn build(spec: GridSpec, rows: Vec) -> Self { crate::register_test_resources(); - // The stylesheet the app draws the grid with, cell padding and the - // monospace font included. libadwaita::init().expect("libadwaita initialises under the test backend"); + // Filtered widget tests never start the application that installs this stylesheet. + let style = gtk::CssProvider::new(); + style.load_from_resource("/app/tablepro/TablePro/style.css"); + gtk::style_context_add_provider_for_display( + >k::gdk::Display::default().expect("test display"), + &style, + gtk::STYLE_PROVIDER_PRIORITY_APPLICATION, + ); let runtime = crate::test_support::test_runtime(); let settings = MemorySettings::new(); let tracker = TabTrackerHandle::default(); @@ -202,6 +209,8 @@ impl Grid { let log = requests.clone(); grid.connect_request(move |_, request| log.borrow_mut().push(request)); let window = gtk::Window::new(); + // Without a window manager, RTL TopStart gravity grows the surface off the screen. + window.set_gravity(gtk::WindowGravity::TopLeft); window.set_default_size(800, 500); window.set_child(Some(&grid)); window.present(); @@ -213,6 +222,7 @@ impl Grid { tracker, columns, requests, + style, _settings: settings, _runtime: runtime, }; @@ -310,6 +320,7 @@ impl Grid { impl Drop for Grid { fn drop(&mut self) { + gtk::style_context_remove_provider_for_display(>k::prelude::WidgetExt::display(&self.window), &self.style); self.window.destroy(); drain_main_context(); } diff --git a/linux/crates/app/src/ui/data_grid/tests/gutter.rs b/linux/crates/app/src/ui/data_grid/tests/gutter.rs index 6f7fd150b7..da126f2346 100644 --- a/linux/crates/app/src/ui/data_grid/tests/gutter.rs +++ b/linux/crates/app/src/ui/data_grid/tests/gutter.rs @@ -15,7 +15,6 @@ fn two_text_rows() -> Grid { Grid::open(two_text_columns(), two_text_values()) } -/// The gutter cell in `cell`'s row: its pending icon and its number. fn gutter(cell: &GridCell) -> (gtk::Image, gtk::Inscription) { let content = descendants(&row_widget(cell)) .into_iter() @@ -31,7 +30,6 @@ fn number(cell: &GridCell) -> Option { gutter(cell).1.text().map(|number| number.to_string()) } -/// The icon the gutter shows for `cell`'s row and the text it names it by. fn state(cell: &GridCell) -> (Option, Option) { let (icon, _) = gutter(cell); let name = icon @@ -83,7 +81,6 @@ fn a_results_grid_numbers_its_rows_too() { assert_eq!(number(&grid.cell_at(1, 1)).as_deref(), Some("2")); } -/// The row keeps the error icon of a failed save until it is edited. #[gtk4::test] fn the_gutter_shows_each_pending_state() { let grid = two_text_rows(); @@ -138,7 +135,6 @@ fn pending_delete_sets_row_widget_description() { assert!(described(&row), "a row a save failed on said nothing"); } -/// A new row's label says so, which a description would only repeat. #[gtk4::test] fn a_new_row_is_labelled_and_neither_it_nor_its_cells_described() { let grid = two_text_rows(); @@ -157,8 +153,6 @@ fn a_new_row_is_labelled_and_neither_it_nor_its_cells_described() { assert!(!described(&draft)); } -/// The second row, since the list keeps the first row's widgets for its -/// focus. #[gtk4::test] fn an_unbound_gutter_cell_stops_following_its_row() { let grid = two_text_rows(); @@ -178,8 +172,6 @@ fn an_unbound_gutter_cell_stops_following_its_row() { assert_eq!(icon.icon_name(), None, "a recycled icon drew a row it no longer shows"); } -/// The gutter is a column like the others for GTK, and none for the -/// layout, the sort or the data columns' numbering. #[gtk4::test] fn the_gutter_neither_sorts_nor_saves_its_width() { let layouts = Layouts::new(); @@ -221,3 +213,619 @@ fn the_gutter_neither_sorts_nor_saves_its_width() { "a sort by the first data column named another" ); } + +struct TestStyle { + display: gtk::gdk::Display, + provider: gtk::CssProvider, +} + +impl TestStyle { + fn new(grid: &Grid, css: &str) -> Self { + let provider = gtk::CssProvider::new(); + provider.load_from_string(css); + let display = gtk::prelude::WidgetExt::display(&grid.window); + gtk::style_context_add_provider_for_display(&display, &provider, gtk::STYLE_PROVIDER_PRIORITY_USER); + after_next_frame(&grid.window); + Self { display, provider } + } +} + +impl Drop for TestStyle { + fn drop(&mut self) { + gtk::style_context_remove_provider_for_display(&self.display, &self.provider); + } +} + +fn wide_rows(count: i64) -> Grid { + use tablepro_core::Value; + let mut columns = vec![crate::ui::data_grid::test_grid::named("id", "integer", true)]; + columns.extend((0..12).map(|n| crate::ui::data_grid::test_grid::named(&format!("column_{n}"), "text", false))); + let rows = (1..=count) + .map(|id| { + std::iter::once(Value::Int(id)) + .chain((0..12).map(|n| Value::Text(format!("value {id}-{n}")))) + .collect() + }) + .collect(); + Grid::open(columns, rows) +} + +fn projection(grid: &Grid) -> gtk::Box { + use gtk::subclass::prelude::*; + grid.grid.imp().gutter_backing.get() +} + +fn scroll(grid: &Grid) -> gtk::ScrolledWindow { + use gtk::subclass::prelude::*; + grid.grid.imp().scrolled.get() +} + +fn pinned_number(grid: &Grid, value: &str) -> gtk::Inscription { + descendants(&grid.grid.column_view()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|number| { + number.text().as_deref() == Some(value) + && number + .parent() + .is_some_and(|content| content.has_css_class("row-number-cell")) + }) + .expect("the pinned row number") +} + +fn pinned_point(grid: &Grid, value: &str) -> (f32, f32) { + let number = pinned_number(grid, value); + let source = number.compute_bounds(&grid.grid.column_view()).expect("number bounds"); + let target = projection(grid) + .compute_bounds(&grid.grid.column_view()) + .expect("gutter bounds"); + (target.x() + 10.0, source.y() + 4.0) +} + +fn assert_aligned(grid: &Grid) { + let view = grid.grid.column_view(); + let shown = descendants(&view) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .filter(|cell| cell.column() == 1) + .filter_map(|cell| { + let bounds = cell.compute_bounds(&view)?; + (bounds.y() >= 40.0 && bounds.y() + bounds.height() < view.height() as f32).then_some((cell, bounds)) + }) + .collect::>(); + assert!(!shown.is_empty(), "no visible rows checked"); + for (cell, bounds) in shown { + let position = cell.position().expect("bound position"); + let number = pinned_number(grid, &(position + 1).to_string()); + let content = number.parent().expect("gutter content"); + let pinned = content.compute_bounds(&view).expect("gutter bounds"); + assert!( + (pinned.y() - bounds.y()).abs() <= 1.0, + "row {position}: {pinned:?} != {bounds:?}" + ); + assert!((pinned.height() - bounds.height()).abs() <= 1.0); + } +} + +fn gutter_image(grid: &Grid) -> gtk::gdk::Texture { + use gtk::subclass::prelude::*; + let viewport = grid.grid.imp().viewport.get(); + let parent = viewport.parent().expect("viewport parent"); + let snapshot = gtk::Snapshot::new(); + parent.snapshot_child(&viewport, &snapshot); + let node = snapshot.to_node().expect("rendered grid"); + let bounds = viewport.compute_bounds(&parent).expect("viewport bounds"); + let width = grid.grid.row_numbers_column().expect("number column").fixed_width() as f32; + let x = if viewport.direction() == gtk::TextDirection::Rtl { + bounds.x() + bounds.width() - width + } else { + bounds.x() + }; + // render_texture uses one physical pixel per unit, independently of GDK_SCALE. + let scale = viewport.scale_factor() as f32; + let scaled = gtk::Snapshot::new(); + scaled.scale(scale, scale); + scaled.append_node(&node); + let node = scaled.to_node().expect("scaled grid"); + let area = gtk::graphene::Rect::new(x * scale, bounds.y() * scale, width * scale, bounds.height() * scale); + grid.window + .renderer() + .expect("renderer") + .render_texture(&node, Some(&area)) +} + +fn assert_pinned_pixels(grid: &Grid) { + struct Animations(gtk::Settings, bool); + impl Drop for Animations { + fn drop(&mut self) { + self.0.set_gtk_enable_animations(self.1); + } + } + let settings = gtk::prelude::WidgetExt::settings(&grid.window); + let _animations = Animations(settings.clone(), settings.is_gtk_enable_animations()); + // Freeze theme transitions while comparing snapshots from different frames. + settings.set_gtk_enable_animations(false); + let adjustment = scroll(grid).hadjustment(); + let value = adjustment.value(); + adjustment.set_value(0.0); + after_next_frame(&grid.window); + let native = gutter_image(grid); + adjustment.set_value(value); + after_next_frame(&grid.window); + let pinned = gutter_image(grid); + let native_bytes = gtk::gdk::TextureDownloader::new(&native).download_bytes().0; + let pinned_bytes = gtk::gdk::TextureDownloader::new(&pinned).download_bytes().0; + assert_eq!(native_bytes.len(), pinned_bytes.len()); + assert_eq!( + native_bytes + .iter() + .zip(pinned_bytes.iter()) + .filter(|(a, b)| a != b) + .count(), + 0, + "the pinned gutter differs from the native row-number column at scale {}; native_png={} pinned_png={}", + grid.window.scale_factor(), + gtk::glib::base64_encode(&native.save_to_png_bytes()), + gtk::glib::base64_encode(&pinned.save_to_png_bytes()) + ); +} + +fn sideways(grid: &Grid) { + let adjustment = scroll(grid).hadjustment(); + adjustment.set_value(300.0); + after_next_frame(&grid.window); +} + +#[gtk4::test] +fn the_row_numbers_stay_in_view_when_the_columns_scroll_sideways() { + let grid = wide_rows(1000); + scroll(&grid).set_overlay_scrolling(false); + assert!(!projection(&grid).is_visible()); + sideways(&grid); + assert!(projection(&grid).is_visible()); + assert!(!projection(&grid).can_target()); + assert!(!projection(&grid).can_focus()); + assert_eq!(projection(&grid).height(), grid.grid.column_view().height()); + assert_eq!( + descendants(&grid.grid) + .iter() + .filter(|widget| widget.is::()) + .count(), + 1, + "the gutter must not introduce a second row layout or accessibility tree" + ); + for fraction in [0.0, 0.5, 1.0] { + let adjustment = scroll(&grid).vadjustment(); + adjustment.set_value(fraction * (adjustment.upper() - adjustment.page_size())); + after_next_frame(&grid.window); + assert_aligned(&grid); + assert_pinned_pixels(&grid); + } + scroll(&grid).hadjustment().set_value(0.0); + drain_main_context(); + assert!(!projection(&grid).is_visible()); +} + +#[gtk4::test] +fn scrolling_over_the_gutter_uses_the_grid_in_both_axes() { + use crate::test_support::{KeyInjector, wait_until}; + use crate::ui::data_grid::test_grid::WAIT; + let grid = wide_rows(1000); + KeyInjector::focus_only(&grid.window); + sideways(&grid); + let input = KeyInjector::connect().expect("X11 input"); + let gutter = projection(&grid); + let vertical = scroll(&grid).vadjustment(); + input.button(&gutter, (10.0, 80.0), 5, 3).expect("wheel down"); + wait_until(WAIT, || vertical.value() > 0.0).expect("the grid scrolled vertically"); + after_next_frame(&grid.window); + assert_aligned(&grid); + let horizontal = scroll(&grid).hadjustment(); + let before = horizontal.value(); + input.button(&gutter, (10.0, 80.0), 7, 3).expect("wheel right"); + wait_until(WAIT, || horizontal.value() > before).expect("the grid scrolled horizontally"); + after_next_frame(&grid.window); + assert_aligned(&grid); +} + +#[gtk4::test] +fn the_pinned_gutter_keeps_row_and_header_menus() { + use crate::test_support::{KeyInjector, wait_until}; + use crate::ui::data_grid::test_grid::WAIT; + use gtk::subclass::prelude::*; + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + sideways(&grid); + let input = KeyInjector::connect().expect("X11 input"); + input + .button(&grid.grid.column_view(), pinned_point(&grid, "2"), 3, 1) + .expect("row menu click"); + let menus = grid.grid.imp().menus.get().expect("menus"); + wait_until(WAIT, || menus.cell.is_visible()).expect("row menu opened"); + let target = grid.grid.target().expect("menu target"); + assert_eq!(target.rows.len(), 1); + assert_eq!(target.rows[0].key(), Some(key(2))); + menus.cell.popdown(); + drain_main_context(); + sideways(&grid); + input + .button(&projection(&grid), (10.0, 10.0), 3, 1) + .expect("header menu click"); + wait_until(WAIT, || menus.row_numbers.is_visible()).expect("header menu opened"); + assert!(grid.grid.activate_action("grid.select-all", None).is_ok()); + assert_eq!(grid.grid.selection().selection().size(), 20); + menus.row_numbers.popdown(); +} + +#[gtk4::test] +fn gutter_and_data_clicks_share_the_selection_anchor() { + use crate::test_support::{KeyInjector, wait_until}; + use crate::ui::data_grid::test_grid::WAIT; + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + grid.focus(1, 1); + sideways(&grid); + let input = KeyInjector::connect().expect("X11 input"); + let data = |position: u32| { + let view = grid.grid.column_view(); + descendants(&view) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|cell| { + cell.position() == Some(position) + && cell.compute_bounds(&view).is_some_and(|bounds| { + bounds.x() > projection(&grid).width() as f32 + && bounds.x() + bounds.width() < view.width() as f32 + }) + }) + .expect("a fully visible data cell") + .compute_point(&view, >k::graphene::Point::new(4.0, 4.0)) + .map(|point| (point.x(), point.y())) + .expect("data point") + }; + for reverse in [false, true] { + let start = if reverse { pinned_point(&grid, "2") } else { data(1) }; + input.click(&grid.grid.column_view(), start, 1).expect("row selection"); + wait_until(WAIT, || { + grid.grid.selection().selection().size() == 1 && grid.grid.selection().is_selected(1) + }) + .expect("second row selected"); + let shift = input.hold(gtk::gdk::Key::Shift_L).expect("Shift"); + let end = if reverse { data(4) } else { pinned_point(&grid, "5") }; + input.click(&grid.grid.column_view(), end, 1).expect("range selection"); + wait_until(WAIT, || grid.grid.selection().selection().size() == 4).expect("native selection range"); + drop(shift); + assert!((1..=4).all(|position| grid.grid.selection().is_selected(position))); + } + input + .press(gtk::gdk::Key::Down, gtk::gdk::ModifierType::empty()) + .expect("keyboard navigation"); + wait_until(WAIT, || { + grid.focused_cell().is_some_and(|cell| cell.position() == Some(5)) + }) + .expect("keyboard follows the clicked row"); +} + +#[gtk4::test] +fn the_gutter_matches_font_and_density_changes() { + let grid = wide_rows(1000); + sideways(&grid); + let style = TestStyle::new( + &grid, + "columnview { font-size: 23px; } columnview .monospace { font-size: 23px; } columnview.data-table > listview > row > cell > * { padding: 9px 6px; }", + ); + for fraction in [0.0, 0.5, 1.0] { + let adjustment = scroll(&grid).vadjustment(); + adjustment.set_value(fraction * (adjustment.upper() - adjustment.page_size())); + after_next_frame(&grid.window); + assert_aligned(&grid); + assert_pinned_pixels(&grid); + } + drop(style); + after_next_frame(&grid.window); + assert_aligned(&grid); +} + +#[gtk4::test] +fn the_pinned_gutter_shows_pending_states_and_stripes() { + let grid = wide_rows(20); + sideways(&grid); + rename_first(&grid, "edited"); + let number = pinned_number(&grid, "1"); + let icon = number + .parent() + .and_then(|content| content.first_child()) + .and_downcast::() + .expect("icon"); + assert_eq!(icon.icon_name().as_deref(), Some(icons::DOCUMENT_EDIT)); + after_next_frame(&grid.window); + assert_pinned_pixels(&grid); + assert_eq!(icon.tooltip_text().as_deref(), Some("Modified")); + let second = pinned_number(&grid, "2"); + assert!(second.parent().expect("content").has_css_class("tp-stripe")); + grid.grid.selection().select_item(1, false); + after_next_frame(&grid.window); + assert_pinned_pixels(&grid); + grid.grid.discard(); + assert!(!icon.is_visible()); + after_next_frame(&grid.window); + assert_pinned_pixels(&grid); +} + +#[gtk4::test] +fn small_fonts_and_an_offscreen_editor_keep_the_gutter_aligned() { + let grid = wide_rows(1200); + let _style = TestStyle::new( + &grid, + "columnview { font-size: 7px; } columnview .monospace { font-size: 7px; }", + ); + rename_first(&grid, "changed"); + grid.focus(0, 1); + assert!(grid.grid.edit().edit_cell(&grid.cell_of(1, 1))); + sideways(&grid); + for fraction in [0.0, 0.5, 1.0, 0.0] { + let adjustment = scroll(&grid).vadjustment(); + adjustment.set_value(fraction * (adjustment.upper() - adjustment.page_size())); + after_next_frame(&grid.window); + assert_aligned(&grid); + assert_pinned_pixels(&grid); + } +} + +#[gtk4::test] +fn a_covered_editor_cannot_take_a_gutter_click() { + use crate::test_support::{KeyInjector, wait_until}; + use crate::ui::data_grid::test_grid::WAIT; + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + grid.focus(0, 1); + assert!(grid.grid.edit().edit_cell(&grid.cell_of(1, 1))); + let input = KeyInjector::connect().expect("X11 input"); + sideways(&grid); + let point = pinned_point(&grid, "1"); + let picked = grid + .grid + .column_view() + .pick(f64::from(point.0), f64::from(point.1), gtk::PickFlags::DEFAULT) + .expect("gutter target"); + assert!(!picked.is::(), "the covered editor took the gutter"); + input.click(&grid.grid.column_view(), point, 1).expect("gutter click"); + wait_until(WAIT, || { + !grid.grid.edit().editor_has_focus() && grid.grid.selection().is_selected(0) + }) + .expect("the gutter selected the row and moved focus out of the editor"); + assert!(grid.grid.selection().is_selected(0)); + assert!(!grid.grid.edit().editor_has_focus()); +} + +#[gtk4::test] +fn clicking_the_pinned_header_does_not_sort_the_covered_column() { + use crate::test_support::KeyInjector; + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + sideways(&grid); + let input = KeyInjector::connect().expect("X11 input"); + let before = sorts(&grid); + input.click(&projection(&grid), (10.0, 10.0), 2).expect("header click"); + after_next_frame(&grid.window); + assert_eq!(sorts(&grid), before); +} + +#[gtk4::test] +fn keyboard_focus_stays_clear_of_the_pinned_gutter() { + use crate::test_support::{KeyInjector, wait_until}; + use crate::ui::data_grid::test_grid::WAIT; + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + grid.focus(0, 10); + after_next_frame(&grid.window); + let input = KeyInjector::connect().expect("X11 input"); + for column in (0..10).rev() { + input + .press(gtk::gdk::Key::Left, gtk::gdk::ModifierType::empty()) + .expect("left"); + wait_until(WAIT, || grid.focused_cell().is_some_and(|cell| cell.column() == column)).expect("focused column"); + after_next_frame(&grid.window); + let cell = grid.focused_cell().expect("cell"); + let bounds = cell.compute_bounds(&grid.grid.column_view()).expect("bounds"); + let width = grid.grid.row_numbers_column().expect("numbers").fixed_width() as f32; + assert!(bounds.x() >= width - 1.0, "column {column} is hidden: {bounds:?}"); + } +} + +#[gtk4::test] +fn dragging_across_the_gutter_uses_one_rubberband() { + use crate::test_support::{KeyInjector, wait_until}; + use crate::ui::data_grid::test_grid::WAIT; + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + sideways(&grid); + let input = KeyInjector::connect().expect("X11 input"); + let view = grid.grid.column_view(); + let from = pinned_point(&grid, "2"); + let to = pinned_point(&grid, "6"); + input + .drag(&view, (10.0, from.1), (160.0, to.1)) + .expect("drag from gutter into data"); + wait_until(WAIT, || grid.grid.selection().selection().size() >= 4).expect("one native rubberband selected rows"); + grid.grid.selection().unselect_all(); + input + .drag(&view, (160.0, to.1), (10.0, from.1)) + .expect("drag from data into gutter"); + wait_until(WAIT, || grid.grid.selection().selection().size() >= 4).expect("the reverse drag selected rows"); +} + +#[gtk4::test] +fn dragging_the_pinned_header_does_not_move_a_data_column() { + use crate::test_support::KeyInjector; + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + sideways(&grid); + let input = KeyInjector::connect().expect("X11 input"); + let before = grid.grid.shown_columns(); + input + .drag(&grid.grid.column_view(), (10.0, 10.0), (220.0, 10.0)) + .expect("header drag"); + after_next_frame(&grid.window); + assert_eq!(grid.grid.shown_columns(), before); +} + +#[gtk4::test] +fn rtl_gutter_menus_and_focus_follow_its_actual_edge() { + use crate::test_support::{KeyInjector, wait_until}; + use crate::ui::data_grid::test_grid::WAIT; + use gtk::subclass::prelude::*; + struct Direction(gtk::TextDirection); + impl Drop for Direction { + fn drop(&mut self) { + gtk::Widget::set_default_direction(self.0); + } + } + let _direction = Direction(gtk::Widget::default_direction()); + gtk::Widget::set_default_direction(gtk::TextDirection::Rtl); + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + sideways(&grid); + let view = grid.grid.column_view(); + let gutter = projection(&grid).compute_bounds(&view).expect("gutter"); + assert!(gutter.x() > view.width() as f32 / 2.0); + assert_pinned_pixels(&grid); + let input = KeyInjector::connect().expect("X11 input"); + input.button(&view, pinned_point(&grid, "2"), 3, 1).expect("row menu"); + let menus = grid.grid.imp().menus.get().expect("menus"); + wait_until(WAIT, || menus.cell.is_visible()).expect("row menu opened"); + assert_eq!(grid.grid.target().expect("target").rows[0].key(), Some(key(2))); + menus.cell.popdown(); + drain_main_context(); + sideways(&grid); + input + .button(&projection(&grid), (10.0, 10.0), 3, 1) + .expect("header menu"); + wait_until(WAIT, || menus.row_numbers.is_visible()).expect("header menu opened"); + menus.row_numbers.popdown(); + grid.focus(0, 1); + assert!(grid.grid.edit().edit_cell(&grid.cell_of(1, 1))); + sideways(&grid); + grid.window.set_default_size(740, 430); + after_next_frame(&grid.window); + let point = pinned_point(&grid, "1"); + let picked = view + .pick(f64::from(point.0), f64::from(point.1), gtk::PickFlags::DEFAULT) + .expect("target"); + assert!( + !picked.is::(), + "RTL resize exposed the editor under the gutter" + ); + grid.grid.edit().cancel_open_edit(); + grid.focus(0, 10); + after_next_frame(&grid.window); + for column in (0..10).rev() { + input + .press(gtk::gdk::Key::Right, gtk::gdk::ModifierType::empty()) + .expect("right"); + wait_until(WAIT, || grid.focused_cell().is_some_and(|cell| cell.column() == column)).expect("focused column"); + after_next_frame(&grid.window); + let cell = grid.focused_cell().expect("cell"); + let bounds = cell.compute_bounds(&view).expect("bounds"); + let width = grid.grid.row_numbers_column().expect("numbers").fixed_width() as f32; + assert!( + bounds.x() + bounds.width() <= view.width() as f32 - width + 1.0, + "column {column}: {bounds:?}" + ); + } +} + +#[gtk4::test] +fn a_newer_horizontal_scroll_cancels_an_older_focus_reveal() { + let grid = wide_rows(20); + grid.focus(0, 10); + after_next_frame(&grid.window); + assert!(grid.grid.focus_cell(0, 0).is_some()); + let adjustment = scroll(&grid).hadjustment(); + adjustment.set_value(300.0); + after_next_frame(&grid.window); + assert_eq!(adjustment.value(), 300.0, "a stale focus request undid the scroll"); + assert!(projection(&grid).is_visible()); +} + +#[gtk4::test] +fn the_pinned_header_keeps_hover_and_never_offers_a_hidden_resize_handle() { + use crate::test_support::{KeyInjector, wait_until}; + use crate::ui::data_grid::test_grid::WAIT; + use gtk::subclass::prelude::*; + let grid = wide_rows(20); + KeyInjector::focus_only(&grid.window); + let view = grid.grid.column_view(); + let header = descendants(&view) + .into_iter() + .find(|widget| widget.css_name() == "header") + .expect("header"); + assert!(gtk::test_accessible_has_role( + &grid.grid.imp().gutter_header.get(), + gtk::AccessibleRole::Presentation, + )); + assert!(gtk::test_accessible_has_role( + &projection(&grid), + gtk::AccessibleRole::Presentation, + )); + let numbers = header.first_child().expect("number title"); + let first_data = numbers.next_sibling().expect("first data title"); + let second_data = first_data.next_sibling().expect("second data title"); + let edge = first_data.compute_bounds(&view).expect("title bounds"); + scroll(&grid) + .hadjustment() + .set_value(f64::from(edge.x() + edge.width() - 12.0)); + after_next_frame(&grid.window); + let input = KeyInjector::connect().expect("X11 input"); + input.hover(&view, (12.0, 10.0)).expect("hidden divider hover"); + wait_until(WAIT, || numbers.state_flags().contains(gtk::StateFlags::PRELIGHT)).expect("number header hover"); + after_next_frame(&grid.window); + assert_ne!( + grid.grid + .imp() + .gutter_header + .cursor() + .and_then(|cursor| cursor.name()) + .as_deref(), + Some("col-resize") + ); + input.hover(&view, (25.0, 10.0)).expect("covered title hover"); + after_next_frame(&grid.window); + assert!(numbers.state_flags().contains(gtk::StateFlags::PRELIGHT)); + assert!(!second_data.state_flags().contains(gtk::StateFlags::PRELIGHT)); + let cover = input.cover_pointer().expect("native pointer cover"); + wait_until(WAIT, || !numbers.state_flags().contains(gtk::StateFlags::PRELIGHT)) + .expect("cover took the stationary pointer"); + drop(cover); + wait_until(WAIT, || numbers.state_flags().contains(gtk::StateFlags::PRELIGHT)) + .expect("header entered without motion"); + assert!( + !second_data.state_flags().contains(gtk::StateFlags::PRELIGHT), + "entry rehighlighted the covered title" + ); + let outside = projection(&grid).width() as f32 + 4.0; + let second = second_data.compute_bounds(&view).expect("second title bounds"); + assert!( + outside < second.x() + second.width(), + "both points must be in the same native title" + ); + input + .hover(&view, (outside, 10.0)) + .expect("uncovered part of same title"); + wait_until(WAIT, || second_data.state_flags().contains(gtk::StateFlags::PRELIGHT)) + .expect("data header hover restored"); + assert!(!numbers.state_flags().contains(gtk::StateFlags::PRELIGHT)); + input.hover(&view, (25.0, 10.0)).expect("number header hover again"); + after_next_frame(&grid.window); + scroll(&grid).hadjustment().set_value(0.0); + after_next_frame(&grid.window); + assert!(numbers.state_flags().contains(gtk::StateFlags::PRELIGHT)); + scroll(&grid).hadjustment().set_value(300.0); + after_next_frame(&grid.window); + assert!( + numbers.state_flags().contains(gtk::StateFlags::PRELIGHT), + "scrolling lost stationary header hover" + ); + input.hover(&view, (25.0, 100.0)).expect("leave the header"); + wait_until(WAIT, || !numbers.state_flags().contains(gtk::StateFlags::PRELIGHT)).expect("header hover cleared"); +} diff --git a/linux/data/resources/style.css b/linux/data/resources/style.css index 4c92a7f3e9..bddc5b6a42 100644 --- a/linux/data/resources/style.css +++ b/linux/data/resources/style.css @@ -10,14 +10,14 @@ textview.sql-editor, textview.sql-editor text { view cell, so with cell focus the grid's focused cell shows only through this ring: on the cell, and on the inline editor laid into it. */ columnview > listview > row > cell:focus-visible > tp-grid-cell, -columnview > listview > row > cell > tp-grid-cell > text:focus-within { +columnview > listview > row > cell > tp-grid-cell > viewport:focus-within { box-shadow: inset 0 0 0 2px var(--accent-color); border-radius: 2px; } @media (prefers-contrast: more) { columnview > listview > row > cell:focus-visible > tp-grid-cell, - columnview > listview > row > cell > tp-grid-cell > text:focus-within { + columnview > listview > row > cell > tp-grid-cell > viewport:focus-within { box-shadow: inset 0 0 0 3px var(--accent-color); } } @@ -28,6 +28,10 @@ columnview.data-table > listview > row > cell { padding: 0; } +columnview.data-table > listview > row > cell > .row-number-cell { + min-height: 16px; +} + columnview.data-table > listview > row > cell > * { padding: 2px 6px; } diff --git a/linux/data/resources/ui/data-grid.ui b/linux/data/resources/ui/data-grid.ui index 4ddaaa06aa..ad6b726ae0 100644 --- a/linux/data/resources/ui/data-grid.ui +++ b/linux/data/resources/ui/data-grid.ui @@ -89,15 +89,44 @@ - - true - true - cell - true - true - + + + + + + true + true + cell + true + true + + + + + + + presentation + start + false + false + false + + + + + + + presentation + false + false + + + + diff --git a/linux/docs/decisions/0027-one-data-grid.md b/linux/docs/decisions/0027-one-data-grid.md index dc83c5084e..617d40e2df 100644 --- a/linux/docs/decisions/0027-one-data-grid.md +++ b/linux/docs/decisions/0027-one-data-grid.md @@ -1,6 +1,6 @@ # 0027: One data grid on GtkColumnView, with rows and a focused cell -- **Status**: Accepted +- **Status**: Accepted; row numbers superseded by [0044](0044-pinned-row-numbers.md) - **Date**: 2026-10-25 ## Context diff --git a/linux/docs/decisions/0044-pinned-row-numbers.md b/linux/docs/decisions/0044-pinned-row-numbers.md new file mode 100644 index 0000000000..e395590e1a --- /dev/null +++ b/linux/docs/decisions/0044-pinned-row-numbers.md @@ -0,0 +1,52 @@ +# 0044: Row numbers share the grid's scrolling and input + +- **Status**: Accepted +- **Date**: 2026-11-08 +- **Supersedes**: [0027](0027-one-data-grid.md), row-number scrolling only + +## Context + +GTK 4.22 has no frozen column or row-header widget API. Its ColumnView moves all +columns by the horizontal adjustment. Two lists would have separate selection +anchors and row-height estimates even with the same model and adjustment. + +## Decision + +Keep one ColumnView as the only row layout, input and accessibility surface. +After its normal snapshot, the scrollable container draws the native row-number +cells and header again at the fixed edge. It snapshots each native row through +its actual parent into a fresh, untransformed snapshot, then clips and translates +the resulting node. A passive themed background covers the underlying data. A header hit area +keeps native pointer crossing and resize cursors out of the covered data headers; +its native hover state styles the original number header. The hit area stays +present at the horizontal origin, so a scroll never transfers the pointer before +layout. It has no keyboard focus or accessibility entry and uses the grid's +existing header menu. + +This preserves the actual row height, selection background, pending icons, stripes +and CSS without another row model or copied measurements. Descendant redraws +invalidate the container, so both drawings use the same frame. The documented +header and row CSS hierarchy identifies the source widgets. + +Pointer events reach the main native list, which keeps its selection anchor, +rubberband and keyboard navigation. Inline editors are allocated only in the +uncovered part of their cell. The grid resolves gutter clicks as rows and uses +its existing row and header menus. Keyboard focus is revealed after allocation, +when the new horizontal geometry is available. + +## Consequences + +The row-number column stays first. Existing saved data-column order remains usable; +loading a layout does not write storage. There is no second list, adjustment, +height group or accessibility tree to synchronize. + +Pixel and gesture tests live in `crates/app/src/ui/data_grid/tests/gutter.rs`. +A toolkit upgrade must keep them passing. If GTK adds a native frozen-column API, +use it and remove the extra snapshot. + +## Sources + +- [GTK 4.22 column API](https://github.com/GNOME/gtk/blob/4.22.0/gtk/gtkcolumnviewcolumn.h) +- [GTK 4.22 column allocation](https://github.com/GNOME/gtk/blob/4.22.0/gtk/gtkcolumnview.c) +- [GTK snapshot_child contract](https://docs.gtk.org/gtk4/method.Widget.snapshot_child.html) +- [GTK 4.22 child snapshots and redraw propagation](https://github.com/GNOME/gtk/blob/4.22.0/gtk/gtkwidget.c) diff --git a/linux/docs/decisions/README.md b/linux/docs/decisions/README.md index 9f32e489aa..a54277ebd7 100644 --- a/linux/docs/decisions/README.md +++ b/linux/docs/decisions/README.md @@ -74,7 +74,7 @@ A fact the repository keeps elsewhere, such as a workflow trigger, a branch, a v | [0024](0024-multi-cursor-on-text-marks.md) | Multiple cursors on text marks, in the app | Accepted | The SQL editor's view, a GtkSourceView subclass, keeps extra cursors as GtkTextMark pairs, runs GTK's own commands once per cursor and repeats committed text from `end-user-action`, so one undo takes back every cursor's edit. | | [0025](0025-bundled-duckdb.md) | DuckDB built from the duckdb crate's bundled sources | Accepted; the crate version superseded by 0031 | No PPA or COPR target but Ubuntu 26.10 ships libduckdb, so DuckDB 1.5.6 is compiled from the crate on every channel, with no extension fetched or loaded on its own. | | [0026](0026-documents-in-the-table-tab.md) | Document collections open in the table tab, and their statements are shell calls | Accepted | A document engine states `DataModel::Document`, lists collections as tables, opens them in the table tab, and every builder writes a mongosh call with bound values through a document arm chosen by the grammar. | -| [0027](0027-one-data-grid.md) | One data grid on GtkColumnView, with rows and a focused cell | Accepted | Every surface shows rows in one `DataGrid`: row selection plus a focused cell, stable row slots, a row number column, values as text and a row detail pane. | +| [0027](0027-one-data-grid.md) | One data grid on GtkColumnView, with rows and a focused cell | Accepted; row numbers superseded by 0044 | Every surface shows rows in one `DataGrid`: row selection plus a focused cell, stable row slots, a row number column, values as text and a row detail pane. | | [0028](0028-sessions-share-a-window.md) | A window holds several sessions in one tab view | Accepted | A `WorkspaceShell` per window shares one tab view among its sessions, each with its own workspace; the sidebar is a tree of the saved connections with each open session's schemas and tables. | | [0029](0029-images-decode-in-glycin.md) | Images from the database decode in glycin's sandbox | Accepted | Row Details decodes a value's picture with the glycin crate 3.x, in a sandboxed loader process, never with GTK's in-process loaders. | | [0030](0030-a-database-is-a-session-of-its-own.md) | A query tab's database, and another database as a session of its own | Accepted; dropping a sibling's database amended by 0034 | A query tab's own editor session moves to its database through the driver, or opens there where the engine binds it at connect; another database the window shows is a sibling session with its own workspace and sidebar row. | @@ -91,6 +91,7 @@ A fact the repository keeps elsewhere, such as a workflow trigger, a branch, a v | [0041](0041-beta-repositories-and-release-packages.md) | Beta repositories, a Flatpak repository of our own, and packages on every GitHub release | Accepted; the run that builds a tag's packages amended by 0043 | A beta tag goes to a beta PPA, COPR project and Flatpak repository that testers add beside the stable ones; a signed Flatpak repository on R2 serves every other distribution with updates; every GitHub release carries the tested .deb and .rpm and a Flatpak bundle that updates from that repository, with SHA256SUMS. | | [0042](0042-account-page-lists-this-platforms-features.md) | Preferences > Account lists only the features TablePro for Linux has | Accepted | Features lists only the codes whose platform flag is on and hides when none is; the licensing links move to a License group; the copy speaks of the plan and the license, never of a feature missing on Linux. | | [0043](0043-a-tag-publishes-its-dry-run.md) | A tag publishes what its commit's dry run built | Accepted | A tag's run takes the tarballs, template, source packages, packages and unsigned Flatpak repositories from the green dry run of its commit, re-signs only the Flatpak, checks the rest against the dry run's SHA256SUMS, and fails before publishing when there is no such run. | +| [0044](0044-pinned-row-numbers.md) | Row numbers share the grid’s scrolling and input | Accepted | A passive gutter shares the main grid’s selection and vertical adjustment inside one scroller; native input stays in the main view. | 0011 is not used. It was reserved for the DDL decision, which was recorded as 0010, and docs cite ADRs by number, so the later ones keep theirs. diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 23a2291ef9..97ad59f0f5 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -275,6 +275,7 @@ crates/app/src/ui/data_grid/imp.rs crates/app/src/ui/data_grid/keys.rs crates/app/src/ui/data_grid/layout_binding.rs crates/app/src/ui/data_grid/mod.rs +crates/app/src/ui/data_grid/pinned_numbers.rs crates/app/src/ui/data_grid/pointer.rs crates/app/src/ui/data_grid/references/mod.rs crates/app/src/ui/data_grid/references/tests.rs