From 03e7ef4132ddda4c56eafb658db448c4a726d7ad Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:53:08 +0100 Subject: [PATCH 01/18] feat(linux-grid): add row numbers, row height and NULL text preferences --- linux/changelog.d/4134.added.md | 1 + .../app/src/services/grid/display_text.rs | 18 ++++- .../app/src/ui/data_grid/display_settings.rs | 65 +++++++++++++++++++ linux/crates/app/src/ui/data_grid/imp.rs | 1 + linux/crates/app/src/ui/data_grid/mod.rs | 3 + .../app/src/ui/data_grid/tests/cells.rs | 21 ++++++ .../preferences_dialog/data_browser_group.rs | 33 +++++++++- linux/crates/platform/src/settings/keys.rs | 3 + linux/crates/platform/src/settings/mod.rs | 26 ++++++++ .../data/app.tablepro.TablePro.gschema.xml.in | 24 +++++++ linux/data/resources/style.css | 14 ++++ .../ui/preferences-data-browser-group.ui | 25 +++++++ linux/po/POTFILES.in | 1 + 13 files changed, 233 insertions(+), 2 deletions(-) create mode 100644 linux/changelog.d/4134.added.md create mode 100644 linux/crates/app/src/ui/data_grid/display_settings.rs diff --git a/linux/changelog.d/4134.added.md b/linux/changelog.d/4134.added.md new file mode 100644 index 0000000000..3aef7231ad --- /dev/null +++ b/linux/changelog.d/4134.added.md @@ -0,0 +1 @@ +Data grid preferences set whether rows are numbered, how tall a row is and what a NULL shows. diff --git a/linux/crates/app/src/services/grid/display_text.rs b/linux/crates/app/src/services/grid/display_text.rs index a6a3f1d70c..fe6f0f895b 100644 --- a/linux/crates/app/src/services/grid/display_text.rs +++ b/linux/crates/app/src/services/grid/display_text.rs @@ -39,6 +39,19 @@ pub fn editable_null_sentinel() -> String { /// A technical term, so it is not translated. const READONLY_NULL: &str = "NULL"; +thread_local! { + static NULL_DISPLAY: std::cell::RefCell = std::cell::RefCell::new(READONLY_NULL.to_owned()); +} + +/// The text a cell shows for NULL, which Preferences set. +pub fn null_display() -> String { + NULL_DISPLAY.with(|text| text.borrow().clone()) +} + +pub fn set_null_display(text: &str) { + NULL_DISPLAY.with(|slot| *slot.borrow_mut() = text.to_owned()); +} + /// For a column the server fills in on INSERT, so a new draft row does /// not read as if its id were stored as NULL. pub fn auto_filled_sentinel() -> String { @@ -51,7 +64,10 @@ pub fn auto_filled_sentinel() -> String { pub fn display_text<'a>(value: &'a Value, column: &ColumnType, scratch: &'a mut String) -> DisplayText<'a> { scratch.clear(); match value { - Value::Null => DisplayText::placeholder(READONLY_NULL), + Value::Null => { + scratch.push_str(&null_display()); + DisplayText::placeholder(scratch.as_str()) + } Value::Text(text) => shown(text, scratch), // The server's own text, never parsed and written out again. Value::Json(json) => shown(json.as_str(), scratch), diff --git a/linux/crates/app/src/ui/data_grid/display_settings.rs b/linux/crates/app/src/ui/data_grid/display_settings.rs new file mode 100644 index 0000000000..d1dc361540 --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/display_settings.rs @@ -0,0 +1,65 @@ +//! The preferences that shape how a grid reads, as the macOS data grid +//! settings do: whether rows are numbered, how much room a row takes, and +//! what a NULL shows. + +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use tablepro_linux_platform::settings::keys; + +use super::DataGrid; +use super::grid_cell::set_class; +use crate::services::grid::display_text::set_null_display; +use crate::ui::handler_guard::HandlerGuard; + +/// The classes a row height takes, one for each word the setting holds. +const HEIGHT_CLASSES: [(&str, &str); 4] = [ + ("compact", "row-compact"), + ("normal", "row-normal"), + ("comfortable", "row-comfortable"), + ("spacious", "row-spacious"), +]; + +impl DataGrid { + /// Follow the row numbers, the row height and the NULL text the + /// preferences name, now and when one changes. + pub(super) fn watch_display_settings(&self) { + let Some(settings) = self.config().map(|config| config.settings.clone()) else { + return; + }; + let weak = self.downgrade(); + // Connected before the reads: GSettings emits `changed` only for a + // key read while a handler was connected. + let handler = settings.gio().connect_changed(None, move |_, key| { + if matches!(key, keys::SHOW_ROW_NUMBERS | keys::GRID_ROW_HEIGHT | keys::NULL_DISPLAY) + && let Some(grid) = weak.upgrade() + { + grid.apply_display_settings(); + } + }); + self.imp() + .display_watch + .replace(Some(HandlerGuard::new(settings.gio(), handler))); + self.apply_display_settings(); + } + + /// Read the three settings again and draw the grid by them. + pub(super) fn apply_display_settings(&self) { + let Some(settings) = self.config().map(|config| config.settings.clone()) else { + return; + }; + let view = self.column_view(); + let height = settings.grid_row_height(); + for (word, class) in HEIGHT_CLASSES { + set_class(&view, class, word == height); + } + if let Some(numbers) = self.row_numbers_column() { + numbers.set_visible(settings.show_row_numbers()); + } + // The text is the app's to show, so every grid reads the same one. + let null = settings.null_display(); + if crate::services::grid::display_text::null_display() != null { + set_null_display(&null); + self.redraw(); + } + } +} diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index 1b043907fd..521dbe8d4a 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -87,6 +87,7 @@ pub struct DataGrid { /// The window's focus handler, while the grid is in a window. pub focus_watch: RefCell, glib::SignalHandlerId)>>, pub(super) font_watch: RefCell>, + pub(super) display_watch: RefCell>, pub(super) stripes_watch: RefCell>, } diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index f1b2db8c4b..40098df398 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -5,6 +5,7 @@ mod client_sorter; mod column_chooser; mod columns; mod copy; +mod display_settings; mod edit; mod find_bar; mod grid_actions; @@ -91,6 +92,7 @@ impl DataGrid { grid.set_columns(columns, sorting, rules); grid.watch_fonts(); grid.watch_stripes(); + grid.watch_display_settings(); grid } @@ -193,6 +195,7 @@ impl DataGrid { self.imp().summary.forget_column(); self.edit().set_rules(self, rules); self.rebuild_columns(columns, sorting); + self.apply_display_settings(); self.show_rows_or_empty(); self.refresh_actions(); } diff --git a/linux/crates/app/src/ui/data_grid/tests/cells.rs b/linux/crates/app/src/ui/data_grid/tests/cells.rs index b828616eda..6f703b35f7 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -204,6 +204,27 @@ fn open_grids_follow_the_stripes_preference() { assert!(striped()); } +#[gtk4::test] +fn open_grids_follow_the_display_preferences() { + let grid = two_text_rows(); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + let view = grid.grid.column_view(); + let numbers = grid.grid.row_numbers_column().expect("a row number column"); + + settings.set_show_row_numbers(false).expect("store the flag"); + settings.set_grid_row_height("compact").expect("store the height"); + drain_main_context(); + assert!(!numbers.is_visible()); + assert!(view.has_css_class("row-compact")); + + settings.set_grid_row_height("spacious").expect("store the height"); + settings.set_show_row_numbers(true).expect("store the flag"); + drain_main_context(); + assert!(numbers.is_visible()); + assert!(view.has_css_class("row-spacious") && !view.has_css_class("row-compact")); + crate::services::grid::display_text::set_null_display("NULL"); +} + #[gtk4::test] fn column_view_carries_data_table_class() { let grid = two_text_rows(); diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index 9fd59b7397..a29ba9c4d0 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -1,10 +1,14 @@ -use gio::prelude::SettingsExtManual; +use gio::prelude::{SettingsExt, SettingsExtManual}; use gtk4::glib; use gtk4::subclass::prelude::*; use libadwaita as adw; +use libadwaita::prelude::ComboRowExt; use tablepro_linux_platform::AppSettings; use tablepro_linux_platform::settings::keys; +/// The words the row height setting holds, in the combo's order. +const ROW_HEIGHTS: [&str; 4] = ["compact", "normal", "comfortable", "spacious"]; + mod imp { use libadwaita::prelude::*; use libadwaita::subclass::prelude::*; @@ -20,6 +24,12 @@ mod imp { pub alternate_rows_row: TemplateChild, #[template_child] pub confirm_row: TemplateChild, + #[template_child] + pub row_numbers_row: TemplateChild, + #[template_child] + pub row_height_row: TemplateChild, + #[template_child] + pub null_display_row: TemplateChild, } #[glib::object_subclass] @@ -80,6 +90,27 @@ impl DataBrowserGroup { gio_settings .bind(keys::CONFIRM_BULK_DELETE, &imp.confirm_row.get(), "active") .build(); + gio_settings + .bind(keys::SHOW_ROW_NUMBERS, &imp.row_numbers_row.get(), "active") + .build(); + gio_settings + .bind(keys::NULL_DISPLAY, &imp.null_display_row.get(), "text") + .build(); + // The combo holds a position and the setting a word. + let row = imp.row_height_row.get(); + let current = settings.grid_row_height(); + row.set_selected( + ROW_HEIGHTS + .iter() + .position(|height| *height == current) + .map_or(1, |at| at as u32), + ); + let stored = gio_settings.clone(); + row.connect_selected_notify(move |row| { + if let Some(height) = ROW_HEIGHTS.get(row.selected() as usize) { + let _ = stored.set_string(keys::GRID_ROW_HEIGHT, height); + } + }); } } diff --git a/linux/crates/platform/src/settings/keys.rs b/linux/crates/platform/src/settings/keys.rs index 7e3cd2fc79..0b9d74d3ef 100644 --- a/linux/crates/platform/src/settings/keys.rs +++ b/linux/crates/platform/src/settings/keys.rs @@ -1,6 +1,9 @@ pub const DEFAULT_PAGE_SIZE: &str = "default-page-size"; pub const CONFIRM_BULK_DELETE: &str = "confirm-bulk-delete"; pub const SHOW_ALTERNATE_ROWS: &str = "show-alternate-rows"; +pub const SHOW_ROW_NUMBERS: &str = "show-row-numbers"; +pub const GRID_ROW_HEIGHT: &str = "grid-row-height"; +pub const NULL_DISPLAY: &str = "null-display"; pub const SAVE_QUERY_HISTORY: &str = "save-query-history"; pub const HISTORY_RETENTION_DAYS: &str = "history-retention-days"; pub const QUERY_TIMEOUT_SECS: &str = "query-timeout-secs"; diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index 45998d1b79..85a11212b4 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -88,6 +88,32 @@ impl AppSettings { self.set_boolean(keys::SHOW_ALTERNATE_ROWS, show) } + pub fn show_row_numbers(&self) -> bool { + self.settings.boolean(keys::SHOW_ROW_NUMBERS) + } + + pub fn set_show_row_numbers(&self, show: bool) -> Result<(), SettingsError> { + self.set_boolean(keys::SHOW_ROW_NUMBERS, show) + } + + /// The grid's row height: `compact`, `normal`, `comfortable` or `spacious`. + pub fn grid_row_height(&self) -> String { + self.settings.string(keys::GRID_ROW_HEIGHT).into() + } + + pub fn set_grid_row_height(&self, height: &str) -> Result<(), SettingsError> { + self.set_string(keys::GRID_ROW_HEIGHT, height) + } + + /// What a cell shows for NULL. + pub fn null_display(&self) -> String { + self.settings.string(keys::NULL_DISPLAY).into() + } + + pub fn set_null_display(&self, text: &str) -> Result<(), SettingsError> { + self.set_string(keys::NULL_DISPLAY, text) + } + /// Whether runs go into the query history. Off records nothing and /// leaves the entries already there. pub fn save_query_history(&self) -> bool { diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index 5e82ecfe29..9df7a6c758 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -71,6 +71,30 @@ Shade every other row of a data grid so a row reads across its columns. + + true + Show row numbers + Show each row's number in the first column of a data grid. + + + + + + + + + + "normal" + Data grid row height + How much room a data grid row takes around its text. + + + + "NULL" + Text for a NULL value + What a data grid cell shows for a value that is NULL. + + true Save query history diff --git a/linux/data/resources/style.css b/linux/data/resources/style.css index 4c92a7f3e9..6fb81af21d 100644 --- a/linux/data/resources/style.css +++ b/linux/data/resources/style.css @@ -219,3 +219,17 @@ tp-diagram-canvas > .tp-diagram-border { tp-diagram-canvas > .tp-diagram-accent { color: var(--accent-color); } + +/* How much room a data grid row takes around its text, from Preferences. + Normal is the default padding above. */ +columnview.data-table.row-compact > listview > row > cell > * { + padding: 0 6px; +} + +columnview.data-table.row-comfortable > listview > row > cell > * { + padding: 4px 6px; +} + +columnview.data-table.row-spacious > listview > row > cell > * { + padding: 6px 6px; +} diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 330633f43a..1f52211557 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -23,6 +23,31 @@ Show Alternate Row Backgrounds + + + Show Row Numbers + + + + + Row Height + + + + Compact + Normal + Comfortable + Spacious + + + + + + + + Text for NULL + + Confirm Before Deleting Rows diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 23a2291ef9..7f37312b2d 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -250,6 +250,7 @@ crates/app/src/ui/data_grid/column_chooser.rs crates/app/src/ui/data_grid/columns.rs crates/app/src/ui/data_grid/copy/mod.rs crates/app/src/ui/data_grid/copy/tests.rs +crates/app/src/ui/data_grid/display_settings.rs crates/app/src/ui/data_grid/edit/actions.rs crates/app/src/ui/data_grid/edit/cell_editor.rs crates/app/src/ui/data_grid/edit/choice_menu.rs From 390a0a32175b8c47875c3cdf8bdaf1b756944ef3 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:50:19 +0100 Subject: [PATCH 02/18] feat(linux-grid): let the data grid have its own cell font --- linux/changelog.d/4135.added.md | 1 + linux/crates/app/src/ui/data_grid/columns.rs | 53 ++++++++++++--- linux/crates/app/src/ui/data_grid/imp.rs | 1 + .../crates/app/src/ui/editor_font_provider.rs | 68 +++++++++++++++++-- .../preferences_dialog/data_browser_group.rs | 27 ++++++++ linux/crates/platform/src/settings/keys.rs | 2 + linux/crates/platform/src/settings/mod.rs | 20 ++++++ .../data/app.tablepro.TablePro.gschema.xml.in | 12 ++++ .../ui/preferences-data-browser-group.ui | 18 +++++ 9 files changed, 187 insertions(+), 15 deletions(-) create mode 100644 linux/changelog.d/4135.added.md diff --git a/linux/changelog.d/4135.added.md b/linux/changelog.d/4135.added.md new file mode 100644 index 0000000000..ed286e72f4 --- /dev/null +++ b/linux/changelog.d/4135.added.md @@ -0,0 +1 @@ +The data grid has its own font setting for cells, in Preferences under Data Browser. diff --git a/linux/crates/app/src/ui/data_grid/columns.rs b/linux/crates/app/src/ui/data_grid/columns.rs index 4a7ffe816d..d99d90b82d 100644 --- a/linux/crates/app/src/ui/data_grid/columns.rs +++ b/linux/crates/app/src/ui/data_grid/columns.rs @@ -17,6 +17,8 @@ use crate::services::grid::{ number_width_chars, sampled_texts, typical_texts, typical_width_chars, }; use crate::ui::handler_guard::HandlerGuard; +use tablepro_linux_platform::EditorFont; +use tablepro_linux_platform::settings::keys; /// Rows sampled for a column's opening width. const WIDTH_SAMPLE: usize = 200; @@ -268,7 +270,7 @@ impl DataGrid { /// before it had a window measured in no theme's font. pub(super) fn rooted(&self) { let measured_in = self.imp().columns.borrow().measured_in.clone(); - if measured_in.is_some_and(|fonts| fonts != fonts_now(&self.column_view())) { + if measured_in.is_some_and(|fonts| fonts != self.fonts_now()) { self.fonts_changed(); } } @@ -277,6 +279,24 @@ impl DataGrid { /// settings; the monospace font is libadwaita's. pub(super) fn watch_fonts(&self) { let style = adw::StyleManager::default(); + // The cell font is its own setting, applied before the columns + // measure themselves in it. + if let Some(settings) = self.config().map(|config| config.settings.clone()) { + crate::ui::editor_font_provider::apply_grid(&settings); + let weak = self.downgrade(); + let font = settings.gio().connect_changed(None, move |_, key| { + if matches!(key, keys::GRID_USE_SYSTEM_FONT | keys::GRID_FONT) + && let Some(grid) = weak.upgrade() + && let Some(config) = grid.config() + { + crate::ui::editor_font_provider::apply_grid(&config.settings); + grid.fonts_changed(); + } + }); + self.imp() + .cell_font_watch + .replace(Some(HandlerGuard::new(settings.gio(), font))); + } let handler = style.connect_monospace_font_name_notify(glib::clone!( #[weak(rename_to = grid)] self, @@ -285,9 +305,21 @@ impl DataGrid { self.imp().font_watch.replace(Some(HandlerGuard::new(&style, handler))); } + /// The font the user picked for cells, `None` for the desktop's. + fn cell_font(&self) -> Option { + match self.config()?.settings.grid_font() { + EditorFont::Custom(description) => Some(description), + EditorFont::System => None, + } + } + + fn fonts_now(&self) -> String { + fonts_now(&self.column_view(), self.cell_font().as_deref()) + } + fn size_columns(&self, measure: Measure) { let widths = self.opening_widths(measure); - self.imp().columns.borrow_mut().measured_in = Some(fonts_now(&self.column_view())); + self.imp().columns.borrow_mut().measured_in = Some(self.fonts_now()); for (index, view_column, width) in widths { self.imp().columns.borrow_mut().auto_widths.insert(index, width); view_column.set_fixed_width(width); @@ -300,7 +332,7 @@ impl DataGrid { let by_type = set.pages == Pages::Empty; let view = self.column_view(); let context = view.create_pango_context(); - let font = value_font(&context); + let font = value_font(&context, self.cell_font().as_deref()); let metrics = context.metrics(Some(&font), None); let char_px = pango::units_to_double(metrics.approximate_char_width()); let null = editable_null_sentinel(); @@ -554,7 +586,7 @@ impl DataGrid { }; let view = self.column_view(); let context = view.create_pango_context(); - let metrics = context.metrics(Some(&value_font(&context)), None); + let metrics = context.metrics(Some(&value_font(&context, self.cell_font().as_deref())), None); let step = (pango::units_to_double(metrics.approximate_digit_width()) * f64::from(STEP_DIGITS)).ceil() as i32; let width = column.fixed_width(); let width = match wider { @@ -867,8 +899,9 @@ fn same_names(layout: &ColumnLayout, columns: &[GridColumn]) -> bool { /// 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 { - let mut monospace = pango::FontDescription::from_string(&adw::StyleManager::default().monospace_font_name()); +fn value_font(context: &pango::Context, custom: Option<&str>) -> pango::FontDescription { + let mut monospace = + pango::FontDescription::from_string(custom.unwrap_or(&adw::StyleManager::default().monospace_font_name())); monospace.unset_fields(!(pango::FontMask::FAMILY | pango::FontMask::SIZE)); let mut font = context.font_description().unwrap_or_default(); font.merge(Some(&monospace), true); @@ -891,13 +924,17 @@ fn header_width(context: &pango::Context, title: &str) -> i32 { /// The grid's font, the text size in it, and the monospace font. A /// widget's own context follows a change only at the next frame, so a /// fresh one is read. -fn fonts_now(view: >k::ColumnView) -> String { +fn fonts_now(view: >k::ColumnView, custom: Option<&str>) -> String { let grid = view .create_pango_context() .font_description() .map(|font| font.to_string()) .unwrap_or_default(); - format!("{grid}; {}", adw::StyleManager::default().monospace_font_name()) + let cells = custom.map_or_else( + || adw::StyleManager::default().monospace_font_name().to_string(), + str::to_owned, + ); + format!("{grid}; {cells}") } /// How wide `text` is in the tabular figures libadwaita's `numeric` diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index 521dbe8d4a..82f1f210c7 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -88,6 +88,7 @@ pub struct DataGrid { pub focus_watch: RefCell, glib::SignalHandlerId)>>, pub(super) font_watch: RefCell>, pub(super) display_watch: RefCell>, + pub(super) cell_font_watch: RefCell>, pub(super) stripes_watch: RefCell>, } diff --git a/linux/crates/app/src/ui/editor_font_provider.rs b/linux/crates/app/src/ui/editor_font_provider.rs index 5d6cf7f61b..21332eeb42 100644 --- a/linux/crates/app/src/ui/editor_font_provider.rs +++ b/linux/crates/app/src/ui/editor_font_provider.rs @@ -6,6 +6,20 @@ use tablepro_linux_platform::{AppSettings, EditorFont}; thread_local! { static PROVIDER: RefCell> = const { RefCell::new(None) }; + static GRID_PROVIDER: RefCell> = const { RefCell::new(None) }; +} + +/// The data grid's cells take the font the user picked for them. Libadwaita's +/// `monospace` class sets their family, so the rule names that class. +pub(crate) fn apply_grid(settings: &AppSettings) { + let font = match settings.grid_font() { + EditorFont::Custom(description) => Some(pango::FontDescription::from_string(&description)), + EditorFont::System => None, + }; + install( + &GRID_PROVIDER, + font.map(|font| font_css("columnview.data-table .monospace", &font)), + ); } /// The CSS the display currently carries for the editor, or `None` when @@ -20,17 +34,27 @@ pub(crate) fn installed_css() -> Option { /// selected there is no rule at all: `style.css` already points the class /// at libadwaita's monospace variables. pub(crate) fn apply(settings: &AppSettings) { + let css = match settings.editor_font() { + EditorFont::Custom(description) => Some(font_css( + EDITOR_SELECTOR, + &pango::FontDescription::from_string(&description), + )), + EditorFont::System => None, + }; + install(&PROVIDER, css); +} + +fn install(slot: &'static std::thread::LocalKey>>, css: Option) { let Some(display) = gtk4::gdk::Display::default() else { return; }; - PROVIDER.with(|cell| { + slot.with(|cell| { if let Some((previous, _)) = cell.borrow_mut().take() { gtk4::style_context_remove_provider_for_display(&display, &previous); } - let EditorFont::Custom(description) = settings.editor_font() else { + let Some(css) = css else { return; }; - let css = editor_font_css(&pango::FontDescription::from_string(&description)); let provider = gtk4::CssProvider::new(); provider.load_from_string(&css); gtk4::style_context_add_provider_for_display(&display, &provider, gtk4::STYLE_PROVIDER_PRIORITY_APPLICATION); @@ -38,7 +62,14 @@ pub(crate) fn apply(settings: &AppSettings) { }); } +const EDITOR_SELECTOR: &str = "textview.sql-editor, textview.sql-editor text"; + +#[cfg(test)] fn editor_font_css(font: &pango::FontDescription) -> String { + font_css(EDITOR_SELECTOR, font) +} + +fn font_css(selector: &str, font: &pango::FontDescription) -> String { let mut declarations = Vec::new(); if let Some(family) = font.family() { declarations.push(format!("font-family: \"{}\";", escape_css_string(&family))); @@ -59,10 +90,7 @@ fn editor_font_css(font: &pango::FontDescription) -> String { pango::Style::Oblique => declarations.push("font-style: oblique;".to_owned()), _ => {} } - format!( - "textview.sql-editor, textview.sql-editor text {{ {} }}", - declarations.join(" ") - ) + format!("{selector} {{ {} }}", declarations.join(" ")) } /// A family name reaches CSS inside double quotes, so a quote or a @@ -88,6 +116,32 @@ mod tests { assert_eq!(installed_css(), None); } + #[gtk4::test] + fn grid_font_styles_cells_only_when_custom() { + let settings = MemorySettings::new(); + let installed = || GRID_PROVIDER.with(|cell| cell.borrow().as_ref().map(|(_, css)| css.clone())); + + apply_grid(settings.get()); + assert_eq!(installed(), None); + + settings + .get() + .set_grid_font(&EditorFont::Custom("Fira Code 11".to_owned())) + .expect("store the custom font"); + apply_grid(settings.get()); + let css = installed().expect("a rule for the cells"); + assert!(css.starts_with("columnview.data-table .monospace"), "{css}"); + assert!(css.contains("Fira Code"), "{css}"); + assert_eq!(installed_css(), None, "the editor keeps its own font"); + + settings + .get() + .set_grid_font(&EditorFont::System) + .expect("back to the system font"); + apply_grid(settings.get()); + assert_eq!(installed(), None); + } + #[gtk4::test] fn custom_font_change_updates_css() { let settings = MemorySettings::new(); diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index a29ba9c4d0..6085736bcb 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -1,5 +1,7 @@ use gio::prelude::{SettingsExt, SettingsExtManual}; + use gtk4::glib; +use gtk4::glib::prelude::{ToValue, ToVariant}; use gtk4::subclass::prelude::*; use libadwaita as adw; use libadwaita::prelude::ComboRowExt; @@ -25,6 +27,12 @@ mod imp { #[template_child] pub confirm_row: TemplateChild, #[template_child] + pub grid_system_font_row: TemplateChild, + #[template_child] + pub grid_font_row: TemplateChild, + #[template_child] + pub grid_font_button: TemplateChild, + #[template_child] pub row_numbers_row: TemplateChild, #[template_child] pub row_height_row: TemplateChild, @@ -96,6 +104,25 @@ impl DataBrowserGroup { gio_settings .bind(keys::NULL_DISPLAY, &imp.null_display_row.get(), "text") .build(); + gio_settings + .bind(keys::GRID_USE_SYSTEM_FONT, &imp.grid_system_font_row.get(), "active") + .build(); + // As the editor's font row: only reachable with the system font off. + gio_settings + .bind(keys::GRID_USE_SYSTEM_FONT, &imp.grid_font_row.get(), "sensitive") + .flags(gio::SettingsBindFlags::GET | gio::SettingsBindFlags::INVERT_BOOLEAN) + .build(); + gio_settings + .bind(keys::GRID_FONT, &imp.grid_font_button.get(), "font-desc") + .mapping(|variant, _| { + let description = variant.get::()?; + Some(gtk4::pango::FontDescription::from_string(&description).to_value()) + }) + .set_mapping(|value, _| { + let description = value.get::().ok()?; + Some(description.to_str().to_variant()) + }) + .build(); // The combo holds a position and the setting a word. let row = imp.row_height_row.get(); let current = settings.grid_row_height(); diff --git a/linux/crates/platform/src/settings/keys.rs b/linux/crates/platform/src/settings/keys.rs index 0b9d74d3ef..fd4fe976b9 100644 --- a/linux/crates/platform/src/settings/keys.rs +++ b/linux/crates/platform/src/settings/keys.rs @@ -9,6 +9,8 @@ pub const HISTORY_RETENTION_DAYS: &str = "history-retention-days"; pub const QUERY_TIMEOUT_SECS: &str = "query-timeout-secs"; pub const USE_SYSTEM_FONT: &str = "use-system-font"; pub const CUSTOM_FONT: &str = "custom-font"; +pub const GRID_USE_SYSTEM_FONT: &str = "grid-use-system-font"; +pub const GRID_FONT: &str = "grid-font"; pub const STYLE_SCHEME: &str = "style-scheme"; pub const VIM_KEYBINDINGS: &str = "vim-keybindings"; pub const CONNECT_DIALOG_DRIVER: &str = "connect-dialog-driver"; diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index 85a11212b4..6a7e391329 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -163,6 +163,26 @@ impl AppSettings { } } + /// The font of the data grid's cells, which follows the desktop unless + /// the user picked one. + pub fn grid_font(&self) -> EditorFont { + if self.settings.boolean(keys::GRID_USE_SYSTEM_FONT) { + EditorFont::System + } else { + EditorFont::Custom(self.settings.string(keys::GRID_FONT).into()) + } + } + + pub fn set_grid_font(&self, font: &EditorFont) -> Result<(), SettingsError> { + match font { + EditorFont::System => self.set_boolean(keys::GRID_USE_SYSTEM_FONT, true), + EditorFont::Custom(description) => { + self.set_string(keys::GRID_FONT, description)?; + self.set_boolean(keys::GRID_USE_SYSTEM_FONT, false) + } + } + } + pub fn style_scheme(&self) -> String { self.settings.string(keys::STYLE_SCHEME).into() } diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index 9df7a6c758..447920b446 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -127,6 +127,18 @@ Pango font description the SQL editor uses when the system font is turned off. + + true + Use the system monospace font in the data grid + Whether the data grid follows the desktop monospace font instead of a custom one. + + + + 'Monospace 10' + Custom data grid font + Pango font description the data grid uses when the system font is turned off. + + 'Adwaita' Editor style scheme diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 1f52211557..1761b2b3b5 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -48,6 +48,24 @@ Text for NULL + + + Use the System Monospace Font for Cells + + + + + Cell font + + + center + + + + + + + Confirm Before Deleting Rows From 8c415d7f27d77d0e74dd8a8c0b83e6684a629972 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:55:42 +0100 Subject: [PATCH 03/18] feat(linux-grid): choose the format Copy writes for several rows --- linux/changelog.d/4137.added.md | 1 + linux/crates/app/src/ui/data_grid/copy/mod.rs | 19 ++++++- .../crates/app/src/ui/data_grid/copy/tests.rs | 17 ++++++ .../preferences_dialog/data_browser_group.rs | 56 ++++++++++++++----- linux/crates/platform/src/settings/keys.rs | 1 + linux/crates/platform/src/settings/mod.rs | 9 +++ .../data/app.tablepro.TablePro.gschema.xml.in | 14 +++++ .../ui/preferences-data-browser-group.ui | 18 ++++++ 8 files changed, 120 insertions(+), 15 deletions(-) create mode 100644 linux/changelog.d/4137.added.md diff --git a/linux/changelog.d/4137.added.md b/linux/changelog.d/4137.added.md new file mode 100644 index 0000000000..b498d0b520 --- /dev/null +++ b/linux/changelog.d/4137.added.md @@ -0,0 +1 @@ +Preferences can set the format Copy writes when several rows are selected, as TSV, JSON, CSV or Markdown. diff --git a/linux/crates/app/src/ui/data_grid/copy/mod.rs b/linux/crates/app/src/ui/data_grid/copy/mod.rs index 222b60e39f..c7d4dc6406 100644 --- a/linux/crates/app/src/ui/data_grid/copy/mod.rs +++ b/linux/crates/app/src/ui/data_grid/copy/mod.rs @@ -173,7 +173,24 @@ fn copy(grid: &DataGrid) { let column = target.cell.as_ref().map(|(_, column)| *column); match (copy_scope(target.rows.len(), column), &target.cell) { (CopyScope::Value(column), Some((row, _))) => copy_value(grid, row, column), - _ => copy_rows(grid, &target.rows, CopyKind::Rows), + _ => copy_rows(grid, &target.rows, preferred_format(grid)), + } +} + +/// What Copy writes for rows: the format Preferences name, TSV when the +/// word is none this build knows. +fn preferred_format(grid: &DataGrid) -> CopyKind { + let word = grid + .config() + .map(|config| config.settings.row_copy_format()) + .unwrap_or_default(); + match word.as_str() { + "rows-headers" => CopyKind::RowsWithHeaders, + "json" => CopyKind::Json, + "csv" => CopyKind::Csv, + "csv-headers" => CopyKind::CsvWithHeaders, + "markdown" => CopyKind::Markdown, + _ => CopyKind::Rows, } } diff --git a/linux/crates/app/src/ui/data_grid/copy/tests.rs b/linux/crates/app/src/ui/data_grid/copy/tests.rs index ba7573fda6..2cc5c6c2e7 100644 --- a/linux/crates/app/src/ui/data_grid/copy/tests.rs +++ b/linux/crates/app/src/ui/data_grid/copy/tests.rs @@ -728,3 +728,20 @@ fn the_text_copies_take_the_columns_on_screen() { assert_eq!(lines, "{\"id\":1,\"name\":\"Ada\"}\n{\"id\":2,\"name\":\"Grace\"}\n"); assert_eq!(one_row, "1, 'Ada', 2, 'Grace'"); } + +#[gtk4::test] +fn copy_writes_several_rows_in_the_preferred_format() { + let grid = Grid::open(people(), people_rows()); + grid.focus(0, 1); + select_all(&grid); + grid.grid + .config() + .expect("a configured grid") + .settings + .set_row_copy_format("markdown") + .expect("store the format"); + + let text = copied(&grid, || activate(&grid.grid, "copy")); + + assert!(text.starts_with('|') && text.contains("---"), "{text}"); +} diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index 6085736bcb..287e6a16a5 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -11,6 +11,9 @@ use tablepro_linux_platform::settings::keys; /// The words the row height setting holds, in the combo's order. const ROW_HEIGHTS: [&str; 4] = ["compact", "normal", "comfortable", "spacious"]; +/// The words the copy format setting holds, in the combo's order. +const ROW_COPY_FORMATS: [&str; 6] = ["rows", "rows-headers", "json", "csv", "csv-headers", "markdown"]; + mod imp { use libadwaita::prelude::*; use libadwaita::subclass::prelude::*; @@ -35,6 +38,8 @@ mod imp { #[template_child] pub row_numbers_row: TemplateChild, #[template_child] + pub row_copy_format_row: TemplateChild, + #[template_child] pub row_height_row: TemplateChild, #[template_child] pub null_display_row: TemplateChild, @@ -123,24 +128,47 @@ impl DataBrowserGroup { Some(description.to_str().to_variant()) }) .build(); - // The combo holds a position and the setting a word. - let row = imp.row_height_row.get(); - let current = settings.grid_row_height(); - row.set_selected( - ROW_HEIGHTS - .iter() - .position(|height| *height == current) - .map_or(1, |at| at as u32), + bind_choice( + &imp.row_height_row.get(), + gio_settings, + keys::GRID_ROW_HEIGHT, + &ROW_HEIGHTS, + 1, + ); + bind_choice( + &imp.row_copy_format_row.get(), + gio_settings, + keys::ROW_COPY_FORMAT, + &ROW_COPY_FORMATS, + 0, ); - let stored = gio_settings.clone(); - row.connect_selected_notify(move |row| { - if let Some(height) = ROW_HEIGHTS.get(row.selected() as usize) { - let _ = stored.set_string(keys::GRID_ROW_HEIGHT, height); - } - }); } } +/// A combo holds a position and the setting a word, so each change of +/// one is written to the other. +fn bind_choice( + row: &adw::ComboRow, + settings: &gio::Settings, + key: &'static str, + words: &'static [&'static str], + fallback: u32, +) { + let current = settings.string(key); + row.set_selected( + words + .iter() + .position(|word| *word == current) + .map_or(fallback, |at| at as u32), + ); + let stored = settings.clone(); + row.connect_selected_notify(move |row| { + if let Some(word) = words.get(row.selected() as usize) { + let _ = stored.set_string(key, word); + } + }); +} + #[cfg(test)] mod tests { use libadwaita::prelude::*; diff --git a/linux/crates/platform/src/settings/keys.rs b/linux/crates/platform/src/settings/keys.rs index fd4fe976b9..bd0fe73c6e 100644 --- a/linux/crates/platform/src/settings/keys.rs +++ b/linux/crates/platform/src/settings/keys.rs @@ -11,6 +11,7 @@ pub const USE_SYSTEM_FONT: &str = "use-system-font"; pub const CUSTOM_FONT: &str = "custom-font"; pub const GRID_USE_SYSTEM_FONT: &str = "grid-use-system-font"; pub const GRID_FONT: &str = "grid-font"; +pub const ROW_COPY_FORMAT: &str = "row-copy-format"; pub const STYLE_SCHEME: &str = "style-scheme"; pub const VIM_KEYBINDINGS: &str = "vim-keybindings"; pub const CONNECT_DIALOG_DRIVER: &str = "connect-dialog-driver"; diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index 6a7e391329..641808a683 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -105,6 +105,15 @@ impl AppSettings { self.set_string(keys::GRID_ROW_HEIGHT, height) } + /// The format Copy writes for several rows, as a word the schema lists. + pub fn row_copy_format(&self) -> String { + self.settings.string(keys::ROW_COPY_FORMAT).into() + } + + pub fn set_row_copy_format(&self, format: &str) -> Result<(), SettingsError> { + self.set_string(keys::ROW_COPY_FORMAT, format) + } + /// What a cell shows for NULL. pub fn null_display(&self) -> String { self.settings.string(keys::NULL_DISPLAY).into() diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index 447920b446..8fb979d9d9 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -89,6 +89,20 @@ How much room a data grid row takes around its text. + + + + + + + + + + "rows" + Format of copied rows + The format Copy writes when several rows are selected. + + "NULL" Text for a NULL value diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 1761b2b3b5..47517dda17 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -43,6 +43,24 @@ + + + Copy Rows As + The format Copy writes when several rows are selected + + + + TSV + TSV with Headers + JSON + CSV + CSV with Headers + Markdown + + + + + Text for NULL From 2bc031bcfcdc82963b082e23512e2121ecb2b1cb Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:59:26 +0100 Subject: [PATCH 04/18] feat(linux-grid): open row details when a row is selected, if asked --- linux/changelog.d/4138.added.md | 1 + .../app/src/ui/data_grid/edit/tests/rows.rs | 17 ++++++++++++++++- .../crates/app/src/ui/data_grid/grid_actions.rs | 16 ++++++++++++++++ linux/crates/app/src/ui/data_grid/mod.rs | 1 + .../ui/preferences_dialog/data_browser_group.rs | 5 +++++ linux/crates/platform/src/settings/keys.rs | 1 + linux/crates/platform/src/settings/mod.rs | 8 ++++++++ linux/data/app.tablepro.TablePro.gschema.xml.in | 6 ++++++ .../ui/preferences-data-browser-group.ui | 6 ++++++ 9 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 linux/changelog.d/4138.added.md diff --git a/linux/changelog.d/4138.added.md b/linux/changelog.d/4138.added.md new file mode 100644 index 0000000000..023ae1adcd --- /dev/null +++ b/linux/changelog.d/4138.added.md @@ -0,0 +1 @@ +Preferences can open the row details pane whenever a row is selected. diff --git a/linux/crates/app/src/ui/data_grid/edit/tests/rows.rs b/linux/crates/app/src/ui/data_grid/edit/tests/rows.rs index eb57aefbbf..d220123550 100644 --- a/linux/crates/app/src/ui/data_grid/edit/tests/rows.rs +++ b/linux/crates/app/src/ui/data_grid/edit/tests/rows.rs @@ -6,7 +6,7 @@ use libadwaita::prelude::*; use tablepro_core::Value; use tablepro_core::edit::CellInput; -use super::{editing, none, press, two_text_rows}; +use super::{details_shown, editing, none, press, two_text_rows}; use crate::services::change_tracker::RowState; use crate::services::grid::edit_policy; use crate::test_support::{drain_main_context, respond, wait_until}; @@ -269,3 +269,18 @@ fn discard_drops_every_pending_change() { assert_eq!(grid.tracker.pending_count(), 0); assert!(super::editing_cell(&grid).is_none(), "the editor outlived the discard"); } + +#[gtk4::test] +fn selecting_a_row_opens_the_details_only_when_preferences_ask() { + let grid = two_text_rows(); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + + grid.focus(0, 1); + assert!(!details_shown(&grid), "off by default"); + + settings.set_auto_show_inspector(true).expect("store the flag"); + grid.grid.selection().unselect_all(); + grid.grid.selection().select_all(); + drain_main_context(); + assert!(details_shown(&grid)); +} diff --git a/linux/crates/app/src/ui/data_grid/grid_actions.rs b/linux/crates/app/src/ui/data_grid/grid_actions.rs index 1b7e5e095c..1a1efab4e2 100644 --- a/linux/crates/app/src/ui/data_grid/grid_actions.rs +++ b/linux/crates/app/src/ui/data_grid/grid_actions.rs @@ -152,6 +152,22 @@ impl DataGrid { self.target()?.cell.map(|(_, column)| column) } + /// A row was selected and Preferences ask for the pane to open on + /// one, as macOS's auto-show inspector does. A pane the user closed + /// stays closed until the next selection. + pub(super) fn open_details_for_selection(&self) { + let wanted = self + .config() + .is_some_and(|config| config.settings.auto_show_inspector()); + let selected = self.target().is_some_and(|target| !target.rows.is_empty()); + if wanted + && selected + && let Some(details) = self.imp().actions.lookup_action("show-details") + { + details.change_state(&true.to_variant()); + } + } + /// Open the detail pane on the focused row, with `column`'s field. pub(crate) fn show_details_for(&self, column: usize) { self.imp().detail_pane.select_field(column); diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index 40098df398..4c07338588 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -385,6 +385,7 @@ impl DataGrid { fn selection_moved(&self) { self.refresh_actions(); self.imp().detail_pane.follow_focus(); + self.open_details_for_selection(); self.emit_by_name::<()>("selection-changed", &[]); } diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index 287e6a16a5..49ae8a5a43 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -38,6 +38,8 @@ mod imp { #[template_child] pub row_numbers_row: TemplateChild, #[template_child] + pub auto_inspector_row: TemplateChild, + #[template_child] pub row_copy_format_row: TemplateChild, #[template_child] pub row_height_row: TemplateChild, @@ -128,6 +130,9 @@ impl DataBrowserGroup { Some(description.to_str().to_variant()) }) .build(); + gio_settings + .bind(keys::AUTO_SHOW_INSPECTOR, &imp.auto_inspector_row.get(), "active") + .build(); bind_choice( &imp.row_height_row.get(), gio_settings, diff --git a/linux/crates/platform/src/settings/keys.rs b/linux/crates/platform/src/settings/keys.rs index bd0fe73c6e..ad5c2b195a 100644 --- a/linux/crates/platform/src/settings/keys.rs +++ b/linux/crates/platform/src/settings/keys.rs @@ -11,6 +11,7 @@ pub const USE_SYSTEM_FONT: &str = "use-system-font"; pub const CUSTOM_FONT: &str = "custom-font"; pub const GRID_USE_SYSTEM_FONT: &str = "grid-use-system-font"; pub const GRID_FONT: &str = "grid-font"; +pub const AUTO_SHOW_INSPECTOR: &str = "auto-show-inspector"; pub const ROW_COPY_FORMAT: &str = "row-copy-format"; pub const STYLE_SCHEME: &str = "style-scheme"; pub const VIM_KEYBINDINGS: &str = "vim-keybindings"; diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index 641808a683..e129d53018 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -105,6 +105,14 @@ impl AppSettings { self.set_string(keys::GRID_ROW_HEIGHT, height) } + pub fn auto_show_inspector(&self) -> bool { + self.settings.boolean(keys::AUTO_SHOW_INSPECTOR) + } + + pub fn set_auto_show_inspector(&self, show: bool) -> Result<(), SettingsError> { + self.set_boolean(keys::AUTO_SHOW_INSPECTOR, show) + } + /// The format Copy writes for several rows, as a word the schema lists. pub fn row_copy_format(&self) -> String { self.settings.string(keys::ROW_COPY_FORMAT).into() diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index 8fb979d9d9..3ab74d7814 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -103,6 +103,12 @@ The format Copy writes when several rows are selected. + + false + Open row details when a row is selected + Whether selecting a row in a data grid opens its row details pane. + + "NULL" Text for a NULL value diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 47517dda17..52eb591ed2 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -43,6 +43,12 @@ + + + Open Row Details on Selection + Selecting a row opens its details pane + + Copy Rows As From 6ed90a90d9a055a3c46c5e6ae421d85631100864 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:20:43 +0100 Subject: [PATCH 05/18] feat(linux-grid): sort a table by a default column when it opens --- linux/changelog.d/4140.added.md | 1 + .../app/src/ui/browse_tab/data_handlers.rs | 3 ++ .../app/src/ui/browse_tab/default_sort.rs | 42 +++++++++++++++++++ linux/crates/app/src/ui/browse_tab/mod.rs | 14 +++++++ .../crates/app/src/ui/browse_tab/tests/mod.rs | 22 ++++++++++ .../preferences_dialog/data_browser_group.rs | 21 ++++++++++ linux/crates/platform/src/settings/keys.rs | 2 + linux/crates/platform/src/settings/mod.rs | 19 +++++++++ .../data/app.tablepro.TablePro.gschema.xml.in | 21 ++++++++++ .../ui/preferences-data-browser-group.ui | 28 +++++++++++++ linux/po/POTFILES.in | 1 + 11 files changed, 174 insertions(+) create mode 100644 linux/changelog.d/4140.added.md create mode 100644 linux/crates/app/src/ui/browse_tab/default_sort.rs diff --git a/linux/changelog.d/4140.added.md b/linux/changelog.d/4140.added.md new file mode 100644 index 0000000000..fae3205070 --- /dev/null +++ b/linux/changelog.d/4140.added.md @@ -0,0 +1 @@ +Preferences can sort a table by its primary key or first column when it opens, ascending or descending. diff --git a/linux/crates/app/src/ui/browse_tab/data_handlers.rs b/linux/crates/app/src/ui/browse_tab/data_handlers.rs index 3ed7a75cb7..8965ebe1fd 100644 --- a/linux/crates/app/src/ui/browse_tab/data_handlers.rs +++ b/linux/crates/app/src/ui/browse_tab/data_handlers.rs @@ -150,6 +150,9 @@ impl BrowseModel { } pub(super) fn on_columns_loaded(&mut self, columns: Vec, fx: &mut Effects) { + if let Some((behavior, descending)) = self.default_sort.take() { + self.current_sort = super::default_sort::resolve(&behavior, descending, &columns); + } if self.current_columns != columns { self.page = None; self.shown_view = None; diff --git a/linux/crates/app/src/ui/browse_tab/default_sort.rs b/linux/crates/app/src/ui/browse_tab/default_sort.rs new file mode 100644 index 0000000000..8395eaf4cc --- /dev/null +++ b/linux/crates/app/src/ui/browse_tab/default_sort.rs @@ -0,0 +1,42 @@ +use tablepro_core::ColumnInfo; + +/// The column a table opens sorted by, as Preferences ask, and the way: +/// `None` for no sorting, or when the table has no primary key to use. +/// Linux sorts by one column, so a composite key gives its first. +pub(super) fn resolve(behavior: &str, descending: bool, columns: &[ColumnInfo]) -> Option<(usize, bool)> { + let column = match behavior { + "primary-key" => columns.iter().position(|column| column.primary_key)?, + "first-column" if !columns.is_empty() => 0, + _ => return None, + }; + Some((column, !descending)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ui::data_grid::test_grid::named; + + fn columns() -> Vec { + vec![named("name", "text", false), named("id", "integer", true)] + } + + #[test] + fn none_sorts_nothing() { + assert_eq!(resolve("none", false, &columns()), None); + } + + #[test] + fn primary_key_picks_the_key_column_in_the_direction() { + assert_eq!(resolve("primary-key", false, &columns()), Some((1, true))); + assert_eq!(resolve("primary-key", true, &columns()), Some((1, false))); + } + + #[test] + fn a_table_without_a_key_stays_unsorted_by_primary_key() { + let keyless = vec![named("name", "text", false)]; + + assert_eq!(resolve("primary-key", false, &keyless), None); + assert_eq!(resolve("first-column", false, &keyless), Some((0, true))); + } +} diff --git a/linux/crates/app/src/ui/browse_tab/mod.rs b/linux/crates/app/src/ui/browse_tab/mod.rs index 3992ec5199..d64e120f99 100644 --- a/linux/crates/app/src/ui/browse_tab/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/mod.rs @@ -22,6 +22,7 @@ mod count_failure_text; mod count_policy; mod data_handlers; mod data_input; +mod default_sort; mod fetch; mod grid_handlers; mod grid_input; @@ -148,6 +149,15 @@ impl BrowseTab { // A sort saved with the tab cannot reach an engine that reads // in its own order. let initial_sort = init.initial_sort.filter(|_| sorts_rows(dialect.as_deref())); + // A tab with a sort of its own, or reopened past its first page, + // keeps what it had; a new one takes the sort Preferences ask for. + let default_sort = + (initial_sort.is_none() && init.initial_offset == 0 && sorts_rows(dialect.as_deref())).then(|| { + ( + init.settings.default_sort(), + init.settings.default_sort_direction() == "descending", + ) + }); let keys = KeysHandle::new(table.clone()); let grid = layout::grid( &tab, @@ -187,6 +197,7 @@ impl BrowseTab { pager: BrowsePager::new(init.page_size, init.initial_offset), deadlines: init.deadlines, current_sort: initial_sort, + default_sort, current_filter: initial_filter, current_columns: Vec::new(), page: None, @@ -492,6 +503,9 @@ pub(crate) struct BrowseModel { pager: BrowsePager, deadlines: Arc, current_sort: Option<(usize, bool)>, + /// What Preferences asked for when the tab opened, until the columns + /// say which column that is. + default_sort: Option<(String, bool)>, /// The WHERE every page and count reads under, kept per connection, /// schema and table. current_filter: tablepro_core::FilterSet, diff --git a/linux/crates/app/src/ui/browse_tab/tests/mod.rs b/linux/crates/app/src/ui/browse_tab/tests/mod.rs index f9b9de38a4..1319f5a0eb 100644 --- a/linux/crates/app/src/ui/browse_tab/tests/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/tests/mod.rs @@ -1536,3 +1536,25 @@ fn a_dotted_field_of_a_document_neither_sorts_nor_takes_an_edit() { assert!(!grid.edit().edit_cell(&cell), "the dotted field opened for editing"); assert_eq!(harness.tracker.pending_count(), 0); } + +/// A table opens sorted by its primary key when Preferences ask, the way +/// they ask, and shows it on the header. +#[gtk4::test] +fn a_new_tab_opens_sorted_by_the_default_sort() { + let mut script = serving_table(); + script.count_rows.always(FakeReply::ok(1_000)); + script.query_bound.always(FakeReply::ok(full_page(0))); + let mut harness = Harness::open(script, []); + wait_until(WAIT, || harness.shown().len() == 100).expect("the first page"); + assert_eq!(harness.tab().current_sort(), None, "no default sort until asked"); + + let settings = harness.stores.settings.get().clone(); + settings.set_default_sort("primary-key").expect("store the sort"); + settings + .set_default_sort_direction("descending") + .expect("store the direction"); + let another = harness.open_another(); + wait_until(WAIT, || another.current_sort().is_some()).expect("the default sort"); + + assert_eq!(another.current_sort(), Some((0, false))); +} diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index 49ae8a5a43..c649c01fc9 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -11,6 +11,9 @@ use tablepro_linux_platform::settings::keys; /// The words the row height setting holds, in the combo's order. const ROW_HEIGHTS: [&str; 4] = ["compact", "normal", "comfortable", "spacious"]; +/// The words the default sort setting holds, in the combo's order. +const DEFAULT_SORTS: [&str; 3] = ["none", "primary-key", "first-column"]; + /// The words the copy format setting holds, in the combo's order. const ROW_COPY_FORMATS: [&str; 6] = ["rows", "rows-headers", "json", "csv", "csv-headers", "markdown"]; @@ -40,6 +43,10 @@ mod imp { #[template_child] pub auto_inspector_row: TemplateChild, #[template_child] + pub default_sort_row: TemplateChild, + #[template_child] + pub default_sort_direction_row: TemplateChild, + #[template_child] pub row_copy_format_row: TemplateChild, #[template_child] pub row_height_row: TemplateChild, @@ -140,6 +147,20 @@ impl DataBrowserGroup { &ROW_HEIGHTS, 1, ); + bind_choice( + &imp.default_sort_row.get(), + gio_settings, + keys::DEFAULT_SORT, + &DEFAULT_SORTS, + 0, + ); + bind_choice( + &imp.default_sort_direction_row.get(), + gio_settings, + keys::DEFAULT_SORT_DIRECTION, + &["ascending", "descending"], + 0, + ); bind_choice( &imp.row_copy_format_row.get(), gio_settings, diff --git a/linux/crates/platform/src/settings/keys.rs b/linux/crates/platform/src/settings/keys.rs index ad5c2b195a..4017ad113c 100644 --- a/linux/crates/platform/src/settings/keys.rs +++ b/linux/crates/platform/src/settings/keys.rs @@ -12,6 +12,8 @@ pub const CUSTOM_FONT: &str = "custom-font"; pub const GRID_USE_SYSTEM_FONT: &str = "grid-use-system-font"; pub const GRID_FONT: &str = "grid-font"; pub const AUTO_SHOW_INSPECTOR: &str = "auto-show-inspector"; +pub const DEFAULT_SORT: &str = "default-sort"; +pub const DEFAULT_SORT_DIRECTION: &str = "default-sort-direction"; pub const ROW_COPY_FORMAT: &str = "row-copy-format"; pub const STYLE_SCHEME: &str = "style-scheme"; pub const VIM_KEYBINDINGS: &str = "vim-keybindings"; diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index e129d53018..2feffd8897 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -113,6 +113,25 @@ impl AppSettings { self.set_boolean(keys::AUTO_SHOW_INSPECTOR, show) } + /// Which column a table opens sorted by: `none`, `primary-key` or + /// `first-column`. + pub fn default_sort(&self) -> String { + self.settings.string(keys::DEFAULT_SORT).into() + } + + pub fn set_default_sort(&self, behavior: &str) -> Result<(), SettingsError> { + self.set_string(keys::DEFAULT_SORT, behavior) + } + + /// `ascending` or `descending`. + pub fn default_sort_direction(&self) -> String { + self.settings.string(keys::DEFAULT_SORT_DIRECTION).into() + } + + pub fn set_default_sort_direction(&self, direction: &str) -> Result<(), SettingsError> { + self.set_string(keys::DEFAULT_SORT_DIRECTION, direction) + } + /// The format Copy writes for several rows, as a word the schema lists. pub fn row_copy_format(&self) -> String { self.settings.string(keys::ROW_COPY_FORMAT).into() diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index 3ab74d7814..a055b2b239 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -109,6 +109,27 @@ Whether selecting a row in a data grid opens its row details pane. + + + + + + + "none" + Default sort of a table + The column a table tab sorts by when it opens, until the user picks another. + + + + + + + + "ascending" + Direction of the default sort + Which way a table tab sorts by its default column. + + "NULL" Text for a NULL value diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 52eb591ed2..76e48f5afd 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -49,6 +49,34 @@ Selecting a row opens its details pane + + + Default Sort + How a table is ordered when it opens + + + + No sorting (server order) + Primary key + First column + + + + + + + + Default Sort Direction + + + + Ascending + Descending + + + + + Copy Rows As diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 7f37312b2d..15704b7dd6 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -193,6 +193,7 @@ crates/app/src/ui/browse_tab/count_failure_text.rs crates/app/src/ui/browse_tab/count_policy.rs crates/app/src/ui/browse_tab/data_handlers.rs crates/app/src/ui/browse_tab/data_input.rs +crates/app/src/ui/browse_tab/default_sort.rs crates/app/src/ui/browse_tab/fetch.rs crates/app/src/ui/browse_tab/grid_handlers.rs crates/app/src/ui/browse_tab/grid_input.rs From 371e23874fbae1070297aa9c207f469930b64588 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:23:59 +0100 Subject: [PATCH 06/18] feat(linux-grid): mark spaces, tabs and line breaks in the value editor --- linux/changelog.d/4141.added.md | 1 + .../src/ui/data_grid/row_detail/invisibles.rs | 47 +++++++++++++++++++ .../app/src/ui/data_grid/row_detail/mod.rs | 4 ++ .../app/src/ui/data_grid/row_detail/tests.rs | 19 ++++++++ .../preferences_dialog/data_browser_group.rs | 5 ++ linux/crates/platform/src/settings/keys.rs | 1 + linux/crates/platform/src/settings/mod.rs | 8 ++++ .../data/app.tablepro.TablePro.gschema.xml.in | 6 +++ .../ui/preferences-data-browser-group.ui | 6 +++ linux/po/POTFILES.in | 1 + 10 files changed, 98 insertions(+) create mode 100644 linux/changelog.d/4141.added.md create mode 100644 linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs diff --git a/linux/changelog.d/4141.added.md b/linux/changelog.d/4141.added.md new file mode 100644 index 0000000000..b00c792ac2 --- /dev/null +++ b/linux/changelog.d/4141.added.md @@ -0,0 +1 @@ +The row details value editor marks spaces, tabs and line breaks, which a Preferences switch turns off. diff --git a/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs b/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs new file mode 100644 index 0000000000..0f96ed94ad --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs @@ -0,0 +1,47 @@ +//! Marks for the spaces, tabs and line breaks of the value editor, which +//! macOS's "show invisible characters" grid setting turns on. + +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use sourceview5::prelude::*; +use tablepro_linux_platform::settings::keys; + +use super::RowDetailPane; +use crate::ui::handler_guard::HandlerGuard; + +impl RowDetailPane { + /// Follow the preference, now and when it changes. + pub(super) fn watch_invisibles(&self, settings: &tablepro_linux_platform::AppSettings) { + let weak = self.downgrade(); + let handler = settings + .gio() + .connect_changed(Some(keys::SHOW_INVISIBLE_CHARACTERS), move |_, _| { + if let Some(pane) = weak.upgrade() { + pane.apply_invisibles(); + } + }); + self.imp() + .guards + .borrow_mut() + .push(HandlerGuard::new(settings.gio(), handler)); + self.apply_invisibles(); + } + + pub(super) fn apply_invisibles(&self) { + let Some(grid) = self.grid() else { + return; + }; + let Some(config) = grid.config() else { + return; + }; + let drawer = self.imp().value_view.space_drawer(); + drawer.set_types_for_locations( + sourceview5::SpaceLocationFlags::ALL, + sourceview5::SpaceTypeFlags::SPACE + | sourceview5::SpaceTypeFlags::TAB + | sourceview5::SpaceTypeFlags::NEWLINE + | sourceview5::SpaceTypeFlags::NBSP, + ); + drawer.set_enable_matrix(config.settings.show_invisible_characters()); + } +} diff --git a/linux/crates/app/src/ui/data_grid/row_detail/mod.rs b/linux/crates/app/src/ui/data_grid/row_detail/mod.rs index 7804cc47ca..904d09c49a 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/mod.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/mod.rs @@ -5,6 +5,7 @@ mod calendar; mod clock; mod fields; mod imp; +mod invisibles; mod picture; #[cfg(test)] mod tests; @@ -47,6 +48,9 @@ impl RowDetailPane { self.connect_close(grid); self.watch_details(grid); self.watch_rows(grid); + if let Some(config) = grid.config() { + self.watch_invisibles(&config.settings); + } self.show_nothing(); } diff --git a/linux/crates/app/src/ui/data_grid/row_detail/tests.rs b/linux/crates/app/src/ui/data_grid/row_detail/tests.rs index 831c4f96df..8c4212f103 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/tests.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/tests.rs @@ -1424,3 +1424,22 @@ fn a_page_that_takes_the_row_closes_its_clock_and_writes_nothing() { ); assert!(!pane.imp().clock_popover.is_visible()); } + +#[gtk4::test] +fn the_value_editor_marks_whitespace_only_when_preferences_ask() { + use sourceview5::prelude::*; + + let (grid, pane) = opened(two_text_columns(), two_text_values()); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + let drawer = pane.imp().value_view.space_drawer(); + + assert!(drawer.enables_matrix(), "marks are on by default, as on macOS"); + + settings.set_show_invisible_characters(false).expect("store the flag"); + drain_main_context(); + assert!(!drawer.enables_matrix()); + + settings.set_show_invisible_characters(true).expect("store the flag"); + drain_main_context(); + assert!(drawer.enables_matrix()); +} diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index c649c01fc9..3342418e97 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -43,6 +43,8 @@ mod imp { #[template_child] pub auto_inspector_row: TemplateChild, #[template_child] + pub invisibles_row: TemplateChild, + #[template_child] pub default_sort_row: TemplateChild, #[template_child] pub default_sort_direction_row: TemplateChild, @@ -147,6 +149,9 @@ impl DataBrowserGroup { &ROW_HEIGHTS, 1, ); + gio_settings + .bind(keys::SHOW_INVISIBLE_CHARACTERS, &imp.invisibles_row.get(), "active") + .build(); bind_choice( &imp.default_sort_row.get(), gio_settings, diff --git a/linux/crates/platform/src/settings/keys.rs b/linux/crates/platform/src/settings/keys.rs index 4017ad113c..a54880b95e 100644 --- a/linux/crates/platform/src/settings/keys.rs +++ b/linux/crates/platform/src/settings/keys.rs @@ -14,6 +14,7 @@ pub const GRID_FONT: &str = "grid-font"; pub const AUTO_SHOW_INSPECTOR: &str = "auto-show-inspector"; pub const DEFAULT_SORT: &str = "default-sort"; pub const DEFAULT_SORT_DIRECTION: &str = "default-sort-direction"; +pub const SHOW_INVISIBLE_CHARACTERS: &str = "show-invisible-characters"; pub const ROW_COPY_FORMAT: &str = "row-copy-format"; pub const STYLE_SCHEME: &str = "style-scheme"; pub const VIM_KEYBINDINGS: &str = "vim-keybindings"; diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index 2feffd8897..69154890fc 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -132,6 +132,14 @@ impl AppSettings { self.set_string(keys::DEFAULT_SORT_DIRECTION, direction) } + pub fn show_invisible_characters(&self) -> bool { + self.settings.boolean(keys::SHOW_INVISIBLE_CHARACTERS) + } + + pub fn set_show_invisible_characters(&self, show: bool) -> Result<(), SettingsError> { + self.set_boolean(keys::SHOW_INVISIBLE_CHARACTERS, show) + } + /// The format Copy writes for several rows, as a word the schema lists. pub fn row_copy_format(&self) -> String { self.settings.string(keys::ROW_COPY_FORMAT).into() diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index a055b2b239..053cef7ad6 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -130,6 +130,12 @@ Which way a table tab sorts by its default column. + + true + Mark spaces, tabs and line breaks in cell values + Whether the row details value editor draws marks for spaces, tabs and line breaks. + + "NULL" Text for a NULL value diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 76e48f5afd..1859ab03ed 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -49,6 +49,12 @@ Selecting a row opens its details pane + + + Mark Spaces, Tabs and Line Breaks + In the value editor of the row details + + Default Sort diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 15704b7dd6..d7a4f24501 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -285,6 +285,7 @@ crates/app/src/ui/data_grid/row_detail/calendar.rs crates/app/src/ui/data_grid/row_detail/clock.rs crates/app/src/ui/data_grid/row_detail/fields.rs crates/app/src/ui/data_grid/row_detail/imp.rs +crates/app/src/ui/data_grid/row_detail/invisibles.rs crates/app/src/ui/data_grid/row_detail/mod.rs crates/app/src/ui/data_grid/row_detail/picture.rs crates/app/src/ui/data_grid/row_detail/tests.rs From ff5eae335ae9eeb0aa3ed14c2a08134db6e067f6 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:53:43 +0100 Subject: [PATCH 07/18] fix(linux-grid): show the chosen NULL text in editable cells too --- .../app/src/services/grid/display_text.rs | 33 +++++++++++++++++-- .../crates/app/src/ui/data_grid/grid_cell.rs | 10 +++--- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/linux/crates/app/src/services/grid/display_text.rs b/linux/crates/app/src/services/grid/display_text.rs index fe6f0f895b..2ee4b4c975 100644 --- a/linux/crates/app/src/services/grid/display_text.rs +++ b/linux/crates/app/src/services/grid/display_text.rs @@ -30,9 +30,22 @@ impl<'a> DisplayText<'a> { } } -/// The brackets keep it apart from a literal `NULL` text value. +/// The brackets keep it apart from a literal `NULL` text value. A text the +/// user chose for NULL is shown as it is, since they picked it. pub fn editable_null_sentinel() -> String { - crate::i18n::gettext("") + // Spelled once, since every bind of a NULL cell asks. + EDITABLE_NULL.with(|slot| { + slot.borrow_mut() + .get_or_insert_with(|| { + let text = null_display(); + if text == READONLY_NULL { + crate::i18n::gettext("") + } else { + text + } + }) + .clone() + }) } /// A read-only cell dims its NULL instead, so it needs no brackets. @@ -41,6 +54,7 @@ const READONLY_NULL: &str = "NULL"; thread_local! { static NULL_DISPLAY: std::cell::RefCell = std::cell::RefCell::new(READONLY_NULL.to_owned()); + static EDITABLE_NULL: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } /// The text a cell shows for NULL, which Preferences set. @@ -50,6 +64,7 @@ pub fn null_display() -> String { pub fn set_null_display(text: &str) { NULL_DISPLAY.with(|slot| *slot.borrow_mut() = text.to_owned()); + EDITABLE_NULL.with(|slot| *slot.borrow_mut() = None); } /// For a column the server fills in on INSERT, so a new draft row does @@ -222,7 +237,7 @@ mod tests { use tablepro_core::column::{BoolStorage, ColumnKind, ColumnType}; use tablepro_core::value::{JsonText, OffsetTimestamp, SqlTime, Temporal, UndecodableReason, UndecodedValue}; - use super::{DISPLAY_MAX_CHARS, DisplayText, display_text}; + use super::{DISPLAY_MAX_CHARS, DisplayText, display_text, editable_null_sentinel, set_null_display}; fn text_column() -> ColumnType { ColumnType::untyped_text("text") @@ -233,6 +248,18 @@ mod tests { display_text(value, &text_column(), &mut scratch).text.to_owned() } + #[test] + fn a_chosen_null_text_reaches_editable_cells_and_the_default_keeps_its_brackets() { + assert_eq!(editable_null_sentinel(), ""); + + set_null_display("(none)"); + assert_eq!(editable_null_sentinel(), "(none)"); + assert_eq!(shown(&Value::Null), "(none)"); + + set_null_display("NULL"); + assert_eq!(editable_null_sentinel(), ""); + } + #[test] fn display_text_borrows_text_without_allocating() { let value = Value::Text("hello".into()); 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..f8790e9497 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -36,8 +36,7 @@ pub struct TextAttributes { deleted: pango::AttrList, deleted_placeholder: pango::AttrList, placeholder: pango::AttrList, - /// The stand-in texts, translated once rather than on every bind. - editable_null: String, + /// The stand-in text, translated once rather than on every bind. auto_filled: String, } @@ -61,7 +60,6 @@ impl TextAttributes { deleted: list(TextMark::Deleted, false), deleted_placeholder: list(TextMark::Deleted, true), placeholder: list(TextMark::Plain, true), - editable_null: editable_null_sentinel(), auto_filled: auto_filled_sentinel(), } } @@ -344,7 +342,11 @@ fn shown_text<'a>( } (Some(ServerValue::Default), _) => DisplayText::placeholder("DEFAULT"), (Some(ServerValue::Expression(expression)), _) => DisplayText::placeholder(expression.sql), - (None, Value::Null) if editable => DisplayText::placeholder(&paint.attributes.editable_null), + (None, Value::Null) if editable => { + scratch.clear(); + scratch.push_str(&editable_null_sentinel()); + DisplayText::placeholder(scratch.as_str()) + } (None, value) => display_text(value, &paint.column.column_type, scratch), } } From ab70c2d05d00a3a9b789801f71ecfe4b6a84945d Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 22:55:55 +0700 Subject: [PATCH 08/18] fix(linux-grid): share live display preferences across grids --- .../app/src/services/grid/display_text.rs | 18 +- linux/crates/app/src/ui/a11y/tests.rs | 1 + linux/crates/app/src/ui/data_grid/columns.rs | 14 +- .../app/src/ui/data_grid/display_settings.rs | 50 ++---- .../crates/app/src/ui/data_grid/grid_cell.rs | 15 +- linux/crates/app/src/ui/data_grid/imp.rs | 3 +- linux/crates/app/src/ui/data_grid/mod.rs | 1 - .../app/src/ui/data_grid/row_detail/fields.rs | 10 +- .../app/src/ui/data_grid/row_detail/tests.rs | 29 +++ .../ui/data_grid/row_detail/value_editor.rs | 7 +- linux/crates/app/src/ui/data_grid/stripes.rs | 30 +--- .../crates/app/src/ui/data_grid/test_grid.rs | 4 +- .../app/src/ui/data_grid/tests/cells.rs | 81 ++++++++- .../app/src/ui/data_grid/tests/columns.rs | 31 ++++ .../preferences_dialog/data_browser_group.rs | 81 ++++++--- .../src/ui/preferences_dialog/general_page.rs | 20 +-- .../src/ui/preferences_dialog/grid_page.rs | 79 ++++++++ .../app/src/ui/preferences_dialog/imp.rs | 4 + .../app/src/ui/preferences_dialog/mod.rs | 62 +++---- .../platform/src/settings/grid_preferences.rs | 168 ++++++++++++++++++ linux/crates/platform/src/settings/mod.rs | 21 ++- linux/crates/platform/tests/settings.rs | 128 +++++++++++++ linux/data/resources/resources.gresource.xml | 1 + .../ui/preferences-data-browser-group.ui | 2 + linux/data/resources/ui/preferences-dialog.ui | 3 + .../resources/ui/preferences-general-page.ui | 3 - .../resources/ui/preferences-grid-page.ui | 12 ++ linux/docs/state-management.md | 6 + linux/docs/storage.md | 6 +- linux/po/POTFILES.in | 2 + 30 files changed, 717 insertions(+), 175 deletions(-) create mode 100644 linux/crates/app/src/ui/preferences_dialog/grid_page.rs create mode 100644 linux/crates/platform/src/settings/grid_preferences.rs create mode 100644 linux/data/resources/ui/preferences-grid-page.ui diff --git a/linux/crates/app/src/services/grid/display_text.rs b/linux/crates/app/src/services/grid/display_text.rs index fe6f0f895b..a6a3f1d70c 100644 --- a/linux/crates/app/src/services/grid/display_text.rs +++ b/linux/crates/app/src/services/grid/display_text.rs @@ -39,19 +39,6 @@ pub fn editable_null_sentinel() -> String { /// A technical term, so it is not translated. const READONLY_NULL: &str = "NULL"; -thread_local! { - static NULL_DISPLAY: std::cell::RefCell = std::cell::RefCell::new(READONLY_NULL.to_owned()); -} - -/// The text a cell shows for NULL, which Preferences set. -pub fn null_display() -> String { - NULL_DISPLAY.with(|text| text.borrow().clone()) -} - -pub fn set_null_display(text: &str) { - NULL_DISPLAY.with(|slot| *slot.borrow_mut() = text.to_owned()); -} - /// For a column the server fills in on INSERT, so a new draft row does /// not read as if its id were stored as NULL. pub fn auto_filled_sentinel() -> String { @@ -64,10 +51,7 @@ pub fn auto_filled_sentinel() -> String { pub fn display_text<'a>(value: &'a Value, column: &ColumnType, scratch: &'a mut String) -> DisplayText<'a> { scratch.clear(); match value { - Value::Null => { - scratch.push_str(&null_display()); - DisplayText::placeholder(scratch.as_str()) - } + Value::Null => DisplayText::placeholder(READONLY_NULL), Value::Text(text) => shown(text, scratch), // The server's own text, never parsed and written out again. Value::Json(json) => shown(json.as_str(), scratch), diff --git a/linux/crates/app/src/ui/a11y/tests.rs b/linux/crates/app/src/ui/a11y/tests.rs index 70f3cc15f7..c7ce7a5277 100644 --- a/linux/crates/app/src/ui/a11y/tests.rs +++ b/linux/crates/app/src/ui/a11y/tests.rs @@ -40,6 +40,7 @@ fn template_classes() -> Vec { preferences_dialog::DataBrowserGroup::static_type(), preferences_dialog::EditorPage::static_type(), preferences_dialog::GeneralPage::static_type(), + preferences_dialog::GridPage::static_type(), preferences_dialog::HistoryGroup::static_type(), saved_queries_dialog::SavedQueriesDialog::static_type(), saved_queries_dialog::SavedQueryRow::static_type(), diff --git a/linux/crates/app/src/ui/data_grid/columns.rs b/linux/crates/app/src/ui/data_grid/columns.rs index 4a7ffe816d..12c443aec7 100644 --- a/linux/crates/app/src/ui/data_grid/columns.rs +++ b/linux/crates/app/src/ui/data_grid/columns.rs @@ -11,12 +11,12 @@ use tablepro_core::Value; use super::grid_cell::{GridCell, TextAttributes}; use super::server_sorter::ServerSorter; use super::{DataGrid, GridRow, GridSorting, TrackedValues, client_sorter, grid_menu, row_number_column}; -use crate::services::grid::display_text::editable_null_sentinel; use crate::services::grid::{ CellDisplay, ColumnLayout, GridColumn, LayoutSlot, Placement, default_width_chars, header_text, merge_order, number_width_chars, sampled_texts, typical_texts, typical_width_chars, }; use crate::ui::handler_guard::HandlerGuard; +use tablepro_linux_platform::settings::GridPreferences; /// Rows sampled for a column's opening width. const WIDTH_SAMPLE: usize = 200; @@ -49,6 +49,7 @@ pub struct ColumnPaint { pub column: GridColumn, pub tracked: TrackedValues, pub attributes: Rc, + pub preferences: GridPreferences, /// The column lines its values up on the last digit. An untyped column /// does once every value it holds is a number. pub numbers: Cell, @@ -159,6 +160,10 @@ impl DataGrid { column: column.clone(), tracked: tracked.clone(), attributes: attributes.clone(), + preferences: self + .config() + .map(|config| config.settings.grid_preferences().clone()) + .unwrap_or_default(), numbers: Cell::new(column.display() == CellDisplay::Number), }); built.view_columns.push(self.build_column(&paint, sorting)); @@ -303,7 +308,6 @@ impl DataGrid { let font = value_font(&context); let metrics = context.metrics(Some(&font), None); let char_px = pango::units_to_double(metrics.approximate_char_width()); - let null = editable_null_sentinel(); let mut widths = Vec::new(); for (paint, view_column) in set.paints.iter().zip(&set.view_columns) { let index = paint.column.index; @@ -348,9 +352,9 @@ impl DataGrid { None => 0, }; let header = header_width(&context, header_text(column)) + indicator; - // A NULL the user can replace draws as ``, wider than the - // fewest cells a column takes. - let placeholder = match paint.tracked.tracks_changes() && values.iter().any(|value| value.is_null()) { + let preferences = paint.preferences.snapshot(); + let null = super::grid_cell::null_text(&preferences.null_display, paint.tracked.tracks_changes()); + let placeholder = match values.iter().any(|value| value.is_null()) { true => drawn_width(&context, &font, &null), false => 0, }; diff --git a/linux/crates/app/src/ui/data_grid/display_settings.rs b/linux/crates/app/src/ui/data_grid/display_settings.rs index d1dc361540..70fbf7b1e5 100644 --- a/linux/crates/app/src/ui/data_grid/display_settings.rs +++ b/linux/crates/app/src/ui/data_grid/display_settings.rs @@ -1,65 +1,47 @@ -//! The preferences that shape how a grid reads, as the macOS data grid -//! settings do: whether rows are numbered, how much room a row takes, and -//! what a NULL shows. - use gtk4::prelude::*; use gtk4::subclass::prelude::*; -use tablepro_linux_platform::settings::keys; +use tablepro_linux_platform::settings::GridRowHeight; use super::DataGrid; use super::grid_cell::set_class; -use crate::services::grid::display_text::set_null_display; use crate::ui::handler_guard::HandlerGuard; -/// The classes a row height takes, one for each word the setting holds. -const HEIGHT_CLASSES: [(&str, &str); 4] = [ - ("compact", "row-compact"), - ("normal", "row-normal"), - ("comfortable", "row-comfortable"), - ("spacious", "row-spacious"), -]; - impl DataGrid { - /// Follow the row numbers, the row height and the NULL text the - /// preferences name, now and when one changes. pub(super) fn watch_display_settings(&self) { - let Some(settings) = self.config().map(|config| config.settings.clone()) else { + let Some(config) = self.config() else { return; }; + let preferences = config.settings.grid_preferences(); let weak = self.downgrade(); - // Connected before the reads: GSettings emits `changed` only for a - // key read while a handler was connected. - let handler = settings.gio().connect_changed(None, move |_, key| { - if matches!(key, keys::SHOW_ROW_NUMBERS | keys::GRID_ROW_HEIGHT | keys::NULL_DISPLAY) - && let Some(grid) = weak.upgrade() - { + let handler = preferences.connect_changed(move |_| { + if let Some(grid) = weak.upgrade() { grid.apply_display_settings(); } }); self.imp() .display_watch - .replace(Some(HandlerGuard::new(settings.gio(), handler))); + .replace(Some(HandlerGuard::new(preferences, handler))); self.apply_display_settings(); } - /// Read the three settings again and draw the grid by them. pub(super) fn apply_display_settings(&self) { - let Some(settings) = self.config().map(|config| config.settings.clone()) else { + let Some(config) = self.config() else { return; }; + let values = config.settings.grid_preferences().snapshot(); let view = self.column_view(); - let height = settings.grid_row_height(); - for (word, class) in HEIGHT_CLASSES { - set_class(&view, class, word == height); + for height in GridRowHeight::ALL { + set_class(&view, height.css_class(), height == values.row_height); } + set_class(&view, "tp-striped", values.show_alternate_rows); if let Some(numbers) = self.row_numbers_column() { - numbers.set_visible(settings.show_row_numbers()); + numbers.set_visible(values.show_row_numbers); } - // The text is the app's to show, so every grid reads the same one. - let null = settings.null_display(); - if crate::services::grid::display_text::null_display() != null { - set_null_display(&null); + let changed = self.imp().applied_null.borrow().as_deref() != Some(&values.null_display); + if changed { + self.imp().applied_null.replace(Some(values.null_display.clone())); self.redraw(); + self.fonts_changed(); } } } 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..cd8a745e24 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -37,7 +37,6 @@ pub struct TextAttributes { deleted_placeholder: pango::AttrList, placeholder: pango::AttrList, /// The stand-in texts, translated once rather than on every bind. - editable_null: String, auto_filled: String, } @@ -61,7 +60,6 @@ impl TextAttributes { deleted: list(TextMark::Deleted, false), deleted_placeholder: list(TextMark::Deleted, true), placeholder: list(TextMark::Plain, true), - editable_null: editable_null_sentinel(), auto_filled: auto_filled_sentinel(), } } @@ -344,11 +342,22 @@ fn shown_text<'a>( } (Some(ServerValue::Default), _) => DisplayText::placeholder("DEFAULT"), (Some(ServerValue::Expression(expression)), _) => DisplayText::placeholder(expression.sql), - (None, Value::Null) if editable => DisplayText::placeholder(&paint.attributes.editable_null), + (None, Value::Null) => { + *scratch = null_text(&paint.preferences.snapshot().null_display, editable); + DisplayText::placeholder(scratch) + } (None, value) => display_text(value, &paint.column.column_type, scratch), } } +pub(super) fn null_text(text: &str, editable: bool) -> String { + match (editable, text) { + (true, "NULL") => editable_null_sentinel(), + (true, _) => format!("<{text}>"), + (false, _) => text.to_owned(), + } +} + pub(super) fn set_class(widget: &impl IsA, class: &str, on: bool) { match on { true => widget.as_ref().add_css_class(class), diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index 521dbe8d4a..92e08c2e2a 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -88,7 +88,7 @@ pub struct DataGrid { pub focus_watch: RefCell, glib::SignalHandlerId)>>, pub(super) font_watch: RefCell>, pub(super) display_watch: RefCell>, - pub(super) stripes_watch: RefCell>, + pub(super) applied_null: RefCell>, } #[glib::object_subclass] @@ -127,6 +127,7 @@ impl ObjectImpl for DataGrid { self.summary.stop(); self.obj().stop_watching_focus(); drop(self.font_watch.take()); + drop(self.display_watch.take()); if let Some(menus) = self.menus.get() { menus.unparent(); } diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index 40098df398..9c4f407fba 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -91,7 +91,6 @@ impl DataGrid { imp.detail_pane.attach(&grid); grid.set_columns(columns, sorting, rules); grid.watch_fonts(); - grid.watch_stripes(); grid.watch_display_settings(); grid } diff --git a/linux/crates/app/src/ui/data_grid/row_detail/fields.rs b/linux/crates/app/src/ui/data_grid/row_detail/fields.rs index b698999b09..325669e934 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/fields.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/fields.rs @@ -40,13 +40,13 @@ pub struct FieldValue { pub deleted: bool, } -pub fn field_value(tracked: &TrackedValues, row: &GridRow, column: &GridColumn) -> FieldValue { +pub fn field_value(tracked: &TrackedValues, row: &GridRow, column: &GridColumn, null_display: &str) -> FieldValue { let mark = tracked.mark(row, column.index); let (text, placeholder, null) = tracked.with_value(row, column.index, |value, computed| match (computed, value) { (Some(ServerValue::Default), _) if column.auto_filled() => (auto_filled_sentinel(), true, false), (Some(ServerValue::Default), _) => ("DEFAULT".to_owned(), true, false), (Some(ServerValue::Expression(expression)), _) => (expression.sql.to_owned(), true, false), - (None, Value::Null) => ("NULL".to_owned(), true, true), + (None, Value::Null) => (null_display.to_owned(), true, true), (None, value) => { let mut scratch = String::new(); let shown = display_text(value, &column.column_type, &mut scratch); @@ -211,7 +211,11 @@ impl RowDetailPane { shown.set_text(None); return; }; - let value = field_value(&grid.tracked(), &row, &column); + let Some(config) = grid.config() else { + return; + }; + let preferences = config.settings.grid_preferences().snapshot(); + let value = field_value(&grid.tracked(), &row, &column, &preferences.null_display); shown.set_text(Some(&value.text)); shown.set_attributes(Some(&value_attributes(&value))); set_class(&shown, "dimmed", value.placeholder || value.deleted); diff --git a/linux/crates/app/src/ui/data_grid/row_detail/tests.rs b/linux/crates/app/src/ui/data_grid/row_detail/tests.rs index 831c4f96df..aa84c89847 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/tests.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/tests.rs @@ -1424,3 +1424,32 @@ fn a_page_that_takes_the_row_closes_its_clock_and_writes_nothing() { ); assert!(!pane.imp().clock_popover.is_visible()); } + +#[gtk4::test] +fn null_preferences_update_details_without_replacing_a_draft() { + let (grid, pane) = opened(two_text_columns(), vec![vec![Value::Int(1), Value::Null]]); + grid.focus(0, 1); + let settings = grid.grid.config().expect("configured grid").settings.clone(); + settings.set_null_display("missing").expect("store placeholder"); + drain_main_context(); + + assert_eq!(pane.imp().placeholder_label.label(), "missing"); + let shown: Vec = descendants(&pane.imp().field_list.get()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .filter_map(|inscription| inscription.text().map(|text| text.to_string())) + .collect(); + assert!(shown.contains(&"missing".to_owned()), "field list showed {shown:?}"); + + edit_field(&grid, &pane, 0, 1); + type_value(&pane, "unfinished"); + assert!(grid.grid.is_editing()); + settings + .set_null_display("absent") + .expect("change placeholder while editing"); + drain_main_context(); + + assert_eq!(pane.typed_text(), "unfinished"); + assert!(grid.grid.is_editing()); + assert_eq!(pending(&grid, 1, 1), None); +} diff --git a/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs b/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs index 326e4dea53..df1174a1e2 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs @@ -350,7 +350,12 @@ impl RowDetailPane { } let tracked = grid.tracked(); let input = tracked.edit_input(&row, column.index); - let content = value_content(&column, &row.id(), tracked.lock(&column, &row), &input); + let mut content = value_content(&column, &row.id(), tracked.lock(&column, &row), &input); + if matches!(input, CellInput::Value(Value::Null)) + && let Some(config) = grid.config() + { + content.open_placeholder = Some(config.settings.grid_preferences().snapshot().null_display.clone()); + } self.show_value(&column.name, &content); self.show_picture(match input { CellInput::Value(Value::Bytes(bytes)) => Some(bytes), diff --git a/linux/crates/app/src/ui/data_grid/stripes.rs b/linux/crates/app/src/ui/data_grid/stripes.rs index b190b95f60..54db9bf583 100644 --- a/linux/crates/app/src/ui/data_grid/stripes.rs +++ b/linux/crates/app/src/ui/data_grid/stripes.rs @@ -1,14 +1,9 @@ +use gtk4 as gtk; use gtk4::prelude::*; -use gtk4::subclass::prelude::*; -use gtk4::{self as gtk, glib}; -use tablepro_linux_platform::settings::keys; -use super::DataGrid; use super::grid_cell::set_class; -use crate::ui::handler_guard::HandlerGuard; const STRIPE: &str = "tp-stripe"; -const STRIPED: &str = "tp-striped"; // Rows are recycled, so `:nth-child` cannot stripe them and GTK has no API // to class a row: each cell's child follows its row's position instead. @@ -21,26 +16,3 @@ pub(super) fn follow(cell: >k::ColumnViewCell) { } }); } - -impl DataGrid { - pub(super) fn watch_stripes(&self) { - let Some(settings) = self.config().map(|config| config.settings.clone()) else { - return; - }; - let view = self.column_view(); - // Connected before the read: GSettings emits `changed` only for a key - // read while a handler was connected. - let handler = settings.gio().connect_changed( - Some(keys::SHOW_ALTERNATE_ROWS), - glib::clone!( - #[weak] - view, - move |settings, key| set_class(&view, STRIPED, settings.boolean(key)) - ), - ); - self.imp() - .stripes_watch - .replace(Some(HandlerGuard::new(settings.gio(), handler))); - set_class(&view, STRIPED, settings.show_alternate_rows()); - } -} 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..5573b1ea11 100644 --- a/linux/crates/app/src/ui/data_grid/test_grid.rs +++ b/linux/crates/app/src/ui/data_grid/test_grid.rs @@ -105,6 +105,7 @@ pub(crate) fn text(value: &str) -> CellInput { /// How a test grid is built: an editing table grid by default. pub(crate) struct GridSpec { pub columns: Vec, + pub settings: Option>, pub editable: bool, pub sorting: GridSorting, pub layout: Option, @@ -123,6 +124,7 @@ impl GridSpec { pub(crate) fn table(columns: Vec) -> Self { Self { columns, + settings: None, editable: true, sorting: GridSorting::Server { initial: None }, layout: None, @@ -187,7 +189,7 @@ impl Grid { }), tracker: spec.editable.then(|| tracker.clone()), result_lock: None, - settings: settings.get().clone(), + settings: spec.settings.unwrap_or_else(|| settings.get().clone()), layout: spec.layout, references: spec.references, dialect: spec.dialect, diff --git a/linux/crates/app/src/ui/data_grid/tests/cells.rs b/linux/crates/app/src/ui/data_grid/tests/cells.rs index 6f703b35f7..3aaa42d8f6 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -29,6 +29,7 @@ fn paint() -> Rc { column: columns[0].clone(), tracked: TrackedValues::untracked(), attributes: Rc::new(TextAttributes::new()), + preferences: Default::default(), numbers: Cell::new(false), }) } @@ -222,7 +223,6 @@ fn open_grids_follow_the_display_preferences() { drain_main_context(); assert!(numbers.is_visible()); assert!(view.has_css_class("row-spacious") && !view.has_css_class("row-compact")); - crate::services::grid::display_text::set_null_display("NULL"); } #[gtk4::test] @@ -522,3 +522,82 @@ fn cells_are_freed_with_the_grid() { let alive = freed.iter().filter(|cell| cell.upgrade().is_some()).count(); assert_eq!(alive, 0, "cells outlived their grid"); } + +#[gtk4::test] +fn null_text_reaches_every_grid_and_stays_with_its_settings() { + let editable = Grid::open(two_text_columns(), vec![vec![Value::Int(1), Value::Null]]); + let settings = editable.grid.config().expect("configured grid").settings.clone(); + let readonly = Grid::build( + GridSpec { + settings: Some(settings.clone()), + ..GridSpec::results(two_text_columns()) + }, + results(&[vec![Value::Int(1), Value::Null]]), + ); + let isolated = Grid::build( + GridSpec::results(two_text_columns()), + results(&[vec![Value::Int(1), Value::Null]]), + ); + let editable_cell = editable.cell_of(1, 1); + let readonly_cell = readonly.cell_at(0, 1); + assert_eq!(Grid::display_text(&editable_cell), editable_null_sentinel()); + assert_eq!(Grid::display_text(&readonly_cell), "NULL"); + + settings.set_null_display("missing").expect("store placeholder"); + drain_main_context(); + + assert_eq!(Grid::display_text(&editable_cell), ""); + assert_eq!(Grid::display_text(&readonly_cell), "missing"); + assert_eq!(Grid::display_text(&isolated.cell_at(0, 1)), "NULL"); + assert!(described(&editable_cell)); + assert!(described(&readonly_cell)); + let reopened = Grid::build( + GridSpec { + settings: Some(settings), + ..GridSpec::results(two_text_columns()) + }, + results(&[vec![Value::Int(1), Value::Null]]), + ); + assert_eq!(Grid::display_text(&reopened.cell_at(0, 1)), "missing"); +} + +#[gtk4::test] +fn display_preferences_preserve_the_inline_draft_and_selected_rows() { + let grid = two_text_rows(); + let cell = grid.focus(0, 1); + grid.grid.selection().select_range(0, 2, true); + assert!(grid.grid.edit().edit_cell(&cell)); + let editor = grid.grid.edit().open_text().expect("inline editor"); + editor.set_text("unfinished"); + let selected = super::selected_ids(&grid); + let settings = grid.grid.config().expect("configured grid").settings.clone(); + + settings.set_null_display("missing").expect("store placeholder"); + settings.set_grid_row_height("spacious").expect("store height"); + settings.set_show_row_numbers(false).expect("hide numbers"); + drain_main_context(); + + assert_eq!(grid.grid.edit().open_text().as_ref(), Some(&editor)); + assert_eq!(editor.text(), "unfinished"); + assert_eq!(grid.grid.edit().editing_cell(), Some(cell)); + assert_eq!(super::selected_ids(&grid), selected); + assert_eq!(grid.tracker.cell_overlay(&key(1), 1).pending, None); +} + +#[gtk4::test] +fn row_height_preferences_change_the_allocated_row_height() { + let grid = two_text_rows(); + let settings = grid.grid.config().expect("configured grid").settings.clone(); + let cell = grid.cell_of(1, 1); + settings.set_grid_row_height("compact").expect("compact height"); + crate::test_support::after_next_frame(&grid.grid); + let row = row_widget(&cell); + wait_until(WAIT, || row.height() > 0).expect("row laid out"); + let compact = row.measure(gtk::Orientation::Vertical, -1).1; + + settings.set_grid_row_height("spacious").expect("spacious height"); + wait_until(WAIT, || row.measure(gtk::Orientation::Vertical, -1).1 > compact) + .expect("the larger padding makes a taller row"); + let spacious = row.measure(gtk::Orientation::Vertical, -1).1; + wait_until(WAIT, || row.height() >= spacious).expect("row uses its larger height"); +} diff --git a/linux/crates/app/src/ui/data_grid/tests/columns.rs b/linux/crates/app/src/ui/data_grid/tests/columns.rs index 887d76ac09..6858622954 100644 --- a/linux/crates/app/src/ui/data_grid/tests/columns.rs +++ b/linux/crates/app/src/ui/data_grid/tests/columns.rs @@ -831,3 +831,34 @@ mod real_keys { assert_eq!(layouts.saved("t").widths.get("name"), None); } } + +#[gtk4::test] +fn null_text_resizes_automatic_columns_and_preserves_manual_widths() { + for editable in [false, true] { + let columns = two_text_columns(); + let spec = if editable { + GridSpec::table(columns) + } else { + GridSpec::results(columns) + }; + let values = vec![vec![Value::Int(1), Value::Null]]; + let rows = if editable { persisted(&values) } else { results(&values) }; + let grid = Grid::build(spec, rows); + let settings = grid.grid.config().expect("configured grid").settings.clone(); + let column = data_column(&grid, 1); + let original = column.fixed_width(); + + settings + .set_null_display("value is unavailable") + .expect("store long placeholder"); + wait_until(WAIT, || column.fixed_width() > original).expect("automatic column grows"); + wait_until(WAIT, || { + shows_whole(grid.cell_at(0, 1).display().expect("cell display")) + }) + .expect("the whole placeholder fits"); + column.set_fixed_width(260); + settings.set_null_display("none").expect("store short placeholder"); + drain_main_context(); + assert_eq!(column.fixed_width(), 260, "the chosen width stays"); + } +} diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index a29ba9c4d0..611b65ca31 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -1,13 +1,10 @@ -use gio::prelude::{SettingsExt, SettingsExtManual}; +use gio::prelude::SettingsExtManual; use gtk4::glib; +use gtk4::prelude::*; use gtk4::subclass::prelude::*; use libadwaita as adw; -use libadwaita::prelude::ComboRowExt; use tablepro_linux_platform::AppSettings; -use tablepro_linux_platform::settings::keys; - -/// The words the row height setting holds, in the combo's order. -const ROW_HEIGHTS: [&str; 4] = ["compact", "normal", "comfortable", "spacious"]; +use tablepro_linux_platform::settings::{GridRowHeight, keys}; mod imp { use libadwaita::prelude::*; @@ -64,8 +61,6 @@ mod imp { } glib::wrapper! { - /// The General page's rows for the row paginator and the delete - /// confirmation. pub struct DataBrowserGroup(ObjectSubclass) @extends adw::PreferencesGroup, gtk4::Widget, @implements gtk4::Accessible, gtk4::Buildable, gtk4::ConstraintTarget; @@ -96,21 +91,20 @@ impl DataBrowserGroup { gio_settings .bind(keys::NULL_DISPLAY, &imp.null_display_row.get(), "text") .build(); - // The combo holds a position and the setting a word. - let row = imp.row_height_row.get(); - let current = settings.grid_row_height(); - row.set_selected( - ROW_HEIGHTS - .iter() - .position(|height| *height == current) - .map_or(1, |at| at as u32), - ); - let stored = gio_settings.clone(); - row.connect_selected_notify(move |row| { - if let Some(height) = ROW_HEIGHTS.get(row.selected() as usize) { - let _ = stored.set_string(keys::GRID_ROW_HEIGHT, height); - } - }); + gio_settings + .bind(keys::GRID_ROW_HEIGHT, &imp.row_height_row.get(), "selected") + .mapping(|variant, _| { + let height = variant.str()?; + let index = GridRowHeight::ALL + .iter() + .position(|candidate| candidate.nick() == height)?; + Some((index as u32).to_value()) + }) + .set_mapping(|value, _| { + let index = value.get::().ok()?; + Some(GridRowHeight::ALL.get(index as usize)?.nick().to_variant()) + }) + .build(); } } @@ -173,4 +167,45 @@ mod tests { Some("Ask before deleting 10 or more rows at once") ); } + + #[gtk4::test] + fn display_preferences_follow_changes_from_another_window() { + let settings = MemorySettings::new(); + let first = bound_group(&settings); + let second = bound_group(&settings); + + first.imp().row_height_row.set_selected(3); + first.imp().row_numbers_row.set_active(false); + first.imp().null_display_row.set_text("empty"); + + assert_eq!(settings.get().grid_row_height(), "spacious"); + assert_eq!(second.imp().row_height_row.selected(), 3); + assert!(!second.imp().row_numbers_row.is_active()); + assert_eq!(second.imp().null_display_row.text(), "empty"); + + settings.get().set_grid_row_height("compact").expect("store the height"); + settings.get().set_show_row_numbers(true).expect("store the flag"); + settings.get().set_null_display("missing").expect("store the text"); + + for group in [&first, &second] { + assert_eq!(group.imp().row_height_row.selected(), 0); + assert!(group.imp().row_numbers_row.is_active()); + assert_eq!(group.imp().null_display_row.text(), "missing"); + } + second.imp().row_height_row.set_selected(1); + assert_eq!(first.imp().row_height_row.selected(), 1); + assert_eq!(settings.get().grid_row_height(), "normal"); + } + + #[gtk4::test] + fn null_text_entry_limits_characters_without_cutting_unicode() { + let settings = MemorySettings::new(); + let group = bound_group(&settings); + let text = "界".repeat(21); + + group.imp().null_display_row.set_text(&text); + + assert_eq!(group.imp().null_display_row.text(), "界".repeat(20)); + assert_eq!(settings.get().null_display(), "界".repeat(20)); + } } diff --git a/linux/crates/app/src/ui/preferences_dialog/general_page.rs b/linux/crates/app/src/ui/preferences_dialog/general_page.rs index 299e3f0cfc..ed143127a7 100644 --- a/linux/crates/app/src/ui/preferences_dialog/general_page.rs +++ b/linux/crates/app/src/ui/preferences_dialog/general_page.rs @@ -9,7 +9,6 @@ use tablepro_linux_platform::AppSettings; use tablepro_linux_platform::settings::keys; use tablepro_session::runtime::Tasks; -use super::data_browser_group::DataBrowserGroup; use super::history_group::HistoryGroup; use crate::ui::file_reveal::FileRevealer; @@ -24,8 +23,6 @@ mod imp { #[template_child] pub restore_session_row: TemplateChild, #[template_child] - pub data_browser_group: TemplateChild, - #[template_child] pub history_group: TemplateChild, #[template_child] pub privacy_group: TemplateChild, @@ -40,7 +37,6 @@ mod imp { type ParentType = adw::PreferencesPage; fn class_init(klass: &mut Self::Class) { - DataBrowserGroup::ensure_type(); HistoryGroup::ensure_type(); klass.bind_template(); } @@ -56,7 +52,6 @@ mod imp { } glib::wrapper! { - /// The General page: startup, the data browser and the query history. pub struct GeneralPage(ObjectSubclass) @extends adw::PreferencesPage, gtk4::Widget, @implements gtk4::Accessible, gtk4::Buildable, gtk4::ConstraintTarget; @@ -89,7 +84,6 @@ impl GeneralPage { .gio() .bind(keys::SHARE_USAGE_DATA, &imp.share_usage_data_row.get(), "active") .build(); - imp.data_browser_group.bind(settings); imp.history_group.bind(settings, storage, history, tasks, revealer); } @@ -136,7 +130,6 @@ mod tests { page } - /// The page's groups, in the order it shows them. fn groups(page: &GeneralPage) -> Vec { crate::test_support::descendants(page) .into_iter() @@ -178,11 +171,11 @@ mod tests { let page = bound_page(&settings, &storage, &root, &runtime.tasks()); let titles: Vec = groups(&page).iter().map(|group| group.title().to_string()).collect(); - assert_eq!(titles, ["Startup", "Data Browser", "Query History"]); + assert_eq!(titles, ["Startup", "Query History"]); } #[gtk4::test] - fn general_page_contains_the_data_browser_and_history_groups() { + fn general_page_contains_startup_and_history_groups() { let settings = MemorySettings::new(); let runtime = test_runtime(); let storage = test_storage(&runtime.tasks()); @@ -193,9 +186,8 @@ mod tests { let titles: Vec = groups.iter().map(|group| group.title().to_string()).collect(); assert_eq!(page.title(), "General"); - assert_eq!(titles, ["Startup", "Data Browser", "Query History"]); - assert!(groups[1].is::()); - assert!(groups[2].is::()); + assert_eq!(titles, ["Startup", "Query History"]); + assert!(groups[1].is::()); } #[gtk4::test] @@ -216,7 +208,7 @@ mod tests { } #[gtk4::test] - fn the_page_binds_both_of_its_groups() { + fn the_page_binds_its_history_group() { let settings = MemorySettings::new(); let runtime = test_runtime(); let storage = test_storage(&runtime.tasks()); @@ -224,10 +216,8 @@ mod tests { let page = bound_page(&settings, &storage, &root, &runtime.tasks()); let imp = page.imp(); - imp.data_browser_group.imp().confirm_row.set_active(false); imp.history_group.imp().save_history_row.set_active(false); - assert!(!settings.get().confirm_bulk_delete()); assert!(!settings.get().save_query_history()); } } diff --git a/linux/crates/app/src/ui/preferences_dialog/grid_page.rs b/linux/crates/app/src/ui/preferences_dialog/grid_page.rs new file mode 100644 index 0000000000..4044a2ba52 --- /dev/null +++ b/linux/crates/app/src/ui/preferences_dialog/grid_page.rs @@ -0,0 +1,79 @@ +use gtk4::glib; +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use libadwaita as adw; +use tablepro_linux_platform::AppSettings; + +use super::data_browser_group::DataBrowserGroup; + +mod imp { + use libadwaita::subclass::prelude::*; + + use super::*; + + #[derive(Default, gtk4::CompositeTemplate)] + #[template(resource = "/app/tablepro/TablePro/ui/preferences-grid-page.ui")] + pub struct GridPage { + #[template_child] + pub data_browser_group: TemplateChild, + } + + #[glib::object_subclass] + impl ObjectSubclass for GridPage { + const NAME: &'static str = "TableProGridPage"; + type Type = super::GridPage; + type ParentType = adw::PreferencesPage; + + fn class_init(klass: &mut Self::Class) { + DataBrowserGroup::ensure_type(); + klass.bind_template(); + } + + fn instance_init(object: &glib::subclass::InitializingObject) { + object.init_template(); + } + } + + impl ObjectImpl for GridPage {} + impl WidgetImpl for GridPage {} + impl PreferencesPageImpl for GridPage {} +} + +glib::wrapper! { + pub struct GridPage(ObjectSubclass) + @extends adw::PreferencesPage, gtk4::Widget, + @implements gtk4::Accessible, gtk4::Buildable, gtk4::ConstraintTarget; +} + +impl Default for GridPage { + fn default() -> Self { + glib::Object::new() + } +} + +impl GridPage { + pub(super) fn bind(&self, settings: &AppSettings) { + self.imp().data_browser_group.bind(settings); + } +} + +#[cfg(test)] +mod tests { + use libadwaita::prelude::*; + + use super::*; + use crate::test_support::MemorySettings; + + #[gtk4::test] + fn the_grid_page_binds_its_data_browser_group() { + crate::register_test_resources(); + let settings = MemorySettings::new(); + let page = GridPage::default(); + page.bind(settings.get()); + + page.imp().data_browser_group.imp().confirm_row.set_active(false); + + assert_eq!(page.title(), "Data Grid"); + assert!(!settings.get().confirm_bulk_delete()); + } +} diff --git a/linux/crates/app/src/ui/preferences_dialog/imp.rs b/linux/crates/app/src/ui/preferences_dialog/imp.rs index a726595628..ee14ce46a7 100644 --- a/linux/crates/app/src/ui/preferences_dialog/imp.rs +++ b/linux/crates/app/src/ui/preferences_dialog/imp.rs @@ -12,6 +12,7 @@ use super::account_page::AccountPage; use super::ai_page::AiPage; use super::editor_page::EditorPage; use super::general_page::GeneralPage; +use super::grid_page::GridPage; use super::mcp_page::McpPage; #[derive(Default, gtk4::CompositeTemplate)] @@ -20,6 +21,8 @@ pub struct PreferencesDialog { #[template_child] pub general_page: TemplateChild, #[template_child] + pub grid_page: TemplateChild, + #[template_child] pub editor_page: TemplateChild, #[template_child] pub mcp_page: TemplateChild, @@ -38,6 +41,7 @@ impl ObjectSubclass for PreferencesDialog { fn class_init(klass: &mut Self::Class) { GeneralPage::ensure_type(); + GridPage::ensure_type(); EditorPage::ensure_type(); McpPage::ensure_type(); AiPage::ensure_type(); diff --git a/linux/crates/app/src/ui/preferences_dialog/mod.rs b/linux/crates/app/src/ui/preferences_dialog/mod.rs index 567b5f661b..d9035c9094 100644 --- a/linux/crates/app/src/ui/preferences_dialog/mod.rs +++ b/linux/crates/app/src/ui/preferences_dialog/mod.rs @@ -5,6 +5,7 @@ mod data_browser_group; mod device_limit_dialog; mod editor_page; mod general_page; +mod grid_page; mod history_group; mod imp; mod mcp_page; @@ -26,7 +27,7 @@ use crate::ui::file_reveal::FileRevealer; #[cfg(test)] pub(super) use self::{ - data_browser_group::DataBrowserGroup, editor_page::EditorPage, general_page::GeneralPage, + data_browser_group::DataBrowserGroup, editor_page::EditorPage, general_page::GeneralPage, grid_page::GridPage, history_group::HistoryGroup, }; @@ -65,6 +66,7 @@ impl PreferencesDialog { revealer.clone(), telemetry.has_project_key(), ); + imp.grid_page.bind(settings); imp.editor_page.bind( settings, editor_page::SnippetsFolder { @@ -110,8 +112,6 @@ impl PreferencesDialog { } } -/// A query history of its own under `root`, opening in the background -/// as the app's does. #[cfg(test)] fn test_history(root: &tempfile::TempDir, tasks: &Tasks) -> HistoryService { let paths = tablepro_storage::StoragePaths::under(root.path(), "tablepro-test", "app.tablepro.TablePro.Devel"); @@ -122,8 +122,8 @@ fn test_history(root: &tempfile::TempDir, tasks: &Tasks) -> HistoryService { HistoryService::start(paths, preferences, tasks) } -/// A storage under a temporary root, so the dialog's storage row and -/// history actions stay away from the developer's own files. +// A storage under a temporary root, so the dialog's storage row and +// history actions stay away from the developer's own files. #[cfg(test)] fn test_storage(tasks: &Tasks) -> crate::storage::SharedStorage { let root = std::env::temp_dir().join(format!("tablepro-prefs-{}", std::process::id())); @@ -141,9 +141,9 @@ mod tests { use crate::test_support::{MemorySettings, assert_labelled, descendants, test_runtime, unlabelled_icon_buttons}; use crate::ui::file_reveal::RecordingRevealer; - /// The template lives in the embedded resources, so a test that - /// builds the dialog has to register them first. Test order is not - /// fixed, so it cannot rely on another test having done it. + // The template lives in the embedded resources, so a test that + // builds the dialog has to register them first. Test order is not + // fixed, so it cannot rely on another test having done it. fn new_dialog( settings: &MemorySettings, storage: &crate::storage::SharedStorage, @@ -164,13 +164,12 @@ mod tests { ) } - /// The dialog's pages, in the order it shows them. They are not in - /// its widget tree until it is presented, so they come from the - /// template. - fn pages(dialog: &PreferencesDialog) -> [adw::PreferencesPage; 5] { + // Pages are not in the widget tree until the dialog is presented. + fn pages(dialog: &PreferencesDialog) -> [adw::PreferencesPage; 6] { let imp = dialog.imp(); [ imp.general_page.get().upcast(), + imp.grid_page.get().upcast(), imp.editor_page.get().upcast(), imp.ai_page.get().upcast(), imp.mcp_page.get().upcast(), @@ -190,9 +189,10 @@ mod tests { test_history(&root, &runtime.tasks()), &runtime.tasks(), ); - let [general, editor, ai, mcp, account] = pages(&dialog); + let [general, grid, editor, ai, mcp, account] = pages(&dialog); assert_eq!(general.title(), "General"); + assert_eq!(grid.title(), "Data Grid"); assert_eq!(editor.title(), "Editor"); assert_eq!(ai.title(), "AI"); assert_eq!(mcp.title(), "MCP"); @@ -303,18 +303,18 @@ mod tests { dialog.imp().general_page.history_group().imp().clear_button.get() } - /// How long a test waits for work that crosses a thread. Long - /// enough that a loaded machine cannot decide the outcome; a - /// passing test returns as soon as its condition holds and never - /// spends it. + // How long a test waits for work that crosses a thread. Long + // enough that a loaded machine cannot decide the outcome; a + // passing test returns as soon as its condition holds and never + // spends it. const WAIT: std::time::Duration = std::time::Duration::from_secs(30); - /// An AdwDialog needs a real window to present into before its - /// toast overlay renders anything. This one opens at a session - /// window's size (session-window.ui). A window left at its 360 px - /// floor gives its content 350 px under Xvfb, which has no - /// compositor, and libadwaita warns that the dialog's bottom sheet, - /// which needs 360, does not fit. + // An AdwDialog needs a real window to present into before its + // toast overlay renders anything. This one opens at a session + // window's size (session-window.ui). A window left at its 360 px + // floor gives its content 350 px under Xvfb, which has no + // compositor, and libadwaita warns that the dialog's bottom sheet, + // which needs 360, does not fit. fn present_on_a_window(dialog: &PreferencesDialog) -> crate::test_support::OwnedWindow { let window = crate::test_support::OwnedWindow::presented( adw::Window::builder().default_width(1200).default_height(760).build(), @@ -347,9 +347,9 @@ mod tests { assert!(clear_button(&dialog).is_mapped()); } - /// What the dialog's toast says, read off the label the overlay - /// renders. AdwPreferencesDialog owns the overlay itself and does - /// not hand it out. + // What the dialog's toast says, read off the label the overlay + // renders. AdwPreferencesDialog owns the overlay itself and does + // not hand it out. fn toast_text(window: &adw::Window) -> Option { crate::test_support::drain_main_context(); crate::test_support::descendants(window) @@ -386,8 +386,8 @@ mod tests { .len() } - /// The test drives the runtime from outside it, which is the one - /// place blocking on it cannot deadlock. + // The test drives the runtime from outside it, which is the one + // place blocking on it cannot deadlock. #[expect( clippy::disallowed_methods, reason = "a GTK test has no runtime of its own, so it drives the app's from outside" @@ -396,9 +396,9 @@ mod tests { runtime.tasks().handle().block_on(future) } - /// Press Clear on the confirmation alert the button raised. The - /// alert presents into the window's dialog host, not into the - /// preferences dialog, so that is where it is. + // Press Clear on the confirmation alert the button raised. The + // alert presents into the window's dialog host, not into the + // preferences dialog, so that is where it is. fn confirm_the_alert(window: &adw::Window) { crate::test_support::drain_main_context(); let alert = diff --git a/linux/crates/platform/src/settings/grid_preferences.rs b/linux/crates/platform/src/settings/grid_preferences.rs new file mode 100644 index 0000000000..6889059db9 --- /dev/null +++ b/linux/crates/platform/src/settings/grid_preferences.rs @@ -0,0 +1,168 @@ +use std::cell::{OnceCell, RefCell}; +use std::rc::Rc; +use std::sync::OnceLock; + +use gio::prelude::*; +use glib::subclass::prelude::*; + +use super::keys; + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum GridRowHeight { + Compact, + #[default] + Normal, + Comfortable, + Spacious, +} + +impl GridRowHeight { + pub const ALL: [Self; 4] = [Self::Compact, Self::Normal, Self::Comfortable, Self::Spacious]; + + pub fn from_nick(nick: &str) -> Self { + match nick { + "compact" => Self::Compact, + "comfortable" => Self::Comfortable, + "spacious" => Self::Spacious, + _ => Self::Normal, + } + } + + pub fn nick(self) -> &'static str { + match self { + Self::Compact => "compact", + Self::Normal => "normal", + Self::Comfortable => "comfortable", + Self::Spacious => "spacious", + } + } + + pub fn css_class(self) -> &'static str { + match self { + Self::Compact => "row-compact", + Self::Normal => "row-normal", + Self::Comfortable => "row-comfortable", + Self::Spacious => "row-spacious", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GridPreferenceValues { + pub show_row_numbers: bool, + pub show_alternate_rows: bool, + pub row_height: GridRowHeight, + pub null_display: String, +} + +impl Default for GridPreferenceValues { + fn default() -> Self { + Self { + show_row_numbers: true, + show_alternate_rows: true, + row_height: GridRowHeight::Normal, + null_display: "NULL".to_owned(), + } + } +} + +impl GridPreferenceValues { + fn read(settings: &gio::Settings) -> Self { + Self { + show_row_numbers: settings.boolean(keys::SHOW_ROW_NUMBERS), + show_alternate_rows: settings.boolean(keys::SHOW_ALTERNATE_ROWS), + row_height: GridRowHeight::from_nick(&settings.string(keys::GRID_ROW_HEIGHT)), + null_display: null_display_text(&settings.string(keys::NULL_DISPLAY)), + } + } +} + +fn null_display_text(text: &str) -> String { + let text: String = text.chars().filter(|ch| !ch.is_control()).take(20).collect(); + if text.trim().is_empty() { + "NULL".to_owned() + } else { + text + } +} + +mod imp { + use super::*; + + #[derive(Default)] + pub struct GridPreferences { + pub(super) settings: OnceCell, + pub(super) handler: RefCell>, + pub(super) values: RefCell>, + } + + #[glib::object_subclass] + impl ObjectSubclass for GridPreferences { + const NAME: &'static str = "TableProGridPreferences"; + type Type = super::GridPreferences; + } + + impl ObjectImpl for GridPreferences { + fn signals() -> &'static [glib::subclass::Signal] { + static SIGNALS: OnceLock> = OnceLock::new(); + SIGNALS.get_or_init(|| vec![glib::subclass::Signal::builder("changed").build()]) + } + + fn dispose(&self) { + if let (Some(settings), Some(handler)) = (self.settings.get(), self.handler.take()) { + settings.disconnect(handler); + } + } + } +} + +glib::wrapper! { + pub struct GridPreferences(ObjectSubclass); +} + +impl Default for GridPreferences { + fn default() -> Self { + glib::Object::new() + } +} + +impl GridPreferences { + pub(super) fn new(settings: &gio::Settings) -> Self { + let preferences = Self::default(); + let _ = preferences.imp().settings.set(settings.clone()); + let weak = preferences.downgrade(); + // GSettings only announces keys read after a handler was connected. + let handler = settings.connect_changed(None, move |settings, key| { + if matches!( + key, + keys::SHOW_ROW_NUMBERS | keys::SHOW_ALTERNATE_ROWS | keys::GRID_ROW_HEIGHT | keys::NULL_DISPLAY + ) && let Some(preferences) = weak.upgrade() + { + preferences.update(GridPreferenceValues::read(settings)); + } + }); + preferences.imp().handler.replace(Some(handler)); + preferences.update(GridPreferenceValues::read(settings)); + preferences + } + + pub fn snapshot(&self) -> Rc { + self.imp().values.borrow().clone() + } + + pub fn connect_changed(&self, callback: impl Fn(&Self) + 'static) -> glib::SignalHandlerId { + self.connect_closure( + "changed", + false, + glib::closure_local!(move |preferences: Self| callback(&preferences)), + ) + } + + fn update(&self, values: GridPreferenceValues) { + if *self.imp().values.borrow().as_ref() == values { + return; + } + self.imp().values.replace(Rc::new(values)); + self.emit_by_name::<()>("changed", &[]); + } +} diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index 85a11212b4..df83a22e82 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -1,8 +1,10 @@ mod editor_font; mod error; +mod grid_preferences; pub mod keys; mod window_geometry; +use std::cell::OnceCell; use std::path::Path; use std::time::Duration; @@ -12,6 +14,7 @@ use tablepro_core::export::{CsvDecimal, CsvDelimiter, CsvLineBreak, CsvOptions, pub use editor_font::EditorFont; pub use error::SettingsError; +pub use grid_preferences::{GridPreferenceValues, GridPreferences, GridRowHeight}; pub use window_geometry::WindowGeometry; /// The provider setting's value while the assistant is off. @@ -19,6 +22,7 @@ pub const AI_PROVIDER_NONE: &str = "none"; pub struct AppSettings { settings: gio::Settings, + grid_preferences: OnceCell, } impl AppSettings { @@ -33,6 +37,7 @@ impl AppSettings { .ok_or_else(|| SettingsError::SchemaNotFound(schema_id.to_owned()))?; Ok(Self { settings: gio::Settings::new_full(&schema, gio::SettingsBackend::NONE, None), + grid_preferences: OnceCell::new(), }) } @@ -55,6 +60,7 @@ impl AppSettings { .ok_or_else(|| SettingsError::SchemaNotFound(schema_id.to_owned()))?; Ok(Self { settings: gio::Settings::new_full(&schema, Some(backend), None), + grid_preferences: OnceCell::new(), }) } @@ -63,6 +69,11 @@ impl AppSettings { &self.settings } + pub fn grid_preferences(&self) -> &GridPreferences { + self.grid_preferences + .get_or_init(|| GridPreferences::new(&self.settings)) + } + pub fn default_page_size(&self) -> u32 { self.settings.uint(keys::DEFAULT_PAGE_SIZE) } @@ -81,7 +92,7 @@ impl AppSettings { } pub fn show_alternate_rows(&self) -> bool { - self.settings.boolean(keys::SHOW_ALTERNATE_ROWS) + self.grid_preferences().snapshot().show_alternate_rows } pub fn set_show_alternate_rows(&self, show: bool) -> Result<(), SettingsError> { @@ -89,25 +100,23 @@ impl AppSettings { } pub fn show_row_numbers(&self) -> bool { - self.settings.boolean(keys::SHOW_ROW_NUMBERS) + self.grid_preferences().snapshot().show_row_numbers } pub fn set_show_row_numbers(&self, show: bool) -> Result<(), SettingsError> { self.set_boolean(keys::SHOW_ROW_NUMBERS, show) } - /// The grid's row height: `compact`, `normal`, `comfortable` or `spacious`. pub fn grid_row_height(&self) -> String { - self.settings.string(keys::GRID_ROW_HEIGHT).into() + self.grid_preferences().snapshot().row_height.nick().to_owned() } pub fn set_grid_row_height(&self, height: &str) -> Result<(), SettingsError> { self.set_string(keys::GRID_ROW_HEIGHT, height) } - /// What a cell shows for NULL. pub fn null_display(&self) -> String { - self.settings.string(keys::NULL_DISPLAY).into() + self.grid_preferences().snapshot().null_display.clone() } pub fn set_null_display(&self, text: &str) -> Result<(), SettingsError> { diff --git a/linux/crates/platform/tests/settings.rs b/linux/crates/platform/tests/settings.rs index 5e50a60ee0..170aa87c07 100644 --- a/linux/crates/platform/tests/settings.rs +++ b/linux/crates/platform/tests/settings.rs @@ -330,3 +330,131 @@ fn nonexistent_dir_is_schema_directory() -> TestResult { assert!(matches!(error, SettingsError::SchemaDirectory { path, .. } if path == missing)); Ok(()) } + +#[test] +fn grid_preferences_start_from_schema_and_keep_one_model() -> TestResult { + use tablepro_linux_platform::settings::{GridPreferenceValues, GridPreferences}; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + assert_eq!(preferences.snapshot().as_ref(), &GridPreferenceValues::default()); + assert_eq!(preferences, fixture.settings.grid_preferences()); + assert_eq!(GridPreferences::default().snapshot(), preferences.snapshot()); + Ok(()) +} + +#[test] +fn every_grid_preference_observer_reads_the_updated_snapshot() -> TestResult { + use std::cell::RefCell; + use std::rc::Rc; + + use tablepro_linux_platform::settings::GridRowHeight; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + let original = preferences.snapshot(); + let first = Rc::new(RefCell::new(Vec::new())); + let second = Rc::new(RefCell::new(Vec::new())); + for observed in [&first, &second] { + let observed = observed.clone(); + preferences.connect_changed(move |preferences| observed.borrow_mut().push(preferences.snapshot())); + } + + fixture.settings.set_show_row_numbers(false)?; + fixture.settings.set_show_alternate_rows(false)?; + fixture.settings.set_grid_row_height("spacious")?; + fixture.settings.set_null_display("Missing")?; + + assert_eq!(first.borrow().len(), 4); + assert_eq!(*first.borrow(), *second.borrow()); + let current = preferences.snapshot(); + assert!(!current.show_row_numbers); + assert!(!current.show_alternate_rows); + assert_eq!(current.row_height, GridRowHeight::Spacious); + assert_eq!(current.null_display, "Missing"); + assert!(original.show_row_numbers); + assert_eq!(original.null_display, "NULL"); + Ok(()) +} + +#[test] +fn grid_preference_backends_stay_independent() -> TestResult { + let first = Fixture::new()?; + let second = Fixture::new()?; + let first_preferences = first.settings.grid_preferences(); + let second_preferences = second.settings.grid_preferences(); + + first.settings.set_null_display("Missing")?; + second.settings.set_grid_row_height("compact")?; + + assert_eq!(first_preferences.snapshot().null_display, "Missing"); + assert_eq!(second_preferences.snapshot().null_display, "NULL"); + assert_eq!(first_preferences.snapshot().row_height.nick(), "normal"); + assert_eq!(second_preferences.snapshot().row_height.nick(), "compact"); + Ok(()) +} + +#[test] +fn null_display_is_bounded_even_for_external_settings_writes() -> TestResult { + use gio::prelude::SettingsExt; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + fixture.settings.gio().set_string(keys::NULL_DISPLAY, "\n\t\r")?; + assert_eq!(preferences.snapshot().null_display, "NULL"); + fixture.settings.gio().set_string(keys::NULL_DISPLAY, " ")?; + assert_eq!(preferences.snapshot().null_display, "NULL"); + fixture.settings.gio().set_string(keys::NULL_DISPLAY, "no\nvalue\t")?; + assert_eq!(preferences.snapshot().null_display, "novalue"); + fixture + .settings + .gio() + .set_string(keys::NULL_DISPLAY, &"界".repeat(25))?; + assert_eq!(preferences.snapshot().null_display, "界".repeat(20)); + Ok(()) +} + +#[test] +fn grid_preference_changes_ignore_unrelated_and_equivalent_values() -> TestResult { + use std::cell::Cell; + use std::rc::Rc; + + let fixture = Fixture::new()?; + let calls = Rc::new(Cell::new(0)); + let observed = calls.clone(); + fixture + .settings + .grid_preferences() + .connect_changed(move |_| observed.set(observed.get() + 1)); + + fixture.settings.set_default_page_size(500)?; + fixture.settings.set_null_display("")?; + fixture.settings.set_null_display("NULL")?; + + assert_eq!(calls.get(), 0); + assert!(fixture.settings.set_grid_row_height("unknown").is_err()); + assert_eq!(fixture.settings.grid_row_height(), "normal"); + Ok(()) +} + +#[test] +fn dropping_grid_preferences_disconnects_the_settings_handler() -> TestResult { + use gio::prelude::*; + + let fixture = Fixture::new()?; + let settings = fixture.settings.gio().clone(); + let preferences = fixture.settings.grid_preferences().downgrade(); + let changed = glib::subclass::SignalId::lookup("changed", gio::Settings::static_type()).expect("changed signal"); + assert!(glib::signal::signal_has_handler_pending( + &settings, changed, None, false + )); + + drop(fixture); + + assert!(preferences.upgrade().is_none()); + assert!(!glib::signal::signal_has_handler_pending( + &settings, changed, None, false + )); + settings.set_boolean(keys::SHOW_ROW_NUMBERS, false)?; + Ok(()) +} diff --git a/linux/data/resources/resources.gresource.xml b/linux/data/resources/resources.gresource.xml index 35964baac2..bf12eb901c 100644 --- a/linux/data/resources/resources.gresource.xml +++ b/linux/data/resources/resources.gresource.xml @@ -33,6 +33,7 @@ ui/preferences-dialog.ui ui/preferences-editor-page.ui ui/preferences-general-page.ui + ui/preferences-grid-page.ui ui/preferences-history-group.ui ui/preferences-ai-page.ui ui/preferences-mcp-page.ui diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 1f52211557..bb541a71b6 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -46,6 +46,8 @@ Text for NULL + 20 + Up to 20 characters. Empty text uses NULL. diff --git a/linux/data/resources/ui/preferences-dialog.ui b/linux/data/resources/ui/preferences-dialog.ui index a3a3429e32..4905d01ac7 100644 --- a/linux/data/resources/ui/preferences-dialog.ui +++ b/linux/data/resources/ui/preferences-dialog.ui @@ -8,6 +8,9 @@ + + + diff --git a/linux/data/resources/ui/preferences-general-page.ui b/linux/data/resources/ui/preferences-general-page.ui index 116c7f3fe4..78724d223f 100644 --- a/linux/data/resources/ui/preferences-general-page.ui +++ b/linux/data/resources/ui/preferences-general-page.ui @@ -16,9 +16,6 @@ - - - diff --git a/linux/data/resources/ui/preferences-grid-page.ui b/linux/data/resources/ui/preferences-grid-page.ui new file mode 100644 index 0000000000..39efcde3a2 --- /dev/null +++ b/linux/data/resources/ui/preferences-grid-page.ui @@ -0,0 +1,12 @@ + + + + + + diff --git a/linux/docs/state-management.md b/linux/docs/state-management.md index 8550e8077c..e7825026c2 100644 --- a/linux/docs/state-management.md +++ b/linux/docs/state-management.md @@ -87,6 +87,12 @@ A tab belongs to its session, and a session to one window ([decisions/0028-sessi - Dropped outside every window, `create-window` declines a new window and the tab goes back to that position ([toolkit-workarounds.md](toolkit-workarounds.md#a-tab-dropped-outside-every-window)). - `ReturnTab` runs from the window's queue, after libadwaita finishes attaching the page. A tab whose session closed while it was out closes where it is; the session's close already asked about it, and its view no longer holds the page to close it. +## Grid preferences + +`AppSettings` owns one `GridPreferences` object. It reads the grid keys from GSettings and announces each changed snapshot. Every grid holds that object through its settings and follows its change signal. Preferences rows bind directly to GSettings, including both directions for choices stored as strings. + +The snapshot belongs to its settings backend, so isolated test settings cannot change another grid. A display change redraws the existing row slots and resizes automatic columns. It keeps row selection, user column widths and active editor drafts. The formatting helpers receive display choices explicitly and keep no global preference state. + ## The SQL editor `SqlEditor` (`crates/app/src/ui/editor/`) runs SQL on a connection of its own and lists what each statement returned. diff --git a/linux/docs/storage.md b/linux/docs/storage.md index d21106bf82..ce4fb3d80f 100644 --- a/linux/docs/storage.md +++ b/linux/docs/storage.md @@ -319,6 +319,10 @@ The schema id is the application id and the path follows it: `app.tablepro.Table | `window-height` | `i` | `760` | 294 to 32767 | | `is-maximized` | `b` | `false` | | | `default-page-size` | `u` | `1000` | 100 to 100000 | +| `show-alternate-rows` | `b` | `true` | | +| `show-row-numbers` | `b` | `true` | | +| `grid-row-height` | `s` | `normal` | compact, normal, comfortable, spacious | +| `null-display` | `s` | `NULL` | Displayed as at most 20 characters, without control characters; blank uses NULL | | `confirm-bulk-delete` | `b` | `true` | | | `restore-session` | `b` | `true` | | | `last-seen-version` | `s` | empty | | @@ -351,7 +355,7 @@ The schema id is the application id and the path follows it: `app.tablepro.Table | `csv-line-break` | enum | `lf` | lf, crlf, cr | | `csv-decimal` | enum | `period` | period, comma | -`tablepro_storage::AppSettings` wraps it in typed accessors: +`tablepro_linux_platform::AppSettings` wraps it in typed accessors: ```rust pub fn open(schema_id: &str) -> Result; diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 7f37312b2d..c7305f6abd 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -490,6 +490,7 @@ crates/app/src/ui/preferences_dialog/data_browser_group.rs crates/app/src/ui/preferences_dialog/device_limit_dialog.rs crates/app/src/ui/preferences_dialog/editor_page.rs crates/app/src/ui/preferences_dialog/general_page.rs +crates/app/src/ui/preferences_dialog/grid_page.rs crates/app/src/ui/preferences_dialog/history_group.rs crates/app/src/ui/preferences_dialog/imp.rs crates/app/src/ui/preferences_dialog/mcp_page.rs @@ -766,6 +767,7 @@ data/resources/ui/preferences-data-browser-group.ui data/resources/ui/preferences-dialog.ui data/resources/ui/preferences-editor-page.ui data/resources/ui/preferences-general-page.ui +data/resources/ui/preferences-grid-page.ui data/resources/ui/preferences-history-group.ui data/resources/ui/preferences-mcp-page.ui data/resources/ui/results-pane.ui From c0da2cff3f543faaabbe21ce76ba914f2e5710fb Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 23:34:33 +0700 Subject: [PATCH 09/18] fix(linux-grid): keep display preferences when resetting columns --- linux/crates/app/src/ui/data_grid/columns.rs | 1 + linux/crates/app/src/ui/data_grid/mod.rs | 3 --- .../crates/app/src/ui/data_grid/tests/layout.rs | 16 ++++++++++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/linux/crates/app/src/ui/data_grid/columns.rs b/linux/crates/app/src/ui/data_grid/columns.rs index e8ab39e933..df2f4c1701 100644 --- a/linux/crates/app/src/ui/data_grid/columns.rs +++ b/linux/crates/app/src/ui/data_grid/columns.rs @@ -194,6 +194,7 @@ impl DataGrid { self.size_unsized_columns(); self.watch_layout_changes(); self.wire_sorting(sorting); + self.apply_display_settings(); } fn build_column(&self, paint: &Rc, sorting: GridSorting) -> gtk::ColumnViewColumn { diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index 9c4f407fba..44213b9528 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -186,15 +186,12 @@ impl DataGrid { self.imp().columns.borrow().columns() } - /// Build the columns for another column set, with what may change in - /// its rows. The rows go, since they were read under the old columns. pub fn set_columns(&self, columns: Arc<[GridColumn]>, sorting: GridSorting, rules: Option) { self.commit_editors(); self.store().clear(); self.imp().summary.forget_column(); self.edit().set_rules(self, rules); self.rebuild_columns(columns, sorting); - self.apply_display_settings(); self.show_rows_or_empty(); self.refresh_actions(); } diff --git a/linux/crates/app/src/ui/data_grid/tests/layout.rs b/linux/crates/app/src/ui/data_grid/tests/layout.rs index 78470730b6..17606d4f34 100644 --- a/linux/crates/app/src/ui/data_grid/tests/layout.rs +++ b/linux/crates/app/src/ui/data_grid/tests/layout.rs @@ -338,3 +338,19 @@ mod real_keys { wait_until(WAIT, || grid.grid.shown_columns() == [0, 1, 2]).expect("the column to move back"); } } + +#[gtk4::test] +fn resetting_the_column_layout_keeps_row_numbers_hidden() { + let grid = Grid::open(two_text_columns(), two_text_values()); + let settings = grid.grid.config().expect("configured grid").settings.clone(); + settings.set_show_row_numbers(false).expect("hide row numbers"); + assert!(!grid.grid.row_numbers_column().expect("row numbers").is_visible()); + + grid.grid.reset_layout(); + + let numbers = grid.grid.row_numbers_column().expect("rebuilt row numbers"); + assert!(!numbers.is_visible()); + assert!(!settings.show_row_numbers()); + settings.set_show_row_numbers(true).expect("show row numbers"); + assert!(numbers.is_visible()); +} From c03b4eb3bcbcc9680fe3c5fdbbcd4fb75ccc3fd9 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 23:39:10 +0700 Subject: [PATCH 10/18] test(linux-grid): load native styles for row height checks --- .../crates/app/src/ui/data_grid/test_grid.rs | 28 +++++++++++++++++-- .../app/src/ui/data_grid/tests/cells.rs | 18 ++++++++---- 2 files changed, 37 insertions(+), 9 deletions(-) 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 5573b1ea11..5925213135 100644 --- a/linux/crates/app/src/ui/data_grid/test_grid.rs +++ b/linux/crates/app/src/ui/data_grid/test_grid.rs @@ -149,7 +149,6 @@ impl GridSpec { } } -/// A grid in a shown window, with the requests it made. pub(crate) struct Grid { pub window: gtk::Window, pub grid: DataGrid, @@ -158,6 +157,28 @@ pub(crate) struct Grid { requests: Rc>>, _settings: MemorySettings, _runtime: AppRuntime, + _style: GridStyle, +} + +struct GridStyle { + display: gtk::gdk::Display, + provider: gtk::CssProvider, +} + +impl GridStyle { + fn new() -> Self { + let display = gtk::gdk::Display::default().expect("test display"); + let provider = gtk::CssProvider::new(); + provider.load_from_resource(&format!("{}/style.css", crate::config::RESOURCE_BASE_PATH)); + gtk::style_context_add_provider_for_display(&display, &provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION); + Self { display, provider } + } +} + +impl Drop for GridStyle { + fn drop(&mut self) { + gtk::style_context_remove_provider_for_display(&self.display, &self.provider); + } } impl Grid { @@ -168,9 +189,9 @@ 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"); + // This fixture has no AdwApplication startup to load its resource stylesheet. + let style = GridStyle::new(); let runtime = crate::test_support::test_runtime(); let settings = MemorySettings::new(); let tracker = TabTrackerHandle::default(); @@ -217,6 +238,7 @@ impl Grid { requests, _settings: settings, _runtime: runtime, + _style: style, }; // A saved layout can hide columns, which draw no cells. let width = opened.grid.shown_columns().len(); diff --git a/linux/crates/app/src/ui/data_grid/tests/cells.rs b/linux/crates/app/src/ui/data_grid/tests/cells.rs index 9c358336ed..0e32c1c01d 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -589,15 +589,21 @@ fn row_height_preferences_change_the_allocated_row_height() { let grid = two_text_rows(); let settings = grid.grid.config().expect("configured grid").settings.clone(); let cell = grid.cell_of(1, 1); - settings.set_grid_row_height("compact").expect("compact height"); crate::test_support::after_next_frame(&grid.grid); let row = row_widget(&cell); wait_until(WAIT, || row.height() > 0).expect("row laid out"); - let compact = row.measure(gtk::Orientation::Vertical, -1).1; + let normal = row.height(); + + settings.set_grid_row_height("compact").expect("compact height"); + wait_until(WAIT, || row.height() < normal).expect("compact rows allocate less height than normal rows"); + let compact = row.height(); settings.set_grid_row_height("spacious").expect("spacious height"); - wait_until(WAIT, || row.measure(gtk::Orientation::Vertical, -1).1 > compact) - .expect("the larger padding makes a taller row"); - let spacious = row.measure(gtk::Orientation::Vertical, -1).1; - wait_until(WAIT, || row.height() >= spacious).expect("row uses its larger height"); + wait_until(WAIT, || row.height() > normal).expect("spacious rows allocate more height than normal rows"); + assert!(row.height() > compact); + + settings.set_grid_row_height("normal").expect("normal height"); + wait_until(WAIT, || row.height() == normal).expect("normal rows restore their original height"); + assert_eq!(row_widget(&cell), row); + assert_eq!(grid.cell_of(1, 1), cell); } From 38801c1aa7f0dfe24f2bfc70ea70279d8870f9e5 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 9 Nov 2026 00:49:25 +0700 Subject: [PATCH 11/18] fix(linux-grid): expose editor state within row details --- linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs b/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs index df1174a1e2..83126e2626 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs @@ -249,7 +249,7 @@ impl RowDetailPane { } } - fn is_editing_value(&self) -> bool { + pub(super) fn is_editing_value(&self) -> bool { self.imp().edit.borrow().is_some() } From f0b307019572c81d6e27cfda848a9220cfd0942f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 9 Nov 2026 01:11:17 +0700 Subject: [PATCH 12/18] test(linux-grid): isolate settings notification contexts --- linux/crates/platform/tests/settings.rs | 135 +++++++++++++++--------- 1 file changed, 85 insertions(+), 50 deletions(-) diff --git a/linux/crates/platform/tests/settings.rs b/linux/crates/platform/tests/settings.rs index 170aa87c07..7036f72749 100644 --- a/linux/crates/platform/tests/settings.rs +++ b/linux/crates/platform/tests/settings.rs @@ -12,6 +12,7 @@ type TestResult = Result<(), Box>; const SCHEMA_ID: &str = "app.tablepro.TablePro"; +// GSettings captures the thread-default context, so every test owns one through glib::async_test. struct Fixture { _dir: tempfile::TempDir, settings: AppSettings, @@ -39,8 +40,8 @@ fn compile_schemas() -> Result> { Ok(dir) } -#[test] -fn defaults_match_schema() -> TestResult { +#[glib::async_test] +async fn defaults_match_schema() -> TestResult { let fixture = Fixture::new()?; assert_eq!(fixture.settings.default_page_size(), 1_000); @@ -61,8 +62,8 @@ fn defaults_match_schema() -> TestResult { Ok(()) } -#[test] -fn usage_data_turns_off_and_on_again() -> TestResult { +#[glib::async_test] +async fn usage_data_turns_off_and_on_again() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_share_usage_data(false)?; @@ -74,8 +75,8 @@ fn usage_data_turns_off_and_on_again() -> TestResult { Ok(()) } -#[test] -fn a_day_of_use_counts_once() -> TestResult { +#[glib::async_test] +async fn a_day_of_use_counts_once() -> TestResult { let fixture = Fixture::new()?; fixture.settings.record_usage_day("2026-11-05")?; @@ -89,8 +90,8 @@ fn a_day_of_use_counts_once() -> TestResult { Ok(()) } -#[test] -fn vim_keybindings_round_trip() -> TestResult { +#[glib::async_test] +async fn vim_keybindings_round_trip() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_vim_keybindings(true)?; @@ -100,8 +101,8 @@ fn vim_keybindings_round_trip() -> TestResult { Ok(()) } -#[test] -fn mcp_server_round_trip_and_port_range() -> TestResult { +#[glib::async_test] +async fn mcp_server_round_trip_and_port_range() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_mcp_server_enabled(true)?; @@ -115,8 +116,8 @@ fn mcp_server_round_trip_and_port_range() -> TestResult { Ok(()) } -#[test] -fn the_assistant_starts_off_and_keeps_each_providers_model() -> TestResult { +#[glib::async_test] +async fn the_assistant_starts_off_and_keeps_each_providers_model() -> TestResult { let fixture = Fixture::new()?; assert_eq!(fixture.settings.ai_provider(), None); assert!(!fixture.settings.ai_inline_suggestions()); @@ -152,8 +153,8 @@ fn the_assistant_starts_off_and_keeps_each_providers_model() -> TestResult { Ok(()) } -#[test] -fn restore_session_round_trip() -> TestResult { +#[glib::async_test] +async fn restore_session_round_trip() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_restore_session(false)?; @@ -162,8 +163,8 @@ fn restore_session_round_trip() -> TestResult { Ok(()) } -#[test] -fn last_seen_version_starts_empty_and_round_trips() -> TestResult { +#[glib::async_test] +async fn last_seen_version_starts_empty_and_round_trips() -> TestResult { let fixture = Fixture::new()?; assert_eq!(fixture.settings.last_seen_version(), ""); @@ -173,8 +174,8 @@ fn last_seen_version_starts_empty_and_round_trips() -> TestResult { Ok(()) } -#[test] -fn confirm_bulk_delete_round_trip() -> TestResult { +#[glib::async_test] +async fn confirm_bulk_delete_round_trip() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_confirm_bulk_delete(false)?; @@ -184,8 +185,8 @@ fn confirm_bulk_delete_round_trip() -> TestResult { Ok(()) } -#[test] -fn show_alternate_rows_round_trip() -> TestResult { +#[glib::async_test] +async fn show_alternate_rows_round_trip() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_show_alternate_rows(false)?; @@ -195,8 +196,8 @@ fn show_alternate_rows_round_trip() -> TestResult { Ok(()) } -#[test] -fn save_query_history_round_trip() -> TestResult { +#[glib::async_test] +async fn save_query_history_round_trip() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_save_query_history(false)?; @@ -205,8 +206,8 @@ fn save_query_history_round_trip() -> TestResult { Ok(()) } -#[test] -fn csv_options_round_trip() -> TestResult { +#[glib::async_test] +async fn csv_options_round_trip() -> TestResult { let fixture = Fixture::new()?; let options = CsvOptions { null_to_empty: false, @@ -225,8 +226,8 @@ fn csv_options_round_trip() -> TestResult { Ok(()) } -#[test] -fn reset_csv_options_restores_defaults() -> TestResult { +#[glib::async_test] +async fn reset_csv_options_restores_defaults() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_csv_options(&CsvOptions { delimiter: CsvDelimiter::Tab, @@ -240,8 +241,8 @@ fn reset_csv_options_restores_defaults() -> TestResult { Ok(()) } -#[test] -fn window_geometry_round_trip() -> TestResult { +#[glib::async_test] +async fn window_geometry_round_trip() -> TestResult { let fixture = Fixture::new()?; let geometry = WindowGeometry { width: 1440, @@ -255,8 +256,8 @@ fn window_geometry_round_trip() -> TestResult { Ok(()) } -#[test] -fn range_rejects_out_of_bounds() -> TestResult { +#[glib::async_test] +async fn range_rejects_out_of_bounds() -> TestResult { let fixture = Fixture::new()?; for (key, result) in [ @@ -278,8 +279,8 @@ fn range_rejects_out_of_bounds() -> TestResult { Ok(()) } -#[test] -fn query_timeout_zero_is_none() -> TestResult { +#[glib::async_test] +async fn query_timeout_zero_is_none() -> TestResult { let fixture = Fixture::new()?; fixture.settings.set_query_timeout_secs(0)?; @@ -288,8 +289,8 @@ fn query_timeout_zero_is_none() -> TestResult { Ok(()) } -#[test] -fn editor_font_defaults_to_system() -> TestResult { +#[glib::async_test] +async fn editor_font_defaults_to_system() -> TestResult { let fixture = Fixture::new()?; assert_eq!(fixture.settings.editor_font(), EditorFont::System); @@ -304,8 +305,8 @@ fn editor_font_defaults_to_system() -> TestResult { Ok(()) } -#[test] -fn missing_schema_is_schema_not_found() -> TestResult { +#[glib::async_test] +async fn missing_schema_is_schema_not_found() -> TestResult { let dir = compile_schemas()?; let result = AppSettings::with_backend("app.tablepro.Absent", dir.path(), &gio::memory_settings_backend_new()); @@ -317,8 +318,8 @@ fn missing_schema_is_schema_not_found() -> TestResult { Ok(()) } -#[test] -fn nonexistent_dir_is_schema_directory() -> TestResult { +#[glib::async_test] +async fn nonexistent_dir_is_schema_directory() -> TestResult { let dir = tempfile::tempdir()?; let missing = dir.path().join("absent"); @@ -331,8 +332,8 @@ fn nonexistent_dir_is_schema_directory() -> TestResult { Ok(()) } -#[test] -fn grid_preferences_start_from_schema_and_keep_one_model() -> TestResult { +#[glib::async_test] +async fn grid_preferences_start_from_schema_and_keep_one_model() -> TestResult { use tablepro_linux_platform::settings::{GridPreferenceValues, GridPreferences}; let fixture = Fixture::new()?; @@ -343,8 +344,8 @@ fn grid_preferences_start_from_schema_and_keep_one_model() -> TestResult { Ok(()) } -#[test] -fn every_grid_preference_observer_reads_the_updated_snapshot() -> TestResult { +#[glib::async_test] +async fn every_grid_preference_observer_reads_the_updated_snapshot() -> TestResult { use std::cell::RefCell; use std::rc::Rc; @@ -377,8 +378,8 @@ fn every_grid_preference_observer_reads_the_updated_snapshot() -> TestResult { Ok(()) } -#[test] -fn grid_preference_backends_stay_independent() -> TestResult { +#[glib::async_test] +async fn grid_preference_backends_stay_independent() -> TestResult { let first = Fixture::new()?; let second = Fixture::new()?; let first_preferences = first.settings.grid_preferences(); @@ -394,8 +395,8 @@ fn grid_preference_backends_stay_independent() -> TestResult { Ok(()) } -#[test] -fn null_display_is_bounded_even_for_external_settings_writes() -> TestResult { +#[glib::async_test] +async fn null_display_is_bounded_even_for_external_settings_writes() -> TestResult { use gio::prelude::SettingsExt; let fixture = Fixture::new()?; @@ -414,8 +415,8 @@ fn null_display_is_bounded_even_for_external_settings_writes() -> TestResult { Ok(()) } -#[test] -fn grid_preference_changes_ignore_unrelated_and_equivalent_values() -> TestResult { +#[glib::async_test] +async fn grid_preference_changes_ignore_unrelated_and_equivalent_values() -> TestResult { use std::cell::Cell; use std::rc::Rc; @@ -437,8 +438,8 @@ fn grid_preference_changes_ignore_unrelated_and_equivalent_values() -> TestResul Ok(()) } -#[test] -fn dropping_grid_preferences_disconnects_the_settings_handler() -> TestResult { +#[glib::async_test] +async fn dropping_grid_preferences_disconnects_the_settings_handler() -> TestResult { use gio::prelude::*; let fixture = Fixture::new()?; @@ -458,3 +459,37 @@ fn dropping_grid_preferences_disconnects_the_settings_handler() -> TestResult { settings.set_boolean(keys::SHOW_ROW_NUMBERS, false)?; Ok(()) } + +#[glib::async_test] +async fn settings_observers_run_while_another_thread_owns_the_global_context() -> TestResult { + use std::cell::Cell; + use std::rc::Rc; + use std::sync::mpsc; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + let calls = Rc::new(Cell::new(0)); + let observed = calls.clone(); + preferences.connect_changed(move |_| observed.set(observed.get() + 1)); + + let (ready, started) = mpsc::sync_channel(0); + let (release, released) = mpsc::channel(); + let owner = std::thread::spawn(move || { + let context = glib::MainContext::default(); + let _guard = context.acquire().expect("only this worker uses the global context"); + ready.send(()).expect("the test waits for context ownership"); + let _ = released.recv(); + }); + started.recv()?; + + let changed = fixture.settings.set_show_row_numbers(false); + let notifications = calls.get(); + let snapshot = preferences.snapshot(); + drop(release); + owner.join().expect("the context owner exits"); + changed?; + + assert_eq!(notifications, 1); + assert!(!snapshot.show_row_numbers); + Ok(()) +} From 65b6a7ffd406e02fd20aa0d747a42a2552f5c8e0 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 9 Nov 2026 02:19:53 +0700 Subject: [PATCH 13/18] fix(linux-grid): type the settings test shutdown channel --- linux/crates/platform/tests/settings.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linux/crates/platform/tests/settings.rs b/linux/crates/platform/tests/settings.rs index 7036f72749..8840f0316f 100644 --- a/linux/crates/platform/tests/settings.rs +++ b/linux/crates/platform/tests/settings.rs @@ -473,7 +473,7 @@ async fn settings_observers_run_while_another_thread_owns_the_global_context() - preferences.connect_changed(move |_| observed.set(observed.get() + 1)); let (ready, started) = mpsc::sync_channel(0); - let (release, released) = mpsc::channel(); + let (release, released) = mpsc::channel::<()>(); let owner = std::thread::spawn(move || { let context = glib::MainContext::default(); let _guard = context.acquire().expect("only this worker uses the global context"); From 068db6828fcf215e538ab577715640006212c55e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 9 Nov 2026 04:35:50 +0700 Subject: [PATCH 14/18] test(linux-grid): assert copied JSON without unordered maps --- linux/crates/app/src/ui/data_grid/copy/tests.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/linux/crates/app/src/ui/data_grid/copy/tests.rs b/linux/crates/app/src/ui/data_grid/copy/tests.rs index f4fe2e6737..0178c743c0 100644 --- a/linux/crates/app/src/ui/data_grid/copy/tests.rs +++ b/linux/crates/app/src/ui/data_grid/copy/tests.rs @@ -25,6 +25,7 @@ use crate::ui::data_grid::{DataGrid, GridCell, GridRequest}; use crate::ui::export::ExportSource; const BEFORE: &str = "nothing copied yet"; +const TWO_TEXT_ROWS_JSON: &str = "[\n{\"id\":1,\"name\":\"A\"},\n{\"id\":2,\"name\":\"B\"}\n]"; /// What a copy test drives: a grid and the requests it made. trait Copies { @@ -747,10 +748,7 @@ fn copy_writes_several_rows_in_the_preferred_format() { RowCopyFormat::Csv => assert_eq!(text, "1,A\n2,B\n"), RowCopyFormat::CsvWithHeaders => assert_eq!(text, "id,name\n1,A\n2,B\n"), RowCopyFormat::Markdown => assert_eq!(text, "| id | name |\n| --- | --- |\n| 1 | A |\n| 2 | B |"), - RowCopyFormat::Json => assert_eq!( - serde_json::from_str::(&text).expect("JSON rows"), - serde_json::json!([{"id": 1, "name": "A"}, {"id": 2, "name": "B"}]), - ), + RowCopyFormat::Json => assert_eq!(text, TWO_TEXT_ROWS_JSON), } } } @@ -775,8 +773,5 @@ fn preferred_row_format_preserves_single_cell_copy_and_explicit_formats() { "id,name\n1,A\n2,B\n" ); let text = copied(&grid, || activate(&grid.grid, "copy")); - assert_eq!( - serde_json::from_str::(&text).expect("JSON rows"), - serde_json::json!([{"id": 1, "name": "A"}, {"id": 2, "name": "B"}]), - ); + assert_eq!(text, TWO_TEXT_ROWS_JSON); } From 41df39fb6fdc4a58f34daac1e862cfaae7d23e9f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 9 Nov 2026 21:16:42 +0700 Subject: [PATCH 15/18] fix(linux-grid): pass the NULL text to the row details search --- linux/crates/app/src/ui/data_grid/row_detail/fields.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/linux/crates/app/src/ui/data_grid/row_detail/fields.rs b/linux/crates/app/src/ui/data_grid/row_detail/fields.rs index ce300f2e15..b06cfdb1c5 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/fields.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/fields.rs @@ -328,7 +328,11 @@ impl RowDetailPane { if wanted.is_empty() || column.name.to_lowercase().contains(&wanted) { return true; } - let value = field_value(&grid.tracked(), &row, &column); + let Some(config) = grid.config() else { + return false; + }; + let preferences = config.settings.grid_preferences().snapshot(); + let value = field_value(&grid.tracked(), &row, &column, &preferences.null_display); !value.null && value.text.to_lowercase().contains(&wanted) } From 48409b112fcda8abc78fd8bdf800c9b2f9dbf5a4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 10 Nov 2026 03:03:16 +0700 Subject: [PATCH 16/18] test(linux-grid): box the browse command the default sort test sends --- .../src/ui/browse_tab/tests/default_sort.rs | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/linux/crates/app/src/ui/browse_tab/tests/default_sort.rs b/linux/crates/app/src/ui/browse_tab/tests/default_sort.rs index b3bda8cf62..1c407f87af 100644 --- a/linux/crates/app/src/ui/browse_tab/tests/default_sort.rs +++ b/linux/crates/app/src/ui/browse_tab/tests/default_sort.rs @@ -163,10 +163,12 @@ fn stale_metadata_cannot_consume_the_pending_default() { columns: vec!["id".into()], }, }; - harness.tab().send(DataInput::Command(BrowseCommand::Columns(Stamped { - stamp: stale.stamp, - value: Ok(reply()), - }))); + harness + .tab() + .send(DataInput::Command(Box::new(BrowseCommand::Columns(Stamped { + stamp: stale.stamp, + value: Ok(reply()), + })))); assert_eq!(harness.tab().current_sort(), None); assert!( harness @@ -179,10 +181,12 @@ fn stale_metadata_cannot_consume_the_pending_default() { .default_sort .is_some() ); - harness.tab().send(DataInput::Command(BrowseCommand::Columns(Stamped { - stamp: current.stamp, - value: Err(LoadFailure::NoColumns), - }))); + harness + .tab() + .send(DataInput::Command(Box::new(BrowseCommand::Columns(Stamped { + stamp: current.stamp, + value: Err(LoadFailure::NoColumns), + })))); assert!( harness .tab() @@ -203,10 +207,12 @@ fn stale_metadata_cannot_consume_the_pending_default() { .expect("model") .sequencer .issue(BrowseRequestKind::Columns); - harness.tab().send(DataInput::Command(BrowseCommand::Columns(Stamped { - stamp: retry.stamp, - value: Ok(reply()), - }))); + harness + .tab() + .send(DataInput::Command(Box::new(BrowseCommand::Columns(Stamped { + stamp: retry.stamp, + value: Ok(reply()), + })))); assert_eq!(harness.tab().current_sort(), Some((0, false))); assert!( harness From f2415357114e1d1fde78c42eb4cc1a06dd3a22c3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 10 Nov 2026 04:25:34 +0700 Subject: [PATCH 17/18] feat(linux-grid): mark zero-width, control and special space characters in cells and value fields --- linux/changelog.d/4141.added.md | 2 +- linux/crates/app/src/services/grid/mod.rs | 1 + .../src/services/grid/special_characters.rs | 380 ++++++++++++++++++ .../app/src/ui/data_grid/display_settings.rs | 18 +- .../app/src/ui/data_grid/edit/cell_editor.rs | 9 +- .../crates/app/src/ui/data_grid/grid_cell.rs | 10 +- linux/crates/app/src/ui/data_grid/imp.rs | 1 + linux/crates/app/src/ui/data_grid/mod.rs | 1 + .../app/src/ui/data_grid/row_detail/fields.rs | 9 +- .../src/ui/data_grid/row_detail/invisibles.rs | 16 +- .../app/src/ui/data_grid/row_detail/tests.rs | 126 +++--- .../ui/data_grid/row_detail/value_editor.rs | 1 + .../app/src/ui/data_grid/special_marks.rs | 148 +++++++ .../app/src/ui/data_grid/tests/cells.rs | 70 ++++ .../preferences_dialog/data_browser_group.rs | 2 +- linux/crates/platform/tests/settings.rs | 2 +- .../data/app.tablepro.TablePro.gschema.xml.in | 4 +- .../ui/preferences-data-browser-group.ui | 4 +- linux/docs/state-management.md | 2 +- linux/po/POTFILES.in | 2 + 20 files changed, 704 insertions(+), 104 deletions(-) create mode 100644 linux/crates/app/src/services/grid/special_characters.rs create mode 100644 linux/crates/app/src/ui/data_grid/special_marks.rs diff --git a/linux/changelog.d/4141.added.md b/linux/changelog.d/4141.added.md index b00c792ac2..5442bf177d 100644 --- a/linux/changelog.d/4141.added.md +++ b/linux/changelog.d/4141.added.md @@ -1 +1 @@ -The row details value editor marks spaces, tabs and line breaks, which a Preferences switch turns off. +Cells and value fields mark zero-width, control and special space characters, which Preferences can turn off. diff --git a/linux/crates/app/src/services/grid/mod.rs b/linux/crates/app/src/services/grid/mod.rs index ba31b78469..bb5763a016 100644 --- a/linux/crates/app/src/services/grid/mod.rs +++ b/linux/crates/app/src/services/grid/mod.rs @@ -22,6 +22,7 @@ mod result_refusal; mod row_key_builder; mod row_snapshot; mod selection_summary; +pub mod special_characters; #[cfg(test)] mod test_columns; diff --git a/linux/crates/app/src/services/grid/special_characters.rs b/linux/crates/app/src/services/grid/special_characters.rs new file mode 100644 index 0000000000..e351b49097 --- /dev/null +++ b/linux/crates/app/src/services/grid/special_characters.rs @@ -0,0 +1,380 @@ +use std::borrow::Cow; +use std::ops::Range; + +// The macOS app's cap per line: past it a value of control bytes would draw one mark each. +pub const MAX_MARKS: usize = 4_096; + +const EMOJI_TAG_BASE: u32 = 0x1F3F4; + +const C0_LABELS: [&str; 32] = [ + "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", + "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US", +]; + +const C1_LABELS: [&str; 32] = [ + "PAD", "HOP", "BPH", "NBH", "IND", "NEL", "SSA", "ESA", "HTS", "HTJ", "VTS", "PLD", "PLU", "RI", "SS2", "SS3", + "DCS", "PU1", "PU2", "STS", "CCH", "MW", "SPA", "EPA", "SOS", "SGC", "SCI", "CSI", "ST", "OSC", "PM", "APC", +]; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SpecialCharacter { + /// Drawn as its short name, since it has no width or no glyph of its own. + Marker(Cow<'static, str>), + /// A space other than U+0020, drawn at its own width. + BlankSpace, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Classified { + /// Bytes of the text the character takes. + pub range: Range, + pub character: SpecialCharacter, +} + +/// The zero-width, control and special space characters of `text`, as the +/// macOS app's "Show invisible characters" marks them. `line_breaks` is for +/// a one-line view, which draws no break for LF or CR. +pub fn special_characters(text: &str, line_breaks: bool) -> SpecialCharacters<'_> { + SpecialCharacters { + text, + chars: text.char_indices(), + line_breaks, + tag_sequence: false, + found: 0, + } +} + +pub struct SpecialCharacters<'a> { + text: &'a str, + chars: std::str::CharIndices<'a>, + line_breaks: bool, + // Whether the characters so far end in an emoji tag sequence's base and tags. + tag_sequence: bool, + found: usize, +} + +impl Iterator for SpecialCharacters<'_> { + type Item = Classified; + + fn next(&mut self) -> Option { + while self.found < MAX_MARKS { + let (index, character) = self.chars.next()?; + let in_tag_sequence = self.tag_sequence; + let value = u32::from(character); + self.tag_sequence = value == EMOJI_TAG_BASE || (is_tag(value) && in_tag_sequence); + let end = index + character.len_utf8(); + let Some(kind) = self.classify(value, index..end, in_tag_sequence) else { + continue; + }; + self.found += 1; + return Some(Classified { + range: index..end, + character: kind, + }); + } + None + } +} + +impl SpecialCharacters<'_> { + fn classify(&self, value: u32, range: Range, in_tag_sequence: bool) -> Option { + let marker = |label| Some(SpecialCharacter::Marker(label)); + match value { + 0x0A | 0x0D if self.line_breaks => marker(control_label(value)), + 0x09 | 0x0A | 0x0D => None, + 0x00..=0x1F | 0x7F..=0x9F => marker(control_label(value)), + 0x2028 | 0x2029 | 0xFFF9..=0xFFFB => marker(label(value)), + 0x00A0 | 0x1680 | 0x2000..=0x200A | 0x202F | 0x205F | 0x3000 => Some(SpecialCharacter::BlankSpace), + _ if is_default_ignorable(value) && !self.is_exempt(value, range, in_tag_sequence) => marker(label(value)), + _ => None, + } + } + + // Each of these shapes the characters around it, as a joiner inside an + // emoji or a variation selector does, so marking it would break what the + // reader sees. + fn is_exempt(&self, value: u32, range: Range, in_tag_sequence: bool) -> bool { + match value { + 0x034F | 0x115F | 0x1160 | 0x17B4 | 0x17B5 | 0x180B..=0x180D | 0x180F => true, + 0xFE00..=0xFE0F | 0xE0100..=0xE01EF => true, + 0x200C | 0x200D => self.joins_non_ascii(range), + _ if is_tag(value) => in_tag_sequence, + _ => false, + } + } + + fn joins_non_ascii(&self, range: Range) -> bool { + let before = self.text[..range.start].chars().next_back(); + let after = self.text[range.end..].chars().next(); + before.into_iter().chain(after).any(|neighbour| !neighbour.is_ascii()) + } +} + +fn is_tag(value: u32) -> bool { + (0xE0020..=0xE007F).contains(&value) +} + +fn is_default_ignorable(value: u32) -> bool { + matches!( + value, + 0x00AD + | 0x034F + | 0x061C + | 0x115F..=0x1160 + | 0x17B4..=0x17B5 + | 0x180B..=0x180F + | 0x200B..=0x200F + | 0x202A..=0x202E + | 0x2060..=0x206F + | 0x3164 + | 0xFE00..=0xFE0F + | 0xFEFF + | 0xFFA0 + | 0xFFF0..=0xFFF8 + | 0x1BCA0..=0x1BCA3 + | 0x1D173..=0x1D17A + | 0xE0000..=0xE0FFF + ) +} + +fn control_label(value: u32) -> Cow<'static, str> { + let named = match value { + 0x00..=0x1F => usize::try_from(value).ok().and_then(|index| C0_LABELS.get(index)), + 0x7F => Some(&"DEL"), + 0x80..=0x9F => usize::try_from(value - 0x80) + .ok() + .and_then(|index| C1_LABELS.get(index)), + _ => None, + }; + named.map_or_else(|| hex_label(value), |label| Cow::Borrowed(*label)) +} + +fn label(value: u32) -> Cow<'static, str> { + let named = match value { + 0x00AD => "SHY", + 0x061C => "ALM", + 0x180E => "MVS", + 0x200B => "ZWSP", + 0x200C => "ZWNJ", + 0x200D => "ZWJ", + 0x200E => "LRM", + 0x200F => "RLM", + 0x2028 => "LSEP", + 0x2029 => "PSEP", + 0x202A => "LRE", + 0x202B => "RLE", + 0x202C => "PDF", + 0x202D => "LRO", + 0x202E => "RLO", + 0x2060 => "WJ", + 0x2066 => "LRI", + 0x2067 => "RLI", + 0x2068 => "FSI", + 0x2069 => "PDI", + 0x206A => "ISS", + 0x206B => "ASS", + 0x206C => "IAFS", + 0x206D => "AAFS", + 0x206E => "NADS", + 0x206F => "NODS", + 0xFEFF => "BOM", + 0xFFF9 => "IAA", + 0xFFFA => "IAS", + 0xFFFB => "IAT", + _ => return hex_label(value), + }; + Cow::Borrowed(named) +} + +fn hex_label(value: u32) -> Cow<'static, str> { + Cow::Owned(format!("{value:04X}")) +} + +/// A one-line view's text with each special character written as its mark. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Revealed { + pub text: String, + pub marks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Mark { + /// Bytes of the revealed text the mark takes. + pub range: Range, + pub labelled: bool, +} + +/// `None` when `text` holds nothing to mark, so a plain value costs no copy. +pub fn reveal(text: &str) -> Option { + let mut found = special_characters(text, true).peekable(); + found.peek()?; + let mut shown = String::with_capacity(text.len() + 8); + let mut marks = Vec::new(); + let mut copied = 0; + for Classified { range, character } in found { + shown.push_str(&text[copied..range.start]); + let start = shown.len(); + let labelled = match character { + SpecialCharacter::Marker(label) => { + shown.push_str(&label); + true + } + SpecialCharacter::BlankSpace => { + shown.push_str(&text[range.clone()]); + false + } + }; + marks.push(Mark { + range: start..shown.len(), + labelled, + }); + copied = range.end; + } + shown.push_str(&text[copied..]); + Some(Revealed { text: shown, marks }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn marked(text: &str, line_breaks: bool) -> Vec<(Range, SpecialCharacter)> { + special_characters(text, line_breaks) + .map(|found| (found.range, found.character)) + .collect() + } + + fn marker(label: &str) -> SpecialCharacter { + SpecialCharacter::Marker(Cow::Owned(label.to_owned())) + } + + #[test] + fn plain_text_spaces_and_tabs_are_not_marked() { + assert!(marked("plain text\twith a tab", true).is_empty()); + assert!(marked("ünïcödé 日本語", true).is_empty()); + assert_eq!(reveal("plain text"), None); + } + + #[test] + fn line_breaks_are_marked_only_in_a_one_line_view() { + assert!(marked("one\ntwo\r\n", false).is_empty()); + assert_eq!( + marked("one\ntwo\r\n", true), + [(3..4, marker("LF")), (7..8, marker("CR")), (8..9, marker("LF"))] + ); + } + + #[test] + fn controls_take_their_names() { + assert_eq!( + marked("\u{1}\u{1b}\u{7f}\u{85}\u{9f}", false), + [ + (0..1, marker("SOH")), + (1..2, marker("ESC")), + (2..3, marker("DEL")), + (3..5, marker("NEL")), + (5..7, marker("APC")), + ] + ); + } + + #[test] + fn special_spaces_keep_their_width() { + for space in [ + '\u{a0}', '\u{1680}', '\u{2000}', '\u{2007}', '\u{200a}', '\u{202f}', '\u{205f}', '\u{3000}', + ] { + let text = format!("a{space}b"); + assert_eq!( + marked(&text, false), + [(1..1 + space.len_utf8(), SpecialCharacter::BlankSpace)], + "U+{:04X}", + u32::from(space) + ); + } + } + + #[test] + fn format_characters_take_their_short_names() { + let cases = [ + ('\u{ad}', "SHY"), + ('\u{200b}', "ZWSP"), + ('\u{200e}', "LRM"), + ('\u{2028}', "LSEP"), + ('\u{2029}', "PSEP"), + ('\u{202e}', "RLO"), + ('\u{2060}', "WJ"), + ('\u{2066}', "LRI"), + ('\u{feff}', "BOM"), + ('\u{fff9}', "IAA"), + ('\u{3164}', "3164"), + ('\u{2061}', "2061"), + ('\u{1d173}', "1D173"), + ('\u{e0001}', "E0001"), + ]; + for (character, label) in cases { + let text = format!("x{character}y"); + assert_eq!( + marked(&text, false), + [(1..1 + character.len_utf8(), marker(label))], + "U+{:04X}", + u32::from(character) + ); + } + } + + #[test] + fn joiners_inside_non_ascii_text_are_left_alone() { + assert!(marked("👨\u{200d}👩", false).is_empty()); + assert!(marked("क\u{200c}ष", false).is_empty()); + assert_eq!(marked("a\u{200d}b", false), [(1..4, marker("ZWJ"))]); + assert_eq!(marked("\u{200c}", false), [(0..3, marker("ZWNJ"))]); + } + + #[test] + fn shaping_selectors_and_combining_ignorables_are_left_alone() { + assert!(marked("✌\u{fe0f}", false).is_empty()); + assert!(marked("a\u{e0100}", false).is_empty()); + assert!(marked("e\u{34f}\u{180b}\u{17b4}\u{115f}", false).is_empty()); + } + + #[test] + fn tags_mark_only_outside_an_emoji_tag_sequence() { + let flag = "\u{1f3f4}\u{e0067}\u{e0062}\u{e0073}\u{e0063}\u{e0074}\u{e007f}"; + assert!(marked(flag, false).is_empty()); + assert_eq!(marked("a\u{e0067}", false), [(1..5, marker("E0067"))]); + let broken = format!("{flag}x\u{e0067}"); + assert_eq!( + marked(&broken, false), + [(broken.len() - 4..broken.len(), marker("E0067"))] + ); + } + + #[test] + fn marks_stop_at_the_cap() { + let text = "\u{1}".repeat(MAX_MARKS + 10); + assert_eq!(special_characters(&text, false).count(), MAX_MARKS); + } + + #[test] + fn reveal_writes_labels_and_keeps_special_spaces() { + let revealed = reveal("a\u{200b}b\u{a0}c\nd").expect("marks"); + assert_eq!(revealed.text, "aZWSPb\u{a0}cLFd"); + assert_eq!( + revealed.marks, + [ + Mark { + range: 1..5, + labelled: true + }, + Mark { + range: 6..8, + labelled: false + }, + Mark { + range: 9..11, + labelled: true + }, + ] + ); + } +} diff --git a/linux/crates/app/src/ui/data_grid/display_settings.rs b/linux/crates/app/src/ui/data_grid/display_settings.rs index 097896fd54..5e31867cac 100644 --- a/linux/crates/app/src/ui/data_grid/display_settings.rs +++ b/linux/crates/app/src/ui/data_grid/display_settings.rs @@ -40,15 +40,20 @@ impl DataGrid { set_class(&view, height.css_class(), height == values.row_height); } set_class(&view, "tp-striped", values.show_alternate_rows); - self.imp() - .detail_pane - .apply_invisibles(values.show_invisible_characters); if let Some(numbers) = self.row_numbers_column() { numbers.set_visible(values.show_row_numbers); super::pinned_numbers::sync(self); } + let marks = values.show_invisible_characters; + let marks_changed = self.imp().applied_marks.replace(Some(marks)) != Some(marks); + if marks_changed { + self.imp().detail_pane.mark_special_characters(); + if let Some(field) = self.edit().open_text() { + super::special_marks::mark_field(&field, marks); + } + } let changed = self.imp().applied_null.borrow().as_deref() != Some(&values.null_display); - if changed { + if changed || marks_changed { self.imp().applied_null.replace(Some(values.null_display.clone())); self.redraw(); } @@ -56,4 +61,9 @@ impl DataGrid { self.fonts_changed(); } } + + pub(crate) fn marks_special_characters(&self) -> bool { + self.config() + .is_some_and(|config| config.settings.grid_preferences().snapshot().show_invisible_characters) + } } 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 0c1aaec229..32793d0108 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 @@ -13,6 +13,7 @@ use crate::services::grid::{ empty_placeholder, next_edit_target, opening_text, }; use crate::ui::data_grid::grid_cell::holds_window_focus; +use crate::ui::data_grid::special_marks::mark_field; use crate::ui::data_grid::{DataGrid, GridCell, GridRow, PinnedRow}; use crate::ui::error_text::edit_parse_message; @@ -335,6 +336,7 @@ impl EditController { commit_when_composed: Cell::new(false), }))); connect(grid, &text, id); + mark_field(&text, grid.marks_special_characters()); text.grab_focus(); if opened == Opened::ToEdit { text.select_region(0, -1); @@ -552,7 +554,6 @@ impl EditController { } } - #[cfg(test)] pub(crate) fn open_text(&self) -> Option { self.open.borrow().as_ref().map(|edit| edit.text.clone()) } @@ -572,7 +573,11 @@ fn connect(grid: &DataGrid, text: >k::Text, id: u64) { grid.edit().on_activate(id); } }); - text.connect_changed(|text| text.remove_css_class("error")); + let weak = grid.downgrade(); + text.connect_changed(move |text| { + text.remove_css_class("error"); + mark_field(text, weak.upgrade().is_some_and(|grid| grid.marks_special_characters())); + }); // Capture phase, so Escape cancels before the GtkText takes it to // clear its own buffer, and Tab commits before the window moves the // focus. 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 5fc03a2827..da6ac988f1 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -7,6 +7,7 @@ use gtk4::{self as gtk, glib, pango}; use tablepro_core::Value; use super::columns::ColumnPaint; +use super::special_marks::show_value; use super::tracked_values::cell_description; use super::{DataGrid, GridRow, ServerValue}; use crate::services::change_tracker::CellState; @@ -312,11 +313,16 @@ impl GridCell { (false, CellState::Modified) => TextMark::Modified, (false, _) => TextMark::Plain, }; + let marks = paint.preferences.snapshot().show_invisible_characters; let null = paint.tracked.with_value(&row, column, |value, computed| { let mut scratch = self.imp().scratch.borrow_mut(); let shown = shown_text(&paint, value, computed, lock.is_none(), &mut scratch); - display.set_text(Some(shown.text)); - display.set_attributes(paint.attributes.for_text(text_mark, shown.placeholder)); + show_value( + display, + shown.text, + paint.attributes.for_text(text_mark, shown.placeholder), + marks && !shown.placeholder, + ); set_class( display, "dimmed", diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index 057a92f85e..d910f0fe9b 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -94,6 +94,7 @@ pub struct DataGrid { pub focus_watch: RefCell, glib::SignalHandlerId)>>, pub(super) font_watch: RefCell>, pub(super) display_watch: RefCell>, + pub(super) applied_marks: Cell>, pub(super) applied_null: RefCell>, pub(super) cell_font: RefCell>, } diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index 0b664e0d0d..bc8dc3507d 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -29,6 +29,7 @@ mod row_number_column; mod selection; mod selection_summary; mod server_sorter; +mod special_marks; mod stripes; mod table_keys; #[cfg(test)] diff --git a/linux/crates/app/src/ui/data_grid/row_detail/fields.rs b/linux/crates/app/src/ui/data_grid/row_detail/fields.rs index b06cfdb1c5..18261242c3 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/fields.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/fields.rs @@ -9,6 +9,7 @@ use super::RowDetailPane; use crate::i18n::gettext; use crate::services::change_tracker::CellState; use crate::services::grid::{GridColumn, auto_filled_sentinel, display_text}; +use crate::ui::data_grid::special_marks::show_value; use crate::ui::data_grid::tracked_values::cell_description; use crate::ui::data_grid::{DataGrid, GridRow, ServerValue, TrackedValues}; use crate::ui::handler_guard::HandlerGuard; @@ -371,8 +372,12 @@ impl RowDetailPane { let preferences = config.settings.grid_preferences().snapshot(); let value = field_value(&grid.tracked(), &row, &column, &preferences.null_display); edited.set_visible(value.modified); - shown.set_text(Some(&value.text)); - shown.set_attributes(Some(&value_attributes(&value))); + show_value( + &shown, + &value.text, + Some(&value_attributes(&value)), + preferences.show_invisible_characters && !value.placeholder, + ); set_class(&shown, "dimmed", value.placeholder || value.deleted); // Adwaita's own warning colour beside the bold, as the grid's // cells mark a pending value. diff --git a/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs b/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs index 7e3114bac5..8c544e8eb4 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs @@ -1,18 +1,12 @@ +use gtk4::prelude::*; use gtk4::subclass::prelude::*; -use sourceview5::prelude::*; use super::RowDetailPane; +use crate::ui::data_grid::special_marks::mark_buffer; impl RowDetailPane { - pub(in crate::ui::data_grid) fn apply_invisibles(&self, show: bool) { - let drawer = self.imp().value_view.space_drawer(); - drawer.set_types_for_locations( - sourceview5::SpaceLocationFlags::ALL, - sourceview5::SpaceTypeFlags::SPACE - | sourceview5::SpaceTypeFlags::TAB - | sourceview5::SpaceTypeFlags::NEWLINE - | sourceview5::SpaceTypeFlags::NBSP, - ); - drawer.set_enable_matrix(show); + pub(in crate::ui::data_grid) fn mark_special_characters(&self) { + let marks = self.grid().is_some_and(|grid| grid.marks_special_characters()); + mark_buffer(self.imp().value_buffer.upcast_ref(), marks); } } diff --git a/linux/crates/app/src/ui/data_grid/row_detail/tests.rs b/linux/crates/app/src/ui/data_grid/row_detail/tests.rs index daf30d69a4..80f96fb3b4 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/tests.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/tests.rs @@ -1542,34 +1542,43 @@ fn a_page_that_takes_the_row_closes_its_clock_and_writes_nothing() { assert!(!pane.imp().clock_popover.is_visible()); } -#[gtk4::test] -fn the_value_editor_marks_whitespace_only_when_preferences_ask() { - use sourceview5::prelude::*; +fn tagged(pane: &RowDetailPane) -> Vec<(i32, i32)> { + crate::ui::data_grid::special_marks::tagged_ranges(pane.imp().value_buffer.upcast_ref()) +} - let (grid, pane) = opened(two_text_columns(), two_text_values()); +fn field_texts(pane: &RowDetailPane) -> Vec { + descendants(&pane.imp().field_list.get()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .filter_map(|inscription| inscription.text().map(|text| text.to_string())) + .collect() +} + +#[gtk4::test] +fn the_value_editor_marks_invisible_characters_while_preferences_ask() { + let value = "a\u{200b}b c\td\u{a0}e\u{1}"; + let (grid, pane) = opened(two_text_columns(), vec![vec![Value::Int(1), Value::Text(value.into())]]); + grid.focus(0, 1); + drain_main_context(); let settings = grid.grid.config().expect("a configured grid").settings.clone(); - let drawer = pane.imp().value_view.space_drawer(); - - assert!(drawer.enables_matrix(), "marks are on by default"); - let types = sourceview5::SpaceTypeFlags::SPACE - | sourceview5::SpaceTypeFlags::TAB - | sourceview5::SpaceTypeFlags::NEWLINE - | sourceview5::SpaceTypeFlags::NBSP; - for location in [ - sourceview5::SpaceLocationFlags::LEADING, - sourceview5::SpaceLocationFlags::INSIDE_TEXT, - sourceview5::SpaceLocationFlags::TRAILING, - ] { - assert_eq!(drawer.types_for_locations(location), types); - } + + assert_eq!(pane.typed_text(), value); + assert_eq!( + tagged(&pane), + [(1, 2), (7, 8), (9, 10)], + "a space and a tab are not marked" + ); + assert!(field_texts(&pane).contains(&"aZWSPb c\td\u{a0}eSOH".to_owned())); settings.set_show_invisible_characters(false).expect("store the flag"); drain_main_context(); - assert!(!drawer.enables_matrix()); + assert!(tagged(&pane).is_empty()); + assert!(field_texts(&pane).contains(&value.to_owned())); + assert_eq!(pane.typed_text(), value); settings.set_show_invisible_characters(true).expect("store the flag"); drain_main_context(); - assert!(drawer.enables_matrix()); + assert_eq!(tagged(&pane), [(1, 2), (7, 8), (9, 10)]); } #[gtk4::test] @@ -1889,65 +1898,38 @@ fn changing_automatic_details_opening_keeps_an_active_value_draft() { } #[gtk4::test] -fn whitespace_preferences_reach_closed_panes_and_keep_settings_isolated() { - use sourceview5::prelude::*; - +fn a_closed_pane_marks_its_value_once_it_opens() { let settings = crate::test_support::MemorySettings::new(); settings .get() .set_show_invisible_characters(false) .expect("start without marks"); - let shared_grid = || { - Grid::build( - GridSpec { - settings: Some(settings.get().clone()), - ..GridSpec::table(two_text_columns()) - }, - page(1..3), - ) - }; - let first = shared_grid(); - let second = shared_grid(); - let isolated = Grid::open(two_text_columns(), two_text_values()); - let first_pane = pane_of(&first); - let second_pane = pane_of(&second); - let isolated_pane = pane_of(&isolated); - let first_drawer = first_pane.imp().value_view.space_drawer(); - let second_drawer = second_pane.imp().value_view.space_drawer(); - assert!(!first_pane.is_open()); - assert!(!second_pane.is_open()); - assert!(!first_drawer.enables_matrix()); - assert!(!second_drawer.enables_matrix()); - assert!(isolated_pane.imp().value_view.space_drawer().enables_matrix()); + let grid = Grid::build( + GridSpec { + settings: Some(settings.get().clone()), + ..GridSpec::table(two_text_columns()) + }, + persisted(&[vec![Value::Int(1), Value::Text("a\u{200b}b".into())]]), + ); + let pane = pane_of(&grid); + settings.get().set_show_invisible_characters(true).expect("show marks"); + drain_main_context(); + assert!(!pane.is_open()); - settings - .get() - .set_show_invisible_characters(true) - .expect("show marks in both grids"); + grid.activate("show-details"); + grid.focus(0, 1); drain_main_context(); - assert!(first_drawer.enables_matrix()); - assert!(second_drawer.enables_matrix()); - assert!(!first_pane.is_open()); - assert!(!second_pane.is_open()); - settings - .get() - .set_show_invisible_characters(false) - .expect("hide marks in both grids"); - first.activate("show-details"); - second.activate("show-details"); - assert!(!first_drawer.enables_matrix()); - assert!(!second_drawer.enables_matrix()); - assert!(isolated_pane.imp().value_view.space_drawer().enables_matrix()); + assert_eq!(pane.typed_text(), "a\u{200b}b"); + assert_eq!(tagged(&pane), [(1, 2)]); + assert!(field_texts(&pane).contains(&"aZWSPb".to_owned())); } #[gtk4::test] -fn whitespace_marks_leave_the_value_draft_and_text_selection_unchanged() { - use sourceview5::prelude::*; - +fn marks_leave_the_value_draft_and_its_selection_alone() { let (grid, pane) = opened(two_text_columns(), two_text_values()); edit_field(&grid, &pane, 0, 1); - let typed = " leading\tinside\ntrailing "; + let typed = "one\u{200b}two\u{a0}three"; type_value(&pane, typed); let buffer = pane.imp().value_buffer.get(); buffer.select_range(&buffer.iter_at_offset(2), &buffer.iter_at_offset(9)); @@ -1956,23 +1938,17 @@ fn whitespace_marks_leave_the_value_draft_and_text_selection_unchanged() { .selection_bounds() .map(|(start, end)| (start.offset(), end.offset())) }; - assert_eq!(selection(), Some((2, 9))); let settings = grid.grid.config().expect("configured grid").settings.clone(); - let drawer = pane.imp().value_view.space_drawer(); - let row = pane.current_row().expect("shown row"); - let revision = row.revision(); + assert_eq!(tagged(&pane), [(3, 4), (7, 8)]); for show in [false, true] { - settings - .set_show_invisible_characters(show) - .expect("change whitespace marks"); + settings.set_show_invisible_characters(show).expect("change the marks"); drain_main_context(); - assert_eq!(drawer.enables_matrix(), show); + assert_eq!(tagged(&pane).is_empty(), !show); assert_eq!(pane.typed_text(), typed); assert_eq!(selection(), Some((2, 9))); assert!(pane.is_editing_value()); assert!(grid.grid.is_editing()); assert_eq!(pending(&grid, 1, 1), None); - assert_eq!(row.revision(), revision, "drawing marks does not replace row values"); } } diff --git a/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs b/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs index 4e6e1936de..6b7a52de1b 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs @@ -253,6 +253,7 @@ impl RowDetailPane { fn text_changed(&self) { self.update_placeholder(); + self.mark_special_characters(); if !self.imp().loading.get() { self.begin_edit(); } diff --git a/linux/crates/app/src/ui/data_grid/special_marks.rs b/linux/crates/app/src/ui/data_grid/special_marks.rs new file mode 100644 index 0000000000..ed0ad9701b --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/special_marks.rs @@ -0,0 +1,148 @@ +use std::ops::Range; + +use gtk4::prelude::*; +use gtk4::{self as gtk, gdk, pango}; + +use crate::services::grid::special_characters::{Mark, reveal, special_characters}; + +// Adwaita's orange 3 under a third of its strength, as the macOS app boxes +// each mark in the system orange: the value's own colour stays readable on +// it in both styles and on a selected row. +const TINT: (u16, u16, u16) = (0xFFFF, 0x7878, 0x0000); +const TINT_ALPHA: u16 = 0x5555; +const TAG_NAME: &str = "tp-special-character"; + +fn tint_rgba() -> gdk::RGBA { + gdk::RGBA::new(1.0, 120.0 / 255.0, 0.0, f32::from(TINT_ALPHA) / f32::from(u16::MAX)) +} + +// An editor cannot write a character's name in its place, so Pango draws +// each one the way it shows hidden characters. Not SPACES: a text view then +// marks every space of the paragraph, and a special space has the tint. +fn shown_in_editors() -> pango::ShowFlags { + pango::ShowFlags::LINE_BREAKS | pango::ShowFlags::IGNORABLES +} + +fn byte_index(index: usize) -> u32 { + u32::try_from(index).unwrap_or(u32::MAX) +} + +fn insert(attributes: &pango::AttrList, attribute: impl Into, range: &Range) { + let mut attribute = attribute.into(); + attribute.set_start_index(range.start); + attribute.set_end_index(range.end); + attributes.insert(attribute); +} + +fn insert_tint(attributes: &pango::AttrList, range: &Range) { + let (red, green, blue) = TINT; + insert(attributes, pango::AttrColor::new_background(red, green, blue), range); + insert(attributes, pango::AttrInt::new_background_alpha(TINT_ALPHA), range); +} + +/// `base` with a tinted box under each mark, a label a size smaller so it +/// reads apart from the value around it. +pub(crate) fn marked_attributes(base: Option<&pango::AttrList>, marks: &[Mark]) -> pango::AttrList { + let attributes = base.and_then(pango::AttrList::copy).unwrap_or_default(); + for mark in marks { + let range = byte_index(mark.range.start)..byte_index(mark.range.end); + insert_tint(&attributes, &range); + if mark.labelled { + insert(&attributes, pango::AttrFloat::new_scale(pango::SCALE_SMALL), &range); + } + } + attributes +} + +/// A one-line view of a value, with its special characters written as +/// their marks while `marks` holds. +pub(crate) fn show_value(display: >k::Inscription, text: &str, attributes: Option<&pango::AttrList>, marks: bool) { + match marks.then(|| reveal(text)).flatten() { + Some(revealed) => { + display.set_text(Some(&revealed.text)); + display.set_attributes(Some(&marked_attributes(attributes, &revealed.marks))); + } + None => { + display.set_text(Some(text)); + display.set_attributes(attributes); + } + } +} + +/// The inline editor's marks, rebuilt from its text; its text stays as typed. +pub(crate) fn mark_field(field: >k::Text, marks: bool) { + let attributes = pango::AttrList::new(); + let text = field.text(); + let mut found = false; + if marks { + for special in special_characters(&text, false) { + let range = byte_index(special.range.start)..byte_index(special.range.end); + insert(&attributes, pango::AttrInt::new_show(shown_in_editors()), &range); + insert_tint(&attributes, &range); + found = true; + } + } + field.set_attributes(found.then_some(&attributes)); +} + +/// A text view's marks, through a tag, so neither its text, its selection +/// nor its undo history changes. +pub(crate) fn mark_buffer(buffer: >k::TextBuffer, marks: bool) { + let (start, end) = buffer.bounds(); + let tag = special_tag(buffer); + buffer.remove_tag(&tag, &start, &end); + if !marks { + return; + } + let text = buffer.text(&start, &end, true); + let mut offset = 0; + let mut scanned = 0; + for special in special_characters(&text, false) { + offset += char_count(&text[scanned..special.range.start]); + let length = char_count(&text[special.range.clone()]); + buffer.apply_tag( + &tag, + &buffer.iter_at_offset(offset), + &buffer.iter_at_offset(offset + length), + ); + offset += length; + scanned = special.range.end; + } +} + +fn char_count(text: &str) -> i32 { + i32::try_from(text.chars().count()).unwrap_or(i32::MAX) +} + +fn special_tag(buffer: >k::TextBuffer) -> gtk::TextTag { + let table = buffer.tag_table(); + if let Some(tag) = table.lookup(TAG_NAME) { + return tag; + } + let tag = gtk::TextTag::builder() + .name(TAG_NAME) + .show_spaces(shown_in_editors()) + .background_rgba(&tint_rgba()) + .build(); + table.add(&tag); + tag +} + +#[cfg(test)] +pub(crate) fn tagged_ranges(buffer: >k::TextBuffer) -> Vec<(i32, i32)> { + let Some(tag) = buffer.tag_table().lookup(TAG_NAME) else { + return Vec::new(); + }; + let mut ranges = Vec::new(); + let mut at = buffer.start_iter(); + loop { + if at.starts_tag(Some(&tag)) { + let mut end = at; + end.forward_to_tag_toggle(Some(&tag)); + ranges.push((at.offset(), end.offset())); + } + if !at.forward_to_tag_toggle(Some(&tag)) { + return ranges; + } + } +} diff --git a/linux/crates/app/src/ui/data_grid/tests/cells.rs b/linux/crates/app/src/ui/data_grid/tests/cells.rs index 0e32c1c01d..502d1bf545 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -607,3 +607,73 @@ fn row_height_preferences_change_the_allocated_row_height() { assert_eq!(row_widget(&cell), row); assert_eq!(grid.cell_of(1, 1), cell); } + +fn marked_value(text: &str) -> Grid { + Grid::open( + two_text_columns(), + vec![vec![Value::Int(1), Value::Text(text.to_owned())]], + ) +} + +#[gtk4::test] +fn cells_mark_invisible_characters_until_preferences_turn_it_off() { + let grid = marked_value("a\u{200b}b\u{a0}c\nd\te f"); + + let cell = grid.cell_of(1, 1); + assert_eq!(Grid::display_text(&cell), "aZWSPb\u{a0}cLFd\te f"); + assert!(has_attribute(&cell, pango::AttrType::Background)); + assert!(has_attribute(&cell, pango::AttrType::Scale)); + + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + settings.set_show_invisible_characters(false).expect("store the flag"); + drain_main_context(); + let cell = grid.cell_of(1, 1); + assert_eq!(Grid::display_text(&cell), "a\u{200b}b\u{a0}c\nd\te f"); + assert!(!has_attribute(&cell, pango::AttrType::Background)); + + settings.set_show_invisible_characters(true).expect("store the flag"); + drain_main_context(); + assert_eq!(Grid::display_text(&grid.cell_of(1, 1)), "aZWSPb\u{a0}cLFd\te f"); +} + +#[gtk4::test] +fn a_cell_with_nothing_to_mark_draws_its_value_as_it_is() { + let grid = marked_value("plain text"); + + let cell = grid.cell_of(1, 1); + assert_eq!(Grid::display_text(&cell), "plain text"); + assert!(!has_attribute(&cell, pango::AttrType::Background)); +} + +#[gtk4::test] +fn the_inline_editor_marks_invisible_characters_and_keeps_its_text() { + let grid = marked_value("a\u{200b}b"); + let cell = grid.focus(0, 1); + assert!(grid.grid.edit().edit_cell(&cell)); + let field = grid.grid.edit().open_text().expect("an inline editor"); + let shown = |field: >k::Text| -> Vec<(u32, u32)> { + field + .attributes() + .map(|list| { + list.attributes() + .iter() + .filter(|attr| attr.type_() == pango::AttrType::Show) + .map(|attr| (attr.start_index(), attr.end_index())) + .collect() + }) + .unwrap_or_default() + }; + + assert_eq!(field.text(), "a\u{200b}b"); + assert_eq!(shown(&field), [(1, 4)]); + field.set_text("plain"); + assert!(shown(&field).is_empty()); + field.set_text("x\u{1}"); + assert_eq!(shown(&field), [(1, 2)]); + + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + settings.set_show_invisible_characters(false).expect("store the flag"); + drain_main_context(); + assert!(shown(&field).is_empty()); + assert_eq!(field.text(), "x\u{1}"); +} diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index 8f2eabc747..b047f64cbd 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -231,7 +231,7 @@ mod tests { } #[gtk4::test] - fn whitespace_switches_follow_each_other_and_external_settings() { + fn invisible_character_switches_follow_each_other_and_external_settings() { let settings = MemorySettings::new(); let first = bound_group(&settings); let second = bound_group(&settings); diff --git a/linux/crates/platform/tests/settings.rs b/linux/crates/platform/tests/settings.rs index 00e8d84e54..d735c38daa 100644 --- a/linux/crates/platform/tests/settings.rs +++ b/linux/crates/platform/tests/settings.rs @@ -610,7 +610,7 @@ async fn default_sort_choices_and_direction_share_the_grid_snapshot() -> TestRes } #[glib::async_test] -async fn whitespace_preference_uses_the_shared_snapshot_and_external_updates() -> TestResult { +async fn invisible_characters_preference_uses_the_shared_snapshot_and_external_updates() -> TestResult { use gio::prelude::SettingsExt; use std::cell::RefCell; use std::rc::Rc; diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index f58f029906..7d705a2a59 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -132,8 +132,8 @@ true - Mark spaces, tabs and line breaks in cell values - Whether the row details value editor draws marks for spaces, tabs and line breaks. + Show invisible characters + Whether cells and value fields mark zero-width, control and special space characters. diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 791a57b19c..b74ff8734f 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -51,8 +51,8 @@ - Mark Spaces, Tabs and Line Breaks - In the value editor of the row details + Show Invisible Characters + Mark zero-width, control and special space characters in cells and value fields diff --git a/linux/docs/state-management.md b/linux/docs/state-management.md index 02602e5a1e..ff5b609adf 100644 --- a/linux/docs/state-management.md +++ b/linux/docs/state-management.md @@ -93,7 +93,7 @@ A tab belongs to its session, and a session to one window ([decisions/0028-sessi ## Grid preferences -`AppSettings` owns one `GridPreferences` object. It reads the grid keys from GSettings and announces each changed snapshot. Every grid holds that object through its settings and follows its change signal. Preferences rows bind directly to GSettings, including both directions for choices stored as strings. Each grid owns its font CSS provider, scoped to that grid and removed when the grid closes. Its custom font description supplies both the rendered font and column width measurement. The value editor applies the whitespace preference to its native SpaceDrawer, including while its pane is closed, without changing the buffer or its selection. Automatic Row Details opening reads the same snapshot when the selection changes and opens only for a nonempty selection. Closing it keeps it closed through focus changes and clearing the selection. Turning the preference off leaves an open pane alone. Copy reads the row format from the shared snapshot when it runs; a single focused cell keeps its value format, and Copy As keeps the requested format. +`AppSettings` owns one `GridPreferences` object. It reads the grid keys from GSettings and announces each changed snapshot. Every grid holds that object through its settings and follows its change signal. Preferences rows bind directly to GSettings, including both directions for choices stored as strings. Each grid owns its font CSS provider, scoped to that grid and removed when the grid closes. Its custom font description supplies both the rendered font and column width measurement. Show Invisible Characters reads the same snapshot. Cells and the row details' field list write each zero-width, control and special space character as its short name over a tint; the inline editor and the value editor mark it with a Pango attribute or a text tag, which leaves their text, selection and undo history as they are. Automatic Row Details opening reads the same snapshot when the selection changes and opens only for a nonempty selection. Closing it keeps it closed through focus changes and clearing the selection. Turning the preference off leaves an open pane alone. Copy reads the row format from the shared snapshot when it runs; a single focused cell keeps its value format, and Copy As keeps the requested format. The snapshot belongs to its settings backend, so isolated test settings cannot change another grid. A display change redraws the existing row slots and resizes automatic columns. It keeps row selection, user column widths and active editor drafts. The formatting helpers receive display choices explicitly and keep no global preference state. diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index dcf8b801eb..6486f7dcdc 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -97,6 +97,7 @@ crates/app/src/services/grid/result_refusal.rs crates/app/src/services/grid/row_key_builder.rs crates/app/src/services/grid/row_snapshot.rs crates/app/src/services/grid/selection_summary.rs +crates/app/src/services/grid/special_characters.rs crates/app/src/services/grid/test_columns.rs crates/app/src/services/history_availability.rs crates/app/src/services/history_preferences.rs @@ -298,6 +299,7 @@ crates/app/src/ui/data_grid/row_number_column.rs crates/app/src/ui/data_grid/selection.rs crates/app/src/ui/data_grid/selection_summary.rs crates/app/src/ui/data_grid/server_sorter.rs +crates/app/src/ui/data_grid/special_marks.rs crates/app/src/ui/data_grid/stripes.rs crates/app/src/ui/data_grid/table_keys.rs crates/app/src/ui/data_grid/test_grid.rs From 65337b1b33320d5f68c8c3702b6d7a2db9262d8d Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 10 Nov 2026 04:29:59 +0700 Subject: [PATCH 18/18] fix(linux-grid): size automatic columns to the marks their cells draw --- linux/crates/app/src/ui/data_grid/columns.rs | 33 ++++++++++-- .../app/src/ui/data_grid/display_settings.rs | 2 +- .../app/src/ui/data_grid/special_marks.rs | 38 +++++++++----- .../app/src/ui/data_grid/tests/columns.rs | 50 +++++++++++++++++++ 4 files changed, 106 insertions(+), 17 deletions(-) diff --git a/linux/crates/app/src/ui/data_grid/columns.rs b/linux/crates/app/src/ui/data_grid/columns.rs index dbbc1acfd4..6902cea875 100644 --- a/linux/crates/app/src/ui/data_grid/columns.rs +++ b/linux/crates/app/src/ui/data_grid/columns.rs @@ -336,6 +336,7 @@ impl DataGrid { .filter_map(|cells| cells.as_deref().and_then(|cells| cells.get(index))) .collect(); let column = &paint.column; + let preferences = paint.preferences.snapshot(); let chars = match (by_type, paint.numbers.get()) { (true, _) => typical_width_chars(column), (false, true) => number_width_chars(column, values.iter().copied()), @@ -348,11 +349,11 @@ impl DataGrid { let sampled = match (by_type, paint.numbers.get()) { (_, true) => tabular_width(&context, &font, &"0".repeat(usize::try_from(chars).unwrap_or_default())), (true, false) => 0, - // One line each, so one layout measures them all. - (false, false) => drawn_width( + (false, false) => sampled_width( &context, &font, - &sampled_texts(column, values.iter().copied()).join("\n"), + &sampled_texts(column, values.iter().copied()), + preferences.show_invisible_characters, ), }; let spelled = match by_type || column.display() == CellDisplay::Temporal { @@ -368,7 +369,6 @@ impl DataGrid { None => 0, }; let header = header_width(&context, header_text(column)) + indicator; - let preferences = paint.preferences.snapshot(); let null = crate::services::grid::display_text::null_text( &preferences.null_display, paint.tracked.tracks_changes(), @@ -966,6 +966,31 @@ fn tabular_width(context: &pango::Context, font: &pango::FontDescription, text: layout.pixel_size().0 } +/// The widest of `texts` as a cell draws it, marks and all. One line each, +/// so one layout measures them all. +fn sampled_width(context: &pango::Context, font: &pango::FontDescription, texts: &[String], marks: bool) -> i32 { + let mut lines = String::new(); + let attributes = pango::AttrList::new(); + for text in texts { + if !lines.is_empty() { + lines.push('\n'); + } + let drawn = super::special_marks::drawn(text, None, marks); + let offset = u32::try_from(lines.len()).unwrap_or(u32::MAX); + for mut attribute in drawn.attributes.iter().flat_map(pango::AttrList::attributes) { + attribute.set_start_index(attribute.start_index().saturating_add(offset)); + attribute.set_end_index(attribute.end_index().saturating_add(offset)); + attributes.insert(attribute); + } + lines.push_str(&drawn.text); + } + let layout = pango::Layout::new(context); + layout.set_text(&lines); + layout.set_font_description(Some(font)); + layout.set_attributes(Some(&attributes)); + layout.pixel_size().0 +} + fn drawn_width(context: &pango::Context, font: &pango::FontDescription, text: &str) -> i32 { let layout = pango::Layout::new(context); layout.set_text(text); diff --git a/linux/crates/app/src/ui/data_grid/display_settings.rs b/linux/crates/app/src/ui/data_grid/display_settings.rs index 5e31867cac..5d00effaea 100644 --- a/linux/crates/app/src/ui/data_grid/display_settings.rs +++ b/linux/crates/app/src/ui/data_grid/display_settings.rs @@ -57,7 +57,7 @@ impl DataGrid { self.imp().applied_null.replace(Some(values.null_display.clone())); self.redraw(); } - if changed || font_changed { + if changed || font_changed || marks_changed { self.fonts_changed(); } } diff --git a/linux/crates/app/src/ui/data_grid/special_marks.rs b/linux/crates/app/src/ui/data_grid/special_marks.rs index ed0ad9701b..24fda08e2d 100644 --- a/linux/crates/app/src/ui/data_grid/special_marks.rs +++ b/linux/crates/app/src/ui/data_grid/special_marks.rs @@ -1,3 +1,4 @@ +use std::borrow::Cow; use std::ops::Range; use gtk4::prelude::*; @@ -42,7 +43,7 @@ fn insert_tint(attributes: &pango::AttrList, range: &Range) { /// `base` with a tinted box under each mark, a label a size smaller so it /// reads apart from the value around it. -pub(crate) fn marked_attributes(base: Option<&pango::AttrList>, marks: &[Mark]) -> pango::AttrList { +fn marked_attributes(base: Option<&pango::AttrList>, marks: &[Mark]) -> pango::AttrList { let attributes = base.and_then(pango::AttrList::copy).unwrap_or_default(); for mark in marks { let range = byte_index(mark.range.start)..byte_index(mark.range.end); @@ -54,21 +55,34 @@ pub(crate) fn marked_attributes(base: Option<&pango::AttrList>, marks: &[Mark]) attributes } -/// A one-line view of a value, with its special characters written as -/// their marks while `marks` holds. -pub(crate) fn show_value(display: >k::Inscription, text: &str, attributes: Option<&pango::AttrList>, marks: bool) { +/// What a one-line view draws for a value: its text, with each special +/// character written as its mark while `marks` holds. +pub(crate) struct Drawn<'a> { + pub text: Cow<'a, str>, + pub attributes: Option, +} + +// Drawing and column width both take the value from here, so a column is +// as wide as the marks its cells draw. +pub(crate) fn drawn<'a>(text: &'a str, attributes: Option<&pango::AttrList>, marks: bool) -> Drawn<'a> { match marks.then(|| reveal(text)).flatten() { - Some(revealed) => { - display.set_text(Some(&revealed.text)); - display.set_attributes(Some(&marked_attributes(attributes, &revealed.marks))); - } - None => { - display.set_text(Some(text)); - display.set_attributes(attributes); - } + Some(revealed) => Drawn { + attributes: Some(marked_attributes(attributes, &revealed.marks)), + text: Cow::Owned(revealed.text), + }, + None => Drawn { + text: Cow::Borrowed(text), + attributes: attributes.cloned(), + }, } } +pub(crate) fn show_value(display: >k::Inscription, text: &str, attributes: Option<&pango::AttrList>, marks: bool) { + let drawn = drawn(text, attributes, marks); + display.set_text(Some(&drawn.text)); + display.set_attributes(drawn.attributes.as_ref()); +} + /// The inline editor's marks, rebuilt from its text; its text stays as typed. pub(crate) fn mark_field(field: >k::Text, marks: bool) { let attributes = pango::AttrList::new(); diff --git a/linux/crates/app/src/ui/data_grid/tests/columns.rs b/linux/crates/app/src/ui/data_grid/tests/columns.rs index b03a7c5e21..0590e64c78 100644 --- a/linux/crates/app/src/ui/data_grid/tests/columns.rs +++ b/linux/crates/app/src/ui/data_grid/tests/columns.rs @@ -891,3 +891,53 @@ fn null_text_resizes_automatic_columns_and_preserves_manual_widths() { assert_eq!(column.fixed_width(), 260, "the chosen width stays"); } } + +/// Whether `display` has the width its text takes as it draws it, under +/// its own attributes. +fn draws_whole(display: >k::Inscription) -> bool { + let layout = display.create_pango_layout(display.text().as_deref()); + layout.set_attributes(display.attributes().as_ref()); + display.width() > 0 && layout.pixel_size().0 <= display.width() +} + +#[gtk4::test] +fn invisible_character_marks_resize_automatic_columns_and_preserve_manual_widths() { + for editable in [false, true] { + let settings = crate::test_support::MemorySettings::new(); + settings + .get() + .set_show_invisible_characters(false) + .expect("start without marks"); + let columns = two_text_columns(); + let spec = if editable { + GridSpec::table(columns) + } else { + GridSpec::results(columns) + }; + let values = vec![vec![ + Value::Int(1), + Value::Text("a\u{200b}b\u{200b}c\u{200b}d\u{200b}e".into()), + ]]; + let rows = if editable { persisted(&values) } else { results(&values) }; + let grid = Grid::build( + GridSpec { + settings: Some(settings.get().clone()), + ..spec + }, + rows, + ); + let column = data_column(&grid, 1); + let original = column.fixed_width(); + + settings.get().set_show_invisible_characters(true).expect("show marks"); + wait_until(WAIT, || column.fixed_width() > original).expect("automatic column grows"); + wait_until(WAIT, || { + draws_whole(grid.cell_at(0, 1).display().expect("cell display")) + }) + .expect("the whole marked value fits"); + column.set_fixed_width(260); + settings.get().set_show_invisible_characters(false).expect("hide marks"); + drain_main_context(); + assert_eq!(column.fixed_width(), 260, "the chosen width stays"); + } +}