From 1716467b33b6fe6513b5d3496dec9cd3ff987af5 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:10:21 +0100 Subject: [PATCH 01/19] feat(linux-grid): add Highlight Rules to colour the rows and cells that meet a condition --- .../crates/app/src/services/grid/highlight.rs | 394 +++++++++++++++++ linux/crates/app/src/services/grid/mod.rs | 2 + linux/crates/app/src/ui/browse_tab/imp.rs | 2 + linux/crates/app/src/ui/browse_tab/mod.rs | 8 + .../crates/app/src/ui/data_grid/grid_cell.rs | 6 +- .../crates/app/src/ui/data_grid/highlight.rs | 62 +++ .../app/src/ui/data_grid/highlight_popover.rs | 401 ++++++++++++++++++ linux/crates/app/src/ui/data_grid/imp.rs | 3 + linux/crates/app/src/ui/data_grid/mod.rs | 4 + .../app/src/ui/data_grid/tests/cells.rs | 73 ++++ .../crates/app/src/ui/editor/results_pane.rs | 15 + linux/data/resources/style.css | 30 ++ linux/data/resources/ui/browse-tab.ui | 14 + linux/data/resources/ui/results-pane.ui | 13 + linux/po/POTFILES.in | 3 + 15 files changed, 1029 insertions(+), 1 deletion(-) create mode 100644 linux/crates/app/src/services/grid/highlight.rs create mode 100644 linux/crates/app/src/ui/data_grid/highlight.rs create mode 100644 linux/crates/app/src/ui/data_grid/highlight_popover.rs diff --git a/linux/crates/app/src/services/grid/highlight.rs b/linux/crates/app/src/services/grid/highlight.rs new file mode 100644 index 0000000000..2cb5d2acfd --- /dev/null +++ b/linux/crates/app/src/services/grid/highlight.rs @@ -0,0 +1,394 @@ +//! Highlight rules: a condition on one column that colours the cell or the +//! whole row that meets it, as the macOS grid's Highlight Rules do +//! (`HighlightRuleSet`). The conditions use the filter strip's operators, +//! read here against the text a cell shows, so a rule matches what the user +//! sees. + +use serde::{Deserialize, Serialize}; +use tablepro_core::filter::{FilterOp, FilterValue}; +use uuid::Uuid; + +/// The colours a rule can paint, the macOS set. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HighlightColor { + Red, + Orange, + Yellow, + Green, + Blue, + Purple, + Gray, +} + +impl HighlightColor { + pub const ALL: [Self; 7] = [ + Self::Red, + Self::Orange, + Self::Yellow, + Self::Green, + Self::Blue, + Self::Purple, + Self::Gray, + ]; + + /// The style class a painted cell wears. + pub fn css_class(self) -> &'static str { + match self { + Self::Red => "tp-hl-red", + Self::Orange => "tp-hl-orange", + Self::Yellow => "tp-hl-yellow", + Self::Green => "tp-hl-green", + Self::Blue => "tp-hl-blue", + Self::Purple => "tp-hl-purple", + Self::Gray => "tp-hl-gray", + } + } +} + +/// What a rule paints. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HighlightTarget { + /// The whole row. + Row, + /// The cell of the rule's column alone. + Cell, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HighlightRule { + pub id: Uuid, + pub enabled: bool, + pub column: String, + pub op: FilterOp, + /// `None` for the null tests; the operand for every other operator. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, + pub case_sensitive: bool, + pub color: HighlightColor, + pub target: HighlightTarget, +} + +impl HighlightRule { + pub fn new(column: impl Into) -> Self { + Self { + id: Uuid::new_v4(), + enabled: true, + column: column.into(), + op: FilterOp::Eq, + value: Some(FilterValue::Single(String::new())), + case_sensitive: false, + color: HighlightColor::Yellow, + target: HighlightTarget::Row, + } + } + + /// Whether the rule says something a row can meet: a column, and the + /// operand its operator takes. + pub fn is_valid(&self) -> bool { + if self.column.is_empty() { + return false; + } + match (self.op, &self.value) { + (FilterOp::IsNull | FilterOp::IsNotNull, _) => true, + (FilterOp::In | FilterOp::NotIn, Some(FilterValue::List(items))) => !items.is_empty(), + (FilterOp::Between, Some(FilterValue::Pair(low, high))) => !low.is_empty() && !high.is_empty(), + (FilterOp::In | FilterOp::NotIn | FilterOp::Between, _) => false, + (_, Some(FilterValue::Single(text))) => !text.is_empty(), + _ => false, + } + } +} + +/// What a row meets: a colour for all of it, and colours for single cells. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RowHighlight { + pub row: Option, + /// By the column's position, the first rule that holds for each. + pub cells: Vec<(usize, HighlightColor)>, +} + +impl RowHighlight { + #[cfg(test)] + pub fn is_none(&self) -> bool { + self.row.is_none() && self.cells.is_empty() + } + + /// The colour of the cell in column `column`: its own rule's, else the row's. + pub fn color_of(&self, column: usize) -> Option { + self.cells + .iter() + .find(|(at, _)| *at == column) + .map(|(_, color)| *color) + .or(self.row) + } +} + +struct Compiled { + column: usize, + rule: HighlightRule, +} + +/// The rules that apply to a result's columns, ready to read rows with. +#[derive(Default)] +pub struct HighlightRules { + compiled: Vec, +} + +impl HighlightRules { + /// The enabled, valid rules whose column the result has. A rule for a + /// column that is not there waits, and meets nothing meanwhile. + pub fn compile(rules: &[HighlightRule], columns: &[String]) -> Self { + let compiled = rules + .iter() + .filter(|rule| rule.enabled && rule.is_valid()) + .filter_map(|rule| { + columns + .iter() + .position(|column| *column == rule.column) + .map(|column| Compiled { + column, + rule: rule.clone(), + }) + }) + .collect(); + Self { compiled } + } + + pub fn is_empty(&self) -> bool { + self.compiled.is_empty() + } + + /// The columns the rules read, which is all a row has to say of itself. + pub fn columns(&self) -> impl Iterator + '_ { + self.compiled.iter().map(|compiled| compiled.column) + } + + /// What `cells` meet, each the text the column shows and `None` for NULL. + pub fn highlight(&self, cells: &[Option<&str>]) -> RowHighlight { + let mut found = RowHighlight::default(); + for compiled in &self.compiled { + let text = cells.get(compiled.column).copied().flatten(); + if !matches(&compiled.rule, text) { + continue; + } + match compiled.rule.target { + HighlightTarget::Row if found.row.is_none() => found.row = Some(compiled.rule.color), + HighlightTarget::Cell if !found.cells.iter().any(|(at, _)| *at == compiled.column) => { + found.cells.push((compiled.column, compiled.rule.color)); + } + _ => {} + } + } + found + } +} + +fn matches(rule: &HighlightRule, text: Option<&str>) -> bool { + let Some(text) = text else { + // NULL meets only the null test. + return rule.op == FilterOp::IsNull; + }; + let sensitive = rule.case_sensitive; + let same = |a: &str, b: &str| compare(a, b, sensitive) == std::cmp::Ordering::Equal; + let single = || match &rule.value { + Some(FilterValue::Single(operand)) => Some(operand.as_str()), + _ => None, + }; + match rule.op { + FilterOp::IsNull => false, + FilterOp::IsNotNull => true, + FilterOp::Eq => single().is_some_and(|operand| same(text, operand)), + FilterOp::NotEq => single().is_some_and(|operand| !same(text, operand)), + FilterOp::Lt => single().is_some_and(|operand| compare(text, operand, sensitive).is_lt()), + FilterOp::LtEq => single().is_some_and(|operand| compare(text, operand, sensitive).is_le()), + FilterOp::Gt => single().is_some_and(|operand| compare(text, operand, sensitive).is_gt()), + FilterOp::GtEq => single().is_some_and(|operand| compare(text, operand, sensitive).is_ge()), + FilterOp::Contains => single().is_some_and(|operand| fold(text, sensitive).contains(&fold(operand, sensitive))), + FilterOp::StartsWith => { + single().is_some_and(|operand| fold(text, sensitive).starts_with(&fold(operand, sensitive))) + } + FilterOp::EndsWith => { + single().is_some_and(|operand| fold(text, sensitive).ends_with(&fold(operand, sensitive))) + } + FilterOp::Like => single().is_some_and(|pattern| like(text, pattern, sensitive)), + FilterOp::NotLike => single().is_some_and(|pattern| !like(text, pattern, sensitive)), + FilterOp::Ilike => single().is_some_and(|pattern| like(text, pattern, false)), + FilterOp::In => match &rule.value { + Some(FilterValue::List(items)) => items.iter().any(|item| same(text, item)), + _ => false, + }, + FilterOp::NotIn => match &rule.value { + Some(FilterValue::List(items)) => !items.is_empty() && !items.iter().any(|item| same(text, item)), + _ => false, + }, + FilterOp::Between => match &rule.value { + Some(FilterValue::Pair(low, high)) => { + compare(text, low, sensitive).is_ge() && compare(text, high, sensitive).is_le() + } + _ => false, + }, + } +} + +fn fold(text: &str, sensitive: bool) -> String { + if sensitive { + text.to_owned() + } else { + text.to_lowercase() + } +} + +/// Numbers compare as numbers when both sides read as one, else as text. +fn compare(a: &str, b: &str, sensitive: bool) -> std::cmp::Ordering { + if let (Ok(x), Ok(y)) = (a.trim().parse::(), b.trim().parse::()) + && let Some(order) = x.partial_cmp(&y) + { + return order; + } + fold(a, sensitive).cmp(&fold(b, sensitive)) +} + +/// SQL LIKE: `%` is any run of characters and `_` any one. +fn like(text: &str, pattern: &str, sensitive: bool) -> bool { + let text: Vec = fold(text, sensitive).chars().collect(); + let pattern: Vec = fold(pattern, sensitive).chars().collect(); + fn walk(text: &[char], pattern: &[char]) -> bool { + match pattern.split_first() { + None => text.is_empty(), + Some(('%', rest)) => (0..=text.len()).any(|skip| walk(&text[skip..], rest)), + Some(('_', rest)) => text.split_first().is_some_and(|(_, tail)| walk(tail, rest)), + Some((letter, rest)) => text + .split_first() + .is_some_and(|(head, tail)| head == letter && walk(tail, rest)), + } + } + walk(&text, &pattern) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rule(op: FilterOp, value: Option) -> HighlightRule { + HighlightRule { + op, + value, + ..HighlightRule::new("status") + } + } + + fn single(text: &str) -> Option { + Some(FilterValue::Single(text.to_owned())) + } + + fn highlights(rule: HighlightRule, text: Option<&str>) -> bool { + let rules = HighlightRules::compile(&[rule], &["status".to_owned()]); + !rules.highlight(&[text]).is_none() + } + + #[test] + fn equal_ignores_case_unless_asked_and_compares_numbers_as_numbers() { + assert!(highlights(rule(FilterOp::Eq, single("Active")), Some("active"))); + let mut exact = rule(FilterOp::Eq, single("Active")); + exact.case_sensitive = true; + assert!(!highlights(exact, Some("active"))); + assert!(highlights(rule(FilterOp::Eq, single("10")), Some("10.0"))); + assert!( + highlights(rule(FilterOp::Gt, single("9")), Some("10")), + "10 is more than 9 as numbers" + ); + assert!(!highlights(rule(FilterOp::Lt, single("9")), Some("10"))); + } + + #[test] + fn text_operators_match_what_the_cell_shows() { + assert!(highlights(rule(FilterOp::Contains, single("RR")), Some("error"))); + assert!(highlights(rule(FilterOp::StartsWith, single("er")), Some("error"))); + assert!(highlights(rule(FilterOp::EndsWith, single("OR")), Some("error"))); + assert!(highlights(rule(FilterOp::Like, single("e%r")), Some("error"))); + assert!(highlights(rule(FilterOp::Like, single("e_ror")), Some("error"))); + assert!(!highlights(rule(FilterOp::NotLike, single("e%")), Some("error"))); + } + + #[test] + fn lists_and_ranges() { + let list = Some(FilterValue::List(vec!["a".to_owned(), "b".to_owned()])); + assert!(highlights(rule(FilterOp::In, list.clone()), Some("B"))); + assert!(!highlights(rule(FilterOp::NotIn, list), Some("b"))); + let range = Some(FilterValue::Pair("5".to_owned(), "10".to_owned())); + assert!(highlights(rule(FilterOp::Between, range.clone()), Some("7"))); + assert!(highlights(rule(FilterOp::Between, range.clone()), Some("10"))); + assert!(!highlights(rule(FilterOp::Between, range), Some("11"))); + } + + #[test] + fn null_meets_only_the_null_test() { + assert!(highlights(rule(FilterOp::IsNull, None), None)); + assert!(!highlights(rule(FilterOp::IsNotNull, None), None)); + assert!(!highlights(rule(FilterOp::NotEq, single("x")), None)); + assert!(highlights(rule(FilterOp::IsNotNull, None), Some(""))); + } + + #[test] + fn a_row_rule_paints_the_row_and_a_cell_rule_its_cell_first() { + let mut row = HighlightRule::new("status"); + row.value = single("error"); + row.color = HighlightColor::Red; + let mut cell = HighlightRule::new("amount"); + cell.op = FilterOp::Gt; + cell.value = single("100"); + cell.target = HighlightTarget::Cell; + cell.color = HighlightColor::Green; + let columns = ["status".to_owned(), "amount".to_owned()]; + let rules = HighlightRules::compile(&[row, cell], &columns); + + let found = rules.highlight(&[Some("error"), Some("250")]); + + assert_eq!(found.row, Some(HighlightColor::Red)); + assert_eq!( + found.color_of(1), + Some(HighlightColor::Green), + "the cell's own rule wins" + ); + assert_eq!(found.color_of(0), Some(HighlightColor::Red)); + assert!(rules.highlight(&[Some("ok"), Some("5")]).is_none()); + } + + #[test] + fn a_disabled_invalid_or_unresolved_rule_paints_nothing() { + let mut off = rule(FilterOp::Eq, single("x")); + off.enabled = false; + let blank = rule(FilterOp::Eq, single("")); + let mut elsewhere = rule(FilterOp::Eq, single("x")); + elsewhere.column = "missing".to_owned(); + + let rules = HighlightRules::compile(&[off, blank, elsewhere], &["status".to_owned()]); + + assert!(rules.is_empty()); + } + + #[test] + fn the_first_rule_that_holds_decides_a_colour() { + let mut first = rule(FilterOp::Contains, single("a")); + first.color = HighlightColor::Blue; + let mut second = rule(FilterOp::Contains, single("a")); + second.color = HighlightColor::Red; + let rules = HighlightRules::compile(&[first, second], &["status".to_owned()]); + + assert_eq!(rules.highlight(&[Some("a")]).row, Some(HighlightColor::Blue)); + } + + #[test] + fn a_rule_round_trips_through_json() { + let original = rule( + FilterOp::Between, + Some(FilterValue::Pair("1".to_owned(), "2".to_owned())), + ); + + let text = serde_json::to_string(&original).expect("encode"); + + assert_eq!(serde_json::from_str::(&text).expect("decode"), original); + } +} diff --git a/linux/crates/app/src/services/grid/mod.rs b/linux/crates/app/src/services/grid/mod.rs index ba31b78469..8a1d2bf641 100644 --- a/linux/crates/app/src/services/grid/mod.rs +++ b/linux/crates/app/src/services/grid/mod.rs @@ -18,6 +18,7 @@ mod find_matches; mod grid_column; mod grid_row_id; mod hex_dump; +mod highlight; mod result_refusal; mod row_key_builder; mod row_snapshot; @@ -46,6 +47,7 @@ pub use self::find_matches::{FindMatch, find_matches}; pub use self::grid_column::{CellDisplay, GridColumn, grid_columns}; pub use self::grid_row_id::GridRowId; pub use self::hex_dump::hex_dump; +pub use self::highlight::{HighlightColor, HighlightRule, HighlightRules, HighlightTarget}; pub use self::result_refusal::ResultRefusal; pub use self::row_key_builder::RowKeyBuilder; pub use self::row_snapshot::RowSnapshot; diff --git a/linux/crates/app/src/ui/browse_tab/imp.rs b/linux/crates/app/src/ui/browse_tab/imp.rs index b6c8158638..f16c50412c 100644 --- a/linux/crates/app/src/ui/browse_tab/imp.rs +++ b/linux/crates/app/src/ui/browse_tab/imp.rs @@ -56,6 +56,8 @@ pub struct BrowseTab { #[template_child] pub filter_button: TemplateChild, #[template_child] + pub highlight_button: TemplateChild, + #[template_child] pub filter_badge: TemplateChild, #[template_child] pub page_size_dropdown: TemplateChild, diff --git a/linux/crates/app/src/ui/browse_tab/mod.rs b/linux/crates/app/src/ui/browse_tab/mod.rs index 3992ec5199..d43948f7c8 100644 --- a/linux/crates/app/src/ui/browse_tab/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/mod.rs @@ -164,6 +164,14 @@ impl BrowseTab { tasks: init.tasks.clone(), }, ); + { + let weak = grid.downgrade(); + tab.imp().highlight_button.set_create_popup_func(move |button| { + if let Some(grid) = weak.upgrade() { + button.set_popover(Some(&crate::ui::data_grid::highlight_rules_popover(&grid))); + } + }); + } let link_changes = init.session.link_changes(); let model = BrowseModel { this: tab.downgrade(), 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..93b1471d6e 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -11,7 +11,7 @@ use super::tracked_values::cell_description; use super::{DataGrid, GridRow, ServerValue}; use crate::services::change_tracker::CellState; use crate::services::grid::display_text::{DisplayText, auto_filled_sentinel, display_text, editable_null_sentinel}; -use crate::services::grid::{CellLock, GridColumn}; +use crate::services::grid::{CellLock, GridColumn, HighlightColor}; /// Enough for any number, date or short text. const SCRATCH_KEPT_BYTES: usize = 256; @@ -273,6 +273,10 @@ impl GridCell { if self.imp().scratch.borrow().capacity() > SCRATCH_KEPT_BYTES { self.imp().scratch.replace(String::new()); } + let colour = self.grid().and_then(|grid| grid.highlight_of(&row, column)); + for each in HighlightColor::ALL { + set_class(self, each.css_class(), colour == Some(each)); + } let numbers = paint.numbers.get(); display.set_xalign(if numbers { 1.0 } else { 0.0 }); set_class(display, "numeric", numbers); diff --git a/linux/crates/app/src/ui/data_grid/highlight.rs b/linux/crates/app/src/ui/data_grid/highlight.rs new file mode 100644 index 0000000000..ca3d21d777 --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/highlight.rs @@ -0,0 +1,62 @@ +//! Highlight rules on the grid: the rules the user wrote for the table or +//! result, compiled against its columns, and the colour each cell draws +//! from them (`HighlightRules`). + +use std::rc::Rc; + +use gtk4::subclass::prelude::*; + +use super::{DataGrid, GridRow}; +use crate::services::grid::display_text::display_text; +use crate::services::grid::{HighlightColor, HighlightRule, HighlightRules}; + +impl DataGrid { + /// Paint rows and cells by `rules`, which replace the ones held. + pub fn set_highlight_rules(&self, rules: Vec) { + self.imp().highlight_source.replace(rules); + self.compile_highlights(); + self.redraw(); + } + + pub fn highlight_rules(&self) -> Vec { + self.imp().highlight_source.borrow().clone() + } + + /// Match the rules to the columns the grid has now. A rule for a + /// column that another read lacks waits and paints nothing. + pub(super) fn compile_highlights(&self) { + let names: Vec = self.grid_columns().iter().map(|column| column.name.clone()).collect(); + let compiled = HighlightRules::compile(&self.imp().highlight_source.borrow(), &names); + self.imp().highlights.replace(Rc::new(compiled)); + } + + /// The colour the cell of `row` in `column` draws, if a rule holds for it. + pub(super) fn highlight_of(&self, row: &GridRow, column: usize) -> Option { + let rules = self.imp().highlights.borrow().clone(); + if rules.is_empty() { + return None; + } + let columns = self.grid_columns(); + // A rule reads only its own column's text, so the others stay empty. + let mut texts: Vec> = vec![None; columns.len()]; + let tracked = self.tracked(); + let mut scratch = String::new(); + for read in rules.columns() { + let Some(definition) = columns.get(read) else { + continue; + }; + texts[read] = tracked.with_value(row, read, |value, computed| { + if computed.is_some() || value.is_null() { + return None; + } + Some( + display_text(value, &definition.column_type, &mut scratch) + .text + .to_owned(), + ) + }); + } + let cells: Vec> = texts.iter().map(Option::as_deref).collect(); + rules.highlight(&cells).color_of(column) + } +} diff --git a/linux/crates/app/src/ui/data_grid/highlight_popover.rs b/linux/crates/app/src/ui/data_grid/highlight_popover.rs new file mode 100644 index 0000000000..1d3b6a72ec --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/highlight_popover.rs @@ -0,0 +1,401 @@ +//! The Highlight Rules popover: the rules of the grid in front, each a +//! condition on a column and the colour it paints, as the macOS bar's +//! pencil opens (`HighlightRulesPopover`). Every change applies at once. + +use std::cell::RefCell; +use std::rc::Rc; + +use gtk4 as gtk; +use gtk4::prelude::*; +use tablepro_core::filter::{FilterOp, FilterValue}; + +use super::DataGrid; +use crate::i18n::gettext; +use crate::services::grid::{HighlightColor, HighlightRule, HighlightTarget}; + +/// The operators a rule offers, in the order the dropdown lists them. +const OPERATORS: [FilterOp; 16] = [ + FilterOp::Eq, + FilterOp::NotEq, + FilterOp::Gt, + FilterOp::GtEq, + FilterOp::Lt, + FilterOp::LtEq, + FilterOp::Contains, + FilterOp::StartsWith, + FilterOp::EndsWith, + FilterOp::Like, + FilterOp::NotLike, + FilterOp::IsNull, + FilterOp::IsNotNull, + FilterOp::In, + FilterOp::NotIn, + FilterOp::Between, +]; + +fn operator_label(op: FilterOp) -> String { + match op { + FilterOp::Eq => gettext("equals"), + FilterOp::NotEq => gettext("doesn't equal"), + FilterOp::Gt => gettext("greater than"), + FilterOp::GtEq => gettext("at least"), + FilterOp::Lt => gettext("less than"), + FilterOp::LtEq => gettext("at most"), + FilterOp::Contains => gettext("contains"), + FilterOp::StartsWith => gettext("starts with"), + FilterOp::EndsWith => gettext("ends with"), + FilterOp::Like | FilterOp::Ilike => gettext("matches pattern"), + FilterOp::NotLike => gettext("doesn't match pattern"), + FilterOp::IsNull => gettext("is empty"), + FilterOp::IsNotNull => gettext("is not empty"), + FilterOp::In => gettext("is one of"), + FilterOp::NotIn => gettext("is none of"), + FilterOp::Between => gettext("between"), + } +} + +fn color_label(color: HighlightColor) -> String { + match color { + HighlightColor::Red => gettext("Red"), + HighlightColor::Orange => gettext("Orange"), + HighlightColor::Yellow => gettext("Yellow"), + HighlightColor::Green => gettext("Green"), + HighlightColor::Blue => gettext("Blue"), + HighlightColor::Purple => gettext("Purple"), + HighlightColor::Gray => gettext("Gray"), + } +} + +/// The blank value an operator takes, so a rule never holds one of another shape. +fn blank_for(op: FilterOp) -> Option { + match op { + FilterOp::IsNull | FilterOp::IsNotNull => None, + FilterOp::In | FilterOp::NotIn => Some(FilterValue::List(Vec::new())), + FilterOp::Between => Some(FilterValue::Pair(String::new(), String::new())), + _ => Some(FilterValue::Single(String::new())), + } +} + +/// What the value entry shows for a rule, and the other way: a list is +/// comma separated, a range is `low, high`. +fn value_text(value: &Option) -> String { + match value { + None => String::new(), + Some(FilterValue::Single(text)) => text.clone(), + Some(FilterValue::Pair(low, high)) => format!("{low}, {high}"), + Some(FilterValue::List(items)) => items.join(", "), + } +} + +fn value_from(op: FilterOp, text: &str) -> Option { + let parts = || text.split(',').map(|part| part.trim().to_owned()); + match op { + FilterOp::IsNull | FilterOp::IsNotNull => None, + FilterOp::In | FilterOp::NotIn => Some(FilterValue::List(parts().filter(|part| !part.is_empty()).collect())), + FilterOp::Between => { + let mut parts = parts(); + Some(FilterValue::Pair( + parts.next().unwrap_or_default(), + parts.next().unwrap_or_default(), + )) + } + _ => Some(FilterValue::Single(text.to_owned())), + } +} + +type Rules = Rc>>; + +/// The popover for `grid`, holding the rules it has now. +pub(crate) fn build(grid: &DataGrid) -> gtk::Popover { + let rules: Rules = Rc::new(RefCell::new(grid.highlight_rules())); + let list = gtk::Box::new(gtk::Orientation::Vertical, 8); + let scrolled = gtk::ScrolledWindow::builder() + .hscrollbar_policy(gtk::PolicyType::Never) + .propagate_natural_height(true) + .max_content_height(360) + .child(&list) + .build(); + let add = gtk::Button::with_label(&gettext("Add Rule")); + add.set_halign(gtk::Align::Start); + let heading = gtk::Label::builder() + .label(gettext("Highlight Rules")) + .xalign(0.0) + .build(); + heading.add_css_class("heading"); + let empty = gtk::Label::builder() + .label(gettext("No rules. Add one to colour the rows or cells that meet it.")) + .wrap(true) + .xalign(0.0) + .build(); + empty.add_css_class("dimmed"); + let body = gtk::Box::new(gtk::Orientation::Vertical, 10); + body.set_margin_top(12); + body.set_margin_bottom(12); + body.set_margin_start(12); + body.set_margin_end(12); + body.set_width_request(380); + body.append(&heading); + body.append(&empty); + body.append(&scrolled); + body.append(&add); + let popover = gtk::Popover::builder().child(&body).build(); + + let weak = grid.downgrade(); + let apply = { + let rules = rules.clone(); + move || { + if let Some(grid) = weak.upgrade() { + grid.set_highlight_rules(rules.borrow().clone()); + } + } + }; + let rebuild: Rc>>> = Rc::default(); + let rebuild_now = { + let (rules, list, empty, apply, rebuild, grid) = ( + rules.clone(), + list.clone(), + empty.clone(), + apply.clone(), + rebuild.clone(), + grid.downgrade(), + ); + move || { + while let Some(child) = list.first_child() { + list.remove(&child); + } + empty.set_visible(rules.borrow().is_empty()); + let columns: Vec = grid + .upgrade() + .map(|grid| grid.grid_columns().iter().map(|column| column.name.clone()).collect()) + .unwrap_or_default(); + let count = rules.borrow().len(); + for index in 0..count { + list.append(&rule_row(index, &rules, &columns, &apply, &rebuild)); + } + } + }; + rebuild.replace(Some(Box::new(rebuild_now.clone()))); + rebuild_now(); + + add.connect_clicked({ + let (rules, apply, rebuild) = (rules.clone(), apply.clone(), rebuild.clone()); + let columns: Vec = grid.grid_columns().iter().map(|column| column.name.clone()).collect(); + move |_| { + let Some(first) = columns.first() else { + return; + }; + rules.borrow_mut().push(HighlightRule::new(first.clone())); + apply(); + if let Some(rebuild) = rebuild.borrow().as_ref() { + rebuild(); + } + } + }); + popover +} + +fn rule_row( + index: usize, + rules: &Rules, + columns: &[String], + apply: &(impl Fn() + Clone + 'static), + rebuild: &Rc>>>, +) -> gtk::Widget { + let rule = rules.borrow()[index].clone(); + let card = gtk::Box::new(gtk::Orientation::Vertical, 6); + card.add_css_class("card"); + card.set_margin_start(1); + card.set_margin_end(1); + let inner = gtk::Box::new(gtk::Orientation::Vertical, 6); + inner.set_margin_top(8); + inner.set_margin_bottom(8); + inner.set_margin_start(8); + inner.set_margin_end(8); + card.append(&inner); + + let edit = { + let (rules, apply) = (rules.clone(), apply.clone()); + move |change: &dyn Fn(&mut HighlightRule)| { + if let Some(rule) = rules.borrow_mut().get_mut(index) { + change(rule); + } + apply(); + } + }; + + let top = gtk::Box::new(gtk::Orientation::Horizontal, 6); + let enabled = gtk::Switch::builder() + .active(rule.enabled) + .valign(gtk::Align::Center) + .build(); + enabled.update_property(&[gtk::accessible::Property::Label(&gettext("Rule enabled"))]); + enabled.connect_active_notify({ + let edit = edit.clone(); + move |switch| edit(&|rule| rule.enabled = switch.is_active()) + }); + let names: Vec<&str> = columns.iter().map(String::as_str).collect(); + let column = gtk::DropDown::from_strings(&names); + column.set_hexpand(true); + column.set_selected( + columns + .iter() + .position(|name| *name == rule.column) + .map_or(0, |at| at as u32), + ); + column.update_property(&[gtk::accessible::Property::Label(&gettext("Column"))]); + column.connect_selected_notify({ + let (edit, columns) = (edit.clone(), columns.to_vec()); + move |dropdown| { + if let Some(name) = columns.get(dropdown.selected() as usize) { + edit(&|rule| rule.column = name.clone()); + } + } + }); + let remove = gtk::Button::from_icon_name("edit-delete-symbolic"); + remove.add_css_class("flat"); + remove.set_tooltip_text(Some(&gettext("Remove Rule"))); + remove.update_property(&[gtk::accessible::Property::Label(&gettext("Remove Rule"))]); + remove.connect_clicked({ + let (rules, apply, rebuild) = (rules.clone(), apply.clone(), rebuild.clone()); + move |_| { + if index < rules.borrow().len() { + rules.borrow_mut().remove(index); + } + apply(); + if let Some(rebuild) = rebuild.borrow().as_ref() { + rebuild(); + } + } + }); + top.append(&enabled); + top.append(&column); + top.append(&remove); + inner.append(&top); + + let middle = gtk::Box::new(gtk::Orientation::Horizontal, 6); + let labels: Vec = OPERATORS.iter().map(|op| operator_label(*op)).collect(); + let label_refs: Vec<&str> = labels.iter().map(String::as_str).collect(); + let operator = gtk::DropDown::from_strings(&label_refs); + operator.set_selected(OPERATORS.iter().position(|op| *op == rule.op).map_or(0, |at| at as u32)); + operator.update_property(&[gtk::accessible::Property::Label(&gettext("Condition"))]); + let value = gtk::Entry::builder() + .hexpand(true) + .placeholder_text(gettext("Value")) + .text(value_text(&rule.value)) + .visible(!matches!(rule.op, FilterOp::IsNull | FilterOp::IsNotNull)) + .build(); + value.update_property(&[gtk::accessible::Property::Label(&gettext("Value"))]); + operator.connect_selected_notify({ + let (edit, value, rebuild) = (edit.clone(), value.clone(), rebuild.clone()); + move |dropdown| { + let Some(op) = OPERATORS.get(dropdown.selected() as usize).copied() else { + return; + }; + edit(&|rule| { + rule.op = op; + rule.value = blank_for(op); + }); + value.set_visible(!matches!(op, FilterOp::IsNull | FilterOp::IsNotNull)); + value.set_text(""); + let _ = &rebuild; + } + }); + value.connect_changed({ + let (edit, operator) = (edit.clone(), operator.clone()); + move |entry| { + let Some(op) = OPERATORS.get(operator.selected() as usize).copied() else { + return; + }; + let text = entry.text(); + edit(&|rule| rule.value = value_from(op, &text)); + } + }); + middle.append(&operator); + middle.append(&value); + inner.append(&middle); + + let bottom = gtk::Box::new(gtk::Orientation::Horizontal, 6); + let color_labels: Vec = HighlightColor::ALL.iter().map(|color| color_label(*color)).collect(); + let color_refs: Vec<&str> = color_labels.iter().map(String::as_str).collect(); + let color = gtk::DropDown::from_strings(&color_refs); + color.set_selected( + HighlightColor::ALL + .iter() + .position(|c| *c == rule.color) + .map_or(0, |at| at as u32), + ); + color.update_property(&[gtk::accessible::Property::Label(&gettext("Colour"))]); + color.connect_selected_notify({ + let edit = edit.clone(); + move |dropdown| { + if let Some(color) = HighlightColor::ALL.get(dropdown.selected() as usize).copied() { + edit(&|rule| rule.color = color); + } + } + }); + let targets = [gettext("Row"), gettext("Cell")]; + let target_refs: Vec<&str> = targets.iter().map(String::as_str).collect(); + let target = gtk::DropDown::from_strings(&target_refs); + target.set_selected(u32::from(rule.target == HighlightTarget::Cell)); + target.update_property(&[gtk::accessible::Property::Label(&gettext("Paints"))]); + target.connect_selected_notify({ + let edit = edit.clone(); + move |dropdown| { + let target = if dropdown.selected() == 1 { + HighlightTarget::Cell + } else { + HighlightTarget::Row + }; + edit(&|rule| rule.target = target); + } + }); + let case = gtk::CheckButton::with_label(&gettext("Match case")); + case.set_active(rule.case_sensitive); + case.connect_toggled({ + let edit = edit.clone(); + move |check| edit(&|rule| rule.case_sensitive = check.is_active()) + }); + bottom.append(&color); + bottom.append(&target); + bottom.append(&case); + inner.append(&bottom); + card.upcast() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_value_reads_back_the_way_it_was_written() { + for (op, text, expected) in [ + (FilterOp::Eq, "open", Some(FilterValue::Single("open".to_owned()))), + ( + FilterOp::In, + "a, b ,, c", + Some(FilterValue::List(vec!["a".to_owned(), "b".to_owned(), "c".to_owned()])), + ), + ( + FilterOp::Between, + "5, 10", + Some(FilterValue::Pair("5".to_owned(), "10".to_owned())), + ), + (FilterOp::IsNull, "ignored", None), + ] { + assert_eq!(value_from(op, text), expected); + } + assert_eq!(value_text(&value_from(FilterOp::Between, "5, 10")), "5, 10"); + assert_eq!(value_text(&value_from(FilterOp::In, "a, b")), "a, b"); + } + + #[test] + fn an_operator_starts_with_a_blank_value_of_its_shape() { + assert_eq!(blank_for(FilterOp::IsNotNull), None); + assert_eq!(blank_for(FilterOp::In), Some(FilterValue::List(Vec::new()))); + assert_eq!( + blank_for(FilterOp::Between), + Some(FilterValue::Pair(String::new(), String::new())) + ); + assert_eq!(blank_for(FilterOp::Eq), Some(FilterValue::Single(String::new()))); + } +} diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index 1b043907fd..e2da925aeb 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -86,6 +86,9 @@ pub struct DataGrid { pub editing: Cell, /// The window's focus handler, while the grid is in a window. pub focus_watch: RefCell, glib::SignalHandlerId)>>, + /// The rules the user wrote, and them compiled against the columns. + pub(super) highlight_source: RefCell>, + pub(super) highlights: RefCell>, pub(super) font_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..b787baf206 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -14,6 +14,8 @@ mod grid_menu; mod grid_request; mod grid_row; mod grid_store; +mod highlight; +mod highlight_popover; mod imp; mod keys; mod layout_binding; @@ -50,6 +52,7 @@ pub(crate) use self::grid_config::{DialectSource, EditRules, GridConfig, GridSor pub(crate) use self::grid_request::GridRequest; pub(crate) use self::grid_row::{GridRow, PinnedRow, RowData}; pub(crate) use self::grid_store::GridStore; +pub(crate) use self::highlight_popover::build as highlight_rules_popover; pub(crate) use self::layout_binding::LayoutBinding; use self::reversed_list::ReversedList; #[cfg(test)] @@ -193,6 +196,7 @@ impl DataGrid { self.imp().summary.forget_column(); self.edit().set_rules(self, rules); self.rebuild_columns(columns, sorting); + self.compile_highlights(); 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..5058199c10 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -501,3 +501,76 @@ 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"); } + +/// A highlight rule tints the rows that meet it, and a cell rule only its +/// own cell, as the macOS grid's Highlight Rules do. +#[gtk4::test] +fn highlight_rules_tint_the_rows_and_cells_that_meet_them() { + use crate::services::grid::{HighlightColor, HighlightRule, HighlightTarget}; + use tablepro_core::filter::{FilterOp, FilterValue}; + + let grid = Grid::open(two_text_columns(), two_text_values()); + let mut row_rule = HighlightRule::new("name"); + row_rule.op = FilterOp::Eq; + row_rule.value = Some(FilterValue::Single("B".to_owned())); + row_rule.color = HighlightColor::Red; + let mut cell_rule = HighlightRule::new("id"); + cell_rule.op = FilterOp::Eq; + cell_rule.value = Some(FilterValue::Single("1".to_owned())); + cell_rule.color = HighlightColor::Green; + cell_rule.target = HighlightTarget::Cell; + + grid.grid.set_highlight_rules(vec![row_rule, cell_rule]); + drain_main_context(); + + let tint = |id: i64, column: usize| { + let cell = grid.cell_of(id, column); + HighlightColor::ALL + .into_iter() + .find(|color| cell.has_css_class(color.css_class())) + }; + assert_eq!(tint(2, 0), Some(HighlightColor::Red), "the row that meets the rule"); + assert_eq!(tint(2, 1), Some(HighlightColor::Red)); + assert_eq!( + tint(1, 0), + Some(HighlightColor::Green), + "the cell that meets its own rule" + ); + assert_eq!(tint(1, 1), None, "a cell rule leaves the row's other cells"); + + grid.grid.set_highlight_rules(Vec::new()); + drain_main_context(); + assert_eq!(tint(2, 1), None, "the tint outlived its rule"); +} + +/// The Highlight Rules popover adds a rule for the grid's first column, +/// and what is typed in it reaches the grid's rules at once. +#[gtk4::test] +fn the_highlight_popover_edits_the_grids_rules() { + use tablepro_core::filter::FilterValue; + + let grid = Grid::open(two_text_columns(), two_text_values()); + let popover = crate::ui::data_grid::highlight_rules_popover(&grid.grid); + let content = popover.child().expect("the popover's content"); + let add = descendants(&content) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|button| button.label().as_deref() == Some("Add Rule")) + .expect("the Add Rule button"); + + add.emit_clicked(); + + let rules = grid.grid.highlight_rules(); + assert_eq!(rules.len(), 1); + assert_eq!(rules[0].column, "id"); + let value = descendants(&content) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .next() + .expect("the rule's value entry"); + value.set_text("1"); + assert_eq!( + grid.grid.highlight_rules()[0].value, + Some(FilterValue::Single("1".to_owned())) + ); +} diff --git a/linux/crates/app/src/ui/editor/results_pane.rs b/linux/crates/app/src/ui/editor/results_pane.rs index 80799a0117..b82df3b9fc 100644 --- a/linux/crates/app/src/ui/editor/results_pane.rs +++ b/linux/crates/app/src/ui/editor/results_pane.rs @@ -54,6 +54,8 @@ mod imp { #[template_child] pub details_toggle: TemplateChild, #[template_child] + pub highlight_button: TemplateChild, + #[template_child] pub transaction_bar: TemplateChild, #[template_child] pub transaction_label: TemplateChild, @@ -307,6 +309,19 @@ impl ResultsPane { let actions = grid.map(DataGrid::actions); self.insert_action_group("grid", actions.as_ref()); self.imp().details_toggle.set_visible(grid.is_some()); + let highlight = self.imp().highlight_button.get(); + highlight.set_visible(grid.is_some()); + match grid { + Some(grid) => { + let weak = grid.downgrade(); + highlight.set_create_popup_func(move |button| { + if let Some(grid) = weak.upgrade() { + button.set_popover(Some(&crate::ui::data_grid::highlight_rules_popover(&grid))); + } + }); + } + None => highlight.set_create_popup_func(|_| {}), + } } /// Put the page of line `index` first among the kept ones, building diff --git a/linux/data/resources/style.css b/linux/data/resources/style.css index 4c92a7f3e9..770f954d10 100644 --- a/linux/data/resources/style.css +++ b/linux/data/resources/style.css @@ -219,3 +219,33 @@ tp-diagram-canvas > .tp-diagram-border { tp-diagram-canvas > .tp-diagram-accent { color: var(--accent-color); } + +/* Highlight rules: a cell, or every cell of a row, tinted by what the user + asked to see. A selected row keeps its accent, as it does for stripes. */ +columnview > listview > row:not(:selected) > cell > .tp-hl-red { + background-color: color-mix(in srgb, var(--red-3) 28%, transparent); +} + +columnview > listview > row:not(:selected) > cell > .tp-hl-orange { + background-color: color-mix(in srgb, var(--orange-3) 28%, transparent); +} + +columnview > listview > row:not(:selected) > cell > .tp-hl-yellow { + background-color: color-mix(in srgb, var(--yellow-3) 32%, transparent); +} + +columnview > listview > row:not(:selected) > cell > .tp-hl-green { + background-color: color-mix(in srgb, var(--green-3) 28%, transparent); +} + +columnview > listview > row:not(:selected) > cell > .tp-hl-blue { + background-color: color-mix(in srgb, var(--blue-3) 28%, transparent); +} + +columnview > listview > row:not(:selected) > cell > .tp-hl-purple { + background-color: color-mix(in srgb, var(--purple-3) 28%, transparent); +} + +columnview > listview > row:not(:selected) > cell > .tp-hl-gray { + background-color: color-mix(in srgb, var(--view-fg-color) 12%, transparent); +} diff --git a/linux/data/resources/ui/browse-tab.ui b/linux/data/resources/ui/browse-tab.ui index 53d43a0eb7..61ed11f60c 100644 --- a/linux/data/resources/ui/browse-tab.ui +++ b/linux/data/resources/ui/browse-tab.ui @@ -13,6 +13,7 @@ max-width: 680sp false false + false false true true @@ -195,6 +196,19 @@ + + + + document-edit-symbolic + Highlight Rules + + + Highlight Rules + + + 6 diff --git a/linux/data/resources/ui/results-pane.ui b/linux/data/resources/ui/results-pane.ui index 398ebe75ae..42fc708654 100644 --- a/linux/data/resources/ui/results-pane.ui +++ b/linux/data/resources/ui/results-pane.ui @@ -80,6 +80,19 @@ + + + document-edit-symbolic + Highlight Rules + false + + + Highlight Rules + + + diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 23a2291ef9..6b88c81649 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -92,6 +92,7 @@ crates/app/src/services/grid/find_matches.rs crates/app/src/services/grid/grid_column.rs crates/app/src/services/grid/grid_row_id.rs crates/app/src/services/grid/hex_dump.rs +crates/app/src/services/grid/highlight.rs crates/app/src/services/grid/mod.rs crates/app/src/services/grid/result_refusal.rs crates/app/src/services/grid/row_key_builder.rs @@ -271,6 +272,8 @@ crates/app/src/ui/data_grid/grid_menu.rs crates/app/src/ui/data_grid/grid_request.rs crates/app/src/ui/data_grid/grid_row.rs crates/app/src/ui/data_grid/grid_store.rs +crates/app/src/ui/data_grid/highlight.rs +crates/app/src/ui/data_grid/highlight_popover.rs crates/app/src/ui/data_grid/imp.rs crates/app/src/ui/data_grid/keys.rs crates/app/src/ui/data_grid/layout_binding.rs From 154256487c5b374086b41ed403a700bc45203559 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:12:46 +0100 Subject: [PATCH 02/19] fix(linux-grid): let a highlight win over the row shading --- linux/data/resources/style.css | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/linux/data/resources/style.css b/linux/data/resources/style.css index 770f954d10..71eff35f2c 100644 --- a/linux/data/resources/style.css +++ b/linux/data/resources/style.css @@ -221,31 +221,32 @@ tp-diagram-canvas > .tp-diagram-accent { } /* Highlight rules: a cell, or every cell of a row, tinted by what the user - asked to see. A selected row keeps its accent, as it does for stripes. */ -columnview > listview > row:not(:selected) > cell > .tp-hl-red { + asked to see. A selected row keeps its accent, as it does for stripes, and + the selector is as specific as the stripes' so a highlight wins on a shaded row. */ +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-red { background-color: color-mix(in srgb, var(--red-3) 28%, transparent); } -columnview > listview > row:not(:selected) > cell > .tp-hl-orange { +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-orange { background-color: color-mix(in srgb, var(--orange-3) 28%, transparent); } -columnview > listview > row:not(:selected) > cell > .tp-hl-yellow { +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-yellow { background-color: color-mix(in srgb, var(--yellow-3) 32%, transparent); } -columnview > listview > row:not(:selected) > cell > .tp-hl-green { +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-green { background-color: color-mix(in srgb, var(--green-3) 28%, transparent); } -columnview > listview > row:not(:selected) > cell > .tp-hl-blue { +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-blue { background-color: color-mix(in srgb, var(--blue-3) 28%, transparent); } -columnview > listview > row:not(:selected) > cell > .tp-hl-purple { +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-purple { background-color: color-mix(in srgb, var(--purple-3) 28%, transparent); } -columnview > listview > row:not(:selected) > cell > .tp-hl-gray { +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-gray { background-color: color-mix(in srgb, var(--view-fg-color) 12%, transparent); } From 3777079b9d992c32022409fc1e4ae8be8e44b57f Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:12:51 +0100 Subject: [PATCH 03/19] docs(linux-grid): add the changelog entry --- linux/changelog.d/4127.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 linux/changelog.d/4127.added.md diff --git a/linux/changelog.d/4127.added.md b/linux/changelog.d/4127.added.md new file mode 100644 index 0000000000..1ca65f943b --- /dev/null +++ b/linux/changelog.d/4127.added.md @@ -0,0 +1 @@ +Highlight Rules in the bottom bar colour the rows or cells that meet a condition. From 72991a9c5a6251cfd612189461b5fb31f6a32bf2 Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:25:43 +0100 Subject: [PATCH 04/19] feat(linux-grid): keep a table's highlight rules across restarts --- .../app/src/application/app_services.rs | 1 + .../persistence/highlight_rules_document.rs | 22 ++++ .../src/persistence/highlight_rules_store.rs | 119 ++++++++++++++++++ linux/crates/app/src/persistence/mod.rs | 5 +- .../app/src/services/connection_deletion.rs | 18 ++- linux/crates/app/src/storage.rs | 13 +- linux/crates/app/src/ui/browse_tab/mod.rs | 14 +++ .../crates/app/src/ui/browse_tab/tests/mod.rs | 1 + .../crates/app/src/ui/data_grid/highlight.rs | 12 ++ linux/crates/app/src/ui/data_grid/imp.rs | 1 + .../app/src/ui/data_grid/tests/cells.rs | 19 +++ .../crates/app/src/ui/workspace/close_flow.rs | 2 + .../app/src/ui/workspace/tab_factory.rs | 1 + linux/po/POTFILES.in | 2 + 14 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 linux/crates/app/src/persistence/highlight_rules_document.rs create mode 100644 linux/crates/app/src/persistence/highlight_rules_store.rs diff --git a/linux/crates/app/src/application/app_services.rs b/linux/crates/app/src/application/app_services.rs index 3f9375b96b..454de6d95a 100644 --- a/linux/crates/app/src/application/app_services.rs +++ b/linux/crates/app/src/application/app_services.rs @@ -362,6 +362,7 @@ impl AppServices { )), column_layouts: self.storage.column_layouts().clone(), filters: self.storage.filter_settings().clone(), + highlight_rules: self.storage.highlight_rules().clone(), workspaces: self.storage.workspaces().clone(), history, spawner: self.tasks.clone(), diff --git a/linux/crates/app/src/persistence/highlight_rules_document.rs b/linux/crates/app/src/persistence/highlight_rules_document.rs new file mode 100644 index 0000000000..05e64b888e --- /dev/null +++ b/linux/crates/app/src/persistence/highlight_rules_document.rs @@ -0,0 +1,22 @@ +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; +use tablepro_storage::document::VersionedDocument; + +use crate::services::grid::HighlightRule; + +/// Per-table highlight rules, keyed connection, schema, table, in the +/// same nesting as the filters. +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +pub struct HighlightRulesDocument { + #[serde(default)] + pub connections: HashMap, +} + +pub type Schemas = HashMap; +pub type Tables = HashMap>; + +impl VersionedDocument for HighlightRulesDocument { + const KIND: &'static str = "highlight-rules"; + const VERSION: u32 = 1; +} diff --git a/linux/crates/app/src/persistence/highlight_rules_store.rs b/linux/crates/app/src/persistence/highlight_rules_store.rs new file mode 100644 index 0000000000..6ccf1f247d --- /dev/null +++ b/linux/crates/app/src/persistence/highlight_rules_store.rs @@ -0,0 +1,119 @@ +use std::rc::Rc; + +use tablepro_session::runtime::Tasks; +use uuid::Uuid; + +use super::StateFile; +use super::highlight_rules_document::HighlightRulesDocument; +use crate::services::grid::HighlightRule; + +/// The highlight rules each table was left with, remembered per +/// connection, schema and table, as the macOS grid keeps them. +#[derive(Clone)] +pub struct HighlightRulesStore { + file: Rc>, +} + +impl HighlightRulesStore { + pub fn load(path: std::path::PathBuf, tasks: &Tasks) -> Self { + Self { + file: Rc::new(StateFile::load(path, tasks)), + } + } + + pub fn path(&self) -> &std::path::Path { + self.file.path() + } + + pub fn rules(&self, connection_id: Uuid, schema: Option<&str>, table: &str) -> Vec { + self.file.read(|document| { + document + .connections + .get(&connection_id.to_string()) + .and_then(|schemas| schemas.get(schema.unwrap_or(""))) + .and_then(|tables| tables.get(table)) + .cloned() + .unwrap_or_default() + }) + } + + pub fn set_rules(&self, connection_id: Uuid, schema: Option<&str>, table: &str, rules: Vec) { + self.file.update(|document| { + let schemas = document.connections.entry(connection_id.to_string()).or_default(); + let schema_key = schema.unwrap_or("").to_owned(); + if rules.is_empty() { + // No rules shrinks the file back, as no filter does. + let removed = schemas + .get_mut(&schema_key) + .is_some_and(|tables| tables.remove(table).is_some()); + if schemas.get(&schema_key).is_some_and(|tables| tables.is_empty()) { + schemas.remove(&schema_key); + } + if schemas.is_empty() { + document.connections.remove(&connection_id.to_string()); + } + return removed; + } + let slot = schemas + .entry(schema_key) + .or_default() + .entry(table.to_owned()) + .or_default(); + if *slot == rules { + return false; + } + *slot = rules; + true + }); + } + + /// Drop everything for a connection the user deleted. + pub fn forget_connection(&self, connection_id: Uuid) { + self.file + .update(|document| document.connections.remove(&connection_id.to_string()).is_some()); + } + + pub fn flush(&self) -> impl Future + Send + use<> { + self.file.flush() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::paused_tasks; + + fn store(root: &tempfile::TempDir) -> HighlightRulesStore { + HighlightRulesStore::load(root.path().join("highlight_rules.json"), &paused_tasks()) + } + + #[tokio::test] + async fn rules_are_kept_per_table_and_schema() { + let root = tempfile::tempdir().expect("tempdir"); + let store = store(&root); + let id = Uuid::new_v4(); + let rule = HighlightRule::new("status"); + + store.set_rules(id, Some("public"), "orders", vec![rule.clone()]); + + assert_eq!(store.rules(id, Some("public"), "orders"), [rule]); + assert!(store.rules(id, Some("audit"), "orders").is_empty()); + assert!(store.rules(id, Some("public"), "users").is_empty()); + assert!(store.rules(Uuid::new_v4(), Some("public"), "orders").is_empty()); + } + + #[tokio::test] + async fn no_rules_removes_the_entry_and_a_deleted_connection_takes_its_rules() { + let root = tempfile::tempdir().expect("tempdir"); + let store = store(&root); + let id = Uuid::new_v4(); + store.set_rules(id, None, "orders", vec![HighlightRule::new("status")]); + store.set_rules(id, None, "orders", Vec::new()); + assert!(store.rules(id, None, "orders").is_empty()); + + store.set_rules(id, None, "users", vec![HighlightRule::new("name")]); + store.forget_connection(id); + + assert!(store.rules(id, None, "users").is_empty()); + } +} diff --git a/linux/crates/app/src/persistence/mod.rs b/linux/crates/app/src/persistence/mod.rs index df14d9dd69..b7da65d229 100644 --- a/linux/crates/app/src/persistence/mod.rs +++ b/linux/crates/app/src/persistence/mod.rs @@ -1,5 +1,5 @@ //! The small versioned JSON files the app keeps beside the user's -//! state: column layouts and per-table filters. +//! state: column layouts, per-table filters and highlight rules. //! //! Each is read once at startup and answered from memory after that, so //! nothing the user does waits on the disk. A file that cannot be read, @@ -9,8 +9,11 @@ mod column_layout_store; mod column_layouts_document; mod filter_settings_document; mod filter_settings_store; +mod highlight_rules_document; +mod highlight_rules_store; mod state_file; pub use column_layout_store::ColumnLayoutStore; pub use filter_settings_store::FilterSettingsStore; +pub use highlight_rules_store::HighlightRulesStore; pub use state_file::StateFile; diff --git a/linux/crates/app/src/services/connection_deletion.rs b/linux/crates/app/src/services/connection_deletion.rs index 5d40e1743b..dbb35175d4 100644 --- a/linux/crates/app/src/services/connection_deletion.rs +++ b/linux/crates/app/src/services/connection_deletion.rs @@ -9,7 +9,7 @@ use uuid::Uuid; use super::deletion_error::DeletionError; use super::deletion_report::{DeletionReport, PurgeFailure}; -use crate::persistence::{ColumnLayoutStore, FilterSettingsStore}; +use crate::persistence::{ColumnLayoutStore, FilterSettingsStore, HighlightRulesStore}; use crate::workspace::{WorkspaceSaveError, WorkspaceStore}; /// What the user chose in the delete dialog. @@ -31,6 +31,7 @@ pub struct ConnectionDeletion { pub connections: Arc, pub column_layouts: ColumnLayoutStore, pub filters: FilterSettingsStore, + pub highlight_rules: HighlightRulesStore, pub workspaces: WorkspaceStore, /// `None` when the history database did not open. pub history: Option, @@ -54,13 +55,19 @@ impl ConnectionDeletion { let mut report = DeletionReport::default(); self.column_layouts.forget_connection(id); self.filters.forget_connection(id); + self.highlight_rules.forget_connection(id); // Awaited inside the delete's hold, so a quit right after it // cannot leave them on disk. self.column_layouts.flush().await; self.filters.flush().await; + self.highlight_rules.flush().await; // Copies kept before an upgrade hold the connection's tables and filter values, and are not // worth keeping without them. - let files = [self.column_layouts.path().to_owned(), self.filters.path().to_owned()]; + let files = [ + self.column_layouts.path().to_owned(), + self.filters.path().to_owned(), + self.highlight_rules.path().to_owned(), + ]; let copies = self .spawner .spawn_blocking_task(move || { @@ -179,6 +186,7 @@ mod tests { vault: Arc, layouts: ColumnLayoutStore, filters: FilterSettingsStore, + highlight_rules: HighlightRulesStore, workspaces: WorkspaceStore, drafts: DraftStore, history: QueryHistory, @@ -251,6 +259,10 @@ mod tests { let vault = Arc::new(FakeSecretVault::new()); let layouts = ColumnLayoutStore::load(paths.column_layouts_file(), &tasks); let filters = FilterSettingsStore::load(paths.filter_settings_file(), &tasks); + let highlight_rules = HighlightRulesStore::load( + paths.filter_settings_file().with_file_name("highlight_rules.json"), + &tasks, + ); let drafts = DraftStore::new(paths.drafts_dir()); let workspaces = WorkspaceStore::start(paths.workspaces_dir(), drafts.clone(), &tasks); let history = QueryHistory::open(&paths).await.expect("the history"); @@ -309,6 +321,7 @@ mod tests { vault, layouts, filters, + highlight_rules, workspaces, drafts, history, @@ -330,6 +343,7 @@ mod tests { }), column_layouts: self.layouts.clone(), filters: self.filters.clone(), + highlight_rules: self.highlight_rules.clone(), workspaces: self.workspaces.clone(), history: Some(self.history.clone()), spawner: paused_tasks(), diff --git a/linux/crates/app/src/storage.rs b/linux/crates/app/src/storage.rs index 74effe3924..2486168305 100644 --- a/linux/crates/app/src/storage.rs +++ b/linux/crates/app/src/storage.rs @@ -4,7 +4,7 @@ use tablepro_core::credentials::SecretVault; use tablepro_session::runtime::Tasks; use tablepro_storage::{ConnectionStore, StoragePaths}; -use crate::persistence::{ColumnLayoutStore, FilterSettingsStore}; +use crate::persistence::{ColumnLayoutStore, FilterSettingsStore, HighlightRulesStore}; use crate::workspace::WorkspaceStore; /// Everything the app persists, resolved once at startup and handed to @@ -17,6 +17,7 @@ pub struct AppStorage { secrets: std::sync::Arc, column_layouts: ColumnLayoutStore, filter_settings: FilterSettingsStore, + highlight_rules: HighlightRulesStore, workspaces: WorkspaceStore, } @@ -27,6 +28,11 @@ impl AppStorage { let connections = ConnectionStore::new(&paths); let column_layouts = ColumnLayoutStore::load(paths.column_layouts_file(), tasks); let filter_settings = FilterSettingsStore::load(paths.filter_settings_file(), tasks); + // Beside the filters, under a name of its own. + let highlight_rules = HighlightRulesStore::load( + paths.filter_settings_file().with_file_name("highlight_rules.json"), + tasks, + ); let workspaces = WorkspaceStore::start( paths.workspaces_dir(), tablepro_storage::DraftStore::new(paths.drafts_dir()), @@ -38,6 +44,7 @@ impl AppStorage { secrets, column_layouts, filter_settings, + highlight_rules, workspaces, } } @@ -62,6 +69,10 @@ impl AppStorage { &self.filter_settings } + pub fn highlight_rules(&self) -> &HighlightRulesStore { + &self.highlight_rules + } + pub fn workspaces(&self) -> &WorkspaceStore { &self.workspaces } diff --git a/linux/crates/app/src/ui/browse_tab/mod.rs b/linux/crates/app/src/ui/browse_tab/mod.rs index d43948f7c8..3dfe1e0ca6 100644 --- a/linux/crates/app/src/ui/browse_tab/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/mod.rs @@ -108,6 +108,7 @@ pub struct BrowseTabInit { pub filter: TableFilter, pub column_layouts: crate::persistence::ColumnLayoutStore, pub filter_settings: crate::persistence::FilterSettingsStore, + pub highlight_rules: crate::persistence::HighlightRulesStore, /// The session the tab reads through. The tab belongs to it and is /// closed before it shuts down. pub session: Arc, @@ -172,6 +173,19 @@ impl BrowseTab { } }); } + // The rules the table was left with, kept again as they change. + if let Some(connection_id) = init.connection_id { + let rules = init + .highlight_rules + .rules(connection_id, init.schema.as_deref(), &init.table); + if !rules.is_empty() { + grid.set_highlight_rules(rules); + } + let (store, schema, table) = (init.highlight_rules.clone(), init.schema.clone(), init.table.clone()); + grid.connect_highlight_rules_changed(move |grid| { + store.set_rules(connection_id, schema.as_deref(), &table, grid.highlight_rules()); + }); + } let link_changes = init.session.link_changes(); let model = BrowseModel { this: tab.downgrade(), 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..9e0218b146 100644 --- a/linux/crates/app/src/ui/browse_tab/tests/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/tests/mod.rs @@ -381,6 +381,7 @@ pub(super) fn table_tab( filter, column_layouts: crate::persistence::ColumnLayoutStore::load(root.join("column_layouts.json"), &tasks), filter_settings, + highlight_rules: crate::persistence::HighlightRulesStore::load(root.join("highlight_rules.json"), &tasks), session: session.clone(), tasks, deadlines: Arc::new(tablepro_session::operation::DefaultDeadlines::new( diff --git a/linux/crates/app/src/ui/data_grid/highlight.rs b/linux/crates/app/src/ui/data_grid/highlight.rs index ca3d21d777..50519b79c9 100644 --- a/linux/crates/app/src/ui/data_grid/highlight.rs +++ b/linux/crates/app/src/ui/data_grid/highlight.rs @@ -4,6 +4,8 @@ use std::rc::Rc; +use gtk4::glib; +use gtk4::prelude::*; use gtk4::subclass::prelude::*; use super::{DataGrid, GridRow}; @@ -16,6 +18,16 @@ impl DataGrid { self.imp().highlight_source.replace(rules); self.compile_highlights(); self.redraw(); + self.emit_by_name::<()>("highlight-rules-changed", &[]); + } + + /// The rules changed, as the popover or a load sets them, for a host that keeps them. + pub fn connect_highlight_rules_changed(&self, f: F) -> glib::SignalHandlerId { + self.connect_closure( + "highlight-rules-changed", + false, + glib::closure_local!(move |grid: &Self| f(grid)), + ) } pub fn highlight_rules(&self) -> Vec { diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index e2da925aeb..561b971a58 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -119,6 +119,7 @@ impl ObjectImpl for DataGrid { .build(), Signal::builder("selection-changed").build(), Signal::builder("editing-changed").build(), + Signal::builder("highlight-rules-changed").build(), ] }) } 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 5058199c10..8b038f0f94 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -574,3 +574,22 @@ fn the_highlight_popover_edits_the_grids_rules() { Some(FilterValue::Single("1".to_owned())) ); } + +/// A host that keeps the rules hears of each change, and only of changes. +#[gtk4::test] +fn the_grid_tells_its_host_when_the_highlight_rules_change() { + use crate::services::grid::HighlightRule; + + let grid = Grid::open(two_text_columns(), two_text_values()); + let heard = Rc::new(Cell::new(0)); + let count = heard.clone(); + grid.grid + .connect_highlight_rules_changed(move |_| count.set(count.get() + 1)); + + grid.grid.set_highlight_rules(vec![HighlightRule::new("name")]); + assert_eq!(heard.get(), 1); + assert_eq!(grid.grid.highlight_rules().len(), 1); + + grid.grid.set_highlight_rules(Vec::new()); + assert_eq!(heard.get(), 2); +} diff --git a/linux/crates/app/src/ui/workspace/close_flow.rs b/linux/crates/app/src/ui/workspace/close_flow.rs index 2257f256c2..0101a46845 100644 --- a/linux/crates/app/src/ui/workspace/close_flow.rs +++ b/linux/crates/app/src/ui/workspace/close_flow.rs @@ -41,6 +41,7 @@ impl WorkspaceModel { let hold = self.context.hold.acquire(); let column_layouts = self.storage.column_layouts().flush(); let filter_settings = self.storage.filter_settings().flush(); + let highlight_rules = self.storage.highlight_rules().flush(); // The key is free once the window lets go of it, which is before // these land; a delete of the connection waits for them. let drafts_landing = self.storage.workspaces().writes_in_flight(&self.key); @@ -50,6 +51,7 @@ impl WorkspaceModel { glib::spawn_future_local(async move { column_layouts.await; filter_settings.await; + highlight_rules.await; for failure in editor_drafts.await { tracing::warn!(failure, "an editor draft was not saved"); } diff --git a/linux/crates/app/src/ui/workspace/tab_factory.rs b/linux/crates/app/src/ui/workspace/tab_factory.rs index 55b8f44575..f094f885b2 100644 --- a/linux/crates/app/src/ui/workspace/tab_factory.rs +++ b/linux/crates/app/src/ui/workspace/tab_factory.rs @@ -254,6 +254,7 @@ impl TabFactory { filter, column_layouts: parts.storage.column_layouts().clone(), filter_settings: parts.storage.filter_settings().clone(), + highlight_rules: parts.storage.highlight_rules().clone(), session, tasks: parts.context.tasks.clone(), deadlines: parts.context.deadlines.clone(), diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 6b88c81649..904f1c17e7 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -36,6 +36,8 @@ crates/app/src/persistence/column_layout_store.rs crates/app/src/persistence/column_layouts_document.rs crates/app/src/persistence/filter_settings_document.rs crates/app/src/persistence/filter_settings_store.rs +crates/app/src/persistence/highlight_rules_document.rs +crates/app/src/persistence/highlight_rules_store.rs crates/app/src/persistence/mod.rs crates/app/src/persistence/state_file.rs crates/app/src/runtime/app_runtime.rs From 372a4b03583f3ed1b3cf42f11fabc3ff1d35abbc Mon Sep 17 00:00:00 2001 From: sedax90 <5001801+sedax90@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:25:47 +0100 Subject: [PATCH 05/19] docs(linux-grid): add the changelog entry --- linux/changelog.d/4129.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 linux/changelog.d/4129.added.md diff --git a/linux/changelog.d/4129.added.md b/linux/changelog.d/4129.added.md new file mode 100644 index 0000000000..284e1e6f98 --- /dev/null +++ b/linux/changelog.d/4129.added.md @@ -0,0 +1 @@ +A table's highlight rules are kept and come back when it opens again. From 4632452ffff2271ace03aa83131197f1f021e5fd Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 22:59:42 +0700 Subject: [PATCH 06/19] fix(linux-grid): rebuild highlight rule evaluation and editing --- linux/ARCHITECTURE.md | 7 + .../crates/app/src/services/grid/highlight.rs | 251 +++-- linux/crates/app/src/services/grid/mod.rs | 2 +- linux/crates/app/src/ui/browse_tab/imp.rs | 2 - linux/crates/app/src/ui/browse_tab/layout.rs | 13 + linux/crates/app/src/ui/browse_tab/mod.rs | 8 - .../app/src/ui/data_grid/grid_actions.rs | 1 + .../crates/app/src/ui/data_grid/grid_cell.rs | 32 +- .../crates/app/src/ui/data_grid/highlight.rs | 105 +- .../app/src/ui/data_grid/highlight_dialog.rs | 958 ++++++++++++++++++ .../app/src/ui/data_grid/highlight_popover.rs | 401 -------- linux/crates/app/src/ui/data_grid/imp.rs | 3 +- linux/crates/app/src/ui/data_grid/mod.rs | 3 +- .../app/src/ui/data_grid/tests/cells.rs | 46 +- .../crates/app/src/ui/editor/results_pane.rs | 74 +- linux/data/resources/style.css | 4 +- linux/data/resources/ui/browse-tab.ui | 4 +- linux/data/resources/ui/results-pane.ui | 3 +- linux/po/POTFILES.in | 2 +- 19 files changed, 1357 insertions(+), 562 deletions(-) create mode 100644 linux/crates/app/src/ui/data_grid/highlight_dialog.rs delete mode 100644 linux/crates/app/src/ui/data_grid/highlight_popover.rs diff --git a/linux/ARCHITECTURE.md b/linux/ARCHITECTURE.md index df1511b24c..619486d018 100644 --- a/linux/ARCHITECTURE.md +++ b/linux/ARCHITECTURE.md @@ -115,6 +115,13 @@ Every surface that shows rows, the table tab, the SQL editor's results and the k - **Keys.** Two controllers on the column view, from the accelerator table: the `GridCell` owner in the capture phase for the keys GtkListFactoryWidget binds itself (Return, Space, Menu), and the `Grid` owner in the bubble phase, after a focused editor had its turn. A disabled action lets its key go on. Return and a double click reach the grid as the view's `activate`: an editable cell opens its editor, any other cell its value in the detail pane. Typed text opens the editor and the key is forwarded to it, so its input method sees the first key. - **What a host hears.** The grid asks its host only for what it cannot do itself, through its `request` signal: a server sort, an export, a foreign key to follow, a filter rule from a cell, a toast, and "pending changes changed". It also says when its selection and its editing state change, so the table tab's Save stays on while a value is being typed. +### Highlight rules + +Table and query-result grids share the Highlight Rules dialog through `grid.highlight-rules`. +The grid owns the ordered rules; the dialog changes them by UUID. Each rule names a column and its occurrence, so duplicate result names stay distinct. Missing columns keep their rules until that column returns or the user changes it. + +The pure evaluator in `services/grid/highlight.rs` reads the full current values, including pending edits. The first matching row rule sets the row colour; the first cell rule for a column takes precedence over it. NULL and unavailable values stay distinct from text. Colours use libadwaita variables, and selection keeps the theme accent. The cell description announces a highlight; pending edits keep their bold text. + ## Driver layer The contract, the transports, the trust each engine builds, the liveness bounds and the session's health are the core's: `../core/ARCHITECTURE.md`, Driver layer. What the Linux app adds follows. diff --git a/linux/crates/app/src/services/grid/highlight.rs b/linux/crates/app/src/services/grid/highlight.rs index 2cb5d2acfd..6cdd399c87 100644 --- a/linux/crates/app/src/services/grid/highlight.rs +++ b/linux/crates/app/src/services/grid/highlight.rs @@ -1,14 +1,13 @@ -//! Highlight rules: a condition on one column that colours the cell or the -//! whole row that meets it, as the macOS grid's Highlight Rules do -//! (`HighlightRuleSet`). The conditions use the filter strip's operators, -//! read here against the text a cell shows, so a rule matches what the user -//! sees. +use std::borrow::Cow; use serde::{Deserialize, Serialize}; +use tablepro_core::column::ColumnKind; use tablepro_core::filter::{FilterOp, FilterValue}; +use tablepro_core::value::SqlDecimal; use uuid::Uuid; -/// The colours a rule can paint, the macOS set. +use super::GridColumn; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum HighlightColor { @@ -32,7 +31,6 @@ impl HighlightColor { Self::Gray, ]; - /// The style class a painted cell wears. pub fn css_class(self) -> &'static str { match self { Self::Red => "tp-hl-red", @@ -46,13 +44,10 @@ impl HighlightColor { } } -/// What a rule paints. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum HighlightTarget { - /// The whole row. Row, - /// The cell of the rule's column alone. Cell, } @@ -61,8 +56,9 @@ pub struct HighlightRule { pub id: Uuid, pub enabled: bool, pub column: String, + #[serde(default)] + pub column_occurrence: usize, pub op: FilterOp, - /// `None` for the null tests; the operand for every other operator. #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option, pub case_sensitive: bool, @@ -76,6 +72,7 @@ impl HighlightRule { id: Uuid::new_v4(), enabled: true, column: column.into(), + column_occurrence: 0, op: FilterOp::Eq, value: Some(FilterValue::Single(String::new())), case_sensitive: false, @@ -84,12 +81,7 @@ impl HighlightRule { } } - /// Whether the rule says something a row can meet: a column, and the - /// operand its operator takes. pub fn is_valid(&self) -> bool { - if self.column.is_empty() { - return false; - } match (self.op, &self.value) { (FilterOp::IsNull | FilterOp::IsNotNull, _) => true, (FilterOp::In | FilterOp::NotIn, Some(FilterValue::List(items))) => !items.is_empty(), @@ -101,11 +93,9 @@ impl HighlightRule { } } -/// What a row meets: a colour for all of it, and colours for single cells. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RowHighlight { pub row: Option, - /// By the column's position, the first rule that holds for each. pub cells: Vec<(usize, HighlightColor)>, } @@ -115,7 +105,6 @@ impl RowHighlight { self.row.is_none() && self.cells.is_empty() } - /// The colour of the cell in column `column`: its own rule's, else the row's. pub fn color_of(&self, column: usize) -> Option { self.cells .iter() @@ -125,52 +114,65 @@ impl RowHighlight { } } +#[derive(Debug, Clone)] +pub enum HighlightValue<'a> { + Unavailable, + Null, + NonText, + Text(Cow<'a, str>), +} + struct Compiled { column: usize, + kind: ColumnKind, rule: HighlightRule, } -/// The rules that apply to a result's columns, ready to read rows with. #[derive(Default)] pub struct HighlightRules { compiled: Vec, + columns: Vec, } impl HighlightRules { - /// The enabled, valid rules whose column the result has. A rule for a - /// column that is not there waits, and meets nothing meanwhile. - pub fn compile(rules: &[HighlightRule], columns: &[String]) -> Self { - let compiled = rules + pub fn compile(rules: &[HighlightRule], columns: &[GridColumn]) -> Self { + let compiled: Vec = rules .iter() .filter(|rule| rule.enabled && rule.is_valid()) .filter_map(|rule| { columns .iter() - .position(|column| *column == rule.column) - .map(|column| Compiled { + .enumerate() + .filter(|(_, column)| column.name == rule.column) + .nth(rule.column_occurrence) + .map(|(column, definition)| Compiled { column, + kind: definition.column_type.kind.clone(), rule: rule.clone(), }) }) .collect(); - Self { compiled } + let mut columns: Vec = compiled.iter().map(|rule| rule.column).collect(); + columns.sort_unstable(); + columns.dedup(); + Self { compiled, columns } } pub fn is_empty(&self) -> bool { self.compiled.is_empty() } - /// The columns the rules read, which is all a row has to say of itself. pub fn columns(&self) -> impl Iterator + '_ { - self.compiled.iter().map(|compiled| compiled.column) + self.columns.iter().copied() } - /// What `cells` meet, each the text the column shows and `None` for NULL. - pub fn highlight(&self, cells: &[Option<&str>]) -> RowHighlight { + pub fn highlight(&self, cells: &[HighlightValue<'_>]) -> RowHighlight { let mut found = RowHighlight::default(); for compiled in &self.compiled { - let text = cells.get(compiled.column).copied().flatten(); - if !matches(&compiled.rule, text) { + let Some(value) = cells.get(compiled.column) else { + continue; + }; + if !matches(&compiled.rule, &compiled.kind, value) { continue; } match compiled.rule.target { @@ -185,13 +187,15 @@ impl HighlightRules { } } -fn matches(rule: &HighlightRule, text: Option<&str>) -> bool { - let Some(text) = text else { - // NULL meets only the null test. - return rule.op == FilterOp::IsNull; +fn matches(rule: &HighlightRule, kind: &ColumnKind, value: &HighlightValue<'_>) -> bool { + let text = match value { + HighlightValue::Unavailable => return false, + HighlightValue::Null => return rule.op == FilterOp::IsNull, + HighlightValue::NonText => return rule.op == FilterOp::IsNotNull, + HighlightValue::Text(text) => text.as_ref(), }; let sensitive = rule.case_sensitive; - let same = |a: &str, b: &str| compare(a, b, sensitive) == std::cmp::Ordering::Equal; + let same = |a: &str, b: &str| compare(a, b, sensitive, kind.is_numeric()) == std::cmp::Ordering::Equal; let single = || match &rule.value { Some(FilterValue::Single(operand)) => Some(operand.as_str()), _ => None, @@ -201,10 +205,10 @@ fn matches(rule: &HighlightRule, text: Option<&str>) -> bool { FilterOp::IsNotNull => true, FilterOp::Eq => single().is_some_and(|operand| same(text, operand)), FilterOp::NotEq => single().is_some_and(|operand| !same(text, operand)), - FilterOp::Lt => single().is_some_and(|operand| compare(text, operand, sensitive).is_lt()), - FilterOp::LtEq => single().is_some_and(|operand| compare(text, operand, sensitive).is_le()), - FilterOp::Gt => single().is_some_and(|operand| compare(text, operand, sensitive).is_gt()), - FilterOp::GtEq => single().is_some_and(|operand| compare(text, operand, sensitive).is_ge()), + FilterOp::Lt => single().is_some_and(|operand| compare(text, operand, sensitive, true).is_lt()), + FilterOp::LtEq => single().is_some_and(|operand| compare(text, operand, sensitive, true).is_le()), + FilterOp::Gt => single().is_some_and(|operand| compare(text, operand, sensitive, true).is_gt()), + FilterOp::GtEq => single().is_some_and(|operand| compare(text, operand, sensitive, true).is_ge()), FilterOp::Contains => single().is_some_and(|operand| fold(text, sensitive).contains(&fold(operand, sensitive))), FilterOp::StartsWith => { single().is_some_and(|operand| fold(text, sensitive).starts_with(&fold(operand, sensitive))) @@ -225,7 +229,7 @@ fn matches(rule: &HighlightRule, text: Option<&str>) -> bool { }, FilterOp::Between => match &rule.value { Some(FilterValue::Pair(low, high)) => { - compare(text, low, sensitive).is_ge() && compare(text, high, sensitive).is_le() + compare(text, low, sensitive, true).is_ge() && compare(text, high, sensitive, true).is_le() } _ => false, }, @@ -240,36 +244,56 @@ fn fold(text: &str, sensitive: bool) -> String { } } -/// Numbers compare as numbers when both sides read as one, else as text. -fn compare(a: &str, b: &str, sensitive: bool) -> std::cmp::Ordering { - if let (Ok(x), Ok(y)) = (a.trim().parse::(), b.trim().parse::()) - && let Some(order) = x.partial_cmp(&y) - { - return order; +fn compare(a: &str, b: &str, sensitive: bool, numeric: bool) -> std::cmp::Ordering { + if numeric && let (Ok(x), Ok(y)) = (a.trim().parse::(), b.trim().parse::()) { + return x.cmp_numeric(&y); } fold(a, sensitive).cmp(&fold(b, sensitive)) } -/// SQL LIKE: `%` is any run of characters and `_` any one. fn like(text: &str, pattern: &str, sensitive: bool) -> bool { - let text: Vec = fold(text, sensitive).chars().collect(); + let text = fold(text, sensitive); let pattern: Vec = fold(pattern, sensitive).chars().collect(); - fn walk(text: &[char], pattern: &[char]) -> bool { - match pattern.split_first() { - None => text.is_empty(), - Some(('%', rest)) => (0..=text.len()).any(|skip| walk(&text[skip..], rest)), - Some(('_', rest)) => text.split_first().is_some_and(|(_, tail)| walk(tail, rest)), - Some((letter, rest)) => text - .split_first() - .is_some_and(|(head, tail)| head == letter && walk(tail, rest)), + // Each prefix is visited once per character, so repeated wildcards cannot branch exponentially. + let mut reachable = vec![false; pattern.len() + 1]; + reachable[0] = true; + for (index, token) in pattern.iter().enumerate() { + reachable[index + 1] = *token == '%' && reachable[index]; + } + for character in text.chars() { + let mut diagonal = reachable[0]; + reachable[0] = false; + for (index, token) in pattern.iter().enumerate() { + let above = reachable[index + 1]; + reachable[index + 1] = match token { + '%' => reachable[index] || above, + '_' => diagonal, + literal => diagonal && *literal == character, + }; + diagonal = above; } } - walk(&text, &pattern) + reachable[pattern.len()] } #[cfg(test)] mod tests { use super::*; + use crate::services::grid::test_columns::{grid, info}; + + fn columns(names: &[&str]) -> Vec { + names.iter().map(|name| grid(info(name, "numeric"))).collect() + } + + fn cells<'a>(texts: &[Option<&'a str>]) -> Vec> { + texts + .iter() + .map(|text| match text { + Some(text) => HighlightValue::Text(Cow::Borrowed(text)), + None => HighlightValue::Null, + }) + .collect() + } fn rule(op: FilterOp, value: Option) -> HighlightRule { HighlightRule { @@ -284,8 +308,8 @@ mod tests { } fn highlights(rule: HighlightRule, text: Option<&str>) -> bool { - let rules = HighlightRules::compile(&[rule], &["status".to_owned()]); - !rules.highlight(&[text]).is_none() + let rules = HighlightRules::compile(&[rule], &columns(&["status"])); + !rules.highlight(&cells(&[text])).is_none() } #[test] @@ -341,10 +365,10 @@ mod tests { cell.value = single("100"); cell.target = HighlightTarget::Cell; cell.color = HighlightColor::Green; - let columns = ["status".to_owned(), "amount".to_owned()]; + let columns = columns(&["status", "amount"]); let rules = HighlightRules::compile(&[row, cell], &columns); - let found = rules.highlight(&[Some("error"), Some("250")]); + let found = rules.highlight(&cells(&[Some("error"), Some("250")])); assert_eq!(found.row, Some(HighlightColor::Red)); assert_eq!( @@ -353,7 +377,7 @@ mod tests { "the cell's own rule wins" ); assert_eq!(found.color_of(0), Some(HighlightColor::Red)); - assert!(rules.highlight(&[Some("ok"), Some("5")]).is_none()); + assert!(rules.highlight(&cells(&[Some("ok"), Some("5")])).is_none()); } #[test] @@ -364,7 +388,7 @@ mod tests { let mut elsewhere = rule(FilterOp::Eq, single("x")); elsewhere.column = "missing".to_owned(); - let rules = HighlightRules::compile(&[off, blank, elsewhere], &["status".to_owned()]); + let rules = HighlightRules::compile(&[off, blank, elsewhere], &columns(&["status"])); assert!(rules.is_empty()); } @@ -375,9 +399,9 @@ mod tests { first.color = HighlightColor::Blue; let mut second = rule(FilterOp::Contains, single("a")); second.color = HighlightColor::Red; - let rules = HighlightRules::compile(&[first, second], &["status".to_owned()]); + let rules = HighlightRules::compile(&[first, second], &columns(&["status"])); - assert_eq!(rules.highlight(&[Some("a")]).row, Some(HighlightColor::Blue)); + assert_eq!(rules.highlight(&cells(&[Some("a")])).row, Some(HighlightColor::Blue)); } #[test] @@ -391,4 +415,95 @@ mod tests { assert_eq!(serde_json::from_str::(&text).expect("decode"), original); } + + #[test] + fn repeated_wildcards_do_not_branch_exponentially() { + assert!(!like(&"a".repeat(1_000), "%a%a%a%b", true)); + assert!(like("é界", "__", true)); + assert!(like("", "%%%", true)); + assert!(!like("", "_", true)); + assert!(like("error", "%r", true)); + assert!(!like("errors", "%r", true)); + } + + #[test] + fn numeric_rules_preserve_large_integer_and_decimal_digits() { + let smaller = "9007199254740992"; + let larger = "9007199254740993"; + assert!(!highlights(rule(FilterOp::Eq, single(smaller)), Some(larger))); + assert!(highlights(rule(FilterOp::Gt, single(smaller)), Some(larger))); + assert!(!highlights( + rule(FilterOp::In, Some(FilterValue::List(vec![smaller.into()]))), + Some(larger) + )); + assert!(!highlights( + rule( + FilterOp::Between, + Some(FilterValue::Pair(smaller.into(), smaller.into())) + ), + Some(larger) + )); + assert!(highlights( + rule(FilterOp::Gt, single("0.12345678901234567890")), + Some("0.12345678901234567891") + )); + } + + #[test] + fn text_equality_keeps_numeric_looking_strings_distinct() { + let columns = [grid(info("status", "text"))]; + let equal = HighlightRules::compile(&[rule(FilterOp::Eq, single("1"))], &columns); + assert!(equal.highlight(&cells(&[Some("01")])).is_none()); + let order = HighlightRules::compile(&[rule(FilterOp::Gt, single("9"))], &columns); + assert!(!order.highlight(&cells(&[Some("10")])).is_none()); + } + + #[test] + fn duplicate_names_resolve_by_occurrence_and_wait_if_missing() { + let mut second = rule(FilterOp::Eq, single("2")); + second.column_occurrence = 1; + second.target = HighlightTarget::Cell; + let rules = HighlightRules::compile(&[second.clone()], &columns(&["status", "status"])); + let found = rules.highlight(&cells(&[Some("1"), Some("2")])); + assert_eq!(found.color_of(0), None); + assert_eq!(found.color_of(1), Some(HighlightColor::Yellow)); + assert!(HighlightRules::compile(&[second], &columns(&["status"])).is_empty()); + } + + #[test] + fn unavailable_and_missing_values_are_not_null() { + let rules = HighlightRules::compile(&[rule(FilterOp::IsNull, None)], &columns(&["status"])); + assert!(rules.highlight(&[]).is_none()); + assert!(rules.highlight(&[HighlightValue::Unavailable]).is_none()); + assert!(rules.highlight(&[HighlightValue::NonText]).is_none()); + assert!(!rules.highlight(&[HighlightValue::Null]).is_none()); + let rules = HighlightRules::compile(&[rule(FilterOp::IsNotNull, None)], &columns(&["status"])); + assert!(!rules.highlight(&[HighlightValue::NonText]).is_none()); + assert!(rules.highlight(&[HighlightValue::Unavailable]).is_none()); + } + + #[test] + fn matching_uses_full_values_and_never_binary_placeholders() { + let long = format!("{}tail", "x".repeat(2_000)); + assert!(highlights(rule(FilterOp::EndsWith, single("tail")), Some(&long))); + let rules = HighlightRules::compile(&[rule(FilterOp::Contains, single("byte"))], &columns(&["status"])); + assert!(rules.highlight(&[HighlightValue::NonText]).is_none()); + } + + #[test] + fn an_empty_column_name_is_still_addressable() { + let mut rule = rule(FilterOp::Eq, single("1")); + rule.column.clear(); + let rules = HighlightRules::compile(&[rule], &columns(&[""])); + assert!(!rules.highlight(&cells(&[Some("1")])).is_none()); + } + + #[test] + fn rules_read_each_column_only_once() { + let rules = HighlightRules::compile( + &[rule(FilterOp::Eq, single("1")), rule(FilterOp::Gt, single("2"))], + &columns(&["status"]), + ); + assert_eq!(rules.columns().collect::>(), [0]); + } } diff --git a/linux/crates/app/src/services/grid/mod.rs b/linux/crates/app/src/services/grid/mod.rs index 8a1d2bf641..a0eb86f413 100644 --- a/linux/crates/app/src/services/grid/mod.rs +++ b/linux/crates/app/src/services/grid/mod.rs @@ -47,7 +47,7 @@ pub use self::find_matches::{FindMatch, find_matches}; pub use self::grid_column::{CellDisplay, GridColumn, grid_columns}; pub use self::grid_row_id::GridRowId; pub use self::hex_dump::hex_dump; -pub use self::highlight::{HighlightColor, HighlightRule, HighlightRules, HighlightTarget}; +pub use self::highlight::{HighlightColor, HighlightRule, HighlightRules, HighlightTarget, HighlightValue}; pub use self::result_refusal::ResultRefusal; pub use self::row_key_builder::RowKeyBuilder; pub use self::row_snapshot::RowSnapshot; diff --git a/linux/crates/app/src/ui/browse_tab/imp.rs b/linux/crates/app/src/ui/browse_tab/imp.rs index f16c50412c..b6c8158638 100644 --- a/linux/crates/app/src/ui/browse_tab/imp.rs +++ b/linux/crates/app/src/ui/browse_tab/imp.rs @@ -56,8 +56,6 @@ pub struct BrowseTab { #[template_child] pub filter_button: TemplateChild, #[template_child] - pub highlight_button: TemplateChild, - #[template_child] pub filter_badge: TemplateChild, #[template_child] pub page_size_dropdown: TemplateChild, diff --git a/linux/crates/app/src/ui/browse_tab/layout.rs b/linux/crates/app/src/ui/browse_tab/layout.rs index 95a8522f33..19892e498b 100644 --- a/linux/crates/app/src/ui/browse_tab/layout.rs +++ b/linux/crates/app/src/ui/browse_tab/layout.rs @@ -73,6 +73,7 @@ fn more_menu(page_sizes: &[u64]) -> gio::Menu { actions.append(Some(&gettext("_Filter Rows")), Some("browse.filter")); actions.append_item(&export); actions.append(Some(&gettext("_Count Rows")), Some("browse.count-rows")); + actions.append(Some(&gettext("_Highlight Rules…")), Some("grid.highlight-rules")); let sizes = gio::Menu::new(); for size in page_sizes { let item = gio::MenuItem::new(Some(&format_thousands(*size)), None); @@ -311,6 +312,18 @@ mod tests { assert_eq!(read(export, "accel").as_deref(), Some("e")); } + #[test] + fn the_narrow_menu_keeps_highlight_rules_available() { + let actions = more_menu(&[]).item_link(0, "section").expect("actions"); + assert!((0..actions.n_items()).any(|item| { + actions + .item_attribute_value(item, "action", None) + .and_then(|value| value.get::()) + .as_deref() + == Some("grid.highlight-rules") + })); + } + #[gtk4::test] fn the_dropdown_shows_a_page_size_set_in_preferences() { let dropdown = gtk::DropDown::default(); diff --git a/linux/crates/app/src/ui/browse_tab/mod.rs b/linux/crates/app/src/ui/browse_tab/mod.rs index d43948f7c8..3992ec5199 100644 --- a/linux/crates/app/src/ui/browse_tab/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/mod.rs @@ -164,14 +164,6 @@ impl BrowseTab { tasks: init.tasks.clone(), }, ); - { - let weak = grid.downgrade(); - tab.imp().highlight_button.set_create_popup_func(move |button| { - if let Some(grid) = weak.upgrade() { - button.set_popover(Some(&crate::ui::data_grid::highlight_rules_popover(&grid))); - } - }); - } let link_changes = init.session.link_changes(); let model = BrowseModel { this: tab.downgrade(), 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..ad76c64322 100644 --- a/linux/crates/app/src/ui/data_grid/grid_actions.rs +++ b/linux/crates/app/src/ui/data_grid/grid_actions.rs @@ -72,6 +72,7 @@ pub fn install(grid: &DataGrid) { } }); add(grid, "columns", column_chooser::present); + add(grid, "highlight-rules", super::highlight_dialog::present); grid.edit().install_actions(grid); copy::install_actions(grid); references::install_actions(grid); 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 93b1471d6e..06cf43c3d6 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -280,12 +280,23 @@ impl GridCell { let numbers = paint.numbers.get(); display.set_xalign(if numbers { 1.0 } else { 0.0 }); set_class(display, "numeric", numbers); - // Adwaita's own warning colour, beside the bold, so a changed value - // reads apart from the rest without a tint of the app's own. - set_class(display, "warning", text_mark == TextMark::Modified); + // Tinted backgrounds need full-opacity text; italic, bold and strikeout keep their meaning. + if colour.is_some() { + display.remove_css_class("dimmed"); + } + // Warning text loses contrast over some highlights; bold still marks the edit. + set_class(display, "warning", text_mark == TextMark::Modified && colour.is_none()); // On the cell, since GtkColumnViewCell passes on no accessible // property of its own. - match cell_description(mark.state, null) { + let description = match (cell_description(mark.state, null), colour) { + (Some(state), Some(colour)) => Some(crate::i18n::gettext_f( + "{state}. {highlight}", + &[("state", &state), ("highlight", &highlight_description(colour))], + )), + (None, Some(colour)) => Some(highlight_description(colour)), + (state, None) => state, + }; + match description { Some(description) => self.update_property(&[gtk::accessible::Property::Description(&description)]), None => self.reset_property(gtk::AccessibleProperty::Description), } @@ -367,3 +378,16 @@ pub(crate) fn holds_window_focus(widget: >k::Widget) -> bool { .and_then(|window| gtk::prelude::GtkWindowExt::focus(&window)) .is_some_and(|focus| focus == *widget || focus.is_ancestor(widget)) } + +fn highlight_description(colour: HighlightColor) -> String { + use crate::i18n::gettext; + match colour { + HighlightColor::Red => gettext("Highlighted red"), + HighlightColor::Orange => gettext("Highlighted orange"), + HighlightColor::Yellow => gettext("Highlighted yellow"), + HighlightColor::Green => gettext("Highlighted green"), + HighlightColor::Blue => gettext("Highlighted blue"), + HighlightColor::Purple => gettext("Highlighted purple"), + HighlightColor::Gray => gettext("Highlighted gray"), + } +} diff --git a/linux/crates/app/src/ui/data_grid/highlight.rs b/linux/crates/app/src/ui/data_grid/highlight.rs index ca3d21d777..5f9bd76e42 100644 --- a/linux/crates/app/src/ui/data_grid/highlight.rs +++ b/linux/crates/app/src/ui/data_grid/highlight.rs @@ -1,62 +1,119 @@ -//! Highlight rules on the grid: the rules the user wrote for the table or -//! result, compiled against its columns, and the colour each cell draws -//! from them (`HighlightRules`). - +use std::borrow::Cow; use std::rc::Rc; +use gtk4::prelude::*; use gtk4::subclass::prelude::*; +use tablepro_core::Value; use super::{DataGrid, GridRow}; -use crate::services::grid::display_text::display_text; -use crate::services::grid::{HighlightColor, HighlightRule, HighlightRules}; +use crate::services::grid::display_text::whole_text; +use crate::services::grid::{HighlightColor, HighlightRule, HighlightRules, HighlightValue}; impl DataGrid { - /// Paint rows and cells by `rules`, which replace the ones held. pub fn set_highlight_rules(&self, rules: Vec) { + if *self.imp().highlight_source.borrow() == rules { + return; + } self.imp().highlight_source.replace(rules); self.compile_highlights(); self.redraw(); + self.emit_by_name::<()>("highlight-rules-changed", &[]); } pub fn highlight_rules(&self) -> Vec { self.imp().highlight_source.borrow().clone() } - /// Match the rules to the columns the grid has now. A rule for a - /// column that another read lacks waits and paints nothing. pub(super) fn compile_highlights(&self) { - let names: Vec = self.grid_columns().iter().map(|column| column.name.clone()).collect(); - let compiled = HighlightRules::compile(&self.imp().highlight_source.borrow(), &names); + let compiled = HighlightRules::compile(&self.imp().highlight_source.borrow(), &self.grid_columns()); self.imp().highlights.replace(Rc::new(compiled)); } - /// The colour the cell of `row` in `column` draws, if a rule holds for it. pub(super) fn highlight_of(&self, row: &GridRow, column: usize) -> Option { let rules = self.imp().highlights.borrow().clone(); if rules.is_empty() { return None; } let columns = self.grid_columns(); - // A rule reads only its own column's text, so the others stay empty. - let mut texts: Vec> = vec![None; columns.len()]; + let mut values = vec![HighlightValue::Unavailable; columns.len()]; let tracked = self.tracked(); let mut scratch = String::new(); + let stored = row.cells(); for read in rules.columns() { let Some(definition) = columns.get(read) else { continue; }; - texts[read] = tracked.with_value(row, read, |value, computed| { - if computed.is_some() || value.is_null() { - return None; + if stored.as_ref().is_some_and(|cells| read >= cells.len()) { + continue; + } + values[read] = tracked.with_value(row, read, |value, computed| { + if computed.is_some() { + return HighlightValue::Unavailable; + } + match value { + Value::Null => HighlightValue::Null, + Value::Bytes(_) => HighlightValue::NonText, + Value::Undecodable(_) => HighlightValue::Unavailable, + value => HighlightValue::Text(Cow::Owned( + whole_text(value, &definition.column_type, &mut scratch).to_owned(), + )), } - Some( - display_text(value, &definition.column_type, &mut scratch) - .text - .to_owned(), - ) }); } - let cells: Vec> = texts.iter().map(Option::as_deref).collect(); - rules.highlight(&cells).color_of(column) + rules.highlight(&values).color_of(column) + } +} + +#[cfg(test)] +mod tests { + use tablepro_core::edit::CellInput; + use tablepro_core::filter::{FilterOp, FilterValue}; + + use super::*; + use crate::services::tracker_edit::TrackerEdit; + use crate::ui::data_grid::test_grid::{Grid, key, two_text_columns}; + + #[gtk4::test] + fn highlights_read_past_the_display_cut_and_follow_pending_values() { + let long = format!("{}tail", "x".repeat(2_000)); + let grid = Grid::open(two_text_columns(), vec![vec![Value::Int(1), Value::Text(long.clone())]]); + let mut rule = HighlightRule::new("name"); + rule.op = FilterOp::EndsWith; + rule.value = Some(FilterValue::Single("tail".into())); + grid.grid.set_highlight_rules(vec![rule]); + let row = grid.grid.store().row(0).expect("a row"); + assert_eq!(grid.grid.highlight_of(&row, 1), Some(HighlightColor::Yellow)); + + let delta = grid.tracker.apply(TrackerEdit::Cell { + row_key: key(1), + col: 1, + original: Value::Text(long), + value: CellInput::Value(Value::Text("different".into())), + }); + grid.grid.apply_delta(&delta); + assert_eq!(grid.grid.highlight_of(&row, 1), None); + } + + #[gtk4::test] + fn computed_and_absent_cells_do_not_match_null_rules() { + let grid = Grid::open(two_text_columns(), vec![vec![Value::Int(1), Value::Text("old".into())]]); + let mut rule = HighlightRule::new("name"); + rule.op = FilterOp::IsNull; + rule.value = None; + grid.grid.set_highlight_rules(vec![rule]); + let row = grid.grid.store().row(0).expect("a row"); + let delta = grid.tracker.apply(TrackerEdit::Cell { + row_key: key(1), + col: 1, + original: Value::Text("old".into()), + value: CellInput::Default, + }); + grid.grid.apply_delta(&delta); + assert_eq!(grid.grid.highlight_of(&row, 1), None); + + let absent = GridRow::new(super::super::RowData::result(vec![Value::Int(2)].into())); + assert_eq!(grid.grid.highlight_of(&absent, 1), None); + let null = GridRow::new(super::super::RowData::result(vec![Value::Int(2), Value::Null].into())); + assert_eq!(grid.grid.highlight_of(&null, 1), Some(HighlightColor::Yellow)); } } diff --git a/linux/crates/app/src/ui/data_grid/highlight_dialog.rs b/linux/crates/app/src/ui/data_grid/highlight_dialog.rs new file mode 100644 index 0000000000..c8d74524c5 --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/highlight_dialog.rs @@ -0,0 +1,958 @@ +use std::cell::{Cell, OnceCell, RefCell}; +use std::collections::HashMap; + +use gtk4 as gtk; +use gtk4::{gdk, gio, glib}; +use libadwaita as adw; +use libadwaita::prelude::*; +use libadwaita::subclass::prelude::*; +use tablepro_core::filter::{FilterOp, FilterValue}; +use uuid::Uuid; + +use super::DataGrid; +use crate::i18n::{gettext, gettext_f}; +use crate::services::grid::{HighlightColor, HighlightRule, HighlightTarget}; +use crate::ui::handler_guard::HandlerGuard; + +const OPERATORS: [FilterOp; 17] = [ + FilterOp::Eq, + FilterOp::NotEq, + FilterOp::Gt, + FilterOp::GtEq, + FilterOp::Lt, + FilterOp::LtEq, + FilterOp::Contains, + FilterOp::StartsWith, + FilterOp::EndsWith, + FilterOp::Like, + FilterOp::NotLike, + FilterOp::Ilike, + FilterOp::IsNull, + FilterOp::IsNotNull, + FilterOp::In, + FilterOp::NotIn, + FilterOp::Between, +]; + +fn operator_label(op: FilterOp) -> String { + match op { + FilterOp::Eq => gettext("equals"), + FilterOp::NotEq => gettext("doesn't equal"), + FilterOp::Gt => gettext("greater than"), + FilterOp::GtEq => gettext("at least"), + FilterOp::Lt => gettext("less than"), + FilterOp::LtEq => gettext("at most"), + FilterOp::Contains => gettext("contains"), + FilterOp::StartsWith => gettext("starts with"), + FilterOp::EndsWith => gettext("ends with"), + FilterOp::Like => gettext("matches pattern"), + FilterOp::NotLike => gettext("doesn't match pattern"), + FilterOp::Ilike => gettext("matches pattern, ignoring case"), + FilterOp::IsNull => gettext("is NULL"), + FilterOp::IsNotNull => gettext("is not NULL"), + FilterOp::In => gettext("is one of"), + FilterOp::NotIn => gettext("is none of"), + FilterOp::Between => gettext("between"), + } +} + +fn color_label(color: HighlightColor) -> String { + match color { + HighlightColor::Red => gettext("Red"), + HighlightColor::Orange => gettext("Orange"), + HighlightColor::Yellow => gettext("Yellow"), + HighlightColor::Green => gettext("Green"), + HighlightColor::Blue => gettext("Blue"), + HighlightColor::Purple => gettext("Purple"), + HighlightColor::Gray => gettext("Gray"), + } +} + +fn blank_for(op: FilterOp) -> Option { + match op { + FilterOp::IsNull | FilterOp::IsNotNull => None, + FilterOp::In | FilterOp::NotIn => Some(FilterValue::List(vec![String::new()])), + FilterOp::Between => Some(FilterValue::Pair(String::new(), String::new())), + _ => Some(FilterValue::Single(String::new())), + } +} + +fn operand_summary(value: &Option) -> String { + let short = |text: &str| { + let mut chars = text.chars(); + let mut result: String = chars.by_ref().take(40).collect(); + if chars.next().is_some() { + result.push('…'); + } + result + }; + match value { + None => String::new(), + Some(FilterValue::Single(text)) => short(text), + Some(FilterValue::Pair(low, high)) => { + gettext_f("{from} to {to}", &[("from", &short(low)), ("to", &short(high))]) + } + Some(FilterValue::List(values)) => { + let mut result = values + .iter() + .take(3) + .map(|value| short(value)) + .collect::>() + .join(", "); + if values.len() > 3 { + result.push('…'); + } + result + } + } +} + +fn operand_for(op: FilterOp, value: &Option) -> Option { + match (op, value) { + (FilterOp::IsNull | FilterOp::IsNotNull, _) => None, + (FilterOp::In | FilterOp::NotIn, Some(FilterValue::List(_))) + | (FilterOp::Between, Some(FilterValue::Pair(_, _))) => value.clone(), + (FilterOp::In | FilterOp::NotIn | FilterOp::Between, _) => blank_for(op), + (_, Some(FilterValue::Single(_))) => value.clone(), + _ => blank_for(op), + } +} + +mod imp { + use super::*; + + #[derive(Default)] + pub struct HighlightDialog { + pub(super) grid: glib::WeakRef, + pub(super) list: OnceCell, + pub(super) add: OnceCell, + pub(super) rows: RefCell>>, + pub(super) watches: RefCell>, + pub(super) updating: Cell, + pub(super) queued: Cell, + pub(super) drag_id: OnceCell, + } + + #[glib::object_subclass] + impl ObjectSubclass for HighlightDialog { + const NAME: &'static str = "TableProHighlightDialog"; + type Type = super::HighlightDialog; + type ParentType = adw::Dialog; + } + + impl ObjectImpl for HighlightDialog { + fn dispose(&self) { + self.watches.borrow_mut().clear(); + } + } + impl WidgetImpl for HighlightDialog {} + impl AdwDialogImpl for HighlightDialog {} +} + +glib::wrapper! { + pub struct HighlightDialog(ObjectSubclass) + @extends adw::Dialog, gtk::Widget, + @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget; +} + +pub(crate) fn build(grid: &DataGrid) -> adw::Dialog { + let dialog: HighlightDialog = glib::Object::new(); + dialog.setup(grid); + dialog.upcast() +} + +pub(crate) fn present(grid: &DataGrid) { + if let Some(dialog) = grid.imp().highlight_dialog.upgrade() { + dialog.present(Some(grid)); + return; + } + let dialog = build(grid); + grid.imp().highlight_dialog.set(Some(&dialog)); + dialog.present(Some(grid)); +} + +impl HighlightDialog { + fn setup(&self, grid: &DataGrid) { + self.imp().grid.set(Some(grid)); + let _ = self.imp().drag_id.set(Uuid::new_v4()); + self.set_title(&gettext("Highlight Rules")); + self.set_content_width(480); + self.set_content_height(600); + let header = adw::HeaderBar::new(); + let add = gtk::Button::with_label(&gettext("Add Rule")); + add.add_css_class("suggested-action"); + add.set_sensitive(!grid.grid_columns().is_empty()); + header.pack_end(&add); + let list = gtk::Box::new(gtk::Orientation::Vertical, 18); + list.set_margin_top(18); + list.set_margin_bottom(18); + list.set_margin_start(18); + list.set_margin_end(18); + let description = gtk::Label::builder() + .label(gettext( + "The first matching rule sets the colour. A cell rule takes priority over a row rule.", + )) + .wrap(true) + .xalign(0.0) + .build(); + description.add_css_class("dimmed"); + let body = gtk::Box::new(gtk::Orientation::Vertical, 0); + description.set_margin_start(18); + description.set_margin_end(18); + description.set_margin_top(18); + body.append(&description); + body.append(&list); + let clamp = adw::Clamp::builder().maximum_size(600).child(&body).build(); + let scroll = gtk::ScrolledWindow::builder() + .hscrollbar_policy(gtk::PolicyType::Never) + .child(&clamp) + .build(); + let toolbar = adw::ToolbarView::new(); + toolbar.add_top_bar(&header); + toolbar.set_content(Some(&scroll)); + self.set_child(Some(&toolbar)); + self.set_focus(Some(&add)); + let _ = self.imp().list.set(list); + let _ = self.imp().add.set(add.clone()); + add.connect_clicked(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |_| dialog.add_rule() + )); + self.rebuild(None); + let columns = grid.column_view().columns(); + let handler = columns.connect_items_changed(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |_, _, _, _| dialog.queue_rebuild() + )); + self.imp() + .watches + .borrow_mut() + .push(HandlerGuard::new(&columns, handler)); + let handler = grid.connect_local( + "highlight-rules-changed", + false, + glib::clone!( + #[weak(rename_to = dialog)] + self, + #[upgrade_or] + None, + move |_| { + if !dialog.imp().updating.get() { + dialog.queue_rebuild(); + } + None + } + ), + ); + self.imp().watches.borrow_mut().push(HandlerGuard::new(grid, handler)); + self.connect_closed(|dialog| { + dialog.imp().watches.borrow_mut().clear(); + if let Some(grid) = dialog.imp().grid.upgrade() { + grid.imp().highlight_dialog.set(None::<&adw::Dialog>); + } + }); + } + + fn queue_rebuild(&self) { + if self.imp().queued.replace(true) { + return; + } + let weak = self.downgrade(); + glib::idle_add_local_once(move || { + if let Some(dialog) = weak.upgrade() { + dialog.imp().queued.set(false); + let focus = dialog.focus().and_then(|focus| { + dialog.imp().rows.borrow().iter().find_map(|(id, row)| { + row.upgrade() + .filter(|row| focus.is_ancestor(row) || focus == *row.upcast_ref::()) + .map(|_| *id) + }) + }); + dialog.rebuild(focus); + } + }); + } + + fn publish(&self, grid: &DataGrid, rules: Vec) { + self.imp().updating.set(true); + grid.set_highlight_rules(rules); + self.imp().updating.set(false); + } + + fn add_rule(&self) { + let Some(grid) = self.imp().grid.upgrade() else { + return; + }; + let Some(first) = grid.grid_columns().first().cloned() else { + return; + }; + let rule = HighlightRule::new(first.name.clone()); + let id = rule.id; + let mut rules = grid.highlight_rules(); + rules.push(rule); + self.publish(&grid, rules); + self.rebuild(Some(id)); + } + + fn edit(&self, id: Uuid, change: impl FnOnce(&mut HighlightRule)) { + let Some(grid) = self.imp().grid.upgrade() else { + return; + }; + let mut rules = grid.highlight_rules(); + let Some(rule) = rules.iter_mut().find(|rule| rule.id == id) else { + return; + }; + change(rule); + self.publish(&grid, rules); + self.update_summary(id); + } + + fn update_summary(&self, id: Uuid) { + let Some(grid) = self.imp().grid.upgrade() else { + return; + }; + let Some(rule) = grid.highlight_rules().into_iter().find(|rule| rule.id == id) else { + return; + }; + let Some(row) = self.imp().rows.borrow().get(&id).and_then(glib::WeakRef::upgrade) else { + return; + }; + let available = grid + .grid_columns() + .iter() + .filter(|column| column.name == rule.column) + .nth(rule.column_occurrence) + .is_some(); + let summary = if !available { + gettext("Column unavailable. Choose another column to use this rule.") + } else if !rule.enabled { + gettext("Disabled") + } else if !rule.is_valid() { + gettext("Enter a value to use this rule.") + } else { + let target = match rule.target { + HighlightTarget::Row => gettext("Row"), + HighlightTarget::Cell => gettext("Cell"), + }; + gettext_f( + "{column} {condition} {value}; {target}, {colour}", + &[ + ("column", &rule.column), + ("condition", &operator_label(rule.op)), + ("value", &operand_summary(&rule.value)), + ("target", &target), + ("colour", &color_label(rule.color)), + ], + ) + }; + row.set_subtitle(&summary); + } + + fn rebuild(&self, focus: Option) { + let Some(list) = self.imp().list.get() else { + return; + }; + let expanded: Vec = self + .imp() + .rows + .borrow() + .iter() + .filter_map(|(id, row)| row.upgrade().filter(|row| row.is_expanded()).map(|_| *id)) + .collect(); + while let Some(child) = list.first_child() { + list.remove(&child); + } + self.imp().rows.borrow_mut().clear(); + let Some(grid) = self.imp().grid.upgrade() else { + return; + }; + let rules = grid.highlight_rules(); + if let Some(add) = self.imp().add.get() { + add.set_sensitive(!grid.grid_columns().is_empty()); + } + if rules.is_empty() { + let empty = adw::StatusPage::builder() + .title(gettext("No Highlight Rules")) + .description(gettext("Add a rule to colour matching rows or cells.")) + .icon_name("document-edit-symbolic") + .build(); + list.append(&empty); + } + for (index, rule) in rules.iter().enumerate() { + let group = adw::PreferencesGroup::new(); + let row = self.rule_row(rule, index, rules.len()); + group.add(&row); + list.append(&group); + self.imp().rows.borrow_mut().insert(rule.id, row.downgrade()); + self.update_summary(rule.id); + row.set_expanded(expanded.contains(&rule.id) || focus == Some(rule.id)); + if focus == Some(rule.id) { + row.grab_focus(); + } + } + if rules.is_empty() + && focus.is_some() + && let Some(add) = self.imp().add.get() + { + add.grab_focus(); + } + } + + fn remove(&self, id: Uuid) { + let Some(grid) = self.imp().grid.upgrade() else { + return; + }; + let mut rules = grid.highlight_rules(); + let Some(index) = rules.iter().position(|rule| rule.id == id) else { + return; + }; + rules.remove(index); + let next = rules + .get(index.min(rules.len().saturating_sub(1))) + .map(|rule| rule.id) + .unwrap_or(id); + self.publish(&grid, rules); + self.rebuild(Some(next)); + } + + fn move_rule(&self, id: Uuid, before: Uuid) -> bool { + let Some(grid) = self.imp().grid.upgrade() else { + return false; + }; + let mut rules = grid.highlight_rules(); + let (Some(from), Some(to)) = ( + rules.iter().position(|rule| rule.id == id), + rules.iter().position(|rule| rule.id == before), + ) else { + return false; + }; + if from == to { + return false; + } + let rule = rules.remove(from); + rules.insert(to, rule); + self.publish(&grid, rules); + self.rebuild(Some(id)); + true + } + + fn step(&self, id: Uuid, up: bool) { + let Some(grid) = self.imp().grid.upgrade() else { + return; + }; + let rules = grid.highlight_rules(); + let Some(index) = rules.iter().position(|rule| rule.id == id) else { + return; + }; + let next = if up { index.checked_sub(1) } else { index.checked_add(1) }; + if let Some(target) = next.and_then(|next| rules.get(next)) { + self.move_rule(id, target.id); + } + } + + fn rule_row(&self, rule: &HighlightRule, index: usize, count: usize) -> adw::ExpanderRow { + let id = rule.id; + let row = adw::ExpanderRow::builder() + .title(gettext_f("Rule {number}", &[("number", &(index + 1).to_string())])) + .use_markup(false) + .subtitle_lines(2) + .build(); + self.order_controls(&row, id, index, count); + let enabled = adw::SwitchRow::builder() + .title(gettext("Enabled")) + .active(rule.enabled) + .build(); + enabled.connect_active_notify(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |row| dialog.edit(id, |rule| rule.enabled = row.is_active()) + )); + row.add_row(&enabled); + self.column_control(&row, rule); + let condition = combo( + &gettext("Condition"), + &OPERATORS.iter().map(|op| operator_label(*op)).collect::>(), + OPERATORS.iter().position(|op| *op == rule.op).unwrap_or(0), + ); + condition.connect_selected_notify(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |row| { + if let Some(op) = OPERATORS.get(row.selected() as usize).copied() { + dialog.edit(id, |rule| { + rule.op = op; + rule.value = blank_for(op); + }); + dialog.rebuild(Some(id)); + } + } + )); + row.add_row(&condition); + self.value_controls(&row, rule); + let color = combo( + &gettext("Colour"), + &HighlightColor::ALL + .iter() + .map(|color| color_label(*color)) + .collect::>(), + HighlightColor::ALL + .iter() + .position(|color| *color == rule.color) + .unwrap_or(0), + ); + color.connect_selected_notify(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |row| { + if let Some(color) = HighlightColor::ALL.get(row.selected() as usize).copied() { + dialog.edit(id, |rule| rule.color = color); + } + } + )); + row.add_row(&color); + let target = combo( + &gettext("Apply to"), + &[gettext("Row"), gettext("Cell")], + usize::from(rule.target == HighlightTarget::Cell), + ); + target.connect_selected_notify(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |row| dialog.edit(id, |rule| { + rule.target = if row.selected() == 1 { + HighlightTarget::Cell + } else { + HighlightTarget::Row + }; + }) + )); + row.add_row(&target); + let case = adw::SwitchRow::builder() + .title(gettext("Match Case")) + .active(rule.case_sensitive) + .sensitive(!matches!( + rule.op, + FilterOp::IsNull | FilterOp::IsNotNull | FilterOp::Ilike + )) + .build(); + case.connect_active_notify(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |row| dialog.edit(id, |rule| rule.case_sensitive = row.is_active()) + )); + row.add_row(&case); + row + } + + fn column_control(&self, row: &adw::ExpanderRow, rule: &HighlightRule) { + let Some(grid) = self.imp().grid.upgrade() else { + return; + }; + let columns = grid.grid_columns(); + let choices: Vec<(String, usize)> = columns + .iter() + .enumerate() + .map(|(index, column)| { + ( + column.name.clone(), + columns[..index] + .iter() + .filter(|other| other.name == column.name) + .count(), + ) + }) + .collect(); + let mut labels: Vec = choices + .iter() + .map(|(name, occurrence)| { + if choices.iter().filter(|(other, _)| other == name).count() > 1 { + gettext_f( + "{column} ({number})", + &[("column", name), ("number", &(occurrence + 1).to_string())], + ) + } else { + name.clone() + } + }) + .collect(); + let selected = choices + .iter() + .position(|(name, occurrence)| *name == rule.column && *occurrence == rule.column_occurrence) + .unwrap_or_else(|| { + labels.push(gettext_f("{column} (unavailable)", &[("column", &rule.column)])); + labels.len() - 1 + }); + let column = combo(&gettext("Column"), &labels, selected); + let id = rule.id; + column.connect_selected_notify(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |row| { + if let Some((name, occurrence)) = choices.get(row.selected() as usize) { + dialog.edit(id, |rule| { + rule.column.clone_from(name); + rule.column_occurrence = *occurrence; + }); + } + } + )); + row.add_row(&column); + } + + fn value_controls(&self, row: &adw::ExpanderRow, rule: &HighlightRule) { + let id = rule.id; + let value = operand_for(rule.op, &rule.value); + match &value { + None => {} + Some(FilterValue::Single(value)) => { + let entry = entry(&gettext("Value"), value); + entry.connect_changed(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |entry| dialog.edit(id, |rule| rule.value = + Some(FilterValue::Single(entry.text().to_string()))) + )); + row.add_row(&entry); + } + Some(FilterValue::Pair(low, high)) => { + for (first, title, text) in [(true, gettext("From"), low), (false, gettext("To"), high)] { + let entry = entry(&title, text); + entry.connect_changed(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |entry| dialog.edit(id, |rule| { + rule.value = operand_for(rule.op, &rule.value); + if let Some(FilterValue::Pair(low, high)) = &mut rule.value { + if first { + *low = entry.text().to_string(); + } else { + *high = entry.text().to_string(); + } + } + }) + )); + row.add_row(&entry); + } + } + Some(FilterValue::List(values)) => { + for (index, text) in values.iter().enumerate() { + let entry = entry( + &gettext_f("Value {number}", &[("number", &(index + 1).to_string())]), + text, + ); + entry.connect_changed(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |entry| dialog.edit(id, |rule| { + rule.value = operand_for(rule.op, &rule.value); + if let Some(FilterValue::List(values)) = &mut rule.value + && let Some(value) = values.get_mut(index) + { + *value = entry.text().to_string(); + } + }) + )); + let remove = gtk::Button::builder() + .icon_name("edit-delete-symbolic") + .valign(gtk::Align::Center) + .tooltip_text(gettext("Remove Value")) + .build(); + remove.add_css_class("flat"); + remove.connect_clicked(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |_| { + dialog.edit(id, |rule| { + rule.value = operand_for(rule.op, &rule.value); + if let Some(FilterValue::List(values)) = &mut rule.value + && index < values.len() + { + values.remove(index); + } + }); + dialog.rebuild(Some(id)); + } + )); + entry.add_suffix(&remove); + row.add_row(&entry); + } + let add = adw::ButtonRow::builder() + .title(gettext("Add Value")) + .start_icon_name("list-add-symbolic") + .build(); + add.connect_activated(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |_| { + dialog.edit(id, |rule| { + rule.value = operand_for(rule.op, &rule.value); + if let Some(FilterValue::List(values)) = &mut rule.value { + values.push(String::new()); + } + }); + dialog.rebuild(Some(id)); + } + )); + row.add_row(&add); + } + } + } + + fn order_controls(&self, row: &adw::ExpanderRow, id: Uuid, index: usize, count: usize) { + let menu = gio::Menu::new(); + menu.append(Some(&gettext("Move Up")), Some("rule.up")); + menu.append(Some(&gettext("Move Down")), Some("rule.down")); + menu.append(Some(&gettext("Remove Rule")), Some("rule.remove")); + let actions = gio::SimpleActionGroup::new(); + for (name, enabled) in [("up", index > 0), ("down", index + 1 < count), ("remove", true)] { + let action = gio::SimpleAction::new(name, None); + action.set_enabled(enabled); + action.connect_activate(glib::clone!( + #[weak(rename_to = dialog)] + self, + move |action, _| { + match action.name().as_str() { + "up" => dialog.step(id, true), + "down" => dialog.step(id, false), + _ => dialog.remove(id), + } + } + )); + actions.add_action(&action); + } + row.insert_action_group("rule", Some(&actions)); + let button = gtk::MenuButton::builder() + .icon_name("view-more-symbolic") + .menu_model(&menu) + .valign(gtk::Align::Center) + .tooltip_text(gettext("Rule Actions")) + .build(); + button.add_css_class("flat"); + row.add_suffix(&button); + let handle = gtk::Image::from_icon_name("list-drag-handle-symbolic"); + handle.set_tooltip_text(Some(&gettext("Drag to Reorder"))); + row.add_prefix(&handle); + let source = gtk::DragSource::builder().actions(gdk::DragAction::MOVE).build(); + let Some(drag_id) = self.imp().drag_id.get() else { + return; + }; + let token = format!("{drag_id}:{id}"); + source.connect_prepare(move |_, _, _| Some(gdk::ContentProvider::for_value(&token.to_value()))); + handle.add_controller(source); + let target = gtk::DropTarget::new(String::static_type(), gdk::DragAction::MOVE); + target.connect_drop(glib::clone!( + #[weak(rename_to = dialog)] + self, + #[upgrade_or] + false, + move |_, value, _, _| { + let Ok(token) = value.get::() else { + return false; + }; + let Some((owner, rule)) = token.split_once(':') else { + return false; + }; + if Uuid::parse_str(owner).ok().as_ref() != dialog.imp().drag_id.get() { + return false; + } + let Ok(from) = Uuid::parse_str(rule) else { + return false; + }; + dialog.move_rule(from, id) + } + )); + row.add_controller(target); + } +} + +fn combo(title: &str, labels: &[String], selected: usize) -> adw::ComboRow { + let refs: Vec<&str> = labels.iter().map(String::as_str).collect(); + adw::ComboRow::builder() + .title(title) + .model(>k::StringList::new(&refs)) + .selected(selected as u32) + .use_markup(false) + .build() +} + +fn entry(title: &str, text: &str) -> adw::EntryRow { + adw::EntryRow::builder().title(title).text(text).build() +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::test_support::{descendants, drain_main_context}; + use crate::ui::data_grid::GridSorting; + use crate::ui::data_grid::test_grid::{Grid, named, two_text_columns, two_text_values}; + + fn editor(grid: &Grid) -> HighlightDialog { + build(&grid.grid).downcast().expect("highlight dialog") + } + + fn entry_named(dialog: &HighlightDialog, title: &str) -> adw::EntryRow { + descendants(dialog) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| row.title() == title) + .expect("entry row") + } + + fn combo_named(dialog: &HighlightDialog, title: &str) -> adw::ComboRow { + descendants(dialog) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| row.title() == title) + .expect("combo row") + } + + #[gtk4::test] + fn add_button_creates_a_rule_and_entry_changes_apply_immediately() { + let grid = Grid::open(two_text_columns(), two_text_values()); + let dialog = editor(&grid); + dialog.imp().add.get().expect("add button").emit_clicked(); + let rules = grid.grid.highlight_rules(); + assert_eq!(rules.len(), 1); + assert_eq!(rules[0].column, "id"); + entry_named(&dialog, "Value").set_text("1"); + assert_eq!( + grid.grid.highlight_rules()[0].value, + Some(FilterValue::Single("1".to_owned())) + ); + } + + #[test] + fn malformed_operands_can_be_repaired_without_losing_valid_values() { + let extra = Some(FilterValue::Single("ignored".to_owned())); + assert_eq!(operand_for(FilterOp::IsNull, &extra), None); + assert_eq!(operand_for(FilterOp::Between, &extra), blank_for(FilterOp::Between)); + let pair = Some(FilterValue::Pair("a, b".to_owned(), " c ".to_owned())); + assert_eq!(operand_for(FilterOp::Between, &pair), pair); + } + + #[gtk4::test] + fn edits_follow_rule_identity_after_reordering_and_removal() { + let grid = Grid::open(two_text_columns(), two_text_values()); + let first = HighlightRule::new("id"); + let second = HighlightRule::new("name"); + grid.grid.set_highlight_rules(vec![first.clone(), second.clone()]); + let dialog = editor(&grid); + let old_entry = entry_named(&dialog, "Value"); + let row = dialog + .imp() + .rows + .borrow() + .get(&first.id) + .and_then(glib::WeakRef::upgrade) + .expect("first row"); + row.activate_action("rule.down", None).expect("move action"); + old_entry.set_text("99"); + let rules = grid.grid.highlight_rules(); + assert_eq!(rules[1].id, first.id); + assert_eq!(rules[1].value, Some(FilterValue::Single("99".to_owned()))); + assert_eq!(rules[0].id, second.id); + dialog.remove(first.id); + old_entry.set_text("100"); + assert_eq!(grid.grid.highlight_rules(), [second]); + } + + #[gtk4::test] + fn missing_and_duplicate_columns_keep_their_identity() { + let grid = Grid::open(vec![named("same", "text", false), named("same", "text", false)], vec![]); + let mut rule = HighlightRule::new("gone"); + rule.value = Some(FilterValue::Single("x".to_owned())); + grid.grid.set_highlight_rules(vec![rule]); + let dialog = editor(&grid); + let column = combo_named(&dialog, "Column"); + assert_eq!(column.selected(), 2); + let selected = column + .selected_item() + .and_downcast::() + .expect("missing choice"); + assert!(selected.string().contains("unavailable")); + column.set_selected(1); + let rules = grid.grid.highlight_rules(); + assert_eq!(rules[0].column, "same"); + assert_eq!(rules[0].column_occurrence, 1); + drop(dialog); + let dialog = editor(&grid); + assert_eq!(combo_named(&dialog, "Column").selected(), 1); + } + + #[gtk4::test] + fn changing_columns_updates_an_open_dialog() { + let grid = Grid::open(two_text_columns(), two_text_values()); + grid.grid.set_highlight_rules(vec![HighlightRule::new("name")]); + let dialog = editor(&grid); + let mut columns = grid.grid.grid_columns().to_vec(); + columns.truncate(1); + columns[0].name = "replacement".to_owned(); + grid.grid.set_columns(Arc::from(columns), GridSorting::Client, None); + drain_main_context(); + let column = combo_named(&dialog, "Column"); + assert_eq!(column.selected(), 1); + column.set_selected(0); + assert_eq!(grid.grid.highlight_rules()[0].column, "replacement"); + } + + #[gtk4::test] + fn list_and_range_fields_preserve_commas_and_spaces() { + let grid = Grid::open(two_text_columns(), two_text_values()); + let mut rule = HighlightRule::new("name"); + rule.op = FilterOp::In; + rule.value = Some(FilterValue::List(vec!["a, b".to_owned(), " c ".to_owned()])); + grid.grid.set_highlight_rules(vec![rule.clone()]); + let dialog = editor(&grid); + assert_eq!(entry_named(&dialog, "Value 1").text(), "a, b"); + entry_named(&dialog, "Value 2").set_text(" d, e "); + assert_eq!( + grid.grid.highlight_rules()[0].value, + Some(FilterValue::List(vec!["a, b".to_owned(), " d, e ".to_owned()])) + ); + let condition = combo_named(&dialog, "Condition"); + condition.set_selected( + OPERATORS + .iter() + .position(|op| *op == FilterOp::Between) + .expect("between") as u32, + ); + entry_named(&dialog, "From").set_text("a, b"); + entry_named(&dialog, "To").set_text("z, x"); + assert_eq!( + grid.grid.highlight_rules()[0].value, + Some(FilterValue::Pair("a, b".to_owned(), "z, x".to_owned())) + ); + } + + #[gtk4::test] + fn dialog_widgets_and_watchers_are_released() { + let grid = Grid::open(two_text_columns(), two_text_values()); + grid.grid.set_highlight_rules(vec![HighlightRule::new("id")]); + let dialog = editor(&grid); + let weak_dialog = dialog.downgrade(); + let weak_value = entry_named(&dialog, "Value").downgrade(); + drop(dialog); + drain_main_context(); + assert!(weak_dialog.upgrade().is_none()); + assert!(weak_value.upgrade().is_none()); + grid.grid.set_highlight_rules(Vec::new()); + drain_main_context(); + } + + #[gtk4::test] + fn external_rule_changes_refresh_the_dialog_and_empty_columns_disable_add() { + let grid = Grid::open(two_text_columns(), two_text_values()); + let dialog = editor(&grid); + grid.grid.set_highlight_rules(vec![HighlightRule::new("name")]); + drain_main_context(); + assert_eq!(dialog.imp().rows.borrow().len(), 1); + grid.grid.set_columns(Arc::from([]), GridSorting::Client, None); + drain_main_context(); + assert!(!dialog.imp().add.get().expect("add button").is_sensitive()); + assert_eq!(grid.grid.highlight_rules().len(), 1); + } +} diff --git a/linux/crates/app/src/ui/data_grid/highlight_popover.rs b/linux/crates/app/src/ui/data_grid/highlight_popover.rs deleted file mode 100644 index 1d3b6a72ec..0000000000 --- a/linux/crates/app/src/ui/data_grid/highlight_popover.rs +++ /dev/null @@ -1,401 +0,0 @@ -//! The Highlight Rules popover: the rules of the grid in front, each a -//! condition on a column and the colour it paints, as the macOS bar's -//! pencil opens (`HighlightRulesPopover`). Every change applies at once. - -use std::cell::RefCell; -use std::rc::Rc; - -use gtk4 as gtk; -use gtk4::prelude::*; -use tablepro_core::filter::{FilterOp, FilterValue}; - -use super::DataGrid; -use crate::i18n::gettext; -use crate::services::grid::{HighlightColor, HighlightRule, HighlightTarget}; - -/// The operators a rule offers, in the order the dropdown lists them. -const OPERATORS: [FilterOp; 16] = [ - FilterOp::Eq, - FilterOp::NotEq, - FilterOp::Gt, - FilterOp::GtEq, - FilterOp::Lt, - FilterOp::LtEq, - FilterOp::Contains, - FilterOp::StartsWith, - FilterOp::EndsWith, - FilterOp::Like, - FilterOp::NotLike, - FilterOp::IsNull, - FilterOp::IsNotNull, - FilterOp::In, - FilterOp::NotIn, - FilterOp::Between, -]; - -fn operator_label(op: FilterOp) -> String { - match op { - FilterOp::Eq => gettext("equals"), - FilterOp::NotEq => gettext("doesn't equal"), - FilterOp::Gt => gettext("greater than"), - FilterOp::GtEq => gettext("at least"), - FilterOp::Lt => gettext("less than"), - FilterOp::LtEq => gettext("at most"), - FilterOp::Contains => gettext("contains"), - FilterOp::StartsWith => gettext("starts with"), - FilterOp::EndsWith => gettext("ends with"), - FilterOp::Like | FilterOp::Ilike => gettext("matches pattern"), - FilterOp::NotLike => gettext("doesn't match pattern"), - FilterOp::IsNull => gettext("is empty"), - FilterOp::IsNotNull => gettext("is not empty"), - FilterOp::In => gettext("is one of"), - FilterOp::NotIn => gettext("is none of"), - FilterOp::Between => gettext("between"), - } -} - -fn color_label(color: HighlightColor) -> String { - match color { - HighlightColor::Red => gettext("Red"), - HighlightColor::Orange => gettext("Orange"), - HighlightColor::Yellow => gettext("Yellow"), - HighlightColor::Green => gettext("Green"), - HighlightColor::Blue => gettext("Blue"), - HighlightColor::Purple => gettext("Purple"), - HighlightColor::Gray => gettext("Gray"), - } -} - -/// The blank value an operator takes, so a rule never holds one of another shape. -fn blank_for(op: FilterOp) -> Option { - match op { - FilterOp::IsNull | FilterOp::IsNotNull => None, - FilterOp::In | FilterOp::NotIn => Some(FilterValue::List(Vec::new())), - FilterOp::Between => Some(FilterValue::Pair(String::new(), String::new())), - _ => Some(FilterValue::Single(String::new())), - } -} - -/// What the value entry shows for a rule, and the other way: a list is -/// comma separated, a range is `low, high`. -fn value_text(value: &Option) -> String { - match value { - None => String::new(), - Some(FilterValue::Single(text)) => text.clone(), - Some(FilterValue::Pair(low, high)) => format!("{low}, {high}"), - Some(FilterValue::List(items)) => items.join(", "), - } -} - -fn value_from(op: FilterOp, text: &str) -> Option { - let parts = || text.split(',').map(|part| part.trim().to_owned()); - match op { - FilterOp::IsNull | FilterOp::IsNotNull => None, - FilterOp::In | FilterOp::NotIn => Some(FilterValue::List(parts().filter(|part| !part.is_empty()).collect())), - FilterOp::Between => { - let mut parts = parts(); - Some(FilterValue::Pair( - parts.next().unwrap_or_default(), - parts.next().unwrap_or_default(), - )) - } - _ => Some(FilterValue::Single(text.to_owned())), - } -} - -type Rules = Rc>>; - -/// The popover for `grid`, holding the rules it has now. -pub(crate) fn build(grid: &DataGrid) -> gtk::Popover { - let rules: Rules = Rc::new(RefCell::new(grid.highlight_rules())); - let list = gtk::Box::new(gtk::Orientation::Vertical, 8); - let scrolled = gtk::ScrolledWindow::builder() - .hscrollbar_policy(gtk::PolicyType::Never) - .propagate_natural_height(true) - .max_content_height(360) - .child(&list) - .build(); - let add = gtk::Button::with_label(&gettext("Add Rule")); - add.set_halign(gtk::Align::Start); - let heading = gtk::Label::builder() - .label(gettext("Highlight Rules")) - .xalign(0.0) - .build(); - heading.add_css_class("heading"); - let empty = gtk::Label::builder() - .label(gettext("No rules. Add one to colour the rows or cells that meet it.")) - .wrap(true) - .xalign(0.0) - .build(); - empty.add_css_class("dimmed"); - let body = gtk::Box::new(gtk::Orientation::Vertical, 10); - body.set_margin_top(12); - body.set_margin_bottom(12); - body.set_margin_start(12); - body.set_margin_end(12); - body.set_width_request(380); - body.append(&heading); - body.append(&empty); - body.append(&scrolled); - body.append(&add); - let popover = gtk::Popover::builder().child(&body).build(); - - let weak = grid.downgrade(); - let apply = { - let rules = rules.clone(); - move || { - if let Some(grid) = weak.upgrade() { - grid.set_highlight_rules(rules.borrow().clone()); - } - } - }; - let rebuild: Rc>>> = Rc::default(); - let rebuild_now = { - let (rules, list, empty, apply, rebuild, grid) = ( - rules.clone(), - list.clone(), - empty.clone(), - apply.clone(), - rebuild.clone(), - grid.downgrade(), - ); - move || { - while let Some(child) = list.first_child() { - list.remove(&child); - } - empty.set_visible(rules.borrow().is_empty()); - let columns: Vec = grid - .upgrade() - .map(|grid| grid.grid_columns().iter().map(|column| column.name.clone()).collect()) - .unwrap_or_default(); - let count = rules.borrow().len(); - for index in 0..count { - list.append(&rule_row(index, &rules, &columns, &apply, &rebuild)); - } - } - }; - rebuild.replace(Some(Box::new(rebuild_now.clone()))); - rebuild_now(); - - add.connect_clicked({ - let (rules, apply, rebuild) = (rules.clone(), apply.clone(), rebuild.clone()); - let columns: Vec = grid.grid_columns().iter().map(|column| column.name.clone()).collect(); - move |_| { - let Some(first) = columns.first() else { - return; - }; - rules.borrow_mut().push(HighlightRule::new(first.clone())); - apply(); - if let Some(rebuild) = rebuild.borrow().as_ref() { - rebuild(); - } - } - }); - popover -} - -fn rule_row( - index: usize, - rules: &Rules, - columns: &[String], - apply: &(impl Fn() + Clone + 'static), - rebuild: &Rc>>>, -) -> gtk::Widget { - let rule = rules.borrow()[index].clone(); - let card = gtk::Box::new(gtk::Orientation::Vertical, 6); - card.add_css_class("card"); - card.set_margin_start(1); - card.set_margin_end(1); - let inner = gtk::Box::new(gtk::Orientation::Vertical, 6); - inner.set_margin_top(8); - inner.set_margin_bottom(8); - inner.set_margin_start(8); - inner.set_margin_end(8); - card.append(&inner); - - let edit = { - let (rules, apply) = (rules.clone(), apply.clone()); - move |change: &dyn Fn(&mut HighlightRule)| { - if let Some(rule) = rules.borrow_mut().get_mut(index) { - change(rule); - } - apply(); - } - }; - - let top = gtk::Box::new(gtk::Orientation::Horizontal, 6); - let enabled = gtk::Switch::builder() - .active(rule.enabled) - .valign(gtk::Align::Center) - .build(); - enabled.update_property(&[gtk::accessible::Property::Label(&gettext("Rule enabled"))]); - enabled.connect_active_notify({ - let edit = edit.clone(); - move |switch| edit(&|rule| rule.enabled = switch.is_active()) - }); - let names: Vec<&str> = columns.iter().map(String::as_str).collect(); - let column = gtk::DropDown::from_strings(&names); - column.set_hexpand(true); - column.set_selected( - columns - .iter() - .position(|name| *name == rule.column) - .map_or(0, |at| at as u32), - ); - column.update_property(&[gtk::accessible::Property::Label(&gettext("Column"))]); - column.connect_selected_notify({ - let (edit, columns) = (edit.clone(), columns.to_vec()); - move |dropdown| { - if let Some(name) = columns.get(dropdown.selected() as usize) { - edit(&|rule| rule.column = name.clone()); - } - } - }); - let remove = gtk::Button::from_icon_name("edit-delete-symbolic"); - remove.add_css_class("flat"); - remove.set_tooltip_text(Some(&gettext("Remove Rule"))); - remove.update_property(&[gtk::accessible::Property::Label(&gettext("Remove Rule"))]); - remove.connect_clicked({ - let (rules, apply, rebuild) = (rules.clone(), apply.clone(), rebuild.clone()); - move |_| { - if index < rules.borrow().len() { - rules.borrow_mut().remove(index); - } - apply(); - if let Some(rebuild) = rebuild.borrow().as_ref() { - rebuild(); - } - } - }); - top.append(&enabled); - top.append(&column); - top.append(&remove); - inner.append(&top); - - let middle = gtk::Box::new(gtk::Orientation::Horizontal, 6); - let labels: Vec = OPERATORS.iter().map(|op| operator_label(*op)).collect(); - let label_refs: Vec<&str> = labels.iter().map(String::as_str).collect(); - let operator = gtk::DropDown::from_strings(&label_refs); - operator.set_selected(OPERATORS.iter().position(|op| *op == rule.op).map_or(0, |at| at as u32)); - operator.update_property(&[gtk::accessible::Property::Label(&gettext("Condition"))]); - let value = gtk::Entry::builder() - .hexpand(true) - .placeholder_text(gettext("Value")) - .text(value_text(&rule.value)) - .visible(!matches!(rule.op, FilterOp::IsNull | FilterOp::IsNotNull)) - .build(); - value.update_property(&[gtk::accessible::Property::Label(&gettext("Value"))]); - operator.connect_selected_notify({ - let (edit, value, rebuild) = (edit.clone(), value.clone(), rebuild.clone()); - move |dropdown| { - let Some(op) = OPERATORS.get(dropdown.selected() as usize).copied() else { - return; - }; - edit(&|rule| { - rule.op = op; - rule.value = blank_for(op); - }); - value.set_visible(!matches!(op, FilterOp::IsNull | FilterOp::IsNotNull)); - value.set_text(""); - let _ = &rebuild; - } - }); - value.connect_changed({ - let (edit, operator) = (edit.clone(), operator.clone()); - move |entry| { - let Some(op) = OPERATORS.get(operator.selected() as usize).copied() else { - return; - }; - let text = entry.text(); - edit(&|rule| rule.value = value_from(op, &text)); - } - }); - middle.append(&operator); - middle.append(&value); - inner.append(&middle); - - let bottom = gtk::Box::new(gtk::Orientation::Horizontal, 6); - let color_labels: Vec = HighlightColor::ALL.iter().map(|color| color_label(*color)).collect(); - let color_refs: Vec<&str> = color_labels.iter().map(String::as_str).collect(); - let color = gtk::DropDown::from_strings(&color_refs); - color.set_selected( - HighlightColor::ALL - .iter() - .position(|c| *c == rule.color) - .map_or(0, |at| at as u32), - ); - color.update_property(&[gtk::accessible::Property::Label(&gettext("Colour"))]); - color.connect_selected_notify({ - let edit = edit.clone(); - move |dropdown| { - if let Some(color) = HighlightColor::ALL.get(dropdown.selected() as usize).copied() { - edit(&|rule| rule.color = color); - } - } - }); - let targets = [gettext("Row"), gettext("Cell")]; - let target_refs: Vec<&str> = targets.iter().map(String::as_str).collect(); - let target = gtk::DropDown::from_strings(&target_refs); - target.set_selected(u32::from(rule.target == HighlightTarget::Cell)); - target.update_property(&[gtk::accessible::Property::Label(&gettext("Paints"))]); - target.connect_selected_notify({ - let edit = edit.clone(); - move |dropdown| { - let target = if dropdown.selected() == 1 { - HighlightTarget::Cell - } else { - HighlightTarget::Row - }; - edit(&|rule| rule.target = target); - } - }); - let case = gtk::CheckButton::with_label(&gettext("Match case")); - case.set_active(rule.case_sensitive); - case.connect_toggled({ - let edit = edit.clone(); - move |check| edit(&|rule| rule.case_sensitive = check.is_active()) - }); - bottom.append(&color); - bottom.append(&target); - bottom.append(&case); - inner.append(&bottom); - card.upcast() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_value_reads_back_the_way_it_was_written() { - for (op, text, expected) in [ - (FilterOp::Eq, "open", Some(FilterValue::Single("open".to_owned()))), - ( - FilterOp::In, - "a, b ,, c", - Some(FilterValue::List(vec!["a".to_owned(), "b".to_owned(), "c".to_owned()])), - ), - ( - FilterOp::Between, - "5, 10", - Some(FilterValue::Pair("5".to_owned(), "10".to_owned())), - ), - (FilterOp::IsNull, "ignored", None), - ] { - assert_eq!(value_from(op, text), expected); - } - assert_eq!(value_text(&value_from(FilterOp::Between, "5, 10")), "5, 10"); - assert_eq!(value_text(&value_from(FilterOp::In, "a, b")), "a, b"); - } - - #[test] - fn an_operator_starts_with_a_blank_value_of_its_shape() { - assert_eq!(blank_for(FilterOp::IsNotNull), None); - assert_eq!(blank_for(FilterOp::In), Some(FilterValue::List(Vec::new()))); - assert_eq!( - blank_for(FilterOp::Between), - Some(FilterValue::Pair(String::new(), String::new())) - ); - assert_eq!(blank_for(FilterOp::Eq), Some(FilterValue::Single(String::new()))); - } -} diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index e2da925aeb..33457e3333 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -86,7 +86,7 @@ pub struct DataGrid { pub editing: Cell, /// The window's focus handler, while the grid is in a window. pub focus_watch: RefCell, glib::SignalHandlerId)>>, - /// The rules the user wrote, and them compiled against the columns. + pub(super) highlight_dialog: glib::WeakRef, pub(super) highlight_source: RefCell>, pub(super) highlights: RefCell>, pub(super) font_watch: RefCell>, @@ -119,6 +119,7 @@ impl ObjectImpl for DataGrid { .build(), Signal::builder("selection-changed").build(), Signal::builder("editing-changed").build(), + Signal::builder("highlight-rules-changed").build(), ] }) } diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index b787baf206..f9b047585a 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -15,7 +15,7 @@ mod grid_request; mod grid_row; mod grid_store; mod highlight; -mod highlight_popover; +mod highlight_dialog; mod imp; mod keys; mod layout_binding; @@ -52,7 +52,6 @@ pub(crate) use self::grid_config::{DialectSource, EditRules, GridConfig, GridSor pub(crate) use self::grid_request::GridRequest; pub(crate) use self::grid_row::{GridRow, PinnedRow, RowData}; pub(crate) use self::grid_store::GridStore; -pub(crate) use self::highlight_popover::build as highlight_rules_popover; pub(crate) use self::layout_binding::LayoutBinding; use self::reversed_list::ReversedList; #[cfg(test)] 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 5058199c10..0578ce3878 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -502,8 +502,6 @@ fn cells_are_freed_with_the_grid() { assert_eq!(alive, 0, "cells outlived their grid"); } -/// A highlight rule tints the rows that meet it, and a cell rule only its -/// own cell, as the macOS grid's Highlight Rules do. #[gtk4::test] fn highlight_rules_tint_the_rows_and_cells_that_meet_them() { use crate::services::grid::{HighlightColor, HighlightRule, HighlightTarget}; @@ -531,6 +529,7 @@ fn highlight_rules_tint_the_rows_and_cells_that_meet_them() { }; assert_eq!(tint(2, 0), Some(HighlightColor::Red), "the row that meets the rule"); assert_eq!(tint(2, 1), Some(HighlightColor::Red)); + assert!(described(&grid.cell_of(2, 1)), "a highlight needs a spoken description"); assert_eq!( tint(1, 0), Some(HighlightColor::Green), @@ -541,36 +540,25 @@ fn highlight_rules_tint_the_rows_and_cells_that_meet_them() { grid.grid.set_highlight_rules(Vec::new()); drain_main_context(); assert_eq!(tint(2, 1), None, "the tint outlived its rule"); + assert!(!described(&grid.cell_of(2, 1))); } -/// The Highlight Rules popover adds a rule for the grid's first column, -/// and what is typed in it reaches the grid's rules at once. #[gtk4::test] -fn the_highlight_popover_edits_the_grids_rules() { +fn highlights_announce_their_colour_and_keep_modified_text_readable() { + use crate::services::grid::{HighlightColor, HighlightRule}; use tablepro_core::filter::FilterValue; - let grid = Grid::open(two_text_columns(), two_text_values()); - let popover = crate::ui::data_grid::highlight_rules_popover(&grid.grid); - let content = popover.child().expect("the popover's content"); - let add = descendants(&content) - .into_iter() - .filter_map(|widget| widget.downcast::().ok()) - .find(|button| button.label().as_deref() == Some("Add Rule")) - .expect("the Add Rule button"); - - add.emit_clicked(); - - let rules = grid.grid.highlight_rules(); - assert_eq!(rules.len(), 1); - assert_eq!(rules[0].column, "id"); - let value = descendants(&content) - .into_iter() - .filter_map(|widget| widget.downcast::().ok()) - .next() - .expect("the rule's value entry"); - value.set_text("1"); - assert_eq!( - grid.grid.highlight_rules()[0].value, - Some(FilterValue::Single("1".to_owned())) - ); + let grid = two_text_rows(); + let mut rule = HighlightRule::new("name"); + rule.value = Some(FilterValue::Single("edited".to_owned())); + rule.color = HighlightColor::Red; + grid.grid.set_highlight_rules(vec![rule]); + rename_first(&grid, "edited"); + let cell = grid.cell_of(1, 1); + assert!(cell.has_css_class(HighlightColor::Red.css_class())); + assert!(has_attribute(&cell, pango::AttrType::Weight)); + assert!(!has_class(&cell, "warning")); + assert!(described(&cell)); + grid.grid.set_highlight_rules(Vec::new()); + assert!(has_class(&cell, "warning")); } diff --git a/linux/crates/app/src/ui/editor/results_pane.rs b/linux/crates/app/src/ui/editor/results_pane.rs index b82df3b9fc..ae0f359a20 100644 --- a/linux/crates/app/src/ui/editor/results_pane.rs +++ b/linux/crates/app/src/ui/editor/results_pane.rs @@ -54,7 +54,7 @@ mod imp { #[template_child] pub details_toggle: TemplateChild, #[template_child] - pub highlight_button: TemplateChild, + pub highlight_button: TemplateChild, #[template_child] pub transaction_bar: TemplateChild, #[template_child] @@ -77,6 +77,7 @@ mod imp { pub page_builder: RefCell>, /// The lines whose page is built, most recently shown first. pub(super) built: RefCell>, + pub(super) highlights: RefCell>>, } #[glib::object_subclass] @@ -172,6 +173,7 @@ impl ResultsPane { imp.stack.remove(&page); } } + imp.highlights.borrow_mut().clear(); imp.stack.set_visible_child_name("empty"); self.show_grid(None); imp.sidebar.set(SidebarState::default()); @@ -199,6 +201,7 @@ impl ResultsPane { forgotten }; for page in forgotten { + self.remember_highlights(&page); if let Some(widget) = imp.stack.child_by_name(&page_name(page.index)) { imp.stack.remove(&widget); } @@ -309,23 +312,19 @@ impl ResultsPane { let actions = grid.map(DataGrid::actions); self.insert_action_group("grid", actions.as_ref()); self.imp().details_toggle.set_visible(grid.is_some()); - let highlight = self.imp().highlight_button.get(); - highlight.set_visible(grid.is_some()); - match grid { - Some(grid) => { - let weak = grid.downgrade(); - highlight.set_create_popup_func(move |button| { - if let Some(grid) = weak.upgrade() { - button.set_popover(Some(&crate::ui::data_grid::highlight_rules_popover(&grid))); - } - }); - } - None => highlight.set_create_popup_func(|_| {}), + self.imp().highlight_button.set_visible(grid.is_some()); + } + + fn remember_highlights(&self, page: &KeptPage) { + let rules = page.grid.as_ref().map(DataGrid::highlight_rules).unwrap_or_default(); + let mut saved = self.imp().highlights.borrow_mut(); + if rules.is_empty() { + saved.remove(&page.index); + } else { + saved.insert(page.index, rules); } } - /// Put the page of line `index` first among the kept ones, building - /// it when it is not kept. fn keep_page(&self, index: u32) -> bool { let imp = self.imp(); { @@ -341,6 +340,10 @@ impl ResultsPane { let Some(ResultPage { widget, grid }) = page else { return false; }; + if let Some(grid) = &grid { + let rules = imp.highlights.borrow_mut().remove(&index).unwrap_or_default(); + grid.set_highlight_rules(rules); + } imp.stack.add_named(&widget, Some(&page_name(index))); let evicted: Vec = { let mut built = imp.built.borrow_mut(); @@ -349,6 +352,7 @@ impl ResultsPane { built.drain(keep..).collect() }; for oldest in evicted { + self.remember_highlights(&oldest); if let Some(page) = imp.stack.child_by_name(&page_name(oldest.index)) { imp.stack.remove(&page); } @@ -639,6 +643,46 @@ mod tests { assert_eq!(pane.imp().stack.visible_child_name().as_deref(), Some("entry-1")); } + #[gtk4::test] + fn highlight_rules_survive_result_eviction_and_rebuild_but_not_a_new_run() { + use crate::services::grid::HighlightRule; + use crate::ui::data_grid::test_grid::{Grid, GridSpec, named, results}; + use tablepro_core::Value; + + let pane = pane(); + pane.set_page_builder(|_| { + let fixture = Grid::build( + GridSpec::results(vec![named("status", "text", false)]), + results(&[vec![Value::Text("open".to_owned())]]), + ); + fixture.window.set_child(None::<>k4::Widget>); + let grid = fixture.grid.clone(); + Some(ResultPage { + widget: grid.clone().upcast(), + grid: Some(grid), + }) + }); + pane.append(&vec![command(); 10]); + let rule = HighlightRule::new("status"); + pane.kept_grid(0) + .expect("first result") + .set_highlight_rules(vec![rule.clone()]); + for index in 1..10 { + pane.select(index); + } + assert!(pane.kept_grid(0).is_none()); + pane.select(0); + assert_eq!( + pane.kept_grid(0).expect("restored result").highlight_rules(), + [rule.clone()] + ); + pane.rebuild_page(0); + assert_eq!(pane.kept_grid(0).expect("rebuilt result").highlight_rules(), [rule]); + pane.clear(); + pane.append(&[command()]); + assert!(pane.kept_grid(0).expect("new run").highlight_rules().is_empty()); + } + #[gtk4::test] fn going_back_to_a_recent_result_keeps_its_page() { let pane = pane(); diff --git a/linux/data/resources/style.css b/linux/data/resources/style.css index 71eff35f2c..194fbb12ce 100644 --- a/linux/data/resources/style.css +++ b/linux/data/resources/style.css @@ -220,9 +220,7 @@ tp-diagram-canvas > .tp-diagram-accent { color: var(--accent-color); } -/* Highlight rules: a cell, or every cell of a row, tinted by what the user - asked to see. A selected row keeps its accent, as it does for stripes, and - the selector is as specific as the stripes' so a highlight wins on a shaded row. */ +/* Selection stays distinct from rules, and rule colours take precedence over stripes. */ columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-red { background-color: color-mix(in srgb, var(--red-3) 28%, transparent); } diff --git a/linux/data/resources/ui/browse-tab.ui b/linux/data/resources/ui/browse-tab.ui index 61ed11f60c..b73a2af127 100644 --- a/linux/data/resources/ui/browse-tab.ui +++ b/linux/data/resources/ui/browse-tab.ui @@ -197,8 +197,8 @@ - - + + grid.highlight-rules document-edit-symbolic Highlight Rules