diff --git a/core/crates/core/src/export/value_text.rs b/core/crates/core/src/export/value_text.rs index 7457fc6a22..9960e0cc33 100644 --- a/core/crates/core/src/export/value_text.rs +++ b/core/crates/core/src/export/value_text.rs @@ -84,13 +84,9 @@ fn second_digits(kind: &ColumnKind) -> Option { kind.fractional_digits().map(|digits| digits.min(9)) } -/// The fractional second, at the digits the column declares. -/// -/// With no declared precision the fraction is the one the value -/// carries, trimmed, because inventing digits would claim a precision -/// the column never promised. fn fraction_text(nanos: u32, digits: Option) -> String { - let nanos = nanos.min(999_999_999); + // Chrono encodes a leap second above one billion nanos; %S already prints its extra second. + let nanos = nanos % 1_000_000_000; let Some(digits) = digits else { return match nanos { 0 => String::new(), @@ -461,6 +457,50 @@ mod tests { ); } + #[test] + fn timestamp_leap_seconds_keep_their_fraction_at_each_precision() { + let value = Value::Timestamp(Temporal::Finite( + NaiveDate::from_ymd_opt(2016, 12, 31) + .expect("a date") + .and_hms_nano_opt(23, 59, 59, 1_123_000_000) + .expect("a leap second"), + )); + for (digits, expected) in [ + (Some(0), "2016-12-31 23:59:60"), + (Some(3), "2016-12-31 23:59:60.123"), + (Some(6), "2016-12-31 23:59:60.123000"), + (Some(9), "2016-12-31 23:59:60.123000000"), + (None, "2016-12-31 23:59:60.123"), + ] { + let column = typed("timestamp", stamp(digits, TemporalZone::Naive)); + assert_eq!(value_text(&value, &column).as_deref(), Some(expected), "{digits:?}"); + } + assert_eq!(value_to_text(&value).as_deref(), Some("2016-12-31 23:59:60.123")); + } + + #[test] + fn offset_timestamp_leap_seconds_keep_their_fraction_at_each_precision() { + let timestamp = chrono::DateTime::parse_from_rfc3339("2017-01-01T05:29:60.123456789+05:30") + .expect("a leap second with an offset"); + let value = Value::TimestampTz(Temporal::Finite(crate::value::OffsetTimestamp::from_datetime( + timestamp, + ))); + for (digits, expected) in [ + (Some(0), "2017-01-01 05:29:60+05:30"), + (Some(3), "2017-01-01 05:29:60.123+05:30"), + (Some(6), "2017-01-01 05:29:60.123456+05:30"), + (Some(9), "2017-01-01 05:29:60.123456789+05:30"), + (None, "2017-01-01 05:29:60.123456789+05:30"), + ] { + let column = typed("timestamptz", stamp(digits, TemporalZone::Offset)); + assert_eq!(value_text(&value, &column).as_deref(), Some(expected), "{digits:?}"); + } + assert_eq!( + value_to_text(&value).as_deref(), + Some("2017-01-01 05:29:60.123456789+05:30") + ); + } + #[test] fn value_text_time_precision_from_kind() { let value = Value::Time(SqlTime::new(false, 12, 0, 0, 123_456_000).expect("a time")); diff --git a/linux/changelog.d/4137.added.md b/linux/changelog.d/4137.added.md new file mode 100644 index 0000000000..b498d0b520 --- /dev/null +++ b/linux/changelog.d/4137.added.md @@ -0,0 +1 @@ +Preferences can set the format Copy writes when several rows are selected, as TSV, JSON, CSV or Markdown. diff --git a/linux/changelog.d/4138.added.md b/linux/changelog.d/4138.added.md new file mode 100644 index 0000000000..023ae1adcd --- /dev/null +++ b/linux/changelog.d/4138.added.md @@ -0,0 +1 @@ +Preferences can open the row details pane whenever a row is selected. diff --git a/linux/changelog.d/4140.added.md b/linux/changelog.d/4140.added.md new file mode 100644 index 0000000000..fae3205070 --- /dev/null +++ b/linux/changelog.d/4140.added.md @@ -0,0 +1 @@ +Preferences can sort a table by its primary key or first column when it opens, ascending or descending. diff --git a/linux/changelog.d/4141.added.md b/linux/changelog.d/4141.added.md new file mode 100644 index 0000000000..5442bf177d --- /dev/null +++ b/linux/changelog.d/4141.added.md @@ -0,0 +1 @@ +Cells and value fields mark zero-width, control and special space characters, which Preferences can turn off. diff --git a/linux/changelog.d/4142.added.md b/linux/changelog.d/4142.added.md new file mode 100644 index 0000000000..be7fa0c0b6 --- /dev/null +++ b/linux/changelog.d/4142.added.md @@ -0,0 +1 @@ +Preferences can show dates and timestamps in cells as ISO, US or EU dates, with or without the time. diff --git a/linux/crates/app/src/services/grid/column_width.rs b/linux/crates/app/src/services/grid/column_width.rs index a0ce376e48..2c1456979e 100644 --- a/linux/crates/app/src/services/grid/column_width.rs +++ b/linux/crates/app/src/services/grid/column_width.rs @@ -2,8 +2,9 @@ use tablepro_core::Value; use tablepro_core::column::{ColumnKind, TemporalZone, TextLength}; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; -use super::display_text::display_text; +use super::display_text::display_text_formatted; use super::{CellDisplay, GridColumn}; +use tablepro_linux_platform::settings::DateFormat; const MIN_CHARS: u32 = 4; const TEXT_MAX_CHARS: u32 = 40; @@ -15,25 +16,22 @@ const TYPICAL_CHARS: u32 = 20; /// A number of a type that sets no precision. const TYPICAL_DIGITS: u32 = 10; -/// The monospace cells a column's values open at: its widest sampled -/// value. Text is capped so one long value does not push the rest off -/// screen; a number or a date is never cut. The header, drawn in another -/// font, is the caller's to measure. -pub fn default_width_chars<'a>(column: &GridColumn, sample: impl IntoIterator) -> u32 { - let widest = widest_cells(column, sample); +pub fn default_width_chars<'a>( + column: &GridColumn, + sample: impl IntoIterator, + date_format: DateFormat, +) -> u32 { + let widest = widest_cells(column, sample, date_format); let cells = match column.display() { CellDisplay::Bool => BOOL_CHARS, CellDisplay::Number => widest, - CellDisplay::Temporal => widest.max(spelled_chars(&column.column_type.kind).unwrap_or(0)), + CellDisplay::Temporal => widest.max(spelled_chars(&column.column_type.kind, date_format).unwrap_or(0)), CellDisplay::Text | CellDisplay::Json | CellDisplay::Binary => widest.min(TEXT_MAX_CHARS), }; cells.max(MIN_CHARS) } -/// The monospace cells a column's values open at in a table that holds -/// no rows: a value its type leads one to expect. A bounded type gives -/// its widest value, text no wider than a name. -pub fn typical_width_chars(column: &GridColumn) -> u32 { +pub fn typical_width_chars(column: &GridColumn, date_format: DateFormat) -> u32 { let kind = &column.column_type.kind; let typical = match kind { ColumnKind::Bool(_) => BOOL_CHARS, @@ -46,24 +44,22 @@ pub fn typical_width_chars(column: &GridColumn) -> u32 { ColumnKind::Text { length: TextLength::Varying(length) | TextLength::Fixed(length), } => (*length).min(TYPICAL_CHARS), - _ => spelled_chars(kind).unwrap_or(TYPICAL_CHARS), + _ => spelled_chars(kind, date_format).unwrap_or(TYPICAL_CHARS), }; typical.clamp(MIN_CHARS, TEXT_MAX_CHARS) } -/// The values the column's type spells out, cut at the cap, for the -/// caller to measure. -pub fn typical_texts(column: &GridColumn) -> Vec { - spelled(&column.column_type.kind) +pub fn typical_texts(column: &GridColumn, date_format: DateFormat) -> Vec { + spelled(&column.column_type.kind, date_format) .into_iter() - .map(|text| within_cap(text).to_owned()) + .map(|text| within_cap(&text).to_owned()) .collect() } /// The width of a column that turned out to hold only numbers, as an /// untyped PostgreSQL result does: a number is never cut. pub fn number_width_chars<'a>(column: &GridColumn, sample: impl IntoIterator) -> u32 { - widest_cells(column, sample).max(MIN_CHARS) + widest_cells(column, sample, DateFormat::Iso).max(MIN_CHARS) } /// The column's name as its header draws it, cut at the cap. @@ -71,23 +67,22 @@ pub fn header_text(column: &GridColumn) -> &str { within_cap(&column.name) } -fn widest_cells<'a>(column: &GridColumn, sample: impl IntoIterator) -> u32 { +fn widest_cells<'a>(column: &GridColumn, sample: impl IntoIterator, date_format: DateFormat) -> u32 { let mut scratch = String::new(); sample .into_iter() .take(SAMPLE_ROWS) .filter(|value| !value.is_null()) - .map(|value| cells(display_text(value, &column.column_type, &mut scratch).text)) + .map(|value| cells(display_text_formatted(value, &column.column_type, date_format, &mut scratch).text)) .max() .unwrap_or(0) } -/// The sampled values for the caller to measure, as the cells draw them -/// and cut at the cap: of the plain ASCII ones, which a monospace font -/// draws one cell each, the one that takes the most cells, and every -/// other one, since its characters may draw in a fallback font. A number -/// column is measured in tabular digits instead. -pub fn sampled_texts<'a>(column: &GridColumn, sample: impl IntoIterator) -> Vec { +pub fn sampled_texts<'a>( + column: &GridColumn, + sample: impl IntoIterator, + date_format: DateFormat, +) -> Vec { if column.display() == CellDisplay::Number { return Vec::new(); } @@ -95,7 +90,7 @@ pub fn sampled_texts<'a>(column: &GridColumn, sample: impl IntoIterator = None; let mut others = Vec::new(); for value in sample.into_iter().take(SAMPLE_ROWS).filter(|value| !value.is_null()) { - let text = within_cap(display_text(value, &column.column_type, &mut scratch).text); + let text = within_cap(display_text_formatted(value, &column.column_type, date_format, &mut scratch).text); if !is_plain(text) { others.push(text.to_owned()); continue; @@ -111,12 +106,8 @@ pub fn sampled_texts<'a>(column: &GridColumn, sample: impl IntoIterator Vec<&str> { - match kind { +fn spelled(kind: &ColumnKind, date_format: DateFormat) -> Vec { + let values: Vec<&str> = match kind { ColumnKind::Date => vec!["0000-00-00"], ColumnKind::Time { with_offset: false, .. } => vec!["00:00:00"], ColumnKind::Time { with_offset: true, .. } => vec!["00:00:00+00:00"], @@ -131,11 +122,15 @@ fn spelled(kind: &ColumnKind) -> Vec<&str> { multiple: false, } => labels.iter().take(SAMPLE_ROWS).map(String::as_str).collect(), _ => Vec::new(), - } + }; + values + .into_iter() + .map(|text| super::date_display::width_text(text, kind, date_format)) + .collect() } -fn spelled_chars(kind: &ColumnKind) -> Option { - spelled(kind).into_iter().map(cells).max() +fn spelled_chars(kind: &ColumnKind, date_format: DateFormat) -> Option { + spelled(kind, date_format).iter().map(|text| cells(text)).max() } /// The cells `text` takes in a monospace font, where a Chinese or @@ -169,9 +164,26 @@ mod tests { use tablepro_core::column::{BoolStorage, ColumnKind, IntegerKind, IntegerWidth, TemporalZone, TextLength}; use tablepro_core::value::{SqlDecimal, Temporal}; - use super::{default_width_chars, number_width_chars, sampled_texts, typical_texts, typical_width_chars}; + use super::{DateFormat, number_width_chars}; + use crate::services::grid::GridColumn; use crate::services::grid::test_columns::result_only; + fn default_width_chars<'a>(column: &GridColumn, sample: impl IntoIterator) -> u32 { + super::default_width_chars(column, sample, DateFormat::Iso) + } + + fn sampled_texts<'a>(column: &GridColumn, sample: impl IntoIterator) -> Vec { + super::sampled_texts(column, sample, DateFormat::Iso) + } + + fn typical_width_chars(column: &GridColumn) -> u32 { + super::typical_width_chars(column, DateFormat::Iso) + } + + fn typical_texts(column: &GridColumn) -> Vec { + super::typical_texts(column, DateFormat::Iso) + } + fn text() -> ColumnKind { ColumnKind::Text { length: TextLength::Unbounded, @@ -431,4 +443,26 @@ mod tests { "text has no widest" ); } + #[test] + fn empty_timestamp_columns_size_the_selected_format_and_declared_fraction() { + let column = result_only( + "at", + ColumnKind::Timestamp { + fractional_digits: Some(6), + zone: TemporalZone::Offset, + }, + ); + for (format, width) in [ + (DateFormat::Iso, 32), + (DateFormat::UsLong, 35), + (DateFormat::EuLong, 32), + (DateFormat::IsoDate, 10), + (DateFormat::UsShort, 10), + (DateFormat::EuShort, 10), + ] { + assert_eq!(super::default_width_chars(&column, &[], format), width); + assert_eq!(super::typical_width_chars(&column, format), width); + assert_eq!(super::typical_texts(&column, format)[0].len(), width as usize); + } + } } diff --git a/linux/crates/app/src/services/grid/date_display.rs b/linux/crates/app/src/services/grid/date_display.rs new file mode 100644 index 0000000000..4f6a3ff19c --- /dev/null +++ b/linux/crates/app/src/services/grid/date_display.rs @@ -0,0 +1,335 @@ +use tablepro_core::Value; +use tablepro_core::column::{ColumnKind, ColumnType, TimeRange}; +use tablepro_core::value::Temporal; +use tablepro_linux_platform::settings::DateFormat; + +#[derive(Clone, Copy)] +enum Shape { + Date, + Timestamp, + Clock, +} + +pub(super) fn formatted(value: &Value, column: &ColumnType, format: DateFormat) -> Option { + if format == DateFormat::Iso { + return None; + } + let shape = match value { + Value::Date(Temporal::Finite(_)) => Shape::Date, + Value::Timestamp(Temporal::Finite(_)) | Value::TimestampTz(Temporal::Finite(_)) => Shape::Timestamp, + Value::Time(time) if clock_column(&column.kind) && time.to_time_of_day().is_some() => Shape::Clock, + Value::TimeTz(time) if clock_column(&column.kind) && time.time.to_time_of_day().is_some() => Shape::Clock, + _ => return None, + }; + // Core owns the declared precision, BC era and offset spelling. Only their layout changes here. + let canonical = tablepro_core::export::value_text(value, column)?; + reformat(&canonical, shape, format) +} + +pub(super) fn width_text(canonical: &str, kind: &ColumnKind, format: DateFormat) -> String { + let shape = match kind { + ColumnKind::Date => Shape::Date, + ColumnKind::Timestamp { .. } => Shape::Timestamp, + _ if clock_column(kind) => Shape::Clock, + _ => return canonical.to_owned(), + }; + let mut text = canonical.to_owned(); + if !matches!(shape, Shape::Date) + && let Some(digits) = kind.fractional_digits().filter(|digits| *digits > 0) + && let Some(clock) = text.find("00:00:00") + { + text.insert_str(clock + 8, &format!(".{}", "0".repeat(usize::from(digits.min(9))))); + } + reformat(&text, shape, format).unwrap_or(text) +} + +fn clock_column(kind: &ColumnKind) -> bool { + matches!( + kind, + ColumnKind::Time { + range: TimeRange::TimeOfDay, + .. + } + ) +} + +fn reformat(canonical: &str, shape: Shape, format: DateFormat) -> Option { + if format == DateFormat::Iso { + return Some(canonical.to_owned()); + } + if matches!(shape, Shape::Clock) { + return match format { + DateFormat::UsLong => us_clock(canonical), + _ => Some(canonical.to_owned()), + }; + } + let (canonical, era) = match canonical.strip_suffix(" BC") { + Some(text) => (text, " BC"), + None => (canonical, ""), + }; + let (date, clock) = match shape { + Shape::Timestamp => { + let (date, clock) = canonical.split_once(' ')?; + (date, Some(clock)) + } + Shape::Date => (canonical, None), + Shape::Clock => return None, + }; + let (year, rest) = date.split_once('-')?; + let (month, day) = rest.split_once('-')?; + let date = match format { + DateFormat::Iso | DateFormat::IsoDate => date.to_owned(), + DateFormat::UsLong | DateFormat::UsShort => format!("{month}/{day}/{year}"), + DateFormat::EuLong | DateFormat::EuShort => format!("{day}/{month}/{year}"), + }; + let clock = match (clock, format) { + (Some(clock), DateFormat::UsLong) => Some(us_clock(clock)?), + (Some(clock), DateFormat::EuLong) => Some(clock.to_owned()), + _ => None, + }; + Some(match clock { + Some(clock) => format!("{date} {clock}{era}"), + None => format!("{date}{era}"), + }) +} + +fn us_clock(canonical: &str) -> Option { + let (hour, rest) = canonical.split_once(':')?; + let hour = hour.parse::().ok().filter(|hour| *hour < 24)?; + let (rest, offset) = rest.split_at(rest.find(['+', '-']).unwrap_or(rest.len())); + let shown_hour = match hour % 12 { + 0 => 12, + other => other, + }; + let period = if hour < 12 { "AM" } else { "PM" }; + Some(format!("{shown_hour:02}:{rest} {period}{offset}")) +} + +#[cfg(test)] +mod tests { + use chrono::{FixedOffset, NaiveDate}; + use tablepro_core::column::TemporalZone; + use tablepro_core::value::{OffsetTimestamp, SqlTime, TimeWithOffset}; + + use super::*; + use crate::services::grid::display_text::{display_text, display_text_formatted}; + + fn column(kind: ColumnKind) -> ColumnType { + ColumnType { + kind, + ..ColumnType::untyped_text("temporal") + } + } + + fn stamp(digits: Option) -> ColumnType { + column(ColumnKind::Timestamp { + fractional_digits: digits, + zone: TemporalZone::Naive, + }) + } + + fn clock(range: TimeRange, digits: Option, with_offset: bool) -> ColumnType { + column(ColumnKind::Time { + fractional_digits: digits, + range, + with_offset, + }) + } + + fn shown(value: &Value, column: &ColumnType, format: DateFormat) -> String { + display_text_formatted(value, column, format, &mut String::new()) + .text + .to_owned() + } + + #[test] + fn dates_follow_the_chosen_format_and_iso_leaves_them_alone() { + let day = NaiveDate::from_ymd_opt(2024, 12, 31).expect("a day"); + let date = Value::Date(Temporal::Finite(day)); + let timestamp = Value::Timestamp(Temporal::Finite(day.and_hms_opt(23, 59, 58).expect("a clock"))); + for (format, expected_date, expected_stamp) in [ + (DateFormat::Iso, "2024-12-31", "2024-12-31 23:59:58"), + (DateFormat::IsoDate, "2024-12-31", "2024-12-31"), + (DateFormat::UsLong, "12/31/2024", "12/31/2024 11:59:58 PM"), + (DateFormat::UsShort, "12/31/2024", "12/31/2024"), + (DateFormat::EuLong, "31/12/2024", "31/12/2024 23:59:58"), + (DateFormat::EuShort, "31/12/2024", "31/12/2024"), + ] { + assert_eq!(shown(&date, &column(ColumnKind::Date), format), expected_date); + assert_eq!(shown(×tamp, &stamp(None), format), expected_stamp); + } + } + + #[test] + fn fractions_keep_the_column_precision_in_every_long_format() { + let timestamp = Value::Timestamp(Temporal::Finite( + NaiveDate::from_ymd_opt(2024, 12, 31) + .expect("a day") + .and_hms_nano_opt(23, 59, 58, 100_000_000) + .expect("a clock"), + )); + for (digits, fraction) in [ + (None, ".1"), + (Some(0), ""), + (Some(3), ".100"), + (Some(6), ".100000"), + (Some(9), ".100000000"), + ] { + assert_eq!( + shown(×tamp, &stamp(digits), DateFormat::UsLong), + format!("12/31/2024 11:59:58{fraction} PM") + ); + assert_eq!( + shown(×tamp, &stamp(digits), DateFormat::EuLong), + format!("31/12/2024 23:59:58{fraction}") + ); + } + assert_eq!( + display_text(×tamp, &stamp(Some(6)), &mut String::new()).text, + "2024-12-31 23:59:58.100000" + ); + } + + #[test] + fn leap_seconds_keep_the_fraction_for_naive_and_offset_timestamps() { + let leap = NaiveDate::from_ymd_opt(2016, 12, 31) + .expect("a day") + .and_hms_nano_opt(23, 59, 59, 1_123_000_000) + .expect("a leap second"); + let offset = FixedOffset::east_opt(5 * 3600 + 30 * 60).expect("offset"); + let with_offset = OffsetTimestamp::from_datetime(leap.and_local_timezone(offset).single().expect("an instant")); + for (value, column, offset) in [ + (Value::Timestamp(Temporal::Finite(leap)), stamp(Some(6)), ""), + ( + Value::TimestampTz(Temporal::Finite(with_offset)), + column(ColumnKind::Timestamp { + fractional_digits: Some(6), + zone: TemporalZone::Offset, + }), + "+05:30", + ), + ] { + for (format, expected) in [ + (DateFormat::Iso, format!("2016-12-31 23:59:60.123000{offset}")), + (DateFormat::UsLong, format!("12/31/2016 11:59:60.123000 PM{offset}")), + (DateFormat::EuLong, format!("31/12/2016 23:59:60.123000{offset}")), + (DateFormat::IsoDate, "2016-12-31".to_owned()), + (DateFormat::UsShort, "12/31/2016".to_owned()), + (DateFormat::EuShort, "31/12/2016".to_owned()), + ] { + assert_eq!(shown(&value, &column, format), expected); + } + } + } + + #[test] + fn bc_years_and_years_past_four_digits_keep_their_era() { + for (year, expected) in [(0, "01/01/0001 BC"), (-43, "01/01/0044 BC"), (10_000, "01/01/10000")] { + let day = NaiveDate::from_ymd_opt(year, 1, 1).expect("a day"); + assert_eq!( + shown( + &Value::Date(Temporal::Finite(day)), + &column(ColumnKind::Date), + DateFormat::UsShort + ), + expected + ); + } + let value = Value::Timestamp(Temporal::Finite( + NaiveDate::from_ymd_opt(0, 1, 1) + .expect("a day") + .and_hms_opt(13, 0, 0) + .expect("a clock"), + )); + assert_eq!( + shown(&value, &stamp(None), DateFormat::UsLong), + "01/01/0001 01:00:00 PM BC" + ); + } + + #[test] + fn timestamp_offsets_keep_local_dates_and_seconds_only_with_the_clock() { + let offset = FixedOffset::east_opt(5 * 3600 + 30 * 60 + 15).expect("offset"); + let value = Value::TimestampTz(Temporal::Finite(OffsetTimestamp::from_datetime( + NaiveDate::from_ymd_opt(2024, 12, 31) + .expect("a day") + .and_hms_nano_opt(0, 1, 2, 123_456_789) + .expect("a clock") + .and_local_timezone(offset) + .single() + .expect("an instant"), + ))); + for (format, expected) in [ + (DateFormat::Iso, "2024-12-31 00:01:02.123456789+05:30:15"), + (DateFormat::IsoDate, "2024-12-31"), + (DateFormat::UsLong, "12/31/2024 12:01:02.123456789 AM+05:30:15"), + (DateFormat::UsShort, "12/31/2024"), + (DateFormat::EuLong, "31/12/2024 00:01:02.123456789+05:30:15"), + (DateFormat::EuShort, "31/12/2024"), + ] { + assert_eq!(shown(&value, &stamp(Some(9)), format), expected); + } + } + + #[test] + fn clocks_use_twelve_hours_only_for_us_long_even_in_date_only_formats() { + for (hour, expected) in [ + (0, "12:04:05.100000 AM"), + (12, "12:04:05.100000 PM"), + (23, "11:04:05.100000 PM"), + ] { + let time = SqlTime::new(false, hour, 4, 5, 100_000_000).expect("clock"); + let column = clock(TimeRange::TimeOfDay, Some(6), false); + for format in DateFormat::ALL { + let expected = if format == DateFormat::UsLong { + expected.to_owned() + } else { + time.format(Some(6)) + }; + assert_eq!(shown(&Value::Time(time), &column, format), expected); + } + } + let value = Value::TimeTz(TimeWithOffset { + time: SqlTime::new(false, 13, 4, 5, 100_000_000).expect("clock"), + offset: FixedOffset::west_opt(3 * 3600 + 15).expect("offset"), + }); + assert_eq!( + shown(&value, &clock(TimeRange::TimeOfDay, Some(6), true), DateFormat::UsLong), + "01:04:05.100000 PM-03:00:15" + ); + assert_eq!( + shown(&value, &clock(TimeRange::TimeOfDay, Some(6), true), DateFormat::UsShort), + "13:04:05.100000-03:00:15" + ); + } + + #[test] + fn durations_and_unknown_time_columns_never_become_clocks() { + for time in ["13:00:00", "-01:00:00", "24:00:00", "100:00:00"] { + let value = Value::Time(time.parse().expect("time")); + for column in [ + clock(TimeRange::Duration, None, false), + clock(TimeRange::LongDuration, None, false), + column(ColumnKind::Other), + ] { + for format in DateFormat::ALL { + assert_eq!(shown(&value, &column, format), time); + } + } + } + } + + #[test] + fn nonfinite_and_text_values_keep_their_canonical_spelling() { + for (value, expected) in [ + (Value::Date(Temporal::Infinity), "infinity"), + (Value::Timestamp(Temporal::NegInfinity), "-infinity"), + (Value::TimestampTz(Temporal::Infinity), "infinity"), + (Value::Text("2024-12-31".into()), "2024-12-31"), + ] { + for format in DateFormat::ALL { + assert_eq!(shown(&value, &stamp(None), format), expected); + } + } + } +} diff --git a/linux/crates/app/src/services/grid/display_text.rs b/linux/crates/app/src/services/grid/display_text.rs index 71c2accb87..1e6b3fb3ec 100644 --- a/linux/crates/app/src/services/grid/display_text.rs +++ b/linux/crates/app/src/services/grid/display_text.rs @@ -2,6 +2,7 @@ use std::fmt::Write; use tablepro_core::Value; use tablepro_core::column::{BoolStorage, ColumnKind, ColumnType}; +use tablepro_linux_platform::settings::DateFormat; /// A million-character value would hang the main thread in Pango /// layout, and the cell shapes all it is given though a line of it @@ -52,10 +53,16 @@ pub fn auto_filled_sentinel() -> String { crate::i18n::gettext("(auto)") } -/// The text of `value` as the cell draws it. Text, JSON and a value the -/// driver kept as the server's text are borrowed; anything else is -/// written into `scratch`, the cell's own buffer. pub fn display_text<'a>(value: &'a Value, column: &ColumnType, scratch: &'a mut String) -> DisplayText<'a> { + display_text_formatted(value, column, DateFormat::Iso, scratch) +} + +pub fn display_text_formatted<'a>( + value: &'a Value, + column: &ColumnType, + date_format: DateFormat, + scratch: &'a mut String, +) -> DisplayText<'a> { scratch.clear(); match value { Value::Null => DisplayText::placeholder(READONLY_NULL), @@ -82,16 +89,18 @@ pub fn display_text<'a>(value: &'a Value, column: &ColumnType, scratch: &'a mut DisplayText::placeholder(scratch) } other => { - write_value(other, column, scratch); + write_value(other, column, date_format, scratch); cut_in_place(scratch) } } } -/// The text `display_text` spells, whole: past the cell's cut and without -/// its note of what it left out, for a search that must reach the rest. A -/// placeholder is the placeholder. -pub fn whole_text<'a>(value: &'a Value, column: &ColumnType, scratch: &'a mut String) -> &'a str { +pub fn whole_text<'a>( + value: &'a Value, + column: &ColumnType, + date_format: DateFormat, + scratch: &'a mut String, +) -> &'a str { match value { Value::Text(text) => text, Value::Json(json) => json.as_str(), @@ -99,16 +108,17 @@ pub fn whole_text<'a>(value: &'a Value, column: &ColumnType, scratch: &'a mut St Value::Null | Value::Bytes(_) | Value::Undecodable(_) => display_text(value, column, scratch).text, other => { scratch.clear(); - write_value(other, column, scratch); + write_value(other, column, date_format, scratch); scratch } } } -/// Everything else renders the way it exports, so what the grid shows -/// and what a copy produces are the same text. The common scalars are -/// written straight into the buffer. -fn write_value(value: &Value, column: &ColumnType, scratch: &mut String) { +fn write_value(value: &Value, column: &ColumnType, date_format: DateFormat, scratch: &mut String) { + if let Some(text) = super::date_display::formatted(value, column, date_format) { + *scratch = text; + return; + } // Writing to a String cannot fail. let _ = match value { Value::Bool(flag) => scratch.write_str(if *flag { "true" } else { "false" }), diff --git a/linux/crates/app/src/services/grid/find_matches.rs b/linux/crates/app/src/services/grid/find_matches.rs index aabac8d56b..0664712ef7 100644 --- a/linux/crates/app/src/services/grid/find_matches.rs +++ b/linux/crates/app/src/services/grid/find_matches.rs @@ -1,5 +1,6 @@ use super::display_text::whole_text; use super::{GridColumn, RowSnapshot}; +use tablepro_linux_platform::settings::DateFormat; const CANCEL_CHECK_ROWS: usize = 256; @@ -18,6 +19,7 @@ pub fn find_matches( rows: &[RowSnapshot], columns: &[GridColumn], order: &[usize], + date_format: DateFormat, cancelled: &dyn Fn() -> bool, ) -> Vec { if query.is_empty() { @@ -36,7 +38,7 @@ pub fn find_matches( if value.is_null() { continue; } - let text = whole_text(value, &column.column_type, &mut scratch); + let text = whole_text(value, &column.column_type, date_format, &mut scratch); if text.to_lowercase().contains(&needle) { matches.push(FindMatch { row: row_index, @@ -56,9 +58,20 @@ mod tests { use tablepro_core::Value; use tablepro_core::column::ColumnKind; - use super::{FindMatch, find_matches}; + use super::FindMatch; use crate::services::grid::test_columns::result_only; use crate::services::grid::{GridColumn, RowSnapshot}; + use tablepro_linux_platform::settings::DateFormat; + + fn find_matches( + query: &str, + rows: &[RowSnapshot], + columns: &[GridColumn], + order: &[usize], + cancelled: &dyn Fn() -> bool, + ) -> Vec { + super::find_matches(query, rows, columns, order, DateFormat::Iso, cancelled) + } fn columns(count: usize) -> Vec { (0..count) @@ -159,4 +172,18 @@ mod tests { assert_eq!(checks.get(), 2); assert_eq!(find_matches("hit", &rows, &columns(1), &[0], &|| true), Vec::new()); } + #[test] + fn date_matches_use_the_explicit_format_without_changing_null_rules() { + use tablepro_core::value::Temporal; + let day = chrono::NaiveDate::from_ymd_opt(2024, 12, 31).expect("a date"); + let rows = [row(&[Value::Date(Temporal::Finite(day))]), row(&[Value::Null])]; + let column = result_only("day", ColumnKind::Date); + let columns = [column]; + assert_eq!( + super::find_matches("31/12/2024", &rows, &columns, &[0], DateFormat::EuShort, &|| false), + vec![at(0, 0)] + ); + assert!(super::find_matches("31/12/2024", &rows, &columns, &[0], DateFormat::Iso, &|| false).is_empty()); + assert!(super::find_matches("NULL", &rows, &columns, &[0], DateFormat::EuShort, &|| false).is_empty()); + } } diff --git a/linux/crates/app/src/services/grid/mod.rs b/linux/crates/app/src/services/grid/mod.rs index ba31b78469..53687adef7 100644 --- a/linux/crates/app/src/services/grid/mod.rs +++ b/linux/crates/app/src/services/grid/mod.rs @@ -9,6 +9,7 @@ mod cell_preset; mod column_layout; mod column_width; mod copy_scope; +mod date_display; mod delete_availability; pub mod display_text; mod edit_navigation; @@ -22,6 +23,7 @@ mod result_refusal; mod row_key_builder; mod row_snapshot; mod selection_summary; +pub mod special_characters; #[cfg(test)] mod test_columns; diff --git a/linux/crates/app/src/services/grid/special_characters.rs b/linux/crates/app/src/services/grid/special_characters.rs new file mode 100644 index 0000000000..e351b49097 --- /dev/null +++ b/linux/crates/app/src/services/grid/special_characters.rs @@ -0,0 +1,380 @@ +use std::borrow::Cow; +use std::ops::Range; + +// The macOS app's cap per line: past it a value of control bytes would draw one mark each. +pub const MAX_MARKS: usize = 4_096; + +const EMOJI_TAG_BASE: u32 = 0x1F3F4; + +const C0_LABELS: [&str; 32] = [ + "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", + "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US", +]; + +const C1_LABELS: [&str; 32] = [ + "PAD", "HOP", "BPH", "NBH", "IND", "NEL", "SSA", "ESA", "HTS", "HTJ", "VTS", "PLD", "PLU", "RI", "SS2", "SS3", + "DCS", "PU1", "PU2", "STS", "CCH", "MW", "SPA", "EPA", "SOS", "SGC", "SCI", "CSI", "ST", "OSC", "PM", "APC", +]; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SpecialCharacter { + /// Drawn as its short name, since it has no width or no glyph of its own. + Marker(Cow<'static, str>), + /// A space other than U+0020, drawn at its own width. + BlankSpace, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Classified { + /// Bytes of the text the character takes. + pub range: Range, + pub character: SpecialCharacter, +} + +/// The zero-width, control and special space characters of `text`, as the +/// macOS app's "Show invisible characters" marks them. `line_breaks` is for +/// a one-line view, which draws no break for LF or CR. +pub fn special_characters(text: &str, line_breaks: bool) -> SpecialCharacters<'_> { + SpecialCharacters { + text, + chars: text.char_indices(), + line_breaks, + tag_sequence: false, + found: 0, + } +} + +pub struct SpecialCharacters<'a> { + text: &'a str, + chars: std::str::CharIndices<'a>, + line_breaks: bool, + // Whether the characters so far end in an emoji tag sequence's base and tags. + tag_sequence: bool, + found: usize, +} + +impl Iterator for SpecialCharacters<'_> { + type Item = Classified; + + fn next(&mut self) -> Option { + while self.found < MAX_MARKS { + let (index, character) = self.chars.next()?; + let in_tag_sequence = self.tag_sequence; + let value = u32::from(character); + self.tag_sequence = value == EMOJI_TAG_BASE || (is_tag(value) && in_tag_sequence); + let end = index + character.len_utf8(); + let Some(kind) = self.classify(value, index..end, in_tag_sequence) else { + continue; + }; + self.found += 1; + return Some(Classified { + range: index..end, + character: kind, + }); + } + None + } +} + +impl SpecialCharacters<'_> { + fn classify(&self, value: u32, range: Range, in_tag_sequence: bool) -> Option { + let marker = |label| Some(SpecialCharacter::Marker(label)); + match value { + 0x0A | 0x0D if self.line_breaks => marker(control_label(value)), + 0x09 | 0x0A | 0x0D => None, + 0x00..=0x1F | 0x7F..=0x9F => marker(control_label(value)), + 0x2028 | 0x2029 | 0xFFF9..=0xFFFB => marker(label(value)), + 0x00A0 | 0x1680 | 0x2000..=0x200A | 0x202F | 0x205F | 0x3000 => Some(SpecialCharacter::BlankSpace), + _ if is_default_ignorable(value) && !self.is_exempt(value, range, in_tag_sequence) => marker(label(value)), + _ => None, + } + } + + // Each of these shapes the characters around it, as a joiner inside an + // emoji or a variation selector does, so marking it would break what the + // reader sees. + fn is_exempt(&self, value: u32, range: Range, in_tag_sequence: bool) -> bool { + match value { + 0x034F | 0x115F | 0x1160 | 0x17B4 | 0x17B5 | 0x180B..=0x180D | 0x180F => true, + 0xFE00..=0xFE0F | 0xE0100..=0xE01EF => true, + 0x200C | 0x200D => self.joins_non_ascii(range), + _ if is_tag(value) => in_tag_sequence, + _ => false, + } + } + + fn joins_non_ascii(&self, range: Range) -> bool { + let before = self.text[..range.start].chars().next_back(); + let after = self.text[range.end..].chars().next(); + before.into_iter().chain(after).any(|neighbour| !neighbour.is_ascii()) + } +} + +fn is_tag(value: u32) -> bool { + (0xE0020..=0xE007F).contains(&value) +} + +fn is_default_ignorable(value: u32) -> bool { + matches!( + value, + 0x00AD + | 0x034F + | 0x061C + | 0x115F..=0x1160 + | 0x17B4..=0x17B5 + | 0x180B..=0x180F + | 0x200B..=0x200F + | 0x202A..=0x202E + | 0x2060..=0x206F + | 0x3164 + | 0xFE00..=0xFE0F + | 0xFEFF + | 0xFFA0 + | 0xFFF0..=0xFFF8 + | 0x1BCA0..=0x1BCA3 + | 0x1D173..=0x1D17A + | 0xE0000..=0xE0FFF + ) +} + +fn control_label(value: u32) -> Cow<'static, str> { + let named = match value { + 0x00..=0x1F => usize::try_from(value).ok().and_then(|index| C0_LABELS.get(index)), + 0x7F => Some(&"DEL"), + 0x80..=0x9F => usize::try_from(value - 0x80) + .ok() + .and_then(|index| C1_LABELS.get(index)), + _ => None, + }; + named.map_or_else(|| hex_label(value), |label| Cow::Borrowed(*label)) +} + +fn label(value: u32) -> Cow<'static, str> { + let named = match value { + 0x00AD => "SHY", + 0x061C => "ALM", + 0x180E => "MVS", + 0x200B => "ZWSP", + 0x200C => "ZWNJ", + 0x200D => "ZWJ", + 0x200E => "LRM", + 0x200F => "RLM", + 0x2028 => "LSEP", + 0x2029 => "PSEP", + 0x202A => "LRE", + 0x202B => "RLE", + 0x202C => "PDF", + 0x202D => "LRO", + 0x202E => "RLO", + 0x2060 => "WJ", + 0x2066 => "LRI", + 0x2067 => "RLI", + 0x2068 => "FSI", + 0x2069 => "PDI", + 0x206A => "ISS", + 0x206B => "ASS", + 0x206C => "IAFS", + 0x206D => "AAFS", + 0x206E => "NADS", + 0x206F => "NODS", + 0xFEFF => "BOM", + 0xFFF9 => "IAA", + 0xFFFA => "IAS", + 0xFFFB => "IAT", + _ => return hex_label(value), + }; + Cow::Borrowed(named) +} + +fn hex_label(value: u32) -> Cow<'static, str> { + Cow::Owned(format!("{value:04X}")) +} + +/// A one-line view's text with each special character written as its mark. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Revealed { + pub text: String, + pub marks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Mark { + /// Bytes of the revealed text the mark takes. + pub range: Range, + pub labelled: bool, +} + +/// `None` when `text` holds nothing to mark, so a plain value costs no copy. +pub fn reveal(text: &str) -> Option { + let mut found = special_characters(text, true).peekable(); + found.peek()?; + let mut shown = String::with_capacity(text.len() + 8); + let mut marks = Vec::new(); + let mut copied = 0; + for Classified { range, character } in found { + shown.push_str(&text[copied..range.start]); + let start = shown.len(); + let labelled = match character { + SpecialCharacter::Marker(label) => { + shown.push_str(&label); + true + } + SpecialCharacter::BlankSpace => { + shown.push_str(&text[range.clone()]); + false + } + }; + marks.push(Mark { + range: start..shown.len(), + labelled, + }); + copied = range.end; + } + shown.push_str(&text[copied..]); + Some(Revealed { text: shown, marks }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn marked(text: &str, line_breaks: bool) -> Vec<(Range, SpecialCharacter)> { + special_characters(text, line_breaks) + .map(|found| (found.range, found.character)) + .collect() + } + + fn marker(label: &str) -> SpecialCharacter { + SpecialCharacter::Marker(Cow::Owned(label.to_owned())) + } + + #[test] + fn plain_text_spaces_and_tabs_are_not_marked() { + assert!(marked("plain text\twith a tab", true).is_empty()); + assert!(marked("ünïcödé 日本語", true).is_empty()); + assert_eq!(reveal("plain text"), None); + } + + #[test] + fn line_breaks_are_marked_only_in_a_one_line_view() { + assert!(marked("one\ntwo\r\n", false).is_empty()); + assert_eq!( + marked("one\ntwo\r\n", true), + [(3..4, marker("LF")), (7..8, marker("CR")), (8..9, marker("LF"))] + ); + } + + #[test] + fn controls_take_their_names() { + assert_eq!( + marked("\u{1}\u{1b}\u{7f}\u{85}\u{9f}", false), + [ + (0..1, marker("SOH")), + (1..2, marker("ESC")), + (2..3, marker("DEL")), + (3..5, marker("NEL")), + (5..7, marker("APC")), + ] + ); + } + + #[test] + fn special_spaces_keep_their_width() { + for space in [ + '\u{a0}', '\u{1680}', '\u{2000}', '\u{2007}', '\u{200a}', '\u{202f}', '\u{205f}', '\u{3000}', + ] { + let text = format!("a{space}b"); + assert_eq!( + marked(&text, false), + [(1..1 + space.len_utf8(), SpecialCharacter::BlankSpace)], + "U+{:04X}", + u32::from(space) + ); + } + } + + #[test] + fn format_characters_take_their_short_names() { + let cases = [ + ('\u{ad}', "SHY"), + ('\u{200b}', "ZWSP"), + ('\u{200e}', "LRM"), + ('\u{2028}', "LSEP"), + ('\u{2029}', "PSEP"), + ('\u{202e}', "RLO"), + ('\u{2060}', "WJ"), + ('\u{2066}', "LRI"), + ('\u{feff}', "BOM"), + ('\u{fff9}', "IAA"), + ('\u{3164}', "3164"), + ('\u{2061}', "2061"), + ('\u{1d173}', "1D173"), + ('\u{e0001}', "E0001"), + ]; + for (character, label) in cases { + let text = format!("x{character}y"); + assert_eq!( + marked(&text, false), + [(1..1 + character.len_utf8(), marker(label))], + "U+{:04X}", + u32::from(character) + ); + } + } + + #[test] + fn joiners_inside_non_ascii_text_are_left_alone() { + assert!(marked("👨\u{200d}👩", false).is_empty()); + assert!(marked("क\u{200c}ष", false).is_empty()); + assert_eq!(marked("a\u{200d}b", false), [(1..4, marker("ZWJ"))]); + assert_eq!(marked("\u{200c}", false), [(0..3, marker("ZWNJ"))]); + } + + #[test] + fn shaping_selectors_and_combining_ignorables_are_left_alone() { + assert!(marked("✌\u{fe0f}", false).is_empty()); + assert!(marked("a\u{e0100}", false).is_empty()); + assert!(marked("e\u{34f}\u{180b}\u{17b4}\u{115f}", false).is_empty()); + } + + #[test] + fn tags_mark_only_outside_an_emoji_tag_sequence() { + let flag = "\u{1f3f4}\u{e0067}\u{e0062}\u{e0073}\u{e0063}\u{e0074}\u{e007f}"; + assert!(marked(flag, false).is_empty()); + assert_eq!(marked("a\u{e0067}", false), [(1..5, marker("E0067"))]); + let broken = format!("{flag}x\u{e0067}"); + assert_eq!( + marked(&broken, false), + [(broken.len() - 4..broken.len(), marker("E0067"))] + ); + } + + #[test] + fn marks_stop_at_the_cap() { + let text = "\u{1}".repeat(MAX_MARKS + 10); + assert_eq!(special_characters(&text, false).count(), MAX_MARKS); + } + + #[test] + fn reveal_writes_labels_and_keeps_special_spaces() { + let revealed = reveal("a\u{200b}b\u{a0}c\nd").expect("marks"); + assert_eq!(revealed.text, "aZWSPb\u{a0}cLFd"); + assert_eq!( + revealed.marks, + [ + Mark { + range: 1..5, + labelled: true + }, + Mark { + range: 6..8, + labelled: false + }, + Mark { + range: 9..11, + labelled: true + }, + ] + ); + } +} diff --git a/linux/crates/app/src/ui/browse_tab/data_handlers.rs b/linux/crates/app/src/ui/browse_tab/data_handlers.rs index 434ed8ef31..cd4362927a 100644 --- a/linux/crates/app/src/ui/browse_tab/data_handlers.rs +++ b/linux/crates/app/src/ui/browse_tab/data_handlers.rs @@ -171,6 +171,12 @@ impl BrowseModel { } pub(super) fn on_columns_loaded(&mut self, columns: Vec, fx: &mut Effects) { + if let Some((behavior, direction)) = self.default_sort.take() { + let result: Vec = columns.iter().map(ColumnInfo::result_column).collect(); + let sortable = self.grid_columns_for_catalog(&result, &columns); + self.current_sort = + super::default_sort::resolve(behavior, direction, &sortable).filter(|_| self.sorts_rows()); + } if self.current_columns != columns { self.page = None; self.shown_view = None; @@ -250,13 +256,15 @@ impl BrowseModel { /// its place. A document's field whose name a filter, a sort or an /// update cannot spell takes none of them (ADR 0026). fn grid_columns_for(&self, result: &[ResultColumn]) -> Arc<[GridColumn]> { + self.grid_columns_for_catalog(result, &self.current_columns) + } + + fn grid_columns_for_catalog(&self, result: &[ResultColumn], catalog: &[ColumnInfo]) -> Arc<[GridColumn]> { let documents = self .dialect .as_ref() .is_some_and(|dialect| dialect.grammar() == SqlGrammar::Mongo); - grid_columns(result, &self.current_columns, |name| { - !documents || is_addressable_field(name) - }) + grid_columns(result, catalog, |name| !documents || is_addressable_field(name)) } /// Give the grid `columns` when it shows others. Its rows go with the diff --git a/linux/crates/app/src/ui/browse_tab/default_sort.rs b/linux/crates/app/src/ui/browse_tab/default_sort.rs new file mode 100644 index 0000000000..cc3f3ff22d --- /dev/null +++ b/linux/crates/app/src/ui/browse_tab/default_sort.rs @@ -0,0 +1,104 @@ +use tablepro_linux_platform::settings::{DefaultSort, GridSortDirection}; + +use crate::services::grid::GridColumn; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InitialSort { + Default, + Kept(Option<(usize, bool)>), +} + +pub(super) fn resolve( + behavior: DefaultSort, + direction: GridSortDirection, + columns: &[GridColumn], +) -> Option<(usize, bool)> { + let column = match behavior { + DefaultSort::PrimaryKey => columns + .iter() + .find(|column| column.catalog.as_ref().is_some_and(|catalog| catalog.primary_key))?, + DefaultSort::FirstColumn => columns.first()?, + DefaultSort::None => return None, + }; + column.sortable().then_some((column.index, direction.ascending())) +} + +#[cfg(test)] +mod tests { + use tablepro_core::ColumnInfo; + + use super::*; + use crate::services::grid::grid_columns; + use crate::ui::data_grid::test_grid::named; + + fn columns() -> std::sync::Arc<[GridColumn]> { + let catalog = vec![named("name", "text", false), named("id", "integer", true)]; + grid_columns( + &catalog.iter().map(ColumnInfo::result_column).collect::>(), + &catalog, + |_| true, + ) + } + + #[test] + fn none_sorts_nothing() { + assert_eq!( + resolve(DefaultSort::None, GridSortDirection::Ascending, &columns()), + None + ); + } + + #[test] + fn primary_key_picks_the_key_column_in_the_direction() { + assert_eq!( + resolve(DefaultSort::PrimaryKey, GridSortDirection::Ascending, &columns()), + Some((1, true)) + ); + assert_eq!( + resolve(DefaultSort::PrimaryKey, GridSortDirection::Descending, &columns()), + Some((1, false)) + ); + } + + #[test] + fn a_table_without_a_key_stays_unsorted_by_primary_key() { + let keyless = columns()[..1].to_vec(); + assert_eq!( + resolve(DefaultSort::PrimaryKey, GridSortDirection::Ascending, &keyless), + None + ); + assert_eq!( + resolve(DefaultSort::FirstColumn, GridSortDirection::Ascending, &keyless), + Some((0, true)) + ); + } + + #[test] + fn unaddressable_and_missing_columns_are_not_sorted() { + let mut columns = columns().to_vec(); + columns[0].addressable = false; + columns[1].addressable = false; + assert_eq!( + resolve(DefaultSort::FirstColumn, GridSortDirection::Ascending, &columns), + None + ); + assert_eq!( + resolve(DefaultSort::PrimaryKey, GridSortDirection::Ascending, &columns), + None + ); + assert_eq!( + resolve(DefaultSort::FirstColumn, GridSortDirection::Ascending, &[]), + None + ); + } + + #[test] + fn a_composite_key_uses_its_first_column() { + let mut columns = columns().to_vec(); + columns[0].catalog.as_mut().expect("catalog").primary_key = true; + assert_eq!( + resolve(DefaultSort::PrimaryKey, GridSortDirection::Descending, &columns), + Some((0, false)) + ); + } +} diff --git a/linux/crates/app/src/ui/browse_tab/mod.rs b/linux/crates/app/src/ui/browse_tab/mod.rs index c81b355936..c86f3a493e 100644 --- a/linux/crates/app/src/ui/browse_tab/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/mod.rs @@ -22,6 +22,7 @@ mod count_failure_text; mod count_policy; mod data_handlers; mod data_input; +mod default_sort; mod fetch; mod grid_handlers; mod grid_input; @@ -57,6 +58,7 @@ use tablepro_core::dialect::{SqlDialect, TablePaging}; use tablepro_core::meta::{RowIdentity, TableRef}; use tablepro_core::{ColumnInfo, FilterSet}; use tablepro_linux_platform::AppSettings; +use tablepro_linux_platform::settings::{DefaultSort, GridSortDirection}; use tablepro_session::operation::DeadlinePolicy; use tablepro_session::runtime::{Tasks, WatchForwarder}; use tablepro_session::{LinkGeneration, Session}; @@ -70,6 +72,7 @@ use self::browse_tab_widgets::BrowseTabWidgets; use self::column_recheck::ColumnRecheck; pub(super) use self::columns_fetch::{ColumnFreshness, load_columns}; pub(crate) use self::data_input::DataInput; +pub use self::default_sort::InitialSort; pub(crate) use self::grid_input::GridInput; pub(crate) use self::page_reply::PageReply; use self::page_state::PageState; @@ -104,7 +107,7 @@ pub struct BrowseTabInit { pub read_only: bool, pub page_size: u64, pub initial_offset: u64, - pub initial_sort: Option<(usize, bool)>, + pub initial_sort: InitialSort, pub filter: TableFilter, pub column_layouts: crate::persistence::ColumnLayoutStore, pub filter_settings: crate::persistence::FilterSettingsStore, @@ -147,7 +150,14 @@ impl BrowseTab { let actions = browse_actions::install_browse_actions(&tab, init.page_size); // A sort saved with the tab cannot reach an engine that reads // in its own order. - let initial_sort = init.initial_sort.filter(|_| sorts_rows(dialect.as_deref())); + let preferences = init.settings.grid_preferences().snapshot(); + let (initial_sort, default_sort) = match init.initial_sort { + InitialSort::Default => ( + None, + Some((preferences.default_sort, preferences.default_sort_direction)), + ), + InitialSort::Kept(sort) => (sort.filter(|_| sorts_rows(dialect.as_deref())), None), + }; let keys = KeysHandle::new(table.clone()); let grid = layout::grid( &tab, @@ -187,6 +197,7 @@ impl BrowseTab { pager: BrowsePager::new(init.page_size, init.initial_offset), deadlines: init.deadlines, current_sort: initial_sort, + default_sort, current_filter: initial_filter, current_columns: Vec::new(), page: None, @@ -568,6 +579,9 @@ pub(crate) struct BrowseModel { pager: BrowsePager, deadlines: Arc, current_sort: Option<(usize, bool)>, + /// What Preferences asked for when the tab opened, until the columns + /// say which column that is. + default_sort: Option<(DefaultSort, GridSortDirection)>, /// The WHERE every page and count reads under, kept per connection, /// schema and table. current_filter: tablepro_core::FilterSet, diff --git a/linux/crates/app/src/ui/browse_tab/paging_handlers.rs b/linux/crates/app/src/ui/browse_tab/paging_handlers.rs index 83061d8c9c..1416dd15a4 100644 --- a/linux/crates/app/src/ui/browse_tab/paging_handlers.rs +++ b/linux/crates/app/src/ui/browse_tab/paging_handlers.rs @@ -68,6 +68,7 @@ impl BrowseModel { /// A sort the headers did not make, which they show too. /// Read the first page in `next` order. pub(super) fn sort_by(&mut self, next: Option<(usize, bool)>, fx: &mut Effects) { + self.default_sort = None; // One header click can report the same sort twice. if self.current_sort == next { return; diff --git a/linux/crates/app/src/ui/browse_tab/tests/default_sort.rs b/linux/crates/app/src/ui/browse_tab/tests/default_sort.rs new file mode 100644 index 0000000000..1c407f87af --- /dev/null +++ b/linux/crates/app/src/ui/browse_tab/tests/default_sort.rs @@ -0,0 +1,228 @@ +use std::sync::Arc; +use std::time::Duration; + +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use tablepro_core::DriverError; +use tablepro_test_support::{ConnectionScript, FakeReply}; + +use super::super::{GridInput, InitialSort, PagingInput}; +use super::{Harness, WAIT, column, column_view, page_queries, rows, serving_table}; +use crate::test_support::wait_until; +use crate::ui::data_grid::GridRequest; + +fn serving_rows() -> ConnectionScript { + let mut script = serving_table(); + script.query_bound.always(FakeReply::ok(rows(&["Ada"]))); + script +} + +fn loaded(harness: &Harness) { + wait_until(WAIT, || !harness.tab().is_loading() && harness.shown().len() == 1).expect("first page"); +} + +#[gtk4::test] +fn the_default_sort_reaches_the_first_page_query_and_header() { + let harness = Harness::open_with_sort(serving_rows(), InitialSort::Default, "primary-key", "descending"); + loaded(&harness); + + let queries = page_queries(&harness); + assert_eq!(queries.len(), 1); + assert!(queries[0].contains("ORDER BY \"users\".\"id\" DESC"), "{}", queries[0]); + assert_eq!(harness.tab().current_sort(), Some((0, false))); + let sorter = column_view(harness.tab()) + .sorter() + .and_downcast::() + .expect("sorter"); + assert_eq!(sorter.primary_sort_column(), harness.grid().data_view_column(0)); + assert_eq!(sorter.primary_sort_order(), gtk4::SortType::Descending); +} + +#[gtk4::test] +fn kept_sorts_include_an_explicitly_unsorted_first_page() { + for kept in [None, Some((1, true))] { + let harness = Harness::open_with_sort(serving_rows(), InitialSort::Kept(kept), "primary-key", "descending"); + loaded(&harness); + assert_eq!(harness.tab().current_sort(), kept); + if kept.is_some() { + assert!(page_queries(&harness)[0].contains("ORDER BY \"users\".\"name\" ASC")); + } else { + // Stable paging can add the key's ascending order without selecting a header sort. + assert!(!page_queries(&harness)[0].contains("DESC")); + let sorter = column_view(harness.tab()) + .sorter() + .and_downcast::() + .expect("sorter"); + assert!(sorter.primary_sort_column().is_none()); + } + } +} + +#[gtk4::test] +fn refresh_and_preference_changes_preserve_the_users_sort() { + let harness = Harness::open_with_sort(serving_rows(), InitialSort::Default, "primary-key", "descending"); + loaded(&harness); + harness.grid().sort_by(Some((1, true))); + wait_until(WAIT, || { + page_queries(&harness).len() == 2 && !harness.tab().is_loading() + }) + .expect("manual sort"); + + harness + .stores + .settings + .get() + .set_default_sort("first-column") + .expect("preference"); + harness.tab().send(PagingInput::Refresh); + wait_until(WAIT, || { + page_queries(&harness).len() == 3 && !harness.tab().is_loading() + }) + .expect("refresh"); + + assert_eq!(harness.tab().current_sort(), Some((1, true))); + assert!(page_queries(&harness)[2].contains("ORDER BY \"users\".\"name\" ASC")); +} + +#[gtk4::test] +fn a_failed_metadata_read_keeps_the_default_for_its_retry() { + let mut script = serving_rows(); + script.fetch_columns.once(FakeReply::err(DriverError::server("busy"))); + let harness = Harness::open_with_sort(script, InitialSort::Default, "primary-key", "descending"); + wait_until(WAIT, || harness.visible_page().as_deref() == Some("error")).expect("metadata failure"); + assert!(page_queries(&harness).is_empty()); + + harness.tab().send(PagingInput::Refresh); + loaded(&harness); + + assert_eq!(harness.tab().current_sort(), Some((0, false))); + assert!(page_queries(&harness)[0].contains("ORDER BY \"users\".\"id\" DESC")); +} + +#[gtk4::test] +fn explicitly_clearing_sort_before_metadata_cancels_the_default() { + let mut script = serving_rows(); + script.fetch_columns.always(FakeReply::Late { + after: Duration::from_millis(150), + outcome: Ok(vec![column("id", true), column("name", false)]), + }); + let harness = Harness::open_with_sort(script, InitialSort::Default, "primary-key", "descending"); + + harness.tab().send(GridInput::Request(GridRequest::Sort(None))); + loaded(&harness); + + assert_eq!(harness.tab().current_sort(), None); + assert!(!page_queries(&harness)[0].contains("DESC")); +} + +#[gtk4::test] +fn a_keyless_table_and_an_engine_without_sorting_skip_the_default() { + let mut keyless = serving_rows(); + keyless + .fetch_columns + .always(FakeReply::ok(vec![column("id", false), column("name", false)])); + keyless + .row_identity + .always(FakeReply::ok(tablepro_core::meta::RowIdentity::Unordered)); + let harness = Harness::open_with_sort(keyless, InitialSort::Default, "primary-key", "descending"); + loaded(&harness); + assert_eq!(harness.tab().current_sort(), None); + drop(harness); + + let mut unsupported = serving_rows(); + unsupported.dialect = Arc::new(tablepro_driver_cassandra::CqlDialect::new( + &tablepro_core::ServerInfo::new("Cassandra", "5.0", 5, 0, 0), + )); + let harness = Harness::open_with_sort(unsupported, InitialSort::Default, "primary-key", "descending"); + wait_until(WAIT, || harness.grid().data_view_column(0).is_some()).expect("metadata"); + assert_eq!(harness.tab().current_sort(), None); + assert!(harness.grid().data_view_column(0).expect("column").sorter().is_none()); +} + +#[gtk4::test] +fn stale_metadata_cannot_consume_the_pending_default() { + use super::super::{BrowseCommand, BrowseRequestKind, ColumnsReply, DataInput}; + use crate::runtime::Stamped; + use crate::ui::tab_load::LoadFailure; + use tablepro_core::meta::RowIdentity; + + let mut script = serving_rows(); + script.fetch_columns.always(FakeReply::UntilStopped); + let harness = Harness::open_with_sort(script, InitialSort::Default, "primary-key", "descending"); + let (stale, current) = { + let mut borrowed = harness.tab().imp().model.borrow_mut(); + let model = borrowed.as_mut().expect("model"); + ( + model.sequencer.issue(BrowseRequestKind::Columns), + model.sequencer.issue(BrowseRequestKind::Columns), + ) + }; + let reply = || ColumnsReply { + columns: vec![column("id", true), column("name", false)].into(), + identity: RowIdentity::UniqueKey { + columns: vec!["id".into()], + }, + }; + harness + .tab() + .send(DataInput::Command(Box::new(BrowseCommand::Columns(Stamped { + stamp: stale.stamp, + value: Ok(reply()), + })))); + assert_eq!(harness.tab().current_sort(), None); + assert!( + harness + .tab() + .imp() + .model + .borrow() + .as_ref() + .expect("model") + .default_sort + .is_some() + ); + harness + .tab() + .send(DataInput::Command(Box::new(BrowseCommand::Columns(Stamped { + stamp: current.stamp, + value: Err(LoadFailure::NoColumns), + })))); + assert!( + harness + .tab() + .imp() + .model + .borrow() + .as_ref() + .expect("model") + .default_sort + .is_some() + ); + let retry = harness + .tab() + .imp() + .model + .borrow_mut() + .as_mut() + .expect("model") + .sequencer + .issue(BrowseRequestKind::Columns); + harness + .tab() + .send(DataInput::Command(Box::new(BrowseCommand::Columns(Stamped { + stamp: retry.stamp, + value: Ok(reply()), + })))); + assert_eq!(harness.tab().current_sort(), Some((0, false))); + assert!( + harness + .tab() + .imp() + .model + .borrow() + .as_ref() + .expect("model") + .default_sort + .is_none() + ); +} 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 73c7f5278d..49a600fc2c 100644 --- a/linux/crates/app/src/ui/browse_tab/tests/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/tests/mod.rs @@ -1,3 +1,4 @@ +mod default_sort; mod load; mod references; mod rows; @@ -16,7 +17,9 @@ use tablepro_session::Session; use tablepro_session::fakes::FakeEstablish; use tablepro_test_support::{CallCounters, ConnectionScript, FakeConnection, FakeReply}; -use super::{BrowseTab, BrowseTabInit, DataInput, GridInput, PagingInput, RowTotal, SaveInput, TableFilter}; +use super::{ + BrowseTab, BrowseTabInit, DataInput, GridInput, InitialSort, PagingInput, RowTotal, SaveInput, TableFilter, +}; use crate::services::change_tracker::RowKey; use crate::services::tab_tracker_handle::TabTrackerHandle; use crate::services::tracker_delta::TrackerDelta; @@ -162,24 +165,50 @@ impl Harness { filter: TableFilter, read_only: bool, ) -> Self { - libadwaita::init().expect("libadwaita initialises under the test backend"); - crate::register_test_resources(); - let runtime = crate::test_support::test_runtime(); - let fake = FakeSession::start(script, reconnects, runtime.tasks()); - let stores = TabStores::new(); - let tracker = TabTrackerHandle::default(); - let tab = table_tab( - &fake.session, - &runtime, - &stores, + Self::open_configured( + script, + reconnects, Opening { saved, filter, - tracker: tracker.clone(), read_only, ..Opening::users() }, - ); + TabStores::new(), + ) + } + + fn open_with_sort(script: ConnectionScript, initial_sort: InitialSort, choice: &str, direction: &str) -> Self { + let stores = TabStores::new(); + stores.settings.get().set_default_sort(choice).expect("default sort"); + stores + .settings + .get() + .set_default_sort_direction(direction) + .expect("default direction"); + Self::open_configured( + script, + [], + Opening { + initial_sort, + ..Opening::users() + }, + stores, + ) + } + + fn open_configured( + script: ConnectionScript, + reconnects: impl IntoIterator, + opening: Opening, + stores: TabStores, + ) -> Self { + libadwaita::init().expect("libadwaita initialises under the test backend"); + crate::register_test_resources(); + let runtime = crate::test_support::test_runtime(); + let fake = FakeSession::start(script, reconnects, runtime.tasks()); + let tracker = opening.tracker.clone(); + let tab = table_tab(&fake.session, &runtime, &stores, opening); Self { tab: Some(tab), tracker, @@ -349,6 +378,7 @@ pub(super) struct Opening { pub(super) filter: TableFilter, pub(super) tracker: TabTrackerHandle, pub(super) read_only: bool, + pub(super) initial_sort: InitialSort, } impl Opening { @@ -359,6 +389,7 @@ impl Opening { filter: TableFilter::Remembered, tracker: TabTrackerHandle::default(), read_only: false, + initial_sort: InitialSort::Default, } } } @@ -375,6 +406,7 @@ pub(super) fn table_tab( filter, tracker, read_only, + initial_sort, } = opening; let tasks = runtime.tasks(); let connection_id = uuid::Uuid::new_v4(); @@ -389,7 +421,7 @@ pub(super) fn table_tab( read_only, page_size: 100, initial_offset: 0, - initial_sort: None, + initial_sort, filter, column_layouts: crate::persistence::ColumnLayoutStore::load(root.join("column_layouts.json"), &tasks), filter_settings, @@ -1621,6 +1653,26 @@ fn a_dotted_field_of_a_document_neither_sorts_nor_takes_an_edit() { assert_eq!(harness.tracker.pending_count(), 0); } +#[gtk4::test] +fn a_new_tab_opens_sorted_by_the_default_sort() { + let mut script = serving_table(); + script.count_rows.always(FakeReply::ok(1_000)); + script.query_bound.always(FakeReply::ok(full_page(0))); + let mut harness = Harness::open(script, []); + wait_until(WAIT, || harness.shown().len() == 100).expect("the first page"); + assert_eq!(harness.tab().current_sort(), None, "no default sort until asked"); + + let settings = harness.stores.settings.get().clone(); + settings.set_default_sort("primary-key").expect("store the sort"); + settings + .set_default_sort_direction("descending") + .expect("store the direction"); + let another = harness.open_another(); + wait_until(WAIT, || another.current_sort().is_some()).expect("the default sort"); + + assert_eq!(another.current_sort(), Some((0, false))); +} + #[gtk4::test] fn the_bottom_bar_switches_between_data_and_structure() { use gtk4::subclass::prelude::ObjectSubclassIsExt; diff --git a/linux/crates/app/src/ui/data_grid/columns.rs b/linux/crates/app/src/ui/data_grid/columns.rs index dbbc1acfd4..1b33b5a93d 100644 --- a/linux/crates/app/src/ui/data_grid/columns.rs +++ b/linux/crates/app/src/ui/data_grid/columns.rs @@ -336,10 +336,12 @@ impl DataGrid { .filter_map(|cells| cells.as_deref().and_then(|cells| cells.get(index))) .collect(); let column = &paint.column; + let preferences = paint.preferences.snapshot(); + let date_format = preferences.date_format; let chars = match (by_type, paint.numbers.get()) { - (true, _) => typical_width_chars(column), + (true, _) => typical_width_chars(column, date_format), (false, true) => number_width_chars(column, values.iter().copied()), - (false, false) => default_width_chars(column, values.iter().copied()), + (false, false) => default_width_chars(column, values.iter().copied(), date_format), }; let estimate = (f64::from(chars) * char_px).ceil() as i32; // A number is never cut. Nor is a date, held or not, nor with @@ -348,15 +350,15 @@ impl DataGrid { let sampled = match (by_type, paint.numbers.get()) { (_, true) => tabular_width(&context, &font, &"0".repeat(usize::try_from(chars).unwrap_or_default())), (true, false) => 0, - // One line each, so one layout measures them all. - (false, false) => drawn_width( + (false, false) => sampled_width( &context, &font, - &sampled_texts(column, values.iter().copied()).join("\n"), + &sampled_texts(column, values.iter().copied(), date_format), + preferences.show_invisible_characters, ), }; let spelled = match by_type || column.display() == CellDisplay::Temporal { - true => typical_texts(column) + true => typical_texts(column, date_format) .iter() .map(|typical| tabular_width(&context, &font, typical)) .max() @@ -368,7 +370,6 @@ impl DataGrid { None => 0, }; let header = header_width(&context, header_text(column)) + indicator; - let preferences = paint.preferences.snapshot(); let null = crate::services::grid::display_text::null_text( &preferences.null_display, paint.tracked.tracks_changes(), @@ -966,6 +967,31 @@ fn tabular_width(context: &pango::Context, font: &pango::FontDescription, text: layout.pixel_size().0 } +/// The widest of `texts` as a cell draws it, marks and all. One line each, +/// so one layout measures them all. +fn sampled_width(context: &pango::Context, font: &pango::FontDescription, texts: &[String], marks: bool) -> i32 { + let mut lines = String::new(); + let attributes = pango::AttrList::new(); + for text in texts { + if !lines.is_empty() { + lines.push('\n'); + } + let drawn = super::special_marks::drawn(text, None, marks); + let offset = u32::try_from(lines.len()).unwrap_or(u32::MAX); + for mut attribute in drawn.attributes.iter().flat_map(pango::AttrList::attributes) { + attribute.set_start_index(attribute.start_index().saturating_add(offset)); + attribute.set_end_index(attribute.end_index().saturating_add(offset)); + attributes.insert(attribute); + } + lines.push_str(&drawn.text); + } + let layout = pango::Layout::new(context); + layout.set_text(&lines); + layout.set_font_description(Some(font)); + layout.set_attributes(Some(&attributes)); + layout.pixel_size().0 +} + fn drawn_width(context: &pango::Context, font: &pango::FontDescription, text: &str) -> i32 { let layout = pango::Layout::new(context); layout.set_text(text); diff --git a/linux/crates/app/src/ui/data_grid/copy/mod.rs b/linux/crates/app/src/ui/data_grid/copy/mod.rs index 222b60e39f..decb23cc3f 100644 --- a/linux/crates/app/src/ui/data_grid/copy/mod.rs +++ b/linux/crates/app/src/ui/data_grid/copy/mod.rs @@ -5,6 +5,7 @@ use gtk4::{self as gtk, glib}; use tablepro_core::column::{ColumnInfo, ResultColumn}; use tablepro_core::edit::CellInput; use tablepro_core::{FilterRule, Value}; +use tablepro_linux_platform::settings::RowCopyFormat; use super::grid_actions::{add, add_for_column, enable}; use super::selection::Resolved; @@ -165,7 +166,6 @@ impl ShownColumns { } } -/// Copy: the target cell's value when one row is in play, else the rows. fn copy(grid: &DataGrid) { let Some(target) = grid.target() else { return; @@ -173,7 +173,22 @@ fn copy(grid: &DataGrid) { let column = target.cell.as_ref().map(|(_, column)| *column); match (copy_scope(target.rows.len(), column), &target.cell) { (CopyScope::Value(column), Some((row, _))) => copy_value(grid, row, column), - _ => copy_rows(grid, &target.rows, CopyKind::Rows), + _ => copy_rows(grid, &target.rows, preferred_format(grid)), + } +} + +fn preferred_format(grid: &DataGrid) -> CopyKind { + match grid + .config() + .map(|config| config.settings.row_copy_format()) + .unwrap_or_default() + { + RowCopyFormat::Rows => CopyKind::Rows, + RowCopyFormat::RowsWithHeaders => CopyKind::RowsWithHeaders, + RowCopyFormat::Json => CopyKind::Json, + RowCopyFormat::Csv => CopyKind::Csv, + RowCopyFormat::CsvWithHeaders => CopyKind::CsvWithHeaders, + RowCopyFormat::Markdown => CopyKind::Markdown, } } diff --git a/linux/crates/app/src/ui/data_grid/copy/tests.rs b/linux/crates/app/src/ui/data_grid/copy/tests.rs index 8a46da5545..afab86f749 100644 --- a/linux/crates/app/src/ui/data_grid/copy/tests.rs +++ b/linux/crates/app/src/ui/data_grid/copy/tests.rs @@ -25,6 +25,7 @@ use crate::ui::data_grid::{DataGrid, GridCell, GridRequest}; use crate::ui::export::ExportSource; const BEFORE: &str = "nothing copied yet"; +const TWO_TEXT_ROWS_JSON: &str = "[\n{\"id\":1,\"name\":\"A\"},\n{\"id\":2,\"name\":\"B\"}\n]"; /// What a copy test drives: a grid and the requests it made. trait Copies { @@ -747,3 +748,49 @@ fn the_text_copies_take_the_columns_on_screen() { assert_eq!(lines, "{\"id\":1,\"name\":\"Ada\"}\n{\"id\":2,\"name\":\"Grace\"}\n"); assert_eq!(one_row, "1, 'Ada', 2, 'Grace'"); } + +#[gtk4::test] +fn copy_writes_several_rows_in_the_preferred_format() { + use tablepro_linux_platform::settings::RowCopyFormat; + + let grid = Grid::open(two_text_columns(), two_text_values()); + select_all(&grid); + let settings = &grid.grid.config().expect("a configured grid").settings; + for format in RowCopyFormat::ALL { + settings.set_row_copy_format(format.nick()).expect("store the format"); + + let text = copied(&grid, || activate(&grid.grid, "copy")); + + match format { + RowCopyFormat::Rows => assert_eq!(text, "1\tA\n2\tB\n"), + RowCopyFormat::RowsWithHeaders => assert_eq!(text, "id\tname\n1\tA\n2\tB\n"), + RowCopyFormat::Csv => assert_eq!(text, "1,A\n2,B\n"), + RowCopyFormat::CsvWithHeaders => assert_eq!(text, "id,name\n1,A\n2,B\n"), + RowCopyFormat::Markdown => assert_eq!(text, "| id | name |\n| --- | --- |\n| 1 | A |\n| 2 | B |"), + RowCopyFormat::Json => assert_eq!(text, TWO_TEXT_ROWS_JSON), + } + } +} + +#[gtk4::test] +fn preferred_row_format_preserves_single_cell_copy_and_explicit_formats() { + let grid = Grid::open(two_text_columns(), two_text_values()); + grid.grid + .config() + .expect("a configured grid") + .settings + .set_row_copy_format("json") + .expect("store the format"); + grid.grid.selection().select_item(0, true); + grid.focus(0, 1); + + assert_eq!(copied(&grid, || activate(&grid.grid, "copy")), "A"); + + select_all(&grid); + assert_eq!( + copied(&grid, || activate(&grid.grid, "copy-csv-headers")), + "id,name\n1,A\n2,B\n" + ); + let text = copied(&grid, || activate(&grid.grid, "copy")); + assert_eq!(text, TWO_TEXT_ROWS_JSON); +} diff --git a/linux/crates/app/src/ui/data_grid/display_settings.rs b/linux/crates/app/src/ui/data_grid/display_settings.rs index 10f1fd29de..fe730a4638 100644 --- a/linux/crates/app/src/ui/data_grid/display_settings.rs +++ b/linux/crates/app/src/ui/data_grid/display_settings.rs @@ -44,13 +44,31 @@ impl DataGrid { numbers.set_visible(values.show_row_numbers); super::pinned_numbers::sync(self); } + let marks = values.show_invisible_characters; + let marks_changed = self.imp().applied_marks.replace(Some(marks)) != Some(marks); + if marks_changed { + self.imp().detail_pane.mark_special_characters(); + if let Some(field) = self.edit().open_text() { + super::special_marks::mark_field(&field, marks); + } + } let changed = self.imp().applied_null.borrow().as_deref() != Some(&values.null_display); - if changed { + let dates_changed = + self.imp().applied_date_format.replace(Some(values.date_format)) != Some(values.date_format); + if changed || dates_changed || marks_changed { self.imp().applied_null.replace(Some(values.null_display.clone())); self.redraw(); } - if changed || font_changed { + if dates_changed { + self.find_rows_changed(); + } + if changed || font_changed || dates_changed || marks_changed { self.fonts_changed(); } } + + pub(crate) fn marks_special_characters(&self) -> bool { + self.config() + .is_some_and(|config| config.settings.grid_preferences().snapshot().show_invisible_characters) + } } diff --git a/linux/crates/app/src/ui/data_grid/edit/cell_editor.rs b/linux/crates/app/src/ui/data_grid/edit/cell_editor.rs index 0c1aaec229..32793d0108 100644 --- a/linux/crates/app/src/ui/data_grid/edit/cell_editor.rs +++ b/linux/crates/app/src/ui/data_grid/edit/cell_editor.rs @@ -13,6 +13,7 @@ use crate::services::grid::{ empty_placeholder, next_edit_target, opening_text, }; use crate::ui::data_grid::grid_cell::holds_window_focus; +use crate::ui::data_grid::special_marks::mark_field; use crate::ui::data_grid::{DataGrid, GridCell, GridRow, PinnedRow}; use crate::ui::error_text::edit_parse_message; @@ -335,6 +336,7 @@ impl EditController { commit_when_composed: Cell::new(false), }))); connect(grid, &text, id); + mark_field(&text, grid.marks_special_characters()); text.grab_focus(); if opened == Opened::ToEdit { text.select_region(0, -1); @@ -552,7 +554,6 @@ impl EditController { } } - #[cfg(test)] pub(crate) fn open_text(&self) -> Option { self.open.borrow().as_ref().map(|edit| edit.text.clone()) } @@ -572,7 +573,11 @@ fn connect(grid: &DataGrid, text: >k::Text, id: u64) { grid.edit().on_activate(id); } }); - text.connect_changed(|text| text.remove_css_class("error")); + let weak = grid.downgrade(); + text.connect_changed(move |text| { + text.remove_css_class("error"); + mark_field(text, weak.upgrade().is_some_and(|grid| grid.marks_special_characters())); + }); // Capture phase, so Escape cancels before the GtkText takes it to // clear its own buffer, and Tab commits before the window moves the // focus. diff --git a/linux/crates/app/src/ui/data_grid/edit/tests/rows.rs b/linux/crates/app/src/ui/data_grid/edit/tests/rows.rs index 1dc09f2a7a..900d3d92d9 100644 --- a/linux/crates/app/src/ui/data_grid/edit/tests/rows.rs +++ b/linux/crates/app/src/ui/data_grid/edit/tests/rows.rs @@ -6,7 +6,7 @@ use libadwaita::prelude::*; use tablepro_core::Value; use tablepro_core::edit::CellInput; -use super::{editing, none, pending, press, two_text_rows}; +use super::{details_shown, editing, none, pending, press, two_text_rows}; use crate::services::change_tracker::RowState; use crate::services::grid::edit_policy; use crate::test_support::{drain_main_context, respond, wait_until}; @@ -526,3 +526,97 @@ fn a_deleted_focus_does_not_disable_presets_for_other_selected_rows() { assert_eq!(pending(&grid, 2, 1), Some(CellInput::Value(Value::Null))); assert_eq!(grid.tracker.row_state(&key(1)), RowState::PendingDelete); } + +#[gtk4::test] +fn selecting_a_row_opens_the_details_only_when_preferences_ask() { + let grid = two_text_rows(); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + + grid.focus(0, 1); + grid.grid.selection().select_item(0, true); + assert!(!details_shown(&grid), "off by default"); + + settings.set_auto_show_inspector(true).expect("store the flag"); + drain_main_context(); + assert!(!details_shown(&grid), "the preference waits for a new selection"); + grid.focus(0, 0); + assert!(!details_shown(&grid), "focus alone does not select a row"); + grid.grid.selection().select_item(1, true); + drain_main_context(); + assert!(details_shown(&grid)); + + settings + .set_auto_show_inspector(false) + .expect("turn automatic opening off"); + drain_main_context(); + assert!(details_shown(&grid), "turning the preference off leaves the pane open"); + grid.activate("show-details"); + grid.grid.selection().select_item(0, true); + drain_main_context(); + assert!(!details_shown(&grid)); +} + +#[gtk4::test] +fn closing_details_keeps_it_closed_through_focus_moves_and_escape() { + let grid = two_text_rows(); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + settings + .set_auto_show_inspector(true) + .expect("enable automatic opening"); + select_all_from(&grid, 0, 1); + assert!(details_shown(&grid)); + + assert!(press(&grid, gdk::Key::Return, gdk::ModifierType::ALT_MASK)); + assert!(!details_shown(&grid)); + grid.focus(1, 0); + assert!( + !details_shown(&grid), + "moving focus with the same selection keeps it closed" + ); + assert!(press(&grid, gdk::Key::Escape, none())); + drain_main_context(); + assert!(grid.grid.selection().selection().is_empty()); + assert!( + grid.grid.focused_cell().is_some(), + "the action target still has a focused row" + ); + assert!(!details_shown(&grid), "clearing the selection must not reopen details"); + grid.focus(0, 1); + assert!( + !details_shown(&grid), + "a focused cell without a selection keeps it closed" + ); + + grid.grid.selection().select_item(0, true); + drain_main_context(); + assert!(details_shown(&grid), "a new selection opens details again"); +} + +#[gtk4::test] +fn open_grids_use_the_shared_auto_details_preference_on_their_next_selection() { + let first = two_text_rows(); + let settings = first.grid.config().expect("a configured grid").settings.clone(); + let second = Grid::build( + GridSpec { + settings: Some(settings.clone()), + ..GridSpec::table(two_text_columns()) + }, + page(1..3), + ); + let isolated = two_text_rows(); + for grid in [&first, &second, &isolated] { + grid.grid.selection().unselect_all(); + assert!(!details_shown(grid)); + } + + settings + .set_auto_show_inspector(true) + .expect("enable automatic opening"); + for grid in [&first, &second, &isolated] { + grid.grid.selection().select_item(0, true); + } + drain_main_context(); + assert!(details_shown(&first)); + assert!(details_shown(&second)); + assert!(!details_shown(&isolated)); +} diff --git a/linux/crates/app/src/ui/data_grid/find_bar.rs b/linux/crates/app/src/ui/data_grid/find_bar.rs index 551e7ee0eb..f5ad64f616 100644 --- a/linux/crates/app/src/ui/data_grid/find_bar.rs +++ b/linux/crates/app/src/ui/data_grid/find_bar.rs @@ -208,13 +208,17 @@ impl DataGrid { let rows: Vec = shown.iter().map(GridRow::pin).collect(); let columns = self.grid_columns(); let order = self.shown_columns(); + let date_format = self + .config() + .map(|config| config.settings.date_format()) + .unwrap_or_default(); let cancelled = Arc::new(AtomicBool::new(false)); state.running.replace(Some(cancelled.clone())); let grid = self.downgrade(); glib::spawn_future_local(async move { let answer = tasks .spawn_blocking_task(move || { - find_matches(&query, &snapshots, &columns, &order, &|| { + find_matches(&query, &snapshots, &columns, &order, date_format, &|| { cancelled.load(Ordering::Relaxed) }) }) @@ -657,4 +661,26 @@ mod tests { let focused = grid.focused_cell().expect("a focused cell"); assert_eq!((focused.position(), focused.column()), (Some(1), 2), "on row 2's note"); } + #[gtk4::test] + fn find_searches_the_current_date_display_and_repeats_after_format_changes() { + use tablepro_core::value::Temporal; + + let day = chrono::NaiveDate::from_ymd_opt(2026, 11, 8).expect("a date"); + let grid = Grid::build( + GridSpec::results(vec![named("id", "integer", false), named("day", "date", false)]), + results(&[vec![Value::Int(1), Value::Date(Temporal::Finite(day))]]), + ); + let settings = grid.grid.config().expect("configured grid").settings.clone(); + settings.set_date_format("eu-short").expect("European dates"); + search(&grid, "08/11/2026"); + wait_for_label(&grid, "1 of 1"); + assert_eq!(on_match(&grid), Some((1, 1))); + + settings.set_date_format("iso").expect("ISO dates"); + wait_for_label(&grid, "No results"); + assert_eq!(grid.grid.imp().search_entry.text(), "08/11/2026"); + settings.set_date_format("eu-short").expect("European dates again"); + wait_for_label(&grid, "1 of 1"); + assert_eq!(on_match(&grid), Some((1, 1))); + } } 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..7acbc5abf3 100644 --- a/linux/crates/app/src/ui/data_grid/grid_actions.rs +++ b/linux/crates/app/src/ui/data_grid/grid_actions.rs @@ -152,6 +152,20 @@ impl DataGrid { self.target()?.cell.map(|(_, column)| column) } + pub(super) fn open_details_for_selection(&self) { + let wanted = self + .config() + .is_some_and(|config| config.settings.auto_show_inspector()); + // Action targets include a focused row after Escape clears the selection. + let selected = !self.selection().selection().is_empty(); + if wanted + && selected + && let Some(details) = self.imp().actions.lookup_action("show-details") + { + details.change_state(&true.to_variant()); + } + } + /// Open the detail pane on the focused row, with `column`'s field. pub(crate) fn show_details_for(&self, column: usize) { self.imp().detail_pane.select_field(column); diff --git a/linux/crates/app/src/ui/data_grid/grid_cell.rs b/linux/crates/app/src/ui/data_grid/grid_cell.rs index 5fc03a2827..d2249461be 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -7,10 +7,11 @@ use gtk4::{self as gtk, glib, pango}; use tablepro_core::Value; use super::columns::ColumnPaint; +use super::special_marks::show_value; use super::tracked_values::cell_description; use super::{DataGrid, GridRow, ServerValue}; use crate::services::change_tracker::CellState; -use crate::services::grid::display_text::{DisplayText, auto_filled_sentinel, display_text, null_text}; +use crate::services::grid::display_text::{DisplayText, auto_filled_sentinel, display_text_formatted, null_text}; use crate::services::grid::{CellLock, GridColumn}; /// Enough for any number, date or short text. @@ -312,11 +313,16 @@ impl GridCell { (false, CellState::Modified) => TextMark::Modified, (false, _) => TextMark::Plain, }; + let marks = paint.preferences.snapshot().show_invisible_characters; let null = paint.tracked.with_value(&row, column, |value, computed| { let mut scratch = self.imp().scratch.borrow_mut(); let shown = shown_text(&paint, value, computed, lock.is_none(), &mut scratch); - display.set_text(Some(shown.text)); - display.set_attributes(paint.attributes.for_text(text_mark, shown.placeholder)); + show_value( + display, + shown.text, + paint.attributes.for_text(text_mark, shown.placeholder), + marks && !shown.placeholder, + ); set_class( display, "dimmed", @@ -404,7 +410,12 @@ fn shown_text<'a>( *scratch = null_text(&paint.preferences.snapshot().null_display, editable); DisplayText::placeholder(scratch) } - (None, value) => display_text(value, &paint.column.column_type, scratch), + (None, value) => display_text_formatted( + value, + &paint.column.column_type, + paint.preferences.snapshot().date_format, + scratch, + ), } } diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index 057a92f85e..05bd615a8d 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -94,7 +94,9 @@ pub struct DataGrid { pub focus_watch: RefCell, glib::SignalHandlerId)>>, pub(super) font_watch: RefCell>, pub(super) display_watch: RefCell>, + pub(super) applied_marks: Cell>, pub(super) applied_null: RefCell>, + pub(super) applied_date_format: Cell>, pub(super) cell_font: RefCell>, } diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index 8fbf4b920e..bc8dc3507d 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -29,6 +29,7 @@ mod row_number_column; mod selection; mod selection_summary; mod server_sorter; +mod special_marks; mod stripes; mod table_keys; #[cfg(test)] @@ -417,6 +418,7 @@ impl DataGrid { fn selection_moved(&self) { self.refresh_actions(); self.imp().detail_pane.follow_focus(); + self.open_details_for_selection(); self.emit_by_name::<()>("selection-changed", &[]); } diff --git a/linux/crates/app/src/ui/data_grid/row_detail/fields.rs b/linux/crates/app/src/ui/data_grid/row_detail/fields.rs index d112d56f8c..a4da790526 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/fields.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/fields.rs @@ -4,11 +4,14 @@ use gtk4::prelude::*; use gtk4::subclass::prelude::*; use gtk4::{self as gtk, glib, pango}; use tablepro_core::Value; +use tablepro_linux_platform::settings::DateFormat; use super::RowDetailPane; use crate::i18n::gettext; use crate::services::change_tracker::CellState; -use crate::services::grid::{GridColumn, auto_filled_sentinel, display_text}; +use crate::services::grid::display_text::display_text_formatted; +use crate::services::grid::{GridColumn, auto_filled_sentinel}; +use crate::ui::data_grid::special_marks::show_value; use crate::ui::data_grid::tracked_values::cell_description; use crate::ui::data_grid::{DataGrid, GridRow, ServerValue, TrackedValues}; use crate::ui::handler_guard::HandlerGuard; @@ -42,7 +45,13 @@ pub struct FieldValue { pub deleted: bool, } -pub fn field_value(tracked: &TrackedValues, row: &GridRow, column: &GridColumn, null_display: &str) -> FieldValue { +pub fn field_value( + tracked: &TrackedValues, + row: &GridRow, + column: &GridColumn, + null_display: &str, + date_format: DateFormat, +) -> FieldValue { let mark = tracked.mark(row, column.index); let (text, placeholder, null) = tracked.with_value(row, column.index, |value, computed| match (computed, value) { (Some(ServerValue::Default), _) if column.auto_filled() => (auto_filled_sentinel(), true, false), @@ -51,7 +60,7 @@ pub fn field_value(tracked: &TrackedValues, row: &GridRow, column: &GridColumn, (None, Value::Null) => (null_display.to_owned(), true, true), (None, value) => { let mut scratch = String::new(); - let shown = display_text(value, &column.column_type, &mut scratch); + let shown = display_text_formatted(value, &column.column_type, date_format, &mut scratch); (shown.text.to_owned(), shown.placeholder, false) } }); @@ -335,7 +344,13 @@ impl RowDetailPane { return false; }; let preferences = config.settings.grid_preferences().snapshot(); - let value = field_value(&grid.tracked(), &row, &column, &preferences.null_display); + let value = field_value( + &grid.tracked(), + &row, + &column, + &preferences.null_display, + preferences.date_format, + ); !value.null && value.text.to_lowercase().contains(&wanted) } @@ -382,10 +397,20 @@ impl RowDetailPane { return; }; let preferences = config.settings.grid_preferences().snapshot(); - let value = field_value(&grid.tracked(), &row, &column, &preferences.null_display); + let value = field_value( + &grid.tracked(), + &row, + &column, + &preferences.null_display, + preferences.date_format, + ); edited.set_visible(value.modified); - shown.set_text(Some(&value.text)); - shown.set_attributes(Some(&value_attributes(&value))); + show_value( + &shown, + &value.text, + Some(&value_attributes(&value)), + preferences.show_invisible_characters && !value.placeholder, + ); set_class(&shown, "dimmed", value.placeholder || value.deleted); // Adwaita's own warning colour beside the bold, as the grid's // cells mark a pending value. diff --git a/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs b/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs new file mode 100644 index 0000000000..8c544e8eb4 --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/row_detail/invisibles.rs @@ -0,0 +1,12 @@ +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; + +use super::RowDetailPane; +use crate::ui::data_grid::special_marks::mark_buffer; + +impl RowDetailPane { + pub(in crate::ui::data_grid) fn mark_special_characters(&self) { + let marks = self.grid().is_some_and(|grid| grid.marks_special_characters()); + mark_buffer(self.imp().value_buffer.upcast_ref(), marks); + } +} diff --git a/linux/crates/app/src/ui/data_grid/row_detail/mod.rs b/linux/crates/app/src/ui/data_grid/row_detail/mod.rs index 68aa409846..5dab5cc14b 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/mod.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/mod.rs @@ -5,6 +5,7 @@ mod calendar; mod clock; mod fields; mod imp; +mod invisibles; mod picture; #[cfg(test)] mod tests; diff --git a/linux/crates/app/src/ui/data_grid/row_detail/tests.rs b/linux/crates/app/src/ui/data_grid/row_detail/tests.rs index cbecb66443..1747ca4d97 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/tests.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/tests.rs @@ -1542,6 +1542,45 @@ fn a_page_that_takes_the_row_closes_its_clock_and_writes_nothing() { assert!(!pane.imp().clock_popover.is_visible()); } +fn tagged(pane: &RowDetailPane) -> Vec<(i32, i32)> { + crate::ui::data_grid::special_marks::tagged_ranges(pane.imp().value_buffer.upcast_ref()) +} + +fn field_texts(pane: &RowDetailPane) -> Vec { + descendants(&pane.imp().field_list.get()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .filter_map(|inscription| inscription.text().map(|text| text.to_string())) + .collect() +} + +#[gtk4::test] +fn the_value_editor_marks_invisible_characters_while_preferences_ask() { + let value = "a\u{200b}b c\td\u{a0}e\u{1}"; + let (grid, pane) = opened(two_text_columns(), vec![vec![Value::Int(1), Value::Text(value.into())]]); + grid.focus(0, 1); + drain_main_context(); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + + assert_eq!(pane.typed_text(), value); + assert_eq!( + tagged(&pane), + [(1, 2), (7, 8), (9, 10)], + "a space and a tab are not marked" + ); + assert!(field_texts(&pane).contains(&"aZWSPb c\td\u{a0}eSOH".to_owned())); + + settings.set_show_invisible_characters(false).expect("store the flag"); + drain_main_context(); + assert!(tagged(&pane).is_empty()); + assert!(field_texts(&pane).contains(&value.to_owned())); + assert_eq!(pane.typed_text(), value); + + settings.set_show_invisible_characters(true).expect("store the flag"); + drain_main_context(); + assert_eq!(tagged(&pane), [(1, 2), (7, 8), (9, 10)]); +} + #[gtk4::test] fn null_preferences_update_details_without_replacing_a_draft() { let (grid, pane) = opened(two_text_columns(), vec![vec![Value::Int(1), Value::Null]]); @@ -1968,3 +2007,116 @@ fn search_keys_and_tab_order_reach_the_filter_list_and_value() { .expect("Escape"); wait_until(WAIT, || !grid.grid.imp().split_view.shows_sidebar()).expect("Escape closes the empty overlay search"); } + +#[gtk4::test] +fn changing_automatic_details_opening_keeps_an_active_value_draft() { + let (grid, pane) = opened(two_text_columns(), two_text_values()); + edit_field(&grid, &pane, 0, 1); + type_value(&pane, "unfinished"); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + + settings + .set_auto_show_inspector(true) + .expect("enable automatic opening"); + settings + .set_auto_show_inspector(false) + .expect("disable automatic opening"); + drain_main_context(); + + assert!(pane.is_open()); + assert!(pane.is_editing_value()); + assert_eq!(pane.typed_text(), "unfinished"); + assert_eq!(pending(&grid, 1, 1), None); +} + +#[gtk4::test] +fn a_closed_pane_marks_its_value_once_it_opens() { + let settings = crate::test_support::MemorySettings::new(); + settings + .get() + .set_show_invisible_characters(false) + .expect("start without marks"); + let grid = Grid::build( + GridSpec { + settings: Some(settings.get().clone()), + ..GridSpec::table(two_text_columns()) + }, + persisted(&[vec![Value::Int(1), Value::Text("a\u{200b}b".into())]]), + ); + let pane = pane_of(&grid); + settings.get().set_show_invisible_characters(true).expect("show marks"); + drain_main_context(); + assert!(!pane.is_open()); + + grid.activate("show-details"); + grid.focus(0, 1); + drain_main_context(); + + assert_eq!(pane.typed_text(), "a\u{200b}b"); + assert_eq!(tagged(&pane), [(1, 2)]); + assert!(field_texts(&pane).contains(&"aZWSPb".to_owned())); +} + +#[gtk4::test] +fn marks_leave_the_value_draft_and_its_selection_alone() { + let (grid, pane) = opened(two_text_columns(), two_text_values()); + edit_field(&grid, &pane, 0, 1); + let typed = "one\u{200b}two\u{a0}three"; + type_value(&pane, typed); + let buffer = pane.imp().value_buffer.get(); + buffer.select_range(&buffer.iter_at_offset(2), &buffer.iter_at_offset(9)); + let selection = || { + buffer + .selection_bounds() + .map(|(start, end)| (start.offset(), end.offset())) + }; + let settings = grid.grid.config().expect("configured grid").settings.clone(); + assert_eq!(tagged(&pane), [(3, 4), (7, 8)]); + + for show in [false, true] { + settings.set_show_invisible_characters(show).expect("change the marks"); + drain_main_context(); + assert_eq!(tagged(&pane).is_empty(), !show); + assert_eq!(pane.typed_text(), typed); + assert_eq!(selection(), Some((2, 9))); + assert!(pane.is_editing_value()); + assert!(grid.grid.is_editing()); + assert_eq!(pending(&grid, 1, 1), None); + } +} + +#[gtk4::test] +fn date_format_updates_detail_fields_without_reformatting_the_value_draft() { + let (grid, pane) = date_grid(a_date(2026, 11, 8)); + let settings = grid.grid.config().expect("configured grid").settings.clone(); + assert_eq!(pane.typed_text(), "2026-11-08"); + let field_texts = || { + descendants(&pane.imp().field_list.get()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .filter_map(|inscription| inscription.text().map(|text| text.to_string())) + .collect::>() + }; + + settings.set_date_format("eu-short").expect("European date display"); + drain_main_context(); + assert!(field_texts().contains(&"08/11/2026".to_owned())); + assert_eq!(pane.typed_text(), "2026-11-08", "the editor keeps its parseable form"); + edit_field(&grid, &pane, 0, 1); + type_value(&pane, "2026-11-09"); + let buffer = pane.imp().value_buffer.get(); + buffer.select_range(&buffer.iter_at_offset(5), &buffer.iter_at_offset(7)); + + settings.set_date_format("us-short").expect("US date display"); + drain_main_context(); + assert!(field_texts().contains(&"11/08/2026".to_owned())); + assert_eq!(pane.typed_text(), "2026-11-09"); + assert_eq!( + buffer + .selection_bounds() + .map(|(start, end)| (start.offset(), end.offset())), + Some((5, 7)) + ); + assert!(pane.is_editing_value()); + assert_eq!(pending(&grid, 1, 1), None); +} diff --git a/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs b/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs index 56c18441f8..6b7a52de1b 100644 --- a/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs +++ b/linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs @@ -247,12 +247,13 @@ impl RowDetailPane { } } - fn is_editing_value(&self) -> bool { + pub(super) fn is_editing_value(&self) -> bool { self.imp().edit.borrow().is_some() } fn text_changed(&self) { self.update_placeholder(); + self.mark_special_characters(); if !self.imp().loading.get() { self.begin_edit(); } diff --git a/linux/crates/app/src/ui/data_grid/special_marks.rs b/linux/crates/app/src/ui/data_grid/special_marks.rs new file mode 100644 index 0000000000..24fda08e2d --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/special_marks.rs @@ -0,0 +1,162 @@ +use std::borrow::Cow; +use std::ops::Range; + +use gtk4::prelude::*; +use gtk4::{self as gtk, gdk, pango}; + +use crate::services::grid::special_characters::{Mark, reveal, special_characters}; + +// Adwaita's orange 3 under a third of its strength, as the macOS app boxes +// each mark in the system orange: the value's own colour stays readable on +// it in both styles and on a selected row. +const TINT: (u16, u16, u16) = (0xFFFF, 0x7878, 0x0000); +const TINT_ALPHA: u16 = 0x5555; +const TAG_NAME: &str = "tp-special-character"; + +fn tint_rgba() -> gdk::RGBA { + gdk::RGBA::new(1.0, 120.0 / 255.0, 0.0, f32::from(TINT_ALPHA) / f32::from(u16::MAX)) +} + +// An editor cannot write a character's name in its place, so Pango draws +// each one the way it shows hidden characters. Not SPACES: a text view then +// marks every space of the paragraph, and a special space has the tint. +fn shown_in_editors() -> pango::ShowFlags { + pango::ShowFlags::LINE_BREAKS | pango::ShowFlags::IGNORABLES +} + +fn byte_index(index: usize) -> u32 { + u32::try_from(index).unwrap_or(u32::MAX) +} + +fn insert(attributes: &pango::AttrList, attribute: impl Into, range: &Range) { + let mut attribute = attribute.into(); + attribute.set_start_index(range.start); + attribute.set_end_index(range.end); + attributes.insert(attribute); +} + +fn insert_tint(attributes: &pango::AttrList, range: &Range) { + let (red, green, blue) = TINT; + insert(attributes, pango::AttrColor::new_background(red, green, blue), range); + insert(attributes, pango::AttrInt::new_background_alpha(TINT_ALPHA), range); +} + +/// `base` with a tinted box under each mark, a label a size smaller so it +/// reads apart from the value around it. +fn marked_attributes(base: Option<&pango::AttrList>, marks: &[Mark]) -> pango::AttrList { + let attributes = base.and_then(pango::AttrList::copy).unwrap_or_default(); + for mark in marks { + let range = byte_index(mark.range.start)..byte_index(mark.range.end); + insert_tint(&attributes, &range); + if mark.labelled { + insert(&attributes, pango::AttrFloat::new_scale(pango::SCALE_SMALL), &range); + } + } + attributes +} + +/// What a one-line view draws for a value: its text, with each special +/// character written as its mark while `marks` holds. +pub(crate) struct Drawn<'a> { + pub text: Cow<'a, str>, + pub attributes: Option, +} + +// Drawing and column width both take the value from here, so a column is +// as wide as the marks its cells draw. +pub(crate) fn drawn<'a>(text: &'a str, attributes: Option<&pango::AttrList>, marks: bool) -> Drawn<'a> { + match marks.then(|| reveal(text)).flatten() { + Some(revealed) => Drawn { + attributes: Some(marked_attributes(attributes, &revealed.marks)), + text: Cow::Owned(revealed.text), + }, + None => Drawn { + text: Cow::Borrowed(text), + attributes: attributes.cloned(), + }, + } +} + +pub(crate) fn show_value(display: >k::Inscription, text: &str, attributes: Option<&pango::AttrList>, marks: bool) { + let drawn = drawn(text, attributes, marks); + display.set_text(Some(&drawn.text)); + display.set_attributes(drawn.attributes.as_ref()); +} + +/// The inline editor's marks, rebuilt from its text; its text stays as typed. +pub(crate) fn mark_field(field: >k::Text, marks: bool) { + let attributes = pango::AttrList::new(); + let text = field.text(); + let mut found = false; + if marks { + for special in special_characters(&text, false) { + let range = byte_index(special.range.start)..byte_index(special.range.end); + insert(&attributes, pango::AttrInt::new_show(shown_in_editors()), &range); + insert_tint(&attributes, &range); + found = true; + } + } + field.set_attributes(found.then_some(&attributes)); +} + +/// A text view's marks, through a tag, so neither its text, its selection +/// nor its undo history changes. +pub(crate) fn mark_buffer(buffer: >k::TextBuffer, marks: bool) { + let (start, end) = buffer.bounds(); + let tag = special_tag(buffer); + buffer.remove_tag(&tag, &start, &end); + if !marks { + return; + } + let text = buffer.text(&start, &end, true); + let mut offset = 0; + let mut scanned = 0; + for special in special_characters(&text, false) { + offset += char_count(&text[scanned..special.range.start]); + let length = char_count(&text[special.range.clone()]); + buffer.apply_tag( + &tag, + &buffer.iter_at_offset(offset), + &buffer.iter_at_offset(offset + length), + ); + offset += length; + scanned = special.range.end; + } +} + +fn char_count(text: &str) -> i32 { + i32::try_from(text.chars().count()).unwrap_or(i32::MAX) +} + +fn special_tag(buffer: >k::TextBuffer) -> gtk::TextTag { + let table = buffer.tag_table(); + if let Some(tag) = table.lookup(TAG_NAME) { + return tag; + } + let tag = gtk::TextTag::builder() + .name(TAG_NAME) + .show_spaces(shown_in_editors()) + .background_rgba(&tint_rgba()) + .build(); + table.add(&tag); + tag +} + +#[cfg(test)] +pub(crate) fn tagged_ranges(buffer: >k::TextBuffer) -> Vec<(i32, i32)> { + let Some(tag) = buffer.tag_table().lookup(TAG_NAME) else { + return Vec::new(); + }; + let mut ranges = Vec::new(); + let mut at = buffer.start_iter(); + loop { + if at.starts_tag(Some(&tag)) { + let mut end = at; + end.forward_to_tag_toggle(Some(&tag)); + ranges.push((at.offset(), end.offset())); + } + if !at.forward_to_tag_toggle(Some(&tag)) { + return ranges; + } + } +} diff --git a/linux/crates/app/src/ui/data_grid/tests/cells.rs b/linux/crates/app/src/ui/data_grid/tests/cells.rs index 0e32c1c01d..8efbdaf20b 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -607,3 +607,113 @@ fn row_height_preferences_change_the_allocated_row_height() { assert_eq!(row_widget(&cell), row); assert_eq!(grid.cell_of(1, 1), cell); } + +#[gtk4::test] +fn date_formats_update_every_grid_without_crossing_settings_backends() { + use tablepro_core::value::Temporal; + + let day = chrono::NaiveDate::from_ymd_opt(2026, 11, 8).expect("a date"); + let columns = || vec![named("id", "integer", true), named("day", "date", false)]; + let values = vec![vec![Value::Int(1), Value::Date(Temporal::Finite(day))]]; + let first = Grid::open(columns(), values.clone()); + let settings = first.grid.config().expect("configured grid").settings.clone(); + let shared = || { + Grid::build( + GridSpec { + settings: Some(settings.clone()), + ..GridSpec::results(columns()) + }, + results(&values), + ) + }; + let second = shared(); + let isolated = Grid::open(columns(), values.clone()); + let first_cell = first.cell_of(1, 1); + let second_cell = second.cell_at(0, 1); + assert_eq!(Grid::display_text(&first_cell), "2026-11-08"); + assert_eq!(Grid::display_text(&second_cell), "2026-11-08"); + + settings.set_date_format("eu-short").expect("choose European dates"); + drain_main_context(); + assert_eq!(Grid::display_text(&first_cell), "08/11/2026"); + assert_eq!(Grid::display_text(&second_cell), "08/11/2026"); + assert_eq!(Grid::display_text(&isolated.cell_of(1, 1)), "2026-11-08"); + let reopened = shared(); + assert_eq!(Grid::display_text(&reopened.cell_at(0, 1)), "08/11/2026"); + + settings.set_date_format("us-short").expect("choose US dates"); + drain_main_context(); + assert_eq!(Grid::display_text(&first_cell), "11/08/2026"); + assert_eq!(Grid::display_text(&second_cell), "11/08/2026"); + assert_eq!(Grid::display_text(&reopened.cell_at(0, 1)), "11/08/2026"); +} + +fn marked_value(text: &str) -> Grid { + Grid::open( + two_text_columns(), + vec![vec![Value::Int(1), Value::Text(text.to_owned())]], + ) +} + +#[gtk4::test] +fn cells_mark_invisible_characters_until_preferences_turn_it_off() { + let grid = marked_value("a\u{200b}b\u{a0}c\nd\te f"); + + let cell = grid.cell_of(1, 1); + assert_eq!(Grid::display_text(&cell), "aZWSPb\u{a0}cLFd\te f"); + assert!(has_attribute(&cell, pango::AttrType::Background)); + assert!(has_attribute(&cell, pango::AttrType::Scale)); + + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + settings.set_show_invisible_characters(false).expect("store the flag"); + drain_main_context(); + let cell = grid.cell_of(1, 1); + assert_eq!(Grid::display_text(&cell), "a\u{200b}b\u{a0}c\nd\te f"); + assert!(!has_attribute(&cell, pango::AttrType::Background)); + + settings.set_show_invisible_characters(true).expect("store the flag"); + drain_main_context(); + assert_eq!(Grid::display_text(&grid.cell_of(1, 1)), "aZWSPb\u{a0}cLFd\te f"); +} + +#[gtk4::test] +fn a_cell_with_nothing_to_mark_draws_its_value_as_it_is() { + let grid = marked_value("plain text"); + + let cell = grid.cell_of(1, 1); + assert_eq!(Grid::display_text(&cell), "plain text"); + assert!(!has_attribute(&cell, pango::AttrType::Background)); +} + +#[gtk4::test] +fn the_inline_editor_marks_invisible_characters_and_keeps_its_text() { + let grid = marked_value("a\u{200b}b"); + let cell = grid.focus(0, 1); + assert!(grid.grid.edit().edit_cell(&cell)); + let field = grid.grid.edit().open_text().expect("an inline editor"); + let shown = |field: >k::Text| -> Vec<(u32, u32)> { + field + .attributes() + .map(|list| { + list.attributes() + .iter() + .filter(|attr| attr.type_() == pango::AttrType::Show) + .map(|attr| (attr.start_index(), attr.end_index())) + .collect() + }) + .unwrap_or_default() + }; + + assert_eq!(field.text(), "a\u{200b}b"); + assert_eq!(shown(&field), [(1, 4)]); + field.set_text("plain"); + assert!(shown(&field).is_empty()); + field.set_text("x\u{1}"); + assert_eq!(shown(&field), [(1, 2)]); + + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + settings.set_show_invisible_characters(false).expect("store the flag"); + drain_main_context(); + assert!(shown(&field).is_empty()); + assert_eq!(field.text(), "x\u{1}"); +} diff --git a/linux/crates/app/src/ui/data_grid/tests/columns.rs b/linux/crates/app/src/ui/data_grid/tests/columns.rs index b03a7c5e21..50a8fa9e32 100644 --- a/linux/crates/app/src/ui/data_grid/tests/columns.rs +++ b/linux/crates/app/src/ui/data_grid/tests/columns.rs @@ -891,3 +891,86 @@ fn null_text_resizes_automatic_columns_and_preserves_manual_widths() { assert_eq!(column.fixed_width(), 260, "the chosen width stays"); } } + +#[gtk4::test] +fn timestamp_formats_resize_automatic_columns_but_keep_manual_widths() { + let timestamp = chrono::NaiveDate::from_ymd_opt(2026, 11, 8) + .expect("a date") + .and_hms_opt(13, 4, 5) + .expect("a time"); + let grid = Grid::open( + vec![named("id", "integer", true), named("at", "timestamp", false)], + vec![vec![Value::Int(1), Value::Timestamp(Temporal::Finite(timestamp))]], + ); + let settings = grid.grid.config().expect("configured grid").settings.clone(); + let column = data_column(&grid, 1); + settings.set_date_format("us-short").expect("short date"); + drain_main_context(); + let short = column.fixed_width(); + + settings.set_date_format("us-long").expect("date and time"); + wait_until(WAIT, || column.fixed_width() > short).expect("long format widens the column"); + let long = column.fixed_width(); + assert_eq!(Grid::display_text(&grid.cell_of(1, 1)), "11/08/2026 01:04:05 PM"); + wait_until(WAIT, || { + shows_whole(grid.cell_of(1, 1).display().expect("cell display")) + }) + .expect("the whole date and time fits"); + + settings.set_date_format("eu-short").expect("short European date"); + wait_until(WAIT, || column.fixed_width() < long).expect("short format narrows an automatic column"); + column.set_fixed_width(320); + settings.set_date_format("us-long").expect("date and time again"); + drain_main_context(); + assert_eq!(column.fixed_width(), 320, "a manual width stays"); +} + +/// Whether `display` has the width its text takes as it draws it, under +/// its own attributes. +fn draws_whole(display: >k::Inscription) -> bool { + let layout = display.create_pango_layout(display.text().as_deref()); + layout.set_attributes(display.attributes().as_ref()); + display.width() > 0 && layout.pixel_size().0 <= display.width() +} + +#[gtk4::test] +fn invisible_character_marks_resize_automatic_columns_and_preserve_manual_widths() { + for editable in [false, true] { + let settings = crate::test_support::MemorySettings::new(); + settings + .get() + .set_show_invisible_characters(false) + .expect("start without marks"); + let columns = two_text_columns(); + let spec = if editable { + GridSpec::table(columns) + } else { + GridSpec::results(columns) + }; + let values = vec![vec![ + Value::Int(1), + Value::Text("a\u{200b}b\u{200b}c\u{200b}d\u{200b}e".into()), + ]]; + let rows = if editable { persisted(&values) } else { results(&values) }; + let grid = Grid::build( + GridSpec { + settings: Some(settings.get().clone()), + ..spec + }, + rows, + ); + let column = data_column(&grid, 1); + let original = column.fixed_width(); + + settings.get().set_show_invisible_characters(true).expect("show marks"); + wait_until(WAIT, || column.fixed_width() > original).expect("automatic column grows"); + wait_until(WAIT, || { + draws_whole(grid.cell_at(0, 1).display().expect("cell display")) + }) + .expect("the whole marked value fits"); + column.set_fixed_width(260); + settings.get().set_show_invisible_characters(false).expect("hide marks"); + drain_main_context(); + assert_eq!(column.fixed_width(), 260, "the chosen width stays"); + } +} diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index b811995241..c528b1acff 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -4,7 +4,9 @@ use gtk4::prelude::*; use gtk4::subclass::prelude::*; use libadwaita as adw; use tablepro_linux_platform::AppSettings; -use tablepro_linux_platform::settings::{GridRowHeight, keys}; +use tablepro_linux_platform::settings::{ + DateFormat, DefaultSort, GridRowHeight, GridSortDirection, RowCopyFormat, keys, +}; mod imp { use libadwaita::prelude::*; @@ -30,6 +32,18 @@ mod imp { #[template_child] pub row_numbers_row: TemplateChild, #[template_child] + pub auto_inspector_row: TemplateChild, + #[template_child] + pub invisibles_row: TemplateChild, + #[template_child] + pub date_format_row: TemplateChild, + #[template_child] + pub default_sort_row: TemplateChild, + #[template_child] + pub default_sort_direction_row: TemplateChild, + #[template_child] + pub row_copy_format_row: TemplateChild, + #[template_child] pub row_height_row: TemplateChild, #[template_child] pub null_display_row: TemplateChild, @@ -113,22 +127,64 @@ impl DataBrowserGroup { }) .build(); gio_settings - .bind(keys::GRID_ROW_HEIGHT, &imp.row_height_row.get(), "selected") - .mapping(|variant, _| { - let height = variant.str()?; - let index = GridRowHeight::ALL - .iter() - .position(|candidate| candidate.nick() == height)?; - Some((index as u32).to_value()) - }) - .set_mapping(|value, _| { - let index = value.get::().ok()?; - Some(GridRowHeight::ALL.get(index as usize)?.nick().to_variant()) - }) + .bind(keys::AUTO_SHOW_INSPECTOR, &imp.auto_inspector_row.get(), "active") + .build(); + bind_choice( + &imp.row_height_row.get(), + gio_settings, + keys::GRID_ROW_HEIGHT, + GridRowHeight::ALL.map(GridRowHeight::nick), + ); + gio_settings + .bind(keys::SHOW_INVISIBLE_CHARACTERS, &imp.invisibles_row.get(), "active") .build(); + bind_choice( + &imp.date_format_row.get(), + gio_settings, + keys::DATE_FORMAT, + DateFormat::ALL.map(DateFormat::nick), + ); + bind_choice( + &imp.default_sort_row.get(), + gio_settings, + keys::DEFAULT_SORT, + DefaultSort::ALL.map(DefaultSort::nick), + ); + bind_choice( + &imp.default_sort_direction_row.get(), + gio_settings, + keys::DEFAULT_SORT_DIRECTION, + GridSortDirection::ALL.map(GridSortDirection::nick), + ); + bind_choice( + &imp.row_copy_format_row.get(), + gio_settings, + keys::ROW_COPY_FORMAT, + RowCopyFormat::ALL.map(RowCopyFormat::nick), + ); } } +fn bind_choice( + row: &adw::ComboRow, + settings: &gio::Settings, + key: &'static str, + words: [&'static str; N], +) { + settings + .bind(key, row, "selected") + .mapping(move |variant, _| { + let word = variant.str()?; + let index = words.iter().position(|candidate| *candidate == word)?; + Some((index as u32).to_value()) + }) + .set_mapping(move |value, _| { + let index = value.get::().ok()?; + Some(words.get(index as usize)?.to_variant()) + }) + .build(); +} + #[cfg(test)] mod tests { use libadwaita::prelude::*; @@ -169,6 +225,39 @@ mod tests { assert!(settings.get().show_alternate_rows()); } + #[gtk4::test] + fn automatic_details_switches_stay_in_sync() { + let settings = MemorySettings::new(); + let first = bound_group(&settings); + let second = bound_group(&settings); + assert!(!first.imp().auto_inspector_row.is_active()); + + first.imp().auto_inspector_row.set_active(true); + assert!(settings.get().auto_show_inspector()); + assert!(second.imp().auto_inspector_row.is_active()); + settings.get().set_auto_show_inspector(false).expect("store the flag"); + assert!(!first.imp().auto_inspector_row.is_active()); + assert!(!second.imp().auto_inspector_row.is_active()); + } + + #[gtk4::test] + fn invisible_character_switches_follow_each_other_and_external_settings() { + let settings = MemorySettings::new(); + let first = bound_group(&settings); + let second = bound_group(&settings); + assert!(first.imp().invisibles_row.is_active()); + + first.imp().invisibles_row.set_active(false); + assert!(!settings.get().show_invisible_characters()); + assert!(!second.imp().invisibles_row.is_active()); + settings + .get() + .set_show_invisible_characters(true) + .expect("store the flag"); + assert!(first.imp().invisibles_row.is_active()); + assert!(second.imp().invisibles_row.is_active()); + } + #[gtk4::test] fn the_group_is_titled_for_the_data_browser() { let settings = MemorySettings::new(); @@ -258,4 +347,76 @@ mod tests { assert!(first.imp().grid_system_font_row.is_active()); assert!(!second.imp().grid_font_row.is_sensitive()); } + + #[gtk4::test] + fn copy_format_rows_follow_every_choice_from_both_windows() { + let settings = MemorySettings::new(); + let first = bound_group(&settings); + let second = bound_group(&settings); + + for (index, format) in RowCopyFormat::ALL.into_iter().enumerate() { + first.imp().row_copy_format_row.set_selected(index as u32); + assert_eq!(settings.get().row_copy_format(), format); + assert_eq!(second.imp().row_copy_format_row.selected(), index as u32); + } + for (index, format) in RowCopyFormat::ALL.into_iter().enumerate().rev() { + settings + .get() + .set_row_copy_format(format.nick()) + .expect("store copy format"); + assert_eq!(first.imp().row_copy_format_row.selected(), index as u32); + assert_eq!(second.imp().row_copy_format_row.selected(), index as u32); + } + second.imp().row_copy_format_row.set_selected(2); + assert_eq!(first.imp().row_copy_format_row.selected(), 2); + assert_eq!(settings.get().row_copy_format(), RowCopyFormat::Json); + } + #[gtk4::test] + fn default_sort_rows_follow_other_windows_and_external_settings() { + let settings = MemorySettings::new(); + let first = bound_group(&settings); + let second = bound_group(&settings); + first.imp().default_sort_row.set_selected(1); + first.imp().default_sort_direction_row.set_selected(1); + assert_eq!(settings.get().default_sort(), DefaultSort::PrimaryKey); + assert_eq!(settings.get().default_sort_direction(), GridSortDirection::Descending); + assert_eq!(second.imp().default_sort_row.selected(), 1); + assert_eq!(second.imp().default_sort_direction_row.selected(), 1); + + settings.get().set_default_sort("first-column").expect("default sort"); + settings + .get() + .set_default_sort_direction("ascending") + .expect("direction"); + for group in [&first, &second] { + assert_eq!(group.imp().default_sort_row.selected(), 2); + assert_eq!(group.imp().default_sort_direction_row.selected(), 0); + } + } + + #[gtk4::test] + fn date_format_rows_follow_both_windows_and_external_settings() { + let settings = MemorySettings::new(); + let first = bound_group(&settings); + let second = bound_group(&settings); + assert_eq!(first.imp().date_format_row.selected(), 0); + assert_eq!(second.imp().date_format_row.selected(), 0); + + for (index, format) in DateFormat::ALL.into_iter().enumerate() { + first.imp().date_format_row.set_selected(index as u32); + assert_eq!(settings.get().date_format(), format); + assert_eq!(second.imp().date_format_row.selected(), index as u32); + } + for (index, format) in DateFormat::ALL.into_iter().enumerate().rev() { + settings + .get() + .set_date_format(format.nick()) + .expect("store date format"); + assert_eq!(first.imp().date_format_row.selected(), index as u32); + assert_eq!(second.imp().date_format_row.selected(), index as u32); + } + second.imp().date_format_row.set_selected(2); + assert_eq!(first.imp().date_format_row.selected(), 2); + assert_eq!(settings.get().date_format(), DateFormat::UsLong); + } } diff --git a/linux/crates/app/src/ui/workspace/tab_spec.rs b/linux/crates/app/src/ui/workspace/tab_spec.rs index ad6bdbf233..e27f926216 100644 --- a/linux/crates/app/src/ui/workspace/tab_spec.rs +++ b/linux/crates/app/src/ui/workspace/tab_spec.rs @@ -2,7 +2,7 @@ use tablepro_core::meta::TableRef; use tablepro_storage::DraftId; use super::structure_target::StructureTarget; -use crate::ui::browse_tab::TableFilter; +use crate::ui::browse_tab::{InitialSort, TableFilter}; use crate::workspace::{DiagramPlace, EditorFileRecord}; /// A tab to open. Every way a tab opens builds one of these: the sidebar, @@ -45,8 +45,7 @@ pub(crate) enum TabSpec { pub(crate) struct TablePage { pub offset: u64, pub page_size: u64, - /// The column index and whether it sorts ascending. - pub sort: Option<(usize, bool)>, + pub sort: InitialSort, } impl TablePage { @@ -54,7 +53,7 @@ impl TablePage { Self { offset: 0, page_size, - sort: None, + sort: InitialSort::Default, } } } diff --git a/linux/crates/app/src/ui/workspace/tests/references.rs b/linux/crates/app/src/ui/workspace/tests/references.rs index b054047d2b..b97a0ebd0c 100644 --- a/linux/crates/app/src/ui/workspace/tests/references.rs +++ b/linux/crates/app/src/ui/workspace/tests/references.rs @@ -234,3 +234,106 @@ fn a_followed_tab_keeps_its_filter_in_the_saved_tabs_and_through_a_reopen() { assert_eq!(reopened.table(), "customers"); assert_eq!(reopened.applied_filter(), customer("42").filter); } + +#[gtk4::test] +fn reopening_a_closed_unsorted_table_does_not_apply_the_default() { + let test = TestWindow::connected_with("ReopenUnsortedGrid", serving_tables); + test.services + .settings + .set_default_sort("primary-key") + .expect("default sort"); + test.services + .settings + .set_default_sort_direction("descending") + .expect("direction"); + let (_, page) = open_orders(&test); + let tab = page.child().downcast::().expect("table tab"); + wait_until(WAIT, || !tab.is_loading() && tab.grid().store().len() == 1).expect("initial page"); + assert_eq!(tab.current_sort(), Some((0, false))); + tab.grid().sort_by(None); + wait_until(WAIT, || !tab.is_loading() && tab.current_sort().is_none()).expect("clear sort"); + let workspace = test.workspace(); + let view = shell_of(&workspace).imp().tab_view.clone(); + let count = view.n_pages(); + workspace + .sender() + .expect("input") + .deliver(WorkspaceInput::CloseActiveWorkspaceTab); + wait_until(WAIT, || view.n_pages() < count).expect("closed table"); + + WidgetExt::activate_action(&test.window, "win.reopen-closed-tab", None).expect("reopen"); + let mut reopened = None; + wait_until(WAIT, || { + reopened = view + .selected_page() + .filter(|candidate| candidate != &page) + .and_then(|page| page.child().downcast::().ok()); + reopened + .as_ref() + .is_some_and(|tab| !tab.is_loading() && tab.grid().store().len() == 1) + }) + .expect("reopened table"); + assert_eq!(reopened.expect("tab").current_sort(), None); +} + +#[gtk4::test] +fn session_restore_keeps_an_unsorted_first_page() { + use crate::test_support::finish_on_main; + use crate::ui::SessionWindowInput; + use crate::ui::session_window::tests::Script; + use crate::workspace::WorkspaceRecord; + + let mut connection = ConnectionScript::default(); + serving_tables(&mut connection); + let test = TestWindow::with_script( + "RestoreUnsortedGrid", + Script { + connection, + ..Script::default() + }, + ); + test.services + .settings + .set_default_sort("primary-key") + .expect("default sort"); + test.services + .settings + .set_default_sort_direction("descending") + .expect("direction"); + let store = test.services.storage.workspaces(); + store + .schedule( + &test.key(), + WorkspaceRecord { + active_tab: Some(0), + tabs: vec![TabRecord::Table { + schema: None, + table: "orders".into(), + offset: 0, + page_size: 100, + sort: None, + filter: None, + }], + }, + ) + .expect("saved table"); + finish_on_main(WAIT, store.flush(&test.key())) + .expect("flush") + .expect("save"); + + test.window + .send(SessionWindowInput::OpenSaved(Box::new(test.saved.clone()))); + test.wait_for_page("workspace"); + let view = shell_of(&test.workspace()).imp().tab_view.clone(); + let mut restored = None; + wait_until(WAIT, || { + restored = view + .selected_page() + .and_then(|page| page.child().downcast::().ok()); + restored + .as_ref() + .is_some_and(|tab| !tab.is_loading() && tab.grid().store().len() == 1) + }) + .expect("restored table"); + assert_eq!(restored.expect("tab").current_sort(), None); +} diff --git a/linux/crates/app/src/ui/workspace/workspace_tabs.rs b/linux/crates/app/src/ui/workspace/workspace_tabs.rs index 98e2fe5436..38286b614f 100644 --- a/linux/crates/app/src/ui/workspace/workspace_tabs.rs +++ b/linux/crates/app/src/ui/workspace/workspace_tabs.rs @@ -1,3 +1,4 @@ +use crate::ui::browse_tab::InitialSort; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::rc::Rc; @@ -145,7 +146,7 @@ impl WorkspaceModel { page: TablePage { offset, page_size, - sort: sort.map(|sort| (sort.column, sort.ascending)), + sort: InitialSort::Kept(sort.map(|sort| (sort.column, sort.ascending))), }, filter: filter.map_or(TableFilter::Remembered, TableFilter::Kept), }, @@ -985,7 +986,7 @@ impl WorkspaceModel { page: TablePage { offset, page_size, - sort, + sort: InitialSort::Kept(sort), }, filter: TableFilter::Kept(filter), }); diff --git a/linux/crates/platform/src/settings/grid_preferences.rs b/linux/crates/platform/src/settings/grid_preferences.rs index f23cbb69dc..b8b034d86b 100644 --- a/linux/crates/platform/src/settings/grid_preferences.rs +++ b/linux/crates/platform/src/settings/grid_preferences.rs @@ -47,23 +47,180 @@ impl GridRowHeight { } } +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum RowCopyFormat { + #[default] + Rows, + RowsWithHeaders, + Json, + Csv, + CsvWithHeaders, + Markdown, +} + +impl RowCopyFormat { + pub const ALL: [Self; 6] = [ + Self::Rows, + Self::RowsWithHeaders, + Self::Json, + Self::Csv, + Self::CsvWithHeaders, + Self::Markdown, + ]; + + pub fn from_nick(nick: &str) -> Self { + match nick { + "rows-headers" => Self::RowsWithHeaders, + "json" => Self::Json, + "csv" => Self::Csv, + "csv-headers" => Self::CsvWithHeaders, + "markdown" => Self::Markdown, + _ => Self::Rows, + } + } + + pub fn nick(self) -> &'static str { + match self { + Self::Rows => "rows", + Self::RowsWithHeaders => "rows-headers", + Self::Json => "json", + Self::Csv => "csv", + Self::CsvWithHeaders => "csv-headers", + Self::Markdown => "markdown", + } + } +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum DefaultSort { + #[default] + None, + PrimaryKey, + FirstColumn, +} + +impl DefaultSort { + pub const ALL: [Self; 3] = [Self::None, Self::PrimaryKey, Self::FirstColumn]; + + pub fn from_nick(nick: &str) -> Self { + match nick { + "primary-key" => Self::PrimaryKey, + "first-column" => Self::FirstColumn, + _ => Self::None, + } + } + + pub fn nick(self) -> &'static str { + match self { + Self::None => "none", + Self::PrimaryKey => "primary-key", + Self::FirstColumn => "first-column", + } + } +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum GridSortDirection { + #[default] + Ascending, + Descending, +} + +impl GridSortDirection { + pub const ALL: [Self; 2] = [Self::Ascending, Self::Descending]; + + pub fn from_nick(nick: &str) -> Self { + match nick { + "descending" => Self::Descending, + _ => Self::Ascending, + } + } + + pub fn nick(self) -> &'static str { + match self { + Self::Ascending => "ascending", + Self::Descending => "descending", + } + } + + pub fn ascending(self) -> bool { + self == Self::Ascending + } +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum DateFormat { + #[default] + Iso, + IsoDate, + UsLong, + UsShort, + EuLong, + EuShort, +} + +impl DateFormat { + pub const ALL: [Self; 6] = [ + Self::Iso, + Self::IsoDate, + Self::UsLong, + Self::UsShort, + Self::EuLong, + Self::EuShort, + ]; + + pub fn from_nick(nick: &str) -> Self { + match nick { + "iso-date" => Self::IsoDate, + "us-long" => Self::UsLong, + "us-short" => Self::UsShort, + "eu-long" => Self::EuLong, + "eu-short" => Self::EuShort, + _ => Self::Iso, + } + } + + pub fn nick(self) -> &'static str { + match self { + Self::Iso => "iso", + Self::IsoDate => "iso-date", + Self::UsLong => "us-long", + Self::UsShort => "us-short", + Self::EuLong => "eu-long", + Self::EuShort => "eu-short", + } + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct GridPreferenceValues { + pub date_format: DateFormat, + pub default_sort: DefaultSort, + pub default_sort_direction: GridSortDirection, pub show_row_numbers: bool, pub show_alternate_rows: bool, pub row_height: GridRowHeight, pub null_display: String, pub font: EditorFont, + pub row_copy_format: RowCopyFormat, + pub auto_show_inspector: bool, + pub show_invisible_characters: bool, } impl Default for GridPreferenceValues { fn default() -> Self { Self { + date_format: DateFormat::Iso, + default_sort: DefaultSort::None, + default_sort_direction: GridSortDirection::Ascending, show_row_numbers: true, show_alternate_rows: true, row_height: GridRowHeight::Normal, null_display: "NULL".to_owned(), font: EditorFont::System, + row_copy_format: RowCopyFormat::Rows, + auto_show_inspector: false, + show_invisible_characters: true, } } } @@ -71,6 +228,12 @@ impl Default for GridPreferenceValues { impl GridPreferenceValues { fn read(settings: &gio::Settings) -> Self { Self { + date_format: DateFormat::from_nick(&settings.string(keys::DATE_FORMAT)), + row_copy_format: RowCopyFormat::from_nick(&settings.string(keys::ROW_COPY_FORMAT)), + auto_show_inspector: settings.boolean(keys::AUTO_SHOW_INSPECTOR), + show_invisible_characters: settings.boolean(keys::SHOW_INVISIBLE_CHARACTERS), + default_sort: DefaultSort::from_nick(&settings.string(keys::DEFAULT_SORT)), + default_sort_direction: GridSortDirection::from_nick(&settings.string(keys::DEFAULT_SORT_DIRECTION)), show_row_numbers: settings.boolean(keys::SHOW_ROW_NUMBERS), show_alternate_rows: settings.boolean(keys::SHOW_ALTERNATE_ROWS), row_height: GridRowHeight::from_nick(&settings.string(keys::GRID_ROW_HEIGHT)), @@ -143,11 +306,17 @@ impl GridPreferences { if matches!( key, keys::SHOW_ROW_NUMBERS + | keys::DATE_FORMAT + | keys::DEFAULT_SORT + | keys::DEFAULT_SORT_DIRECTION | keys::SHOW_ALTERNATE_ROWS | keys::GRID_ROW_HEIGHT | keys::NULL_DISPLAY | keys::GRID_USE_SYSTEM_FONT | keys::GRID_FONT + | keys::ROW_COPY_FORMAT + | keys::AUTO_SHOW_INSPECTOR + | keys::SHOW_INVISIBLE_CHARACTERS ) && let Some(preferences) = weak.upgrade() { preferences.update(GridPreferenceValues::read(settings)); diff --git a/linux/crates/platform/src/settings/keys.rs b/linux/crates/platform/src/settings/keys.rs index fd4fe976b9..e4c21ca8a6 100644 --- a/linux/crates/platform/src/settings/keys.rs +++ b/linux/crates/platform/src/settings/keys.rs @@ -11,6 +11,12 @@ pub const USE_SYSTEM_FONT: &str = "use-system-font"; pub const CUSTOM_FONT: &str = "custom-font"; pub const GRID_USE_SYSTEM_FONT: &str = "grid-use-system-font"; pub const GRID_FONT: &str = "grid-font"; +pub const AUTO_SHOW_INSPECTOR: &str = "auto-show-inspector"; +pub const DEFAULT_SORT: &str = "default-sort"; +pub const DEFAULT_SORT_DIRECTION: &str = "default-sort-direction"; +pub const SHOW_INVISIBLE_CHARACTERS: &str = "show-invisible-characters"; +pub const DATE_FORMAT: &str = "date-format"; +pub const ROW_COPY_FORMAT: &str = "row-copy-format"; pub const STYLE_SCHEME: &str = "style-scheme"; pub const VIM_KEYBINDINGS: &str = "vim-keybindings"; pub const CONNECT_DIALOG_DRIVER: &str = "connect-dialog-driver"; diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index 2ececf6c1d..5d7c96e2a6 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -14,7 +14,9 @@ use tablepro_core::export::{CsvDecimal, CsvDelimiter, CsvLineBreak, CsvOptions, pub use editor_font::EditorFont; pub use error::SettingsError; -pub use grid_preferences::{GridPreferenceValues, GridPreferences, GridRowHeight}; +pub use grid_preferences::{ + DateFormat, DefaultSort, GridPreferenceValues, GridPreferences, GridRowHeight, GridSortDirection, RowCopyFormat, +}; pub use window_geometry::WindowGeometry; /// The provider setting's value while the assistant is off. @@ -115,6 +117,54 @@ impl AppSettings { self.set_string(keys::GRID_ROW_HEIGHT, height) } + pub fn auto_show_inspector(&self) -> bool { + self.grid_preferences().snapshot().auto_show_inspector + } + + pub fn set_auto_show_inspector(&self, show: bool) -> Result<(), SettingsError> { + self.set_boolean(keys::AUTO_SHOW_INSPECTOR, show) + } + + pub fn default_sort(&self) -> DefaultSort { + self.grid_preferences().snapshot().default_sort + } + + pub fn set_default_sort(&self, behavior: &str) -> Result<(), SettingsError> { + self.set_string(keys::DEFAULT_SORT, behavior) + } + + pub fn default_sort_direction(&self) -> GridSortDirection { + self.grid_preferences().snapshot().default_sort_direction + } + + pub fn set_default_sort_direction(&self, direction: &str) -> Result<(), SettingsError> { + self.set_string(keys::DEFAULT_SORT_DIRECTION, direction) + } + + pub fn show_invisible_characters(&self) -> bool { + self.grid_preferences().snapshot().show_invisible_characters + } + + pub fn set_show_invisible_characters(&self, show: bool) -> Result<(), SettingsError> { + self.set_boolean(keys::SHOW_INVISIBLE_CHARACTERS, show) + } + + pub fn date_format(&self) -> DateFormat { + self.grid_preferences().snapshot().date_format + } + + pub fn set_date_format(&self, format: &str) -> Result<(), SettingsError> { + self.set_string(keys::DATE_FORMAT, format) + } + + pub fn row_copy_format(&self) -> RowCopyFormat { + self.grid_preferences().snapshot().row_copy_format + } + + pub fn set_row_copy_format(&self, format: &str) -> Result<(), SettingsError> { + self.set_string(keys::ROW_COPY_FORMAT, format) + } + pub fn null_display(&self) -> String { self.grid_preferences().snapshot().null_display.clone() } diff --git a/linux/crates/platform/tests/settings.rs b/linux/crates/platform/tests/settings.rs index b30491b437..e95371763f 100644 --- a/linux/crates/platform/tests/settings.rs +++ b/linux/crates/platform/tests/settings.rs @@ -533,3 +533,148 @@ async fn grid_font_uses_the_shared_snapshot_and_preserves_the_editor_font() -> T assert_eq!(calls.get(), 3); Ok(()) } + +#[glib::async_test] +async fn row_copy_format_publishes_every_format_through_the_shared_model() -> TestResult { + use std::cell::RefCell; + use std::rc::Rc; + use tablepro_linux_platform::settings::RowCopyFormat; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + let original = preferences.snapshot(); + let observed = Rc::new(RefCell::new(Vec::new())); + let updates = observed.clone(); + preferences.connect_changed(move |preferences| updates.borrow_mut().push(preferences.snapshot().row_copy_format)); + + assert_eq!(fixture.settings.row_copy_format(), RowCopyFormat::Rows); + for format in RowCopyFormat::ALL { + fixture.settings.set_row_copy_format(format.nick())?; + assert_eq!(fixture.settings.row_copy_format(), format); + assert_eq!(preferences.snapshot().row_copy_format, format); + assert_eq!(RowCopyFormat::from_nick(format.nick()), format); + } + assert_eq!(observed.borrow().as_slice(), &RowCopyFormat::ALL[1..]); + assert_eq!(original.row_copy_format, RowCopyFormat::Rows); + assert_eq!(RowCopyFormat::from_nick("unknown"), RowCopyFormat::Rows); + Ok(()) +} + +#[glib::async_test] +async fn automatic_details_preference_is_published_in_the_shared_snapshot() -> TestResult { + use gio::prelude::SettingsExt; + use std::cell::RefCell; + use std::rc::Rc; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + let original = preferences.snapshot(); + let observed = Rc::new(RefCell::new(Vec::new())); + let changes = observed.clone(); + preferences.connect_changed(move |preferences| { + changes.borrow_mut().push(preferences.snapshot().auto_show_inspector); + }); + assert!(!fixture.settings.auto_show_inspector()); + + fixture.settings.set_auto_show_inspector(true)?; + assert!(fixture.settings.auto_show_inspector()); + fixture.settings.gio().set_boolean(keys::AUTO_SHOW_INSPECTOR, false)?; + assert!(!fixture.settings.auto_show_inspector()); + assert_eq!(observed.borrow().as_slice(), &[true, false]); + assert!(!original.auto_show_inspector); + Ok(()) +} + +#[glib::async_test] +async fn default_sort_choices_and_direction_share_the_grid_snapshot() -> TestResult { + use tablepro_linux_platform::settings::{DefaultSort, GridSortDirection}; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + assert_eq!(preferences.snapshot().default_sort, DefaultSort::None); + assert_eq!( + preferences.snapshot().default_sort_direction, + GridSortDirection::Ascending + ); + for choice in DefaultSort::ALL { + fixture.settings.set_default_sort(choice.nick())?; + assert_eq!(preferences.snapshot().default_sort, choice); + } + for direction in GridSortDirection::ALL { + fixture.settings.set_default_sort_direction(direction.nick())?; + assert_eq!(preferences.snapshot().default_sort_direction, direction); + } + assert!(fixture.settings.set_default_sort("unknown").is_err()); + assert!(fixture.settings.set_default_sort_direction("sideways").is_err()); + Ok(()) +} + +#[glib::async_test] +async fn invisible_characters_preference_uses_the_shared_snapshot_and_external_updates() -> TestResult { + use gio::prelude::SettingsExt; + use std::cell::RefCell; + use std::rc::Rc; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + let original = preferences.snapshot(); + let observed = Rc::new(RefCell::new(Vec::new())); + let changes = observed.clone(); + preferences.connect_changed(move |preferences| { + changes + .borrow_mut() + .push(preferences.snapshot().show_invisible_characters); + }); + assert!(fixture.settings.show_invisible_characters()); + + fixture.settings.set_show_invisible_characters(false)?; + assert!(!fixture.settings.show_invisible_characters()); + fixture + .settings + .gio() + .set_boolean(keys::SHOW_INVISIBLE_CHARACTERS, true)?; + assert!(fixture.settings.show_invisible_characters()); + assert_eq!(observed.borrow().as_slice(), &[false, true]); + assert!(original.show_invisible_characters); + Ok(()) +} + +#[glib::async_test] +async fn date_format_publishes_all_choices_without_changing_other_backends() -> TestResult { + use gio::prelude::SettingsExt; + use std::cell::RefCell; + use std::rc::Rc; + use tablepro_linux_platform::settings::DateFormat; + + let fixture = Fixture::new()?; + let isolated = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + let original = preferences.snapshot(); + let observed = Rc::new(RefCell::new(Vec::new())); + let changes = observed.clone(); + preferences.connect_changed(move |preferences| changes.borrow_mut().push(preferences.snapshot().date_format)); + + assert_eq!(fixture.settings.date_format(), DateFormat::Iso); + for format in DateFormat::ALL.into_iter().skip(1).chain([DateFormat::Iso]) { + fixture.settings.gio().set_string(keys::DATE_FORMAT, format.nick())?; + assert_eq!(fixture.settings.date_format(), format); + assert_eq!(preferences.snapshot().date_format, format); + assert_eq!(DateFormat::from_nick(format.nick()), format); + assert_eq!(isolated.settings.date_format(), DateFormat::Iso); + } + assert_eq!( + observed.borrow().as_slice(), + &[ + DateFormat::IsoDate, + DateFormat::UsLong, + DateFormat::UsShort, + DateFormat::EuLong, + DateFormat::EuShort, + DateFormat::Iso, + ] + ); + assert_eq!(original.date_format, DateFormat::Iso); + assert_eq!(DateFormat::from_nick("unknown"), DateFormat::Iso); + assert!(fixture.settings.set_date_format("unknown").is_err()); + Ok(()) +} diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index c82785d5ae..2044a4b947 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -89,6 +89,67 @@ How much room a data grid row takes around its text. + + + + + + + + + + "rows" + Format of copied rows + The format Copy writes when several rows are selected. + + + + false + Open row details when a row is selected + Whether selecting a row in a data grid opens its row details pane. + + + + + + + + + "none" + Default sort of a table + The column a table tab sorts by when it opens, until the user picks another. + + + + + + + + "ascending" + Direction of the default sort + Which way a table tab sorts by its default column. + + + + true + Show invisible characters + Whether cells and value fields mark zero-width, control and special space characters. + + + + + + + + + + + + "iso" + Date format of cells + How the data grid spells dates and timestamps. A copy and an export keep the database's own spelling. + + "NULL" Text for a NULL value diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 40c40db731..280989f6b4 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -43,6 +43,85 @@ + + + Open Row Details on Selection + Selecting a row opens its details pane + + + + + Show Invisible Characters + Mark zero-width, control and special space characters in cells and value fields + + + + + Date Format + + How cells show dates and timestamps. Copy and export use the original values. + + + + + 2024-12-31 23:59:59 + 2024-12-31 + 12/31/2024 11:59:59 PM + 12/31/2024 + 31/12/2024 23:59:59 + 31/12/2024 + + + + + + + + Default Sort + How a table is ordered when it opens + + + + No sorting (server order) + Primary key + First column + + + + + + + + Default Sort Direction + + + + Ascending + Descending + + + + + + + + Copy Rows As + The format Copy writes when several rows are selected + + + + TSV + TSV with Headers + JSON + CSV + CSV with Headers + Markdown + + + + + Text for NULL diff --git a/linux/docs/state-management.md b/linux/docs/state-management.md index 5aca04ebab..1c7420b838 100644 --- a/linux/docs/state-management.md +++ b/linux/docs/state-management.md @@ -93,9 +93,11 @@ A tab belongs to its session, and a session to one window ([decisions/0028-sessi ## Grid preferences -`AppSettings` owns one `GridPreferences` object. It reads the grid keys from GSettings and announces each changed snapshot. Every grid holds that object through its settings and follows its change signal. Preferences rows bind directly to GSettings, including both directions for choices stored as strings. Each grid owns its font CSS provider, scoped to that grid and removed when the grid closes. Its custom font description supplies both the rendered font and column width measurement. +`AppSettings` owns one `GridPreferences` object. It reads the grid keys from GSettings and announces each changed snapshot. Every grid holds that object through its settings and follows its change signal. Preferences rows bind directly to GSettings, including both directions for choices stored as strings. Each grid owns its font CSS provider, scoped to that grid and removed when the grid closes. Its custom font description supplies both the rendered font and column width measurement. Show Invisible Characters reads the same snapshot. Cells and the row details' field list write each zero-width, control and special space character as its short name over a tint; the inline editor and the value editor mark it with a Pango attribute or a text tag, which leaves their text, selection and undo history as they are. Automatic Row Details opening reads the same snapshot when the selection changes and opens only for a nonempty selection. Closing it keeps it closed through focus changes and clearing the selection. Turning the preference off leaves an open pane alone. Copy reads the row format from the shared snapshot when it runs; a single focused cell keeps its value format, and Copy As keeps the requested format. -The snapshot belongs to its settings backend, so isolated test settings cannot change another grid. A display change redraws the existing row slots and resizes automatic columns. It keeps row selection, user column widths and active editor drafts. The formatting helpers receive display choices explicitly and keep no global preference state. +The snapshot belongs to its settings backend, so isolated test settings cannot change another grid. A display change redraws the existing row slots and resizes automatic columns. It keeps row selection, user column widths and active editor drafts. The formatting helpers receive display choices explicitly and keep no global preference state. Date display changes update cells, detail fields and automatic widths. Find captures the date format before its worker starts and repeats an active search when that format changes. The value editor, Copy and export retain the canonical value spelling. + +A new table tab snapshots the default sort from `GridPreferences`. `InitialSort::Default` is resolved once after accepted initial metadata, before its first page query. A metadata failure keeps it pending, and an explicit sort cancels it. Restored and reopened tabs carry `InitialSort::Kept`, including an unsorted first page. Later preference changes and refreshes preserve the tab's sort. The saved workspace format stays the same. ## The SQL editor diff --git a/linux/docs/storage.md b/linux/docs/storage.md index d70a66a716..2a5d22803a 100644 --- a/linux/docs/storage.md +++ b/linux/docs/storage.md @@ -345,6 +345,12 @@ The schema id is the application id and the path follows it: `app.tablepro.Table | `show-row-numbers` | `b` | `true` | | | `grid-use-system-font` | `b` | `true` | | | `grid-font` | `s` | `Monospace 10` | | +| `show-invisible-characters` | `b` | `true` | | +| `auto-show-inspector` | `b` | `false` | | +| `row-copy-format` | `s` | `rows` | rows, rows-headers, json, csv, csv-headers, markdown | +| `default-sort` | `s` | `none` | `none`, `primary-key`, `first-column` | +| `default-sort-direction` | `s` | `ascending` | `ascending`, `descending` | +| `date-format` | `s` | `iso` | iso, iso-date, us-long, us-short, eu-long, eu-short; display only, copy and export retain original values | | `grid-row-height` | `s` | `normal` | compact, normal, comfortable, spacious | | `null-display` | `s` | `NULL` | Displayed as at most 20 characters, without control characters; blank uses NULL | | `confirm-bulk-delete` | `b` | `true` | | diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 879e1aa5b7..03f8d99c48 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -83,6 +83,7 @@ crates/app/src/services/grid/cell_preset.rs crates/app/src/services/grid/column_layout.rs crates/app/src/services/grid/column_width.rs crates/app/src/services/grid/copy_scope.rs +crates/app/src/services/grid/date_display.rs crates/app/src/services/grid/delete_availability.rs crates/app/src/services/grid/display_text.rs crates/app/src/services/grid/edit_navigation.rs @@ -97,6 +98,7 @@ crates/app/src/services/grid/result_refusal.rs crates/app/src/services/grid/row_key_builder.rs crates/app/src/services/grid/row_snapshot.rs crates/app/src/services/grid/selection_summary.rs +crates/app/src/services/grid/special_characters.rs crates/app/src/services/grid/test_columns.rs crates/app/src/services/history_availability.rs crates/app/src/services/history_preferences.rs @@ -193,6 +195,7 @@ crates/app/src/ui/browse_tab/count_failure_text.rs crates/app/src/ui/browse_tab/count_policy.rs crates/app/src/ui/browse_tab/data_handlers.rs crates/app/src/ui/browse_tab/data_input.rs +crates/app/src/ui/browse_tab/default_sort.rs crates/app/src/ui/browse_tab/fetch.rs crates/app/src/ui/browse_tab/grid_handlers.rs crates/app/src/ui/browse_tab/grid_input.rs @@ -211,6 +214,7 @@ crates/app/src/ui/browse_tab/row_total.rs crates/app/src/ui/browse_tab/save_handlers.rs crates/app/src/ui/browse_tab/save_input.rs crates/app/src/ui/browse_tab/table_filter.rs +crates/app/src/ui/browse_tab/tests/default_sort.rs crates/app/src/ui/browse_tab/tests/load.rs crates/app/src/ui/browse_tab/tests/mod.rs crates/app/src/ui/browse_tab/tests/references.rs @@ -286,6 +290,7 @@ crates/app/src/ui/data_grid/row_detail/calendar.rs crates/app/src/ui/data_grid/row_detail/clock.rs crates/app/src/ui/data_grid/row_detail/fields.rs crates/app/src/ui/data_grid/row_detail/imp.rs +crates/app/src/ui/data_grid/row_detail/invisibles.rs crates/app/src/ui/data_grid/row_detail/mod.rs crates/app/src/ui/data_grid/row_detail/picture.rs crates/app/src/ui/data_grid/row_detail/tests.rs @@ -295,6 +300,7 @@ crates/app/src/ui/data_grid/row_number_column.rs crates/app/src/ui/data_grid/selection.rs crates/app/src/ui/data_grid/selection_summary.rs crates/app/src/ui/data_grid/server_sorter.rs +crates/app/src/ui/data_grid/special_marks.rs crates/app/src/ui/data_grid/stripes.rs crates/app/src/ui/data_grid/table_keys.rs crates/app/src/ui/data_grid/test_grid.rs