From 4d94d3e27c4ebecf75e93c7bf89b8c263768ec42 Mon Sep 17 00:00:00 2001 From: Aleksander Helgaker Date: Tue, 1 Dec 2026 10:54:16 +0100 Subject: [PATCH] =?UTF-8?q?Data:=20paste=20or=20import=20clipboard=20text?= =?UTF-8?q?=20as=20columns=20(Get=20Data=20=E2=80=BA=20From=20Clipboard?= =?UTF-8?q?=E2=80=A6,=20Paste=20Data=E2=80=A6)=20(#4839)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(data): paste or import clipboard text as columns Data › Get Data (Text/CSV) becomes a split button. Its menu adds From Clipboard…, and the cell menu adds Paste Data… after Paste Special…. Both open a dialog that asks for the separator (comma, semicolon, tab, space or another character), starting on the one the text uses. From Clipboard imports into a new sheet as a table, and Paste Data pastes the columns at the clicked cell. The dialog imports the text it read when it opened, and Paste Data names the sheet with its cell. - data.fromTextCsv: `at` pastes at a cell, Sheet!-qualified or on the active sheet. Without a delimiter, craft-csv's sniffer picks comma, semicolon or tab. JSON records are read only when no delimiter is given. The delimiter must be one character other than a quote or line break, up to U+00FF. The reader's cells are written with their number formats, so dates and percents keep them and formula-looking text stays text. - data.fromClipboard (UI command): the same with the system clipboard. - Key tips: Alt/F10, A, P, N opens the Get Data menu with G and C (APNC is new). Up/Down in a menu key tips opened moves focus onto its items, wrapping at the ends. Enter runs the focused item without also confirming what it opens. Co-Authored-By: Claude Opus 5.5 * fix(data): clipboard import review fixes and rustfmt - Paste Data's destination is a "Paste at" reference box holding the selection's top-left cell, the cell Paste uses. As in the other dialogs with reference boxes, OK shows the dialog's own sheet again first, found by its uid, and is refused once that sheet is deleted. - A paste at a cell covers every field of the text, trailing blank fields and records included, so they clear the cells under them. read_csv_with_report now reports the record count and the widest record. - CSV dates are read as serials of the destination workbook's date system (1900 or 1904). - The first arrow into a key-tip menu cancels the focus move egui had already queued, so it lands on the first item even when a ribbon button was focused. - cargo fmt. Co-Authored-By: Claude Opus 5.5 * fix(data): Paste Data refuses rows past the sheet and clears all-blank text - read_csv_with_report reports `truncated` when the text has records past a sheet's last row. A paste at a cell refuses such text before writing anything, instead of dropping the rest. Text with exactly MAX_ROWS records still pastes. - A paste at a cell uses the text's record extent even when it has no non-empty field, so text like `,` clears the cells it covers instead of failing as an empty file. Co-Authored-By: Claude Opus 5.5 * fix(data): Paste Data refuses text wider than a sheet The CSV reader keeps one field past MAX_COLS per record, so a wider record can be told from one that fits, and reports it as `truncated`, as it does records past the last row. A paste at a cell refuses such text before writing anything; text exactly MAX_COLS fields wide still pastes. Importing into a new sheet still keeps the first MAX_COLS fields, as before. Co-Authored-By: Claude Opus 5.5 * fix(data): read bracket-led text without a separator as delimited text From Text/CSV, Get Data and From Clipboard read any text whose first character is `[` as JSON when no separator was given, so delimited text whose first field is bracketed (`[Draft];Oslo`) was rejected with a JSON parse error. Text is now read as records only when it parses as a JSON array of objects; anything else goes to the delimited reader, which picks the separator by the text. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/extra.rs | 2 +- crates/engine/src/cmd/extra/data.rs | 335 ++++++++++++++---- crates/engine/src/io.rs | 6 + crates/ui-egui/src/app/clipboard.rs | 16 + crates/ui-egui/src/app/commands.rs | 1 + crates/ui-egui/src/control.rs | 5 + crates/ui-egui/src/dialogs.rs | 7 +- crates/ui-egui/src/dialogs/data.rs | 38 ++ crates/ui-egui/src/dialogs/show.rs | 12 +- crates/ui-egui/src/grid/menus.rs | 12 +- crates/ui-egui/src/keytips.rs | 13 + .../src/keytips/keytip_table/generated.rs | 1 + crates/ui-egui/src/keytips/keytips.json | 7 + crates/ui-egui/src/ribbon/controls.rs | 38 ++ crates/ui-egui/src/ribbon/data.rs | 17 +- crates/ui-egui/tests/it/clipboard.rs | 116 ++++++ crates/ui-egui/tests/it/keytips_generated.rs | 12 +- crates/ui-egui/tests/keytips.rs | 36 ++ crates/xlsx/src/csv.rs | 13 +- crates/xlsx/src/lib.rs | 7 + docs/ui-parity.md | 8 +- xtask/src/keytips.rs | 6 + 22 files changed, 630 insertions(+), 78 deletions(-) diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 47526bf4a..71493ef46 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -207,7 +207,7 @@ pub fn specs() -> Vec { "From Text/CSV", ["Data", "Get & Transform Data"], None, - "{path | text, delimiter?: \",\", sheet?: new sheet name} → imports into a new sheet as a table", + "{path | text, delimiter?: one character (comma, semicolon or tab picked by the text without it; a JSON array of objects is read as records only without it), sheet?: new sheet name, at?: cell, `Sheet!`-qualified or on the active sheet} → imports into a new sheet as a table, or with `at` pastes the columns there (no table), keeping the number formats the reader gives dates, percents and currency", has_doc, from_csv ), diff --git a/crates/engine/src/cmd/extra/data.rs b/crates/engine/src/cmd/extra/data.rs index cc4490e7f..81133256d 100644 --- a/crates/engine/src/cmd/extra/data.rs +++ b/crates/engine/src/cmd/extra/data.rs @@ -1,5 +1,5 @@ use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range}; -use gridcraft_model::Cell; +use gridcraft_model::{Cell, Workbook}; pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result { let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?; @@ -166,79 +166,200 @@ pub(super) fn from_csv(s: &mut Session, p: &Json) -> Result { s.ui_requests.push(crate::UiRequest::Dialog("open".into(), json!({}))); return ok(); }; + let at = paste_target(s, p)?; + let delimiter = delimiter_param(p)?; let text = String::from_utf8_lossy(&bytes); - // JSON array of objects → rows. - let rows: Vec> = - if text.trim_start().starts_with('[') { - let arr: Vec = serde_json::from_str(&text).map_err(|e| bad("data.getData", e.to_string()))?; - let mut keys: Vec = Vec::new(); - let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new(); - for o in &arr { - if let Some(m) = o.as_object() { - for k in m.keys() { - if !seen.contains(k.as_str()) { - // Stop collecting at the column limit. - if keys.len() >= gridcraft_core::MAX_COLS as usize { - return Err(EngineError::Other("The data has more fields than a sheet has columns.".into())); - } - seen.insert(k.as_str()); - keys.push(k.clone()); - } + // A JSON array of objects is read as records, unless a separator says the text is delimited. + // Any other text, such as a copied range whose first field is `[Draft]`, is delimited. + if delimiter.is_none() + && let Some(records) = json_records(&text) + { + let rows = json_rows(&records)?; + return write_json_rows(s, p, at, rows); + } + // With no separator given (0) the reader picks comma, semicolon or tab by the text. Dates are + // read as serials of the workbook they go into. + let opts = gridcraft_xlsx::CsvOptions { + delimiter: delimiter.unwrap_or(0), + date_system: s.doc()?.wb.date_system, + max_used_cells: Some(MAX_IMPORT_CELLS), + ..Default::default() + }; + // The cell limit is enforced while parsing, before an oversized file is stored. + let (wb, report) = gridcraft_xlsx::read_csv_with_report(&bytes, &opts).map_err(|e| match e { + gridcraft_xlsx::IoError::TooLarge(_) => too_many_cells(), + e => EngineError::Other(e.to_string()), + })?; + // Pasted at a cell, the text covers every field it has, blank ones included (all of them, for + // text like `,`), so they clear what is under them; it must not lose records or fields past a + // sheet's last row or column. Imported into a sheet of its own, it is its cells with data. + let src = match (at, wb.sheet(0).and_then(|sh| sh.used_range())) { + (Some(_), _) if report.truncated => return Err(EngineError::Other("The text has more rows or columns than a sheet has.".into())), + (Some(_), _) if report.records > 0 => RangeRef::new(CellRef::new(0, 0), CellRef::new(report.records - 1, report.fields.saturating_sub(1))), + (None, Some(used)) => used, + _ => return Err(EngineError::Other("The file is empty.".into())), + }; + if src.count() > MAX_IMPORT_CELLS { + return Err(too_many_cells()); + } + if let Some((sheet, cell)) = at { + let range = write_parsed(s, sheet, cell, &wb, src)?; + return pasted(s, sheet, range); + } + let name = new_sheet(s, p)?; + let sheet = s.doc()?.wb.active_sheet(); + write_parsed(s, sheet, CellRef::new(0, 0), &wb, src)?; + Ok(as_table(s, name, src.height(), src.width())) +} + +/// The `delimiter` parameter as the byte the CSV reader splits at: one character other than a +/// quote or line break. The reader reads the byte back as a character, so U+0001–U+00FF all work. +/// `None` without one. +fn delimiter_param(p: &Json) -> Result> { + let Some(d) = str_param(p, "delimiter") else { return Ok(None) }; + let mut chars = d.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) if !matches!(c, '\0' | '"' | '\r' | '\n') => match u8::try_from(u32::from(c)) { + Ok(byte) => Ok(Some(byte)), + Err(_) => Err(EngineError::Other(format!("The separator can't be `{c}`: use a character such as , ; or |."))), + }, + _ => Err(EngineError::Other("The separator must be one character, such as , ; or |, and not a quote or line break.".into())), + } +} + +/// Paste Data's `at`: a cell (or a range's top-left cell, as Paste takes a selection) on the sheet +/// it names (`'My Sheet'!C5`), else on the active sheet. +fn paste_target(s: &Session, p: &Json) -> Result> { + let t = match p.get("at") { + None | Some(Json::Null) => return Ok(None), + Some(Json::String(t)) => t, + Some(v) => return Err(bad("at", format!("invalid cell reference `{v}`"))), + }; + let wb = &s.doc()?.wb; + let (name, body) = crate::cmd::split_sheet(t); + let sheet = match name { + Some(n) => wb.sheet_index(&n).ok_or_else(|| bad("at", format!("no sheet named `{n}`")))?, + None => wb.active_sheet(), + }; + let cell = + CellRef::parse(body).or_else(|| RangeRef::parse(body).map(|r| r.start)).ok_or_else(|| bad("at", format!("invalid cell reference `{t}`")))?; + Ok(Some((sheet, cell))) +} + +fn doesnt_fit() -> EngineError { + EngineError::Other("The data doesn't fit on the sheet from that cell.".into()) +} + +/// The records of text that is a JSON array of objects (`[]` included); `None` for any other +/// text, which is read as delimited text. +fn json_records(text: &str) -> Option> { + if !text.trim_start().starts_with('[') { + return None; + } + serde_json::from_str::>(text).ok().filter(|arr| arr.iter().all(Json::is_object)) +} + +/// JSON records as rows: a header row of every key, then one row per object. +fn json_rows(arr: &[Json]) -> Result>> { + let mut keys: Vec = Vec::new(); + let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new(); + for o in arr { + if let Some(m) = o.as_object() { + for k in m.keys() { + if !seen.contains(k.as_str()) { + // Stop collecting at the column limit. + if keys.len() >= gridcraft_core::MAX_COLS as usize { + return Err(EngineError::Other("The data has more fields than a sheet has columns.".into())); } + seen.insert(k.as_str()); + keys.push(k.clone()); } } - if arr.len() as u64 + 1 > u64::from(gridcraft_core::MAX_ROWS) { - return Err(EngineError::Other("The data has more rows than a sheet has.".into())); - } - if (arr.len() as u64 + 1).saturating_mul(keys.len().max(1) as u64) > MAX_IMPORT_CELLS { - return Err(too_many_cells()); - } - let mut out = vec![keys.iter().map(|k| json!(k)).collect::>()]; - for o in &arr { - out.push(keys.iter().map(|k| o.get(k).cloned().unwrap_or(Json::Null)).collect()); - } - out - } else { - let delim = str_param(p, "delimiter") - .and_then(|d| d.chars().next()) - .unwrap_or(if text.lines().next().is_some_and(|l| l.contains('\t')) { '\t' } else { ',' }); - let opts = gridcraft_xlsx::CsvOptions { delimiter: delim as u8, max_used_cells: Some(MAX_IMPORT_CELLS), ..Default::default() }; - // The cell limit is enforced while parsing, before an oversized file is stored. - let wb = gridcraft_xlsx::read_csv(&bytes, &opts).map_err(|e| match e { - gridcraft_xlsx::IoError::TooLarge(_) => too_many_cells(), - e => EngineError::Other(e.to_string()), - })?; - let sh = wb.sheet(0).ok_or(EngineError::NoDocument)?; - let Some(u) = sh.used_range() else { return Err(EngineError::Other("The file is empty.".into())) }; - if u.count() > MAX_IMPORT_CELLS { - return Err(too_many_cells()); - } - (u.start.row..=u.end.row) - .map(|r| { - (u.start.col..=u.end.col) - .map(|c| match sh.value(CellRef::new(r, c)) { - Value::Number(n) => json!(n), - Value::Bool(b) => json!(b), - Value::Empty => Json::Null, - v => json!(v.display()), - }) - .collect() - }) - .collect() - }; - if rows.is_empty() || rows.len() > 1_048_576 { + } + } + if arr.is_empty() { return Err(EngineError::Other("Nothing to import.".into())); } + if arr.len() as u64 + 1 > u64::from(gridcraft_core::MAX_ROWS) { + return Err(EngineError::Other("The data has more rows than a sheet has.".into())); + } + if (arr.len() as u64 + 1).saturating_mul(keys.len().max(1) as u64) > MAX_IMPORT_CELLS { + return Err(too_many_cells()); + } + let mut out = vec![keys.iter().map(|k| json!(k)).collect::>()]; + for o in arr { + out.push(keys.iter().map(|k| o.get(k).cloned().unwrap_or(Json::Null)).collect()); + } + Ok(out) +} + +fn write_json_rows(s: &mut Session, p: &Json, at: Option<(usize, CellRef)>, rows: Vec>) -> Result { + let h = u32::try_from(rows.len()).map_err(|_| too_many_cells())?; + let w = u32::try_from(rows.iter().map(Vec::len).max().unwrap_or(1).max(1)).map_err(|_| too_many_cells())?; + if let Some((sheet, cell)) = at { + let end = cell.offset(i64::from(h) - 1, i64::from(w) - 1).ok_or_else(doesnt_fit)?; + s.execute("range.setValues", json!({"range": cell.a1(), "sheet": sheet, "values": rows}))?; + return pasted(s, sheet, RangeRef::new(cell, end)); + } + let name = new_sheet(s, p)?; + s.execute("range.setValues", json!({"range": "A1", "values": rows}))?; + Ok(as_table(s, name, h, w)) +} + +/// Writes the CSV reader's cells in `src` to `sheet` from `at`, as a paste replaces cells: each +/// value as the reader typed it, with the number format it gave (a date stays a date, text it +/// kept as text stays text), and a blank field clearing its cell. Returns the range written. +fn write_parsed(s: &mut Session, sheet: usize, at: CellRef, read: &Workbook, src: RangeRef) -> Result { + let end = at.offset(i64::from(src.height()) - 1, i64::from(src.width()) - 1).ok_or_else(doesnt_fit)?; + let from = read.sheet(0).ok_or(EngineError::NoDocument)?; + edit(s, |cx| { + for c in src.iter() { + let dest = CellRef::new(at.row + (c.row - src.start.row), at.col + (c.col - src.start.col)); + match from.cell(c).filter(|cell| cell.value != Value::Empty) { + Some(cell) => { + let format = &read.styles.get(cell.style).num_fmt; + let mut style = cx.wb.sheet(sheet).map(|sh| sh.style_id(dest)).unwrap_or_default(); + if format.as_str() != "General" { + style = cx.wb.styles.derive(style, |st| st.num_fmt = format.clone()); + } + cx.sheet_mut(sheet)?.set_cell(dest, Cell { value: cell.value.clone(), formula: None, style, py: None }); + } + None => { + cx.sheet_mut(sheet)?.remove_cell(dest); + } + } + cx.changed.push((sheet, dest)); + } + Ok(()) + })?; + Ok(RangeRef::new(at, end)) +} + +/// After a paste at a cell: its sheet active and the pasted range selected, as Paste leaves them. +fn pasted(s: &mut Session, sheet: usize, range: RangeRef) -> Result { + if s.doc()?.wb.active_sheet() != sheet { + s.execute("sheet.activate", json!({"sheet": sheet}))?; + } + s.execute("selection.set", json!({"range": range.a1()}))?; + let name = s.doc()?.wb.sheet(sheet).map(|sh| sh.name.clone()); + Ok(json!({"sheet": name, "range": range.a1(), "rows": range.height(), "cols": range.width()})) +} + +/// A new sheet for an import, named by `sheet` or the file's name when that name is free. +fn new_sheet(s: &mut Session, p: &Json) -> Result { let name = str_param(p, "sheet").map(str::to_string).or_else(|| { str_param(p, "path").and_then(|x| std::path::Path::new(x).file_stem().and_then(std::ffi::OsStr::to_str).map(|f| f.chars().take(31).collect())) }); let r = s.execute("home.insertSheet", json!({"name": name})).or_else(|_| s.execute("home.insertSheet", json!({})))?; - let w = rows.iter().map(Vec::len).max().unwrap_or(1).max(1); - s.execute("range.setValues", json!({"range": "A1", "values": rows}))?; - let range = RangeRef::new(CellRef::new(0, 0), CellRef::new(rows.len() as u32 - 1, w as u32 - 1)); + Ok(r["name"].clone()) +} + +/// The imported block at A1 of the new sheet as a table with a header row, its columns fitted. +fn as_table(s: &mut Session, name: Json, rows: u32, cols: u32) -> Json { + let range = RangeRef::new(CellRef::new(0, 0), CellRef::new(rows.saturating_sub(1), cols.saturating_sub(1))); let _ = s.execute("insert.table", json!({"range": range.a1(), "header": true})); - let _ = s.execute("home.autofitColumnWidth", json!({"cols": RangeRef::cols(0, w as u32 - 1).a1()})); - Ok(json!({"sheet": r["name"], "rows": rows.len(), "cols": w})) + let _ = s.execute("home.autofitColumnWidth", json!({"cols": RangeRef::cols(0, cols.saturating_sub(1)).a1()})); + json!({"sheet": name, "rows": rows, "cols": cols}) } pub(super) fn from_table_range(s: &mut Session, p: &Json) -> Result { @@ -276,6 +397,94 @@ mod tests { s } + #[test] + fn pasted_text_keeps_its_place_formats_and_sheet() { + use gridcraft_core::{CellRef, Value}; + let mut s = s(); + s.execute("cell.set", json!({"cell": "B2", "input": "old"})).unwrap(); + // Another sheet is active when the paste aimed at Sheet1 runs. + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + // A separator rules out JSON (`[Draft]` is a field), and the blank first field keeps the + // rest one column right of `at`. + let text = "\t[Draft]\t2026-01-15\n\t\t15%"; + s.execute("data.fromTextCsv", json!({"text": text, "delimiter": "\t", "at": "Sheet1!B2"})).unwrap(); + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + assert_eq!(sh.name, "Sheet1", "the paste shows its sheet"); + let at = |a1: &str| CellRef::parse(a1).unwrap(); + assert_eq!(sh.value(at("B2")), Value::Empty, "a blank field clears what was there"); + assert_eq!(sh.value(at("C2")), Value::text("[Draft]")); + for a1 in ["D2", "D3"] { + assert!(matches!(sh.value(at(a1)), Value::Number(_)), "{a1}"); + assert_ne!(d.wb.styles.get(sh.style_id(at(a1))).num_fmt.as_str(), "General", "{a1} keeps the format the reader gave it"); + } + let other = d.wb.sheet(d.wb.sheet_index("Other").unwrap()).unwrap(); + assert!(other.used_range().is_none(), "the active sheet at OK is left alone"); + } + + #[test] + fn a_paste_clears_under_trailing_blanks_and_dates_follow_the_workbooks_date_system() { + use gridcraft_core::{CellRef, DateSystem, Value}; + let at = |a1: &str| CellRef::parse(a1).unwrap(); + let pasted = |system: DateSystem| { + let mut s = s(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).date_system = system; + s.execute("range.setValues", json!({"range": "B1", "values": [["x", "y"], ["z", "w"]]})).unwrap(); + // The second field and the second record are blank: they clear C1 and B2:C2. + s.execute("data.fromTextCsv", json!({"text": "2026-01-15,\n,\n", "delimiter": ",", "at": "B1"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap().clone(); + for a1 in ["C1", "B2", "C2"] { + assert_eq!(sh.value(at(a1)), Value::Empty, "{a1}"); + } + match sh.value(at("B1")) { + Value::Number(n) => n, + v => panic!("{v:?}"), + } + }; + // The same day is 1,462 serials lower in the 1904 date system. + assert_eq!(pasted(DateSystem::D1900) - pasted(DateSystem::D1904), 1462.0); + + // Text of blank fields only clears the cells it covers. + let mut s = s(); + s.execute("range.setValues", json!({"range": "B1", "values": [["x", "y", "z"]]})).unwrap(); + s.execute("data.fromTextCsv", json!({"text": ",", "delimiter": ",", "at": "B1"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!((sh.value(at("B1")), sh.value(at("C1"))), (Value::Empty, Value::Empty)); + assert_eq!(sh.value(at("D1")), Value::text("z"), "past the text's two fields"); + } + + #[test] + fn a_paste_with_more_records_or_fields_than_a_sheet_has_is_refused() { + use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, Value}; + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "old"})).unwrap(); + // One record per line break, so a record past the last row; then a field past the last column. + let long = format!("new{}", "\n".repeat(MAX_ROWS as usize + 1)); + let wide = format!("new{}", ",".repeat(MAX_COLS as usize)); + for text in [long, wide] { + let err = s.execute("data.fromTextCsv", json!({"text": text, "delimiter": ",", "at": "A1"})).expect_err("too large"); + assert!(err.to_string().contains("more rows or columns"), "{err}"); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.value(CellRef::parse("A1").unwrap()), Value::text("old"), "nothing is written"); + } + // A record exactly as wide as the sheet fits. + let fits = format!("new{}x", ",".repeat(MAX_COLS as usize - 1)); + s.execute("data.fromTextCsv", json!({"text": fits, "delimiter": ",", "at": "A1"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.value(CellRef::new(0, MAX_COLS - 1)), Value::text("x")); + } + + #[test] + fn a_separator_is_one_character_the_reader_can_split_at() { + let mut s = s(); + for bad in ["||", "", "\"", "€"] { + assert!(s.execute("data.fromTextCsv", json!({"text": "a||b", "delimiter": bad})).is_err(), "{bad:?}"); + } + // Up to U+00FF the reader splits at the character itself. + let out = s.execute("data.fromTextCsv", json!({"text": "a§b\n1§2", "delimiter": "§"})).unwrap(); + assert_eq!(out["cols"].as_u64(), Some(2), "{out}"); + } + #[test] fn sparse_imports_are_refused_before_their_rows_are_built() { let mut s = s(); diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 63415fd87..3c19ddd2d 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -1196,3 +1196,9 @@ pub fn image_size(data: &[u8]) -> Option<(u32, u32)> { #[cfg(test)] mod tests; + +/// The separator delimited text uses: comma, semicolon or tab, picked as the CSV reader picks it +/// when none is given (consistent field counts over its first records; comma when none fits). +pub fn guess_separator(text: &str) -> char { + char::from(craft_csv::sniff_delimiter(text, '"')) +} diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 4b7cc74d9..c6388ac0e 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -62,6 +62,22 @@ impl SheetApp { } } + /// `data.fromClipboard {delimiter?, at?}`: the text on the system clipboard, imported as + /// `data.fromTextCsv` imports text: into a new sheet as a table, or at the cell `at`. Without + /// a `delimiter` the engine picks comma, semicolon or tab by the text. + pub(super) fn import_clipboard_text(&mut self, p: &Json) -> Result { + let text = self.clipboard_text_to_import()?; + self.run_command("data.fromTextCsv", json!({"text": text, "delimiter": p.get("delimiter"), "at": p.get("at")})) + } + + /// The text From Clipboard imports, or why there is none. + pub(crate) fn clipboard_text_to_import(&mut self) -> Result { + if self.services.paste_text.is_none() { + return Err("GridCraft can't read the clipboard here. Paste the text into a cell, then use Text to Columns.".into()); + } + self.system_clipboard_text().filter(|t| !t.trim().is_empty()).ok_or_else(|| "There's no text on the clipboard to import.".into()) + } + /// Paste a picture from the system clipboard (a screenshot, an image copied in a browser) as /// a floating picture whose top-left corner is the active cell, as Excel does. pub fn paste_picture(&mut self, image: image::RgbaImage) { diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 68694b002..51eebb781 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -217,6 +217,7 @@ impl SheetApp { self.check_for_updates(); Ok(Json::Null) } + "data.fromClipboard" => self.import_clipboard_text(p), "ui.printSettings" => printing::settings(&mut self.printing, p, self.services.printers.as_ref()), "ui.printSubmit" => self.submit_print(p.clone()), "ui.ribbonTab" => { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index e882a98d9..c9b8c6b61 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -262,6 +262,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) - for (id, label, params) in [ ("ui.ribbonTab", "Ribbon Tab", ""), ("app.checkForUpdates", "Check for Updates…", ""), + ( + "data.fromClipboard", + "From Clipboard", + "{delimiter?, at?} → as data.fromTextCsv {text, delimiter?, at?} with the text on the system clipboard: into a new sheet, or at the cell `at`", + ), ("view.collapseRibbon", "Collapse Ribbon", ""), ( "view.expandFormulaBar", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f52686101..54d1c7b27 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -32,7 +32,7 @@ mod zoom; use analysis::toolpak_defaults; use charts::select_chart; -use data::{abs, data_validation_fields, remove_duplicates_range, validation_defaults}; +use data::{abs, data_validation_fields, from_clipboard_form, remove_duplicates_range, validation_defaults}; use find::go_to_entries; pub(crate) use names::insert_name; use names::pasteable_names; @@ -138,6 +138,10 @@ impl Dialog { _ => {} } } + // Typing a separator in From Clipboard's Other box chooses Other. + if self.name == "fromClipboard" && key == "other" && value.as_str().is_some_and(|s| !s.is_empty()) { + self.values.insert("separator".into(), json!("other")); + } self.values.insert(key.into(), value); } @@ -687,6 +691,7 @@ impl Dialog { ], json!({"tab": true, "comma": true, "destination": active}), ), + "fromClipboard" => from_clipboard_form(app, p("at").as_str())?, "removeDuplicates" => Dialog::form( "removeDuplicates", "Remove Duplicates", diff --git a/crates/ui-egui/src/dialogs/data.rs b/crates/ui-egui/src/dialogs/data.rs index 103160fe4..98cf3bd55 100644 --- a/crates/ui-egui/src/dialogs/data.rs +++ b/crates/ui-egui/src/dialogs/data.rs @@ -3,6 +3,44 @@ use super::show::build_params; use super::show::{form_fields, ok_cancel}; use super::{Dialog, Field, Json, SheetApp, json, vec2}; +/// Data › Get Data › From Clipboard…, and the cell menu's Paste Data… with the cell `at`: the +/// separator to split the clipboard text at, starting on the one the text seems to use. The text +/// read now is the text OK imports, whatever the clipboard holds by then. With no text to import +/// that is said now, not after OK. +pub(super) fn from_clipboard_form(app: &mut SheetApp, at: Option<&str>) -> Option { + use Field::{Choice, Note, Ref, Text}; + let text = match app.clipboard_text_to_import() { + Ok(text) => text, + Err(e) => { + app.alert(e); + return None; + } + }; + let separator = match gridcraft_engine::io::guess_separator(&text) { + '\t' => "tab", + ';' => "semicolon", + _ => "comma", + }; + // From Paste Data… the columns go in at the cell; from Get Data, into a new sheet. As a + // reference box the cell means the sheet the dialog opened on, whichever is shown by OK. + let mut fields = Vec::new(); + if at.is_some() { + fields.push(Note("The columns replace what is there.".into())); + fields.push(Ref { key: "at", label: "Paste at:" }); + } + fields.extend([ + Choice { + key: "separator", + label: "Separator", + // Keyed as Text to Columns keys it: the separator, not the Comma cell style. + options: vec![("comma", "Text to Columns|Comma"), ("semicolon", "Semicolon"), ("tab", "Tab"), ("space", "Space"), ("other", "Other")], + }, + Text { key: "other", label: "Other separator:" }, + ]); + let title = if at.is_some() { "Paste Data" } else { "Import from Clipboard" }; + Some(Dialog::form("fromClipboard", title, "data.fromTextCsv", fields, json!({"separator": separator, "other": "", "at": at, "text": text}))) +} + /// Initial values of the Data Validation form: the rule stored on the active cell, so OK without /// edits keeps it; a plain list rule when the cell has none. pub(super) fn validation_defaults(app: &SheetApp) -> Json { diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index d2f1f0bfe..0f2c23dc2 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -57,6 +57,16 @@ pub(crate) fn build_params(d: &Dialog) -> Json { } } } + "fromClipboard" => { + let delimiter = match d.values.get("separator").and_then(Json::as_str) { + Some("semicolon") => ";", + Some("tab") => "\t", + Some("space") => " ", + Some("other") => d.values.get("other").and_then(Json::as_str).unwrap_or_default(), + _ => ",", + }; + v = json!({ "text": d.values.get("text"), "delimiter": delimiter, "at": d.values.get("at") }); + } "textToColumns" => { let mut delims = Vec::new(); for (k, c) in [("tab", "\t"), ("semicolon", ";"), ("comma", ","), ("space", " ")] { @@ -634,7 +644,7 @@ pub(super) fn form_fields(app: &SheetApp, ui: &mut egui::Ui, d: &mut Dialog) { }; take_first_focus(d, &r); if r.changed() { - d.values.insert(key.into(), json!(s)); + d.set_value(key, json!(s)); } if let Some(pick) = d.pick.as_mut().filter(|pick| pick.key == key) { track_pick(pick, &r, r.changed()); diff --git a/crates/ui-egui/src/grid/menus.rs b/crates/ui-egui/src/grid/menus.rs index d832c2df9..c10bb1c18 100644 --- a/crates/ui-egui/src/grid/menus.rs +++ b/crates/ui-egui/src/grid/menus.rs @@ -134,6 +134,7 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) { ("Copy", "edit.copy"), ("Paste", "edit.paste"), ("Paste Special…", "ui:pasteSpecial"), + ("Paste Data…", "ui:pasteData"), ("-", ""), ("Insert…", "ui:insertCells"), ("Delete…", "ui:deleteCells"), @@ -151,8 +152,10 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) { ("Define Name…", "ui:defineName"), ("Link…", "ui:insertLink"), ]; - if let Some(item) = insert_copied { - items.insert(6, item); + if let Some(item) = insert_copied + && let Some(i) = items.iter().position(|(_, id)| *id == "ui:insertCells") + { + items.insert(i + 1, item); } if link.is_some() && let Some(i) = items.iter().position(|(_, id)| *id == "ui:insertLink") @@ -178,6 +181,11 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) { close = true; match id { "ui:pasteSpecial" => app.open_dialog("pasteSpecial", json!({})), + "ui:pasteData" => { + // Where Paste pastes: the selection's top-left cell. + let at = app.session.active().map(|d| d.selection.current().start.a1()); + app.open_dialog("fromClipboard", json!({"at": at})); + } "ui:insertPaste" => app.open_dialog("insertPaste", json!({})), "ui:insertCells" => app.open_dialog("insertCells", json!({})), "ui:deleteCells" => app.open_dialog("deleteCells", json!({})), diff --git a/crates/ui-egui/src/keytips.rs b/crates/ui-egui/src/keytips.rs index f2e3d9bf3..42d9e2b8c 100644 --- a/crates/ui-egui/src/keytips.rs +++ b/crates/ui-egui/src/keytips.rs @@ -33,6 +33,9 @@ pub struct KeyTips { alt_held: bool, // Keep consuming a held mnemonic after its action closes keytips. held: Vec, + // Up or Down pressed this frame while a sequence was under way, for a menu that key tips + // opened to take (`take_menu_arrow`). + menu_arrow: Option, } impl KeyTips { @@ -45,6 +48,13 @@ impl KeyTips { self.alt_armed = false; self.alt_held = false; self.held.clear(); + self.menu_arrow = None; + } + + /// Up or Down pressed this frame during a sequence: a menu that key tips opened (Alt, H, V) + /// takes it to move keyboard focus onto its items. Unclaimed, it is dropped next frame. + pub fn take_menu_arrow(&mut self) -> Option { + self.menu_arrow.take() } fn toggle(&mut self) { @@ -54,6 +64,7 @@ impl KeyTips { /// Remove only handled events before any text editors or the grid see them. pub fn process(&mut self, ctx: &Context, enabled: bool) -> Vec { + self.menu_arrow = None; if !enabled || !ctx.input(|i| i.focused) { self.clear(); return Vec::new(); @@ -121,6 +132,8 @@ impl KeyTips { handled = true; if *key == Key::Escape { self.back(); + } else if matches!(key, Key::ArrowDown | Key::ArrowUp) { + self.menu_arrow = Some(*key); } else if key.name().len() == 1 { let next = format!("{}{key_name}", self.prefix.as_deref().unwrap_or_default(), key_name = key.name()); match keytip_table::lookup(&next) { diff --git a/crates/ui-egui/src/keytips/keytip_table/generated.rs b/crates/ui-egui/src/keytips/keytip_table/generated.rs index 7651bf344..d79e23b42 100644 --- a/crates/ui-egui/src/keytips/keytip_table/generated.rs +++ b/crates/ui-egui/src/keytips/keytip_table/generated.rs @@ -287,6 +287,7 @@ pub const SEQUENCES: &[(&str, Entry)] = &[ ("AO", Entry::Finish(Action::Command("data.queriesConnections"))), // Excel: Queries & Connections ("AP1", Entry::Finish(Action::Command("file.properties"))), // Excel: Properties ("APN", Entry::Continue), // Excel: Get Data (Power Query) Menu; group level: Power Query variants = GAP + ("APNC", Entry::Finish(Action::Dialog("fromClipboard"))), // Excel: (none); From Clipboard… item GridCraft adds to the Get Data menu (Excel's has none); C is free under APN ("APND", Entry::Finish(Action::Pending("data.fromDatabase"))), // pending; Excel: From Database (Microsoft Query); gap #12; reserved until the command lands ("APNE", Entry::Finish(Action::Pending("data.powerQueryEditor"))), // pending; Excel: Launch Power Query Editor; gap #12; reserved until the command lands ("APNG", Entry::Finish(Action::Command("data.getData"))), // Excel: Get Data (Power Query); containment(Get Data) diff --git a/crates/ui-egui/src/keytips/keytips.json b/crates/ui-egui/src/keytips/keytips.json index daaa416f9..5ecbf8d07 100644 --- a/crates/ui-egui/src/keytips/keytips.json +++ b/crates/ui-egui/src/keytips/keytips.json @@ -1972,6 +1972,13 @@ "excel": "Get Data (Power Query) Menu", "note": "group level: Power Query variants = GAP" }, + { + "seq": "APNC", + "kind": "dialog", + "target": "fromClipboard", + "excel": "(none)", + "note": "From Clipboard… item GridCraft adds to the Get Data menu (Excel's has none); C is free under APN" + }, { "seq": "APND", "kind": "command", diff --git a/crates/ui-egui/src/ribbon/controls.rs b/crates/ui-egui/src/ribbon/controls.rs index 3b8e252f4..848d286e5 100644 --- a/crates/ui-egui/src/ribbon/controls.rs +++ b/crates/ui-egui/src/ribbon/controls.rs @@ -274,6 +274,7 @@ fn combo_popup( } pub(super) fn menu_items(app: &mut SheetApp, ui: &mut Ui, items: &[(&str, &str, serde_json::Value)]) { + let mut buttons = Vec::new(); for (label, id, p) in items { if *label == "-" { ui.separator(); @@ -285,6 +286,13 @@ pub(super) fn menu_items(app: &mut SheetApp, ui: &mut Ui, items: &[(&str, &str, keytip(app, ui, sequence, pos2(response.rect.right() - 10.0, response.rect.center().y)); } if response.clicked() { + // Enter on a focused item clicks it without a pointer click to close the menu, and the + // same press must not also confirm the dialog or message the item opens. + ui.close(); + ui.input_mut(|i| { + i.consume_key(egui::Modifiers::NONE, egui::Key::Enter); + i.consume_key(egui::Modifiers::NONE, egui::Key::Space); + }); if let Some(d) = id.strip_prefix("dialog:") { app.open_dialog(d, p.clone()); } else if *id == "edit.paste" { @@ -293,6 +301,36 @@ pub(super) fn menu_items(app: &mut SheetApp, ui: &mut Ui, items: &[(&str, &str, act(app, id, p.clone()); } } + buttons.push(response); + } + menu_focus(app, ui, &buttons); +} + +/// Up and Down in a menu, as in Excel's: in one that key tips opened (Alt, H, V), the first press +/// ends key tips and moves keyboard focus onto the first or last item; egui then moves it between +/// items, Enter runs the focused one and Esc closes the menu. Focus wraps at the ends rather than +/// leaving the open menu. +fn menu_focus(app: &mut SheetApp, ui: &Ui, buttons: &[egui::Response]) { + let (Some(first), Some(last)) = (buttons.first(), buttons.last()) else { return }; + if let Some(key) = app.keytips.take_menu_arrow() { + app.keytips.clear(); + let target = if key == egui::Key::ArrowUp { last } else { first }; + target.request_focus(); + // egui read the arrow before key tips took it: with a widget focused, it would move on + // from the item just focused. + ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); + return; + } + let focused = buttons.iter().position(egui::Response::has_focus); + let wrap = ui.input(|i| match focused { + Some(0) if i.key_pressed(egui::Key::ArrowUp) => Some(last), + Some(n) if n + 1 == buttons.len() && i.key_pressed(egui::Key::ArrowDown) => Some(first), + _ => None, + }); + if let Some(target) = wrap { + target.request_focus(); + // Instead of the move egui would make, out of the menu. + ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); } } diff --git a/crates/ui-egui/src/ribbon/data.rs b/crates/ui-egui/src/ribbon/data.rs index 1cecdb2db..e44003f77 100644 --- a/crates/ui-egui/src/ribbon/data.rs +++ b/crates/ui-egui/src/ribbon/data.rs @@ -1,12 +1,21 @@ -use super::controls::{act, control_keytip, keytip, menu_items, sep}; -use super::{Icon, SheetApp, Ui, big_button, json, keytip_table, small_button}; +use super::controls::{act, control_keytip, keytip, menu_items, popup_command, sep}; +use super::{Icon, SheetApp, Ui, big_button, big_split_button, json, keytip_table, small_button}; pub(super) fn data(app: &mut SheetApp, ui: &mut Ui) { - let gd = big_button(ui, Icon::Folder, "Get Data\n(Text/CSV)", "Import a text or CSV file", false); - control_keytip(app, ui, &gd, "data.getData"); + // The button opens a text or CSV file; its menu can also import the text on the clipboard. + let (gd, gd_menu) = big_split_button(ui, Icon::Folder, "Get Data\n(Text/CSV)", "Import a text or CSV file"); + // Alt, A, P, N opens the menu with its item letters, G for a file and C for the clipboard, + // which the button's own badge would repeat. + let keyed = keytip_table::opens_menu(app.keytips.prefix().unwrap_or_default(), "data.getData"); + if !keyed { + control_keytip(app, ui, &gd_menu, "data.getData"); + } if gd.clicked() { app.open_dialog("open", json!({})); } + egui::Popup::menu(&gd_menu).open_memory(popup_command(keyed, gd_menu.clicked())).show(|ui| { + menu_items(app, ui, &[("From Text/CSV…", "data.getData", json!({})), ("From Clipboard…", "dialog:fromClipboard", json!({}))]); + }); sep(ui); ui.vertical(|ui| { let __k = small_button(ui, Icon::SortAsc, "", "Sort A to Z", false); diff --git a/crates/ui-egui/tests/it/clipboard.rs b/crates/ui-egui/tests/it/clipboard.rs index 38c6ea259..3fdf9892a 100644 --- a/crates/ui-egui/tests/it/clipboard.rs +++ b/crates/ui-egui/tests/it/clipboard.rs @@ -559,3 +559,119 @@ fn ribbon_paste_prefers_clipboard_text_over_a_picture() { assert_eq!(value_at(&h, "D2"), Some(Value::from("words"))); assert!(pictures(&h).is_empty()); } + +#[test] +fn get_data_from_clipboard_splits_the_clipboard_text_at_the_chosen_separator() { + // Semicolon-separated, as Excel writes CSV where a comma is the decimal separator. + let (clipboard, services) = system_clipboard("Name;City\r\n\"Smith; John\";Oslo\r\nAda;42\r\n"); + let mut h = harness(services); + let sheets = |h: &Harness| h.state().session.active().unwrap().wb.sheets.len(); + let separator = |h: &Harness| h.state().dialog.as_ref().and_then(|d| d.values.get("separator")?.as_str().map(str::to_string)); + let before = sheets(&h); + h.state_mut().ui.ribbon_tab = "Data".into(); + h.run_steps(2); + let open_from_clipboard = |h: &mut Harness| { + h.get_by_role_and_label(Role::Button, "Get Data (Text/CSV) options").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "From Clipboard…").click(); + h.run_steps(3); + }; + + // The dialog starts on the separator the text uses, and OK imports that text into a new + // sheet, even when the clipboard has moved on. + open_from_clipboard(&mut h); + assert_eq!(separator(&h).as_deref(), Some("semicolon")); + clipboard.borrow_mut().0 = "copied later".into(); + h.get_by_label_contains("OK").click(); + h.run_steps(3); + assert!(h.state().message.is_none(), "{:?}", h.state().message); + assert!(h.state().dialog.is_none()); + assert_eq!(sheets(&h), before + 1, "the text goes into a new sheet"); + assert_eq!(value_at(&h, "A2"), Some(Value::from("Smith; John")), "a quoted separator stays in its field"); + assert_eq!(value_at(&h, "B2"), Some(Value::from("Oslo"))); + assert_eq!(value_at(&h, "B3"), Some(Value::number(42.0))); + + // Typing a separator in Other chooses it. + clipboard.borrow_mut().0 = "a|b,c\n".into(); + open_from_clipboard(&mut h); + assert_eq!(separator(&h).as_deref(), Some("comma")); + h.get_by_role_and_label(Role::TextInput, "Other separator:").click(); + h.run_steps(2); + h.input_mut().events.push(Event::Text("|".into())); + h.run_steps(2); + assert_eq!(separator(&h).as_deref(), Some("other")); + h.get_by_label_contains("OK").click(); + h.run_steps(3); + assert_eq!(sheets(&h), before + 2); + assert_eq!(value_at(&h, "A1"), Some(Value::from("a"))); + assert_eq!(value_at(&h, "B1"), Some(Value::from("b,c"))); + + // With no text on the clipboard it says so and opens no dialog. + clipboard.borrow_mut().0 = " \n".into(); + open_from_clipboard(&mut h); + let message = format!("{:?}", h.state().message); + assert!(message.contains("no text on the clipboard"), "{message}"); + assert!(h.state().dialog.is_none()); + assert_eq!(sheets(&h), before + 2); +} + +#[test] +fn from_clipboard_without_a_separator_reads_text_starting_with_a_bracket_as_columns() { + // Delimited text whose first field is in brackets is not JSON, and the separator is picked + // by the text; a JSON array of objects is still read as records. + let (clipboard, services) = system_clipboard("[Draft];Oslo\nDone;Bergen\n"); + let mut h = harness(services); + let sheets = |h: &Harness| h.state().session.active().unwrap().wb.sheets.len(); + let before = sheets(&h); + h.state_mut().run("data.fromClipboard", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(sheets(&h), before + 1); + assert_eq!(value_at(&h, "A1"), Some(Value::from("[Draft]"))); + assert_eq!(value_at(&h, "B1"), Some(Value::from("Oslo")), "the next field is the next column"); + assert_eq!(value_at(&h, "B2"), Some(Value::from("Bergen"))); + + clipboard.borrow_mut().0 = r#"[{"city": "Oslo"}]"#.into(); + h.state_mut().run("data.fromClipboard", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(sheets(&h), before + 2); + assert_eq!(value_at(&h, "A1"), Some(Value::from("city")), "the key is the header"); + assert_eq!(value_at(&h, "A2"), Some(Value::from("Oslo"))); +} + +#[test] +fn paste_data_in_the_cell_menu_splits_the_clipboard_text_into_columns_at_the_cell() { + let (_, services) = system_clipboard("x;y\r\n1;\"a; b\"\r\n"); + let mut h = harness(services); + let sheets = h.state().session.active().unwrap().wb.sheets.len(); + h.state_mut().run("selection.set", json!({"cell": "C3"})).unwrap(); + h.run_steps(2); + let app = h.state(); + let sh = app.session.active().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let pos = geo.cell_rect(sh, CellRef::parse("C3").unwrap()).center(); + h.input_mut().events.push(Event::PointerMoved(pos)); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + assert!(h.state().grid.context_menu.is_some()); + h.get_by_role_and_label(Role::Button, "Paste Data…").click(); + h.run_steps(3); + assert_eq!(h.state().dialog.as_ref().map(|d| d.title.as_str()), Some("Paste Data")); + // By OK its sheet is renamed and another sheet, now active, has its old name (the sheet tabs + // and the control channel work while the dialog is open). + h.state_mut().session.execute("sheet.rename", json!({"sheet": 0, "name": "Renamed"})).unwrap(); + h.state_mut().session.execute("home.insertSheet", json!({"name": "Sheet1"})).unwrap(); + h.run_steps(2); + h.get_by_label_contains("OK").click(); + h.run_steps(3); + assert!(h.state().message.is_none(), "{:?}", h.state().message); + let wb = &h.state().session.active().unwrap().wb; + assert_eq!(wb.sheets.len(), sheets + 1, "no sheet of its own"); + assert_eq!(wb.active().unwrap().name, "Renamed", "the paste goes to the sheet it was asked on"); + assert!(wb.active().unwrap().tables.is_empty(), "no table either"); + assert_eq!(value_at(&h, "C3"), Some(Value::from("x"))); + assert_eq!(value_at(&h, "D3"), Some(Value::from("y"))); + assert_eq!(value_at(&h, "C4"), Some(Value::number(1.0))); + assert_eq!(value_at(&h, "D4"), Some(Value::from("a; b"))); +} diff --git a/crates/ui-egui/tests/it/keytips_generated.rs b/crates/ui-egui/tests/it/keytips_generated.rs index 86001238f..d63c77a0d 100644 --- a/crates/ui-egui/tests/it/keytips_generated.rs +++ b/crates/ui-egui/tests/it/keytips_generated.rs @@ -2093,6 +2093,16 @@ fn keytip_apn_() { assert_eq!(h.state().keytips.prefix(), Some("APN"), "APN must stay armed waiting for more input"); } +#[test] +fn keytip_apnc_() { + let mut h = harness(blank()); + sequence(&mut h, "APNC", false); + assert!( + h.state().message.as_ref().is_some_and(|(_, m)| m.contains("clipboard")), + "APNC must open From Clipboard, which says there is no clipboard here" + ); +} + #[test] fn keytip_apnd_() { let mut h = harness(blank()); @@ -3086,7 +3096,7 @@ fn keytip_q_() { #[test] fn generated_test_count_matches_the_table() { - const EXPECTED: usize = 413; + const EXPECTED: usize = 414; assert_eq!(gridcraft_ui_egui::keytips::keytip_table::SEQUENCES.len(), EXPECTED); } diff --git a/crates/ui-egui/tests/keytips.rs b/crates/ui-egui/tests/keytips.rs index 6835c0d8d..021e477c8 100644 --- a/crates/ui-egui/tests/keytips.rs +++ b/crates/ui-egui/tests/keytips.rs @@ -827,3 +827,39 @@ fn borders_keytip_opens_the_borders_menu() { assert_eq!(h.state().keytips.prefix(), Some("H"), "Esc backs out to the Home letters"); assert!(!egui::Popup::is_any_open(&h.ctx), "and closes the menu"); } + +#[test] +fn get_data_key_tips_open_its_menu_and_arrows_move_through_it() { + let mut h = harness(blank()); + let focused = |h: &Harness, label: &str| h.get_by_label(label).is_focused(); + // A ribbon button has keyboard focus first, so egui would act on the arrow too. + h.state_mut().ui.ribbon_tab = "Data".into(); + h.run_steps(2); + h.get_by_label("Filter").focus(); + h.run_steps(2); + // Alt, A, P, N opens the menu; Down then moves keyboard focus onto its items, wrapping. + sequence(&mut h, &[Key::A, Key::P, Key::N], false); + assert_eq!(h.state().keytips.prefix(), Some("APN")); + key(&mut h, Key::ArrowDown); + assert_eq!(h.state().keytips.prefix(), None, "an arrow ends key tips"); + assert!(focused(&h, "From Text/CSV…")); + key(&mut h, Key::ArrowDown); + assert!(focused(&h, "From Clipboard…")); + key(&mut h, Key::ArrowDown); + assert!(focused(&h, "From Text/CSV…"), "Down on the last item wraps to the first"); + key(&mut h, Key::ArrowUp); + assert!(focused(&h, "From Clipboard…"), "Up on the first item wraps to the last"); + // Enter runs the focused item and closes the menu, and doesn't also dismiss what the item + // shows: this harness has no system clipboard, which From Clipboard says. + key(&mut h, Key::Enter); + let message = format!("{:?}", h.state().message); + assert!(message.contains("can't read the clipboard"), "{message}"); + assert!(h.query_by_label("From Clipboard…").is_none(), "the menu closed"); + + // C runs From Clipboard straight from the key tips. + h.state_mut().message = None; + h.run_steps(2); + sequence(&mut h, &[Key::A, Key::P, Key::N, Key::C], false); + let message = format!("{:?}", h.state().message); + assert!(message.contains("can't read the clipboard"), "{message}"); +} diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index d406c9a8f..50036ab0c 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -40,9 +40,10 @@ pub(crate) fn sep_line(text: &str, quote: char) -> Option<(Option, usize)> } } -/// [`craft_csv::parse_records`] with a record kept to the grid's [`MAX_COLS`] fields. +/// [`craft_csv::parse_records`] with a record kept to one field past the grid's [`MAX_COLS`], so a +/// wider record can be told from one that fits; readers use the first `MAX_COLS`. fn parse_records(text: &str, delim: char, quote: char, on_record: impl FnMut(Vec) -> bool) { - craft_csv::parse_records(text, delim, quote, MAX_COLS as usize, on_record); + craft_csv::parse_records(text, delim, quote, MAX_COLS as usize + 1, on_record); } /// The delimiter and quote character to read `text` with. craft-csv always splits and unquotes, so @@ -351,10 +352,16 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook // The bounding box of the non-empty cells, which is the sheet's used range. let mut used: Option<(u32, u32, u32, u32)> = None; let mut too_many = false; + let mut widest = 0; parse_records(body, delim, quote, |rec| { if row >= MAX_ROWS { + report.truncated = true; return false; } + if rec.len() > MAX_COLS as usize { + report.truncated = true; + } + widest = widest.max(rec.len().min(MAX_COLS as usize)); // A blank line is an empty row. for (col, f) in rec.into_iter().enumerate() { if col as u32 >= MAX_COLS { @@ -401,6 +408,8 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook } wb.styles = styles; wb.sheets = vec![Arc::new(sheet)]; + report.records = row; + report.fields = u32::try_from(widest).unwrap_or(MAX_COLS); Ok((wb, report)) } diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index a1537533d..a4890ec36 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -72,6 +72,13 @@ pub enum IoError { #[derive(Clone, Debug, Default, PartialEq)] pub struct ReadReport { pub warnings: Vec, + /// A CSV read: how many records the text has and the most fields one of them has, blank ones + /// included, which a paste covers. The sheet's used range holds only the non-empty cells. + pub records: u32, + pub fields: u32, + /// A CSV read: the text has records past a sheet's last row, or fields past its last column, + /// which were left out. + pub truncated: bool, } impl ReadReport { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index eef256a03..902006923 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (File › Print › Settings: Print Selection; earlier: preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (Data › Get Data's menu imports the text on the clipboard, Alt, A, P, N, C; the cell menu's Paste Data… pastes it as columns; arrows move through key-tip menus; earlier: File › Print › Settings: Print Selection; earlier: preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -16,7 +16,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes |---|---|---|---| | 2026-10-14 | minor | Dialogs (Find and Replace, Go To, Format Cells, Sort and the rest) move by their title bar instead of staying pinned to the centre (#1250) | | Title bar, Quick Access Toolbar, AutoSave toggle | yes | yes | done; macOS window controls misaligned (#170), Dock icon size (#169) | -| Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow | +| Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum, Data › Get Data); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow | | Ribbon collapse, simplified ribbon, customize ribbon/QAT | yes | partial | customization missing (File ▸ Options is the one missing File command) | | Formulas › Function Library | Insert Function, AutoSum, Recently Used and a menu per function category | yes (10-24): a big Insert Function button and three columns of labelled small buttons, the layout Excel uses when the window is not wide enough for a big button per category; each category's book icon has its own colour; a category menu shows each function's description on hover and ends with Insert Function…, which opens the dialog on that category; More Functions cascades into Statistical, Engineering, Cube, Information, Compatibility and Web; AutoSum is a split button whose menu (Sum, Average, Count Numbers, Max, Min, More Functions…) Home › Editing shares; Recently Used has the MR key tip | the wide layout with a big button per category is not offered; a function counts as recently used once its formula is entered, not when Insert Function's OK is pressed | | Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable tabs) | done; missing contextual tabs for pictures, shapes, sparklines, header/footer, slicers | @@ -67,12 +67,13 @@ this logic, with one undo step. | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | | AutoFilter value dropdowns | Choices come from rows satisfying the other columns' active criteria; the current column only determines checkbox state, including (Blanks), so its filter can be changed or cleared (#2641). Without a search, Apply preserves selected and excluded values and blanks absent from the narrowed list. With a search, Apply excludes nonmatches throughout the column, including values hidden by another filter. Clear Filter clears the whole column. Custom comparisons, Top 10, average and color criteria use the same evaluator as row filtering. Top 10 / average thresholds still use the original range. Manual hidden rows do not restrict choices; imported icon criteria remain unevaluated. | | Data › Advanced Filter | dialog offers in-place or copy-to filtering, list and optional criteria ranges, and unique records; Alt+A,Q opens it (#1622). The engine's copy-to path clears only the result footprint and rejects worksheet overflow (#1031). | +| Data › Get Data (Text/CSV) | a split button: the button opens a text or CSV file, as before; its menu has From Text/CSV… and From Clipboard…, which asks for the separator (Comma, Semicolon, Tab, Space, or one character typed in Other; it starts on the one the text's first line uses) and imports the text on the clipboard into a new sheet as a table. `data.fromClipboard {delimiter?}` does the same without the dialog, guessing the separator when none is given. Excel's Get Data menu has no clipboard entry; this one is GridCraft's own. Where the host can't read the clipboard (the web build), it says so instead of importing nothing. Alt or F10, A, P, N opens the menu with its key tips (G a file, C the clipboard); Up or Down then moves keyboard focus onto its items, wrapping at the ends, and Enter runs one, as in every key-tip menu drawn from a list (Paste's too). The cell menu's Paste Data… opens the same dialog with a Paste at reference box (the selection's top-left cell, where Paste pastes; the sheet is the dialog's own, as in other dialogs with reference boxes) and puts the columns there instead (`data.fromClipboard {at}`), replacing what is there, with no table; every field of the text is written, so blank ones at either end clear what is under them. Both, like From Text/CSV, keep the number formats the CSV reader gives dates, percents and currency (dates in the workbook's 1900 or 1904 date system), and without a separator the reader picks comma, semicolon or tab by the text (`data.fromTextCsv`; a JSON array of records is read only then) | | Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; Data › Outline › Settings (`data.outlineSettings`) puts summary rows above and summary columns left of their detail, saved as `outlinePr` (the dialog's Automatic styles check box and Apply Styles button are missing), View › Show Outline Symbols (Ctrl+8) hides the bands and is saved with the sheet, and a block of cells still groups rows without the Rows / Columns dialog | | Reorder selected whole columns by dragging their headers | done (10-11) | | Freeze panes, split panes | freeze done; split to verify | | A Table's header names and filter buttons in the column headings once its header row scrolls away | done (#1423): with the active cell in the Table, as in Excel; the button opens the column's filter menu, the rest of the heading still selects the column. Plain AutoFilter ranges keep their letters (Excel does the same) | | Copy as HTML table for other apps | done (#36, 10-10) | -| Context menu on cells | 16 items (Cut, Copy, Paste, Paste Special, Insert, Delete, Clear Contents, Filter by value, Sort, New Comment, New Note, Format Cells, Pick From Drop-down List, Define Name, Link). Insert Copied Cells (Insert Cut Cells for whole rows/columns) while the clipboard holds a copy (#21). Show Details on a PivotTable's value, subtotal or grand total cell (`pivot.showDetails`). Missing: Insert Cut Cells for a cell block, paste-option icons, Quick Analysis, Get Data from Table, Show Changes, Smart Lookup | +| Context menu on cells | 17 items (Cut, Copy, Paste, Paste Special, Paste Data, Insert, Delete, Clear Contents, Filter by value, Sort, New Comment, New Note, Format Cells, Pick From Drop-down List, Define Name, Link). Insert Copied Cells (Insert Cut Cells for whole rows/columns) while the clipboard holds a copy (#21). Show Details on a PivotTable's value, subtotal or grand total cell (`pivot.showDetails`). Missing: Insert Cut Cells for a cell block, paste-option icons, Quick Analysis, Get Data from Table, Show Changes, Smart Lookup | | Move and resize charts, pictures and shapes | done (#190, #213): charts, pictures, shapes, equations and slicers select with a frame of eight handles; each handle resizes only its own edges (they never cross), the body moves the object, and the pointer shows a resize or move cursor; Delete or Backspace deletes the selected object and Escape drops the selection; double-click edits a text box, opens Format Chart for a chart. Rotation handle, Shift for proportional resizing, Alt to snap to cells and multi-object selection missing | | Form controls: buttons, scroll bars (sliders), spin buttons | done (10-31): Insert › Controls (Button, Slider, Spin Button; Excel has them under Developer › Insert) places one by a drag, or at its default size by a click; a click works a control: drag the thumb, page on the track, click or hold an arrow (a drag or a hold is one undo step), press a button, which runs a macro or a command and asks first in a workbook opened from a file (an answer runs only the action it asked about: if an agent changes the button, its macro or the selection while the prompt is open, nothing runs); the control last worked takes the arrows, Page Up and Page Down, Home, End, and Space or Enter (a button gives the keyboard back as soon as the grid takes a key or a right-click; Space on a slider or spin button does what it does with no control focused: it toggles a checkbox cell or starts a cell edit like any other character); Ctrl or Cmd+click or a right-click selects it to move or resize; its menu has Edit Text, Assign Action, Format Control and Delete. Check boxes, option buttons, list boxes and drop-downs (form controls) are kept from files but not shown | | Context menus on row/column headers, sheet tabs, charts, shapes | headers and tabs done; objects partial | @@ -296,6 +297,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-11-27 | minor | Data › Get Data (Text/CSV) is a split button: the button still opens a text or CSV file, and its menu adds From Clipboard…, which asks for the separator (comma, semicolon, tab, space or another character; the one the text uses is chosen first) and imports the text on the clipboard into a new sheet as a table, as From Text/CSV imports a file (`data.fromClipboard {delimiter?}`); Alt, A, P, N, C reaches it, and Up or Down in a menu key tips opened (Get Data, Paste) moves focus onto its items. The cell menu's Paste Data… uses the same dialog to put the columns at the cell (`at`) | | 2026-11-19 | minor | Typing a leading `+` or `-` starts a formula whenever the entry isn't a number on its own, as in Excel: `+5+4` enters `=+5+4` and `-5+4` enters `=-5+4` (they stayed text; only a letter or `(` after the sign started one). `+5`, `-5` and `-$5` stay numbers, and a lone `+` or `-` and an entry that doesn't read as a formula (`--`, `+49 170 1234567`) stay text, as observed in Excel for the web; only `=` entries are refused (#2023) | | 2026-11-19 | minor | AutoSum from the ribbon or keyboard on one cell proposes `=SUM(range)` in the editor instead of entering it, with the range pointed and selected: a click, drag, arrow key or typing replaces it and Enter enters it, as in Excel. With nothing to sum the caret waits inside `=SUM()`. A block still gets its totals at once, and programmatic `formulas.autoSum` is unchanged (#1834) | | 2026-11-15 | minor | The rows of both validation list popups are drawn in slots of exactly the row height the popup scrolls by, so a font whose text is laid out a pixel taller than its nominal line height no longer pushes the last visible row under the "More entries not shown" note (seen with the pinned test fonts, not with the fonts of a desktop install). That note is translated in all 18 interface catalogs, and the validation-list UI tests run on the pinned font set | diff --git a/xtask/src/keytips.rs b/xtask/src/keytips.rs index 71bd9c509..606c5e9d1 100644 --- a/xtask/src/keytips.rs +++ b/xtask/src/keytips.rs @@ -331,6 +331,12 @@ fn render_tests(entries: &[Entry], probe: &Probe) -> String { "sequence(&mut h, {seq:?}, false);\n assert!(h.state().backstage.is_some(), \"{seq} must open the Options page\");", seq = e.seq, ), + // From Clipboard first reads the clipboard, which the test harness doesn't have: it + // says so rather than opening a dialog with nothing to import. + "dialog" if e.target == "fromClipboard" => format!( + "sequence(&mut h, {seq:?}, false);\n assert!(h.state().message.as_ref().is_some_and(|(_, m)| m.contains(\"clipboard\")), \"{seq} must open From Clipboard, which says there is no clipboard here\");", + seq = e.seq, + ), "dialog" => format!( "sequence(&mut h, {seq:?}, false);\n assert!(h.state().dialog.is_some(), \"{seq} must open the {dialog} dialog\");", seq = e.seq,