diff --git a/linux/ARCHITECTURE.md b/linux/ARCHITECTURE.md index 7912490f3c..e547f42ac6 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/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. 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..506b4bebbd --- /dev/null +++ b/linux/crates/app/src/services/grid/highlight.rs @@ -0,0 +1,509 @@ +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; + +use super::GridColumn; + +#[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, + ]; + + 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", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HighlightTarget { + Row, + Cell, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HighlightRule { + pub id: Uuid, + pub enabled: bool, + pub column: String, + #[serde(default)] + pub column_occurrence: usize, + pub op: FilterOp, + #[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(), + column_occurrence: 0, + op: FilterOp::Eq, + value: Some(FilterValue::Single(String::new())), + case_sensitive: false, + color: HighlightColor::Yellow, + target: HighlightTarget::Row, + } + } + + pub fn is_valid(&self) -> bool { + 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, + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RowHighlight { + pub row: Option, + pub cells: Vec<(usize, HighlightColor)>, +} + +impl RowHighlight { + #[cfg(test)] + pub fn is_none(&self) -> bool { + self.row.is_none() && self.cells.is_empty() + } + + pub fn color_of(&self, column: usize) -> Option { + self.cells + .iter() + .find(|(at, _)| *at == column) + .map(|(_, color)| *color) + .or(self.row) + } +} + +#[derive(Debug, Clone)] +pub enum HighlightValue<'a> { + Unavailable, + Null, + NonText, + Text(Cow<'a, str>), +} + +struct Compiled { + column: usize, + kind: ColumnKind, + rule: HighlightRule, +} + +#[derive(Default)] +pub struct HighlightRules { + compiled: Vec, + columns: Vec, +} + +impl HighlightRules { + 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() + .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(); + 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() + } + + pub fn columns(&self) -> impl Iterator + '_ { + self.columns.iter().copied() + } + + pub fn highlight(&self, cells: &[HighlightValue<'_>]) -> RowHighlight { + let mut found = RowHighlight::default(); + for compiled in &self.compiled { + let Some(value) = cells.get(compiled.column) else { + continue; + }; + if !matches(&compiled.rule, &compiled.kind, value) { + 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, 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, kind.is_numeric()) == 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, 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))) + } + 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, true).is_ge() && compare(text, high, sensitive, true).is_le() + } + _ => false, + }, + } +} + +fn fold(text: &str, sensitive: bool) -> String { + if sensitive { + text.to_owned() + } else { + text.to_lowercase() + } +} + +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)) +} + +fn like(text: &str, pattern: &str, sensitive: bool) -> bool { + let text = fold(text, sensitive); + let pattern: Vec = fold(pattern, sensitive).chars().collect(); + // 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; + } + } + 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 { + 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], &columns(&["status"])); + !rules.highlight(&cells(&[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 = columns(&["status", "amount"]); + let rules = HighlightRules::compile(&[row, cell], &columns); + + let found = rules.highlight(&cells(&[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(&cells(&[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], &columns(&["status"])); + + 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], &columns(&["status"])); + + assert_eq!(rules.highlight(&cells(&[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); + } + + #[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(std::slice::from_ref(&second), &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 53687adef7..339e6350be 100644 --- a/linux/crates/app/src/services/grid/mod.rs +++ b/linux/crates/app/src/services/grid/mod.rs @@ -19,6 +19,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; @@ -48,6 +49,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, 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/layout.rs b/linux/crates/app/src/ui/browse_tab/layout.rs index ce1e4799bc..33852ad23c 100644 --- a/linux/crates/app/src/ui/browse_tab/layout.rs +++ b/linux/crates/app/src/ui/browse_tab/layout.rs @@ -72,6 +72,7 @@ fn more_menu(page_sizes: &[u64]) -> gio::Menu { actions.append(Some(&gettext("Col_umns…")), Some("grid.columns")); 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); @@ -319,6 +320,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/data_grid/columns.rs b/linux/crates/app/src/ui/data_grid/columns.rs index 1b33b5a93d..5d8be38c26 100644 --- a/linux/crates/app/src/ui/data_grid/columns.rs +++ b/linux/crates/app/src/ui/data_grid/columns.rs @@ -48,6 +48,7 @@ enum Measure { #[derive(Debug)] pub struct ColumnPaint { pub column: GridColumn, + pub grid: glib::WeakRef, pub tracked: TrackedValues, pub attributes: Rc, pub preferences: GridPreferences, @@ -159,6 +160,7 @@ impl DataGrid { for column in columns.iter() { let paint = Rc::new(ColumnPaint { column: column.clone(), + grid: self.downgrade(), tracked: tracked.clone(), attributes: attributes.clone(), preferences: self 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 7acbc5abf3..ddebacfec7 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 d2249461be..48be4d52c0 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -12,7 +12,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_formatted, null_text}; -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; @@ -333,15 +333,31 @@ impl GridCell { if self.imp().scratch.borrow().capacity() > SCRATCH_KEPT_BYTES { self.imp().scratch.replace(String::new()); } + // GTK binds a new row before attaching it to the grid widget tree. + let colour = paint.grid.upgrade().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); - // 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), } @@ -433,3 +449,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 new file mode 100644 index 0000000000..1fca6c305c --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/highlight.rs @@ -0,0 +1,121 @@ +use std::borrow::Cow; +use std::rc::Rc; + +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use tablepro_core::Value; +use tablepro_linux_platform::settings::DateFormat; + +use super::{DataGrid, GridRow}; +use crate::services::grid::display_text::whole_text; +use crate::services::grid::{HighlightColor, HighlightRule, HighlightRules, HighlightValue}; + +impl DataGrid { + 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() + } + + pub(super) fn compile_highlights(&self) { + let compiled = HighlightRules::compile(&self.imp().highlight_source.borrow(), &self.grid_columns()); + self.imp().highlights.replace(Rc::new(compiled)); + } + + 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(); + 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; + }; + 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, + // Rules match the stored value, so the display's date format never changes which rows light up. + value => HighlightValue::Text(Cow::Owned( + whole_text(value, &definition.column_type, DateFormat::Iso, &mut scratch).to_owned(), + )), + } + }); + } + 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..f39a1684cb --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/highlight_dialog.rs @@ -0,0 +1,963 @@ +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 controls(dialog: &HighlightDialog) -> Vec { + // Until presentation, AdwDialog keeps its content outside its widget tree. + descendants(&dialog.child().expect("dialog content")) + } + + fn entry_named(dialog: &HighlightDialog, title: &str) -> adw::EntryRow { + controls(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 { + controls(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/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index 4c5d99c420..e25b394e0d 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -92,6 +92,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)>>, + pub(super) highlight_dialog: glib::WeakRef, + pub(super) highlight_source: RefCell>, + pub(super) highlights: RefCell>, pub(super) font_watch: RefCell>, pub(super) display_watch: RefCell>, pub(super) applied_marks: Cell>, @@ -128,6 +131,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 39f23de9e5..09913154f6 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -16,6 +16,8 @@ mod grid_menu; mod grid_request; mod grid_row; mod grid_store; +mod highlight; +mod highlight_dialog; mod imp; mod keys; mod layout_binding; @@ -231,6 +233,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 8efbdaf20b..52fefbb93d 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -27,6 +27,7 @@ fn paint() -> Rc { let columns = grid_columns(&[info.result_column()], &[info], |_| true); Rc::new(ColumnPaint { column: columns[0].clone(), + grid: glib::WeakRef::new(), tracked: TrackedValues::untracked(), attributes: Rc::new(TextAttributes::new()), preferences: Default::default(), @@ -523,6 +524,125 @@ fn cells_are_freed_with_the_grid() { assert_eq!(alive, 0, "cells outlived their grid"); } +#[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!(described(&grid.cell_of(2, 1)), "a highlight needs a spoken description"); + 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"); + assert!(!described(&grid.cell_of(2, 1))); +} + +#[gtk4::test] +fn highlights_announce_their_colour_and_keep_modified_text_readable() { + use crate::services::grid::{HighlightColor, HighlightRule}; + use tablepro_core::filter::FilterValue; + + 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")); +} + +#[gtk4::test] +fn restored_highlights_apply_to_the_first_rows_without_a_refresh() { + use crate::services::grid::{HighlightColor, HighlightRule, HighlightTarget}; + use tablepro_core::filter::FilterValue; + + let grid = Grid::open(two_text_columns(), Vec::new()); + grid.grid + .set_columns([].into(), crate::ui::data_grid::GridSorting::None, None); + let mut row_rule = HighlightRule::new("name"); + row_rule.value = Some(FilterValue::Single("B".to_owned())); + row_rule.color = HighlightColor::Red; + let mut cell_rule = HighlightRule::new("id"); + cell_rule.value = Some(FilterValue::Single("1".to_owned())); + cell_rule.target = HighlightTarget::Cell; + cell_rule.color = HighlightColor::Green; + grid.grid.set_highlight_rules(vec![row_rule, cell_rule]); + grid.grid + .set_columns(grid.columns.clone(), crate::ui::data_grid::GridSorting::None, None); + grid.grid + .replace_rows(crate::ui::data_grid::test_grid::persisted(&two_text_values()), 0); + wait_until(WAIT, || grid.cells().len() == 4).expect("first rows bind"); + + assert!(grid.cell_of(2, 0).has_css_class(HighlightColor::Red.css_class())); + assert!(grid.cell_of(2, 1).has_css_class(HighlightColor::Red.css_class())); + assert!(grid.cell_of(1, 0).has_css_class(HighlightColor::Green.css_class())); + assert!(!grid.cell_of(1, 1).has_css_class(HighlightColor::Green.css_class())); + assert!(described(&grid.cell_of(2, 1))); +} + +#[gtk4::test] +fn a_cell_can_read_highlights_when_bound_before_it_is_parented() { + use crate::services::grid::{HighlightColor, HighlightRule}; + use tablepro_core::filter::FilterValue; + + let grid = Grid::open(two_text_columns(), two_text_values()); + let mut rule = HighlightRule::new("name"); + rule.value = Some(FilterValue::Single("A".to_owned())); + rule.color = HighlightColor::Red; + grid.grid.set_highlight_rules(vec![rule]); + let cell = GridCell::new(Rc::new(ColumnPaint { + column: grid.columns[1].clone(), + grid: grid.grid.downgrade(), + tracked: grid.grid.tracked(), + attributes: Rc::new(TextAttributes::new()), + preferences: Default::default(), + numbers: Cell::new(false), + })); + assert!(cell.parent().is_none()); + cell.bind(&grid.grid.store().row(0).expect("first row")); + assert!(cell.has_css_class(HighlightColor::Red.css_class())); + assert!(described(&cell)); + cell.unbind(); + let owner = grid.grid.downgrade(); + drop(grid); + drain_main_context(); + assert!(owner.upgrade().is_none(), "cell paint kept the grid alive"); +} + #[gtk4::test] fn null_text_reaches_every_grid_and_stays_with_its_settings() { let editable = Grid::open(two_text_columns(), vec![vec![Value::Int(1), Value::Null]]); diff --git a/linux/crates/app/src/ui/editor/results_pane.rs b/linux/crates/app/src/ui/editor/results_pane.rs index 6ee4a68875..0d8dfe8f18 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 columns_button: TemplateChild, #[template_child] pub transaction_bar: TemplateChild, @@ -77,6 +79,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 +175,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 +203,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,11 +314,20 @@ 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()); + self.imp().highlight_button.set_visible(grid.is_some()); self.imp().columns_button.set_visible(grid.is_some()); } - /// Put the page of line `index` first among the kept ones, building - /// it when it is not kept. + 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); + } + } + fn keep_page(&self, index: u32) -> bool { let imp = self.imp(); { @@ -329,6 +343,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(); @@ -337,6 +355,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); } @@ -676,6 +695,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(), + std::slice::from_ref(&rule) + ); + 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 5bd021dc9e..e7ba20027a 100644 --- a/linux/data/resources/style.css +++ b/linux/data/resources/style.css @@ -224,6 +224,35 @@ tp-diagram-canvas > .tp-diagram-accent { color: var(--accent-color); } +/* 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); +} + +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-orange { + background-color: color-mix(in srgb, var(--orange-3) 28%, transparent); +} + +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-yellow { + background-color: color-mix(in srgb, var(--yellow-3) 32%, transparent); +} + +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-green { + background-color: color-mix(in srgb, var(--green-3) 28%, transparent); +} + +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-blue { + background-color: color-mix(in srgb, var(--blue-3) 28%, transparent); +} + +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-purple { + background-color: color-mix(in srgb, var(--purple-3) 28%, transparent); +} + +columnview.data-table > listview > row:not(:selected) > cell > .tp-hl-gray { + background-color: color-mix(in srgb, var(--view-fg-color) 12%, transparent); +} + /* How much room a data grid row takes around its text, from Preferences. Normal is the default padding above. */ columnview.data-table.row-compact > listview > row > cell > * { diff --git a/linux/data/resources/ui/browse-tab.ui b/linux/data/resources/ui/browse-tab.ui index e3441ac4e4..3c81d1368c 100644 --- a/linux/data/resources/ui/browse-tab.ui +++ b/linux/data/resources/ui/browse-tab.ui @@ -12,6 +12,7 @@ false false false + false false false true @@ -199,6 +200,19 @@ + + + grid.highlight-rules + document-edit-symbolic + Highlight Rules + + + Highlight Rules + + + Filter Rows diff --git a/linux/data/resources/ui/results-pane.ui b/linux/data/resources/ui/results-pane.ui index 91d117e571..3c3640cf6e 100644 --- a/linux/data/resources/ui/results-pane.ui +++ b/linux/data/resources/ui/results-pane.ui @@ -80,6 +80,20 @@ + + + grid.highlight-rules + document-edit-symbolic + Highlight Rules + false + + + Highlight Rules + + + view-reveal-symbolic diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index dfebdbe0aa..45acc4b95b 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -97,6 +97,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 @@ -281,6 +282,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_dialog.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