DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge remote-tracking branch 'origin/main' into table-menu-insert
moppeeer1fbe3f272a61
diff --cc crates/engine/src/cmd/table.rsindex 165ba9588,2a124e7a9..e7e9cc3e7--- a/crates/engine/src/cmd/table.rs+++ b/crates/engine/src/cmd/table.rs@@@ -17,2513 -17,15 +17,16 @@@ use serde_json::{Value, json}use super::{CommandSpec, bad, cmd, f64_or, has_doc, has_text, ok, str_param};use crate::{Result, Session};- pub fn specs() -> Vec<CommandSpec> {- let mut v = style_specs();- v.extend(table_specs());- v- }-- fn style_specs() -> Vec<CommandSpec> {- vec![- cmd!(- "style.cell.create",- "New Cell Style…",- [],- None,- "{name, fromSelection?: bool (the target cell's look), fill?, tint?, insets?: n|[t,l,b,r], vj?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|fixed|emboxHeight, firstBaselineMin?: pt, stroke?: {weight?, color?, tint?, type?, gapColor?, gapTint?} (all four edges; values as table.setCell's stroke), paragraphStyle?, basedOn?: cell style name, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} → {name}",- has_doc,- |s, p| cell_style_create(s, p)- ),- cmd!(- "style.cell.apply",- "Apply Cell Style",- [],- None,- "{name, story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} — the target cells (the whole table when the cursor is in it)",- in_table,- cell_style_apply- ),- cmd!(- "style.cell.edit",- "Cell Style Options…",- [],- None,- "{name, …same as style.cell.create} — cells using the style follow",- has_doc,- cell_style_edit- ),- cmd!(- "style.table.create",- "New Table Style…",- [],- None,- "{name, basedOn?: table style name, header?, body?, footer?, leftColumn?, rightColumn?: cell style names, border?: {weight?, color?, tint?, type?, gapColor?, gapTint?}, altRows?: {first, firstColor, next, nextColor}, spaceBefore?, spaceAfter?} → {name}",- has_doc,- table_style_create- ),- cmd!(- "style.table.apply",- "Apply Table Style",- [],- None,- "{name, story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?}",- in_table,- table_style_apply- ),- cmd!(- "style.table.edit",- "Table Style Options…",- [],- None,- "{name, …same as style.table.create} — tables using the style follow",- has_doc,- table_style_edit- ),- ]- }-- fn table_specs() -> Vec<CommandSpec> {- vec![- cmd!(- "table.insert",- "Create Table",- [],- // InDesign's Cmd+Alt+Shift+T opens the Insert Table dialog (`app.insertTableDialog`).- None,- "{rows?: body rows (4, at most 500), cols? | columns? (4, at most 200), headerRows? (0), footerRows? (0, each at most 100), tableStyle?: name, width?} — at the text insertion point, styled in the same step",- has_text,- insert- ),- cmd!(- "table.convertFromText",- "Convert Text to Table",- ["Table"],- None,- "{columnSeparator?: tab|comma, width?: table width (default: the column)} — selected paragraphs become rows",- has_text,- convert_from_text- ),- cmd!(- "table.convertToText",- "Convert Table to Text",- ["Table"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — cells separated by tabs, rows by paragraphs",- in_table,- convert_to_text- ),- cmd!(- "table.insertRow",- "Insert Row",- [],- None,- "{where?: above|below, count? (1), story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- |s, p| insert_row(s, p, None)- ),- cmd!(- "table.insertRowAbove",- "Insert Row Above",- ["Table", "Insert"],- None,- "{count?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- |s, p| insert_row(s, p, Some(true))- ),- cmd!(- "table.insertRowBelow",- "Insert Row Below",- ["Table", "Insert"],- None,- "{count?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- |s, p| insert_row(s, p, Some(false))- ),- cmd!(- "table.insertColumn",- "Insert Column",- [],- None,- "{where?: left|right, count? (1), width?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- |s, p| insert_col(s, p, None)- ),- cmd!(- "table.insertColumnLeft",- "Insert Column Left",- ["Table", "Insert"],- None,- "{count?, width?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- |s, p| insert_col(s, p, Some(true))- ),- cmd!(- "table.insertColumnRight",- "Insert Column Right",- ["Table", "Insert"],- None,- "{count?, width?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- |s, p| insert_col(s, p, Some(false))- ),- cmd!(- "table.deleteRow",- "Delete Row",- ["Table", "Delete"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the rows of the target cells",- in_table,- delete_rows- ),- cmd!(- "table.deleteColumn",- "Delete Column",- ["Table", "Delete"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the columns of the target cells",- in_table,- delete_cols- ),- cmd!(- "table.delete",- "Delete Table",- ["Table", "Delete"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- delete_table- ),- cmd!(- "table.merge",- "Merge Cells",- ["Table"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — merge the target cell range",- in_table,- merge- ),- cmd!(- "table.dropCells",- "Drag Rows or Columns",- [],- None,- "{frame, from: [x, y], to: [x, y]} — selected whole rows (or columns) dragged from `from` move to the row (column) at `to`; otherwise a text drag",- has_doc,- drop_cells- ),- cmd!(- "table.placeGraphic",- "Convert Cell to Graphic Cell",- ["Table", "Convert Cell Type"],- None,- "{path? | base64?, name?: with base64, fit?: proportional|fill (default proportional), story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — an image in the target cell (its text is kept but hidden)",- in_table,- place_graphic- ),- cmd!(- "table.textCell",- "Convert Cell to Text Cell",- ["Table", "Convert Cell Type"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — drop the target cells' graphics",- in_table,- |s, p| {- let g = target(s, p, "table.textCell")?;- edit_table(s, &g, "table.textCell", |t| {- for (r, c) in t.selected_owners(g.range) {- if let Some(cell) = t.cell_mut(r, c) {- cell.graphic = None;- }- }- ok()- })- }- ),- cmd!(- "table.moveRow",- "Move Row",- [],- None,- "{from?, to, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} (0-based; from defaults to the target row) — like dragging a row",- in_table,- |s, p| move_rc(s, p, true)- ),- cmd!(- "table.moveColumn",- "Move Column",- [],- None,- "{from?, to, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} (0-based; from defaults to the target column)",- in_table,- |s, p| move_rc(s, p, false)- ),- cmd!(- "table.sortRows",- "Sort",- ["Table"],- None,- "{column?: 0-based (default: the target cell's), descending?: bool, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — body rows by that column's text (numbers numerically)",- in_table,- sort_rows- ),- cmd!(- "table.unmerge",- "Unmerge Cells",- ["Table"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- unmerge- ),- cmd!(- "table.splitHorizontally",- "Split Cell Horizontally",- ["Table"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — each target cell becomes two, one above the other",- in_table,- |s, p| split(s, p, true)- ),- cmd!(- "table.splitVertically",- "Split Cell Vertically",- ["Table"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — each target cell becomes two, side by side",- in_table,- |s, p| split(s, p, false)- ),- cmd!(- "table.setCell",- "Cell Options",- [],- None,- "{fill?: swatch, tint?: 0..1, insets?: n | [t,l,b,r], vj? | verticalJustification?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|fixed|emboxHeight, firstBaselineMin?: pt, rotation?: 0|90|180|270 (Cell Options › Text › Rotation; kept and written back to IDML, composed horizontally for now), text?, stroke?: {weight?, color?: swatch, tint?: 0..1, type?: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed | {kind:…}, gapColor?: swatch, gapTint?: 0..1, edges?: name | [names] (all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical; default all)}, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — top/left/bottom/right are the target range's outer sides, innerHorizontal/innerVertical the lines between its rows/columns",- in_table,- set_cell- ),- cmd!(- query "table.getCellStroke",- "Get Cell Stroke",- [],- None,- "{story?, table?, rows?, cols?, edges?} → {weight, color, tint, type, gapColor, gapTint, fill, fillTint, edges: count} of the chosen edges of the target cells; a value that differs between them is null",- in_table_or_ids,- get_cell_stroke- ),- cmd!(- "table.setRowHeight",- "Row Height",- [],- None,- "{height, mode?: atLeast|exactly, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- set_row_height- ),- cmd!(- "table.setColumnWidth",- "Column Width",- [],- None,- "{width, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- set_col_width- ),- cmd!(- "table.resizeBorder",- "Resize Row or Column",- [],- None,- "{story?, table?, frame?, axis: column|row, index, delta? | size?, keepTableSize?: bool} — moves the border after column/row `index` by `delta` (or makes that column/row `size` wide/high); later columns/rows move along. The last index is the table's end/bottom edge. keepTableSize: on an inner border the next column/row gives or takes the change; on the edge all columns/rows scale proportionally. A dragged row becomes At Least. Refuses a locked `frame`",- in_table_or_ids,- resize_border- ),- cmd!(- "table.distributeColumns",- "Distribute Columns Evenly",- ["Table"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- distribute_cols- ),- cmd!(- "table.distributeRows",- "Distribute Rows Evenly",- ["Table"],- None,- "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} — equal fixed heights preserving the selected rows' composed total height; may overset cell text; unmerge row-spanning cells first",- in_table,- distribute_rows- ),- cmd!(- "table.options",- "Table Options",- [],- None,- "{direction?: leftToRight|rightToLeft, border?: {weight?, color?, tint?, type?, gapColor?, gapTint?}, spaceBefore?, spaceAfter?, headerRows?, footerRows?, repeatHeader?, repeatFooter?, altRows?: {first, firstColor, firstTint, next, nextColor, nextTint, skipFirst, skipLast} | null, altCols?: … | null, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",- in_table,- options- ),- cmd!(- "table.convertRowsToHeader",- "To Header",- ["Table", "Convert Rows"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the target rows, at the top of the table or right after its header rows",- |s| can_convert_rows(s, RowKind::Header),- |s, p| convert_rows(s, p, RowKind::Header)- ),- cmd!(- "table.convertRowsToBody",- "To Body",- ["Table", "Convert Rows"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the target header rows next to the body, footer rows next to it, or both",- |s| can_convert_rows(s, RowKind::Body),- |s, p| convert_rows(s, p, RowKind::Body)- ),- cmd!(- "table.convertRowsToFooter",- "To Footer",- ["Table", "Convert Rows"],- None,- "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the target rows, at the bottom of the table or right before its footer rows",- |s| can_convert_rows(s, RowKind::Footer),- |s, p| convert_rows(s, p, RowKind::Footer)- ),- cmd!(noundo "table.select", "Select Cells", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?, what?: cell|row|column|table}", in_table_or_ids, select),- cmd!(noundo "table.selectTable", "Select Table", ["Table", "Select"], None, "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}", in_table, |s, p| {- select(s, &super::with_param(p, "what", json!("table")))- }),- cmd!(noundo "table.selectRow", "Select Row", ["Table", "Select"], None, "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}", in_table, |s, p| {- select(s, &super::with_param(p, "what", json!("row")))- }),- cmd!(noundo "table.selectColumn", "Select Column", ["Table", "Select"], None, "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}", in_table, |s, p| {- select(s, &super::with_param(p, "what", json!("column")))- }),- cmd!(noundo "table.nextCell", "Next Cell", [], None, "{}", in_cell, |s, _| step_cell(s, true)),- cmd!(noundo "table.prevCell", "Previous Cell", [], None, "{}", in_cell, |s, _| step_cell(s, false)),- cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} → rows, columns, cells (text, spans, fill), options", in_table_or_ids, get),- ]- }-- // ---------- enablement and targeting ------------ fn in_table(s: &Session) -> std::result::Result<(), String> {- has_doc(s)?;- let st = s.active().ok_or("no document open")?;- if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some()) {- return Ok(());- }- if let Some(t) = st.selection.text- && st.doc.story(t.story).is_some_and(|x| x.table_at(t.focus).is_some())- {- return Ok(());- }- Err("place the insertion point in a table".into())- }-- fn in_table_or_ids(s: &Session) -> std::result::Result<(), String> {- has_doc(s)- }-- fn in_cell(s: &Session) -> std::result::Result<(), String> {- has_doc(s)?;- if s.active().is_some_and(|d| d.selection.text.is_some_and(|t| t.cell.is_some())) { Ok(()) } else { Err("not in a table cell".into()) }- }-- /// The table a command acts on and its target cell range.- struct Tgt {- story: StoryId,- table: u64,- range: CellRange,- }-- fn find_table(doc: &Document, id: u64) -> Option<StoryId> {- doc.stories.iter().find(|(_, s)| s.tables.contains_key(&id)).map(|(k, _)| *k)- }-- fn pair(p: &Value, many: &str, one: &str) -> Option<(usize, usize)> {- if let Some(a) = p.get(many).and_then(Value::as_array) {- let a0 = a.first()?.as_u64()? as usize;- let a1 = a.get(1).and_then(Value::as_u64).map_or(a0, |v| v as usize);- return Some((a0.min(a1), a0.max(a1)));- }- p.get(one).and_then(Value::as_u64).map(|v| (v as usize, v as usize))- }-- fn target(s: &Session, p: &Value, cmd: &str) -> Result<Tgt> {- let st = s.doc()?;- let doc = &st.doc;- let explicit_table = p.get("table").and_then(Value::as_u64);- let explicit_story = p.get("story").and_then(Value::as_u64).map(StoryId);- let (story, table, range) = if let Some(tid) = explicit_table {- let sid = explicit_story.or_else(|| find_table(doc, tid)).ok_or_else(|| bad(cmd, format!("no table {tid}")))?;- (sid, tid, None)- } else if let Some(c) = st.selection.cells {- (c.story, c.table, Some(c.range))- } else if let Some(t) = st.selection.text {- match t.cell {- Some(c) => (t.story, c.table, Some(CellRange::cell(c.row, c.col))),- None => {- let tid = doc.story(t.story).and_then(|x| x.table_at(t.focus)).ok_or_else(|| bad(cmd, "the insertion point is not in a table"))?;- (t.story, tid, None)- }- }- } else {- return Err(bad(cmd, "place the insertion point in a table"));- };- let t = doc.story(story).and_then(|x| x.tables.get(&table)).ok_or_else(|| bad(cmd, format!("no table {table}")))?;- let (nr, nc) = (t.nrows(), t.ncols());- let mut range = range.unwrap_or(CellRange { r0: 0, c0: 0, r1: nr - 1, c1: nc - 1 });- if let Some((a, b)) = pair(p, "rows", "row") {- range.r0 = a;- range.r1 = b;- }- if let Some((a, b)) = pair(p, "cols", "col") {- range.c0 = a;- range.c1 = b;- }- if range.r1 >= nr || range.c1 >= nc {- return Err(bad(cmd, format!("cell range out of bounds ({nr}×{nc} table)")));- }- Ok(Tgt { story, table, range })- }-- /// Edit the target table; afterwards selections pointing into it are clamped to its new shape.- fn edit_table<T>(s: &mut Session, g: &Tgt, cmd: &str, f: impl FnOnce(&mut Table) -> Result<T>) -> Result<T> {- let cmd = cmd.to_string();- s.edit(|d, sel| {- let st = d.story_mut(g.story).ok_or_else(|| bad(&cmd, "no story"))?;- let t = st.table_mut(g.table).ok_or_else(|| bad(&cmd, "no table"))?;- let r = f(t)?;- clamp_selection(d, sel);- Ok(r)- })- }-- /// Keep text/cell selections valid after the table changed shape (or disappeared).- fn clamp_selection(d: &Document, sel: &mut Selection) {- if let Some(ts) = sel.cells {- match d.story(ts.story).and_then(|x| x.tables.get(&ts.table)) {- Some(t) => {- let (mr, mc) = (t.nrows() - 1, t.ncols() - 1);- let r = ts.range;- sel.cells = Some(TableSel { range: CellRange::new(r.r0.min(mr), r.c0.min(mc), r.r1.min(mr), r.c1.min(mc)), ..ts });- }- None => sel.cells = None,- }- }- if let Some(t) = sel.text- && let Some(c) = t.cell- {- let story = d.story(t.story);- match story.and_then(|x| x.tables.get(&c.table)) {- Some(tb) => {- let (r, col) = tb.owner(c.row.min(tb.nrows() - 1), c.col.min(tb.ncols() - 1));- let text = tb.cell(r, col).map_or("", |x| x.text.text.as_str());- sel.text = Some(TextSel {- anchor: floor_char_boundary(text, t.anchor),- focus: floor_char_boundary(text, t.focus),- cell: Some(CellAddr { table: c.table, row: r, col }),- ..t- });- }- None => {- let pos = story.map_or(0, |x| floor_char_boundary(&x.text, t.anchor));- sel.text = Some(TextSel { anchor: pos, focus: pos, cell: None, ..t });- }- }- }- }-- fn count(p: &Value) -> usize {- p.get("count").and_then(Value::as_u64).unwrap_or(1).clamp(1, 1000) as usize- }-- fn color_param(p: &Value, key: &str) -> Option<String> {- str_param(p, key).map(str::to_string)- }-- // ---------- create / convert ------------ /// Width of the text column at the caret (the new table spans it).- fn column_width(s: &Session, t: &TextSel) -> f64 {- let Some(st) = s.active() else { return 300.0 };- let specs = compose::frame_specs(&st.doc, t.story);- let spec = t.frame.and_then(|f| specs.iter().find(|x| x.id == f)).or(specs.first());- spec.and_then(|f| f.columns().first().map(|c| c.width())).unwrap_or(300.0)- }-- /// The direction of the paragraph at `offset` in `story`, as composition resolves it (its style- /// chain, then local overrides). A table created there takes it.- fn para_direction(d: &Document, story: StoryId, offset: usize) -> designcraft_doc::TextDirection {- d.story(story)- .and_then(|st| st.paras.get(st.para_at(offset)))- .map_or(designcraft_doc::TextDirection::LeftToRight, |pf| d.styles.resolve_para(pf).0.direction)- }-- /// The most body rows, columns, and header or footer rows `table.insert` makes (the Insert Table- /// dialog's limits too).- pub const MAX_BODY_ROWS: u64 = 500;- pub const MAX_COLUMNS: u64 = 200;- pub const MAX_HEADER_FOOTER_ROWS: u64 = 100;-- /// A command's `tableStyle`: none for an absent one or [Basic Table] (a new table's look), else the- /// resolved style and the cell styles it names. Anything but an existing style's name is an error.- fn table_style_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<(designcraft_doc::TableStyle, Vec<designcraft_doc::CellStyle>)>> {- let name = match p.get("tableStyle") {- None | Some(Value::Null) => return Ok(None),- Some(Value::String(n)) if n == designcraft_doc::BASIC_TABLE => return Ok(None),- Some(Value::String(n)) => n,- Some(_) => return Err(bad(cmd, "`tableStyle` must be a table style's name")),- };- let styles = &s.doc()?.doc.styles;- if !styles.table.iter().any(|x| x.name == *name) {- return Err(bad(cmd, format!("no table style `{name}`")));- }- Ok(Some((styles.resolve_table_style(name), styles.cell.clone())))- }-- fn insert(s: &mut Session, p: &Value) -> Result<Value> {- let t = s.doc()?.selection.text.ok_or_else(|| bad("table.insert", "no insertion point"))?;- if t.cell.is_some() {- return Err(bad("table.insert", "tables can't be nested in cells"));- }- let rows = p.get("rows").and_then(Value::as_u64).unwrap_or(4).clamp(1, MAX_BODY_ROWS) as usize;- let cols = p.get("cols").or_else(|| p.get("columns")).and_then(Value::as_u64).unwrap_or(4).clamp(1, MAX_COLUMNS) as usize;- let header = p.get("headerRows").and_then(Value::as_u64).unwrap_or(0).min(MAX_HEADER_FOOTER_ROWS) as usize;- let footer = p.get("footerRows").and_then(Value::as_u64).unwrap_or(0).min(MAX_HEADER_FOOTER_ROWS) as usize;- let style = table_style_param(s, p, "table.insert")?;- let width = p.get("width").and_then(Value::as_f64).unwrap_or_else(|| column_width(s, &t));- s.edit(|d, sel| {- let id = d.alloc();- let mut table = Table::new(id, rows, cols, header, footer, width);- table.options.direction = para_direction(d, t.story, t.range().start);- let st = d.story_mut(t.story).ok_or_else(|| bad("table.insert", "no story"))?;- // Cells start with the paragraph format at the caret.- let pf = st.paras[st.para_at(t.range().start)].clone();- let cf = st.char_format_at(t.range().start).clone();- for c in &mut table.cells {- c.text.paras[0] = designcraft_doc::ParaFormat { table: None, ..pf.clone() };- c.text.chars[0].format = cf.clone();- }- if let Some((ts, cells)) = &style {- ts.apply_to(&mut table, cells);- }- let r = t.range();- st.delete(r.clone());- st.insert_table(r.start, table);- *sel = Selection::text(TextSel { story: t.story, anchor: 0, focus: 0, frame: t.frame, cell: Some(CellAddr { table: id, row: 0, col: 0 }) });- Ok(json!({"story": t.story.0, "table": id}))- })- }-- fn convert_from_text(s: &mut Session, p: &Value) -> Result<Value> {- let t = s.doc()?.selection.text.ok_or_else(|| bad("table.convertFromText", "no text selected"))?;- if t.cell.is_some() {- return Err(bad("table.convertFromText", "select text outside tables"));- }- let sep = if str_param(p, "columnSeparator") == Some("comma") { ',' } else { '\t' };- let width = p.get("width").and_then(Value::as_f64).unwrap_or_else(|| column_width(s, &t));- s.edit(|d, sel| {- let id = d.alloc();- let direction = para_direction(d, t.story, t.range().start);- let st = d.story_mut(t.story).ok_or_else(|| bad("table.convertFromText", "no story"))?;- let ranges = st.para_ranges();- let (pa, pb) = (st.para_at(t.range().start), st.para_at(t.range().end));- if (pa..=pb).any(|i| st.paras[i].table.is_some()) {- return Err(bad("table.convertFromText", "the selection contains a table"));- }- let (a, b) = (ranges[pa].start, ranges[pb].end);- let data: Vec<Vec<String>> = st.text[a..b].split('\n').map(|line| line.split(sep).map(|c| c.trim().to_string()).collect()).collect();- let pf = st.paras[pa].clone();- let cf = st.format_after(a).clone();- let mut table = Table::from_strings(id, &data, width, &pf, &cf);- table.options.direction = direction;- st.delete(a..b);- let anchor = st.insert_table(a, table);- *sel = Selection::text(TextSel::caret(t.story, anchor));- Ok(json!({"table": id, "rows": data.len()}))- })- }-- fn convert_to_text(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.convertToText")?;- s.edit(|d, sel| {- let st = d.story_mut(g.story).ok_or_else(|| bad("table.convertToText", "no story"))?;- let text = st.tables.get(&g.table).map(|t| t.plain_text()).unwrap_or_default();- let a = st.table_anchor(g.table).ok_or_else(|| bad("table.convertToText", "no anchor"))?;- st.replace(a..a + designcraft_doc::TABLE_ANCHOR.len_utf8(), &text);- *sel = Selection::text(TextSel::caret(g.story, a + text.len()));- ok()- })- }-- fn delete_table(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.delete")?;- s.edit(|d, sel| {- let st = d.story_mut(g.story).ok_or_else(|| bad("table.delete", "no story"))?;- let a = st.table_anchor(g.table).ok_or_else(|| bad("table.delete", "no anchor"))?;- // Remove the anchor paragraph (with one separator) so no empty paragraph is left behind.- let end = a + designcraft_doc::TABLE_ANCHOR.len_utf8();- let r = if &st.text[end..] == "\n" && a > 0 && st.text[..a].ends_with('\n') {- // Inserted at the end of the story: remove the empty paragraph after it too.- a - 1..end + 1- } else if st.text[end..].starts_with('\n') {- a..end + 1- } else if a > 0 && st.text[..a].ends_with('\n') {- a - 1..end- } else {- a..end- };- st.delete(r.clone());- *sel = Selection::text(TextSel::caret(g.story, r.start.min(st.len())));- ok()- })- }-- // ---------- rows and columns ------------ fn insert_row(s: &mut Session, p: &Value, above: Option<bool>) -> Result<Value> {- let g = target(s, p, "table.insertRow")?;- let above = above.unwrap_or(str_param(p, "where") == Some("above"));- let n = count(p);- let at = if above { g.range.r0 } else { g.range.r1 + 1 };- let r = edit_table(s, &g, "table.insertRow", |t| {- t.insert_rows(at, n);- Ok(json!({"rows": t.nrows()}))- })?;- shift_selection(s, g.table, at, n, true);- Ok(r)- }-- /// After inserting rows/columns at `at`, selections at or after it follow their cells.- fn shift_selection(s: &mut Session, table: u64, at: usize, n: usize, rows: bool) {- let Ok(st) = s.doc_mut() else { return };- if let Some(t) = st.selection.text.as_mut()- && let Some(c) = t.cell.as_mut()- && c.table == table- {- let v = if rows { &mut c.row } else { &mut c.col };- if *v >= at {- *v += n;- }- }- if let Some(ts) = st.selection.cells.as_mut()- && ts.table == table- {- let (a, b) = if rows { (&mut ts.range.r0, &mut ts.range.r1) } else { (&mut ts.range.c0, &mut ts.range.c1) };- if *a >= at {- *a += n;- }- if *b >= at {- *b += n;- }- }- }-- fn insert_col(s: &mut Session, p: &Value, left: Option<bool>) -> Result<Value> {- let g = target(s, p, "table.insertColumn")?;- let left = left.unwrap_or(str_param(p, "where") == Some("left"));- let rtl = s- .doc()?- .doc- .story(g.story)- .and_then(|st| st.tables.get(&g.table))- .is_some_and(|t| t.options.direction == designcraft_doc::TextDirection::RightToLeft);- let n = count(p);- let at = if left != rtl { g.range.c0 } else { g.range.c1 + 1 };- let width = p.get("width").and_then(Value::as_f64);- let r = edit_table(s, &g, "table.insertColumn", |t| {- let w = width.unwrap_or_else(|| t.columns[g.range.c0.min(t.ncols() - 1)].width);- t.insert_cols(at, n, w);- Ok(json!({"columns": t.ncols()}))- })?;- shift_selection(s, g.table, at, n, false);- Ok(r)- }-- fn delete_rows(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.deleteRow")?;- let all = s.doc()?.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).is_some_and(|t| g.range.r0 == 0 && g.range.r1 + 1 >= t.nrows());- if all {- return delete_table(s, p);- }- edit_table(s, &g, "table.deleteRow", |t| {- t.delete_rows(g.range.r0, g.range.r1 - g.range.r0 + 1);- Ok(json!({"rows": t.nrows()}))- })- }-- fn delete_cols(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.deleteColumn")?;- let all = s.doc()?.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).is_some_and(|t| g.range.c0 == 0 && g.range.c1 + 1 >= t.ncols());- if all {- return delete_table(s, p);- }- edit_table(s, &g, "table.deleteColumn", |t| {- t.delete_cols(g.range.c0, g.range.c1 - g.range.c0 + 1);- Ok(json!({"columns": t.ncols()}))- })- }-- fn merge(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.merge")?;- let r = edit_table(s, &g, "table.merge", |t| {- t.merge(g.range).map_err(|e| bad("table.merge", e))?;- Ok(t.expand_range(g.range))- })?;- // The caret goes to the merged cell.- let st = s.doc_mut()?;- st.selection = Selection::text(TextSel {- story: g.story,- anchor: 0,- focus: 0,- frame: st.selection.text.and_then(|t| t.frame),- cell: Some(CellAddr { table: g.table, row: r.r0, col: r.c0 }),- });- ok()- }-- fn split(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {- let g = target(s, p, "table.split")?;- edit_table(s, &g, "table.split", |t| {- t.split_cells(g.range, horizontal).map_err(|e| bad("table.split", e))?;- Ok(json!({"rows": t.nrows(), "cols": t.ncols()}))- })- }-- fn unmerge(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.unmerge")?;- edit_table(s, &g, "table.unmerge", |t| {- for r in g.range.r0..=g.range.r1 {- for c in g.range.c0..=g.range.c1 {- t.unmerge(r, c);- }- }- ok()- })- }-- /// Cell edges chosen for a stroke edit: the target range's four outer sides (physical left and- /// right) and the lines between its rows and columns.- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]- struct EdgeSel {- top: bool,- left: bool,- bottom: bool,- right: bool,- inner_h: bool,- inner_v: bool,- }-- impl EdgeSel {- const ALL: EdgeSel = EdgeSel { top: true, left: true, bottom: true, right: true, inner_h: true, inner_v: true };-- fn parse(v: Option<&Value>, cmd: &str) -> Result<EdgeSel> {- let names: Vec<&Value> = match v {- None | Some(Value::Null) => return Ok(EdgeSel::ALL),- Some(Value::Array(a)) => a.iter().collect(),- Some(v) => vec![v],- };- let mut e = EdgeSel::default();- for n in names {- match n.as_str() {- Some("all") => e = EdgeSel::ALL,- Some("outer") => (e.top, e.left, e.bottom, e.right) = (true, true, true, true),- Some("inner") => (e.inner_h, e.inner_v) = (true, true),- Some("top") => e.top = true,- Some("left") => e.left = true,- Some("bottom") => e.bottom = true,- Some("right") => e.right = true,- Some("innerHorizontal") => e.inner_h = true,- Some("innerVertical") => e.inner_v = true,- _ => return Err(bad(cmd, format!("unknown edge {n}; use all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical"))),- }- }- if e == EdgeSel::default() {- return Err(bad(cmd, "no edges chosen"));- }- Ok(e)- }-- /// Which sides (top, left, bottom, right) of the cell at `(r, c)` with `spans` are chosen- /// within `rg`. Left and right are physical sides, also in RTL tables.- fn sides(&self, rg: CellRange, (r, c): (usize, usize), spans: (u32, u32), rtl: bool) -> [bool; 4] {- let last_row = r.saturating_add((spans.0.max(1) - 1) as usize);- let last_col = c.saturating_add((spans.1.max(1) - 1) as usize);- let (start, end) = (c <= rg.c0, last_col >= rg.c1);- let (left_outer, right_outer) = if rtl { (end, start) } else { (start, end) };- [- if r <= rg.r0 { self.top } else { self.inner_h },- if left_outer { self.left } else { self.inner_v },- if last_row >= rg.r1 { self.bottom } else { self.inner_h },- if right_outer { self.right } else { self.inner_v },- ]- }- }-- /// A finite number in `lo..=hi`, or an error naming `key`.- fn num_in(v: &Value, key: &str, lo: f64, hi: f64, cmd: &str) -> Result<Option<f64>> {- match v.get(key) {- None | Some(Value::Null) => Ok(None),- Some(x) => match x.as_f64() {- Some(n) if n.is_finite() && (lo..=hi).contains(&n) => Ok(Some(n)),- _ => Err(bad(cmd, format!("{key} must be a number from {lo} to {hi}"))),- },- }- }-- /// A swatch of the document (or [None]), or an error naming `key`.- fn swatch_in(doc: &Document, v: &Value, keys: &[&str], cmd: &str) -> Result<Option<String>> {- let Some((key, x)) = keys.iter().find_map(|k| v.get(*k).filter(|x| !x.is_null()).map(|x| (*k, x))) else { return Ok(None) };- let name = x.as_str().ok_or_else(|| bad(cmd, format!("{key} must be a swatch name")))?;- if name != designcraft_color::swatch::NONE && doc.swatch(name).is_none() {- return Err(bad(cmd, format!("no swatch `{name}`")));- }- Ok(Some(name.to_string()))- }-- /// The cell stroke type names of `type`.- const CELL_STROKE_TYPES: &[&str] =- &["solid", "dashed", "dotted", "thickThin", "thinThick", "thinThin", "thickThick", "thinThickThin", "thickThinThick", "wavy", "hashed"];-- /// The attributes a stroke edit sets. A plain `"dashed"` gets a pattern scaled to the- /// resulting weight of each edge.- struct StrokeEdit {- attrs: designcraft_doc::CellStrokeAttrs,- scaled_dashes: bool,- }-- impl StrokeEdit {- fn parse(doc: &Document, v: &Value, cmd: &str) -> Result<StrokeEdit> {- if !v.is_object() {- return Err(bad(cmd, "stroke must be an object"));- }- let mut attrs = designcraft_doc::CellStrokeAttrs {- weight: num_in(v, "weight", 0.0, 1000.0, cmd)?,- color: swatch_in(doc, v, &["color"], cmd)?,- tint: num_in(v, "tint", 0.0, 1.0, cmd)?.map(|t| t as f32),- gap_color: swatch_in(doc, v, &["gapColor", "gapSwatch"], cmd)?,- gap_tint: num_in(v, "gapTint", 0.0, 1.0, cmd)?.map(|t| t as f32),- kind: None,- };- let mut scaled_dashes = false;- match v.get("type") {- None | Some(Value::Null) => {}- Some(Value::String(name)) if name == "dashed" => {- scaled_dashes = true;- attrs.kind = Some(StrokeType::Dashed { pattern: Vec::new() });- }- Some(Value::String(name)) if CELL_STROKE_TYPES.contains(&name.as_str()) => {- attrs.kind = Some(serde_json::from_value(json!({"kind": name})).map_err(|e| bad(cmd, e.to_string()))?);- }- Some(t @ Value::Object(_)) => {- let kind: StrokeType = serde_json::from_value(t.clone()).map_err(|e| bad(cmd, format!("bad stroke type: {e}")))?;- let finite = |v: &[f64]| v.len() <= 64 && v.iter().all(|x| x.is_finite() && *x >= 0.0);- match &kind {- StrokeType::Dashed { pattern } if !StrokeType::valid_dash_pattern(pattern) => {- return Err(bad(cmd, "a dash pattern needs 1 to 64 lengths, each 0 or 0.1 to 10000 pt, not all 0"));- }- StrokeType::Stripes { bands } if bands.len() > 64 || !bands.iter().all(|(a, b)| finite(&[*a, *b])) => {- return Err(bad(cmd, "stripes need up to 64 bands of non-negative numbers"));- }- StrokeType::Style { name } if !doc.stroke_styles.iter().any(|s| s.name == *name) => {- return Err(bad(cmd, format!("no stroke style `{name}`")));- }- _ => {}- }- attrs.kind = Some(kind);- }- Some(other) => return Err(bad(cmd, format!("unknown stroke type {other}"))),- }- Ok(StrokeEdit { attrs, scaled_dashes })- }-- fn apply(&self, mut base: CellStroke) -> CellStroke {- self.attrs.apply_to(&mut base);- if self.scaled_dashes {- let w = base.weight.max(1.0);- base.kind = StrokeType::Dashed { pattern: vec![w * 3.0, w * 2.0] };- }- base- }- }-- /// The stroke drawn on side `side` of the owner cell at `(r, c)` (where that side meets its- /// first neighbour), as rendering resolves it; the cell's own copy if the side has no stretch.- fn drawn_side(t: &Table, owners: &[(usize, usize)], (r, c): (usize, usize), side: usize) -> Option<CellStroke> {- let drawn = compose::table::cell_side_strokes(t, owners, (r, c), side).first().map(|s| s.stroke.clone());- drawn.or_else(|| t.cell(r, c).and_then(|cell| cell.strokes.get(side).cloned()))- }-- /// Cell Options › Text › First Baseline: `firstBaseline` (offset method) and `firstBaselineMin` (pt).- fn first_baseline_params(p: &Value, id: &str) -> Result<(Option<designcraft_doc::FirstBaseline>, Option<f64>)> {- let fb = match p.get("firstBaseline").filter(|v| !v.is_null()) {- Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(id, format!("firstBaseline: {e}")))?),- None => None,- };- let min = match p.get("firstBaselineMin").filter(|v| !v.is_null()) {- Some(v) => match v.as_f64().filter(|m| m.is_finite() && (0.0..=8640.0).contains(m)) {- Some(m) => Some(m),- None => return Err(bad(id, "firstBaselineMin: a number of points from 0 to 8640")),- },- None => None,- };- Ok((fb, min))- }-- fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {- const ID: &str = "table.setCell";- let g = target(s, p, ID)?;- let doc = &s.doc()?.doc;- let fill = swatch_in(doc, p, &["fill"], ID)?;- let tint = num_in(p, "tint", 0.0, 1.0, ID)?.map(|t| t as f32);- let insets: Option<[f64; 4]> = match p.get("insets") {- Some(Value::Number(n)) => n.as_f64().map(|v| [v.max(0.0); 4]),- Some(Value::Array(a)) if a.len() == 4 => {- let v: Vec<f64> = a.iter().map(|x| x.as_f64().unwrap_or(0.0).max(0.0)).collect();- Some([v[0], v[1], v[2], v[3]])- }- _ => None,- };- let vj = match str_param(p, "vj").or_else(|| str_param(p, "verticalJustification")) {- Some("top") => Some(VerticalJustification::Top),- Some("center") => Some(VerticalJustification::Center),- Some("bottom") => Some(VerticalJustification::Bottom),- Some("justify") => Some(VerticalJustification::Justify),- Some(o) => return Err(bad(ID, format!("unknown vj `{o}`"))),- None => None,- };- let (first_baseline, first_baseline_min) = first_baseline_params(p, ID)?;- // Cell Options › Text › Rotation. The value is kept and written back to IDML; only 0 is- // composed so far, which the IDML import reports (#1468).- let rotation = match p.get("rotation").filter(|v| !v.is_null()) {- Some(v) => match v.as_f64().map(|d| d.rem_euclid(360.0)) {- Some(d) if d == 0.0 || d == 90.0 || d == 180.0 || d == 270.0 => Some(d),- _ => return Err(bad(ID, "rotation: 0, 90, 180 or 270 degrees")),- },- None => None,- };- let text = str_param(p, "text").map(|_| super::text_param(p, "text"));- let stroke = match p.get("stroke").filter(|v| !v.is_null()) {- Some(sv) => Some((StrokeEdit::parse(doc, sv, ID)?, EdgeSel::parse(sv.get("edges"), ID)?)),- None => None,- };- edit_table(s, &g, ID, |t| {- let owners = t.owners();- let nc = t.ncols();- let nr = t.nrows();- let rtl = t.options.direction == designcraft_doc::TextDirection::RightToLeft;- // Local edits outrank previously imported edges, including explicit zero/None.- let priority = if stroke.is_some() { next_cell_stroke_priority(t) } else { 0 };- let rg = g.range;- // Edges are inner or outer within the selection grown to whole merged cells, so a- // merged cell selected through one of its grid positions keeps its own outline.- let outline = t.expand_range(rg);- // Each chosen edge starts from the stroke drawn there, which both copies of a shared- // edge then take, so the edit changes only the attributes it names.- let mut bases = std::collections::HashMap::new();- if let Some((_, edges)) = &stroke {- for (r, c) in t.selected_owners(rg) {- let Some(cell) = t.cell(r, c) else { continue };- for (i, on) in edges.sides(outline, (r, c), (cell.row_span, cell.col_span), rtl).into_iter().enumerate() {- if let Some(base) = drawn_side(t, &owners, (r, c), i).filter(|_| on) {- bases.insert((r, c, i), base);- }- }- }- }- let mut edited = std::collections::HashSet::new();- for (r, c) in t.selected_owners(rg) {- let Some(cell) = t.cell_mut(r, c) else { continue };- if let Some(f) = &fill {- cell.fill = f.clone();- }- if let Some(ti) = tint {- cell.fill_tint = ti;- }- if let Some(i) = insets {- cell.insets = i;- }- if let Some(v) = vj {- cell.vj = v;- }- if let Some(v) = first_baseline {- cell.first_baseline = v;- }- if let Some(v) = first_baseline_min {- cell.first_baseline_min = v;- }- if let Some(v) = rotation {- cell.rotation = v;- }- if let Some(tx) = &text {- let len = cell.text.len();- cell.text.replace(0..len, tx);- }- if let Some((edit, _)) = &stroke {- for i in 0..4 {- if let Some(base) = bases.remove(&(r, c, i)) {- edited.insert((r, c, i));- cell.strokes[i] = edit.apply(base);- cell.stroke_defined[i] = true;- cell.stroke_priorities[i] = priority;- cell.border_overrides[i] = true;- }- }- }- }- // Keep both copies of unmerged shared boundaries consistent: each edited edge is- // copied to its neighbour. Left/right name physical sides, also in RTL tables.- let mirror = |t: &mut Table, from: (usize, usize), edge: usize, to: (usize, usize), opposite: usize| {- if edited.contains(&(from.0, from.1, edge)) {- mirror_cell_edge(t, &owners, from, edge, to, opposite);- }- };- if let Some((_, edges)) = &stroke {- if edges.top- && let Some(row) = rg.r0.checked_sub(1)- {- for c in rg.c0..=rg.c1 {- mirror(t, (rg.r0, c), 0, (row, c), 2);- }- }- if edges.bottom && rg.r1.saturating_add(1) < nr {- for c in rg.c0..=rg.c1 {- mirror(t, (rg.r1, c), 2, (rg.r1 + 1, c), 0);- }- }- if (if rtl { edges.right } else { edges.left })- && let Some(col) = rg.c0.checked_sub(1)- {- for r in rg.r0..=rg.r1 {- mirror(t, (r, rg.c0), if rtl { 3 } else { 1 }, (r, col), if rtl { 1 } else { 3 });- }- }- if (if rtl { edges.left } else { edges.right }) && rg.c1.saturating_add(1) < nc {- for r in rg.r0..=rg.r1 {- mirror(t, (r, rg.c1), if rtl { 1 } else { 3 }, (r, rg.c1 + 1), if rtl { 3 } else { 1 });- }- }- }- ok()- })- }-- /// The shown stroke attributes of the chosen edges of the target cells, and their fill; values- /// that differ are null.- fn get_cell_stroke(s: &mut Session, p: &Value) -> Result<Value> {- const ID: &str = "table.getCellStroke";- let g = target(s, p, ID)?;- let edges = EdgeSel::parse(p.get("edges"), ID)?;- let st = s.doc()?;- let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;- let owners = t.owners();- let outline = t.expand_range(g.range);- let rtl = t.options.direction == designcraft_doc::TextDirection::RightToLeft;- // One value per key, or null once two edges (cells) disagree.- fn merge(slot: &mut Option<Value>, v: Value) {- match slot {- None => *slot = Some(v),- Some(cur) if *cur != v => *cur = Value::Null,- _ => {}- }- }- let keys = ["weight", "color", "tint", "type", "gapColor", "gapTint"];- let mut stroke: [Option<Value>; 6] = Default::default();- let (mut fill, mut fill_tint) = (None, None);- // Each drawn edge once: a shared edge is a side of both its cells.- let mut seen = std::collections::HashSet::new();- for (r, c) in t.selected_owners(g.range) {- let Some(cell) = t.cell(r, c) else { continue };- merge(&mut fill, json!(cell.fill));- merge(&mut fill_tint, json!(cell.fill_tint));- for (i, on) in edges.sides(outline, (r, c), (cell.row_span, cell.col_span), rtl).into_iter().enumerate() {- if !on {- continue;- }- for side in compose::table::cell_side_strokes(t, &owners, (r, c), i) {- let (x, y) = (Some((r, c)), side.neighbor);- if !seen.insert((i % 2, side.boundary, x.min(y), x.max(y))) {- continue;- }- let e = side.stroke;- let values = [json!(e.weight), json!(e.color), json!(e.tint), json!(e.kind), json!(e.gap_color), json!(e.gap_tint)];- for (slot, v) in stroke.iter_mut().zip(values) {- merge(slot, v);- }- }- }- }- let mut out = serde_json::Map::new();- for (k, v) in keys.iter().zip(stroke) {- out.insert((*k).into(), v.unwrap_or(Value::Null));- }- out.insert("fill".into(), fill.unwrap_or(Value::Null));- out.insert("fillTint".into(), fill_tint.unwrap_or(Value::Null));- out.insert("edges".into(), json!(seen.len()));- Ok(Value::Object(out))- }-- /// Only saturation needs rebasing. Preserve every distinct priority's order and keep- /// zero/negative priorities untouched; the work is bounded by the table's edges.- fn next_cell_stroke_priority(t: &mut Table) -> i32 {- let highest = t.cells.iter().flat_map(|cell| cell.stroke_priorities).max().unwrap_or(0).max(0);- if highest < i32::MAX {- return highest + 1;- }- let values: std::collections::BTreeSet<_> = t.cells.iter().flat_map(|cell| cell.stroke_priorities).filter(|p| *p > 0).collect();- let mut ranks = std::collections::BTreeMap::new();- let mut highest = 0i32;- for value in values {- highest = highest.saturating_add(1);- ranks.insert(value, highest);- }- for cell in &mut t.cells {- for priority in &mut cell.stroke_priorities {- if let Some(rank) = ranks.get(priority) {- *priority = *rank;- }- }- }- highest.saturating_add(1)- }-- fn mirror_cell_edge(t: &mut Table, owners: &[(usize, usize)], from: (usize, usize), edge: usize, to: (usize, usize), opposite: usize) {- let owner = |pos: (usize, usize)| owners.get(pos.0.checked_mul(t.ncols())?.checked_add(pos.1)?).copied();- if owner(from) != Some(from) || owner(to) != Some(to) {- return;- }- // A merged cell's edge may border several separately editable cells. Mirroring- // a segment onto that whole edge would change unselected neighbors; priorities- // instead resolve each segment without altering the merged cell's formatting.- let merged = |cell: &designcraft_doc::Cell| cell.row_span > 1 || cell.col_span > 1;- if t.cell(from.0, from.1).is_some_and(merged) || t.cell(to.0, to.1).is_some_and(merged) {- return;- }- let source = t- .cell(from.0, from.1)- .map(|cell| (cell.strokes[edge].clone(), cell.stroke_defined[edge], cell.stroke_priorities[edge], cell.border_overrides[edge]));- if let (Some((stroke, defined, priority, border_override)), Some(neighbor)) = (source, t.cell_mut(to.0, to.1)) {- neighbor.strokes[opposite] = stroke;- neighbor.stroke_defined[opposite] = defined;- neighbor.stroke_priorities[opposite] = priority;- neighbor.border_overrides[opposite] = border_override;- }- }-- fn set_row_height(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.setRowHeight")?;- let h = p.get("height").and_then(Value::as_f64).map(|h| h.clamp(0.0, 10000.0));- let mode = match str_param(p, "mode") {- Some("exactly") => Some(RowHeightMode::Exactly),- Some("atLeast") => Some(RowHeightMode::AtLeast),- Some(o) => return Err(bad("table.setRowHeight", format!("unknown mode `{o}`"))),- None => None,- };- if h.is_none() && mode.is_none() {- return Err(bad("table.setRowHeight", "missing height"));- }- edit_table(s, &g, "table.setRowHeight", |t| {- for row in &mut t.rows[g.range.r0..=g.range.r1] {- if let Some(h) = h {- row.height = h;- }- if let Some(m) = mode {- row.mode = m;- }- }- ok()- })- }-- fn set_col_width(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.setColumnWidth")?;- let w = p.get("width").and_then(Value::as_f64).ok_or_else(|| bad("table.setColumnWidth", "missing width"))?.clamp(3.0, 10000.0);- edit_table(s, &g, "table.setColumnWidth", |t| {- for c in &mut t.columns[g.range.c0..=g.range.c1] {- c.width = w;- }- ok()- })- }-- /// Smallest column width and row height a border drag leaves.- const MIN_TRACK: f64 = 3.0;- const MAX_TRACK: f64 = 10000.0;-- /// Composed height of `row` (laid out from cells that span only that row), else its model height.- fn composed_row_height(cs: &compose::ComposedStory, t: &Table, row: usize) -> Option<f64> {- let laid_out = cs- .frames- .iter()- .flat_map(|f| &f.tables)- .filter(|f| f.table == t.id)- .flat_map(|f| &f.cells)- .filter(|c| c.row == row && t.cell(c.row, c.col).is_some_and(|x| x.row_span <= 1))- .map(|c| c.rect.height())- .filter(|h| h.is_finite() && *h > 0.0)- .reduce(f64::max);- laid_out.or_else(|| t.rows.get(row).map(|r| r.height))- }-- /// Move the border after `index` among `sizes` by `delta`. Returns the new sizes.- fn resize_track(sizes: &[f64], index: usize, delta: f64, keep: bool) -> Option<Vec<f64>> {- let mut out = sizes.to_vec();- let cur = *sizes.get(index)?;- let last = index + 1 == sizes.len();- if keep && last {- // Scale every track so the table edge moves by `delta`.- let total: f64 = sizes.iter().sum();- let smallest = sizes.iter().copied().fold(f64::INFINITY, f64::min);- let largest = sizes.iter().copied().fold(0.0, f64::max);- if !(total > 0.0 && smallest > 0.0 && largest > 0.0) {- return None;- }- let lo = (MIN_TRACK / smallest).min(1.0);- let hi = (MAX_TRACK / largest).max(1.0);- let f = ((total + delta) / total).clamp(lo, hi);- out.iter_mut().for_each(|v| *v *= f);- } else if keep {- let next = *sizes.get(index + 1)?;- let pair = cur + next;- let a = (cur + delta).clamp(MIN_TRACK, (pair - MIN_TRACK).max(MIN_TRACK));- let [this, after] = out.get_mut(index..index + 2)? else { return None };- *this = a;- *after = (pair - a).max(MIN_TRACK);- } else {- *out.get_mut(index)? = (cur + delta).clamp(MIN_TRACK, MAX_TRACK);- }- out.iter().all(|v| v.is_finite()).then_some(out)- }-- /// The frame a border drag names must hold the table's story and be editable.- fn check_border_frame(st: &crate::DocState, p: &Value, story: designcraft_doc::StoryId) -> Result<()> {- const ID: &str = "table.resizeBorder";- if let Some(fid) = super::id_param(p, "frame") {- let it = st.doc.item(fid).ok_or_else(|| bad(ID, format!("no frame {}", fid.0)))?;- if it.text_frame().map(|f| f.story) != Some(story) {- return Err(bad(ID, "the table is not in that frame's story"));- }- if it.locked || st.doc.layer(it.layer).is_some_and(|l| l.locked) {- return Err(bad(ID, "the frame or its layer is locked"));- }- }- Ok(())- }-- /// The change in track size: `delta`, or `size` measured from the current size `cur`.- fn border_delta(p: &Value, cur: f64) -> Result<f64> {- const ID: &str = "table.resizeBorder";- let delta = match (p.get("delta").and_then(Value::as_f64), p.get("size").and_then(Value::as_f64)) {- (Some(d), _) => d,- (None, Some(sz)) => sz - cur,- (None, None) => return Err(bad(ID, "`delta` or `size` required")),- };- if !delta.is_finite() {- return Err(bad(ID, "`delta`/`size` must be a finite number"));- }- Ok(delta)- }-- fn resize_border(s: &mut Session, p: &Value) -> Result<Value> {- const ID: &str = "table.resizeBorder";- let column = match str_param(p, "axis") {- Some("column") => true,- Some("row") => false,- _ => return Err(bad(ID, "axis must be `column` or `row`")),- };- let index = p.get("index").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad(ID, "`index` required"))?;- let keep = p.get("keepTableSize").and_then(Value::as_bool).unwrap_or(false);- let g = target(s, p, ID)?;- let st = s.doc()?;- check_border_frame(st, p, g.story)?;- let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;- let sizes: Vec<f64> = if column {- t.columns.iter().map(|c| c.width).collect()- } else {- let cs = s.cache.get(&st.doc, g.story, None);- (0..t.nrows()).map(|r| composed_row_height(&cs, t, r).unwrap_or(MIN_TRACK)).collect()- };- let cur = *sizes.get(index).ok_or_else(|| bad(ID, format!("index {index} out of range")))?;- let delta = border_delta(p, cur)?;- let new = resize_track(&sizes, index, delta, keep).ok_or_else(|| bad(ID, "invalid table geometry"))?;- let size = new.get(index).copied().unwrap_or(cur);- let scaled = keep && index + 1 == sizes.len();- edit_table(s, &g, ID, |t| {- if column {- for (c, w) in t.columns.iter_mut().zip(&new) {- c.width = *w;- }- } else {- for (i, (r, h)) in t.rows.iter_mut().zip(&new).enumerate() {- // Only the rows the drag changed take the new height.- if scaled || i == index || (keep && i == index + 1) {- r.height = *h;- }- if i == index && !scaled {- r.mode = RowHeightMode::AtLeast;- }- }- }- Ok(json!({"axis": if column { "column" } else { "row" }, "index": index, "size": size}))- })- }-- fn distribute_rows(s: &mut Session, p: &Value) -> Result<Value> {- const ID: &str = "table.distributeRows";- if !p.is_object() {- return Err(bad(ID, "parameters must be an object"));- }- if let Some(rows) = p.get("rows") {- let valid = rows.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|v| v.as_u64().is_some_and(|n| usize::try_from(n).is_ok())));- if !valid {- return Err(bad(ID, "rows must be two non-negative row indices"));- }- }- for key in ["row", "story", "table"] {- if let Some(v) = p.get(key)- && v.as_u64().is_none_or(|n| usize::try_from(n).is_err())- {- return Err(bad(ID, format!("{key} must be a non-negative integer")));- }- }- let g = target(s, p, ID)?;- let st = s.doc()?;- let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;- if t.cells.iter().any(|c| c.row_span > 1) {- return Err(bad(ID, "unmerge cells that span rows first"));- }- let cs = s.cache.get(&st.doc, g.story, None);- let mut total = 0.0;- for row in g.range.r0..=g.range.r1 {- let height = cs- .frames- .iter()- .flat_map(|f| &f.tables)- .filter(|f| f.table == g.table)- .flat_map(|f| &f.cells)- .filter(|c| c.row == row)- .map(|c| c.rect.height())- .reduce(f64::max)- .ok_or_else(|| bad(ID, "all selected rows must be laid out; enlarge or thread the text frame first"))?;- if !height.is_finite() || height <= 0.0 {- return Err(bad(ID, "invalid composed row height"));- }- total += height;- }- let count = g.range.r1 - g.range.r0 + 1;- let height = total / count as f64;- if !height.is_finite() {- return Err(bad(ID, "invalid total row height"));- }- edit_table(s, &g, ID, |t| {- let rows = t.rows.get_mut(g.range.r0..=g.range.r1).ok_or_else(|| bad(ID, "invalid row range"))?;- for row in rows {- row.height = height;- row.mode = RowHeightMode::Exactly;- }- Ok(json!({"rows": count, "height": height}))- })- }-- fn distribute_cols(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.distributeColumns")?;- edit_table(s, &g, "table.distributeColumns", |t| {- let cols = &mut t.columns[g.range.c0..=g.range.c1];- let avg = cols.iter().map(|c| c.width).sum::<f64>() / cols.len() as f64;- cols.iter_mut().for_each(|c| c.width = avg);- ok()- })- }-- fn parse_alt(v: &Value) -> Option<AltFills> {- if v.is_null() {- return None;- }- let d = AltFills::default();- Some(AltFills {- first: v.get("first").and_then(Value::as_u64).map_or(d.first, |x| u32::try_from(x).unwrap_or(u32::MAX)),- first_color: color_param(v, "firstColor").unwrap_or(d.first_color),- first_tint: v.get("firstTint").and_then(Value::as_f64).map_or(d.first_tint, |x| x as f32),- next: v.get("next").and_then(Value::as_u64).map_or(d.next, |x| u32::try_from(x).unwrap_or(u32::MAX)),- next_color: color_param(v, "nextColor").unwrap_or(d.next_color),- next_tint: v.get("nextTint").and_then(Value::as_f64).map_or(d.next_tint, |x| x as f32),- skip_first: v.get("skipFirst").and_then(Value::as_u64).map_or(0, |x| u32::try_from(x).unwrap_or(u32::MAX)),- skip_last: v.get("skipLast").and_then(Value::as_u64).map_or(0, |x| u32::try_from(x).unwrap_or(u32::MAX)),- })- }-- fn options(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.options")?;- let border = match p.get("border").filter(|v| !v.is_null()) {- Some(b) => Some(StrokeEdit::parse(&s.doc()?.doc, b, "table.options")?),- None => None,- };- let p = p.clone();- edit_table(s, &g, "table.options", |t| {- let o = &mut t.options;- if let Some(v) = p.get("direction") {- o.direction = serde_json::from_value(v.clone()).map_err(|e| bad("table.options", e.to_string()))?;- }- if let Some(b) = &border {- o.border = b.apply(o.border.clone());- o.borders = Default::default();- }- o.space_before = f64_or(&p, "spaceBefore", o.space_before);- o.space_after = f64_or(&p, "spaceAfter", o.space_after);- if let Some(b) = p.get("repeatHeader").and_then(Value::as_bool) {- o.repeat_header = b;- }- if let Some(b) = p.get("repeatFooter").and_then(Value::as_bool) {- o.repeat_footer = b;- }- if let Some(v) = p.get("altRows") {- o.alt_rows = parse_alt(v);- }- if let Some(v) = p.get("altCols") {- o.alt_cols = parse_alt(v);- }- // At most 100 of each, as in `table.insert`: the rows the table lacks are added below.- let h = p.get("headerRows").and_then(Value::as_u64).map(|v| v.min(100) as usize);- let f = p.get("footerRows").and_then(Value::as_u64).map(|v| v.min(100) as usize);- if h.is_some() || f.is_some() {- let (h, f) = (h.unwrap_or(t.header_rows()), f.unwrap_or(t.footer_rows()));- // Add rows when there aren't enough for the requested header/footer plus one body row.- let need = h + f + 1;- if t.nrows() < need {- let at = t.nrows();- t.insert_rows(at, need - at);- }- t.set_header_footer(h, f);- }- Ok(json!({"options": t.options}))- })- }-- /// Convert Rows is greyed out unless the selected cells (or the caret's cell) can change kind.- fn can_convert_rows(s: &Session, kind: RowKind) -> std::result::Result<(), String> {- let st = s.active().ok_or("no document open")?;- if st.selection.cells.is_none() {- in_cell(s)?;- }- let g = target(s, &Value::Null, "table.convertRows").map_err(|e| e.to_string())?;- let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or("no table")?;- t.convert_rows_counts(g.range.r0, g.range.r1, kind).map(|_| ())- }-- fn convert_rows(s: &mut Session, p: &Value, kind: RowKind) -> Result<Value> {- const ID: &str = "table.convertRows";- let g = target(s, p, ID)?;- edit_table(s, &g, ID, |t| {- let (h, f) = t.convert_rows_counts(g.range.r0, g.range.r1, kind).map_err(|e| bad(ID, e))?;- t.set_header_footer(h, f);- Ok(json!({"headerRows": h, "footerRows": f}))- })- }-- // ---------- selection ------------ fn select(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.select")?;- let (nr, nc) = {- let st = s.doc()?;- let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad("table.select", "no table"))?;- (t.nrows(), t.ncols())- };- let mut r = g.range;- match str_param(p, "what") {- Some("table") => r = CellRange { r0: 0, c0: 0, r1: nr - 1, c1: nc - 1 },- Some("row") => {- r.c0 = 0;- r.c1 = nc - 1;- }- Some("column") => {- r.r0 = 0;- r.r1 = nr - 1;- }- _ => {}- }- let st = s.doc_mut()?;- let frame = st.selection.text.and_then(|t| t.frame);- st.selection = Selection {- cells: Some(TableSel { story: g.story, table: g.table, range: r }),- text: Some(TextSel { story: g.story, anchor: 0, focus: 0, frame, cell: Some(CellAddr { table: g.table, row: r.r0, col: r.c0 }) }),- ..Default::default()- };- st.bump_revision();- Ok(json!({"story": g.story.0, "table": g.table, "range": r}))- }-- /// Move the caret to the next/previous cell (Tab / Shift-Tab), selecting its text. Tab in the last- /// cell adds a row.- pub(crate) fn step_cell(s: &mut Session, forward: bool) -> Result<Value> {- let t = s.doc()?.selection.text.ok_or_else(|| bad("table.nextCell", "no caret"))?;- let c = t.cell.ok_or_else(|| bad("table.nextCell", "not in a cell"))?;- let (owners, nr, nc) = {- let st = s.doc()?;- let tb = st.doc.story(t.story).and_then(|x| x.tables.get(&c.table)).ok_or_else(|| bad("table.nextCell", "no table"))?;- (tb.owners(), tb.nrows(), tb.ncols())- };- let cur = c.row * nc + c.col;- let next =- if forward { (cur + 1..nr * nc).find(|&i| owners[i] == (i / nc, i % nc)) } else { (0..cur).rev().find(|&i| owners[i] == (i / nc, i % nc)) };- let (row, col) = match next {- Some(i) => (i / nc, i % nc),- None if forward => {- let g = Tgt { story: t.story, table: c.table, range: CellRange::cell(nr - 1, 0) };- edit_table(s, &g, "table.nextCell", |tb| {- tb.insert_rows(nr, 1);- ok()- })?;- (nr, 0)- }- None => return ok(),- };- let st = s.doc_mut()?;- let len = st.doc.text_story(t.story, Some(CellAddr { table: c.table, row, col })).map_or(0, |x| x.len());- st.selection = Selection::text(TextSel { anchor: 0, focus: len, cell: Some(CellAddr { table: c.table, row, col }), ..t });- st.bump_revision();- Ok(json!({"row": row, "col": col}))- }-- fn get(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.get")?;- let st = s.doc()?;- let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad("table.get", "no table"))?;- let owners = t.owners();- let cells: Vec<Value> = (0..t.nrows())- .flat_map(|r| (0..t.ncols()).map(move |c| (r, c)))- .filter(|&(r, c)| owners[r * t.ncols() + c] == (r, c))- .filter_map(|(r, c)| {- let cell = t.cell(r, c)?;- Some(json!({"row": r, "col": c, "rowSpan": cell.row_span, "colSpan": cell.col_span, "text": cell.text.text, "fill": cell.fill,- "insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style}))- })- .collect();- Ok(json!({- "story": g.story.0, "table": g.table, "anchor": st.doc.story(g.story).and_then(|x| x.table_anchor(g.table)),- "rows": t.rows, "columns": t.columns, "headerRows": t.header_rows(), "footerRows": t.footer_rows(),- "cells": cells, "options": t.options, "range": g.range, "style": t.style,- }))- }-- // ---------- cell and table styles ------------ /// A style's uniform edge stroke from `stroke`/`border`: the given values over the default- /// edge, validated like `table.setCell`'s stroke.- fn stroke_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<Option<CellStroke>> {- match v.filter(|v| !v.is_null()) {- Some(v) => Ok(Some(StrokeEdit::parse(&s.doc()?.doc, v, cmd)?.apply(CellStroke::default()))),- None => Ok(None),- }- }-- /// Fill in the cell style fields given in `p`.- fn cell_style_fields(cs: &mut designcraft_doc::CellStyle, p: &Value, stroke: Option<CellStroke>, cmd: &str) -> Result<()> {- if let Some(v) = p.get("basedOn") {- cs.based_on = v.as_str().map(str::to_string);- }- if let Some(f) = color_param(p, "fill") {- cs.fill = Some(f);- }- if let Some(t) = p.get("tint").and_then(Value::as_f64) {- cs.fill_tint = Some(t.clamp(0.0, 1.0) as f32);- }- match p.get("insets") {- Some(Value::Number(n)) => {- cs.insets = n.as_f64().map(|v| [v.max(0.0); 4]);- cs.inset_overrides = Default::default();- }- Some(Value::Array(a)) if a.len() == 4 => {- let v: Vec<f64> = a.iter().map(|x| x.as_f64().unwrap_or(0.0).max(0.0)).collect();- cs.insets = Some([v[0], v[1], v[2], v[3]]);- cs.inset_overrides = Default::default();- }- _ => {}- }- if let Some(v) = p.get("vj") {- cs.vj = Some(serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("vj: {e}")))?);- }- let (first_baseline, first_baseline_min) = first_baseline_params(p, cmd)?;- if first_baseline.is_some() {- cs.first_baseline = first_baseline;- }- if first_baseline_min.is_some() {- cs.first_baseline_min = first_baseline_min;- }- if let Some(st) = stroke {- cs.stroke = Some(st);- cs.strokes = Default::default();- }- if let Some(ps) = str_param(p, "paragraphStyle") {- cs.paragraph_style = Some(ps.to_string());- }- Ok(())- }-- fn cell_style_create(s: &mut Session, p: &Value) -> Result<Value> {- let base = str_param(p, "name").unwrap_or("Cell Style 1").to_string();- let mut cs = designcraft_doc::CellStyle::default();- if p.get("fromSelection").and_then(Value::as_bool).unwrap_or(false) {- let g = target(s, p, "style.cell.create")?;- let d = &s.doc()?.doc;- let cell = d- .story(g.story)- .and_then(|st| st.tables.get(&g.table))- .and_then(|t| {- let (r, c) = t.owner(g.range.r0, g.range.c0);- t.cell(r, c)- })- .ok_or_else(|| bad("style.cell.create", "no cell"))?;- cs.fill = Some(cell.fill.clone());- cs.fill_tint = Some(cell.fill_tint);- cs.insets = Some(cell.insets);- cs.vj = Some(cell.vj);- cs.first_baseline = Some(cell.first_baseline);- cs.first_baseline_min = Some(cell.first_baseline_min);- cs.stroke = Some(cell.strokes[0].clone());- cs.paragraph_style = cell.text.paras.first().map(|p| p.style.clone());- }- let stroke = stroke_param(s, p.get("stroke"), "style.cell.create")?;- cell_style_fields(&mut cs, p, stroke, "style.cell.create")?;- s.edit(|d, _| {- let name = designcraft_doc::Styles::unique_name(|n| d.styles.cell.iter().any(|c| c.name == n), &base);- cs.name = name.clone();- d.styles_mut().cell.push(cs);- Ok(json!({"name": name}))- })- }-- fn cell_style_apply(s: &mut Session, p: &Value) -> Result<Value> {- let name = str_param(p, "name").ok_or_else(|| bad("style.cell.apply", "missing name"))?.to_string();- let styles = &s.doc()?.doc.styles.cell;- if !styles.iter().any(|c| c.name == name) {- return Err(bad("style.cell.apply", format!("no cell style `{name}`")));- }- let cs = designcraft_doc::resolve_cell_style(styles, &name);- let g = target(s, p, "style.cell.apply")?;- edit_table(s, &g, "style.cell.apply", |t| {- let mut n = 0;- for (r, c) in t.selected_owners(g.range) {- if let Some(cell) = t.cell_mut(r, c) {- cs.apply_to(cell);- n += 1;- }- }- Ok(json!({"cells": n}))- })- }-- /// Re-apply cell styles named in `names` to every cell using them (after a style edit).- fn reapply_cell_styles(d: &mut Document, names: &[String]) {- let styles: Vec<_> = names.iter().map(|name| designcraft_doc::resolve_cell_style(&d.styles.cell, name)).collect();- for sid in d.stories.keys().copied().collect::<Vec<_>>() {- let Some(st) = d.story_mut(sid) else { continue };- for t in st.tables.values_mut() {- if !t.cells.iter().any(|c| names.contains(&c.style)) {- continue;- }- for cell in &mut std::sync::Arc::make_mut(t).cells {- if names.contains(&cell.style)- && let Some(cs) = styles.iter().find(|x| x.name == cell.style)- {- cs.apply_to(cell);- }- }- }- st.rev = st.rev.wrapping_add(1);- }- }-- /// Include descendants when editing an inherited style, with the resolver's depth limit.- fn dependent_styles<'a>(name: &str, styles: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> Vec<String> {- let styles: Vec<_> = styles.collect();- styles- .iter()- .filter(|(candidate, _)| {- let mut current = Some(*candidate);- for _ in 0..32 {- let Some(current_name) = current else { return false };- if current_name == name {- return true;- }- current = styles.iter().find(|(n, _)| *n == current_name).and_then(|(_, base)| *base);- }- false- })- .map(|(name, _)| (*name).to_string())- .collect()- }-- fn cell_style_edit(s: &mut Session, p: &Value) -> Result<Value> {- let name = str_param(p, "name").ok_or_else(|| bad("style.cell.edit", "missing name"))?.to_string();- let stroke = stroke_param(s, p.get("stroke"), "style.cell.edit")?;- let p = p.clone();- s.edit(|d, _| {- let cs = d.styles_mut().cell.iter_mut().find(|c| c.name == name).ok_or_else(|| bad("style.cell.edit", format!("no cell style `{name}`")))?;- cell_style_fields(cs, &p, stroke, "style.cell.edit")?;- let names = dependent_styles(&name, d.styles.cell.iter().map(|cs| (cs.name.as_str(), cs.based_on.as_deref())));- reapply_cell_styles(d, &names);- ok()- })- }-- fn table_style_fields(ts: &mut designcraft_doc::TableStyle, p: &Value, border: Option<CellStroke>) {- if let Some(v) = p.get("basedOn") {- ts.based_on = v.as_str().map(str::to_string);- }- for (k, f) in [- ("header", &mut ts.header),- ("body", &mut ts.body),- ("footer", &mut ts.footer),- ("leftColumn", &mut ts.left_column),- ("rightColumn", &mut ts.right_column),- ] {- if let Some(v) = p.get(k) {- *f = v.as_str().map(str::to_string);- }- }- if let Some(b) = border {- ts.border = Some(b);- ts.borders = Default::default();- }- if let Some(a) = p.get("altRows").and_then(Value::as_object) {- let n = |k: &str, d: u32| a.get(k).and_then(Value::as_u64).map_or(d, |v| u32::try_from(v).unwrap_or(u32::MAX));- let c = |k: &str| a.get(k).and_then(Value::as_str).unwrap_or(designcraft_color::swatch::NONE).to_string();- let t = |k: &str| a.get(k).and_then(Value::as_f64).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32);- ts.alt_rows = Some(designcraft_doc::AltFills {- first: n("first", 1),- first_color: c("firstColor"),- first_tint: t("firstTint"),- next: n("next", 1),- next_color: c("nextColor"),- next_tint: t("nextTint"),- skip_first: n("skipFirst", 0),- skip_last: n("skipLast", 0),- });- }- if let Some(v) = p.get("spaceBefore").and_then(Value::as_f64) {- ts.space_before = Some(v);- }- if let Some(v) = p.get("spaceAfter").and_then(Value::as_f64) {- ts.space_after = Some(v);- }- }-- fn table_style_create(s: &mut Session, p: &Value) -> Result<Value> {- let base = str_param(p, "name").unwrap_or("Table Style 1").to_string();- let mut ts = designcraft_doc::TableStyle::default();- let border = stroke_param(s, p.get("border"), "style.table.create")?;- table_style_fields(&mut ts, p, border);- s.edit(|d, _| {- let name = designcraft_doc::Styles::unique_name(|n| d.styles.table.iter().any(|c| c.name == n), &base);- ts.name = name.clone();- d.styles_mut().table.push(ts);- Ok(json!({"name": name}))- })- }-- fn table_style_apply(s: &mut Session, p: &Value) -> Result<Value> {- let name = str_param(p, "name").ok_or_else(|| bad("style.table.apply", "missing name"))?.to_string();- let doc = &s.doc()?.doc;- if !doc.styles.table.iter().any(|c| c.name == name) {- return Err(bad("style.table.apply", format!("no table style `{name}`")));- }- let ts = doc.styles.resolve_table_style(&name);- let cells = doc.styles.cell.clone();- let g = target(s, p, "style.table.apply")?;- edit_table(s, &g, "style.table.apply", |t| {- ts.apply_to(t, &cells);- ok()- })- }-- fn table_style_edit(s: &mut Session, p: &Value) -> Result<Value> {- let name = str_param(p, "name").ok_or_else(|| bad("style.table.edit", "missing name"))?.to_string();- let border = stroke_param(s, p.get("border"), "style.table.edit")?;- let p = p.clone();- s.edit(|d, _| {- let ts =- d.styles_mut().table.iter_mut().find(|c| c.name == name).ok_or_else(|| bad("style.table.edit", format!("no table style `{name}`")))?;- table_style_fields(ts, &p, border);- let names = dependent_styles(&name, d.styles.table.iter().map(|ts| (ts.name.as_str(), ts.based_on.as_deref())));- let styles: Vec<_> = names.iter().map(|name| d.styles.resolve_table_style(name)).collect();- let cells = d.styles.cell.clone();- for sid in d.stories.keys().copied().collect::<Vec<_>>() {- let Some(st) = d.story_mut(sid) else { continue };- for t in st.tables.values_mut() {- if let Some(ts) = styles.iter().find(|ts| ts.name == t.style) {- ts.apply_to(std::sync::Arc::make_mut(t), &cells);- }- }- st.rev = st.rev.wrapping_add(1);- }- ok()- })- }-- #[cfg(test)]- mod style_tests {- use serde_json::json;-- use crate::Session;-- #[test]- fn cell_first_baseline_is_a_cell_option_and_a_cell_style_attribute() {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();- let sid = r["story"].as_u64().unwrap();- s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();- s.execute("table.setCell", &json!({"row": 0, "col": 0, "firstBaseline": "capHeight", "firstBaselineMin": 3})).unwrap();- let got = s.execute("table.get", &json!({})).unwrap();- let cell = got["cells"].as_array().unwrap().iter().find(|c| c["row"] == 0 && c["col"] == 0).unwrap().clone();- assert_eq!((cell["firstBaseline"].as_str(), cell["firstBaselineMin"].as_f64()), (Some("capHeight"), Some(3.0)));- assert!(s.execute("table.setCell", &json!({"row": 0, "col": 0, "firstBaseline": "middle"})).is_err());- // Cell Options › Text › Rotation: carried and written back, composed horizontally so far,- // which the IDML import reports (#1468).- for (given, want) in [(90, 90.0), (270, 270.0), (0, 0.0), (-90, 270.0), (450, 90.0)] {- s.execute("table.setCell", &json!({"row": 0, "col": 0, "rotation": given})).unwrap_or_else(|e| panic!("{given}: {e}"));- let cell = s.execute("table.get", &json!({})).unwrap()["cells"][0].clone();- assert_eq!(cell["rotation"].as_f64(), Some(want), "{given}");- }- for bad in [45, 1, 100] {- assert!(s.execute("table.setCell", &json!({"row": 0, "col": 0, "rotation": bad})).is_err(), "{bad}");- }- assert!(s.execute("table.setCell", &json!({"row": 0, "col": 0, "firstBaselineMin": -1})).is_err());- s.execute("style.cell.create", &json!({"name": "Leading", "firstBaseline": "leading"})).unwrap();- s.execute("style.cell.apply", &json!({"name": "Leading", "row": 1, "col": 1})).unwrap();- let d = &s.doc().unwrap().doc;- let t = d.story(designcraft_doc::StoryId(sid)).unwrap().tables.values().next().unwrap();- assert_eq!(t.cell(1, 1).unwrap().first_baseline, designcraft_doc::FirstBaseline::Leading);- assert_eq!(t.cell(1, 0).unwrap().first_baseline, designcraft_doc::FirstBaseline::Ascent);- }-- #[test]- fn cell_and_table_styles_apply_and_follow_edits() {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();- let sid = r["story"].as_u64().unwrap();- s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 3, "cols": 2, "headerRows": 1})).unwrap();- s.execute("style.paragraph.create", &json!({"name": "Cell Head"})).unwrap();- s.execute("style.cell.create", &json!({"name": "Head", "fill": "[Black]", "paragraphStyle": "Cell Head", "insets": 6})).unwrap();- s.execute("style.cell.create", &json!({"name": "Body", "fill": "[Paper]"})).unwrap();- s.execute("style.table.create", &json!({"name": "Data", "header": "Head", "body": "Body", "border": {"weight": 2, "color": "[Black]"}}))- .unwrap();- s.execute("style.table.apply", &json!({"name": "Data"})).unwrap();- let t = |s: &Session| -> designcraft_doc::Table {- let d = &s.doc().unwrap().doc;- (**d.story(designcraft_doc::StoryId(sid)).unwrap().tables.values().next().unwrap()).clone()- };- let tb = t(&s);- assert_eq!(tb.style, "Data");- assert_eq!(tb.options.border.weight, 2.0);- let head = tb.cell(0, 0).unwrap();- assert_eq!((head.fill.as_str(), head.style.as_str(), head.insets), ("[Black]", "Head", [6.0; 4]));- assert_eq!(head.text.paras[0].style, "Cell Head");- assert_eq!(tb.cell(1, 1).unwrap().style, "Body");- // Editing the cell style updates its cells.- s.execute("style.cell.edit", &json!({"name": "Head", "fill": "C=100 M=0 Y=0 K=0"})).unwrap();- assert_eq!(t(&s).cell(0, 1).unwrap().fill, "C=100 M=0 Y=0 K=0");- // Editing the table style re-applies it.- s.execute("style.table.edit", &json!({"name": "Data", "border": {"weight": 4}})).unwrap();- assert_eq!(t(&s).options.border.weight, 4.0);- assert!(s.execute("style.cell.apply", &json!({"name": "Nope"})).is_err());- }- }-- /// The table cell under spread point `pt` in text frame `frame`: (story, table, row, col).- fn cell_at(s: &Session, frame: designcraft_doc::ItemId, pt: designcraft_geom::Point) -> Option<(StoryId, u64, usize, usize)> {- let st = s.active()?;- let loc = st.doc.find(frame)?;- let it = st.doc.item_at(&loc)?;- let sid = it.text_frame()?.story;- let inner = (st.doc.parent_xf(&loc) * st.doc.text_xf(it)).inverse() * pt;- let cs = s.cache.get(&st.doc, sid, None);- let fi = cs.frames.iter().position(|f| f.frame == frame)?;- let (table, row, col, _) = designcraft_compose::hit_cell(&cs, fi, inner)?;- Some((sid, table, row, col))- }-- fn drop_cells(s: &mut Session, p: &Value) -> Result<Value> {- const ID: &str = "table.dropCells";- let frame = super::id_param(p, "frame").ok_or_else(|| bad(ID, "`frame` required"))?;- let pt = |k: &str| -> Result<designcraft_geom::Point> {- let a = p.get(k).and_then(Value::as_array).ok_or_else(|| bad(ID, format!("`{k}` required")))?;- Ok(designcraft_geom::Point::new(a.first().and_then(Value::as_f64).unwrap_or(0.0), a.get(1).and_then(Value::as_f64).unwrap_or(0.0)))- };- let (from, to) = (pt("from")?, pt("to")?);- let sel = s.doc()?.selection.cells;- let hit_from = cell_at(s, frame, from);- let hit_to = cell_at(s, frame, to);- if let (Some(ts), Some((sid, tid, fr, fc)), Some((_, tid2, tr, tc))) = (sel, hit_from, hit_to)- && ts.story == sid- && ts.table == tid- && tid2 == tid- && s.doc()?.doc.story(sid).and_then(|st| st.tables.get(&tid)).is_some_and(|t| t.selected_owners(ts.range).binary_search(&(fr, fc)).is_ok())- {- let (nr, nc) = {- let t = s.doc()?.doc.story(sid).and_then(|st| st.tables.get(&tid)).ok_or_else(|| bad(ID, "no table"))?;- (t.nrows(), t.ncols())- };- let r = ts.range;- let rows = r.c0 == 0 && r.c1 + 1 == nc;- let cols = r.r0 == 0 && r.r1 + 1 == nr;- if rows || cols {- let (lo, hi, target) = if rows { (r.r0, r.r1, tr) } else { (r.c0, r.c1, tc) };- if target >= lo && target <= hi {- return Ok(json!({"moved": 0}));- }- let n = hi - lo + 1;- let r2 = s.edit(|d, selm| {- let t = d.story_mut(sid).and_then(|st| st.table_mut(tid)).ok_or_else(|| bad(ID, "no table"))?;- let mv = |t: &mut designcraft_doc::Table, a: usize, b: usize| if rows { t.move_row(a, b) } else { t.move_col(a, b) };- let new_lo = if target > hi {- for _ in 0..n {- mv(t, lo, target).map_err(|e| bad(ID, e))?;- }- target + 1 - n- } else {- for k in 0..n {- mv(t, lo + k, target + k).map_err(|e| bad(ID, e))?;- }- target- };- let range =- if rows { CellRange::new(new_lo, r.c0, new_lo + n - 1, r.c1) } else { CellRange::new(r.r0, new_lo, r.r1, new_lo + n - 1) };- selm.cells = Some(TableSel { range, ..ts });- Ok(json!({"moved": n, "to": new_lo}))- })?;- return Ok(r2);- }- }- // Not a row/column drag: select text from the press to the release.- s.execute("text.placeCaret", &json!({"frame": frame.0, "point": [from.x, from.y]}))?;- s.execute("text.extendTo", &json!({"frame": frame.0, "point": [to.x, to.y]}))- }-- fn place_graphic(s: &mut Session, p: &Value) -> Result<Value> {- const ID: &str = "table.placeGraphic";- let g = target(s, p, ID)?;- let (bytes, name, link) = super::file::read_source(p)?;- let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad(ID, "unsupported or corrupt image"))?;- let (nw, nh) = designcraft_render::natural_size(&bytes, 0).ok_or_else(|| bad(ID, "invalid image dimensions"))?;- let fill = p.get("fit").and_then(Value::as_str) == Some("fill");- // Compute fitting before the edit: a small EPS can overflow in a huge cell.- let t = s.doc()?.doc.story(g.story).and_then(|st| st.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;- let (r, c) = t.owner(g.range.r0, g.range.c0);- let cell = t.cell(r, c).ok_or_else(|| bad(ID, "no cell"))?;- let (rs, cs) = (cell.row_span.max(1) as usize, cell.col_span.max(1) as usize);- let w: f64 = t.columns.get(c..c.saturating_add(cs).min(t.ncols())).ok_or_else(|| bad(ID, "invalid cell span"))?.iter().map(|x| x.width).sum();- let h: f64 = t.rows.get(r..r.saturating_add(rs).min(t.nrows())).ok_or_else(|| bad(ID, "invalid cell span"))?.iter().map(|x| x.height).sum();- let ins = cell.insets;- let (bw, bh) = ((w - ins[1] - ins[3]).max(1.0), (h - ins[0] - ins[2]).max(1.0));- let k = if fill { (bw / nw).max(bh / nh) } else { (bw / nw).min(bh / nh) };- let xf = designcraft_geom::Affine::translate(((bw - nw * k) / 2.0, (bh - nh * k) / 2.0)) * designcraft_geom::Affine::scale(k);- super::file::validate_placement((nw, nh), designcraft_geom::Rect::new(0.0, 0.0, bw, bh), xf, ID)?;- s.edit(|d, sel| {- let fresh = designcraft_doc::AssetId(d.alloc());- let mime = designcraft_render::image_mime(&bytes).to_string();- let aid = d.add_asset(designcraft_doc::Asset {- id: fresh,- name,- mime,- link,- data: std::sync::Arc::new(bytes),- pixels: Some((pw, ph)),- ..Default::default()- });- let st = d.story_mut(g.story).ok_or_else(|| bad(ID, "no story"))?;- let t = st.table_mut(g.table).ok_or_else(|| bad(ID, "no table"))?;- let cell = t.cell_mut(r, c).ok_or_else(|| bad(ID, format!("no cell {r},{c}")))?;- cell.graphic = Some(designcraft_doc::Graphic {- layer_options: None,- asset: aid,- size: (nw, nh),- xf,- clip: None,- auto_fit: if fill { designcraft_doc::Fitting::FillProportionally } else { designcraft_doc::Fitting::FitProportionally },- fit_align: 4,- crop: [0.0; 4],- wrap: Default::default(),- fill: Default::default(),- });- clamp_selection(d, sel);- Ok(json!({"asset": aid.0, "row": r, "col": c}))- })- }-- fn move_rc(s: &mut Session, p: &Value, rows: bool) -> Result<Value> {- const ID: &str = "table.move";- let g = target(s, p, ID)?;- let from = p.get("from").and_then(Value::as_u64).map_or(if rows { g.range.r0 } else { g.range.c0 }, |v| v as usize);- let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(ID, "`to` required"))? as usize;- edit_table(s, &g, ID, |t| {- if rows { t.move_row(from, to) } else { t.move_col(from, to) }.map_err(|e| bad(ID, e))?;- Ok(json!({"from": from, "to": to}))- })- }-- fn sort_rows(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.sortRows")?;- let col = p.get("column").and_then(Value::as_u64).map_or(g.range.c0, |c| c as usize);- let desc = p.get("descending").and_then(Value::as_bool).unwrap_or(false);- edit_table(s, &g, "table.sortRows", |t| {- let (nr, nc) = (t.nrows(), t.ncols());- if col >= nc {- return Err(bad("table.sortRows", format!("no column {col}")));- }- if t.cells.iter().any(|c| c.row_span > 1) {- return Err(bad("table.sortRows", "unmerge cells that span rows first"));- }- let (h, f) = (t.header_rows(), t.footer_rows());- let body: Vec<usize> = (h..nr - f).collect();- let key = |r: usize| t.cell(r, col).map(|c| c.text.text.trim().to_string()).unwrap_or_default();- let mut order = body.clone();- order.sort_by(|a, b| {- let (ka, kb) = (key(*a), key(*b));- let o = match (ka.replace(',', "").parse::<f64>(), kb.replace(',', "").parse::<f64>()) {- (Ok(x), Ok(y)) => x.total_cmp(&y),- _ => ka.to_lowercase().cmp(&kb.to_lowercase()),- };- if desc { o.reverse() } else { o }- });- let rows = t.rows.clone();- let cells = t.cells.clone();- for (k, src) in order.iter().enumerate() {- let dst = body[k];- t.rows[dst] = rows[*src].clone();- for c in 0..nc {- t.cells[dst * nc + c] = cells[src * nc + c].clone();- }- }- Ok(json!({"sorted": body.len()}))- })- }-- #[cfg(test)]- mod sort_tests {- use serde_json::json;-- use crate::Session;-- fn distribution_session() -> Session {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 700], "content": "text", "text": ""})).unwrap();- s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 3, "cols": 2, "headerRows": 1})).unwrap();- for (row, height) in [(0, 25), (1, 40), (2, 80), (3, 30)] {- s.execute("table.setRowHeight", &json!({"row": row, "height": height, "mode": "exactly"})).unwrap();- s.execute("table.setCell", &json!({"row": row, "col": 0, "text": format!("row {row}")})).unwrap();- }- s- }-- fn table(s: &Session) -> designcraft_doc::Table {- (**s.doc().unwrap().doc.stories.values().flat_map(|st| st.tables.values()).next().unwrap()).clone()- }-- #[test]- fn distribute_selected_rows_preserves_height_content_and_undo() {- let mut s = distribution_session();- s.execute("table.select", &json!({"rows": [1, 2], "what": "row"})).unwrap();- let before = table(&s);- let selection = s.doc().unwrap().selection.cells;- let result = s.execute("table.distributeRows", &json!({})).unwrap();- assert_eq!(result, json!({"rows": 2, "height": 60.0}));- let after = table(&s);- assert_eq!(after.rows.iter().map(|r| r.height).collect::<Vec<_>>(), [25.0, 60.0, 60.0, 30.0]);- assert_eq!(after.cells, before.cells);- assert_eq!(after.rows[0].kind, before.rows[0].kind);- assert_eq!(s.doc().unwrap().selection.cells, selection);- let st = s.doc().unwrap();- let sid = st.doc.stories.values().find(|st| !st.tables.is_empty()).unwrap().id;- let cs = s.cache.get(&st.doc, sid, None);- let heights: Vec<_> =- cs.frames.iter().flat_map(|f| &f.tables).flat_map(|f| &f.cells).filter(|c| c.col == 0).map(|c| c.rect.height()).collect();- assert_eq!(heights, [25.0, 60.0, 60.0, 30.0]);- s.execute("edit.undo", &json!({})).unwrap();- assert_eq!(table(&s), before);- s.execute("edit.redo", &json!({})).unwrap();- assert_eq!(table(&s), after);- }-- #[test]- fn distribution_uses_content_grown_heights_and_explicit_table() {- let mut s = distribution_session();- s.execute("table.setRowHeight", &json!({"rows": [1, 2], "height": 3, "mode": "atLeast"})).unwrap();- s.execute("table.setCell", &json!({"row": 2, "col": 0, "text": "one\ntwo\nthree"})).unwrap();- let st = s.doc().unwrap();- let story = st.doc.stories.values().find(|st| !st.tables.is_empty()).unwrap();- let (sid, tid) = (story.id, *story.tables.keys().next().unwrap());- let cs = s.cache.get(&st.doc, sid, None);- let total: f64 = cs- .frames- .iter()- .flat_map(|f| &f.tables)- .flat_map(|f| &f.cells)- .filter(|c| c.col == 0 && (1..=2).contains(&c.row))- .map(|c| c.rect.height())- .sum();- let result = s.execute("table.distributeRows", &json!({"story": sid.0, "table": tid, "rows": [1, 2]})).unwrap();- assert!((result["height"].as_f64().unwrap() * 2.0 - total).abs() < 1e-6);- assert!(table(&s).rows[1].height > 3.0);- assert_eq!(table(&s).rows[1].mode, designcraft_doc::RowHeightMode::Exactly);- }-- #[test]- fn distribution_keeps_column_spans_and_caret() {- let mut s = distribution_session();- s.execute("table.merge", &json!({"rows": [1, 1], "cols": [0, 1]})).unwrap();- let before = table(&s);- let caret = s.doc().unwrap().selection.text;- let result = s.execute("table.distributeRows", &json!({"rows": [2, 1]})).unwrap();- assert_eq!(result["height"], 60.0);- assert_eq!(table(&s).cell(1, 0).unwrap().col_span, 2);- assert_eq!(table(&s).cells, before.cells);- assert_eq!(s.doc().unwrap().selection.text, caret);- }-- #[test]- fn distribution_rejects_merges_and_missing_rows_without_changes() {- let mut s = distribution_session();- s.execute("table.merge", &json!({"rows": [1, 2], "cols": [0, 0]})).unwrap();- let before = table(&s);- assert!(s.execute("table.distributeRows", &json!({"rows": [1, 2]})).is_err());- assert_eq!(table(&s), before);- s.execute("edit.undo", &json!({})).unwrap();- s.execute("table.setRowHeight", &json!({"rows": [0, 3], "height": 10000, "mode": "exactly"})).unwrap();- let before = table(&s);- assert!(s.execute("table.distributeRows", &json!({"rows": [0, 3]})).is_err());- assert_eq!(table(&s), before);- assert!(s.execute("table.distributeRows", &json!({"rows": [0, 99]})).is_err());- for params in- [json!({"rows": "all"}), json!({"rows": [0]}), json!({"rows": [-1, 2]}), json!({"row": 1.5}), json!({"table": "bad"}), json!([])]- {- assert!(s.execute("table.distributeRows", ¶ms).is_err(), "{params}");- assert_eq!(table(&s), before);- }- }-- #[test]- fn sort_body_rows_by_a_column() {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();- s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 3, "cols": 2, "headerRows": 1})).unwrap();- let cells = [("Name", "Qty"), ("pear", "10"), ("Apple", "9"), ("fig", "100")];- for (r, (a, b)) in cells.iter().enumerate() {- s.execute("table.setCell", &json!({"rows": [r, r], "cols": [0, 0], "text": a})).unwrap();- s.execute("table.setCell", &json!({"rows": [r, r], "cols": [1, 1], "text": b})).unwrap();- }- let col = |s: &Session, c: usize| -> Vec<String> {- let d = &s.doc().unwrap().doc;- let t = d.stories.values().flat_map(|st| st.tables.values()).next().unwrap();- (0..t.nrows()).map(|r| t.cell(r, c).unwrap().text.text.clone()).collect()- };- s.execute("table.sortRows", &json!({"column": 0})).unwrap();- assert_eq!(col(&s, 0), ["Name", "Apple", "fig", "pear"], "header stays; case-insensitive");- s.execute("table.sortRows", &json!({"column": 1, "descending": true})).unwrap();- assert_eq!(col(&s, 1), ["Qty", "100", "10", "9"], "numbers by value");- s.execute("table.splitVertically", &json!({"rows": [1, 1], "cols": [0, 0]})).unwrap();- let r = s.execute("table.splitHorizontally", &json!({"rows": [0, 0], "cols": [1, 1]})).unwrap();- assert_eq!((r["rows"].as_u64(), r["cols"].as_u64()), (Some(5), Some(3)));- }-- #[test]- fn graphic_cells_draw_their_image() {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();- s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();- s.execute("table.rowHeight", &json!({"height": 100})).ok();- // A red image into the first cell.- let px: Vec<u8> = (0..40 * 40).flat_map(|_| [255, 0, 0, 255]).collect();- let png = designcraft_render::Rendered { width: 40, height: 40, pixels: px }.to_png();- s.execute("table.setCell", &json!({"rows": [0, 0], "cols": [0, 0], "text": ""})).ok();- let g = s.execute("table.placeGraphic", &json!({"base64": super::super::file::base64_encode(&png), "name": "r.png", "fit": "fill"})).unwrap();- assert_eq!((g["row"].as_u64(), g["col"].as_u64()), (Some(0), Some(0)));- let d = s.doc().unwrap().doc.clone();- let st = d.stories.values().find(|st| !st.tables.is_empty()).unwrap();- let t = st.tables.values().next().unwrap();- let cs = s.cache.get(&d, st.id, None);- let cell = cs.frames[0].tables[0].cells.iter().find(|c| c.row == 0 && c.col == 0).unwrap().clone();- let fx = d.item(cs.frames[0].frame).unwrap().xf;- let centre = fx * cell.clip.center();- let mut rr = designcraft_render::Renderer::new();- rr.threads = 0;- let img = rr.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap();- let p = img.pixel(centre.x as u32, centre.y as u32);- assert!(p[0] > 200 && p[1] < 60, "red in the graphic cell: {p:?}");- assert!(t.cell(0, 0).unwrap().graphic.is_some());- s.execute("table.textCell", &json!({})).unwrap();- let d = s.doc().unwrap().doc.clone();- assert!(d.stories.values().flat_map(|st| st.tables.values()).all(|t| t.cell(0, 0).unwrap().graphic.is_none()));- }-- #[test]- fn move_rows_and_columns() {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();- s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 3, "cols": 2})).unwrap();- for (r, c, t) in [(0, 0, "a"), (1, 0, "b"), (2, 0, "c"), (0, 1, "x")] {- s.execute("table.setCell", &json!({"rows": [r, r], "cols": [c, c], "text": t})).unwrap();- }- let cell = |s: &Session, r: usize, c: usize| {- let d = &s.doc().unwrap().doc;- let t = d.stories.values().flat_map(|st| st.tables.values()).next().unwrap();- t.cell(r, c).unwrap().text.text.clone()- };- // Dragging a selected row onto the last row moves it there.- let d = s.doc().unwrap().doc.clone();- let (sid, tid) = d.stories.values().find_map(|st| st.tables.keys().next().map(|k| (st.id, *k))).unwrap();- let fid = d.stories[&sid].frames[0];- let cs = s.cache.get(&d, sid, None);- let cells = &cs.frames[0].tables[0].cells;- let centre = |r: usize| {- let c = cells.iter().find(|c| c.row == r && c.col == 0).unwrap().rect.center();- d.text_xf(d.item(fid).unwrap()) * c- };- let (from, to) = (centre(0), centre(2));- s.execute("table.select", &json!({"story": sid.0, "table": tid, "rows": [0, 0], "what": "row"})).unwrap();- let r2 = s.execute("table.dropCells", &json!({"frame": fid.0, "from": [from.x, from.y], "to": [to.x, to.y]})).unwrap();- assert_eq!(r2["moved"], 1);- assert_eq!([cell(&s, 0, 0), cell(&s, 1, 0), cell(&s, 2, 0)], ["b", "c", "a"]);- s.execute("edit.undo", &json!({})).unwrap();- assert_eq!([cell(&s, 0, 0), cell(&s, 1, 0), cell(&s, 2, 0)], ["a", "b", "c"]);- s.execute("table.moveRow", &json!({"from": 0, "to": 2})).unwrap();- assert_eq!([cell(&s, 0, 0), cell(&s, 1, 0), cell(&s, 2, 0)], ["b", "c", "a"]);- s.execute("table.moveColumn", &json!({"from": 1, "to": 0})).unwrap();- assert_eq!((cell(&s, 2, 0), cell(&s, 2, 1)), ("x".to_string(), "a".to_string()));- }-- #[test]- fn move_row_cannot_move_a_header_row_out_of_place() {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();- s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 3, "cols": 2, "headerRows": 1})).unwrap();- assert!(s.execute("table.moveRow", &json!({"from": 0, "to": 2})).is_err());- s.doc().unwrap().doc.check().unwrap();- // Dragging the selected header row onto the last body row is refused too.- let d = s.doc().unwrap().doc.clone();- let (sid, tid) = d.stories.values().find_map(|st| st.tables.keys().next().map(|k| (st.id, *k))).unwrap();- let fid = d.stories[&sid].frames[0];- let cs = s.cache.get(&d, sid, None);- let cells = &cs.frames[0].tables[0].cells;- let centre = |r: usize| {- let c = cells.iter().find(|c| c.row == r && c.col == 0).unwrap().rect.center();- d.text_xf(d.item(fid).unwrap()) * c- };- let (from, to) = (centre(0), centre(2));- s.execute("table.select", &json!({"story": sid.0, "table": tid, "rows": [0, 0], "what": "row"})).unwrap();- assert!(s.execute("table.dropCells", &json!({"frame": fid.0, "from": [from.x, from.y], "to": [to.x, to.y]})).is_err());- s.doc().unwrap().doc.check().unwrap();- }-- #[test]- fn table_options_limits_header_and_footer_rows() {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 700], "content": "text", "text": ""})).unwrap();- s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();- // The limit `table.insert` has: the table used to grow by as many rows as were asked for.- s.execute("table.options", &json!({"headerRows": 5000, "footerRows": 5000})).unwrap();- let t = table(&s);- assert_eq!((t.header_rows(), t.footer_rows(), t.nrows()), (100, 100, 201));- }- }-- #[cfg(test)]- mod arabic_tests {- use super::*;- #[test]- fn arabic_table_direction_and_physical_left_insertion_support_undo() {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [0, 0, 400, 300], "content": "text", "text": ""})).unwrap();- s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();- s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap();- s.execute("table.setCell", &json!({"rows": [0, 0], "cols": [0, 0], "text": "Right"})).unwrap();- s.execute("table.options", &json!({"direction": "rightToLeft"})).unwrap();- s.execute("table.select", &json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();- s.execute("table.insertColumnLeft", &json!({})).unwrap();- let t = s.doc().unwrap().doc.stories.values().flat_map(|st| st.tables.values()).next().unwrap();- assert_eq!(t.ncols(), 3);- assert_eq!(t.cell(0, 0).unwrap().text.text, "Right");- assert!(t.cell(0, 1).unwrap().text.text.is_empty());- s.execute("edit.undo", &json!({})).unwrap();- let t = s.doc().unwrap().doc.stories.values().flat_map(|st| st.tables.values()).next().unwrap();- assert_eq!(t.ncols(), 2);- assert_eq!(t.options.direction, designcraft_doc::TextDirection::RightToLeft);- }-- /// A text frame whose paragraphs have a paragraph style with `direction`, with the story's- /// text selected. Returns the session and the story id.- fn styled_frame(direction: &str, text: &str) -> (Session, u64) {- let mut s = Session::new();- s.execute("file.new", &json!({"preset": "A4", "pages": 1})).unwrap();- s.execute("style.paragraph.create", &json!({"name": "Dir", "para": {"direction": direction}})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [40, 330, 555, 420], "content": "text", "text": text, "caret": true})).unwrap();- s.execute("edit.selectAll", &json!({})).unwrap();- s.execute("style.paragraph.apply", &json!({"name": "Dir"})).unwrap();- s.execute("edit.selectAll", &json!({})).unwrap();- (s, r["story"].as_u64().unwrap())- }-- fn only_table(s: &Session) -> std::sync::Arc<designcraft_doc::Table> {- s.doc().unwrap().doc.stories.values().flat_map(|st| st.tables.values()).next().unwrap().clone()- }-- /// Text converted to a table in a right-to-left paragraph laid its columns out left to right- /// (#100): the first column belongs on the right.- #[test]- fn tables_take_the_direction_of_their_paragraph() {- use designcraft_doc::TextDirection::{LeftToRight, RightToLeft};- let (mut s, sid) = styled_frame("rightToLeft", "١\t٢\t٣\nأ\tب\tج");- s.execute("table.convertFromText", &json!({"columnSeparator": "tab"})).unwrap();- assert_eq!(only_table(&s).options.direction, RightToLeft);- let st = s.doc().unwrap();- let cs = s.cache.get(&st.doc, designcraft_doc::StoryId(sid), None);- let placed = &cs.frames[0].tables[0];- let (first, last) = (placed.cell(0, 0).unwrap().rect, placed.cell(0, 2).unwrap().rect);- assert!(first.x0 > last.x0, "cell ١ is the rightmost: {first:?} {last:?}");-- let (mut s, _) = styled_frame("leftToRight", "1\t2\t3\na\tb\tc");- s.execute("table.convertFromText", &json!({"columnSeparator": "tab"})).unwrap();- assert_eq!(only_table(&s).options.direction, LeftToRight);-- for (direction, expected) in [("rightToLeft", RightToLeft), ("leftToRight", LeftToRight)] {- let (mut s, _) = styled_frame(direction, "x");- s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap();- assert_eq!(only_table(&s).options.direction, expected, "table.insert in a {direction} paragraph");- }- }- }-- #[cfg(test)]- mod resize_border_tests {- use serde_json::json;-- use crate::Session;-- /// A 3×3 table of 80 pt columns; returns the session, frame id, story and table ids.- fn session() -> (Session, u64, u64, u64) {- let mut s = Session::new();- s.execute("file.new", &json!({})).unwrap();- let r = s.execute("frame.create", &json!({"rect": [72, 72, 472, 600], "content": "text", "text": ""})).unwrap();- s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();- let t = s.execute("table.insert", &json!({"rows": 3, "cols": 3, "width": 240})).unwrap();- (s, r["id"].as_u64().unwrap(), t["story"].as_u64().unwrap(), t["table"].as_u64().unwrap())- }-- fn table(s: &Session) -> designcraft_doc::Table {- (**s.doc().unwrap().doc.stories.values().flat_map(|st| st.tables.values()).next().unwrap()).clone()- }-- fn widths(s: &Session) -> Vec<f64> {- table(s).columns.iter().map(|c| c.width).collect()- }-- /// Composed cell rects of column 0, top to bottom.- fn rows(s: &Session) -> Vec<designcraft_geom::Rect> {- let st = s.doc().unwrap();- let sid = st.doc.stories.values().find(|x| !x.tables.is_empty()).unwrap().id;- let cs = s.cache.get(&st.doc, sid, None);- cs.frames.iter().flat_map(|f| &f.tables).flat_map(|f| &f.cells).filter(|c| c.col == 0).map(|c| c.rect).collect()- }-- fn resize(s: &mut Session, ids: (u64, u64, u64), mut p: serde_json::Value) {- p["frame"] = json!(ids.0);- p["story"] = json!(ids.1);- p["table"] = json!(ids.2);- s.execute("table.resizeBorder", &p).unwrap();- }-- #[test]- fn column_border_drags_widen_the_table_or_keep_its_width() {- let (mut s, f, st, t) = session();- resize(&mut s, (f, st, t), json!({"axis": "column", "index": 0, "delta": 20}));- assert_eq!(widths(&s), [100.0, 80.0, 80.0]);- resize(&mut s, (f, st, t), json!({"axis": "column", "index": 1, "delta": 30, "keepTableSize": true}));- assert_eq!(widths(&s), [100.0, 110.0, 50.0]);- // Clamped at the minimum; the neighbour takes only what is left.- resize(&mut s, (f, st, t), json!({"axis": "column", "index": 1, "delta": 500, "keepTableSize": true}));- assert_eq!(widths(&s), [100.0, 157.0, 3.0]);- resize(&mut s, (f, st, t), json!({"axis": "column", "index": 0, "delta": -1000}));- assert_eq!(widths(&s), [3.0, 157.0, 3.0]);- // Shift on the end edge scales every column.- resize(&mut s, (f, st, t), json!({"axis": "column", "index": 2, "size": 166, "keepTableSize": true}));- let w = widths(&s);- assert!((w.iter().sum::<f64>() - 326.0).abs() < 1e-9, "{w:?}");- assert!((w[1] / w[0] - 157.0 / 3.0).abs() < 1e-9, "{w:?}");- assert!(s.execute("table.resizeBorder", &json!({"table": t, "axis": "column", "index": 3, "delta": 1})).is_err());- assert!(s.execute("table.resizeBorder", &json!({"table": t, "axis": "column", "index": 0})).is_err());- }-- #[test]- fn row_drag_sets_at_least_and_moves_later_rows() {- let (mut s, f, st, t) = session();- s.execute("table.setRowHeight", &json!({"table": t, "row": 0, "height": 30, "mode": "exactly"})).unwrap();- let before = rows(&s);- resize(&mut s, (f, st, t), json!({"axis": "row", "index": 0, "delta": 12}));- let row = &table(&s).rows[0];- assert_eq!((row.height, row.mode), (42.0, designcraft_doc::RowHeightMode::AtLeast));- let after = rows(&s);- assert!((after[0].height() - 42.0).abs() < 1e-9);- assert!((after[1].y0 - before[1].y0 - 12.0).abs() < 1e-9 && (after[1].height() - before[1].height()).abs() < 1e-9);- // Below the minimum: clamped, never negative.- resize(&mut s, (f, st, t), json!({"axis": "row", "index": 0, "delta": -1000}));- assert_eq!(table(&s).rows[0].height, 3.0);- }-- #[test]- fn a_drag_is_one_undo_step_and_locked_frames_refuse() {- let (mut s, f, st, t) = session();- let before = table(&s);- s.begin_interaction("Resize Column").unwrap();- for d in [5.0, 15.0, 25.0] {- let p = json!({"frame": f, "story": st, "table": t, "axis": "column", "index": 0, "delta": d});- s.preview("table.resizeBorder", p).unwrap();- }- s.commit_interaction().unwrap();- assert_eq!(widths(&s), [105.0, 80.0, 80.0]);- s.execute("edit.undo", &json!({})).unwrap();- assert_eq!(table(&s), before);- s.execute("object.setFlags", &json!({"ids": [f], "locked": true})).unwrap();- assert!(s.execute("table.resizeBorder", &json!({"frame": f, "table": t, "axis": "column", "index": 0, "delta": 5})).is_err());- }- }-- #[cfg(test)]- mod style_alt_rows_tests {- use serde_json::json;-- use super::table_style_fields;-- #[test]- fn style_alt_rows_counts_saturate() {- let mut ts = designcraft_doc::TableStyle::default();- let p = json!({"altRows": {"first": 4294967297u64, "next": 4294967296u64, "skipFirst": 4294967295u64, "skipLast": 3}});- table_style_fields(&mut ts, &p, None);- let a = ts.alt_rows.unwrap();- assert_eq!(a.first, u32::MAX, "first");- assert_eq!(a.next, u32::MAX, "next");- assert_eq!(a.skip_first, u32::MAX, "skip_first");- assert_eq!(a.skip_last, 3, "skip_last");- }- }+ mod cell;+ mod content;+ mod options;+ mod registry;+ mod selection;+ mod sizing;+ mod structure;+ mod styles;+ mod target;++ pub use registry::specs;++pub use structure::{MAX_BODY_ROWS, MAX_COLUMNS, MAX_HEADER_FOOTER_ROWS};+ pub(crate) use selection::step_cell;diff --cc crates/engine/src/cmd/table/registry.rsindex 000000000,28d451ced..bcc18cb58mode 000000,100644..100644--- a/crates/engine/src/cmd/table/registry.rs+++ b/crates/engine/src/cmd/table/registry.rs@@@ -1,0 -1,402 +1,403 @@@+ use super::cell::{get_cell_stroke, set_cell};+ use super::content::{drop_cells, place_graphic, sort_rows};+ use super::options::{get, options};+ use super::selection::{move_rc, select, step_cell};+ use super::sizing::{distribute_cols, distribute_rows, resize_border, set_col_width, set_row_height};+ use super::structure::{+ can_convert_rows, convert_from_text, convert_rows, convert_to_text, delete_cols, delete_rows, delete_table, insert, insert_col, insert_row,+ merge, split, unmerge,+ };+ use super::styles::{cell_style_apply, cell_style_create, cell_style_edit, table_style_apply, table_style_create, table_style_edit};+ use super::target::{edit_table, in_cell, in_table, in_table_or_ids, target};+ use super::{CommandSpec, RowKind, cmd, has_doc, has_text, json, ok};++ pub fn specs() -> Vec<CommandSpec> {+ let mut v = style_specs();+ v.extend(table_specs());+ v+ }++ fn style_specs() -> Vec<CommandSpec> {+ vec![+ cmd!(+ "style.cell.create",+ "New Cell Style…",+ [],+ None,+ "{name, fromSelection?: bool (the target cell's look), fill?, tint?, insets?: n|[t,l,b,r], vj?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|fixed|emboxHeight, firstBaselineMin?: pt, stroke?: {weight?, color?, tint?, type?, gapColor?, gapTint?} (all four edges; values as table.setCell's stroke), paragraphStyle?, basedOn?: cell style name, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} → {name}",+ has_doc,+ |s, p| cell_style_create(s, p)+ ),+ cmd!(+ "style.cell.apply",+ "Apply Cell Style",+ [],+ None,+ "{name, story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} — the target cells (the whole table when the cursor is in it)",+ in_table,+ cell_style_apply+ ),+ cmd!(+ "style.cell.edit",+ "Cell Style Options…",+ [],+ None,+ "{name, …same as style.cell.create} — cells using the style follow",+ has_doc,+ cell_style_edit+ ),+ cmd!(+ "style.table.create",+ "New Table Style…",+ [],+ None,+ "{name, basedOn?: table style name, header?, body?, footer?, leftColumn?, rightColumn?: cell style names, border?: {weight?, color?, tint?, type?, gapColor?, gapTint?}, altRows?: {first, firstColor, next, nextColor}, spaceBefore?, spaceAfter?} → {name}",+ has_doc,+ table_style_create+ ),+ cmd!(+ "style.table.apply",+ "Apply Table Style",+ [],+ None,+ "{name, story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?}",+ in_table,+ table_style_apply+ ),+ cmd!(+ "style.table.edit",+ "Table Style Options…",+ [],+ None,+ "{name, …same as style.table.create} — tables using the style follow",+ has_doc,+ table_style_edit+ ),+ ]+ }++ fn table_specs() -> Vec<CommandSpec> {+ vec![+ cmd!(+ "table.insert",+ "Create Table",+ [],- Some("Cmd+Alt+Shift+T"),- "{rows?: body rows (4), cols? | columns? (4), headerRows? (0), footerRows? (0), width?} — at the text insertion point",++ // InDesign's Cmd+Alt+Shift+T opens the Insert Table dialog (`app.insertTableDialog`).++ None,++ "{rows?: body rows (4, at most 500), cols? | columns? (4, at most 200), headerRows? (0), footerRows? (0, each at most 100), tableStyle?: name, width?} — at the text insertion point, styled in the same step",+ has_text,+ insert+ ),+ cmd!(+ "table.convertFromText",+ "Convert Text to Table",+ ["Table"],+ None,+ "{columnSeparator?: tab|comma, width?: table width (default: the column)} — selected paragraphs become rows",+ has_text,+ convert_from_text+ ),+ cmd!(+ "table.convertToText",+ "Convert Table to Text",+ ["Table"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — cells separated by tabs, rows by paragraphs",+ in_table,+ convert_to_text+ ),+ cmd!(+ "table.insertRow",+ "Insert Row",+ [],+ None,+ "{where?: above|below, count? (1), story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ |s, p| insert_row(s, p, None)+ ),+ cmd!(+ "table.insertRowAbove",+ "Insert Row Above",+ ["Table", "Insert"],+ None,+ "{count?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ |s, p| insert_row(s, p, Some(true))+ ),+ cmd!(+ "table.insertRowBelow",+ "Insert Row Below",+ ["Table", "Insert"],+ None,+ "{count?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ |s, p| insert_row(s, p, Some(false))+ ),+ cmd!(+ "table.insertColumn",+ "Insert Column",+ [],+ None,+ "{where?: left|right, count? (1), width?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ |s, p| insert_col(s, p, None)+ ),+ cmd!(+ "table.insertColumnLeft",+ "Insert Column Left",+ ["Table", "Insert"],+ None,+ "{count?, width?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ |s, p| insert_col(s, p, Some(true))+ ),+ cmd!(+ "table.insertColumnRight",+ "Insert Column Right",+ ["Table", "Insert"],+ None,+ "{count?, width?, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ |s, p| insert_col(s, p, Some(false))+ ),+ cmd!(+ "table.deleteRow",+ "Delete Row",+ ["Table", "Delete"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the rows of the target cells",+ in_table,+ delete_rows+ ),+ cmd!(+ "table.deleteColumn",+ "Delete Column",+ ["Table", "Delete"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the columns of the target cells",+ in_table,+ delete_cols+ ),+ cmd!(+ "table.delete",+ "Delete Table",+ ["Table", "Delete"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ delete_table+ ),+ cmd!(+ "table.merge",+ "Merge Cells",+ ["Table"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — merge the target cell range",+ in_table,+ merge+ ),+ cmd!(+ "table.dropCells",+ "Drag Rows or Columns",+ [],+ None,+ "{frame, from: [x, y], to: [x, y]} — selected whole rows (or columns) dragged from `from` move to the row (column) at `to`; otherwise a text drag",+ has_doc,+ drop_cells+ ),+ cmd!(+ "table.placeGraphic",+ "Convert Cell to Graphic Cell",+ ["Table", "Convert Cell Type"],+ None,+ "{path? | base64?, name?: with base64, fit?: proportional|fill (default proportional), story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — an image in the target cell (its text is kept but hidden)",+ in_table,+ place_graphic+ ),+ cmd!(+ "table.textCell",+ "Convert Cell to Text Cell",+ ["Table", "Convert Cell Type"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — drop the target cells' graphics",+ in_table,+ |s, p| {+ let g = target(s, p, "table.textCell")?;+ edit_table(s, &g, "table.textCell", |t| {+ for (r, c) in t.selected_owners(g.range) {+ if let Some(cell) = t.cell_mut(r, c) {+ cell.graphic = None;+ }+ }+ ok()+ })+ }+ ),+ cmd!(+ "table.moveRow",+ "Move Row",+ [],+ None,+ "{from?, to, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} (0-based; from defaults to the target row) — like dragging a row",+ in_table,+ |s, p| move_rc(s, p, true)+ ),+ cmd!(+ "table.moveColumn",+ "Move Column",+ [],+ None,+ "{from?, to, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} (0-based; from defaults to the target column)",+ in_table,+ |s, p| move_rc(s, p, false)+ ),+ cmd!(+ "table.sortRows",+ "Sort",+ ["Table"],+ None,+ "{column?: 0-based (default: the target cell's), descending?: bool, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — body rows by that column's text (numbers numerically)",+ in_table,+ sort_rows+ ),+ cmd!(+ "table.unmerge",+ "Unmerge Cells",+ ["Table"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ unmerge+ ),+ cmd!(+ "table.splitHorizontally",+ "Split Cell Horizontally",+ ["Table"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — each target cell becomes two, one above the other",+ in_table,+ |s, p| split(s, p, true)+ ),+ cmd!(+ "table.splitVertically",+ "Split Cell Vertically",+ ["Table"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — each target cell becomes two, side by side",+ in_table,+ |s, p| split(s, p, false)+ ),+ cmd!(+ "table.setCell",+ "Cell Options",+ [],+ None,+ "{fill?: swatch, tint?: 0..1, insets?: n | [t,l,b,r], vj? | verticalJustification?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|fixed|emboxHeight, firstBaselineMin?: pt, rotation?: 0|90|180|270 (Cell Options › Text › Rotation; kept and written back to IDML, composed horizontally for now), text?, stroke?: {weight?, color?: swatch, tint?: 0..1, type?: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed | {kind:…}, gapColor?: swatch, gapTint?: 0..1, edges?: name | [names] (all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical; default all)}, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — top/left/bottom/right are the target range's outer sides, innerHorizontal/innerVertical the lines between its rows/columns",+ in_table,+ set_cell+ ),+ cmd!(+ query "table.getCellStroke",+ "Get Cell Stroke",+ [],+ None,+ "{story?, table?, rows?, cols?, edges?} → {weight, color, tint, type, gapColor, gapTint, fill, fillTint, edges: count} of the chosen edges of the target cells; a value that differs between them is null",+ in_table_or_ids,+ get_cell_stroke+ ),+ cmd!(+ "table.setRowHeight",+ "Row Height",+ [],+ None,+ "{height, mode?: atLeast|exactly, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ set_row_height+ ),+ cmd!(+ "table.setColumnWidth",+ "Column Width",+ [],+ None,+ "{width, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ set_col_width+ ),+ cmd!(+ "table.resizeBorder",+ "Resize Row or Column",+ [],+ None,+ "{story?, table?, frame?, axis: column|row, index, delta? | size?, keepTableSize?: bool} — moves the border after column/row `index` by `delta` (or makes that column/row `size` wide/high); later columns/rows move along. The last index is the table's end/bottom edge. keepTableSize: on an inner border the next column/row gives or takes the change; on the edge all columns/rows scale proportionally. A dragged row becomes At Least. Refuses a locked `frame`",+ in_table_or_ids,+ resize_border+ ),+ cmd!(+ "table.distributeColumns",+ "Distribute Columns Evenly",+ ["Table"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ distribute_cols+ ),+ cmd!(+ "table.distributeRows",+ "Distribute Rows Evenly",+ ["Table"],+ None,+ "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} — equal fixed heights preserving the selected rows' composed total height; may overset cell text; unmerge row-spanning cells first",+ in_table,+ distribute_rows+ ),+ cmd!(+ "table.options",+ "Table Options",+ [],+ None,+ "{direction?: leftToRight|rightToLeft, border?: {weight?, color?, tint?, type?, gapColor?, gapTint?}, spaceBefore?, spaceAfter?, headerRows?, footerRows?, repeatHeader?, repeatFooter?, altRows?: {first, firstColor, firstTint, next, nextColor, nextTint, skipFirst, skipLast} | null, altCols?: … | null, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}",+ in_table,+ options+ ),+ cmd!(+ "table.convertRowsToHeader",+ "To Header",+ ["Table", "Convert Rows"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the target rows, at the top of the table or right after its header rows",+ |s| can_convert_rows(s, RowKind::Header),+ |s, p| convert_rows(s, p, RowKind::Header)+ ),+ cmd!(+ "table.convertRowsToBody",+ "To Body",+ ["Table", "Convert Rows"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the target header rows next to the body, footer rows next to it, or both",+ |s| can_convert_rows(s, RowKind::Body),+ |s, p| convert_rows(s, p, RowKind::Body)+ ),+ cmd!(+ "table.convertRowsToFooter",+ "To Footer",+ ["Table", "Convert Rows"],+ None,+ "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — the target rows, at the bottom of the table or right before its footer rows",+ |s| can_convert_rows(s, RowKind::Footer),+ |s, p| convert_rows(s, p, RowKind::Footer)+ ),+ cmd!(noundo "table.select", "Select Cells", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?, what?: cell|row|column|table}", in_table_or_ids, select),+ cmd!(noundo "table.selectTable", "Select Table", ["Table", "Select"], None, "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}", in_table, |s, p| {+ select(s, &crate::cmd::with_param(p, "what", json!("table")))+ }),+ cmd!(noundo "table.selectRow", "Select Row", ["Table", "Select"], None, "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}", in_table, |s, p| {+ select(s, &crate::cmd::with_param(p, "what", json!("row")))+ }),+ cmd!(noundo "table.selectColumn", "Select Column", ["Table", "Select"], None, "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}", in_table, |s, p| {+ select(s, &crate::cmd::with_param(p, "what", json!("column")))+ }),+ cmd!(noundo "table.nextCell", "Next Cell", [], None, "{}", in_cell, |s, _| step_cell(s, true)),+ cmd!(noundo "table.prevCell", "Previous Cell", [], None, "{}", in_cell, |s, _| step_cell(s, false)),+ cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} → rows, columns, cells (text, spans, fill), options", in_table_or_ids, get),+ ]+ }diff --cc crates/engine/src/cmd/table/structure.rsindex 000000000,174704c4a..c16f39f0dmode 000000,100644..100644--- a/crates/engine/src/cmd/table/structure.rs+++ b/crates/engine/src/cmd/table/structure.rs@@@ -1,0 -1,240 +1,266 @@@+ use super::target::{column_width, count, edit_table, in_cell, para_direction, target};+ use super::{CellAddr, Result, RowKind, Selection, Session, Table, TextSel, Value, bad, json, ok, str_param};+++/// The most body rows, columns, and header or footer rows `table.insert` makes (the Insert Table++/// dialog's limits too).++pub const MAX_BODY_ROWS: u64 = 500;++pub const MAX_COLUMNS: u64 = 200;++pub const MAX_HEADER_FOOTER_ROWS: u64 = 100;++++/// A command's `tableStyle`: none for an absent one or [Basic Table] (a new table's look), else the++/// resolved style and the cell styles it names. Anything but an existing style's name is an error.++fn table_style_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<(designcraft_doc::TableStyle, Vec<designcraft_doc::CellStyle>)>> {++ let name = match p.get("tableStyle") {++ None | Some(Value::Null) => return Ok(None),++ Some(Value::String(n)) if n == designcraft_doc::BASIC_TABLE => return Ok(None),++ Some(Value::String(n)) => n,++ Some(_) => return Err(bad(cmd, "`tableStyle` must be a table style's name")),++ };++ let styles = &s.doc()?.doc.styles;++ if !styles.table.iter().any(|x| x.name == *name) {++ return Err(bad(cmd, format!("no table style `{name}`")));++ }++ Ok(Some((styles.resolve_table_style(name), styles.cell.clone())))++}+++ pub(super) fn insert(s: &mut Session, p: &Value) -> Result<Value> {+ let t = s.doc()?.selection.text.ok_or_else(|| bad("table.insert", "no insertion point"))?;+ if t.cell.is_some() {+ return Err(bad("table.insert", "tables can't be nested in cells"));+ }- let rows = p.get("rows").and_then(Value::as_u64).unwrap_or(4).clamp(1, 500) as usize;- let cols = p.get("cols").or_else(|| p.get("columns")).and_then(Value::as_u64).unwrap_or(4).clamp(1, 200) as usize;- let header = p.get("headerRows").and_then(Value::as_u64).unwrap_or(0).min(100) as usize;- let footer = p.get("footerRows").and_then(Value::as_u64).unwrap_or(0).min(100) as usize;++ let rows = p.get("rows").and_then(Value::as_u64).unwrap_or(4).clamp(1, MAX_BODY_ROWS) as usize;++ let cols = p.get("cols").or_else(|| p.get("columns")).and_then(Value::as_u64).unwrap_or(4).clamp(1, MAX_COLUMNS) as usize;++ let header = p.get("headerRows").and_then(Value::as_u64).unwrap_or(0).min(MAX_HEADER_FOOTER_ROWS) as usize;++ let footer = p.get("footerRows").and_then(Value::as_u64).unwrap_or(0).min(MAX_HEADER_FOOTER_ROWS) as usize;++ let style = table_style_param(s, p, "table.insert")?;+ let width = p.get("width").and_then(Value::as_f64).unwrap_or_else(|| column_width(s, &t));+ s.edit(|d, sel| {+ let id = d.alloc();+ let mut table = Table::new(id, rows, cols, header, footer, width);+ table.options.direction = para_direction(d, t.story, t.range().start);+ let st = d.story_mut(t.story).ok_or_else(|| bad("table.insert", "no story"))?;+ // Cells start with the paragraph format at the caret.+ let pf = st.paras[st.para_at(t.range().start)].clone();+ let cf = st.char_format_at(t.range().start).clone();+ for c in &mut table.cells {+ c.text.paras[0] = designcraft_doc::ParaFormat { table: None, ..pf.clone() };+ c.text.chars[0].format = cf.clone();+ }++ if let Some((ts, cells)) = &style {++ ts.apply_to(&mut table, cells);++ }+ let r = t.range();+ st.delete(r.clone());+ st.insert_table(r.start, table);+ *sel = Selection::text(TextSel { story: t.story, anchor: 0, focus: 0, frame: t.frame, cell: Some(CellAddr { table: id, row: 0, col: 0 }) });+ Ok(json!({"story": t.story.0, "table": id}))+ })+ }++ pub(super) fn convert_from_text(s: &mut Session, p: &Value) -> Result<Value> {+ let t = s.doc()?.selection.text.ok_or_else(|| bad("table.convertFromText", "no text selected"))?;+ if t.cell.is_some() {+ return Err(bad("table.convertFromText", "select text outside tables"));+ }+ let sep = if str_param(p, "columnSeparator") == Some("comma") { ',' } else { '\t' };+ let width = p.get("width").and_then(Value::as_f64).unwrap_or_else(|| column_width(s, &t));+ s.edit(|d, sel| {+ let id = d.alloc();+ let direction = para_direction(d, t.story, t.range().start);+ let st = d.story_mut(t.story).ok_or_else(|| bad("table.convertFromText", "no story"))?;+ let ranges = st.para_ranges();+ let (pa, pb) = (st.para_at(t.range().start), st.para_at(t.range().end));+ if (pa..=pb).any(|i| st.paras[i].table.is_some()) {+ return Err(bad("table.convertFromText", "the selection contains a table"));+ }+ let (a, b) = (ranges[pa].start, ranges[pb].end);+ let data: Vec<Vec<String>> = st.text[a..b].split('\n').map(|line| line.split(sep).map(|c| c.trim().to_string()).collect()).collect();+ let pf = st.paras[pa].clone();+ let cf = st.format_after(a).clone();+ let mut table = Table::from_strings(id, &data, width, &pf, &cf);+ table.options.direction = direction;+ st.delete(a..b);+ let anchor = st.insert_table(a, table);+ *sel = Selection::text(TextSel::caret(t.story, anchor));+ Ok(json!({"table": id, "rows": data.len()}))+ })+ }++ pub(super) fn convert_to_text(s: &mut Session, p: &Value) -> Result<Value> {+ let g = target(s, p, "table.convertToText")?;+ s.edit(|d, sel| {+ let st = d.story_mut(g.story).ok_or_else(|| bad("table.convertToText", "no story"))?;+ let text = st.tables.get(&g.table).map(|t| t.plain_text()).unwrap_or_default();+ let a = st.table_anchor(g.table).ok_or_else(|| bad("table.convertToText", "no anchor"))?;+ st.replace(a..a + designcraft_doc::TABLE_ANCHOR.len_utf8(), &text);+ *sel = Selection::text(TextSel::caret(g.story, a + text.len()));+ ok()+ })+ }++ pub(super) fn delete_table(s: &mut Session, p: &Value) -> Result<Value> {+ let g = target(s, p, "table.delete")?;+ s.edit(|d, sel| {+ let st = d.story_mut(g.story).ok_or_else(|| bad("table.delete", "no story"))?;+ let a = st.table_anchor(g.table).ok_or_else(|| bad("table.delete", "no anchor"))?;+ // Remove the anchor paragraph (with one separator) so no empty paragraph is left behind.+ let end = a + designcraft_doc::TABLE_ANCHOR.len_utf8();+ let r = if &st.text[end..] == "\n" && a > 0 && st.text[..a].ends_with('\n') {+ // Inserted at the end of the story: remove the empty paragraph after it too.+ a - 1..end + 1+ } else if st.text[end..].starts_with('\n') {+ a..end + 1+ } else if a > 0 && st.text[..a].ends_with('\n') {+ a - 1..end+ } else {+ a..end+ };+ st.delete(r.clone());+ *sel = Selection::text(TextSel::caret(g.story, r.start.min(st.len())));+ ok()+ })+ }++ // ---------- rows and columns ----------++ pub(super) fn insert_row(s: &mut Session, p: &Value, above: Option<bool>) -> Result<Value> {+ let g = target(s, p, "table.insertRow")?;+ let above = above.unwrap_or(str_param(p, "where") == Some("above"));+ let n = count(p);+ let at = if above { g.range.r0 } else { g.range.r1 + 1 };+ let r = edit_table(s, &g, "table.insertRow", |t| {+ t.insert_rows(at, n);+ Ok(json!({"rows": t.nrows()}))+ })?;+ shift_selection(s, g.table, at, n, true);+ Ok(r)+ }++ /// After inserting rows/columns at `at`, selections at or after it follow their cells.+ fn shift_selection(s: &mut Session, table: u64, at: usize, n: usize, rows: bool) {+ let Ok(st) = s.doc_mut() else { return };+ if let Some(t) = st.selection.text.as_mut()+ && let Some(c) = t.cell.as_mut()+ && c.table == table+ {+ let v = if rows { &mut c.row } else { &mut c.col };+ if *v >= at {+ *v += n;+ }+ }+ if let Some(ts) = st.selection.cells.as_mut()+ && ts.table == table+ {+ let (a, b) = if rows { (&mut ts.range.r0, &mut ts.range.r1) } else { (&mut ts.range.c0, &mut ts.range.c1) };+ if *a >= at {+ *a += n;+ }+ if *b >= at {+ *b += n;+ }+ }+ }++ pub(super) fn insert_col(s: &mut Session, p: &Value, left: Option<bool>) -> Result<Value> {+ let g = target(s, p, "table.insertColumn")?;+ let left = left.unwrap_or(str_param(p, "where") == Some("left"));+ let rtl = s+ .doc()?+ .doc+ .story(g.story)+ .and_then(|st| st.tables.get(&g.table))+ .is_some_and(|t| t.options.direction == designcraft_doc::TextDirection::RightToLeft);+ let n = count(p);+ let at = if left != rtl { g.range.c0 } else { g.range.c1 + 1 };+ let width = p.get("width").and_then(Value::as_f64);+ let r = edit_table(s, &g, "table.insertColumn", |t| {+ let w = width.unwrap_or_else(|| t.columns[g.range.c0.min(t.ncols() - 1)].width);+ t.insert_cols(at, n, w);+ Ok(json!({"columns": t.ncols()}))+ })?;+ shift_selection(s, g.table, at, n, false);+ Ok(r)+ }++ pub(super) fn delete_rows(s: &mut Session, p: &Value) -> Result<Value> {+ let g = target(s, p, "table.deleteRow")?;+ let all = s.doc()?.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).is_some_and(|t| g.range.r0 == 0 && g.range.r1 + 1 >= t.nrows());+ if all {+ return delete_table(s, p);+ }+ edit_table(s, &g, "table.deleteRow", |t| {+ t.delete_rows(g.range.r0, g.range.r1 - g.range.r0 + 1);+ Ok(json!({"rows": t.nrows()}))+ })+ }++ pub(super) fn delete_cols(s: &mut Session, p: &Value) -> Result<Value> {+ let g = target(s, p, "table.deleteColumn")?;+ let all = s.doc()?.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).is_some_and(|t| g.range.c0 == 0 && g.range.c1 + 1 >= t.ncols());+ if all {+ return delete_table(s, p);+ }+ edit_table(s, &g, "table.deleteColumn", |t| {+ t.delete_cols(g.range.c0, g.range.c1 - g.range.c0 + 1);+ Ok(json!({"columns": t.ncols()}))+ })+ }++ pub(super) fn merge(s: &mut Session, p: &Value) -> Result<Value> {+ let g = target(s, p, "table.merge")?;+ let r = edit_table(s, &g, "table.merge", |t| {+ t.merge(g.range).map_err(|e| bad("table.merge", e))?;+ Ok(t.expand_range(g.range))+ })?;+ // The caret goes to the merged cell.+ let st = s.doc_mut()?;+ st.selection = Selection::text(TextSel {+ story: g.story,+ anchor: 0,+ focus: 0,+ frame: st.selection.text.and_then(|t| t.frame),+ cell: Some(CellAddr { table: g.table, row: r.r0, col: r.c0 }),+ });+ ok()+ }++ pub(super) fn split(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {+ let g = target(s, p, "table.split")?;+ edit_table(s, &g, "table.split", |t| {+ t.split_cells(g.range, horizontal).map_err(|e| bad("table.split", e))?;+ Ok(json!({"rows": t.nrows(), "cols": t.ncols()}))+ })+ }++ pub(super) fn unmerge(s: &mut Session, p: &Value) -> Result<Value> {+ let g = target(s, p, "table.unmerge")?;+ edit_table(s, &g, "table.unmerge", |t| {+ for r in g.range.r0..=g.range.r1 {+ for c in g.range.c0..=g.range.c1 {+ t.unmerge(r, c);+ }+ }+ ok()+ })+ }++ /// Convert Rows is greyed out unless the selected cells (or the caret's cell) can change kind.+ pub(super) fn can_convert_rows(s: &Session, kind: RowKind) -> std::result::Result<(), String> {+ let st = s.active().ok_or("no document open")?;+ if st.selection.cells.is_none() {+ in_cell(s)?;+ }+ let g = target(s, &Value::Null, "table.convertRows").map_err(|e| e.to_string())?;+ let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or("no table")?;+ t.convert_rows_counts(g.range.r0, g.range.r1, kind).map(|_| ())+ }++ pub(super) fn convert_rows(s: &mut Session, p: &Value, kind: RowKind) -> Result<Value> {+ const ID: &str = "table.convertRows";+ let g = target(s, p, ID)?;+ edit_table(s, &g, ID, |t| {+ let (h, f) = t.convert_rows_counts(g.range.r0, g.range.r1, kind).map_err(|e| bad(ID, e))?;+ t.set_header_footer(h, f);+ Ok(json!({"headerRows": h, "footerRows": f}))+ })+ }diff --cc crates/ui-egui/src/dialogs.rsindex 4a020a93a,bb3077103..6de67e638--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -234,6 -186,6 +245,52 @@@ fn color_theme(app: &DesignApp, ui: &mumod color_theme_tests {use super::*;++ /// Insert Table: the dimensions as typed, and the Table Style chosen is applied to the new++ /// table; [Basic Table] (the default) leaves it unstyled.++ #[test]++ fn insert_table_applies_its_dimensions_and_table_style() {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({})).unwrap();++ app.run("style.table.create", json!({"name": "Grid"})).unwrap();++ for (style, expected) in [("Grid", "Grid"), (designcraft_doc::BASIC_TABLE, "")] {++ app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap();++ assert_eq!(app.run("app.insertTableDialog", json!({})).unwrap(), Value::Null);++ for (field, value) in [("bodyRows", json!(5)), ("columns", json!(3)), ("headerRows", json!(1)), ("tableStyle", json!(style))] {++ ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value}));++ }++ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);++ let t = app.run("table.get", json!({})).unwrap();++ let len = |k: &str| t[k].as_array().map_or(0, Vec::len);++ assert_eq!((len("rows"), len("columns"), t["headerRows"].as_u64()), (6, 3, Some(1)), "{t}");++ assert_eq!(t["style"].as_str().unwrap_or(""), expected, "{t}");++ // One Insert Table, one undo.++ app.run("edit.undo", json!({})).unwrap();++ assert!(app.run("table.get", json!({})).is_err(), "the table is gone");++ }++ // A null style is no style: the table is made, unstyled.++ app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap();++ app.run("app.insertTableDialog", json!({})).unwrap();++ ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": null}));++ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);++ assert_eq!(app.run("table.get", json!({})).unwrap()["style"].as_str().unwrap_or(""), "");++ app.run("edit.undo", json!({})).unwrap();++ // A style that no longer exists changes nothing.++ let tables = |app: &DesignApp| app.session.active().unwrap().doc.stories.values().map(|s| s.tables.len()).sum::<usize>();++ app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap();++ app.run("app.insertTableDialog", json!({})).unwrap();++ ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": "Gone"}));++ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);++ assert_eq!(tables(&app), 0);++ let d = app.ui.dialog.as_ref().expect("the dialog stays open to be corrected");++ assert_eq!((d.id.as_str(), d.s("tableStyle")), ("insertTable", "Gone".to_string()));++ // So does a style that isn't a name: the command refuses it, rather than making the table++ // unstyled.++ ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": 42}));++ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);++ assert_eq!(tables(&app), 0);++ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("insertTable"), "the dialog stays open");++ }++#[test]fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() {let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());diff --cc crates/ui-egui/src/dialogs/tests.rsindex 000000000,84cbf3bea..f6b689e67mode 000000,100644..100644--- a/crates/ui-egui/src/dialogs/tests.rs+++ b/crates/ui-egui/src/dialogs/tests.rs@@@ -1,0 -1,3523 +1,3523 @@@+ use super::*;++ #[test]+ fn paragraph_style_settings_show_captured_color_and_pending_spacing_without_changing_the_document() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Heading"})).unwrap();+ app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":7})).unwrap();+ app.run("type.char", json!({"fontFamily":"Source Sans 3","fontStyle":"Bold","size":16,"fill":"[Paper]"})).unwrap();+ app.run("style.paragraph.create", json!({"name":"Header","fromSelection":true})).unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ let style = doc.styles.para("Header").unwrap();+ let mut d = Dialog::new("paragraphStyleOptions", json!({"name":"Header"}));+ let summary = paragraph_style_summary("", &d, style, &doc.styles);+ for value in ["Source Sans 3", "Bold", "16 pt", "[Paper]"] {+ assert!(summary.contains(value), "{summary}");+ }+ assert!(summary.len() < 250, "default attributes do not swamp the captured settings: {summary}");+ d.fields.insert("c.fill".into(), json!("[Registration]"));+ d.fields.insert("p.spaceAfter".into(), json!(4.5));+ let summary = paragraph_style_summary("", &d, style, &doc.styles);+ assert!(summary.contains("[Registration]") && !summary.contains("[Paper]"), "{summary}");+ assert!(summary.contains("4.5 pt"), "{summary}");+ assert_eq!(app.session.doc().unwrap().doc, doc);+ }++ /// A dialog opened without the menu's fields has no `useDefaults` field at all. Confirming it+ /// with no layer unticked must keep the file's defaults, not choose every layer explicitly:+ /// an implicit all-on choice is rejected for a PDF without layers, so the command's error+ /// tells the two apart.+ #[test]+ fn layer_options_confirm_without_the_menu_fields_keeps_file_defaults() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 100, "height": 100, "pages": 1})).unwrap();+ let pdf = app.run("file.exportPdf", json!({})).unwrap()["base64"].clone();+ let placed = app.run("file.place", json!({"base64": pdf, "name": "plain.pdf", "x": 0, "y": 0, "width": 100})).unwrap();+ let id = designcraft_doc::ItemId(placed["id"].as_u64().unwrap());+ app.run("selection.set", json!({"ids": [placed["id"]]})).unwrap();+ app.ui.dialog = Some(Dialog::new("layerOptions", json!({})));+ confirm(&mut app).unwrap();+ assert!(!app.session.doc().unwrap().doc.item(id).unwrap().has_pdf_layer_override(), "an untouched dialog keeps the file defaults");+ // The menu's own dialog still asks for an explicit all-on choice when that is the state+ // it was opened in; a layerless PDF refuses it rather than accepting an empty override.+ app.ui.dialog = Some(Dialog::new("layerOptions", json!({"useDefaults": false, "layers": []})));+ let err = confirm(&mut app).unwrap_err();+ assert!(err.contains("could not be changed"), "{err}");+ assert!(!app.session.doc().unwrap().doc.item(id).unwrap().has_pdf_layer_override(), "a layerless PDF never takes an explicit choice");+ }++ #[test]+ fn paragraph_style_settings_compare_with_the_chosen_parent() {+ let mut styles = designcraft_doc::Styles::default();+ styles.paragraph.push(designcraft_doc::ParagraphStyle {+ name: "Parent".into(),+ chars: designcraft_doc::CharAttrs { size: Some(20.0), ..Default::default() },+ based_on: None,+ next_style: None,+ para: Default::default(),+ shortcut: String::new(),+ });+ let style = designcraft_doc::ParagraphStyle {+ name: "Child".into(),+ based_on: Some("Parent".into()),+ next_style: None,+ para: Default::default(),+ chars: Default::default(),+ shortcut: String::new(),+ };+ let d = Dialog::new("paragraphStyleOptions", json!({"name":"Child"}));+ assert_eq!(paragraph_style_summary("", &d, &style, &styles), "Parent");+ }++ #[test]+ fn step_and_repeat_dialog_previews_and_makes_the_copies_as_one_undo_step() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 600, 540, 640]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ let open = |app: &mut DesignApp| {+ crate::menus::activate(app, "edit.stepAndRepeat", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(STEP_AND_REPEAT));+ };+ let set = |app: &mut DesignApp, k: &str, v: Value| {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);+ };+ let items = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].items.len();+ let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len();+ let (n0, u0) = (items(&app), undo(&app));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ open(&mut app);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["Step and Repeat", "Repeat", "Count:", "Create as a grid", "Offset", "Vertical:", "Horizontal:", "Preview", "OK", "Cancel"] {+ visible_label(&labels, screen, expected);+ }+ // Preview: the copies show, and change with the fields, without an undo step.+ set(&mut app, "count", json!("5"));+ set(&mut app, "vertical", json!("-0.75 in"));+ set(&mut app, "horizontal", json!("0"));+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!((items(&app), undo(&app)), (n0 + 5, u0));+ set(&mut app, "count", json!("3"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0 + 3);+ set(&mut app, "preview", json!(false));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0, "Preview off takes them away");+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0 + 3);+ // Cancel puts the document back.+ cancel(&mut app);+ assert!(app.ui.dialog.is_none());+ assert_eq!((items(&app), undo(&app)), (n0, u0));+ // OK after a preview makes the copies once, as one undo step, 0.75 in apart.+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ open(&mut app);+ set(&mut app, "count", json!("2"));+ set(&mut app, "vertical", json!("-0.75 in"));+ set(&mut app, "horizontal", json!("0"));+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let r = confirm(&mut app).unwrap();+ assert_eq!((items(&app), undo(&app)), (n0 + 2, u0 + 1));+ let last = r["ids"][1].as_u64().unwrap();+ let top = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(last)).unwrap().bounds().min_y();+ assert!((top - (600.0 - 108.0)).abs() < 1e-6, "{top}");+ // Create as a grid: Rows × Columns cells, the original being one.+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ open(&mut app);+ set(&mut app, "grid", json!(true));+ set(&mut app, "rows", json!("2"));+ set(&mut app, "columns", json!("3"));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "Rows:");+ visible_label(&labels, screen, "Columns:");+ assert_eq!(confirm(&mut app).unwrap()["created"], 5);+ // A value that isn't a measure keeps the dialog open and says so.+ open(&mut app);+ set(&mut app, "vertical", json!("up"));+ assert!(confirm(&mut app).is_err());+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.s("status"), "Invalid value: up");+ }++ /// A three-page document in `units` with Document Setup open.+ fn document_setup_app(units: &str) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 3})).unwrap();+ app.run("document.preferences", json!({"horizontalUnits": units, "verticalUnits": units})).unwrap();+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);+ app+ }++ fn setup_fields(app: &mut DesignApp, fields: Value) {+ let d = app.ui.dialog.as_mut().unwrap();+ for (k, v) in fields.as_object().unwrap() {+ d.fields.insert(k.clone(), v.clone());+ }+ }++ /// File › File Info opens filled from the document and OK stores what was typed; Export PDF+ /// then names the file after the document and takes the PDF's title from File Info.+ #[test]+ fn file_info_dialog_stores_the_fields_and_titles_the_pdf() {+ use std::sync::{Arc, Mutex};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "flyer-v3"})).unwrap();+ app.run("file.info", json!({"author": "Ana Ruiz", "keywords": ["spring", "shoes"]})).unwrap();+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.id, "fileInfo");+ assert_eq!((d.s("documentTitle"), d.s("author"), d.s("keywords")), (String::new(), "Ana Ruiz".into(), "spring; shoes".into()));+ setup_fields(&mut app, json!({"documentTitle": "Spring Catalog", "author": "", "keywords": "spring, catalog", "description": "Shoes"}));+ confirm(&mut app).unwrap();+ assert!(app.ui.dialog.is_none());+ let info = app.session.active().unwrap().doc.file_info.clone();+ assert_eq!((info.document_title.as_str(), info.author.as_str(), info.description.as_str()), ("Spring Catalog", "", "Shoes"));+ assert_eq!(info.keywords, ["spring", "catalog"]);+ // Keywords left as shown stay as they are, even one with a comma in it.+ app.run("file.info", json!({"keywords": ["Washington, DC", "map"]})).unwrap();+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ setup_fields(&mut app, json!({"author": "Studio"}));+ confirm(&mut app).unwrap();+ let info = app.session.active().unwrap().doc.file_info.clone();+ assert_eq!((info.author.as_str(), info.keywords.clone()), ("Studio", vec!["Washington, DC".to_string(), "map".to_string()]));+ // Another keyword edited: the one with a comma in it still stays one keyword.+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("keywords"), "Washington, DC; map");+ setup_fields(&mut app, json!({"keywords": "Washington, DC; atlas"}));+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.file_info.keywords, ["Washington, DC", "atlas"]);++ let writes: Arc<Mutex<Vec<Vec<u8>>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = writes.clone();+ app.services.write = Some(Box::new(move |_: &str, bytes: &[u8]| {+ sink.lock().unwrap().push(bytes.to_vec());+ Ok(())+ }));+ let names: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));+ let asked = names.clone();+ app.answer_dialogs(move |request| match request {+ craft_dialogs::Request::File(dialog) => {+ asked.lock().unwrap().push(dialog.file_name.clone().unwrap_or_default());+ craft_dialogs::Answer::Paths(vec!["/tmp/designcraft-file-info.pdf".into()])+ }+ craft_dialogs::Request::Message(_) => craft_dialogs::Answer::Message(craft_dialogs::MessageResult::Yes),+ });+ open_pdf_export(&mut app);+ confirm(&mut app).unwrap();+ app.settle_dialogs();+ assert_eq!(names.lock().unwrap().as_slice(), ["flyer-v3.pdf"]);+ let pdf = String::from_utf8_lossy(&writes.lock().unwrap()[0]).into_owned();+ assert!(pdf.contains("/Title(Spring Catalog)") && !pdf.contains("/Title(flyer-v3)"), "the PDF's title is File Info's");+ // A title given to the export is the PDF's title, even when it is the document's name.+ open_pdf_export(&mut app);+ setup_fields(&mut app, json!({"title": "flyer-v3"}));+ confirm(&mut app).unwrap();+ app.settle_dialogs();+ let asked = names.lock().unwrap().last().cloned().unwrap_or_default();+ assert_eq!(std::path::Path::new(&asked).file_name().and_then(|n| n.to_str()), Some("flyer-v3.pdf"), "{asked}");+ let pdf = String::from_utf8_lossy(&writes.lock().unwrap()[1]).into_owned();+ assert!(pdf.contains("/Title(flyer-v3)") && !pdf.contains("/Title(Spring Catalog)"), "the given title wins");+ }++ /// File Info's OK stores the fields in the document the dialog was opened for, even when+ /// another document became active meanwhile; once that document has closed, OK stores nothing.+ #[test]+ fn file_info_dialog_stores_into_the_document_it_was_opened_for() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "first"})).unwrap();+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ app.run("file.new", json!({"title": "second"})).unwrap();+ setup_fields(&mut app, json!({"author": "Ana Ruiz"}));+ confirm(&mut app).unwrap();+ let docs = app.session.documents();+ let author = |title: &str| docs.iter().find(|d| d.doc.title == title).map(|d| d.doc.file_info.author.clone());+ assert_eq!((author("first").as_deref(), author("second").as_deref()), (Some("Ana Ruiz"), Some("")));+ assert_eq!(app.session.active().map(|d| d.doc.title.as_str()), Some("second"), "the active document stays active");++ crate::menus::activate(&mut app, "file.info", &Value::Null);+ app.run("file.close", json!({})).unwrap();+ setup_fields(&mut app, json!({"author": "Studio"}));+ confirm(&mut app).unwrap();+ assert!(app.session.documents().iter().all(|d| d.doc.file_info.author != "Studio"), "the dialog's document closed");+ }++ /// File Info opened through `ui.dialog.open` with only some fields stores only those fields;+ /// the others keep what the document holds.+ #[test]+ fn file_info_opened_with_some_fields_keeps_the_others() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("file.info", json!({"documentTitle": "Spring Catalog", "keywords": ["spring", "shoes"]})).unwrap();+ assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "fileInfo", "fields": {"author": "Ana Ruiz", "description": ""}}))["ok"], true);+ confirm(&mut app).unwrap();+ let info = app.session.active().unwrap().doc.file_info.clone();+ assert_eq!((info.document_title.as_str(), info.author.as_str(), info.description.as_str()), ("Spring Catalog", "Ana Ruiz", ""));+ assert_eq!(info.keywords, ["spring", "shoes"]);+ }++ /// Fields given to `ui.dialog.open` as JSON other than text reach `file.info` as they are: a+ /// keyword list stays a list, and `null` clears a field.+ #[test]+ fn file_info_opened_with_a_keyword_list_stores_the_list() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("file.info", json!({"author": "Ana Ruiz"})).unwrap();+ let fields = json!({"keywords": ["Washington, DC", "map"], "author": null});+ assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "fileInfo", "fields": fields}))["ok"], true);+ confirm(&mut app).unwrap();+ let info = app.session.active().unwrap().doc.file_info.clone();+ assert_eq!(info.keywords, ["Washington, DC", "map"]);+ assert_eq!(info.author, "");+ }++ /// File Info's OK for a document that is not the active one leaves the active document's+ /// Data Merge preview showing the record it showed.+ #[test]+ fn file_info_for_another_document_keeps_the_active_preview() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "first"})).unwrap();+ crate::menus::activate(&mut app, "file.info", &Value::Null);+ app.run("file.new", json!({"title": "second"})).unwrap();+ let csv = designcraft_engine::cmd::base64_encode(b"Name\nAda\nGrace\n");+ app.run("data.source.select", json!({"bytes": csv, "name": "people.csv"})).unwrap();+ app.run("data.preview", json!({"record": 2})).unwrap();+ setup_fields(&mut app, json!({"author": "Ana Ruiz"}));+ confirm(&mut app).unwrap();+ let active = app.session.active().unwrap();+ assert_eq!((active.doc.title.as_str(), active.preview_record), ("second", Some(2)), "the preview still shows record 2");+ let first = app.session.documents().iter().find(|d| d.doc.title == "first").map(|d| d.doc.file_info.author.clone());+ assert_eq!(first.as_deref(), Some("Ana Ruiz"));+ }++ #[test]+ fn document_setup_ok_applies_margins_bleed_and_size_in_one_step() {+ let mut app = document_setup_app("millimeters");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.id, "documentSetup");+ assert_eq!((d.s("marginTop"), d.b("marginLinked")), ("12.7 mm".to_string(), true), "the document's margins, in its units");+ setup_fields(+ &mut app,+ json!({"marginTop": "20 mm", "marginBottom": "20 mm", "marginInside": "20 mm", "marginOutside": "20 mm", "bleedTop": "3 mm",+ "bleedBottom": "3 mm", "bleedInside": "3 mm", "bleedOutside": "3 mm", "width": "210 mm", "height": "297 mm"}),+ );+ confirm(&mut app).unwrap();+ assert!(app.ui.dialog.is_none());+ let mm = designcraft_geom::units::PT_PER_MM;+ let doc = &app.session.active().unwrap().doc;+ assert!((doc.settings.page_width - 210.0 * mm).abs() < 1e-6 && (doc.settings.bleed[2] - 3.0 * mm).abs() < 1e-6);+ assert!(doc.spreads.iter().flat_map(|s| &s.pages).all(|p| (p.margins.top - 20.0 * mm).abs() < 1e-6), "every page");+ app.run("edit.undo", json!({})).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert!((doc.settings.page_width - 612.0).abs() < 1e-6 && doc.settings.bleed[0] == 0.0, "one undo step");+ }++ #[test]+ fn document_setup_reads_a_bare_number_in_the_documents_units() {+ let mut app = document_setup_app("millimeters");+ setup_fields(&mut app, json!({"bleedTop": "5", "bleedBottom": "5", "bleedInside": "5", "bleedOutside": "5", "width": "210"}));+ confirm(&mut app).unwrap();+ let mm = designcraft_geom::units::PT_PER_MM;+ let settings = &app.session.active().unwrap().doc.settings;+ assert!(settings.bleed.iter().all(|b| (b - 5.0 * mm).abs() < 1e-6), "5 mm, not 5 picas: {:?}", settings.bleed);+ assert!((settings.page_width - 210.0 * mm).abs() < 1e-6, "{}", settings.page_width);+ }++ #[test]+ fn document_setup_keeps_each_pages_margins_unless_they_are_edited() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 3, "margins": 36})).unwrap();+ app.run("layout.marginsAndColumns", json!({"pages": [1], "margins": 90})).unwrap();+ let margins =+ |app: &DesignApp| app.session.active().unwrap().doc.spreads.iter().flat_map(|s| &s.pages).map(|p| p.margins.top).collect::<Vec<_>>();+ // Only the page count changes: every page keeps its own margins.+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);+ setup_fields(&mut app, json!({"pages": "4"}));+ confirm(&mut app).unwrap();+ assert_eq!(margins(&app), [36.0, 90.0, 36.0, 36.0]);+ // Edited margins go to every page.+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);+ setup_fields(&mut app, json!({"marginTop": "1p0"}));+ confirm(&mut app).unwrap();+ assert_eq!(margins(&app), [12.0; 4]);+ }++ #[test]+ fn document_setup_keeps_a_value_it_cannot_read_and_changes_nothing() {+ for (key, value) in [("width", "wide"), ("marginTop", "-"), ("pages", "0"), ("bleedTop", "x")] {+ let mut app = document_setup_app("points");+ setup_fields(&mut app, json!({key: value, "bleedInside": "9"}));+ assert!(confirm(&mut app).is_err(), "{key}");+ assert!(app.ui.dialog.is_some(), "{key}: the dialog stays open");+ assert_eq!(app.session.active().unwrap().doc.settings.bleed, [0.0; 4], "{key}: nothing changed");+ }+ }++ #[test]+ fn document_setup_links_edges_and_adjust_layout_applies() {+ let mut app = document_setup_app("points");+ let f = app.run("frame.create", json!({"rect": [36, 36, 576, 756], "content": "text"})).unwrap();+ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 900.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ // Typing in a linked margin sets all four.+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let top = labels.iter().filter(|(t, _, _)| t == "36 pt").map(|(_, r, _)| *r).next().expect("the top margin");+ click_dialog(&mut app, &ctx, screen, top.center());+ let select_all = egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND };+ dialog_frame(&mut app, &ctx, screen, vec![select_all, egui::Event::Text("72 pt".into())]);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(["Top", "Bottom", "Inside", "Outside"].iter().all(|e| d.s(&format!("margin{e}")) == "72 pt"), "linked: {:?}", d.fields);+ // Adjust Layout applies at once, and the frame follows the margins.+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Adjust Layout").center());+ assert!(app.ui.dialog.is_none(), "applied");+ let doc = &app.session.active().unwrap().doc;+ let b = doc.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap().bounds();+ assert!((b.y0 - 72.0).abs() < 1e-6 && doc.page(0).unwrap().margins.outside == 72.0, "{b:?}");+ }++ #[test]+ fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ app.run("table.select", json!({"what": "table"})).unwrap();+ app.run("app.cellOptionsDialog", json!({})).unwrap();+ let ctx = dialog_context("");+ dialog_frame(&mut app, &ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)), vec![]);+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!(d.id, "cellOptions");+ assert_eq!(d.fields["weight"], json!(1.0));+ d.fields.insert("edges".into(), json!(["top", "bottom", "left", "right"]));+ d.fields.insert("gapColor".into(), json!("[Paper]"));+ d.fields.insert("fill".into(), json!("[Black]"));+ d.fields.insert("fillTint".into(), json!(0.2));+ confirm(&mut app).unwrap();+ let st = app.session.active().unwrap();+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();+ let gap = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].gap_color.clone();+ assert_eq!([gap(0, 0, 0), gap(0, 0, 1), gap(1, 1, 2), gap(1, 1, 3)], ["[Paper]"; 4].map(String::from), "outer edges");+ assert_eq!([gap(0, 0, 2), gap(0, 0, 3)], ["[None]"; 2].map(String::from), "inner edges keep theirs");+ assert!(t.cells.iter().all(|c| c.fill == "[Black]" && (c.fill_tint - 0.2).abs() < 1e-6));+ assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");+ }++ #[test]+ fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ app.run("table.select", json!({"what": "table"})).unwrap();+ app.run("table.setCell", json!({"stroke": {"weight": 3, "edges": "innerHorizontal"}})).unwrap();+ app.run("app.cellOptionsDialog", json!({})).unwrap();+ let mut d = app.ui.dialog.take().unwrap();+ d.fields.insert("seed".into(), json!(5));+ let outer = [true, true, true, true, false, false];+ cell_options_edges_changed(&mut app, &mut d, &outer);+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(1.0), &json!(1.0)));+ // A weight typed for the outer edges, then the inner horizontal edges (3 pt) chosen+ // and 1 pt typed: 1 pt differs from what those edges show, so OK applies it.+ d.fields.insert("weight".into(), json!(5.0));+ cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]);+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(5.0), &json!(3.0)));+ d.fields.insert("weight".into(), json!(1.0));+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ let st = app.session.active().unwrap();+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();+ assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]);+ }++ #[test]+ fn preferences_ok_saves_a_story_editor_size_that_loads_back() {+ // `ui.dialog.set` takes any value; a size that isn't finite is saved as `null`.+ let sizes = [(json!("nan"), 20.0), (json!("inf"), 20.0), (json!(null), 20.0), (json!(1e39), 36.0), (json!(3), 8.0), (json!(11), 11.0)];+ for (size, want) in sizes {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.ui.story_editor_size = 20.0;+ app.run("app.preferences", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("storyEditorSize".into(), size);+ confirm(&mut app).unwrap();+ let saved = serde_json::to_vec(&app.ui).unwrap();+ assert_eq!(crate::UiState::from_preferences_json(&saved).unwrap().story_editor_size, want);+ }+ }++ #[test]+ fn preferences_ok_sets_only_the_ruler_units_it_is_given() {+ // `ui.dialog.open` takes any fields, so the vertical units can be missing.+ for (vertical, want) in [(None, "inches"), (Some("points"), "points")] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("document.preferences", json!({"verticalUnits": "inches"})).unwrap();+ let mut fields = json!({"horizontalUnits": "millimeters", "bg.relativeTo": "topOfPage"});+ if let Some(vertical) = vertical {+ fields["verticalUnits"] = json!(vertical);+ }+ app.ui.dialog = Some(Dialog::new("preferences", fields));+ confirm(&mut app).unwrap();+ let units = app.run("document.preferences", json!({})).unwrap();+ assert_eq!((units["horizontalUnits"].as_str(), units["verticalUnits"].as_str()), (Some("millimeters"), Some(want)));+ }+ }++ #[test]+ fn enter_and_escape_close_the_style_menu_not_numbering_and_section_options() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 2})).unwrap();+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };+ for pressed in [egui::Key::Enter, egui::Key::Escape] {+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ // The section's Style menu (the first of the two).+ let style = labels.iter().filter(|(t, r, c)| t.trim() == "1, 2, 3, 4…" && c.contains_rect(*r)).map(|(_, r, _)| *r).next().unwrap();+ click_dialog(&mut app, &ctx, screen, style.center());+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(egui::Popup::is_any_open(&ctx), "the Style menu opened");+ dialog_frame(&mut app, &ctx, screen, vec![key(pressed)]);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(app.ui.dialog.is_some(), "{pressed:?} with the menu open leaves the dialog open");+ assert!(app.session.active().unwrap().doc.sections.iter().all(|s| s.start_number != Some(0)));+ if egui::Popup::is_any_open(&ctx) {+ egui::Popup::close_all(&ctx);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ }+ // With no menu open, Escape closes the dialog.+ dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Escape)]);+ assert!(app.ui.dialog.is_none());+ }++ #[test]+ fn numbering_and_section_options_keep_their_actions_in_view() {+ for language in ["en", "ar"] {+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0)] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = language.into();+ app.run("file.new", json!({"pages": 2})).unwrap();+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ let ctx = dialog_context(language);+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let tr = |s| crate::i18n::tr(language, s);+ for expected in [tr("Numbering & Section Options…").trim_end_matches('…'), tr("OK"), tr("Cancel"), tr("Start Section")] {+ visible_label(&labels, screen, expected);+ }+ if size.x > 1000.0 {+ // Every option fits without scrolling, and choosing one then OK applies it.+ visible_label(&labels, screen, &format!("{} {}", tr("Book Name:"), tr("N/A")));+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("Automatic Page Numbering")).center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("OK")).center());+ assert!(app.ui.dialog.is_none(), "{language}: OK closes the dialog");+ let doc = &app.session.active().unwrap().doc;+ assert!(doc.sections.iter().all(|s| s.start != 0 || s.start_number.is_none()), "{language}: page 1 numbers automatically");+ }+ }+ }+ }++ fn select_all_key() -> egui::Event {+ egui::Event::Key {+ key: egui::Key::A,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() },+ }+ }++ /// The Color Picker over a new document's selected frame, a few frames in.+ fn picker(fields: Value) -> (DesignApp, egui::Context, egui::Rect, u64) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ app.ui.dialog = Some(Dialog::new("colorPicker", fields));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 500.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ (app, ctx, screen, id)+ }++ /// The rightmost painted `text`: the picker's own field, right of egui's colour editor (which+ /// has R/G/B fields of its own).+ fn rightmost(labels: &[(String, egui::Rect, egui::Rect)], text: &str) -> egui::Pos2 {+ labels+ .iter()+ .filter(|(t, _, _)| t.trim() == text)+ .map(|(_, r, _)| r.center())+ .max_by(|a, b| a.x.total_cmp(&b.x))+ .unwrap_or_else(|| panic!("{text} is painted"))+ }++ /// Types `text` one character per frame, with an idle frame after each.+ fn type_slowly(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, text: &str) {+ for ch in text.chars() {+ dialog_frame(app, ctx, screen, vec![egui::Event::Text(ch.into())]);+ dialog_frame(app, ctx, screen, vec![]);+ }+ }++ fn fill(app: &DesignApp, id: u64) -> designcraft_color::Color {+ let d = &app.session.active().unwrap().doc;+ d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap()+ }++ #[test]+ fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() {+ let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ffffff"}));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "ffffff").center());+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "#f5");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f5", "#ffffff"), "half-typed text stays; the colour waits");+ type_slowly(&mut app, &ctx, screen, "9019");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f59019", "#f59019"), "a 7-character #rrggbb commits");+ // Invalid text is replaced by the colour when focus leaves.+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "zz");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#").center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "f59019");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#f59019");+ }++ #[test]+ fn typed_channel_values_are_kept_while_typing() {+ let (mut app, ctx, screen, id) = picker(json!({"target": "fill", "hex": "#010203", "model": "rgb", "rgb": [1, 2, 3]}));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, rightmost(&labels, "1"));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "12.5");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(rightmost(&labels, "12.5").x > rightmost(&labels, "2").x - 1.0, "the typed text stays in the R field");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#0d0203");+ confirm(&mut app).unwrap();+ let designcraft_color::Color::Rgb { r, .. } = fill(&app, id) else { panic!("not RGB") };+ assert!((r - 12.5 / 255.0).abs() < 1e-6, "{r}");+ }++ #[test]+ fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() {+ let cmyk = json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]});+ // Picked by hex: converted to CMYK.+ let (mut app, ctx, screen, id) = picker(cmyk.clone());+ let hex = app.ui.dialog.as_ref().unwrap().s("hex");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, hex.trim_start_matches('#')).center());+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "3366cc");+ confirm(&mut app).unwrap();+ assert!(matches!(fill(&app, id), designcraft_color::Color::Cmyk { .. }), "{:?}", fill(&app, id));+ // A typed C/M/Y/K percent is a percent: M 1 is 1 %.+ let (mut app, ctx, screen, id) = picker(cmyk.clone());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, rightmost(&labels, "50"));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "1");+ confirm(&mut app).unwrap();+ let designcraft_color::Color::Cmyk { c, m, y, k } = fill(&app, id) else { panic!("not CMYK") };+ assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && (y - 1.0).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}");+ // Typed R/G/B values: RGB.+ let (mut app, ctx, screen, id) = picker(cmyk);+ let r = app.ui.dialog.as_ref().unwrap().fields["rgb"][0].as_f64().unwrap();+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, rightmost(&labels, &r.to_string()));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "10");+ confirm(&mut app).unwrap();+ assert!(matches!(fill(&app, id), designcraft_color::Color::Rgb { .. }), "{:?}", fill(&app, id));+ }++ #[test]+ fn ok_without_edits_leaves_the_fill_alone() {+ let (mut app, _, _, id) = picker(json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]}));+ let before = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill.clone();+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill, before);+ }++ #[test]+ fn dialogs_do_not_dim_the_page() {+ let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ff8000"}));+ let time = ctx.input(|i| i.time) + 1.0 / 60.0;+ let output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(&mut app, ui.ctx()));+ fn covers(shape: &egui::Shape, screen: egui::Rect) -> bool {+ match shape {+ egui::Shape::Rect(r) => r.rect.contains_rect(screen) && r.fill.a() > 0,+ egui::Shape::Vec(v) => v.iter().any(|s| covers(s, screen)),+ _ => false,+ }+ }+ assert!(app.ui.dialog.is_some());+ assert!(!output.shapes.iter().any(|s| covers(&s.shape, screen)), "nothing paints over the whole window");+ }++ fn draw(app: &mut DesignApp, ctx: &egui::Context) {+ let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ }++ /// A paragraph styled "Ruled Child", whose Rule Below comes from its parent "Ruled".+ fn ruled_paragraph() -> (DesignApp, Value) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let rule = json!({"on": true, "weight": 3.0, "color": "[Black]", "tint": 0.5, "columnWidth": false, "offset": 4.0, "leftIndent": 6.0, "rightIndent": 2.0});+ app.run("style.paragraph.create", json!({"name": "Ruled", "para": {"ruleBelow": rule}})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Ruled Child", "basedOn": "Ruled"})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("style.paragraph.apply", json!({"name": "Ruled Child"})).unwrap();+ (app, rule)+ }++ fn undo_steps(app: &DesignApp) -> usize {+ app.session.doc().map_or(0, |st| st.history.undo.len())+ }++ #[test]+ fn paragraph_rules_dialog_shows_the_rule_and_applies_one_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.run("app.paragraphRulesDialog", json!({"rule": "ruleBelow"})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.id, "paragraphRules");+ let current = d.fields["current"].clone();+ assert_eq!(shown_rule(&d, "", "ruleBelow", ¤t), rule, "the inherited rule");+ assert_eq!(shown_rule(&d, "", "ruleAbove", ¤t)["on"], false);+ // Pick a colour, as the Color menu does.+ app.ui.dialog.as_mut().unwrap().fields.insert("ruleBelow.color".into(), json!("[Registration]"));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let mut want = rule.clone();+ want["color"] = json!("[Registration]");+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], rule);+ }++ #[test]+ fn paragraph_style_options_edit_one_rule_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"})));+ draw(&mut app, &ctx);+ let resolved = |app: &DesignApp| serde_json::to_value(app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0).unwrap();+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(shown_rule(&d, "p.", "ruleBelow", &resolved(&app)), rule, "inherited from the parent style");+ app.ui.dialog.as_mut().unwrap().fields.insert("p.ruleBelow.weight".into(), json!(1.5));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let mut want = rule.clone();+ want["weight"] = json!(1.5);+ assert_eq!(resolved(&app)["ruleBelow"], want);+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want, "the paragraph follows its style");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(resolved(&app)["ruleBelow"], rule);+ }++ /// Opens Paragraph Style Options on "Ruled Child" at each of `sections`, sets `fields` and+ /// clicks OK; returns the resolved attributes of the paragraph styled with it.+ fn style_section_edit(sections: &[&str], fields: Value) -> Value {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child"})));+ for section in sections {+ app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section));+ draw(&mut app, &ctx);+ }+ for (k, v) in fields.as_object().unwrap() {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.clone(), v.clone());+ }+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let style = app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap();+ let own = serde_json::to_value(&style.para).unwrap();+ for (k, v) in fields.as_object().unwrap() {+ assert_eq!(own[k.trim_start_matches("p.")], *v, "the style sets {k}");+ }+ app.run("type.selectionAttrs", json!({})).unwrap()["para"].clone()+ }++ #[test]+ fn paragraph_style_options_keep_and_border_sections_reach_the_styled_paragraph() {+ let para = style_section_edit(+ &["keep", "border"],+ json!({"p.keepWithNext": 2, "p.keepLinesTogether": true, "p.keepAllLines": false, "p.keepFirst": 3,+ "p.startParagraph": "nextPage", "p.borderOn": true, "p.borderWeights": [2.0, 0.0, 2.0, 0.0]}),+ );+ assert_eq!(para["keepWithNext"], 2);+ assert_eq!(para["keepLinesTogether"], true);+ assert_eq!(para["keepAllLines"], false);+ assert_eq!(para["keepFirst"], 3);+ assert_eq!(para["startParagraph"], "nextPage");+ assert_eq!(para["borderOn"], true);+ assert_eq!(para["borderWeights"], json!([2.0, 0.0, 2.0, 0.0]));+ // Fields not edited keep the resolved value.+ assert_eq!(para["keepLast"], 2);+ assert_eq!(para["ruleBelow"]["weight"], 3.0);+ }++ #[test]+ fn paragraph_style_options_bullets_and_span_sections_reach_the_styled_paragraph() {+ let para = style_section_edit(+ &["bullets", "span"],+ json!({"p.listType": "numbers", "p.numberStyle": "upperRoman", "p.numberExpression": "^#)^t", "p.startAt": 3,+ "p.spanColumns": {"kind": "split", "columns": 3}}),+ );+ assert_eq!(para["listType"], "numbers");+ assert_eq!(para["numberStyle"], "upperRoman");+ assert_eq!(para["numberExpression"], "^#)^t");+ assert_eq!(para["startAt"], 3);+ assert_eq!(para["spanColumns"], json!({"kind": "split", "columns": 3}));+ let props: designcraft_doc::ParaProps = serde_json::from_value(para).unwrap();+ assert_eq!(props.number_label(3), "III)\t");+ }++ #[test]+ fn paragraph_style_options_ignore_optical_margin_is_set_on_ok() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Flush"})).unwrap();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Flush", "section": "indents"})));+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("ignore_optical_margin_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Ignore Optical Margin").click();+ h.run_steps(3);+ h.get_by_label(" OK ").click();+ h.run_steps(3);+ let app = h.state();+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.session.doc().unwrap().doc.styles.para("Flush").unwrap().para.ignore_optical_margin, Some(true));+ }++ #[test]+ fn paragraph_style_options_keep_a_bad_grep_pattern_open_with_the_error() {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "general"})));+ draw(&mut app, &ctx);+ app.ui.dialog.as_mut().unwrap().fields.insert("p.grepStyles".into(), json!([{"style": "[None]", "pattern": "(?<=x"}]));+ let e = confirm(&mut app).unwrap_err();+ assert!(e.contains("bad GREP"), "{e}");+ let d = app.ui.dialog.clone().expect("the dialog stays open");+ assert_eq!((d.s("section").as_str(), d.s("status").contains("bad GREP")), ("grep", true));+ assert!(app.session.doc().unwrap().doc.styles.para("Ruled").unwrap().para.grep_styles.is_none(), "nothing saved");+ draw(&mut app, &ctx);+ }++ #[test]+ fn paragraph_style_options_show_a_refused_rename_on_general_and_trim_a_new_name() {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "rules"})));+ draw(&mut app, &ctx);+ app.ui.dialog.as_mut().unwrap().fields.insert("rename".into(), json!("Ruled Child"));+ let e = confirm(&mut app).unwrap_err();+ let d = app.ui.dialog.clone().expect("the dialog stays open");+ assert_eq!(d.s("section"), "general", "the name field is on General");+ assert!(d.s("status").contains("already exists"), "{e}");++ app.ui.dialog.as_mut().unwrap().fields.insert("rename".into(), json!(" Fresh "));+ app.ui.dialog.as_mut().unwrap().fields.insert("x.tag".into(), json!("h3"));+ confirm(&mut app).unwrap();+ let st = &app.session.doc().unwrap().doc.styles;+ assert!(st.para("Fresh").is_some());+ assert_eq!(st.export_tag("Fresh", false).map(|t| t.tag.as_str()), Some("h3"));+ }++ /// A frame with two paragraphs of [Basic Paragraph]; the first has a local Word Spacing minimum.+ fn two_paragraphs() -> (DesignApp, Value) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One\nTwo"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("type.para", json!({"attrs": {"wordSpaceMin": 0.7}})).unwrap();+ (app, r["story"].clone())+ }++ /// The resolved paragraph attribute `key` of the paragraph at byte `at`.+ fn para_attr(app: &mut DesignApp, story: &Value, at: usize, key: &str) -> Value {+ app.run("text.select", json!({"story": story, "anchor": at, "focus": at})).unwrap();+ app.run("type.selectionAttrs", json!({})).unwrap()["para"][key].clone()+ }++ /// The hyphenation video (Graphd Tutorials, 0:39–1:13): the Paragraph panel menu's+ /// Hyphenation… opens InDesign's Hyphenation Settings for the selected paragraphs. Preview+ /// shows the slider moved to Fewer Hyphens on the page without an undo step, OK makes it one+ /// step on the selected paragraph only, and Cancel puts it back.+ #[test]+ fn hyphenation_settings_preview_apply_and_cancel_on_the_selected_paragraph() {+ let (mut app, story) = two_paragraphs();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));+ let sid = designcraft_doc::StoryId(story.as_u64().unwrap());+ let weight = |app: &DesignApp, para: usize| {+ let d = &app.session.doc().unwrap().doc;+ d.styles.resolve_para(&d.story(sid).unwrap().paras[para]).0.hyph_weight+ };+ assert!(crate::menus::menu_enabled(&app, "app.hyphenationDialog"));+ app.run("app.hyphenationDialog", json!({})).unwrap();+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(+ (d.id.as_str(), d.fields["current"]["hyphWeight"].as_f64(), d.fields["current"]["hyphenate"].as_bool()),+ ("hyphenation", Some(0.5), Some(true))+ );+ for label in [+ "Hyphenation Settings",+ "Hyphenate",+ "Words with at Least:",+ "letters",+ "Hyphen Limit:",+ "hyphens",+ "Hyphenation Zone:",+ "Better Spacing",+ "Fewer Hyphens",+ "Hyphenate Capitalized Words",+ "Hyphenate Last Word",+ "Hyphenate Across Column",+ "Preview",+ ] {+ assert!(labels.iter().any(|(t, _, _)| t == label), "{label}: {labels:?}");+ }+ // Fewer Hyphens (9 of 10) with Preview: on the page, no undo step.+ let before = undo_steps(&app);+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("hyphWeight".into(), json!(0.9));+ d.fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(weight(&app, 0), 0.9, "previewed");+ assert_eq!(undo_steps(&app), before, "a preview is no step");+ // Cancel: back as it was.+ cancel(&mut app);+ assert_eq!(weight(&app, 0), 0.5);+ // Again, and OK: one step, the selected paragraph only.+ app.run("app.hyphenationDialog", json!({})).unwrap();+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("hyphWeight".into(), json!(0.9));+ d.fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ confirm(&mut app).unwrap();+ assert_eq!((weight(&app, 0), weight(&app, 1)), (0.9, 0.5));+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ // Paragraph Style Options › Hyphenation has the same form.+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::story::BASIC_PARAGRAPH, "section": "hyph"})));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for label in ["Hyphenation Zone:", "Better Spacing", "Fewer Hyphens", "Hyphenate Last Word", "Hyphenate Across Column"] {+ assert!(labels.iter().any(|(t, _, _)| t == label), "style options: {label}");+ }+ app.ui.dialog = None;+ app.run("edit.deselectAll", json!({})).unwrap();+ assert!(!crate::menus::menu_enabled(&app, "app.hyphenationDialog"), "no paragraph");+ }++ /// Hyphenate differs across the selection: it shows mixed, and the first click turns it on for+ /// all. Settings the command refuses show why: a preview goes back and isn't retried until they+ /// change, and OK keeps the dialog open.+ /// A mixed Better Spacing ↔ Fewer Hyphens slider: a click on its middle step sets every+ /// selected paragraph to it, though the knob already sat there.+ #[test]+ fn hyphenation_settings_mixed_slider_click_sets_the_step() {+ let (mut app, story) = two_paragraphs();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));+ app.run("type.para", json!({"attrs": {"hyphWeight": 0.2}})).unwrap();+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap();+ app.run("app.hyphenationDialog", json!({})).unwrap();+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let rect = |l: &str| labels.iter().find(|(t, _, _)| t == l).map(|(_, r, _)| *r).unwrap();+ let (better, fewer) = (rect("Better Spacing"), rect("Fewer Hyphens"));+ click_dialog(&mut app, &ctx, screen, egui::pos2((better.right() + fewer.left()) / 2.0, better.center().y));+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphWeight"), Some(&json!(0.5)));+ }++ #[test]+ fn hyphenation_settings_mixed_checkbox_and_refused_settings() {+ let (mut app, story) = two_paragraphs();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0));+ app.run("type.para", json!({"attrs": {"hyphenate": false}})).unwrap();+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap();+ app.run("app.hyphenationDialog", json!({})).unwrap();+ assert!(app.ui.dialog.as_ref().unwrap().fields["current"]["hyphenate"].is_null(), "mixed");+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let at = labels.iter().find(|(t, _, _)| t == "Hyphenate").map(|(_, r, _)| r.left_center() - egui::vec2(10.0, 0.0)).unwrap();+ click_dialog(&mut app, &ctx, screen, at);+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphenate"), Some(&json!(true)), "the first click turns it on");+ // A refused setting (as a control-channel caller could send it): no preview, the reason.+ let before = undo_steps(&app);+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("hyphWeight".into(), json!("heavy"));+ d.fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(!d.fields.contains_key(PREVIEWED) && d.fields.contains_key("status"), "{:?}", d.fields);+ assert!(app.session.doc().unwrap().interaction.is_none(), "the preview went back");+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(app.session.doc().unwrap().interaction.is_none(), "not tried again");+ // OK with it: an error, and the dialog stays open with the reason.+ assert!(confirm(&mut app).is_err());+ let d = app.ui.dialog.as_ref().expect("the dialog stays open");+ assert!(d.fields.contains_key("status"));+ assert_eq!(undo_steps(&app), before);+ // Corrected, it previews and applies.+ app.ui.dialog.as_mut().unwrap().fields.insert("hyphWeight".into(), json!(0.9));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("status"));+ confirm(&mut app).unwrap();+ assert_eq!(para_attr(&mut app, &story, 0, "hyphenate"), true);+ assert_eq!(para_attr(&mut app, &story, 4, "hyphWeight"), 0.9);+ }++ #[test]+ fn justification_dialog_applies_to_a_local_paragraph_and_cancel_changes_nothing() {+ let (mut app, story) = two_paragraphs();+ let ctx = egui::Context::default();+ assert!(crate::menus::menu_enabled(&app, "app.justificationDialog"));+ app.run("app.justificationDialog", json!({})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.id, "justification");+ assert_eq!(d.fields["current"]["wordSpaceMin"], 0.7);+ assert_eq!(d.fields["current"]["wordSpaceDesired"], 1.0);+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.1));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1);+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceMin"), 0.7, "unedited fields stay");+ assert_eq!(para_attr(&mut app, &story, 4, "wordSpaceDesired"), 1.0, "only the selected paragraph");+ let style = app.session.doc().unwrap().doc.styles.resolve_para_style(designcraft_doc::story::BASIC_PARAGRAPH).0.word_space_desired;+ assert_eq!(style, 1.0, "the paragraph style keeps its value");++ // Cancel (Escape) leaves the paragraph alone.+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap();+ app.run("app.justificationDialog", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.2));+ let before = undo_steps(&app);+ let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events: vec![escape],+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ assert!(app.ui.dialog.is_none(), "cancelled");+ assert_eq!(undo_steps(&app), before);+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1);++ app.run("edit.deselectAll", json!({})).unwrap();+ assert!(!crate::menus::menu_enabled(&app, "app.justificationDialog"), "nothing to justify");+ assert!(app.run("app.justificationDialog", json!({})).is_err());+ }++ #[test]+ fn justification_dialog_leaves_mixed_fields_alone_and_refuses_bad_values() {+ let (mut app, story) = two_paragraphs();+ let ctx = egui::Context::default();+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap();+ app.run("app.justificationDialog", json!({})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.fields["current"]["wordSpaceMin"], Value::Null, "mixed shows empty");+ assert_eq!(d.fields["current"]["wordSpaceMax"], 1.33);++ // Out of range, and minimum above desired: an error, the dialog stays open, nothing changes.+ let before = undo_steps(&app);+ for (key, v) in [("wordSpaceMax", 20.0), ("glyphScaleMin", 0.2), ("letterSpaceDesired", f64::NAN)] {+ app.ui.dialog = Some(d.clone());+ app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(v));+ assert!(confirm(&mut app).is_err(), "{key} = {v}");+ assert!(app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("justifyError")), "{key}: the dialog shows why");+ }+ app.ui.dialog = Some(d.clone());+ app.ui.dialog.as_mut().unwrap().fields.insert("letterSpaceMin".into(), json!(0.1));+ assert!(confirm(&mut app).is_err(), "letter spacing minimum above desired");+ draw(&mut app, &ctx);+ assert_eq!(undo_steps(&app), before);++ app.ui.dialog = Some(d);+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceMax".into(), json!(1.5));+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1);+ for (at, min) in [(0, 0.7), (4, 0.8)] {+ assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMax"), 1.5);+ assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMin"), min, "each paragraph keeps its own minimum");+ }+ }++ fn command_app(id: &str, fields: Value) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields));+ app+ }++ #[test]+ fn generic_new_document_preserves_typed_values_and_text_entry() {+ for pages in [json!(2), json!(" 2 ")] {+ let mut app = command_app(+ "file.new",+ json!({+ "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0,+ "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40},+ "title": " ", "status": "internal", "primaryTextFrame": true+ }),+ );+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.page_count(), 2);+ assert!(!doc.settings.facing_pages);+ assert!(doc.title.starts_with("Untitled-"));+ for page in doc.spreads.iter().flat_map(|s| &s.pages) {+ assert!((page.width - 595.2755905511812).abs() < 0.01);+ assert!((page.height - 841.8897637795277).abs() < 0.01);+ assert_eq!(page.columns.gutter, 0.0);+ assert_eq!(page.margins.top, 10.0);+ assert_eq!(page.margins.outside, 40.0);+ }+ // `primaryTextFrame` is documented since #776, so the dialog passes it on (`status` isn't).+ assert!(doc.spreads.iter().any(|s| !s.items.is_empty()), "documented fields reach the command");+ assert!(app.ui.dialog.is_none());+ }+ }++ #[test]+ fn numbering_commands_document_their_fields() {+ let names = |id: &str| command_fields(designcraft_engine::find_command(id).unwrap().params).into_iter().map(|f| f.key).collect::<Vec<_>>();+ assert_eq!(names("layout.section"), ["page", "startNumber", "style", "prefix", "includePrefix", "marker", "remove"]);+ assert_eq!(names("layout.chapterNumbering"), ["style", "start", "source"]);+ }++ #[test]+ fn generic_command_preserves_array_geometry() {+ let mut app = command_app("file.new", json!({}));+ confirm(&mut app).unwrap();+ app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]})));+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap();+ assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0));+ }++ #[test]+ fn generic_explicit_null_uses_the_commands_existing_semantics() {+ // file.new accepts null width by using the selected preset's width.+ for width in [Value::Null, json!("null")] {+ let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "}));+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.title, "Sample layout");+ assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01);+ }+ }++ #[test]+ fn generic_invalid_number_retains_dialog_without_creating_document() {+ let mut app = command_app("file.new", json!({"width": 0}));+ assert!(confirm(&mut app).is_err());+ assert!(app.session.active().is_none());+ let dialog = app.ui.dialog.as_ref().unwrap();+ assert_eq!(dialog.fields["width"], 0);+ assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range"));+ }++ #[test]+ fn style_options_preview_choice_is_remembered_on_reopen() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.paragraph.create", json!({"name":"Tutorial","chars":{"size":10}})).unwrap();+ open_style_options(&mut app, true, "Tutorial");+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("style_preview_remember_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ cancel(h.state_mut());+ open_style_options(h.state_mut(), true, "Tutorial");+ assert!(h.state().ui.dialog.as_ref().unwrap().b("preview"), "Preview stays checked on reopen");+ }++ #[test]+ fn style_options_preview_updates_all_uses_cancels_and_commits_once() {+ use egui_kittest::{Harness, kittest::Queryable};+ for paragraph in [true, false] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect":[36,36,300,300],"content":"text","text":"First\nSecond"})).unwrap();+ app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":12})).unwrap();+ let kind = if paragraph { "paragraph" } else { "character" };+ app.run(&format!("style.{kind}.create"), json!({"name":"Tutorial","chars":{"size":10}})).unwrap();+ app.run(&format!("style.{kind}.apply"), json!({"name":"Tutorial"})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let undo = app.session.doc().unwrap().history.undo.len();+ let journal = app.session.journal.len();+ open_style_options(&mut app, paragraph, "Tutorial");+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::unique("style_preview_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(18));+ h.run_steps(3);+ let app = h.state_mut();+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 18.0);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);+ assert_eq!(app.session.journal.len(), journal);+ // Repeated previews replace each other, never accumulate undo entries.+ app.ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(20));+ h.run_steps(3);+ assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 20.0);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ cancel(h.state_mut());+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo);+ open_style_options(h.state_mut(), paragraph, "Tutorial");+ let d = h.state_mut().ui.dialog.as_mut().unwrap();+ d.fields.insert("preview".into(), json!(true));+ d.fields.insert("c.size".into(), json!(24));+ h.run_steps(3);+ confirm(h.state_mut()).unwrap();+ assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1);+ // Both paragraphs/character runs still use the globally edited definition.+ for pos in [0, 6] {+ h.state_mut().run("text.select", json!({"story":f["story"],"anchor":pos,"focus":pos+1})).unwrap();+ assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 24.0);+ }+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ }+ }++ #[test]+ fn style_preview_refuses_justification_spacing_ok_would_refuse() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let mut d = Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::BASIC_PARAGRAPH, "preview": true, "p.wordSpaceDesired": 1.1}));+ style_options_preview(&mut app, &mut d);+ assert_ne!(app.session.doc().unwrap().doc, before, "a valid value previews");+ // Minimum above Desired: the page goes back and the dialog says why.+ d.fields.insert("p.wordSpaceMin".into(), json!(1.5));+ style_options_preview(&mut app, &mut d);+ assert_eq!(app.session.doc().unwrap().doc, before);+ assert!(d.s("status").contains("Word Spacing"), "{:?}", d.fields.get("status"));+ assert!(app.session.doc().unwrap().interaction.is_none());+ }++ #[test]+ fn invalid_style_preview_leaves_the_starting_document_and_can_be_cancelled() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.character.create", json!({"name":"Emphasis"})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let mut d = Dialog::new("characterStyleOptions", json!({"name":"Emphasis","preview":true,"basedOn":"Emphasis"}));+ style_options_preview(&mut app, &mut d);+ assert!(d.fields.contains_key("status"));+ assert_eq!(app.session.doc().unwrap().doc, before);+ app.ui.dialog = Some(d);+ cancel(&mut app);+ assert_eq!(app.session.doc().unwrap().doc, before);+ assert!(app.session.doc().unwrap().interaction.is_none());+ }++ #[test]+ fn style_preview_rejects_conflicting_scalar_and_nested_rule_fields_without_panicking() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let mut dialog = Dialog::new(+ "paragraphStyleOptions",+ json!({+ "name": designcraft_doc::BASIC_PARAGRAPH, "preview": true,+ "p.ruleAbove": false, "p.ruleAbove.weight": 2+ }),+ );+ style_options_preview(&mut app, &mut dialog);+ assert!(dialog.fields.contains_key("status"));+ assert_eq!(app.session.doc().unwrap().doc, before);+ app.ui.dialog = Some(dialog);+ cancel(&mut app);+ assert!(app.session.doc().unwrap().interaction.is_none());+ }++ #[test]+ fn text_frame_options_set_columns_baseline_and_wrap_as_indesign_does() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ // A 300 pt frame, 2 columns, 12 pt gutter (picas in the dialog).+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "gutter": 12})).unwrap();+ let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone();+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(&app, &mut d);+ // Fixed Number shows each column's width: (300 - 12) / 2 = 144 pt.+ assert_eq!((d.s("columnsKind"), d.s("columnWidth"), d.s("firstBaseline")), ("fixedNumber".into(), "12p0".into(), "ascent".into()));+ for (k, v) in [+ ("columnsKind", json!("fixedWidth")),+ ("columnWidth", json!("10p0")),+ ("firstBaseline", json!("capHeight")),+ ("firstBaselineMin", json!("0p6")),+ ("balanceColumns", json!(true)),+ ("ignoreWrap", json!(true)),+ ] {+ d.fields.insert(k.into(), v);+ }+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ let o = opts(&app);+ assert_eq!(o.columns_kind, designcraft_doc::ColumnsKind::FixedWidth);+ assert_eq!((o.column_width, o.first_baseline_min, o.columns), (120.0, 6.0, 2));+ assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight);+ assert!(o.balance_columns && o.ignore_wrap);+ // Fixed Number again: the width isn't sent.+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(&app, &mut d);+ assert_eq!(d.s("columnWidth"), "10p0", "Fixed Width shows its own width");+ d.fields.insert("columnsKind".into(), json!("fixedNumber"));+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0));+ }++ #[test]+ fn baseline_grid_increment_error_explains_the_positive_measure_rule() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ for increment in ["0", "-1 pt", "not a measure"] {+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(&app, &mut d);+ d.fields.insert("customGrid".into(), json!(true));+ d.fields.insert("gridIncrement".into(), json!(increment));+ app.ui.dialog = Some(d);+ let error = confirm(&mut app).unwrap_err().to_string();+ assert!(error.contains("the baseline grid increment must be a measure greater than zero"), "{increment}: {error}");+ assert!(app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid.is_none());+ }+ }++ #[test]+ fn text_frame_options_set_a_custom_baseline_grid_relative_to() {+ use designcraft_doc::{FrameBaselineGrid, FrameGridRelative};+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ let grid = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid;+ let open = |app: &mut DesignApp, fields: &[(&str, Value)]| {+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(app, &mut d);+ for (k, v) in fields {+ d.fields.insert((*k).into(), v.clone());+ }+ app.ui.dialog = Some(d);+ confirm(app)+ };+ app.run("selection.set", json!({"ids": [id.0]})).unwrap();+ // Turned on, the grid takes the shown start and increment (the document grid's: 3p0 and 1p0).+ open(&mut app, &[("customGrid", json!(true)), ("gridRelativeTo", json!("frame"))]).unwrap();+ assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 36.0, increment: 12.0, relative_to: FrameGridRelative::TopOfFrame }));+ // The dialog shows the frame's grid; changing Relative To keeps its start and increment.+ open(&mut app, &[("gridStart", json!("0p10"))]).unwrap();+ open(&mut app, &[("gridRelativeTo", json!("inset"))]).unwrap();+ assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 10.0, increment: 12.0, relative_to: FrameGridRelative::TopInset }));+ open(&mut app, &[("customGrid", json!(false))]).unwrap();+ assert_eq!(grid(&app), None);+ }++ #[test]+ fn text_frame_options_change_only_what_was_edited() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "inset": [1, 2, 3, 4]})).unwrap();+ let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone();+ let before = opts(&app);+ let open = |app: &mut DesignApp, fields: &[(&str, Value)]| {+ app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({})));+ let mut d = app.ui.dialog.take().unwrap();+ seed_text_frame_options(app, &mut d);+ for (k, v) in fields {+ d.fields.insert((*k).into(), v.clone());+ }+ app.ui.dialog = Some(d);+ confirm(app)+ };+ // OK without edits changes nothing (no undo step either).+ assert_eq!(open(&mut app, &[]).unwrap(), Value::Null);+ assert_eq!(opts(&app), before);+ // The rule's weight is in points; unequal insets the user didn't touch stay.+ open(&mut app, &[("columnRule", json!(true)), ("columnRuleWeight", json!("6"))]).unwrap();+ let o = opts(&app);+ assert!(o.column_rule && o.column_rule_weight == 6.0, "{o:?}");+ assert_eq!((o.inset, o.columns, o.gutter), (before.inset, before.columns, before.gutter));+ // One of the rule's insets edited: the other rule settings stay.+ open(&mut app, &[("columnRuleBottomInset", json!("0p9")), ("columnRuleTint", json!("40"))]).unwrap();+ let o = opts(&app);+ assert_eq!((o.column_rule_bottom_inset, o.column_rule_top_inset, o.column_rule_offset, o.column_rule_weight), (9.0, 0.0, 0.0, 6.0));+ assert!((o.column_rule_tint - 0.4).abs() < 1e-6 && o.column_rule);+ // One inset side edited: the others keep their values.+ open(&mut app, &[("insetLeft", json!("1p0"))]).unwrap();+ assert_eq!(opts(&app).inset, [1.0, 12.0, 3.0, 4.0]);+ open(&mut app, &[("balanceColumns", json!(true))]).unwrap();+ let o = opts(&app);+ assert!(o.balance_columns && o.column_rule && o.columns == 2, "{o:?}");+ // An unknown swatch is an error and the dialog stays open.+ let e = open(&mut app, &[("columnRuleColor", json!("Mauve"))]).unwrap_err();+ assert!(e.contains("Mauve") && app.ui.dialog.is_some(), "{e}");+ assert_eq!(opts(&app).column_rule_color, designcraft_color::swatch::BLACK);+ // Each OK is one undo step.+ for _ in 0..4 {+ app.run("edit.undo", json!({})).unwrap();+ }+ assert_eq!(opts(&app), before);+ }++ #[test]+ fn toc_dialog_adds_a_style_and_ok_makes_the_table_of_contents() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.newSample", json!({})).unwrap();+ crate::menus::activate(&mut app, "toc.generate", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(TOC));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in+ ["Table of Contents", "Title:", "Include Paragraph Styles:", "Other Styles:", "« Add", "Remove »", "Replace Existing Table of Contents"]+ {+ visible_label(&labels, screen, expected);+ }+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Headline").center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "« Add").center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["Entry Style:", "TOC Level 1", "After Entry", "Between Entry and Number:", "Level:"] {+ visible_label(&labels, screen, expected);+ }+ let undo = app.session.doc().unwrap().history.undo.len();+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center());+ assert!(app.ui.dialog.is_none());+ let d = &app.session.doc().unwrap().doc;+ let toc = d.toc.clone().unwrap();+ assert_eq!(toc.entries, vec![designcraft_doc::TocEntry::new("Headline", 1)]);+ let text = &d.story(toc.story).unwrap().text;+ assert!(text.starts_with("Contents\n") && text.contains("\nNotes on the Grid\t"), "{text}");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);+ // Reopened, the dialog shows the table of contents and replaces it.+ crate::menus::activate(&mut app, "toc.generate", &Value::Null);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(d.b("replace"));+ assert_eq!(toc_rows(d).iter().map(|r| r.style.as_str()).collect::<Vec<_>>(), ["Headline"]);+ }++ #[test]+ fn margins_and_columns_link_arithmetic_preview_and_one_undo_step() {+ // Adobe's "Set up a modern magazine layout" (1:41–3:04): linked margins to 0.4375 in, then+ // 5 columns with a 0.1875 in gutter, unlinked, and "*2" typed after the outside margin.+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"preset": "A4", "pages": 3, "facingPages": true, "margins": 36})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)));+ open_margins_and_columns(&mut app);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ let mut labels = vec![];+ for _ in 0..3 {+ labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ for expected in+ ["Margins and Columns", "Margins", "Top:", "Bottom:", "Inside:", "Outside:", "Columns", "Number:", "Gutter:", "Adjust Layout", "Preview"]+ {+ visible_label(&labels, screen, expected);+ }+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(d.b("link"), "four equal margins open linked");+ // Linked: one margin typed is all four.+ app.ui.dialog.as_mut().unwrap().fields.insert("marginTop".into(), json!("0.4375 in"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(MARGIN_FIELDS.iter().all(|(k, _, _)| d.s(k) == "0.4375 in"), "{:?}", d.fields);+ // Preview: the page changes, with no undo step.+ let undo = app.session.doc().unwrap().history.undo.len();+ app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let top = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].pages[0].margins.top;+ assert!((top(&app) - 31.5).abs() < 1e-6, "previewed: {}", top(&app));+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);+ // Unlinked (the link button), the outside margin alone: "*2" typed after it is worked out+ // when the field is left.+ app.ui.dialog.as_mut().unwrap().fields.insert("link".into(), json!(false));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };+ let field = labels+ .iter()+ .filter(|(t, _, _)| t.trim() == "0.4375 in")+ .map(|(_, r, _)| *r)+ .max_by(|a, b| (a.max.x + a.max.y).total_cmp(&(b.max.x + b.max.y)))+ .unwrap();+ click_dialog(&mut app, &ctx, screen, field.center());+ dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::End), egui::Event::Text("*2".into())]);+ dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Tab)]);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let d = app.ui.dialog.as_ref().unwrap();+ assert!(+ !d.s("marginOutside").contains('*') && (d.m("marginOutside").unwrap() - 63.0).abs() < 1e-6,+ "worked out on leaving the field: {}",+ d.s("marginOutside")+ );+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("link".into(), json!(false));+ for (k, v) in [("marginOutside", "0.4375 in*2"), ("columns", "5"), ("gutter", "0.1875 in"), ("target", "all")] {+ d.fields.insert(k.into(), json!(v));+ }+ dialog_frame(&mut app, &ctx, screen, vec![]);+ confirm(&mut app).unwrap();+ let pg = app.session.doc().unwrap().doc.spreads[1].pages[0].clone();+ assert_eq!((pg.margins.top, pg.margins.outside, pg.columns.count), (31.5, 63.0, 5));+ assert!((pg.columns.gutter - 13.5).abs() < 1e-6);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");+ // Cancel after a preview puts the page back.+ open_margins_and_columns(&mut app);+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("preview".into(), json!(true));+ d.fields.insert("columns".into(), json!("2"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ cancel(&mut app);+ assert_eq!(app.session.doc().unwrap().doc.spreads[1].pages[0].columns.count, 5);+ }++ #[test]+ fn create_guides_reads_like_indesigns_and_previews() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 1, "facingPages": false})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)));+ open_create_guides(&mut app);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ let mut labels = vec![];+ for _ in 0..3 {+ labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ for expected in ["Create Guides", "Rows", "Columns", "Options", "Fit Guides to:", "Margins", "Page", "Remove Existing Ruler Guides", "Preview"] {+ visible_label(&labels, screen, expected);+ }+ // Rows and Columns side by side.+ let (r, c) = (visible_label(&labels, screen, "Rows"), visible_label(&labels, screen, "Columns"));+ assert!((r.center().y - c.center().y).abs() < 2.0 && r.center().x < c.center().x);+ // Thirds, single guides, fitted to the page: clicking the Page radio.+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Page").center());+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!(d.s("fitTo"), "page");+ d.fields.insert("rows".into(), json!("3"));+ d.fields.insert("rowGutter".into(), json!("0"));+ d.fields.insert("preview".into(), json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let guides = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].pages[0].guides.len();+ assert_eq!(guides(&app), 2, "previewed");+ confirm(&mut app).unwrap();+ assert_eq!(guides(&app), 2, "made once");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(guides(&app), 0, "one undo step");+ }++ fn dialog_context(language: &str) -> egui::Context {+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx, language);+ crate::theme::apply(&ctx, &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default()));+ ctx+ }++ fn dialog_frame(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, events: Vec<egui::Event>) -> Vec<(String, egui::Rect, egui::Rect)> {+ let time = ctx.input(|i| i.time) + 1.0 / 60.0;+ let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| {+ show(app, ui.ctx());+ });+ output.textures_delta.clear();+ fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) {+ match shape {+ egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)),+ egui::Shape::Vec(shapes) => {+ for s in shapes {+ collect(s, clip, labels);+ }+ }+ _ => {}+ }+ }+ let mut labels = Vec::new();+ for shape in output.shapes {+ collect(&shape.shape, shape.clip_rect, &mut labels);+ }+ labels+ }++ fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect {+ let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted"));+ assert!(screen.contains_rect(*rect), "{expected} must stay on screen: {rect:?}");+ assert!(clip.contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}");+ *rect+ }++ fn click_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2) {+ for pressed in [true, false] {+ dialog_frame(+ app,+ ctx,+ screen,+ vec![+ egui::Event::PointerMoved(pos),+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ }++ fn scroll_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2, delta: egui::Vec2) {+ dialog_frame(+ app,+ ctx,+ screen,+ vec![+ egui::Event::PointerMoved(pos),+ egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta,+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ source: egui::MouseWheelSource::Unknown,+ },+ ],+ );+ // Let smooth wheel scrolling and scrollbar visibility settle before clicking.+ for _ in 0..30 {+ dialog_frame(app, ctx, screen, vec![]);+ }+ }++ fn scope_control(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value {+ let (request, _reply) = crate::control::ControlRequest::new(method, params);+ let crate::control::Outcome::Done(value) = crate::control::handle(app, ctx, &request) else { panic!("ordinary control response") };+ assert_eq!(value["ok"], true, "{value}");+ value["result"].clone()+ }++ fn scope_click(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, label: &str) {+ let labels = dialog_frame(app, ctx, screen, vec![]);+ let pos = visible_label(&labels, screen, label).center();+ click_dialog(app, ctx, screen, pos);+ }++ fn scope_dialog() -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {+ scope_dialog_with_selection("red red | red", 7)+ }++ fn scope_dialog_with_selection(text: &str, end: usize) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {+ scope_dialog_with_tool(text, end, None)+ }++ fn scope_dialog_with_tool(text: &str, end: usize, tool: Option<&str>) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = "en".into();+ app.run("file.new", json!({})).unwrap();+ let frame = app.run("frame.create", json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap();+ let sid = designcraft_engine::doc::StoryId(frame["story"].as_u64().unwrap());+ let ctx = dialog_context("en");+ if let Some(tool) = tool {+ scope_control(&mut app, &ctx, "ui.tool.select", json!({"tool": tool}));+ }+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": end})).unwrap();+ app.run("app.findChange", json!({})).unwrap();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ for (field, value) in [("find", "red"), ("change", "unused")] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ scope_click(&mut app, &ctx, screen, "document");+ scope_click(&mut app, &ctx, screen, "selection");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), "selection");+ (app, ctx, screen, sid)+ }++ fn scope_selected(app: &DesignApp, sid: designcraft_engine::doc::StoryId, a: usize, b: usize) {+ let t = app.session.doc().unwrap().selection.text.unwrap();+ assert_eq!((t.story, t.range(), t.cell), (sid, a..b, None));+ }++ fn scope_state_unchanged(app: &DesignApp, before: &designcraft_engine::DocState) {+ let after = app.session.doc().unwrap();+ assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc));+ assert_eq!(after.uid, before.uid);+ assert_eq!(after.revision, before.revision);+ assert_eq!(after.selection, before.selection);+ assert_eq!(after.history.limit, before.history.limit);+ for (actual, expected) in [(&after.history.undo, &before.history.undo), (&after.history.redo, &before.history.redo)] {+ assert_eq!(actual.len(), expected.len());+ for (a, b) in actual.iter().zip(expected) {+ assert_eq!(a.label, b.label);+ assert_eq!(a.selection, b.selection);+ assert!(std::sync::Arc::ptr_eq(&a.doc, &b.doc));+ }+ }+ }++ #[test]+ fn find_scope_dialog_control_effective_noops_retain_bounds() {+ for (field, value) in [("objectMode", json!(false)), ("story", Value::Null)] {+ let (mut app, ctx, screen, sid) = scope_dialog();+ assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key(field));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], value);+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);+ }+ }++ #[test]+ fn find_scope_dialog_explicit_story_ignored_scope_preserves_grep_cursor() {+ for physical in [false, true] {+ for (text, pattern, hits, changed) in [+ ("é", "é|(?:)", vec![(0, 2)], "X"),+ ("é🙂", "é|(?:)", vec![(0, 2), (6, 6)], "X🙂X"),+ ("é🙂", "(?:)", vec![(0, 0), (2, 2), (6, 6)], "XéX🙂X"),+ ] {+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection(text, 0);+ for (field, value) in [("find", json!(pattern)), ("change", json!("X")), ("story", json!(sid.0))] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ scope_click(&mut app, &ctx, screen, "GREP");+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len()));+ for &(a, b) in &hits {+ scope_click(&mut app, &ctx, screen, "Find Next");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "Found");+ scope_selected(&app, sid, a, b);+ let before = app.session.doc().unwrap().clone();+ let cur = app.ui.dialog.as_ref().unwrap().s("scope");+ let next = if cur == "selection" { "document" } else { "selection" };+ if physical {+ scope_click(&mut app, &ctx, screen, &cur);+ scope_click(&mut app, &ctx, screen, next);+ } else {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next}));+ }+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), next);+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["story"], json!(sid.0));+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len()));+ }+ scope_click(&mut app, &ctx, screen, "Find Next");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");+ // An ignored scope change must not revive an exhausted endpoint either.+ let before = app.session.doc().unwrap().clone();+ let cur = app.ui.dialog.as_ref().unwrap().s("scope");+ let next = if cur == "selection" { "document" } else { "selection" };+ if physical {+ scope_click(&mut app, &ctx, screen, &cur);+ scope_click(&mut app, &ctx, screen, next);+ } else {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next}));+ }+ scope_click(&mut app, &ctx, screen, "Find Next");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} replacement(s) made", hits.len()));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, changed);+ }+ }+ }++ #[test]+ fn find_scope_dialog_explicit_story_transitions_reset_cursor() {+ for remove_override in [false, true] {+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection("é🙂", 0);+ let other = app.run("frame.create", json!({"rect": [180, 36, 100, 100], "content": "text", "text": "other"})).unwrap();+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();+ for (field, value) in [("find", json!("(?:)")), ("story", json!(sid.0))] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ scope_click(&mut app, &ctx, screen, "GREP");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 0);+ let before = app.session.doc().unwrap().clone();+ let value = if remove_override { Value::Null } else { other["story"].clone() };+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": value}));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0}));+ scope_state_unchanged(&app, &before);+ // Away and back still releases continuation even if no Find command intervenes.+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 0);+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 2, 2);+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "é🙂");+ let other_sid = designcraft_engine::doc::StoryId(other["story"].as_u64().unwrap());+ assert_eq!(app.session.doc().unwrap().doc.story(other_sid).unwrap().text, "other");+ }+ }++ #[test]+ fn find_scope_dialog_control_mode_changes_release_bounds() {+ for object_mode in [false, true] {+ let (mut app, ctx, _, sid) = scope_dialog();+ if object_mode {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": true}));+ }+ // Direct Session consumers share the retained domain even while Object is shown.+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));+ assert_eq!(count.as_array().unwrap().len(), 2);+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.next", "params": p}));+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": !object_mode}));+ assert_eq!(app.ui.dialog.as_ref().unwrap().b("objectMode"), !object_mode);+ scope_state_unchanged(&app, &before);+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));+ assert_eq!(changed, json!({"count": 1}));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ }+ }++ #[test]+ fn find_scope_dialog_tool_replacement_releases_bounds() {+ for (tool, replacement) in [("page", "cmd:layout.pageSize"), ("rectangleFrame", "frameSize")] {+ let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool));+ assert_eq!(app.session.tool_id(), tool);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ let active = (app.session.active_index(), app.session.documents().len());+ let off = app.session.layout().xf(designcraft_engine::doc::SpreadRef::Doc(0)).translation();+ let x = off.x + before.doc.spreads[0].pages[0].x + 200.0;+ let y = off.y + 200.0;+ // The Page tool opens Page Size on a double-click (a click selects the page).+ let events = if tool == "page" {+ json!([{"kind": "doubleclick", "x": x, "y": y}])+ } else {+ json!([{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}])+ };+ // Real tool -> Action::Dialog -> after_engine; no injected UI request.+ scope_control(&mut app, &ctx, "ui.pointer", json!({"events": events}));+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, replacement);+ assert!(app.session.ui_requests.is_empty());+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Cancel");+ assert!(app.ui.dialog.is_none());+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ scope_state_unchanged(&app, &before);+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));+ assert_eq!(changed, json!({"count": 1}));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);+ }+ }++ #[test]+ fn find_scope_dialog_tool_without_replacement_retains_bounds() {+ for tool in ["page", "rectangleFrame"] {+ let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ let fields = app.ui.dialog.as_ref().unwrap().fields.clone();+ scope_control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "move", "x": 200, "y": 200}]}));+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange");+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields);+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ }+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn find_scope_dialog_native_pdf_replacement_releases_bounds() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("three.pdf");+ std::fs::write(&path, crate::browser_import_tests::pdf()).unwrap();+ for dismissal in ["Cancel", "Escape", "control"] {+ let (mut app, ctx, screen, sid) = scope_dialog();+ let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let seen_pick = picked.clone();+ let seen_read = read.clone();+ let pick_path = path.to_string_lossy().to_string();+ let read_path = pick_path.clone();+ app.answer_dialogs(move |request| {+ assert_eq!(place_filter(request), Some("Graphics and text"));+ seen_pick.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ craft_dialogs::Answer::Paths(vec![pick_path.clone().into()])+ });+ app.services.read = Some(Box::new(move |path| {+ assert_eq!(path, read_path);+ seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ std::fs::read(path).map_err(|e| e.to_string())+ }));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ let active = (app.session.active_index(), app.session.documents().len());+ // Exercise engine.execute -> UiRequest::Pick -> native host PDF replacement.+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}}));+ app.settle_dialogs();+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1);+ let dialog = app.ui.dialog.as_ref().unwrap();+ assert_eq!(dialog.id, "pdfImport");+ assert_eq!(dialog.s("path"), path.to_string_lossy());+ assert_eq!(dialog.fields["pages"], 3);+ assert_eq!(dialog.s("page"), "1");+ assert!(!dialog.b("async"));+ assert_eq!(dialog.fields["target"], json!(before.uid));+ assert!(app.session.ui_requests.is_empty());+ assert!(app.pending_pdf.is_none());+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ match dismissal {+ "Cancel" => scope_click(&mut app, &ctx, screen, "Cancel"),+ "Escape" => {+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key {+ key: egui::Key::Escape,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers::NONE,+ }],+ );+ }+ "control" => {+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));+ }+ _ => panic!("known dismissal"),+ }+ assert!(app.ui.dialog.is_none());+ assert!(app.pending_pdf.is_none());+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ scope_state_unchanged(&app, &before);+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));+ assert_eq!(changed, json!({"count": 1}));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);+ }+ }++ /// The first file type an open dialog offers: Place's is "Graphics and text".+ fn place_filter(request: &craft_dialogs::Request) -> Option<&str> {+ let craft_dialogs::Request::File(dialog) = request else { return None };+ dialog.filters.first().map(|filter| filter.name.as_str())+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn find_scope_dialog_native_picker_cancel_retains_bounds() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let seen = picked.clone();+ app.answer_dialogs(move |request| {+ assert_eq!(place_filter(request), Some("Graphics and text"));+ seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ craft_dialogs::Answer::Cancelled+ });+ let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let seen_read = read.clone();+ app.services.read = Some(Box::new(move |_| {+ seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Err("canceled picker must not read".into())+ }));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().clone();+ let active = (app.session.active_index(), app.session.documents().len());+ let fields = app.ui.dialog.as_ref().unwrap().fields.clone();+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}}));+ app.settle_dialogs();+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 0);+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange");+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields);+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);+ scope_state_unchanged(&app, &before);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);+ }++ #[test]+ fn find_scope_dialog_exact_baseline_buttons() {+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection("red red", 3);+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red");+ }++ #[test]+ fn find_scope_dialog_grep_tab_alone_restarts_original_selection() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "GREP");+ assert!(app.ui.dialog.as_ref().unwrap().b("grep"));+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("find"), "red");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Text");+ assert!(!app.ui.dialog.as_ref().unwrap().b("grep"));+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ }++ #[test]+ fn find_scope_dialog_buttons_retain_nonempty_hits_and_change_all() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ let history = app.session.doc().unwrap().history.undo.len();+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ scope_click(&mut app, &ctx, screen, "Find Next");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);+ scope_click(&mut app, &ctx, screen, "Cancel");+ assert!(app.ui.dialog.is_none());+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");+ app.run("edit.redo", json!({})).unwrap();+ let native = app.run("file.serialize", json!({})).unwrap();+ app.run("file.openBytes", json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap();+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ }++ fn scope_confirm_case(action: &str) {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Count");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ match action {+ "OK" => scope_click(&mut app, &ctx, screen, "OK"),+ "Enter" => {+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],+ );+ }+ "control" => {+ assert_eq!(scope_control(&mut app, &ctx, "ui.dialog.confirm", json!({}))["count"], 2);+ }+ _ => panic!("known confirmation route"),+ }+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");+ // The closed dialog cannot leave its old seven-byte range for a later direct query.+ let matches = app.run("find.find", json!({"find": "blue", "scope": "selection"})).unwrap();+ assert_eq!(matches.as_array().unwrap().len(), 0);+ }++ #[test]+ fn find_scope_dialog_ok_consumes_retained_bounds() {+ scope_confirm_case("OK");+ }++ #[test]+ fn find_scope_dialog_enter_consumes_retained_bounds() {+ scope_confirm_case("Enter");+ }++ #[test]+ fn find_scope_dialog_control_confirm_consumes_retained_bounds() {+ scope_confirm_case("control");+ }++ #[test]+ fn find_scope_dialog_query_reselection_cancel_and_reopen() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true}));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "r.d"}));+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 7})).unwrap();+ app.run("find.next", json!({"find": "red", "scope": "selection"})).unwrap();+ scope_control(&mut app, &ctx, "ui.dialog.open", json!({"id": "findChange", "fields": {"find": "red", "scope": "selection"}}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");+ app.run("text.select", json!({"story": sid.0, "anchor": 4, "focus": 7})).unwrap();+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 4, 7);+ app.run("app.findChange", json!({})).unwrap();+ for (field, value) in [("find", "red"), ("scope", "selection")] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));+ }+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");+ }++ #[test]+ fn find_scope_dialog_word_reselection_limits_count_and_change_buttons() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let selected = app.session.doc().unwrap().selection.clone();+ let frame = selected.text.unwrap().frame.unwrap();+ let point = {+ let st = app.session.doc().unwrap();+ let cs = app.session.cache.get(&st.doc, sid, None);+ let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap();+ let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5);+ assert_eq!(cs.frames[fi].frame, frame);+ assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1));+ let loc = st.doc.find(frame).unwrap();+ st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner+ };+ let before = app.session.doc().unwrap().doc.clone();+ let revision = app.session.doc().unwrap().revision;+ app.run("text.selectWord", json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap();+ assert_eq!(app.session.doc().unwrap().selection, selected);+ assert!(app.session.doc().unwrap().revision > revision, "a new revision");+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn find_scope_dialog_failed_native_drop_alert_releases_bounds() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("broken.designcraft");+ std::fs::write(&path, b"not a native document").unwrap();+ for dismissal in ["OK", "Escape", "control"] {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ let before = app.session.doc().unwrap().doc.clone();+ let selected = app.session.doc().unwrap().selection.clone();+ let revision = app.session.doc().unwrap().revision;+ let history = app.session.doc().unwrap().history.undo.len();+ let uid = app.session.doc().unwrap().uid;+ let error = app.open_dropped(&path.to_string_lossy()).unwrap_err();+ let alert = app.ui.dialog.as_ref().unwrap();+ assert_eq!(alert.id, "alert");+ assert_eq!(alert.s("title"), "Can't Open the File");+ assert_eq!(alert.s("message"), error);+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));+ assert_eq!(app.session.doc().unwrap().selection, selected);+ assert_eq!(app.session.doc().unwrap().revision, revision);+ assert_eq!(app.session.doc().unwrap().uid, uid);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);+ match dismissal {+ "OK" => scope_click(&mut app, &ctx, screen, "OK"),+ "Escape" => {+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key {+ key: egui::Key::Escape,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers::NONE,+ }],+ );+ }+ "control" => {+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));+ }+ _ => panic!("known dismissal"),+ }+ assert!(app.ui.dialog.is_none());+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ assert_eq!(app.run("find.find", p.clone()).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ assert_eq!(app.run("find.change", p).unwrap(), json!({"count": 1}));+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);+ }+ }++ #[test]+ fn find_scope_dialog_child_errors_and_explicit_parent() {+ let (mut app, ctx, screen, sid) = scope_dialog();+ app.run("text.select", json!({"story": sid.0, "anchor": 13, "focus": 13})).unwrap();+ app.run("table.insert", json!({"rows": 1, "cols": 1})).unwrap();+ app.run("text.insert", json!({"text": "red child", "raw": true})).unwrap();+ let child = app.session.doc().unwrap().selection.text.unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let selection = app.session.doc().unwrap().selection.clone();+ let history = app.session.doc().unwrap().history.undo.len();+ for label in ["Count", "Find Next", "Change All"] {+ scope_click(&mut app, &ctx, screen, label);+ assert!(app.ui.dialog.as_ref().unwrap().s("status").contains("not supported"));+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));+ assert_eq!(app.session.doc().unwrap().selection, selection);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);+ }+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0}));+ scope_click(&mut app, &ctx, screen, "Count");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 match(es)");+ scope_click(&mut app, &ctx, screen, "Change All");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 replacement(s) made");+ assert_eq!(app.session.doc().unwrap().doc.text_story(sid, child.cell).unwrap().text, "red child");+ assert!(app.session.doc().unwrap().doc.story(sid).unwrap().text.starts_with("blue blue | blue"));+ }++ #[test]+ fn find_scope_dialog_error_confirmation_and_escape_release_context() {+ for escape in [false, true] {+ let (mut app, ctx, screen, sid) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Find Next");+ scope_selected(&app, sid, 0, 3);+ if escape {+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],+ );+ } else {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "["}));+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true}));+ scope_click(&mut app, &ctx, screen, "OK");+ }+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);+ }+ }++ #[test]+ fn find_scope_dialog_domain_and_object_changes_release_original_range() {+ for route in ["scope", "object", "menu", "command"] {+ let (mut app, ctx, screen, _) = scope_dialog();+ scope_click(&mut app, &ctx, screen, "Find Next");+ match route {+ "scope" => {+ for scope in ["story", "selection"] {+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": scope}));+ }+ }+ "object" => {+ scope_click(&mut app, &ctx, screen, "Object");+ scope_click(&mut app, &ctx, screen, "Text");+ }+ "menu" => crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null),+ "command" => {+ app.run("app.newDocumentDialog", json!({})).unwrap();+ }+ _ => panic!("known reset route"),+ }+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);+ }+ }++ #[test]+ fn dialog_title_and_actions_fit_scaled_viewports() {+ for language in ["en", "ar"] {+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(589.0, 407.0), egui::vec2(392.0, 271.0), egui::vec2(450.0, 280.0)] {+ for (command, title, ok, cancel) in+ [("app.preferences", "Preferences", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "Create", "Close")]+ {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = language.into();+ app.run("file.new", json!({})).unwrap();+ app.run(command, json!({})).unwrap();+ let ctx = dialog_context(language);+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in [title, ok, cancel] {+ visible_label(&labels, screen, crate::i18n::tr(language, expected));+ }+ }+ }+ }+ }++ #[test]+ fn preferences_first_setting_switches_interface_language() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("app.preferences", json!({})).unwrap();+ let ctx = dialog_context("");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let heading = visible_label(&labels, screen, "Interface Language");+ let combo = visible_label(&labels, screen, "English");+ let scaling = visible_label(&labels, screen, "When Scaling");+ assert!(heading.bottom() <= combo.top() && combo.bottom() <= scaling.top(), "the language comes first: {heading:?} {combo:?} {scaling:?}");+ let pane = labels.iter().filter(|(_, rect, _)| rect.left() >= heading.left() - 1.0 && rect.top() < heading.top());+ assert!(pane.clone().all(|(text, _, _)| text == "Preferences"), "nothing above it: {:?}", pane.collect::<Vec<_>>());++ // Choosing a language applies it at once; the dialog stays open.+ click_dialog(&mut app, &ctx, screen, combo.center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for (_, name) in crate::i18n::LANGUAGES {+ assert!(labels.iter().any(|(text, _, _)| text == name), "{name} is listed by its own name");+ }+ let deutsch = visible_label(&labels, screen, "Deutsch").center();+ click_dialog(&mut app, &ctx, screen, deutsch);+ assert_eq!(app.ui.language, "de");+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences"));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let heading = visible_label(&labels, screen, crate::i18n::tr("de", "Interface Language"));+ let combo = visible_label(&labels, screen, "Deutsch");++ // The names stay endonyms in the German interface.+ click_dialog(&mut app, &ctx, screen, combo.center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for name in ["English", "Français", "日本語", "Українська"] {+ assert!(labels.iter().any(|(text, _, _)| text == name), "{name}");+ }+ click_dialog(&mut app, &ctx, screen, heading.center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(!labels.iter().any(|(text, _, _)| text == "Français"), "the list closes");++ // The control channel's command and the combo show the same setting.+ app.run("app.language", json!({"lang": "ja"})).unwrap();+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(labels.iter().any(|(text, _, _)| text == "日本語"));+ assert!(labels.iter().any(|(text, _, _)| text == crate::i18n::tr("ja", "Interface Language")));++ // Cancel puts back the language the dialog opened with; OK keeps the choice.+ let cancel_button = visible_label(&labels, screen, crate::i18n::tr("ja", "Cancel")).center();+ click_dialog(&mut app, &ctx, screen, cancel_button);+ assert!(app.ui.dialog.is_none());+ assert_eq!(app.ui.language, "");+ app.run("app.preferences", json!({})).unwrap();+ app.run("app.language", json!({"lang": "it"})).unwrap();+ confirm(&mut app).unwrap();+ assert_eq!(app.ui.language, "it");+ app.run("app.preferences", json!({})).unwrap();+ app.run("app.language", json!({"lang": "uk"})).unwrap();+ cancel(&mut app);+ assert_eq!(app.ui.language, "it");+ }++ /// Preferences › Interface › Panels holds Auto-Collapse Iconic Panels, the same setting as the+ /// iconic column's menu.+ #[test]+ fn preferences_set_auto_collapse_iconic_panels() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("app.preferences", json!({})).unwrap();+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["autoCollapseIconicPanels"], json!(false));+ app.ui.dialog.as_mut().unwrap().fields.insert("autoCollapseIconicPanels".into(), json!(true));+ confirm(&mut app).unwrap();+ assert!(app.ui.dock_auto_collapse);+ app.run("app.preferences", json!({})).unwrap();+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["autoCollapseIconicPanels"], json!(true));+ }++ #[test]+ fn preferences_sidebar_scroll_keeps_selected_options_visible() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("app.preferences", json!({})).unwrap();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(589.0, 407.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let sidebar = visible_label(&labels, screen, "General").center();+ assert!(!labels.iter().any(|(text, rect, clip)| text == "File Handling" && clip.contains_rect(*rect)), "last section starts below the sidebar");+ scroll_dialog(&mut app, &ctx, screen, sidebar, egui::vec2(0.0, -600.0));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let files = visible_label(&labels, screen, "File Handling").center();+ click_dialog(&mut app, &ctx, screen, files);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("section"), "files");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["Document Recovery Data", "Save recovery data every:", "OK", "Cancel"] {+ visible_label(&labels, screen, expected);+ }+ }++ #[test]+ fn preferences_horizontal_scroll_reaches_clipped_options() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("app.preferences", json!({})).unwrap();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(450.0, 280.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let body = visible_label(&labels, screen, "When Scaling").center();+ // The last General option sits below this short viewport.+ scroll_dialog(&mut app, &ctx, screen, body, egui::vec2(0.0, -600.0));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let option = "Absolute Numbering (instead of Section Numbering)";+ let (_, rect, clip) = labels.iter().find(|(text, _, _)| text == option).unwrap();+ assert!(rect.right() > clip.right(), "rightmost option starts horizontally clipped: {rect:?}, {clip:?}");+ scroll_dialog(&mut app, &ctx, screen, body, egui::vec2(-600.0, 0.0));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in [option, "Preferences", "OK", "Cancel"] {+ visible_label(&labels, screen, expected);+ }+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, option).center());+ assert!(app.ui.dialog.as_ref().unwrap().b("absolutePageNumbers"));+ }++ /// Scroll the dialog body down at `at` until `text` is painted unclipped on screen.+ fn scroll_to_label(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, at: egui::Pos2, text: &str) -> egui::Rect {+ for _ in 0..40 {+ let labels = dialog_frame(app, ctx, screen, vec![]);+ if let Some((_, rect, _)) = labels.iter().find(|(t, r, clip)| t.trim() == text && screen.contains_rect(*r) && clip.contains_rect(*r)) {+ return *rect;+ }+ scroll_dialog(app, ctx, screen, at, egui::vec2(0.0, -60.0));+ }+ panic!("{text} never scrolled into view");+ }++ #[test]+ fn new_document_vertical_scroll_reaches_every_field_and_preset() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("app.newDocumentDialog", json!({})).unwrap();+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(392.0, 271.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let body = visible_label(&labels, screen, "Width").center();+ let shown = |labels: &[(String, egui::Rect, egui::Rect)]| labels.iter().any(|(t, r, clip)| t == "Primary Text Frame" && clip.contains_rect(*r));+ assert!(!shown(&labels), "the details start vertically clipped");+ let ptf = scroll_to_label(&mut app, &ctx, screen, body, "Primary Text Frame");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["New Document", "Create", "Close"] {+ visible_label(&labels, screen, expected);+ }+ click_dialog(&mut app, &ctx, screen, ptf.center());+ assert!(app.ui.dialog.as_ref().unwrap().b("primaryTextFrame"), "the caption toggles its checkbox");+ // Below the details: the preset tabs and cards.+ scroll_to_label(&mut app, &ctx, screen, body, "[Default]");+ }++ #[test]+ fn arabic_new_document_fields_remain_reachable_and_editable() {+ for size in [egui::vec2(392.0, 271.0), egui::vec2(450.0, 280.0), egui::vec2(1178.0, 814.0)] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = "ar".into();+ app.run("app.newDocumentDialog", json!({})).unwrap();+ let fields = [("height", "66p1"), ("gutter", "1p2"), ("marginBottom", "3p3"), ("marginOutside", "3p4")];+ for (field, value) in fields {+ app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(value));+ }+ let ctx = dialog_context("ar");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ // With craft-fonts' Noto Sans Arabic the rows above are taller, so at the smallest size the+ // Height field starts partly below the body's clip: scroll to it like the other fields.+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let (_, _, body) = labels.iter().find(|(text, _, _)| text.trim() == "66p1").expect("66p1 is painted");+ let height = scroll_to_label(&mut app, &ctx, screen, body.center(), "66p1");+ click_dialog(&mut app, &ctx, screen, height.center());+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![+ egui::Event::Key {+ key: egui::Key::A,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() },+ },+ egui::Event::Text("88p8".into()),+ ],+ );+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("height"), "88p8", "numeric fields accept edits");+ let caption = scroll_to_label(&mut app, &ctx, screen, height.center(), crate::i18n::tr("ar", "Primary Text Frame"));+ click_dialog(&mut app, &ctx, screen, caption.center());+ assert!(app.ui.dialog.as_ref().unwrap().b("primaryTextFrame"), "checkboxes remain clickable");+ for (_, value) in &fields[1..] {+ scroll_to_label(&mut app, &ctx, screen, height.center(), value);+ }+ }+ }++ #[test]+ fn resized_dialogs_cancel_and_reopen_without_applying_edits() {+ for (command, title, field, ok, cancel) in+ [("app.preferences", "Preferences", "recoveryMinutes", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "pages", "Create", "Close")]+ {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run(command, json!({})).unwrap();+ let original = app.ui.dialog.as_ref().unwrap().fields[field].clone();+ app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(42));+ let ctx = dialog_context("en");+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0), egui::vec2(589.0, 407.0)] {+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in [title, ok, cancel] {+ visible_label(&labels, screen, expected);+ }+ }+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(589.0, 407.0));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, cancel).center());+ assert!(app.ui.dialog.is_none());+ assert!(app.session.active().is_none(), "cancelling must not create a document");+ app.run(command, json!({})).unwrap();+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], original, "cancelled edits must not survive reopening");+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, title);+ dialog_frame(+ &mut app,+ &ctx,+ screen,+ vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],+ );+ assert!(app.ui.dialog.is_none(), "Escape must also close the reopened dialog");+ }+ }++ #[test]+ fn paragraph_style_options_tabs_section_adds_a_stop_on_its_ruler() {+ use egui_kittest::kittest::Queryable;+ let (app, _) = ruled_paragraph();+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "tabs"})));+ h.run_steps(4);+ h.get_by_label("Clear All");+ // The ruler sits below the row of alignment buttons; its strip takes the click.+ let b = h.get_by_label("Right-aligned tab").rect();+ h.get_by_label("Right-aligned tab").click();+ h.run_steps(2);+ let left = h.get_by_label("Left-aligned tab").rect();+ let at = egui::pos2(left.min.x + crate::panels::tabs::PAD + 100.0, b.max.y + 14.0);+ crate::test_window::click_at(&mut h, at);+ let d = h.state().app.ui.dialog.clone().unwrap();+ let tabs = d.fields.get("p.tabs").cloned().unwrap_or_default();+ assert_eq!(tabs.as_array().map(Vec::len), Some(1), "{tabs}");+ assert_eq!(tabs[0]["align"], "right");+ confirm(&mut h.state_mut().app).unwrap();+ let app = &mut h.state_mut().app;+ let style = app.session.execute("type.tabs.get", &json!({"style": "Ruled Child"})).unwrap();+ assert_eq!(style["tabs"], tabs);+ assert_eq!(app.session.execute("type.tabs.get", &json!({})).unwrap()["tabs"], tabs, "the paragraph follows its style");+ }++ #[test]+ fn parses_command_params() {+ let f = command_fields("{name, type: custom|lastPageNumber|chapterNumber, text?, rule?: {on, weight}, flag?: bool} — creates");+ let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect();+ assert_eq!(keys, ["name", "type", "text", "rule", "flag"]);+ assert_eq!(f[1].choices, ["custom", "lastPageNumber", "chapterNumber"]);+ assert!(!f[0].optional && f[2].optional);+ assert!(f[4].boolean);+ assert!(command_fields("{}").is_empty());+ assert!(command_fields("no params").is_empty());+ // A parenthetical after the key describes the value.+ let f = command_fields("{angle (degrees, CCW), ids?}");+ let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect();+ assert_eq!(keys, ["angle", "ids"]);+ assert!(!f[0].optional && f[1].optional);+ assert_eq!(f[0].hint, "degrees, CCW");+ let f = command_fields("{scaleX? (%), ref?: 0..8, ids?: parent items (default: all)}");+ let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect();+ assert_eq!(keys, ["scaleX", "ref", "ids"]);+ assert!(f.iter().all(|f| f.optional));+ assert_eq!(f[0].hint, "%");+ assert_eq!(f[2].hint, "parent items (default: all)");+ // Every command with a "…" label parses without panicking.+ for c in designcraft_engine::command_specs() {+ let _ = command_fields(c.params);+ }+ }++ fn test_app() -> crate::DesignApp {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 1})).unwrap();+ app+ }++ #[test]+ fn toc_dialog_keeps_the_character_styles_and_sorting_of_its_entries() {+ let mut app = test_app();+ app.session.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();+ app.session.execute("style.character.create", &json!({"name": "Number"})).unwrap();+ app.session.execute("style.character.create", &json!({"name": "Dots"})).unwrap();+ let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Pears\nApples"})).unwrap()["story"]+ .clone();+ app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 8})).unwrap();+ app.session.execute("style.paragraph.apply", &json!({"name": "Head"})).unwrap();+ app.session.execute("layout.pages.insert", &json!({"count": 1})).unwrap();+ let entries = json!([{"style": "Head", "pageNumberStyle": "Number", "separatorStyle": "Dots", "sort": true}]);+ app.session.execute("toc.generate", &json!({"page": 2, "entries": entries})).unwrap();+ let before = app.session.active().unwrap().doc.toc.clone().unwrap();+ // The dialog shows the options, and OK (Replace Existing) writes them back unchanged.+ open_toc(&mut app);+ let d = app.ui.dialog.as_ref().unwrap();+ let row = &toc_rows(d)[0];+ assert_eq!((row.page_number_style.as_str(), row.separator_style.as_str(), row.sort), ("Number", "Dots", true));+ let chars: Vec<String> = serde_json::from_value(d.fields["charStyles"].clone()).unwrap();+ assert_eq!(chars, ["Number", "Dots"], "[None] is the menu's first choice, not a style");+ let p = toc_params(&app, d);+ assert_eq!(+ (&p["entries"][0]["pageNumberStyle"], &p["entries"][0]["separatorStyle"], &p["entries"][0]["sort"]),+ (&json!("Number"), &json!("Dots"), &json!(true))+ );+ confirm(&mut app).expect("OK regenerates the table of contents");+ let st = app.session.active().unwrap();+ assert_eq!(st.doc.toc.as_ref().unwrap().entries, before.entries);+ // [None] and unsorted are left out of the params.+ let mut d = Dialog::new(TOC, json!({"included": [{"style": "Head", "level": 1, "separator": "^t"}]}));+ d.fields.insert("replace".into(), json!(true));+ let p = toc_params(&app, &d);+ assert!(p["entries"][0].get("pageNumberStyle").is_none() && p["entries"][0].get("sort").is_none(), "{p}");+ }++ #[test]+ fn paragraph_style_options_dialog_saves_edits() {+ let mut app = test_app();+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Body Copy"})).unwrap()["name"].as_str().unwrap().to_string();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": name, "p.align": "center"})));+ confirm(&mut app).expect("OK saves the style edit");+ let st = app.session.active().unwrap();+ assert_eq!(st.doc.styles.para(&name).unwrap().para.align, Some(designcraft_doc::Align::Center));+ }++ #[test]+ fn paragraph_style_options_align_to_grid_shows_and_sets_the_style_grid_alignment() {+ use designcraft_doc::GridAlign;+ use egui_kittest::kittest::Queryable;+ let mut app = test_app();+ app.session.execute("style.paragraph.create", &json!({"name": "Grid Body", "para": {"gridAlign": "firstLineOnly"}})).unwrap();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"})));+ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+ let grid = |h: &egui_kittest::Harness<'static, crate::test_window::Window>| {+ h.state().app.session.active().unwrap().doc.styles.para("Grid Body").unwrap().para.grid_align+ };+ h.run_steps(4);+ h.get_by_value("First Line Only");+ confirm(&mut h.state_mut().app).unwrap();+ assert_eq!(grid(&h), Some(GridAlign::FirstLineOnly), "OK without edits keeps the style's alignment");+ h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"})));+ h.run_steps(4);+ h.get_by_value("First Line Only").click();+ h.run_steps(3);+ h.get_by_label("All Lines").click();+ h.run_steps(3);+ confirm(&mut h.state_mut().app).unwrap();+ assert_eq!(grid(&h), Some(GridAlign::AllLines));+ }++ #[test]+ fn delete_paragraph_style_dialog_removes_the_style_and_reassigns_text() {+ let mut app = test_app();+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();+ let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();+ app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap();+ app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();+ app.session.execute("style.paragraph.apply", &json!({"name": name})).unwrap();+ app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name, "replaceWith": designcraft_doc::BASIC_PARAGRAPH})));+ confirm(&mut app).expect("OK deletes the style");+ let st = app.session.active().unwrap();+ assert!(st.doc.styles.para(&name).is_none(), "style removed");+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap();+ assert_eq!(story.paras[0].style, designcraft_doc::BASIC_PARAGRAPH, "text reassigned to the replacement style");+ }++ #[test]+ fn delete_paragraph_style_dialog_defaults_replacement_to_basic_paragraph() {+ let mut app = test_app();+ let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();+ // No `replaceWith` set — the dialog's default field.+ app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name})));+ confirm(&mut app).expect("OK deletes the style with the default replacement");+ let st = app.session.active().unwrap();+ assert!(st.doc.styles.para(&name).is_none());+ }++ #[test]+ fn character_style_options_dialog_saves_edits() {+ let mut app = test_app();+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ app.ui.dialog = Some(Dialog::new("characterStyleOptions", json!({"name": name, "c.tracking": 20.0})));+ confirm(&mut app).expect("OK saves the style edit");+ let st = app.session.active().unwrap();+ assert_eq!(st.doc.styles.char_style(&name).unwrap().chars.tracking, Some(20.0));+ }++ #[test]+ fn delete_character_style_dialog_removes_the_style_and_reassigns_text() {+ let mut app = test_app();+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();+ app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap();+ app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap();+ app.session.execute("style.character.apply", &json!({"name": name})).unwrap();+ app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name, "replaceWith": designcraft_doc::NO_CHAR_STYLE})));+ confirm(&mut app).expect("OK deletes the style");+ let st = app.session.active().unwrap();+ assert!(st.doc.styles.char_style(&name).is_none(), "style removed");+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap();+ assert_eq!(story.chars[0].format.style, designcraft_doc::NO_CHAR_STYLE, "text reassigned to the replacement style");+ }++ #[test]+ fn delete_character_style_dialog_defaults_replacement_to_none() {+ let mut app = test_app();+ let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ // No `replaceWith` set — the dialog's default field.+ app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name})));+ confirm(&mut app).expect("OK deletes the style with the default replacement");+ let st = app.session.active().unwrap();+ assert!(st.doc.styles.char_style(&name).is_none());+ }++ /// File › Export EPUB… opens EPUB Export Options from the document's setting; OK stores a+ /// changed Split Document as one undo step, and an unchanged one adds none.+ #[test]+ fn epub_export_passes_its_options_to_the_engine() {+ use std::io::Read;+ use std::sync::{Arc, Mutex};+ let mut app = test_app();+ app.session.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap();+ let r = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "One\nTwo"})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ for anchor in [0, 4] {+ app.session.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": anchor})).unwrap();+ app.session.execute("style.paragraph.apply", &json!({"name": "Chapter"})).unwrap();+ }+ let written: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = written.clone();+ app.services.write = Some(Box::new(move |_: &str, bytes: &[u8]| {+ *sink.lock().unwrap() = bytes.to_vec();+ Ok(())+ }));+ crate::menus::export_epub(&mut app, &json!({"path": "book.epub", "split": {"style": "Chapter"}})).unwrap();+ let bytes = written.lock().unwrap().clone();+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();+ let mut opf = String::new();+ z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap();+ assert!(opf.contains("properties=\"cover-image\""), "the first page is the cover: {opf}");+ assert!(z.by_name("OEBPS/content2.xhtml").is_ok(), "the split override reaches the export");+ assert_eq!(app.session.active().unwrap().doc.settings.epub_split, designcraft_doc::EpubSplit::Off, "an override is not stored");+ crate::menus::export_epub(&mut app, &json!({"path": "book.epub", "cover": false})).unwrap();+ let bytes = written.lock().unwrap().clone();+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();+ let mut opf = String::new();+ z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap();+ assert!(!opf.contains("cover-image"), "a caller's cover: false stays: {opf}");+ }++ #[test]+ fn epub_export_options_store_split_document() {+ use designcraft_doc::EpubSplit;+ let mut app = test_app();+ app.session.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap();+ let undo_steps = |app: &crate::DesignApp| app.session.active().map(|st| st.history.undo.len());+ app.run("app.exportEpub", json!({})).unwrap();+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!((d.id.as_str(), d.b("split"), d.s("style").as_str()), ("epubExport", false, designcraft_doc::BASIC_PARAGRAPH));+ d.fields.insert("split".into(), json!(true));+ d.fields.insert("style".into(), json!("Chapter"));+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::Style("Chapter".into()));+ assert_eq!(undo_steps(&app), before.map(|n| n + 1));+ open_epub_export(&mut app);+ assert_eq!(app.ui.dialog.as_ref().map(|d| (d.b("split"), d.s("mode"), d.s("style"))), Some((true, "style".into(), "Chapter".into())));+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before.map(|n| n + 1), "unchanged: no undo step");+ open_epub_export(&mut app);+ app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("exportTags"));+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::ExportTags);+ open_epub_export(&mut app);+ cancel(&mut app);+ assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::ExportTags, "Cancel stores nothing");+ }++ #[test]+ fn pdf_export_defaults() {+ let d = Dialog::new("pdfExport", json!({}));+ let keys: Vec<&str> = d.fields.iter().map(|(k, _)| k.as_str()).collect();+ // serde_json::Map keeps keys sorted.+ let expected = [+ "bleed",+ "compressImages",+ "flatten",+ "marksBleed",+ "marksCrop",+ "marksOffset",+ "marksPageInfo",+ "marksWeight",+ "preset",+ "spreads",+ "standard",+ "tagged",+ ];+ assert_eq!(keys, expected);+ assert_eq!(d.fields["preset"].as_str(), Some("Desktop Printing"));+ assert_eq!(d.fields["standard"].as_str(), Some("none"));+ assert_eq!(d.fields["compressImages"].as_bool(), Some(false));+ assert_eq!(d.fields["flatten"].as_str(), Some(""));+ assert_eq!(d.fields["spreads"].as_bool(), Some(false));+ assert_eq!(d.fields["bleed"].as_bool(), Some(true));+ assert_eq!(d.fields["marksCrop"].as_bool(), Some(false));+ assert_eq!(d.fields["marksBleed"].as_bool(), Some(false));+ assert_eq!(d.fields["marksPageInfo"].as_bool(), Some(false));+ assert_eq!(d.fields["marksWeight"].as_str(), Some("0.25"));+ assert_eq!(d.fields["marksOffset"].as_str(), Some("6"));+ assert_eq!(d.fields["tagged"].as_bool(), Some(true));+ }++ #[test]+ fn pdf_export_override_keeps_override() {+ let d = Dialog::new("pdfExport", json!({"bleed": false}));+ assert_eq!(d.fields["bleed"].as_bool(), Some(false));+ assert_eq!(d.fields["preset"].as_str(), Some("Desktop Printing"));+ assert_eq!(d.fields["tagged"].as_bool(), Some(true));+ }++ #[test]+ fn pdf_export_preset_high_quality_print_keeps_flatten() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("flatten".into(), json!("medium"));+ apply_pdf_preset(&mut d, "Desktop Printing");+ assert_eq!(d.s("standard"), "none");+ assert!(!d.b("compressImages"));+ assert!(!d.b("marksCrop"));+ assert!(!d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "medium", "a leave-unchanged preset must not touch flatten");+ }++ #[test]+ fn pdf_export_preset_press_quality_keeps_flatten() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("flatten".into(), json!("high"));+ apply_pdf_preset(&mut d, "Commercial Printing");+ assert_eq!(d.s("standard"), "none");+ assert!(d.b("compressImages"));+ assert!(d.b("marksCrop"));+ assert!(d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "high");+ }++ #[test]+ fn pdf_export_preset_smallest_file_size_sets_flatten_low() {+ let mut d = Dialog::new("pdfExport", json!({}));+ apply_pdf_preset(&mut d, "Screen and Email");+ assert_eq!(d.s("standard"), "none");+ assert!(d.b("compressImages"));+ assert!(!d.b("marksCrop"));+ assert!(!d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "low");+ }++ /// The PDF/X-1a preset exports X-1a with the High Resolution flattener and printer's marks.+ #[test]+ fn pdf_export_preset_pdf_x1a_flattens_at_high_resolution() {+ let mut d = Dialog::new("pdfExport", json!({}));+ apply_pdf_preset(&mut d, "PDF/X-1a:2003");+ assert_eq!(d.s("standard"), "x1a");+ assert_eq!(d.s("flatten"), "high");+ assert!(d.b("marksCrop") && d.b("marksBleed"));+ assert!(PDF_EXPORT_PRESETS.contains(&"PDF/X-1a:2003"));+ }++ #[test]+ fn pdf_export_preset_pdf_x4_keeps_flatten() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("flatten".into(), json!("medium"));+ apply_pdf_preset(&mut d, "PDF/X-4");+ assert_eq!(d.s("standard"), "x4");+ assert!(!d.b("compressImages"));+ assert!(d.b("marksCrop"));+ assert!(d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "medium");+ }++ #[test]+ fn pdf_export_preset_pdf_a2b_keeps_flatten() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("flatten".into(), json!("low"));+ apply_pdf_preset(&mut d, "PDF/A-2b");+ assert_eq!(d.s("standard"), "a2b");+ assert!(!d.b("compressImages"));+ assert!(!d.b("marksCrop"));+ assert!(!d.b("marksBleed"));+ assert!(!d.b("marksPageInfo"));+ assert_eq!(d.s("flatten"), "low");+ }++ #[test]+ fn open_pdf_export_seeds_fields_from_settings() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.pdf_export.standard = "x4".into();+ app.ui.pdf_export.tagged = false;+ app.ui.pdf_export.marks_crop = true;+ app.ui.pdf_export.flatten = String::new();+ app.ui.flattener = "medium".into();+ open_pdf_export(&mut app);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.id, "pdfExport");+ assert_eq!(d.s("standard"), "x4");+ assert!(!d.b("tagged"));+ assert!(d.b("marksCrop"));+ assert_eq!(d.s("pages"), "all");+ assert_eq!(d.s("flatten"), "medium", "empty flatten falls back to the global flattener");+ assert_eq!(d.s("title"), "", "no document → empty title");++ // A non-empty persisted flatten is used verbatim, not the global fallback.+ app.ui.pdf_export.flatten = "low".into();+ app.ui.flattener = "medium".into();+ open_pdf_export(&mut app);+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.s("flatten"), "low");+ }++ #[test]+ fn pdf_export_preset_custom_changes_nothing() {+ let mut d = Dialog::new("pdfExport", json!({}));+ d.fields.insert("standard".into(), json!("x4"));+ d.fields.insert("compressImages".into(), json!(true));+ d.fields.insert("marksCrop".into(), json!(true));+ d.fields.insert("marksBleed".into(), json!(true));+ d.fields.insert("marksPageInfo".into(), json!(true));+ d.fields.insert("flatten".into(), json!("high"));+ let before = d.fields.clone();+ apply_pdf_preset(&mut d, "Custom");+ assert_eq!(d.fields, before);+ }++ #[test]+ fn confirm_pdf_export_writes_file_and_persists_settings() {+ use std::sync::{Arc, Mutex};+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let writes: Arc<Mutex<Vec<(String, Vec<u8>)>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = writes.clone();+ app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {+ sink.lock().unwrap().push((path.to_string(), bytes.to_vec()));+ Ok(())+ }));+ app.answer_dialogs(crate::app::file_dialogs::testing::answer_with(Some("/tmp/designcraft-test.pdf".into())));++ app.ui.dialog = Some(Dialog::new("pdfExport", json!({})));+ {+ let d = app.ui.dialog.as_mut().unwrap();+ d.fields.insert("standard".into(), json!("x4"));+ d.fields.insert("bleed".into(), json!(false));+ d.fields.insert("marksCrop".into(), json!(true));+ d.fields.insert("tagged".into(), json!(false));+ d.fields.insert("title".into(), json!("Report"));+ }+ confirm(&mut app).unwrap();+ app.settle_dialogs();++ let got = writes.lock().unwrap();+ assert_eq!(got.len(), 1, "confirming the dialog writes exactly one file");+ assert_eq!(got[0].0, "/tmp/designcraft-test.pdf");+ assert!(got[0].1.starts_with(b"%PDF"), "the written bytes are a PDF");+ drop(got);++ assert_eq!(app.ui.pdf_export.standard, "x4");+ assert!(!app.ui.pdf_export.bleed);+ assert!(app.ui.pdf_export.marks_crop);+ assert!(!app.ui.pdf_export.tagged);+ }++ #[test]+ fn update_link_asks_before_replacing_edits_made_in_the_layout() {+ let dir = std::env::temp_dir().join(format!("dc-update-link-dialog-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("note.txt");+ std::fs::write(&path, "One").unwrap();+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let r = app.session.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true, "rect": [72, 72, 300, 200]})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ let text = |app: &crate::DesignApp| app.session.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.clone();++ // Not edited in the layout: updates without asking.+ std::fs::write(&path, "Two").unwrap();+ crate::panels::properties::update_links(&mut app, json!({"story": sid}));+ assert!(app.ui.dialog.is_none());+ assert_eq!(text(&app), "Two");++ // Edited in the layout: asks first; Cancel changes nothing.+ app.session.execute("story.setText", &json!({"story": sid, "text": "Mine"})).unwrap();+ std::fs::write(&path, "Three").unwrap();+ crate::panels::properties::update_links(&mut app, json!({"story": sid}));+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.id.as_str(), d.s("files").as_str()), ("updateLink", "note.txt"));+ app.ui.dialog = None;+ assert_eq!(text(&app), "Mine");++ // Window › Links › Update Link (all links) asks too; confirming updates.+ crate::menus::activate(&mut app, "links.update", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("updateLink"));+ confirm(&mut app).unwrap();+ assert!(app.ui.dialog.is_none());+ assert_eq!(text(&app), "Three");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn confirm_pdf_export_cancelled_save_writes_nothing() {+ use std::sync::{Arc, Mutex};+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let writes: Arc<Mutex<Vec<(String, Vec<u8>)>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = writes.clone();+ app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {+ sink.lock().unwrap().push((path.to_string(), bytes.to_vec()));+ Ok(())+ }));+ app.answer_dialogs(crate::app::file_dialogs::testing::answer_with(None));++ app.ui.dialog = Some(Dialog::new("pdfExport", json!({})));+ let r = confirm(&mut app).unwrap();+ assert_eq!(r, Value::Null);+ app.settle_dialogs();+ assert!(writes.lock().unwrap().is_empty(), "cancelling the save picker must not write");+ }++ use designcraft_doc::{CharAttrs, CharacterStyle};++ /// A document with character styles Base (bold) and Emphasis (italic) on the first two letters.+ fn styled_app() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.character.create", json!({"name": "Base", "chars": {"fontStyle": "Bold"}})).unwrap();+ app.run("style.character.create", json!({"name": "Emphasis", "chars": {"fontStyle": "Italic"}})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 2})).unwrap();+ app.run("style.character.apply", json!({"name": "Emphasis"})).unwrap();+ app+ }++ /// One control-channel request, as the control port or MCP would send it.+ fn ctl(app: &mut DesignApp, method: &str, params: Value) -> Value {+ let (req, _reply) = crate::control::ControlRequest::new(method, params);+ match crate::control::handle(app, &egui::Context::default(), &req) {+ crate::control::Outcome::Done(v) => v,+ crate::control::Outcome::Screenshot { .. } => Value::Null,+ }+ }++ fn char_style(app: &DesignApp, name: &str) -> Option<CharacterStyle> {+ app.session.active().and_then(|st| st.doc.styles.char_style(name).cloned())+ }++ #[test]+ fn character_style_options_set_exactly_the_edited_attributes() {+ let mut app = styled_app();+ assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}))["ok"], true);+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 14}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.fill", "value": "[Paper]"}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": "Base"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert!(app.ui.dialog.is_none());+ let st = char_style(&app, "Emphasis").unwrap();+ assert_eq!(st.based_on.as_deref(), Some("Base"));+ assert_eq!(st.chars, CharAttrs { font_style: Some("Italic".into()), size: Some(14.0), fill: Some("[Paper]".into()), ..Default::default() });+ }++ #[test]+ fn character_style_options_unset_cleared_fields_and_rename_every_use() {+ let mut app = styled_app();+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.fontStyle", "value": null}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Strong"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert!(char_style(&app, "Emphasis").is_none());+ assert!(char_style(&app, "Strong").unwrap().chars.is_empty());+ let st = app.session.active().unwrap();+ let story = st.doc.stories.values().next().unwrap();+ assert!(story.chars.iter().any(|r| r.format.style == "Strong"));+ // A taken name keeps the dialog open with the reason.+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Strong"}}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Base"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false);+ assert!(app.ui.dialog.as_ref().is_some_and(|d| !d.s("status").is_empty()));+ assert!(char_style(&app, "Strong").is_some());+ }++ #[test]+ fn new_character_style_opens_its_options_and_creates_the_style() {+ let mut app = styled_app();+ crate::menus::activate(&mut app, "style.character.create", &Value::Null);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("characterStyleOptions", true, "Character Style 1"));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 9}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let st = char_style(&app, "Character Style 1").unwrap();+ assert_eq!((st.based_on, st.chars), (None, CharAttrs { size: Some(9.0), ..Default::default() }));+ crate::menus::activate(&mut app, "style.character.create", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("rename"), "Character Style 2");+ }++ #[test]+ fn new_paragraph_style_opens_its_options_and_creates_the_style() {+ let mut app = styled_app();+ crate::menus::activate(&mut app, "style.paragraph.create", &Value::Null);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("paragraphStyleOptions", true, "Paragraph Style 1"));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 20}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": designcraft_doc::BASIC_PARAGRAPH}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let st = app.session.active().unwrap().doc.styles.para("Paragraph Style 1").cloned().unwrap();+ assert_eq!(st.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH));+ assert_eq!(st.chars, CharAttrs { size: Some(20.0), ..Default::default() });+ }++ #[test]+ fn style_rows_open_their_options_except_none() {+ let mut app = styled_app();+ open_style_options(&mut app, false, "Emphasis");+ let d = app.ui.dialog.take().unwrap();+ assert_eq!((d.id.as_str(), d.s("name").as_str()), ("characterStyleOptions", "Emphasis"));+ open_style_options(&mut app, false, designcraft_doc::NO_CHAR_STYLE);+ assert!(app.ui.dialog.is_none());+ open_style_options(&mut app, true, designcraft_doc::BASIC_PARAGRAPH);+ assert_eq!(app.ui.dialog.take().unwrap().id, "paragraphStyleOptions");+ }++ #[test]+ fn style_options_sections_draw() {+ let mut app = styled_app();+ let ctx = egui::Context::default();+ let frame = |app: &mut DesignApp| {+ for _ in 0..2 {+ let raw = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))),+ max_texture_side: Some(8192),+ ..Default::default()+ };+ let mut out = ctx.run_ui(raw, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ }+ };+ for lang in ["", "ar"] {+ app.run("app.language", json!({"lang": lang})).unwrap();+ for fields in [json!({"name": "Emphasis"}), json!({"new": true}), json!({"name": "Emphasis", "c.size": null, "c.underline": false})] {+ for section in ["general", "chars", "advanced", "color", "openType", "underline", "strikethrough"] {+ let mut f = fields.clone();+ f["section"] = json!(section);+ app.ui.dialog = Some(Dialog::new("characterStyleOptions", f));+ frame(&mut app);+ assert!(app.ui.dialog.is_some(), "{section} stays open");+ }+ }+ for section in+ ["general", "chars", "advanced", "border", "shading", "keep", "span", "bullets", "color", "openType", "underline", "strikethrough"]+ {+ for fields in [+ json!({"new": true}),+ json!({"new": true, "p.listType": "bullets", "p.spanColumns": {"kind": "span", "columns": 0}, "p.borderOn": true}),+ json!({"new": true, "p.listType": "numbers", "p.startAt": 1, "p.spanColumns": {"kind": "split", "columns": 2}, "p.keepLinesTogether": true}),+ ] {+ let mut f = fields;+ f["section"] = json!(section);+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", f));+ frame(&mut app);+ assert!(app.ui.dialog.is_some(), "{section} stays open");+ }+ }+ }+ }++ #[test]+ fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() {+ use egui::{Event, Modifiers, PointerButton, Pos2, vec2};+ use egui_kittest::{Harness, kittest::Queryable};+ fn drag(h: &mut Harness<'static, DesignApp>, from: Pos2, to: Pos2) {+ h.event(Event::PointerMoved(from));+ h.run_steps(1);+ h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });+ h.run_steps(1);+ for step in 1..=8 {+ h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0)));+ h.run_steps(1);+ }+ h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });+ h.run_steps(3);+ }+ let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::unique("dialog"))).unwrap();+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.ui.dialog = Some(Dialog::new("insertTable", Value::Null));+ let mut ready = false;+ let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ move |ui, app: &mut DesignApp| {+ if !ready {+ crate::theme::install_fonts(ui.ctx(), &app.ui.language);+ crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default()));+ ready = true;+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(4);+ let centred = rect(&h);+ assert!((centred.center() - egui::pos2(600.0, 400.0)).length() < 1.0, "{centred:?}");+ assert!(centred.width() < 1000.0 && centred.height() < 700.0, "the area is the dialog, not the backdrop: {centred:?}");+- let title = h.get_by_label("Create Table").rect().center();++ let title = h.get_by_label("Insert Table").rect().center();+ drag(&mut h, title, title + vec2(100.0, 60.0));+ let moved = rect(&h);+ assert!((moved.min - centred.min - vec2(100.0, 60.0)).length() < 2.0, "{centred:?} -> {moved:?}");++ let body = egui::pos2(moved.right() - 40.0, moved.center().y);+ drag(&mut h, body, body + vec2(-150.0, 80.0));+ assert_eq!(rect(&h), moved, "a drag in the body leaves the dialog in place");++ // The title row stays inside the top edge.- let title = h.get_by_label("Create Table").rect().center();++ let title = h.get_by_label("Insert Table").rect().center();+ drag(&mut h, title, title - vec2(0.0, 1000.0));+ assert!(rect(&h).top().abs() < 1.0, "{:?}", rect(&h));++ // Opened again, the dialog starts centred.+ h.state_mut().ui.dialog = None;+ h.run_steps(2);+ h.state_mut().ui.dialog = Some(Dialog::new("insertTable", Value::Null));+ h.run_steps(4);+ assert!((rect(&h).center() - centred.center()).length() < 1.0, "{:?}", rect(&h));++ // Past the left edge, about 100 px of the title row stays inside.- let title = h.get_by_label("Create Table").rect().center();++ let title = h.get_by_label("Insert Table").rect().center();+ drag(&mut h, title, title - vec2(900.0, 0.0));+ assert!((rect(&h).right() - 100.0).abs() < 2.0, "{:?}", rect(&h));+ }++ #[test]+ fn the_new_document_window_drags_mostly_aside_and_keeps_its_preview() {+ use egui::{Event, Modifiers, PointerButton, vec2};+ use egui_kittest::{Harness, kittest::Queryable};+ let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::unique("dialog"))).unwrap();+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "A"})).unwrap();+ app.ui.new_document_preview = true;+ app.run("app.newDocumentDialog", json!({})).unwrap();+ let mut ready = false;+ let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ move |ui, app: &mut DesignApp| {+ if !ready {+ crate::theme::install_fonts(ui.ctx(), &app.ui.language);+ crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default()));+ ready = true;+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(6);+ let preview = h.state().session.new_document_preview();+ assert!(preview.is_some(), "Preview is on");+ let centred = rect(&h);+ assert!(centred.width() > 900.0, "{centred:?}");+ let from = h.get_all_by_label("New Document").map(|n| n.rect().center()).min_by(|a, b| a.y.total_cmp(&b.y)).unwrap();+ let to = from + vec2(1300.0, 0.0);+ h.event(Event::PointerMoved(from));+ h.run_steps(1);+ h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });+ h.run_steps(1);+ for step in 1..=8 {+ h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0)));+ h.run_steps(1);+ }+ h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });+ h.run_steps(3);+ // All but 100 px of the window's width is past the right edge, over the preview.+ assert!((rect(&h).left() - 1300.0).abs() < 2.0, "{:?}", rect(&h));+ let app = h.state();+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("newDocument"));+ assert_eq!(app.session.new_document_preview(), preview, "moving the window keeps the preview");+ assert_eq!(app.session.documents().len(), 2);+ }++ #[test]+ fn margins_dialog_reads_bare_numbers_in_the_ruler_unit() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap();+ crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null);+ for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] {+ ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "15"}));+ }+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let top = app.session.active().unwrap().doc.page(0).unwrap().margins.top;+ assert!((top - 15.0 * 72.0 / 25.4).abs() < 0.01, "top margin was {top} pt");+ }+ fn facing_app(pages: u64) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": pages, "facingPages": true})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)));+ app+ }++ fn guide_counts(app: &DesignApp) -> Vec<usize> {+ let doc = &app.session.active().unwrap().doc;+ (0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect()+ }++ #[test]+ fn create_guides_dialog_targets_the_page_in_view() {+ let mut app = facing_app(6);+ crate::canvas::go_to_page(&mut app, 4);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "3"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(guide_counts(&app), vec![0, 0, 0, 0, 4, 0]);+ // "Both pages of the spread" covers the facing pair.+ crate::canvas::go_to_page(&mut app, 1);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "target", "value": "spread"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 4, 0]);+ }++ #[test]+ fn parent_dialogs_cover_both_pages_of_the_parent_spread_by_default() {+ let mut app = facing_app(4);+ app.run("layout.parents.edit", json!({"on": true})).unwrap();+ crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("target"), "spread");+ for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] {+ ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "20 pt"}));+ }+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let doc = &app.session.active().unwrap().doc;+ for pg in &doc.parents[0].pages {+ assert_eq!((pg.margins.top, pg.margins.outside, pg.guides.len()), (20.0, 20.0, 2));+ }+ // Every document page shows the parent's guides.+ assert!((0..doc.page_count()).all(|abs| doc.inherited_guides(abs).len() == 2));+ }++ #[test]+ fn other_dialogs_keep_reading_bare_numbers_as_picas() {+ let mut app = facing_app(2);+ app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap();+ app.ui.dialog = Some(Dialog::new("newDocument", json!({"width": "15"})));+ assert_eq!(app.ui.dialog.as_ref().unwrap().m("width"), Some(180.0));+ }+ #[test]+ fn character_style_options_set_the_digits() {+ let mut app = styled_app();+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.digits", "value": "farsi"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi));+ }diff --cc crates/ui-egui/src/menus/tables.rsindex 000000000,4d63d485f..ca4a647a2mode 000000,100644..100644--- a/crates/ui-egui/src/menus/tables.rs+++ b/crates/ui-egui/src/menus/tables.rs@@@ -1,0 -1,671 +1,672 @@@+ /// Menu bar: (menu, entries). Entries: `cmd:<id>`, `ui:<id>`, `-` separator, `>Submenu` … `<`.+ pub const MENUS: &[(&str, &[&str])] = &[+ (+ "File",+ &[+ "ui:app.newDocumentDialog",+ "ui:app.openDialog",+ ">Open Recent",+ "cmd:file.clearRecent",+ "<",+ "-",+ "cmd:file.close",+ "ui:app.save",+ "ui:app.saveDialog",+ "ui:app.saveCopyDialog",+ "cmd:file.revert",+ "-",+ "ui:app.placeDialog",+ "ui:app.placeWithOptions",+ "-",+ "ui:app.exportPdf",+ "ui:app.packageDialog",+ "ui:app.printBooklet",+ "ui:app.exportPng",+ "ui:app.exportIdml",+ "ui:app.exportEpub",+ "ui:app.exportFixedEpub",+ "ui:app.exportInteractivePdf",+ "ui:app.exportHtml",+ "ui:app.exportPptx",+ "ui:app.exportXml",+ "ui:app.exportText",+ ">Export",+ "cmd:snippet.export",+ "<",+ "-",+ "cmd:layout.documentSetup",+ "cmd:file.info",+ ],+ ),+ (+ "Edit",+ &[+ "cmd:edit.undo",+ "cmd:edit.redo",+ "-",+ "cmd:edit.cut",+ "cmd:edit.copy",+ "cmd:edit.paste",+ "cmd:edit.pasteWithoutFormatting",+ "cmd:edit.pasteInto",+ "cmd:edit.pasteInPlace",+ "cmd:edit.clear",+ "-",+ "cmd:edit.duplicate",+ "ui:app.placeAndLink",+ "cmd:edit.stepAndRepeat",+ "-",+ "cmd:edit.selectAll",+ "cmd:guide.selectAll",+ "cmd:edit.deselectAll",+ "-",+ "ui:app.findChange",+ "cmd:find.next",+ "ui:app.storyEditor",+ "-",+ ">Spelling",+ "cmd:spelling.check",+ "ui:edit.dynamicSpelling",+ "cmd:spelling.addWord",+ "ui:app.userDictionary",+ "<",+ ">Transparency Blend Space",+ "cmd:edit.transparencyBlendSpace|Document RGB|{\"space\": \"rgb\"}",+ "cmd:edit.transparencyBlendSpace|Document CMYK|{\"space\": \"cmyk\"}",+ "<",+ "ui:app.colorSettings",+ ">Transparency Flattener Presets",+ "ui:app.flattener|None (keep transparency)|{\"preset\": \"\"}",+ "ui:app.flattener|High Resolution|{\"preset\": \"high\"}",+ "ui:app.flattener|Medium Resolution|{\"preset\": \"medium\"}",+ "ui:app.flattener|Low Resolution|{\"preset\": \"low\"}",+ "<",+ "-",+ "ui:app.palette",+ "ui:app.keyboardShortcuts",+ "ui:app.menus",+ "ui:app.preferences",+ ],+ ),+ (+ "Layout",+ &[+ ">Pages",+ "cmd:layout.pages.insert",+ "cmd:layout.pages.move",+ "ui:app.duplicateSpread",+ "ui:app.deletePage",+ "-",+ "cmd:layout.pages.applyParent",+ "cmd:layout.parents.new",+ "<",+ "cmd:layout.marginsAndColumns",+ "cmd:layout.createGuides",+ "cmd:layout.createAlternate",+ "-",+ "ui:view.firstPage",+ "ui:view.previousPage",+ "ui:view.nextPage",+ "ui:view.lastPage",+ "ui:view.nextSpread",+ "ui:view.previousSpread",+ "ui:view.goToPage",+ "ui:view.goBack",+ "ui:view.goForward",+ "-",+ "cmd:layout.section",+ "cmd:toc.generate",+ "cmd:toc.update",+ ">Index",+ "cmd:index.addReference",+ "cmd:index.generate",+ "cmd:index.update",+ "<",+ ],+ ),+ (+ "Type",+ &[+ ">Size",+ "cmd:type.char|6 pt|{\"attrs\": {\"size\": 6}}",+ "cmd:type.char|7 pt|{\"attrs\": {\"size\": 7}}",+ "cmd:type.char|8 pt|{\"attrs\": {\"size\": 8}}",+ "cmd:type.char|9 pt|{\"attrs\": {\"size\": 9}}",+ "cmd:type.char|10 pt|{\"attrs\": {\"size\": 10}}",+ "cmd:type.char|11 pt|{\"attrs\": {\"size\": 11}}",+ "cmd:type.char|12 pt|{\"attrs\": {\"size\": 12}}",+ "cmd:type.char|14 pt|{\"attrs\": {\"size\": 14}}",+ "cmd:type.char|18 pt|{\"attrs\": {\"size\": 18}}",+ "cmd:type.char|24 pt|{\"attrs\": {\"size\": 24}}",+ "cmd:type.char|30 pt|{\"attrs\": {\"size\": 30}}",+ "cmd:type.char|36 pt|{\"attrs\": {\"size\": 36}}",+ "cmd:type.char|48 pt|{\"attrs\": {\"size\": 48}}",+ "cmd:type.char|60 pt|{\"attrs\": {\"size\": 60}}",+ "cmd:type.char|72 pt|{\"attrs\": {\"size\": 72}}",+ "<",+ "-",+ "ui:app.characterPanel",+ "ui:app.paragraphPanel",+ "ui:app.tabsPanel",+ "ui:app.glyphsPanel",+ "-",+ "ui:app.characterStylesPanel",+ "ui:app.paragraphStylesPanel",+ "-",+ "cmd:type.createOutlines",+ "ui:app.findFontDialog",+ "cmd:font.reload",+ ">Change Case",+ "cmd:type.changeCase|UPPERCASE|{\"case\": \"upper\"}",+ "cmd:type.changeCase|lowercase|{\"case\": \"lower\"}",+ "cmd:type.changeCase|Title Case|{\"case\": \"title\"}",+ "cmd:type.changeCase|Sentence case|{\"case\": \"sentence\"}",+ "<",+ "-",+ ">Type on a Path",+ "cmd:type.pathOptions",+ "cmd:type.pathOptions|Delete Type from Path|{\"delete\": true}",+ "<",+ "-",+ ">Notes",+ "cmd:note.new",+ "cmd:note.convertFromText",+ "ui:window.panel|Notes|{\"panel\": \"notes\"}",+ "-",+ "cmd:note.previous",+ "cmd:note.next",+ "<",+ ">Track Changes",+ "cmd:changes.track",+ "cmd:changes.acceptAll",+ "cmd:changes.rejectAll",+ "<",+ "-",+ "cmd:footnote.insert",+ "ui:app.footnoteOptionsDialog",+ "cmd:endnote.insert",+ "cmd:footnote.goToReference",+ "-",+ ">Hyperlinks & Cross-References",+ "cmd:hyperlink.create",+ "cmd:anchor.create",+ "-",+ "ui:app.insertXrefDialog",+ "cmd:xref.defineFormat",+ "<",+ ">Text Variables",+ "cmd:variables.define",+ "cmd:variables.insert",+ "cmd:variables.convertToText",+ "<",+ "-",+ ">Bulleted & Numbered Lists",+ "cmd:list.bullets",+ "cmd:list.numbers",+ "-",+ "cmd:list.define",+ "<",+ "-",+ ">Insert Special Character",+ ">Symbols",+ "cmd:text.insert|Bullet Character|{\"text\": \"\u{2022}\", \"raw\": true}",+ "cmd:text.insert|Copyright Symbol|{\"text\": \"\u{a9}\", \"raw\": true}",+ "cmd:text.insert|Ellipsis|{\"text\": \"\u{2026}\", \"raw\": true}",+ "cmd:text.insert|Paragraph Symbol|{\"text\": \"\u{b6}\", \"raw\": true}",+ "cmd:text.insert|Registered Trademark Symbol|{\"text\": \"\u{ae}\", \"raw\": true}",+ "cmd:text.insert|Section Symbol|{\"text\": \"\u{a7}\", \"raw\": true}",+ "cmd:text.insert|Trademark Symbol|{\"text\": \"\u{2122}\", \"raw\": true}",+ "<",+ ">Markers",+ "ui:app.insertCurrentPageNumber",+ "cmd:text.insert|Next Page Number|{\"text\": \"\u{e007}\", \"raw\": true}",+ "cmd:text.insert|Previous Page Number|{\"text\": \"\u{e008}\", \"raw\": true}",+ "cmd:text.insert|Section Marker|{\"text\": \"\u{e001}\", \"raw\": true}",+ "<",+ ">Hyphens and Dashes",+ "cmd:text.insert|Em Dash|{\"text\": \"\u{2014}\", \"raw\": true}",+ "cmd:text.insert|En Dash|{\"text\": \"\u{2013}\", \"raw\": true}",+ "cmd:text.insert|Discretionary Hyphen|{\"text\": \"\u{ad}\", \"raw\": true}",+ "cmd:text.insert|Nonbreaking Hyphen|{\"text\": \"\u{2011}\", \"raw\": true}",+ "<",+ ">Quotation Marks",+ "cmd:text.insert|Double Left Quotation Marks|{\"text\": \"\u{201c}\", \"raw\": true}",+ "cmd:text.insert|Double Right Quotation Marks|{\"text\": \"\u{201d}\", \"raw\": true}",+ "cmd:text.insert|Single Left Quotation Mark|{\"text\": \"\u{2018}\", \"raw\": true}",+ "cmd:text.insert|Single Right Quotation Mark|{\"text\": \"\u{2019}\", \"raw\": true}",+ "cmd:text.insert|Straight Double Quotation Marks|{\"text\": \"\\\"\", \"raw\": true}",+ "cmd:text.insert|Straight Single Quotation Mark (Apostrophe)|{\"text\": \"'\", \"raw\": true}",+ "<",+ ">Other",+ "cmd:text.insert|Tab|{\"text\": \"\\t\", \"raw\": true}",+ "cmd:text.insert|Right Indent Tab|{\"text\": \"\u{e006}\", \"raw\": true}",+ "cmd:text.insert|Indent to Here|{\"text\": \"\u{e005}\", \"raw\": true}",+ "<",+ "<",+ ">Insert White Space",+ "cmd:text.insert|Em Space|{\"text\": \"\u{2003}\", \"raw\": true}",+ "cmd:text.insert|En Space|{\"text\": \"\u{2002}\", \"raw\": true}",+ "cmd:text.insert|Nonbreaking Space|{\"text\": \"\u{a0}\", \"raw\": true}",+ "cmd:text.insert|Hair Space|{\"text\": \"\u{200a}\", \"raw\": true}",+ "cmd:text.insert|Sixth Space|{\"text\": \"\u{2006}\", \"raw\": true}",+ "cmd:text.insert|Thin Space|{\"text\": \"\u{2009}\", \"raw\": true}",+ "cmd:text.insert|Quarter Space|{\"text\": \"\u{2005}\", \"raw\": true}",+ "cmd:text.insert|Third Space|{\"text\": \"\u{2004}\", \"raw\": true}",+ "cmd:text.insert|Punctuation Space|{\"text\": \"\u{2008}\", \"raw\": true}",+ "cmd:text.insert|Figure Space|{\"text\": \"\u{2007}\", \"raw\": true}",+ "cmd:text.insert|Flush Space|{\"text\": \"\u{2001}\", \"raw\": true}",+ "<",+ ">Insert Break Character",+ "cmd:text.insert|Column Break|{\"text\": \"\u{e002}\", \"raw\": true}",+ "cmd:text.insert|Frame Break|{\"text\": \"\u{e003}\", \"raw\": true}",+ "cmd:text.insert|Page Break|{\"text\": \"\u{e004}\", \"raw\": true}",+ "cmd:text.insert|Odd Page Break|{\"text\": \"\u{e011}\", \"raw\": true}",+ "cmd:text.insert|Even Page Break|{\"text\": \"\u{e012}\", \"raw\": true}",+ "cmd:text.insert|Paragraph Return|{\"text\": \"\\n\", \"raw\": true}",+ "cmd:text.insert|Forced Line Break|{\"text\": \"\u{2028}\", \"raw\": true}",+ "<",+ "cmd:type.fillWithPlaceholder",+ "-",+ "ui:view.hiddenCharacters",+ "-",+ "cmd:math.insert",+ ">Story Direction",+ "cmd:type.storyDirection|Horizontal|{\"vertical\": false}",+ "cmd:type.storyDirection|Vertical|{\"vertical\": true}",+ "<",+ "cmd:type.tateChuYoko",+ "ui:app.rubyDialog",+ "cmd:type.kenten",+ "cmd:type.warichu",+ ],+ ),+ (+ "Object",+ &[+ ">Transform",+ "cmd:transform.move",+ "cmd:transform.scale",+ "cmd:transform.rotate",+ "cmd:transform.shear",+ "-",+ "cmd:transform.flip",+ "-",+ "cmd:transform.clear",+ "<",+ ">Transform Again",+ "cmd:transform.again",+ "cmd:transform.again|Transform Again Individually|{\"individually\": true}",+ "cmd:transform.again|Transform Sequence Again|{\"sequence\": true}",+ "cmd:transform.again|Transform Sequence Again Individually|{\"sequence\": true, \"individually\": true}",+ "<",+ ">Flex Layout",+ "cmd:flex.add",+ "cmd:flex.convert",+ "cmd:flex.remove",+ "-",+ "ui:window.panel|Show Flex Controls|{\"panel\": \"flexLayout\"}",+ "<",+ ">Paths",+ "cmd:object.makeCompoundPath",+ "cmd:object.releaseCompoundPath",+ "-",+ "cmd:path.reverse",+ "<",+ ">Pathfinder",+ "cmd:object.pathfinder|Add|{\"op\": \"add\"}",+ "cmd:object.pathfinder|Subtract|{\"op\": \"subtract\"}",+ "cmd:object.pathfinder|Intersect|{\"op\": \"intersect\"}",+ "cmd:object.pathfinder|Exclude Overlap|{\"op\": \"exclude\"}",+ "cmd:object.pathfinder|Minus Back|{\"op\": \"minusBack\"}",+ "<",+ ">Arrange",+ "cmd:object.bringToFront",+ "cmd:object.bringForward",+ "cmd:object.sendBackward",+ "cmd:object.sendToBack",+ "<",+ "-",+ "cmd:object.group",+ "cmd:object.ungroup",+ "cmd:object.lock",+ "cmd:object.unlockAll",+ "cmd:object.hide",+ "cmd:object.showAll",+ "-",+ "cmd:object.textFrameOptions",+ "ui:app.layerOptions",+ "cmd:object.exportOptions",+ "cmd:object.primaryTextFrame",+ "cmd:object.cornerOptions",+ "-",+ ">Effects",+ "ui:effects.dialog|Transparency…|{\"page\": \"transparency\"}",+ "cmd:object.dropShadow",+ "cmd:object.innerShadow",+ "cmd:object.outerGlow",+ "cmd:object.innerGlow",+ "cmd:object.bevel",+ "cmd:object.satin",+ "cmd:object.feather",+ "cmd:object.directionalFeather",+ "<",+ ">Select",+ "cmd:select.firstAbove",+ "cmd:select.nextAbove",+ "cmd:select.nextBelow",+ "cmd:select.lastBelow",+ "-",+ "cmd:select.container",+ "cmd:select.content",+ "-",+ "cmd:select.previousInGroup",+ "cmd:select.nextInGroup",+ "<",+ ">Convert Shape",+ "cmd:object.convertShape|Rectangle|{\"to\": \"rectangle\"}",+ "cmd:object.convertShape|Rounded Rectangle|{\"to\": \"roundedRectangle\"}",+ "cmd:object.convertShape|Beveled Rectangle|{\"to\": \"beveledRectangle\"}",+ "cmd:object.convertShape|Inverse Rounded Rectangle|{\"to\": \"inverseRoundedRectangle\"}",+ "cmd:object.convertShape|Ellipse|{\"to\": \"ellipse\"}",+ "cmd:object.convertShape|Triangle|{\"to\": \"triangle\"}",+ "cmd:object.convertShape|Polygon|{\"to\": \"polygon\"}",+ "cmd:object.convertShape|Line|{\"to\": \"line\"}",+ "cmd:object.convertShape|Orthogonal Line|{\"to\": \"orthogonalLine\"}",+ "-",+ "cmd:object.convertShape|Open Path|{\"to\": \"openPath\"}",+ "cmd:object.convertShape|Closed Path|{\"to\": \"closedPath\"}",+ "<",+ "ui:app.qrCode",+ ">Clipping Path",+ "cmd:object.clippingPathOptions|None|{\"type\": \"none\"}",+ "cmd:object.clippingPath|Alpha Channel|{\"type\": \"alpha\"}",+ "cmd:object.clippingPath|Detect Edges|{\"type\": \"edges\"}",+ "<",+ ">Captions",+ "cmd:object.caption",+ "cmd:object.caption|Generate Live Caption|{\"live\": true}",+ "<",+ ">Anchored Object",+ "cmd:anchored.options",+ "cmd:anchored.release",+ "<",+ ">Fitting",+ "ui:fit.fillFrameProportionally",+ "ui:fit.contentProportionally",+ "ui:fit.frameToContent",+ "ui:fit.contentToFrame",+ "ui:fit.centerContent",+ "-",+ "ui:app.fittingOptions",+ "<",+ ">Content",+ "cmd:object.content|Graphic|{\"type\":\"graphic\"}",+ "cmd:object.content|Text|{\"type\":\"text\"}",+ "cmd:object.content|Unassigned|{\"type\":\"unassigned\"}",+ "<",+ ],+ ),+ (++ // InDesign's order. The Table panel is in Window › Type & Tables (Shift+F9).+ "Table",+ &[+ "ui:app.insertTableDialog",+ "cmd:table.convertFromText",+ "cmd:table.convertToText",+ "-",++ ">Cell Options",++ "ui:app.cellOptionsDialog",++ "<",++ "-",+ ">Insert",+ "cmd:table.insertRowAbove",+ "cmd:table.insertRowBelow",+ "cmd:table.insertColumnLeft",+ "cmd:table.insertColumnRight",+ "<",+ ">Delete",+ "cmd:table.deleteRow",+ "cmd:table.deleteColumn",+ "cmd:table.delete",+ "<",+ ">Select",+ "cmd:table.selectRow",+ "cmd:table.selectColumn",+ "cmd:table.selectTable",+ "<",+ "-",- ">Cell Options",- "ui:app.cellOptionsDialog",- "<",+ "cmd:table.merge",+ "cmd:table.unmerge",++ "cmd:table.splitHorizontally",++ "cmd:table.splitVertically",+ ">Convert Cell Type",+ "ui:app.graphicCell|Convert Cell to Graphic Cell…",+ "cmd:table.textCell",+ "<",+ ">Convert Rows",+ "cmd:table.convertRowsToHeader",+ "cmd:table.convertRowsToBody",+ "cmd:table.convertRowsToFooter",+ "<",- "cmd:table.splitHorizontally",- "cmd:table.splitVertically",- "cmd:table.distributeColumns",- "cmd:table.distributeRows",+ "-",- "ui:app.tablePanel",++ "cmd:table.distributeRows",++ "cmd:table.distributeColumns",+ ],+ ),+ (+ "View",+ &[+ "ui:view.overprintPreview",+ ">Proof Setup",+ "ui:view.proofSetup|Working CMYK|{\"target\": \"workingCmyk\"}",+ "ui:view.proofSetup|Internet Standard RGB (sRGB)|{\"target\": \"srgb\"}",+ "ui:view.proofSetup|Legacy Macintosh RGB|{\"target\": \"legacyMacRgb\"}",+ "ui:view.proofSetup|Monitor RGB|{\"target\": \"monitorRgb\"}",+ "ui:view.proofSetup|Color Blindness – Protanopia|{\"target\": \"protanopia\"}",+ "ui:view.proofSetup|Color Blindness – Deuteranopia|{\"target\": \"deuteranopia\"}",+ "-",+ "ui:view.proofSetup|Simulate Paper Color|{\"simulatePaper\": \"toggle\"}",+ "<",+ "ui:view.proofColors",+ ">Separations Preview",+ "ui:view.separations|Off|{\"plate\": null, \"inkLimit\": null}",+ "ui:view.separations|All Inks|{\"plate\": \"all\"}",+ "ui:view.separations|Cyan|{\"plate\": \"cyan\"}",+ "ui:view.separations|Magenta|{\"plate\": \"magenta\"}",+ "ui:view.separations|Yellow|{\"plate\": \"yellow\"}",+ "ui:view.separations|Black|{\"plate\": \"black\"}",+ "ui:view.separations|Ink Limit 300%|{\"inkLimit\": 300}",+ "<",+ "ui:view.flattenerPreview",+ "-",+ "ui:view.zoomIn",+ "ui:view.zoomOut",+ "ui:view.fitPage",+ "ui:view.fitSelection",+ "ui:view.fitSpread",+ "ui:view.actualSize",+ "ui:view.entirePasteboard",+ "-",+ ">Rotate Spread",+ "ui:view.rotateSpread|90° CW|{\"angle\": 90}",+ "ui:view.rotateSpread|90° CCW|{\"angle\": -90}",+ "ui:view.rotateSpread|180°|{\"angle\": 180}",+ "ui:view.rotateSpread|Clear Rotation|{\"angle\": 0}",+ "<",+ "-",+ ">Screen Mode",+ "ui:view.screenMode|Normal|{\"mode\": \"normal\"}",+ "ui:view.screenMode|Preview|{\"mode\": \"preview\"}",+ "ui:view.screenMode|Bleed|{\"mode\": \"bleed\"}",+ "ui:view.screenMode|Slug|{\"mode\": \"slug\"}",+ "ui:view.screenMode|Presentation|{\"mode\": \"presentation\"}",+ "<",+ ">Display Performance",+ "ui:view.fastDisplay",+ "ui:view.typicalDisplay",+ "ui:view.highQualityDisplay",+ "<",+ "-",+ "ui:view.rulers",+ "-",+ ">Extras",+ "ui:view.frameEdges",+ "ui:view.textThreads",+ "<",+ ">Grids & Guides",+ "ui:view.guides",+ "ui:view.lockGuides",+ "cmd:view.lockColumnGuides",+ "ui:view.snapToGuides",+ "ui:view.snapToDocumentGrid",+ "ui:view.smartGuides",+ "ui:view.baselineGrid",+ "ui:view.documentGrid",+ "-",+ "ui:app.deleteAllGuides",+ "<",+ "-",+ ">Structure",+ "ui:view.taggedFrames",+ "ui:view.tagMarkers",+ "<",+ ">Story Editor",+ "ui:view.storyEditorDepthRuler",+ "<",+ ],+ ),+ (+ "Window",+ // InDesign's order: Arrange, Workspace, then the panels alphabetically with their groups.+ &[+ ">Arrange",+ "ui:window.newWindow",+ "ui:window.split",+ "-",+ "ui:window.nextDocument",+ "ui:window.previousDocument",+ "<",+ "ui:window.workspace",+ "-",+ "ui:window.panel|Articles|{\"panel\": \"articles\"}",+ ">Color",+ "ui:window.panel|Color|{\"panel\": \"color\"}",+ "ui:window.panel|Gradient|{\"panel\": \"gradient\"}",+ "ui:window.panel|Swatches|{\"panel\": \"swatches\"}",+ "<",+ "ui:window.taskBar",+ "ui:window.controlBar",+ ">Editorial",+ "ui:window.panel|Notes|{\"panel\": \"notes\"}",+ "ui:window.panel|Track Changes|{\"panel\": \"trackChanges\"}",+ "<",+ "ui:window.panel|Effects|{\"panel\": \"effects\"}",+ "ui:window.panel|Info|{\"panel\": \"info\"}",+ ">Interactive",+ "ui:window.panel|Bookmarks|{\"panel\": \"bookmarks\"}",+ "ui:window.panel|Buttons and Forms|{\"panel\": \"buttons\"}",+ "ui:window.panel|Hyperlinks|{\"panel\": \"hyperlinks\"}",+ "ui:window.panel|Liquid Layout|{\"panel\": \"liquid\"}",+ "ui:window.panel|Media|{\"panel\": \"media\"}",+ "ui:window.panel|Object States|{\"panel\": \"states\"}",+ "ui:window.panel|Page Transitions|{\"panel\": \"transitions\"}",+ "<",+ "ui:window.panel|Layers|{\"panel\": \"layers\"}",+ "ui:window.panel|Links|{\"panel\": \"links\"}",+ ">Object & Layout",+ "ui:window.panel|Align|{\"panel\": \"align\"}",+ "ui:window.panel|Flex Layout|{\"panel\": \"flexLayout\"}",+ "ui:window.panel|Pathfinder|{\"panel\": \"pathfinder\"}",+ "<",+ ">Output",+ "ui:window.panel|Attributes|{\"panel\": \"attributes\"}",+ "ui:window.panel|Preflight|{\"panel\": \"preflight\"}",+ "ui:window.panel|Separations Preview|{\"panel\": \"separations\"}",+ "<",+ "ui:window.panel|Pages|{\"panel\": \"pages\"}",+ "ui:window.panel|Properties|{\"panel\": \"properties\"}",+ "ui:window.panel|Stroke|{\"panel\": \"stroke\"}",+ ">Styles",+ "ui:window.panel|Character Styles|{\"panel\": \"characterStyles\"}",+ "ui:window.panel|Paragraph Styles|{\"panel\": \"paragraphStyles\"}",+ "<",+ "ui:window.panel|Text Wrap|{\"panel\": \"textWrap\"}",+ ">Type & Tables",+ "ui:window.panel|Character|{\"panel\": \"character\"}",+ "ui:window.panel|Conditional Text|{\"panel\": \"conditions\"}",+ "ui:window.panel|Glyphs|{\"panel\": \"glyphs\"}",+ "ui:window.panel|Paragraph|{\"panel\": \"paragraph\"}",+ "ui:window.panel|Story|{\"panel\": \"story\"}",+ "ui:window.panel|Table|{\"panel\": \"table\"}",+ "ui:app.tabsPanel",+ "ui:window.panel|Typography|{\"panel\": \"typography\"}",+ "<",+ ">Utilities",+ "ui:window.panel|Book|{\"panel\": \"book\"}",+ "ui:window.panel|Data Merge|{\"panel\": \"dataMerge\"}",+ "ui:window.panel|Library|{\"panel\": \"library\"}",+ "ui:window.panel|Scripts|{\"panel\": \"scripts\"}",+ "ui:window.panel|Tags|{\"panel\": \"tags\"}",+ "<",+ "-",+ "ui:window.hidePanels",+ "ui:window.hidePanelsExceptTools",+ "ui:window.toolsDoubleColumn",+ "-",+ "ui:window.brightness",+ ],+ ),+ (+ "Help",+ &[+ "ui:help.discord",+ "-",+ "ui:help.appPage",+ "ui:help.github",+ "ui:help.issues",+ "ui:help.website",+ "-",+ "cmd:file.newSample",+ "-",+ "ui:help.checkForUpdates",+ "ui:help.about",+ ],+ ),+ ];++ /// The built-in workspaces, in InDesign's order.+ pub const WORKSPACES: &[&str] =+ &["Advanced", "Book", "Digital Publishing", "Essentials", "Essentials Classic", "Interactive for PDF", "Printing and Proofing", "Typography"];++ /// The built-in workspaces that open a panel below the Properties · Pages · Layers group.+ pub const WORKSPACE_OPEN_PANELS: &[(&str, &str)] =+ &[("Printing and Proofing", "swatches"), ("Interactive for PDF", "buttons"), ("Digital Publishing", "liquid")];++ /// The panel the built-in workspace `name` opens below the Properties · Pages · Layers group.+ pub fn workspace_open_panel(name: &str) -> Option<&'static str> {+ WORKSPACE_OPEN_PANELS.iter().find(|(workspace, _)| *workspace == name).map(|(_, panel)| *panel)+ }++ /// Essentials Classic's iconic column: InDesign's iconic panel groups, top to bottom.+ pub const CLASSIC_GROUPS: &[&[&str]] = &[+ &["pages", "layers", "links"],+ &["stroke", "color"],+ &["swatches"],+ &["effects"],+ &["paragraph"],+ &["textWrap"],+ &["characterStyles", "paragraphStyles"],+ &["gradient"],+ ];++ /// The Typography preset's available panels in the order observed in InDesign's workspace.+ /// CC Libraries has no corresponding DesignCraft panel, and where the Story panel sits in it is+ /// not recorded, so these groups leave it out.+ pub const TYPOGRAPHY_GROUPS: &[&[&str]] = &[+ &["pages", "layers", "swatches"],+ &["glyphs", "textWrap"],+ &["stroke", "gradient"],+ &["hyperlinks", "effects"],+ &["paragraph", "paragraphStyles"],+ &["character", "characterStyles"],+ ];diff --cc crates/ui-egui/src/menus/tests.rsindex 000000000,5e82f6d3f..57ce99cd6mode 000000,100644..100644--- a/crates/ui-egui/src/menus/tests.rs+++ b/crates/ui-egui/src/menus/tests.rs@@@ -1,0 -1,2978 +1,3019 @@@+ use super::*;++ /// The entries (command ids) of a menu bar menu, submenus included.+ fn menu_ids(title: &str) -> Vec<&'static str> {+ let items = MENUS.iter().find(|(t, _)| *t == title).map(|(_, items)| *items).unwrap_or_default();+ items.iter().filter_map(|e| e.split_once(':').map(|(_, rest)| rest.split('|').next().unwrap_or(rest))).collect()+ }++ #[test]+ fn view_items_are_in_the_view_menu_as_in_indesign() {+ let (view, typ) = (menu_ids("View"), menu_ids("Type"));+ for id in [+ "view.rotateSpread",+ "view.proofSetup",+ "view.proofColors",+ "view.flattenerPreview",+ "view.separations",+ "view.taggedFrames",+ "view.tagMarkers",+ "view.storyEditorDepthRuler",+ ] {+ assert!(view.contains(&id), "{id} is in View");+ assert!(!typ.contains(&id), "{id} isn't in Type");+ }+ // Screen Mode and Extras are View submenus; Show Hidden Characters stays in Type.+ assert!(view.contains(&"view.screenMode") && view.contains(&"view.frameEdges"));+ assert!(typ.contains(&"view.hiddenCharacters") && !view.contains(&"view.hiddenCharacters"));+ // W still toggles Normal / Preview without a menu entry.+ assert_eq!(ui_label("view.togglePreview").and_then(|c| c.1), Some("W"));+ }++ /// The submenu paths of a menu bar menu ("View/Screen Mode"), as Edit › Menus keys them.+ fn submenu_paths(title: &str) -> Vec<String> {+ let items = MENUS.iter().find(|(t, _)| *t == title).map(|(_, items)| *items).unwrap_or_default();+ let mut stack = vec![title.to_string()];+ let mut out = Vec::new();+ for e in items {+ if let Some(name) = e.strip_prefix('>') {+ let path = format!("{}/{name}", stack.last().map_or("", String::as_str));+ out.push(path.clone());+ stack.push(path);+ } else if *e == "<" {+ stack.pop();+ }+ }+ out+ }++ /// A command's menu path names the menu entries that really hold it.+ #[test]+ fn define_lists_command_path_matches_the_type_menu() {+ let spec = designcraft_engine::command_specs().iter().find(|c| c.id == "list.define").expect("list.define is a command");+ assert_eq!(spec.menu[0], "Type");+ assert!(submenu_paths("Type").contains(&spec.menu.join("/")), "{:?} is not a Type submenu", spec.menu);+ assert!(menu_ids("Type").contains(&"list.define"));+ }++ #[test]+ fn screen_mode_shows_the_current_mode() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let mode = |app: &DesignApp, m: &str| checked(app, "view.screenMode", &json!({ "mode": m }));+ assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(true), Some(false)));+ app.ui.screen_mode = crate::ScreenMode::Preview;+ assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(false), Some(true)));+ }++ fn walk(items: &[Item], out: &mut Vec<(String, String, Value)>) {+ for it in items {+ match it {+ Item::Sub(_, c) => walk(c, out),+ Item::Cmd { label, id, params, .. } => out.push((label.clone(), id.clone(), params.clone())),+ Item::Sep => {}+ }+ }+ }++ /// Exercise the real dropdown, including clipping and wheel input, on a short viewport.+ #[test]+ fn oversized_edit_menu_scrolls_to_preferences() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 260.0));+ let mut tick = 0;+ let mut frame = |app: &mut DesignApp, events: Vec<egui::Event>| {+ tick += 1;+ let mut output =+ ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| {+ egui::MenuBar::new().ui(ui, |ui| menu_bar(app, ui));+ });+ output.textures_delta.clear();+ let mut labels = Vec::new();+ fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) {+ match shape {+ egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)),+ egui::Shape::Vec(shapes) => {+ for shape in shapes {+ collect(shape, clip, labels);+ }+ }+ _ => {}+ }+ }+ for shape in output.shapes {+ collect(&shape.shape, shape.clip_rect, &mut labels);+ }+ labels+ };+ frame(&mut app, vec![]);+ let labels = frame(&mut app, vec![]);+ let edit = labels.iter().find(|(text, _, _)| text == "Edit").unwrap().1.center();+ for pressed in [true, false] {+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(edit),+ egui::Event::PointerButton { pos: edit, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ for _ in 0..3 {+ frame(&mut app, vec![]);+ }+ let layer = ctx.layer_id_at(egui::pos2(edit.x + 80.0, 100.0)).expect("menu layer");+ let bounds = ctx.memory(|m| m.area_rect(layer.id)).expect("menu bounds");+ let track = egui::pos2(bounds.right() - 9.0, bounds.bottom() - 25.0);+ for pressed in [true, false] {+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(track),+ egui::Event::PointerButton { pos: track, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ assert!(egui::Popup::is_any_open(&ctx), "clicking the scroll track must not dismiss the menu");+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(egui::pos2(edit.x + 80.0, 100.0)),+ egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: egui::vec2(0.0, -3000.0),+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ source: egui::MouseWheelSource::Unknown,+ },+ ],+ );+ let mut labels = Vec::new();+ for _ in 0..60 {+ labels = frame(&mut app, vec![]);+ }+ let (_, rect, clip) = labels.iter().find(|(text, _, _)| text == "Preferences…").expect("Preferences is rendered");+ assert!(screen.contains_rect(*rect) && clip.contains_rect(*rect), "Preferences must be visible after scrolling: {rect:?}, {clip:?}");+ let pos = rect.center();+ for pressed in [true, false] {+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(pos),+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences"));+ assert!(!egui::Popup::is_any_open(&ctx), "choosing a command dismisses the menu");+ }++ #[test]+ fn formatting_affects_text_sends_swatches_to_the_text() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ for (name, color) in [("Cyan", "#00ffff"), ("Magenta", "#ff00ff")] {+ let created = app.run("swatch.create", json!({"name": name, "color": color})).unwrap();+ assert_eq!(created["name"], name);+ }+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words", "caret": false})).unwrap();+ let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());+ app.run("selection.set", json!({"ids": [fid]})).unwrap();+ let text_fill = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone();+ st.char_format_at(2).over.fill.clone()+ };+ let frame_fill = |app: &crate::DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(fid)).unwrap().fill.swatch.clone();+ assert!(!crate::panels::colors_affect_text(&app));+ crate::panels::apply_swatch(&mut app, false, "C=100 M=0 Y=0 K=0", None).unwrap();+ assert_eq!(frame_fill(&app), "C=100 M=0 Y=0 K=0");+ assert_eq!(text_fill(&app), None);+ let r = run_ui(&mut app, "app.formattingAffectsText", &json!({})).unwrap().unwrap();+ assert_eq!(r["on"], true, "toggles on");+ assert!(crate::panels::colors_affect_text(&app));+ crate::panels::apply_swatch(&mut app, false, "C=0 M=100 Y=0 K=0", Some(0.5)).unwrap();+ assert_eq!(frame_fill(&app), "C=100 M=0 Y=0 K=0", "the frame is left alone");+ assert_eq!(text_fill(&app).as_deref(), Some("C=0 M=100 Y=0 K=0"));+ assert_eq!(crate::panels::color_target(&mut app).map(|t| (t.0, t.1)), Some(("C=0 M=100 Y=0 K=0".to_string(), 0.5)));+ }++ #[test]+ fn transform_menu_items_open_their_dialogs() {+ for id in ["transform.move", "transform.scale", "transform.rotate", "transform.shear"] {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ activate(&mut app, id, &Value::Null);+ let dialog = app.ui.dialog.as_ref().map(|d| d.id.clone());+ assert_eq!(dialog.as_deref(), Some(format!("cmd:{id}").as_str()), "{id} opens its dialog");+ }+ }++ #[test]+ fn pdf_export_menu_item_opens_the_dialog_or_exports() {+ // No params: the menu item opens the options dialog.+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ activate(&mut app, "app.exportPdf", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfExport"));+ // Explicit options: programmatic callers still export directly, opening no dialog.+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ activate(&mut app, "app.exportPdf", &json!({"path": "/tmp/x.pdf"}));+ assert!(app.ui.dialog.is_none());+ }++ #[test]+ fn snap_preferences_are_a_command() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let r = run_ui(&mut app, "view.snapPreferences", &json!({"smartSpacing": false, "zone": 8})).unwrap().unwrap();+ assert_eq!(r["smartSpacing"], false);+ assert_eq!(r["alignEdges"], true, "unnamed switches keep their value");+ assert_eq!(r["zone"], 8.0);+ assert!(!app.ui.smart_spacing && (app.ui.snap_zone - 8.0).abs() < 1e-9);+ let r = run_ui(&mut app, "view.snapPreferences", &json!({"zone": -3})).unwrap().unwrap();+ assert_eq!(r["zone"], 0.0, "a negative zone turns snapping off");+ }++ /// Every command with a shortcut in effect: (command key, shortcut), in dispatch order. UI+ /// commands come first: where one shares keys with an engine command (⌘N, ⌘O…) it's the one+ /// with the dialog.+ fn effective_shortcuts(app: &DesignApp) -> Vec<(String, String)> {+ app.keymap.catalog().iter().filter_map(|b| crate::keys::shortcut(&app.keymap, &b.command).map(|s| (b.command.key(), s))).collect()+ }++ #[test]+ #[cfg(not(target_arch = "wasm32"))]+ fn shortcut_edits_wait_for_the_dialog_and_the_menu_bar_owns_its_paste_chord() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ crate::shortcuts_dialog::open(&mut app, None);+ for (id, p) in [+ ("window.setShortcut", json!({"id": "app.palette", "shortcut": "F2"})),+ ("window.resetShortcuts", json!({})),+ ("window.importShortcuts", json!({"text": ""})),+ ] {+ assert!(run_ui(&mut app, id, &p).unwrap().is_err(), "{id} while the dialog is open");+ }+ crate::shortcuts_dialog::close(&mut app, false).unwrap();+ // A chord of the user's: the default one is the bar's from the start.+ run_ui(&mut app, "window.setShortcut", &json!({"id": "edit.pasteInPlace", "shortcut": "Cmd+Alt+V", "steal": true})).unwrap().unwrap();+ let held = egui::Modifiers::COMMAND | egui::Modifiers::ALT;+ app.native_menu = true;+ assert_eq!(paste_chord_command(&app, held), Some("edit.pasteInPlace"), "before the bar carries it");+ app.native_shortcuts.insert("edit.pasteInPlace".into(), "Cmd+Alt+V".into());+ assert_eq!(paste_chord_command(&app, held), None, "the bar's key equivalent runs it, once");+ }++ #[test]+ fn custom_shortcuts_override_defaults() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ assert_eq!(shortcut_of(&app, "app.preferences").as_deref(), Some("Cmd+K"));+ let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "app.preferences", "shortcut": "Cmd+Alt+Shift+9"})).unwrap().unwrap();+ assert_eq!(r["shortcut"], "Cmd+Alt+Shift+9");+ assert!(effective_shortcuts(&app).contains(&("app.preferences".into(), "Cmd+Alt+Shift+9".into())));+ // Taking another command's keys reports the conflict.+ let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": "Cmd+Alt+Shift+9"})).unwrap().unwrap();+ assert_eq!(r["conflicts"], json!(["app.preferences"]));+ run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": ""})).unwrap().unwrap();+ assert_eq!(shortcut_of(&app, "app.palette"), None);+ assert!(run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": "Cmd+Nope"})).unwrap().is_err());+ run_ui(&mut app, "window.resetShortcuts", &json!({})).unwrap().unwrap();+ // ⌘N is the New Document dialog, not a bare file.new.+ let first_cmd_n = effective_shortcuts(&app).into_iter().find(|(_, s)| s == "Cmd+N").map(|(i, _)| i);+ assert_eq!(first_cmd_n.as_deref(), Some("app.newDocumentDialog"));+ assert_eq!(shortcut_of(&app, "app.palette").as_deref(), Some("Cmd+Enter"));+ assert_eq!(+ crate::keys::chord_text(egui::Modifiers { command: true, shift: true, ..Default::default() }, egui::Key::K).as_deref(),+ Some("Cmd+Shift+K")+ );+ if cfg!(target_os = "macos") {+ assert_eq!(shortcut_text("Cmd+Alt+3"), "⌥⌘3");+ assert_eq!(shortcut_text("Cmd+Shift+."), "⇧⌘.");+ } else {+ assert_eq!(shortcut_text("Cmd+Alt+3"), "Ctrl+Alt+3");+ }+ }++ /// One frame of key presses through the shortcut dispatcher.+ fn press_keys(app: &mut crate::DesignApp, ctx: &egui::Context, keys: &[(egui::Key, egui::Modifiers)]) {+ let events = keys+ .iter()+ .flat_map(|&(key, modifiers)| [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }))+ .collect();+ ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| shortcuts(app, &ui.ctx().clone())).textures_delta.clear();+ }++ #[test]+ fn shortcuts_saved_as_a_map_by_older_versions_load_unchanged() {+ let saved = br#"{"shortcuts": {"app.preferences": "Cmd+Alt+Shift+9", "app.palette": "", "file.close": [""]}}"#;+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui = crate::UiState::from_preferences_json(saved).unwrap();+ app.sync_keymap();+ assert_eq!(shortcut_of(&app, "app.preferences").as_deref(), Some("Cmd+Alt+Shift+9"));+ assert_eq!(shortcut_of(&app, "app.palette"), None, "a removed default stays removed");+ assert_eq!(shortcut_of(&app, "file.close"), None);+ assert_eq!(shortcut_of(&app, "app.save").as_deref(), Some("Cmd+S"));+ // Saved again it reads back the same, in the map form an older version reads.+ let resaved = serde_json::to_vec(&app.ui).unwrap();+ assert_eq!(crate::UiState::from_preferences_json(&resaved).unwrap().shortcuts, app.ui.shortcuts);+ let saved: Value = serde_json::from_slice(&resaved).unwrap();+ assert_eq!(saved["shortcuts"], json!({"app.preferences": "Cmd+Alt+Shift+9", "app.palette": "", "file.close": ""}));+ }++ #[test]+ fn panel_shortcuts_open_their_panels() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let shown = |app: &crate::DesignApp, p: &str| crate::panel_docking::showing(app, p);+ assert!(!shown(&app, "layers"));+ press_keys(&mut app, &ctx, &[(egui::Key::F7, egui::Modifiers::NONE)]);+ assert!(shown(&app, "layers"), "F7 opens Layers");+ // A panel without a default key takes one.+ let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "window.panel", "params": {"panel": "links"}, "shortcut": "Shift+F12"}))+ .unwrap()+ .unwrap();+ assert_eq!(r["shortcut"], "Shift+F12");+ press_keys(&mut app, &ctx, &[(egui::Key::F12, egui::Modifiers::SHIFT)]);+ assert!(shown(&app, "links"), "the new key opens Links");+ }++ #[test]+ fn a_reassigned_tool_key_selects_the_tool_and_the_old_key_does_not() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let none = egui::Modifiers::NONE;+ run_ui(&mut app, "window.setShortcut", &json!({"id": "pen", "shortcut": "Y"})).unwrap().unwrap();+ press_keys(&mut app, &ctx, &[(egui::Key::P, none)]);+ assert_eq!(app.session.tool_id(), "selection", "P no longer selects the Pen");+ press_keys(&mut app, &ctx, &[(egui::Key::Y, none)]);+ assert_eq!(app.session.tool_id(), "pen");+ // Tools sharing a key take turns.+ press_keys(&mut app, &ctx, &[(egui::Key::B, none)]);+ assert_eq!(app.session.tool_id(), "contentCollector");+ press_keys(&mut app, &ctx, &[(egui::Key::B, none)]);+ assert_eq!(app.session.tool_id(), "contentPlacer");+ }++ #[test]+ fn split_window_panes_have_their_own_views() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp| {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ frame(&mut app);+ assert_eq!(run_ui(&mut app, "window.split", &json!({})).unwrap().unwrap(), json!(true));+ frame(&mut app);+ frame(&mut app);+ // Both panes have a canvas, each half as wide.+ let r0 = app.canvas_rect.unwrap();+ let r1 = app.other_pane.as_ref().and_then(|o| o.1).unwrap();+ assert!(r0.width() < 800.0 && r1.width() < 800.0 && (r0.center().x - r1.center().x).abs() > 300.0, "{r0:?} {r1:?}");+ // Zooming the right pane leaves the left alone.+ app.switch_pane(1);+ let z0 = app.view().unwrap().zoom;+ crate::canvas::set_zoom(&mut app, z0 * 3.0);+ app.switch_pane(0);+ assert!((app.view().unwrap().zoom - z0).abs() < 1e-9);+ app.switch_pane(1);+ assert!((app.view().unwrap().zoom - z0 * 3.0).abs() < 1e-6);+ assert_eq!(run_ui(&mut app, "window.split", &json!({})).unwrap().unwrap(), json!(false));+ assert_eq!(app.pane, 0);+ frame(&mut app);+ }++ #[test]+ fn split_window_dispatches_text_once_to_the_shared_document() {+ for focus_pane in [0, 1] {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let made = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap();+ let story = made["story"].as_u64().unwrap();+ app.session.set_tool("type");+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap();+ assert!(app.session.wants_text());+ app.run("window.split", json!({"on": true})).unwrap();+ app.focus_pane = focus_pane;++ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ let undo_before = app.session.active().unwrap().history.undo.len();+ frame(&mut app, vec![egui::Event::Text("A".into())]);+ let text = app.run("story.get", json!({"story": story})).unwrap();+ assert_eq!(text["text"], "A", "one key press with pane {focus_pane} focused");+ assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.run("story.get", json!({"story": story})).unwrap()["text"], "");++ // A press and key arriving together must use the newly focused pane, whichever+ // canvas is drawn first. Middle-click changes pane focus without moving the caret.+ let other = app.other_pane.as_ref().and_then(|p| p.1).unwrap().center();+ frame(&mut app, vec![egui::Event::PointerMoved(other)]);+ frame(+ &mut app,+ vec![+ egui::Event::PointerButton { pos: other, button: egui::PointerButton::Middle, pressed: true, modifiers: egui::Modifiers::NONE },+ egui::Event::Text("B".into()),+ ],+ );+ assert_eq!(app.focus_pane, 1 - focus_pane);+ assert_eq!(app.run("story.get", json!({"story": story})).unwrap()["text"], "B", "a key in the pane-switch frame is dispatched once");+ assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);+ }+ }++ #[test]+ fn split_window_click_focus_routes_menu_zoom_but_hover_scroll_stays_local() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("window.split", json!({"on": true})).unwrap();+ let ctx = egui::Context::default();+ let mut time = 0.0;+ let mut frame = |app: &mut crate::DesignApp, events| {+ time += 0.1;+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ time: Some(time),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ for _ in 0..3 {+ frame(&mut app, vec![]);+ }+ let left = app.canvas_rect.unwrap().center();+ let right = app.other_pane.as_ref().and_then(|p| p.1).unwrap().center();+ let cameras = |app: &mut crate::DesignApp| {+ let current = app.pane;+ app.switch_pane(0);+ let left = *app.view().unwrap();+ app.switch_pane(1);+ let right = *app.view().unwrap();+ app.switch_pane(current);+ [left, right]+ };+ let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };+ frame(&mut app, vec![egui::Event::PointerMoved(right)]);+ frame(&mut app, vec![button(right, true)]);+ frame(&mut app, vec![button(right, false)]);+ assert_eq!((app.pane, app.focus_pane), (1, 1));+ let before = cameras(&mut app);+ app.run("view.zoom", json!({"zoom": 2.0})).unwrap();+ let zoomed = cameras(&mut app);+ assert_eq!(zoomed[0], before[0], "menu zoom leaves the other camera alone");+ assert!((zoomed[1].zoom - 2.0).abs() < 1e-9);++ frame(&mut app, vec![egui::Event::PointerMoved(left)]);+ frame(+ &mut app,+ vec![egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: egui::vec2(0.0, -40.0),+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ source: egui::MouseWheelSource::Unknown,+ }],+ );+ let scrolled = cameras(&mut app);+ assert_eq!(scrolled[1], zoomed[1], "hover scroll leaves the focused camera alone");+ assert_ne!(scrolled[0].origin, zoomed[0].origin);+ assert_eq!((app.pane, app.focus_pane), (1, 1), "hovering does not move menu focus");++ frame(&mut app, vec![button(left, true)]);+ frame(&mut app, vec![button(left, false)]);+ assert_eq!((app.pane, app.focus_pane), (0, 0));+ app.run("view.zoom", json!({"zoom": 1.0})).unwrap();+ let final_views = cameras(&mut app);+ assert!((final_views[0].zoom - 1.0).abs() < 1e-9);+ assert_eq!(final_views[1], scrolled[1]);+ }++ #[test]+ fn split_window_contextual_bars_have_independent_widget_ids() {+ fn id_warnings(shape: &egui::Shape, found: &mut Vec<String>) {+ match shape {+ egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| id_warnings(shape, found)),+ egui::Shape::Text(text) if text.galley.text().contains("use of widget ID") => found.push(text.galley.text().to_string()),+ _ => {}+ }+ }++ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ for rect in [[36, 36, 280, 180], [300, 36, 550, 180]] {+ app.run("frame.create", json!({"rect": rect, "content": "unassigned"})).unwrap();+ }+ app.run("edit.selectAll", json!({})).unwrap();+ app.run("window.split", json!({"on": true})).unwrap();+ let ctx = egui::Context::default();+ ctx.options_mut(|options| options.warn_on_id_clash = true);+ let mut warnings = Vec::new();+ for _ in 0..4 {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut output = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ warnings.clear();+ for shape in &output.shapes {+ id_warnings(&shape.shape, &mut warnings);+ }+ output.textures_delta.clear();+ }+ assert!(warnings.is_empty(), "both bars reused the same interactive widget IDs: {warnings:?}");+ let bars: Vec<_> =+ (0_u8..2).map(|pane| ctx.memory(|memory| memory.area_rect(egui::Id::unique(("task_bar", egui::ViewportId::ROOT, pane)))).unwrap()).collect();+ assert!(!bars[0].intersects(bars[1]), "each pane keeps its own bar: {bars:?}");+ }++ #[test]+ fn show_document_grid_toggles_from_the_grids_and_guides_menu() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let tree = menu_tree();+ let mut items = vec![];+ for (_, entries) in &tree {+ walk(entries, &mut items);+ }+ assert!(items.iter().any(|(label, id, _)| id == "view.documentGrid" && label == "Show/Hide Document Grid"));+ assert_eq!(shortcut_of(&app, "view.documentGrid").as_deref(), Some("Cmd+'"));+ assert_eq!(checked(&app, "view.documentGrid", &json!({})), Some(false));+ assert_eq!(run_ui(&mut app, "view.documentGrid", &json!({})).unwrap().unwrap(), json!(true));+ assert!(app.ui.document_grid);+ assert_eq!(checked(&app, "view.documentGrid", &json!({})), Some(true));+ run_ui(&mut app, "view.documentGrid", &json!({})).unwrap().unwrap();+ assert!(!app.ui.document_grid);+ }++ #[test]+ fn interface_language_switches_and_validates() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ run_ui(&mut app, "app.language", &json!({"lang": "de"})).unwrap().unwrap();+ assert_eq!(app.ui.language, "de");+ assert_eq!(checked(&app, "app.language", &json!({"lang": "de"})), Some(true));+ assert!(run_ui(&mut app, "app.language", &json!({"lang": "xx"})).unwrap().is_err());+ assert_eq!(app.ui.language, "de");+ // The language is set in Preferences, not from a menu; without `lang` the command opens it.+ let mut items = Vec::new();+ for (_, entries) in menu_tree() {+ walk(&entries, &mut items);+ }+ assert!(!items.iter().any(|(_, id, _)| id == "app.language"), "no menu item sets the language");+ run_ui(&mut app, "app.language", &json!({})).unwrap().unwrap();+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences"));+ assert_eq!(app.ui.language, "de");+ }++ #[test]+ fn every_interface_language_is_selectable_persisted_and_keeps_document_data() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Мої слова · Zażółć gęślą jaźń"})).unwrap();+ let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap();+ for (code, _) in crate::i18n::LANGUAGES {+ run_ui(&mut app, "app.language", &json!({"lang": code})).unwrap().unwrap();+ assert_eq!(app.ui.language, *code);+ assert_eq!(checked(&app, "app.language", &json!({"lang": code})), Some(true), "{code}");+ assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(), "{code}");+ let bytes = serde_json::to_vec(&app.ui).unwrap();+ let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(restored.language, *code);+ }+ }++ #[test]+ fn arabic_dialog_and_language_switch_keep_finite_widget_geometry() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp| {+ for _ in 0..4 {+ let mut output = ctx.run_ui(+ egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))),+ max_texture_side: Some(8192),+ ..Default::default()+ },+ |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ },+ );+ output.textures_delta.clear();+ }+ };+ app.run("app.language", json!({"lang": "ar"})).unwrap();+ frame(&mut app);+ app.run("app.newDocumentDialog", json!({})).unwrap();+ frame(&mut app); // egui asserts that all allocated rectangles are finite.+ crate::dialogs::confirm(&mut app).unwrap();+ frame(&mut app);+ assert_eq!(app.session.documents().len(), 1);+ for lang in ["uk", "ru", "zh", "", "ar", "pt-br", "it", "cs", "pl", "ka"] {+ app.run("app.language", json!({"lang": lang})).unwrap();+ frame(&mut app);+ }+ }++ #[test]+ fn story_direction_is_checked() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 400], "content": "text", "text": "縦", "vertical": true})).unwrap();+ assert_eq!(checked(&app, "type.storyDirection", &json!({"vertical": true})), Some(true));+ assert_eq!(checked(&app, "type.storyDirection", &json!({"vertical": false})), Some(false));+ }++ #[test]+ fn proof_setup_and_colors() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ assert_eq!(checked(&app, "view.proofColors", &Value::Null), Some(false));+ let r = run_ui(&mut app, "view.proofSetup", &json!({"target": "deuteranopia"})).unwrap().unwrap();+ assert_eq!(r["on"], true);+ assert_eq!(checked(&app, "view.proofSetup", &json!({"target": "deuteranopia"})), Some(true));+ run_ui(&mut app, "view.proofSetup", &json!({"simulatePaper": "toggle"})).unwrap().unwrap();+ assert!(app.ui.proof_setup.simulate_paper);+ run_ui(&mut app, "view.proofColors", &json!({})).unwrap().unwrap();+ assert!(!app.ui.proof_colors);+ assert!(run_ui(&mut app, "view.proofSetup", &json!({"target": "nope"})).unwrap().is_err());+ }++ #[test]+ fn lock_guides_and_lock_column_guides_are_checked_in_grids_and_guides() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let view = menu_ids("View");+ assert!(view.contains(&"view.lockGuides") && view.contains(&"view.lockColumnGuides"));+ assert_eq!(ui_label("view.lockGuides").and_then(|c| c.1), Some("Cmd+Alt+;"));+ // Lock Guides: off at first, toggles, and `on` sets it.+ assert_eq!(checked(&app, "view.lockGuides", &Value::Null), Some(false));+ assert_eq!(app.run("view.lockGuides", json!({})).unwrap(), json!(true));+ assert!(app.ui.guides_locked);+ assert_eq!(app.run("view.lockGuides", json!({"on": true})).unwrap(), json!(true));+ assert_eq!(checked(&app, "view.lockGuides", &Value::Null), Some(true));+ assert_eq!(app.run("view.lockGuides", json!({"on": false})).unwrap(), json!(false));+ // Lock Column Guides: the document's setting, on in new documents.+ assert_eq!(checked(&app, "view.lockColumnGuides", &Value::Null), Some(true));+ app.run("view.lockColumnGuides", json!({})).unwrap();+ assert_eq!(checked(&app, "view.lockColumnGuides", &Value::Null), Some(false));+ }++ #[test]+ fn fitting_has_indesigns_shortcuts() {+ // LYH Studio episode 6 (7:00): "Fit Content to Frame (Ctrl + Shift + Alt + C)" fills the+ // photo frames proportionally.+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();+ let f = app.run("frame.create", json!({"rect": [100, 100, 300, 300]})).unwrap()["id"].as_u64().unwrap();+ app.run("file.place", json!({"base64": designcraft_engine::cmd::base64_encode(&png), "name": "a.png", "frame": f})).unwrap();+ app.run("selection.set", json!({"ids": [f]})).unwrap();+ let width = |app: &crate::DesignApp| {+ let it = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().clone();+ let designcraft_doc::Content::Graphic(g) = &it.content else { panic!("graphic") };+ it.xf.transform_rect_bbox(g.xf.transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1))).width()+ };+ for (id, keys) in [+ ("fit.fillFrameProportionally", "Cmd+Alt+Shift+C"),+ ("fit.contentProportionally", "Cmd+Alt+Shift+E"),+ ("fit.frameToContent", "Cmd+Alt+C"),+ ("fit.contentToFrame", "Cmd+Alt+E"),+ ("fit.centerContent", "Cmd+Shift+E"),+ ] {+ assert_eq!(shortcut_of(&app, id).as_deref(), Some(keys));+ }+ let ctx = egui::Context::default();+ let press = |app: &mut crate::DesignApp, key: egui::Key| {+ let modifiers =+ egui::Modifiers { alt: true, ctrl: !cfg!(target_os = "macos"), shift: true, mac_cmd: cfg!(target_os = "macos"), command: true };+ let input = egui::RawInput {+ events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }],+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| shortcuts(app, &ui.ctx().clone()));+ out.textures_delta.clear();+ };+ press(&mut app, egui::Key::C);+ assert!((width(&app) - 400.0).abs() < 1e-6, "filled: {}", width(&app));+ press(&mut app, egui::Key::E);+ assert!((width(&app) - 200.0).abs() < 1e-6, "fitted: {}", width(&app));+ }++ #[test]+ fn tab_and_presentation_hide_floating_panels_too() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp| {+ for _ in 0..2 {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ }+ };+ // The docked panel's tab and a floating panel group.+ let tab = crate::panel_docking::tab_id("preflight");+ let docked = || ctx.read_response(tab).is_some();+ let group = crate::panel_docking::floating_layer("preflight");+ let shown = |layer: egui::LayerId| ctx.memory(|m| m.areas().is_visible(&layer));+ let toggles = [+ ("window.hidePanels", json!({}), json!({})),+ ("window.hidePanelsExceptTools", json!({}), json!({})),+ ("view.screenMode", json!({"mode": "presentation"}), json!({"mode": "normal"})),+ ];+ app.run("window.panel", json!({"panel": "preflight"})).unwrap();+ frame(&mut app);+ assert!(docked());+ for (id, hide, show) in &toggles {+ app.run(id, hide.clone()).unwrap();+ frame(&mut app);+ assert!(!docked(), "{id} hides the dock");+ app.run(id, show.clone()).unwrap();+ frame(&mut app);+ assert!(docked(), "{id} again brings it back");+ }+ app.run("window.floatPanel", json!({"panel": "preflight", "x": 400, "y": 200})).unwrap();+ frame(&mut app);+ assert!(app.ui.docking.is_some() && shown(group));+ for (id, hide, show) in &toggles {+ app.run(id, hide.clone()).unwrap();+ frame(&mut app);+ assert!(!shown(group), "{id} hides the floating panel");+ app.run(id, show.clone()).unwrap();+ frame(&mut app);+ assert!(shown(group), "{id} again brings it back");+ }+ }++ #[test]+ fn tab_hides_panels_and_documents_cycle() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ assert_eq!(shortcut_of(&app, "window.hidePanels").as_deref(), Some("Tab"));+ run_ui(&mut app, "window.hidePanels", &json!({})).unwrap().unwrap();+ assert_eq!(app.ui.hidden_panels, 1);+ run_ui(&mut app, "window.hidePanelsExceptTools", &json!({})).unwrap().unwrap();+ assert_eq!(app.ui.hidden_panels, 2);+ run_ui(&mut app, "window.hidePanelsExceptTools", &json!({})).unwrap().unwrap();+ assert_eq!(app.ui.hidden_panels, 0);+ for _ in 0..3 {+ app.session.execute("file.new", &json!({})).unwrap();+ }+ assert_eq!(app.session.active_index(), Some(2));+ run_ui(&mut app, "window.nextDocument", &json!({})).unwrap().unwrap();+ assert_eq!(app.session.active_index(), Some(0));+ run_ui(&mut app, "window.previousDocument", &json!({})).unwrap().unwrap();+ assert_eq!(app.session.active_index(), Some(2));+ }++ #[test]+ fn rotate_spread_view() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 3})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp| {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ frame(&mut app);+ frame(&mut app);+ assert_eq!(run_ui(&mut app, "view.rotateSpread", &json!({"angle": 90})).unwrap().unwrap(), json!(90));+ frame(&mut app);+ // Only the spread in view turns: its canvas footprint swaps width and height.+ let d = app.session.active().unwrap().doc.clone();+ let turned: Vec<usize> = d.spreads.iter().enumerate().filter(|(_, sp)| sp.pages[0].view_rotation == 1).map(|(i, _)| i).collect();+ assert_eq!(turned.len(), 1);+ let layout = designcraft_tools::CanvasLayout::new(&d, false);+ let slot = layout.slots[turned[0]];+ let b = d.spreads[turned[0]].bounds();+ assert!((slot.bounds.width() - b.height()).abs() < 1e-6 && (slot.bounds.height() - b.width()).abs() < 1e-6);+ assert_eq!(checked(&app, "view.rotateSpread", &json!({"angle": 0})), Some(false));+ run_ui(&mut app, "view.rotateSpread", &json!({"angle": 0})).unwrap().unwrap();+ assert_eq!(checked(&app, "view.rotateSpread", &json!({"angle": 0})), Some(true));+ frame(&mut app);+ }++ #[test]+ fn hand_tool_hold_starts_power_zoom() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, t: f64, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ time: Some(t),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ frame(&mut app, 0.0, vec![]);+ frame(&mut app, 0.05, vec![]);+ app.select_tool("hand");+ let r = app.canvas_rect.unwrap();+ let p = r.center();+ let z0 = app.view().unwrap().zoom;+ frame(&mut app, 0.1, vec![egui::Event::PointerMoved(p)]);+ frame(+ &mut app,+ 0.2,+ vec![egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }],+ );+ frame(&mut app, 0.4, vec![]);+ assert!(app.power_zoom.is_none(), "not yet");+ frame(&mut app, 0.8, vec![]);+ assert!(app.power_zoom.is_some(), "holding still starts Power Zoom");+ frame(+ &mut app,+ 0.9,+ vec![egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }],+ );+ assert!(app.power_zoom.is_none());+ assert!((app.view().unwrap().zoom - z0).abs() < 1e-9, "back at the zoom it started from");+ }++ #[test]+ fn middle_drag_pans_with_any_tool() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ // A drawing tool: a primary drag would make a frame, a middle drag must not.+ app.select_tool("rectangleFrame");+ let p = app.canvas_rect.unwrap().center();+ let v0 = *app.view().unwrap();+ let items = |app: &crate::DesignApp| app.session.active().unwrap().doc.spreads.iter().map(|s| s.items.len()).sum::<usize>();+ let items0 = items(&app);+ let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() };+ frame(&mut app, vec![egui::Event::PointerMoved(p), button(p, true)]);+ for i in 1..=8 {+ frame(&mut app, vec![egui::Event::PointerMoved(p + egui::vec2(10.0 * i as f32, 5.0 * i as f32))]);+ }+ frame(&mut app, vec![button(p + egui::vec2(80.0, 40.0), false)]);+ let v = *app.view().unwrap();+ assert!((v.zoom - v0.zoom).abs() < 1e-9, "panning keeps the zoom");+ assert!(v.origin.x < v0.origin.x && v.origin.y < v0.origin.y, "dragging right/down moves the view: {v0:?} -> {v:?}");+ assert_eq!(items(&app), items0, "the tool saw nothing");+ }++ #[test]+ fn layout_menu_goes_through_pages_and_spreads_with_their_shortcuts() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key, modifiers: egui::Modifiers| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers },+ ]+ };+ let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap();+ let spread = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap();+ crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap()+ };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ // The Layout menu lists them, as InDesign's does, before Go to Page.+ let layout = MENUS.iter().find(|m| m.0 == "Layout").unwrap().1;+ let at = |id: &str| layout.iter().position(|e| e.starts_with(&format!("ui:{id}"))).unwrap();+ assert!(at("view.firstPage") < at("view.previousPage"));+ assert!(at("view.previousPage") < at("view.nextPage"));+ assert!(at("view.nextPage") < at("view.lastPage"));+ assert!(at("view.lastPage") < at("view.nextSpread"));+ assert!(at("view.nextSpread") < at("view.previousSpread"));+ assert!(at("view.previousSpread") < at("view.goToPage"));+ let shift = egui::Modifiers::SHIFT;+ let cmd_shift = egui::Modifiers { shift: true, command: true, ctrl: true, ..Default::default() };+ let alt = egui::Modifiers::ALT;+ // Pages 1 | 2-3 | 4-5 | 6-7.+ frame(&mut app, key(egui::Key::PageDown, shift));+ assert_eq!(page(&app), 1, "Next Page");+ frame(&mut app, key(egui::Key::PageDown, shift));+ assert_eq!(page(&app), 2, "Next Page goes to the right page of the spread");+ frame(&mut app, key(egui::Key::PageUp, shift));+ assert_eq!(page(&app), 1, "Previous Page");+ frame(&mut app, key(egui::Key::PageDown, cmd_shift));+ assert_eq!(page(&app), 6, "Last Page");+ frame(&mut app, key(egui::Key::PageDown, shift));+ assert_eq!(page(&app), 6, "Next Page stops at the last page");+ frame(&mut app, key(egui::Key::PageUp, cmd_shift));+ assert_eq!(page(&app), 0, "First Page");+ frame(&mut app, key(egui::Key::PageUp, shift));+ assert_eq!(page(&app), 0, "Previous Page stops at the first page");+ frame(&mut app, key(egui::Key::PageDown, alt));+ assert_eq!(spread(&app), 1, "Next Spread");+ frame(&mut app, key(egui::Key::PageDown, alt));+ frame(&mut app, key(egui::Key::PageDown, alt));+ frame(&mut app, key(egui::Key::PageDown, alt));+ assert_eq!(spread(&app), 3, "Next Spread stops at the last spread");+ frame(&mut app, key(egui::Key::PageUp, alt));+ assert_eq!(spread(&app), 2, "Previous Spread");+ // The spread is centred, the zoom kept.+ let zoom = app.view().unwrap().zoom;+ app.run("view.previousSpread", json!({})).unwrap();+ let st = app.session.active().unwrap();+ let slot = designcraft_tools::layout::CanvasLayout::new(&st.doc, false).slots[1];+ let (v, r) = (*app.view().unwrap(), app.canvas_rect.unwrap());+ let centre = (v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom);+ assert!((centre.0 - slot.bounds.center().x).abs() < 1e-6 && (centre.1 - slot.bounds.center().y).abs() < 1e-6);+ assert_eq!(v.zoom, zoom);+ }++ #[test]+ fn go_back_and_go_forward_retrace_the_pages_viewed() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key, modifiers: egui::Modifiers| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers },+ ]+ };+ let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap();+ let can = |app: &crate::DesignApp| (menu_enabled(app, "view.goBack"), menu_enabled(app, "view.goForward"));+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ // In the Layout menu after Go to Page.+ let layout = MENUS.iter().find(|m| m.0 == "Layout").unwrap().1;+ let at = |id: &str| layout.iter().position(|e| *e == format!("ui:{id}")).unwrap();+ assert_eq!(at("view.goBack"), at("view.goToPage") + 1);+ assert_eq!(at("view.goForward"), at("view.goBack") + 1);+ assert_eq!(can(&app), (false, false), "one page viewed: nowhere to go");+ let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() };+ let cmd_shift = egui::Modifiers { shift: true, ..cmd };+ let shift = egui::Modifiers::SHIFT;+ // Pages viewed: 1, 5, 7.+ app.run("view.goToPage", json!({"page": 5})).unwrap();+ frame(&mut app, vec![]);+ frame(&mut app, key(egui::Key::PageDown, cmd_shift));+ assert_eq!(page(&app), 6);+ frame(&mut app, vec![]);+ assert_eq!(can(&app), (true, false));+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(page(&app), 4, "Go Back");+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(page(&app), 0, "Go Back again");+ frame(&mut app, vec![]);+ assert_eq!(can(&app), (false, true), "back at the first page viewed");+ frame(&mut app, key(egui::Key::PageDown, cmd));+ assert_eq!(page(&app), 4, "Go Forward");+ frame(&mut app, key(egui::Key::PageDown, cmd));+ assert_eq!(page(&app), 6, "Go Forward again");+ frame(&mut app, vec![]);+ assert_eq!(can(&app), (true, false));+ // After going back, viewing another page drops the pages ahead.+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(page(&app), 4);+ frame(&mut app, key(egui::Key::PageDown, shift));+ assert_eq!(page(&app), 5, "Next Page");+ frame(&mut app, vec![]);+ assert_eq!(can(&app), (true, false), "nothing ahead after a new page");+ frame(&mut app, key(egui::Key::PageDown, cmd));+ assert_eq!(page(&app), 5, "Go Forward does nothing");+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(page(&app), 4, "Go Back returns to the page before Next Page");+ }++ #[test]+ fn go_back_waits_for_the_view_to_be_fitted() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp| {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ frame(&mut app);+ frame(&mut app);+ app.run("view.goToPage", json!({"page": 5})).unwrap();+ frame(&mut app);+ assert!(menu_enabled(&app, "view.goBack"));+ // Leaving parent pages through the Pages panel: the canvas refits on the next frame.+ app.view_mut().unwrap().fitted = false;+ assert!(!menu_enabled(&app, "view.goBack"), "the refit would replace where Go Back went");+ crate::canvas::go_through_history(&mut app, -1);+ frame(&mut app);+ assert!(menu_enabled(&app, "view.goBack"), "the unfitted Go Back used no history entry");+ }++ #[test]+ fn next_spread_at_the_last_spread_is_no_jump() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key, modifiers: egui::Modifiers| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers },+ ]+ };+ let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap();+ let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() };+ let alt = egui::Modifiers::ALT;+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ // Pages 1 | 2-3 | 4-5 | 6-7: page 6 is the left page of the last spread.+ app.run("view.goToPage", json!({"page": 6})).unwrap();+ frame(&mut app, vec![]);+ assert_eq!(page(&app), 5);+ // Next Spread has no spread to go to; centring the last one moves the view to its fold.+ frame(&mut app, key(egui::Key::PageDown, alt));+ frame(&mut app, key(egui::Key::PageDown, alt));+ assert_ne!(page(&app), 5, "the view moved to the right page");+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(page(&app), 0, "Go Back returns to the page before Go to Page");+ assert!(!menu_enabled(&app, "view.goBack"));+ }++ #[test]+ fn go_back_returns_to_the_view_a_jump_left_and_scrolling_adds_no_entry() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key, modifiers: egui::Modifiers| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers },+ ]+ };+ let spread = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap();+ crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap()+ };+ let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() };+ let alt = egui::Modifiers::ALT;+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ // Pages 1 | 2-3 | 4-5 | 6-7. Spread 2-3 fitted: the view centre is on the fold.+ frame(&mut app, key(egui::Key::PageDown, alt));+ app.run("view.fitSpread", json!({})).unwrap();+ frame(&mut app, vec![]);+ let before = *app.view().unwrap();+ frame(&mut app, key(egui::Key::PageDown, alt));+ assert_eq!(spread(&app), 2, "Next Spread");+ frame(&mut app, key(egui::Key::PageUp, cmd));+ let v = *app.view().unwrap();+ assert!((v.origin - before.origin).hypot() < 1e-6, "Go Back shows the spread as it was: {:?} vs {:?}", v.origin, before.origin);+ assert_eq!(v.zoom, before.zoom);+ // Zoomed in after the jump: Go Back keeps the magnification in use, as InDesign's does, and+ // centres the same place.+ let centre = |app: &crate::DesignApp| {+ let (v, r) = (app.view().unwrap(), app.canvas_rect.unwrap());+ designcraft_geom::Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom)+ };+ let place = centre(&app);+ frame(&mut app, key(egui::Key::PageDown, alt));+ app.run("view.zoomIn", json!({})).unwrap();+ let zoomed = app.view().unwrap().zoom;+ assert!(zoomed > before.zoom);+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(app.view().unwrap().zoom, zoomed, "the zoom in use is kept");+ assert!((centre(&app) - place).hypot() < 1e-6, "the same place: {:?} vs {place:?}", centre(&app));+ // Scrolling down two spreads is not a jump: Go Forward keeps its page, and Go Back skips+ // from where the scroll ended straight to the page before the first jump.+ let slots = designcraft_tools::layout::CanvasLayout::new(&app.session.active().unwrap().doc, false).slots;+ app.view_mut().unwrap().origin.y += slots[3].bounds.center().y - slots[1].bounds.center().y;+ frame(&mut app, vec![]);+ assert_eq!(spread(&app), 3);+ assert!(menu_enabled(&app, "view.goForward"), "scrolling kept the page ahead");+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(spread(&app), 0, "Go Back");+ assert!(!menu_enabled(&app, "view.goBack"), "the scroll added no entry");+ frame(&mut app, key(egui::Key::PageDown, cmd));+ assert_eq!(spread(&app), 3, "Go Forward returns to where the scroll ended");+ frame(&mut app, key(egui::Key::PageDown, cmd));+ assert_eq!(spread(&app), 2);+ }++ #[test]+ fn go_back_after_presentation_returns_to_the_last_spread_presented() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key, modifiers: egui::Modifiers| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers },+ ]+ };+ let spread = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap();+ crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap()+ };+ let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ // Scrolled off the page's centre, so the place Go Back returns to is not just the page.+ let view = app.view_mut().unwrap();+ view.origin.x += 40.0;+ view.origin.y += 60.0;+ frame(&mut app, vec![]);+ assert_eq!(spread(&app), 0);+ let before = *app.view().unwrap();+ // Presentation goes on to spreads 1 and 2; leaving it puts spread 0 back as it was.+ app.run("view.screenMode", json!({"mode": "presentation"})).unwrap();+ frame(&mut app, vec![]);+ frame(&mut app, key(egui::Key::ArrowRight, egui::Modifiers::NONE));+ frame(&mut app, key(egui::Key::ArrowRight, egui::Modifiers::NONE));+ assert_eq!(spread(&app), 2);+ app.run("view.screenMode", json!({"mode": "normal"})).unwrap();+ frame(&mut app, vec![]);+ assert_eq!(spread(&app), 0);+ assert!(!menu_enabled(&app, "view.goForward"));+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(spread(&app), 2, "Go Back shows the last spread presented");+ frame(&mut app, key(egui::Key::PageUp, cmd));+ assert_eq!(spread(&app), 0, "Go Back again, the view Presentation was entered from");+ let v = *app.view().unwrap();+ assert!((v.origin - before.origin).hypot() < 1e-6, "where it was: {:?} vs {:?}", v.origin, before.origin);+ assert!(!menu_enabled(&app, "view.goBack"), "the presentation is one jump: spread 1 isn't kept");+ frame(&mut app, key(egui::Key::PageDown, cmd));+ assert_eq!(spread(&app), 2, "Go Forward");+ }++ #[test]+ fn presentation_shows_one_spread_and_goes_through_them_with_keys_and_clicks() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap();+ app.session.execute("frame.create", &json!({"rect": [100, 100, 300, 300]})).unwrap();+ let id = app.session.active().unwrap().selection.items[0];+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() },+ ]+ };+ let click = |pos: egui::Pos2, modifiers: egui::Modifiers| {+ vec![+ egui::Event::PointerMoved(pos),+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers },+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers },+ ]+ };+ let spread = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap();+ crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap()+ };+ // The spread fills the screen: as wide or as tall as it, centred.+ let fills = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap();+ let b = designcraft_tools::layout::CanvasLayout::new(&st.doc, false).slots[spread(app)].bounds;+ let (v, r) = (*app.view().unwrap(), app.canvas_rect.unwrap());+ let (w, h) = (b.width() * v.zoom, b.height() * v.zoom);+ let x0 = (b.x0 - v.origin.x) * v.zoom;+ let y0 = (b.y0 - v.origin.y) * v.zoom;+ ((w - r.width() as f64).abs() < 0.01 || (h - r.height() as f64).abs() < 0.01)+ && w <= r.width() as f64 + 0.01+ && h <= r.height() as f64 + 0.01+ && (x0 * 2.0 + w - r.width() as f64).abs() < 0.01+ && (y0 * 2.0 + h - r.height() as f64).abs() < 0.01+ };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ // The user's own view (zoomed in, scrolled) comes back after Presentation.+ let view = app.view_mut().unwrap();+ view.zoom = 2.0;+ view.origin.x += 150.0;+ view.origin.y += 300.0;+ let before = *app.view().unwrap();+ app.run("view.screenMode", json!({"mode": "presentation"})).unwrap();+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ assert_eq!(app.canvas_rect.unwrap().size(), egui::vec2(1400.0, 900.0), "the whole window");+ assert_eq!(spread(&app), 0);+ assert!(fills(&app));+ let bounds = app.session.active().unwrap().doc.item(id).unwrap().bounds();+ frame(&mut app, key(egui::Key::ArrowRight));+ frame(&mut app, vec![]);+ assert_eq!(spread(&app), 1, "Right Arrow shows the next spread");+ assert!(fills(&app));+ assert_eq!(app.session.active().unwrap().doc.item(id).unwrap().bounds(), bounds, "the arrow doesn't nudge the selection");+ frame(&mut app, key(egui::Key::PageDown));+ assert_eq!(spread(&app), 2, "Page Down");+ frame(&mut app, key(egui::Key::ArrowLeft));+ assert_eq!(spread(&app), 1, "Left Arrow");+ frame(&mut app, key(egui::Key::End));+ assert_eq!(spread(&app), 3, "End");+ frame(&mut app, key(egui::Key::ArrowRight));+ assert_eq!(spread(&app), 3, "the last spread stays");+ frame(&mut app, key(egui::Key::Home));+ assert_eq!(spread(&app), 0, "Home");+ frame(&mut app, key(egui::Key::PageUp));+ assert_eq!(spread(&app), 0, "the first spread stays");+ let c = app.canvas_rect.unwrap().center();+ frame(&mut app, click(c, egui::Modifiers::NONE));+ frame(&mut app, vec![]);+ assert_eq!(spread(&app), 1, "a click shows the next spread");+ assert!(fills(&app));+ frame(&mut app, click(c, egui::Modifiers::SHIFT));+ frame(&mut app, vec![]);+ assert_eq!(spread(&app), 0, "Shift-click the previous one");+ assert_eq!(app.session.active().unwrap().selection.items, vec![id], "clicks don't select");+ assert_eq!(app.session.tool_id(), "selection");+ // Out of Presentation, the view is the one it was entered from, and the arrow keys nudge+ // again.+ app.run("view.screenMode", json!({"mode": "normal"})).unwrap();+ assert_eq!(*app.view().unwrap(), before);+ frame(&mut app, vec![]);+ frame(&mut app, key(egui::Key::ArrowRight));+ assert_ne!(app.session.active().unwrap().doc.item(id).unwrap().bounds(), bounds);+ }++ #[test]+ fn tool_shortcuts_work_after_drawing_on_the_canvas() {+ // Clicking the canvas gives it keyboard focus; single-key tool shortcuts must still switch+ // tools without pressing Esc first (#1).+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() },+ ]+ };+ let button = |pos: egui::Pos2, pressed: bool| egui::Event::PointerButton {+ pos,+ button: egui::PointerButton::Primary,+ pressed,+ modifiers: Default::default(),+ };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ frame(&mut app, key(egui::Key::F));+ assert_eq!(app.session.tool_id(), "rectangleFrame");+ // Draw a frame.+ let a = app.canvas_rect.unwrap().center();+ let b = a + egui::vec2(120.0, 80.0);+ frame(&mut app, vec![egui::Event::PointerMoved(a), button(a, true)]);+ for i in 1..=4 {+ frame(&mut app, vec![egui::Event::PointerMoved(a + (b - a) * (i as f32 / 4.0))]);+ }+ frame(&mut app, vec![button(b, false)]);+ frame(&mut app, vec![]);+ assert!(app.session.active().is_some_and(|d| !d.selection.items.is_empty()), "drew a frame");+ frame(&mut app, key(egui::Key::V));+ assert_eq!(app.session.tool_id(), "selection", "V switches tools straight after drawing");+ frame(&mut app, key(egui::Key::F));+ assert_eq!(app.session.tool_id(), "rectangleFrame");+ }++ #[test]+ fn escape_and_shift_w_leave_presentation_for_the_previous_mode() {+ // Presentation hides every control, so the keyboard must get out of it (#493).+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "graphic"})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key, modifiers: egui::Modifiers| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers },+ ]+ };+ let selected = |app: &crate::DesignApp| app.session.active().map(|d| d.selection.items.len()).unwrap_or(0);+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ app.run("view.screenMode", json!({"mode": "preview"})).unwrap();+ app.select_tool("rectangleFrame");+ assert_eq!(selected(&app), 1, "the new frame is selected");++ frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT));+ assert_eq!(app.ui.screen_mode, ScreenMode::Presentation, "Shift+W enters Presentation");+ assert_eq!(app.session.tool_id(), "rectangleFrame", "Shift+W is not a tool shortcut");+ frame(&mut app, key(egui::Key::Escape, egui::Modifiers::NONE));+ assert_eq!(app.ui.screen_mode, ScreenMode::Preview, "Esc returns to the mode Presentation was entered from");+ assert_eq!(app.session.tool_id(), "rectangleFrame", "Esc only left Presentation");+ assert_eq!(selected(&app), 1, "Esc only left Presentation");++ frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT));+ frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT));+ assert_eq!(app.ui.screen_mode, ScreenMode::Preview, "Shift+W leaves Presentation for the previous mode");++ app.run("view.screenMode", json!({"mode": "presentation"})).unwrap();+ frame(&mut app, key(egui::Key::W, egui::Modifiers::NONE));+ assert_eq!(app.ui.screen_mode, ScreenMode::Normal, "W from any mode but Normal goes to Normal");++ // Outside Presentation, Esc keeps its usual meaning.+ frame(&mut app, key(egui::Key::Escape, egui::Modifiers::NONE));+ assert_eq!(app.ui.screen_mode, ScreenMode::Normal);+ assert_eq!(app.session.tool_id(), "selection");+ }++ #[test]+ fn cmd_plus_zooms_the_canvas_not_the_window() {+ // A German keyboard has its own + key, so Cmd+= arrives as Plus; it must zoom the canvas like+ // Cmd+- does, not hand the key to egui's whole-window zoom.+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let key = |k: egui::Key, modifiers: egui::Modifiers| {+ vec![+ egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers },+ egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers },+ ]+ };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ let scale = ctx.zoom_factor();+ for (k, m, zooms_in) in [+ (egui::Key::Plus, egui::Modifiers::COMMAND, true),+ (egui::Key::Plus, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, true),+ (egui::Key::Equals, egui::Modifiers::COMMAND, true),+ (egui::Key::Minus, egui::Modifiers::COMMAND, false),+ ] {+ let z0 = app.view().unwrap().zoom;+ frame(&mut app, key(k, m));+ frame(&mut app, vec![]);+ let z = app.view().unwrap().zoom;+ assert!(if zooms_in { z > z0 } else { z < z0 }, "{k:?} {m:?}: {z0} -> {z}");+ assert_eq!(ctx.zoom_factor(), scale, "{k:?} {m:?} leaves the UI scale alone");+ }+ // With a native menu (macOS) its accelerator takes Cmd+= itself, but never sees the Plus key+ // standing in for = (#781).+ app.native_shortcuts.insert("view.zoomIn".to_string(), shortcut_of(&app, "view.zoomIn").unwrap());+ for (k, m, zooms_in) in [+ (egui::Key::Plus, egui::Modifiers::COMMAND, true),+ (egui::Key::Plus, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, true),+ (egui::Key::Equals, egui::Modifiers::COMMAND, false),+ ] {+ let z0 = app.view().unwrap().zoom;+ frame(&mut app, key(k, m));+ frame(&mut app, vec![]);+ let z = app.view().unwrap().zoom;+ assert_eq!(z > z0, zooms_in, "native menu, {k:?} {m:?}: {z0} -> {z}");+ }+ // A shortcut the user set runs here until the native menu bar carries it as its key+ // equivalent; then only the bar runs it, once.+ run_ui(&mut app, "window.setShortcut", &json!({"id": "view.zoomOut", "shortcut": "Cmd+9"})).unwrap().unwrap();+ let zooms_out = |app: &mut crate::DesignApp, k: egui::Key| {+ let z0 = app.view().unwrap().zoom;+ frame(app, key(k, egui::Modifiers::COMMAND));+ frame(app, vec![]);+ app.view().unwrap().zoom < z0+ };+ assert!(zooms_out(&mut app, egui::Key::Num9), "no native bar: the app runs it");+ app.native_shortcuts.insert("view.zoomOut".to_string(), "Cmd+9".to_string());+ assert!(!zooms_out(&mut app, egui::Key::Num9), "the bar's key equivalent runs only there");+ // A second binding of a command whose first the bar holds runs here.+ let cmd = craft_keymap::CommandRef::new("view.zoomOut");+ let bindings = ["Cmd+F11", "Cmd+9"].map(|s| craft_keymap::Binding::parse(s).unwrap()).to_vec();+ app.keymap.set_bindings(&cmd, bindings, craft_keymap::Policy::Steal).unwrap();+ app.ui.shortcuts = app.keymap.overrides().clone();+ app.native_shortcuts.insert("view.zoomOut".to_string(), "Cmd+F11".to_string());+ assert!(!zooms_out(&mut app, egui::Key::F11), "the bar runs its own key");+ assert!(zooms_out(&mut app, egui::Key::Num9), "the second binding runs in the app");+ }++ #[test]+ fn the_quick_apply_shortcut_opens_it_without_running_an_entry() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let cmd_return =+ |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::COMMAND };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ frame(&mut app, vec![cmd_return(true), cmd_return(false)]);+ frame(&mut app, vec![]);+ assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open");+ assert_eq!(app.session.documents().len(), 1, "the first entry (New Document) didn't run");+ // Pressing the shortcut again, or holding it until it repeats, doesn't run it either.+ frame(&mut app, vec![cmd_return(true), cmd_return(false)]);+ let repeat = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: true, modifiers: egui::Modifiers::COMMAND };+ frame(&mut app, vec![repeat, cmd_return(false)]);+ assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open");+ assert_eq!(app.session.documents().len(), 1, "a second ⌘Return or a repeat doesn't run the first entry");+ // A plain Return still does.+ let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };+ frame(&mut app, vec![enter(true), enter(false)]);+ assert_eq!(app.ui.palette, None, "Return runs the first entry and closes Quick Apply");+ assert_eq!(app.session.documents().len(), 2);+ }++ #[test]+ fn quick_apply_rows_are_left_aligned() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ app.ui.palette = Some(String::new());+ let ctx = egui::Context::default();+ let mut shapes = Vec::new();+ for _ in 0..3 {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ shapes = out.shapes;+ }+ let label_x = |label: &str| {+ // The palette is painted last, over anything else with the same text.+ shapes.iter().rev().find_map(|s| match &s.shape {+ egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos.x),+ _ => None,+ })+ };+ // Rows that show a shortcut or a style kind, and rows that show neither, among the first visible ones.+ let items = quick_apply_items(&app.session, "", false);+ let first = items.iter().take(10);+ let plain = first.clone().find(|it| it.shortcut.is_none() && it.kind.is_empty()).expect("a row without a shortcut");+ let with_sc = first.clone().find(|it| it.shortcut.is_some()).expect("a row with a shortcut");+ let (a, b) = (label_x(&plain.label).expect("plain row drawn"), label_x(&with_sc.label).expect("shortcut row drawn"));+ assert!((a - b).abs() < 0.5, "{:?} at x {a}, {:?} at x {b}", plain.label, with_sc.label);+ }++ #[test]+ fn copy_and_paste_keys_work_for_objects_without_a_native_menu() {+ // Without a native menu the paste key arrives only as a paste event, which needs text on+ // the system clipboard (#164, #185).+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ out.platform_output.commands+ };+ let count = |app: &crate::DesignApp| app.session.active().unwrap().doc.spreads[0].items.len();+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone();+ app.session.execute("selection.set", &json!({"ids": [id]})).unwrap();+ let n = count(&app);+ let copied = frame(&mut app, vec![egui::Event::Copy])+ .into_iter()+ .find_map(|c| match c {+ egui::OutputCommand::CopyText(t) => Some(t),+ _ => None,+ })+ .expect("copying objects puts text on the system clipboard");+ assert!(!copied.is_empty());+ frame(&mut app, vec![egui::Event::Paste(copied.clone())]);+ assert_eq!(count(&app), n + 1, "the paste key pastes the copied rectangle");++ // Pasting into text anchors the copied object; the clipboard placeholder isn't typed.+ let r = app.session.execute("frame.create", &json!({"rect": [72, 300, 400, 400], "content": "text", "text": "Hello"})).unwrap();+ let story = r["story"].as_u64().unwrap();+ app.session.execute("tool.select", &json!({"tool": "type"})).unwrap();+ app.session.execute("text.select", &json!({"story": story, "anchor": 5, "focus": 5})).unwrap();+ frame(&mut app, vec![egui::Event::Paste(copied.clone())]);+ // Shift pastes without formatting.+ frame(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), egui::Event::Paste(copied)]);+ let text = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(story)).unwrap().text.clone();+ assert!(text.starts_with("Hello") && !text.contains('\u{FFFC}'), "{text:?}");+ assert!(text.contains(designcraft_doc::OBJECT_MARK), "{text:?}");+ }++ #[test]+ fn paste_with_no_insertion_point_makes_a_text_frame_from_other_apps_text() {+ // #518: text copied in another app pastes as a new, selected text frame; the text an+ // object copy stands for still pastes the objects. One paste each way, with and without+ // a native menu.+ let selected_text = |app: &crate::DesignApp| {+ let d = app.session.active().unwrap();+ let it = d.doc.item(*d.selection.items.first()?)?;+ Some(d.doc.story(it.text_frame()?.story)?.text.clone())+ };+ let ctx = egui::Context::default();+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ native_frame(&mut app, &ctx, vec![], None);+ native_frame(&mut app, &ctx, vec![], None);+ // The paste keys without a native menu: a paste event.+ native_frame(&mut app, &ctx, vec![egui::Event::Paste("From elsewhere".into())], None);+ assert_eq!(document_items(&app), (1, 1), "pasted once");+ assert_eq!(selected_text(&app).as_deref(), Some("From elsewhere"));+ let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone();+ app.session.execute("selection.set", &json!({"ids": [id]})).unwrap();+ let copied = native_frame(&mut app, &ctx, vec![egui::Event::Copy], None)+ .platform_output+ .commands+ .into_iter()+ .find_map(|c| match c {+ egui::OutputCommand::CopyText(t) => Some(t),+ _ => None,+ })+ .expect("copying objects puts text on the system clipboard");+ native_frame(&mut app, &ctx, vec![egui::Event::Paste(copied)], None);+ assert_eq!(document_items(&app), (3, 1));+ assert_eq!(selected_text(&app), None, "the copied rectangle, not a text frame");++ // A native menu: Paste reads the system clipboard.+ let clip = std::rc::Rc::new(std::cell::RefCell::new(Some("Menu text".to_string())));+ let read = clip.clone();+ let services = crate::Services { clipboard_text: Some(Box::new(move || read.borrow().clone())), ..Default::default() };+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), services);+ app.native_menu = true;+ app.session.execute("file.new", &json!({})).unwrap();+ native_frame(&mut app, &ctx, vec![], None);+ native_frame(&mut app, &ctx, vec![], None);+ native_frame(&mut app, &ctx, vec![], Some("edit.paste"));+ native_frame(&mut app, &ctx, vec![], None);+ assert_eq!(document_items(&app), (1, 1), "pasted once");+ assert_eq!(selected_text(&app).as_deref(), Some("Menu text"));+ // Objects copied since that text was copied paste as objects.+ let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone();+ app.session.execute("selection.set", &json!({"ids": [id]})).unwrap();+ native_frame(&mut app, &ctx, vec![], Some("edit.copy"));+ native_frame(&mut app, &ctx, vec![], Some("edit.paste"));+ assert_eq!(document_items(&app), (3, 1));+ assert_eq!(selected_text(&app), None, "the copied rectangle, not a text frame");+ // Newer text from another app wins.+ *clip.borrow_mut() = Some("Newer".into());+ native_frame(&mut app, &ctx, vec![], Some("edit.paste"));+ assert_eq!(document_items(&app), (4, 1));+ assert_eq!(selected_text(&app).as_deref(), Some("Newer"));+ }++ #[test]+ fn sample_scripts_run() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ for (name, text) in app.ui.scripts.clone() {+ let r = app.session.execute("script.run", &json!({"text": text}));+ assert!(r.is_ok(), "{name}: {r:?}");+ }+ }++ #[test]+ fn new_window_shows_a_second_view() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp| {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ frame(&mut app);+ assert_eq!(run_ui(&mut app, "window.newWindow", &json!({})).unwrap().unwrap(), json!(true));+ assert!(!app.split);+ frame(&mut app);+ frame(&mut app);+ // Pane 1 was drawn (its rect is held for it) and has its own view.+ assert!(app.other_pane.as_ref().and_then(|o| o.1).is_some() || app.pane == 1);+ app.switch_pane(1);+ assert!(app.view().is_some(), "the second window has a view");+ app.switch_pane(0);+ assert_eq!(checked(&app, "window.newWindow", &Value::Null), Some(true));+ run_ui(&mut app, "window.newWindow", &json!({"on": false})).unwrap().unwrap();+ frame(&mut app);+ }++ #[test]+ fn panels_float_and_dock() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let r = run_ui(&mut app, "window.floatPanel", &json!({"panel": "swatches", "x": 50, "y": 60})).unwrap().unwrap();+ assert_eq!(r["floating"], json!(["swatches"]));+ let window = &app.ui.docking.as_ref().unwrap().floating[0];+ assert_eq!([window.rect[0], window.rect[1]], [50.0, 60.0]);+ // Showing a floating panel leaves it where it is.+ run_ui(&mut app, "window.panel", &json!({"panel": "swatches"})).unwrap().unwrap();+ assert_eq!(app.ui.open_panel, None);+ let r = run_ui(&mut app, "window.dockPanel", &json!({"panel": "swatches"})).unwrap().unwrap();+ assert_eq!(r["floating"], json!([]));+ assert!(app.ui.docking.as_ref().unwrap().floating.is_empty());+ assert!(run_ui(&mut app, "window.floatPanel", &json!({"panel": "nope"})).unwrap().is_err());+ // Float-only panels (Type › Tabs) have their own windows outside the layout.+ let r = run_ui(&mut app, "window.floatPanel", &json!({"panel": "tabs", "x": 10, "y": 20})).unwrap().unwrap();+ assert_eq!(r["floating"], json!(["tabs"]));+ assert_eq!(app.ui.floating, [("tabs".to_string(), [10.0, 20.0])]);+ run_ui(&mut app, "window.dockPanel", &json!({"panel": "tabs"})).unwrap().unwrap();+ assert!(app.ui.floating.is_empty());+ }++ /// One frame as the desktop app runs it: queued synthetic input, then the native menu item+ /// chosen during the frame (`menu`), then the app's logic and ui.+ fn native_frame(app: &mut crate::DesignApp, ctx: &egui::Context, events: Vec<egui::Event>, menu: Option<&str>) -> egui::FullOutput {+ let mut input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), events, ..Default::default() };+ app.raw_input_hook(ctx, &mut input);+ let mut menu = menu;+ let mut out = ctx.run_ui(input, |ui| {+ let ctx = ui.ctx().clone();+ if let Some(id) = menu.take() {+ activate_native(app, &ctx, id, &Value::Null);+ }+ app.logic(&ctx);+ app.ui(ui);+ });+ out.textures_delta.clear();+ out+ }++ /// A document with two frames, nothing selected, and Quick Apply's search field focused+ /// holding `text`.+ fn app_with_focused_field(ctx: &egui::Context, text: &str) -> crate::DesignApp {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap();+ app.session.execute("frame.create", &json!({"rect": [236, 36, 400, 200]})).unwrap();+ app.session.execute("edit.deselectAll", &json!({})).unwrap();+ app.ui.palette = Some(text.into());+ for _ in 0..3 {+ native_frame(&mut app, ctx, vec![], None);+ }+ assert!(ctx.text_edit_focused());+ app+ }++ fn field_selection(ctx: &egui::Context) -> Option<(usize, usize)> {+ let id = ctx.memory(|m| m.focused())?;+ let r = egui::TextEdit::load_state(ctx, id)?.cursor.char_range()?;+ Some((r.primary.index.min(r.secondary.index).into(), r.primary.index.max(r.secondary.index).into()))+ }++ fn document_items(app: &crate::DesignApp) -> (usize, usize) {+ let d = app.session.active().unwrap();+ (d.doc.spreads.iter().flat_map(|sp| &sp.items).count(), d.selection.items.len())+ }++ #[test]+ fn native_select_all_selects_the_focused_fields_text() {+ // The Mac menu bar takes ⌘A before the window sees it (#30).+ let ctx = egui::Context::default();+ let mut app = app_with_focused_field(&ctx, "frame");+ native_frame(&mut app, &ctx, vec![], Some("edit.selectAll"));+ native_frame(&mut app, &ctx, vec![], None);+ assert_eq!(field_selection(&ctx), Some((0, 5)), "the field's whole text is selected");+ assert_eq!(document_items(&app), (2, 0), "the document selection is unchanged");+ }++ #[test]+ fn native_paste_and_copy_act_on_the_focused_field() {+ let ctx = egui::Context::default();+ let mut app = app_with_focused_field(&ctx, "frame");+ native_frame(&mut app, &ctx, vec![], Some("edit.selectAll"));+ native_frame(&mut app, &ctx, vec![], None);+ // Copy puts the field's selected text on the clipboard.+ native_frame(&mut app, &ctx, vec![], Some("edit.copy"));+ let out = native_frame(&mut app, &ctx, vec![], None);+ assert!(out.platform_output.commands.contains(&egui::OutputCommand::CopyText("frame".into())), "{:?}", out.platform_output.commands);+ // Paste asks the integration for the clipboard, which it hands to the field as a paste.+ let out = native_frame(&mut app, &ctx, vec![], Some("edit.paste"));+ let commands = &out.viewport_output[&egui::ViewportId::ROOT].commands;+ assert!(commands.contains(&egui::ViewportCommand::RequestPaste), "{commands:?}");+ native_frame(&mut app, &ctx, vec![egui::Event::Paste("text".into())], None);+ assert_eq!(app.ui.palette.as_deref(), Some("text"));+ assert_eq!(document_items(&app), (2, 0), "nothing was pasted into the document");+ }++ #[test]+ fn native_copy_and_paste_use_the_system_clipboard_for_canvas_text() {+ let ctx = egui::Context::default();+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200], "content": "text", "text": "hello"})).unwrap();+ let story = *app.session.active().unwrap().doc.stories.keys().next().unwrap();+ app.select_tool("type");+ app.run("text.select", json!({"story": story.0, "anchor": 0, "focus": 5})).unwrap();+ for _ in 0..3 {+ native_frame(&mut app, &ctx, vec![], None);+ }+ assert!(app.session.wants_text());++ native_frame(&mut app, &ctx, vec![], Some("edit.copy"));+ let copied = native_frame(&mut app, &ctx, vec![], None);+ assert!(copied.platform_output.commands.contains(&egui::OutputCommand::CopyText("hello".into())));++ let paste = native_frame(&mut app, &ctx, vec![], Some("edit.paste"));+ let commands = &paste.viewport_output[&egui::ViewportId::ROOT].commands;+ assert!(commands.contains(&egui::ViewportCommand::RequestPaste), "{commands:?}");+ native_frame(&mut app, &ctx, vec![egui::Event::Paste("world".into())], None);+ assert_eq!(app.session.active().unwrap().doc.story(story).unwrap().text, "world");+ }++ #[test]+ fn native_undo_and_redo_act_on_the_focused_field() {+ let ctx = egui::Context::default();+ let mut app = app_with_focused_field(&ctx, "");+ native_frame(&mut app, &ctx, vec![egui::Event::Text("abc".into())], None);+ assert_eq!(app.ui.palette.as_deref(), Some("abc"));+ native_frame(&mut app, &ctx, vec![], Some("edit.undo"));+ native_frame(&mut app, &ctx, vec![], None);+ assert_eq!(app.ui.palette.as_deref(), Some(""), "the field's typing is undone");+ assert_eq!(document_items(&app), (2, 0), "the document's last frame is still there");+ native_frame(&mut app, &ctx, vec![], Some("edit.redo"));+ native_frame(&mut app, &ctx, vec![], None);+ assert_eq!(app.ui.palette.as_deref(), Some("abc"));+ assert_eq!(document_items(&app), (2, 0));+ }++ #[test]+ fn native_editing_items_are_enabled_for_a_focused_field() {+ let ctx = egui::Context::default();+ let mut app = app_with_focused_field(&ctx, "frame");+ // Nothing is selected in the document, so its Copy and Cut are off; the field's are on.+ assert!(!menu_enabled(&app, "edit.copy") && !menu_enabled(&app, "edit.cut"));+ for id in ["edit.selectAll", "edit.copy", "edit.cut", "edit.paste", "edit.undo", "edit.redo"] {+ assert!(native_menu_enabled(&app, &ctx, id), "{id}");+ }+ assert!(!native_menu_enabled(&app, &ctx, "edit.duplicate"), "other items follow the document");+ app.ui.palette = None;+ native_frame(&mut app, &ctx, vec![], None);+ native_frame(&mut app, &ctx, vec![], None);+ assert!(!native_menu_enabled(&app, &ctx, "edit.copy"), "without a focused field, as the document says");+ }++ #[test]+ fn native_select_all_without_a_focused_field_selects_the_documents_items() {+ let ctx = egui::Context::default();+ let mut app = app_with_focused_field(&ctx, "frame");+ app.ui.palette = None;+ native_frame(&mut app, &ctx, vec![], None);+ native_frame(&mut app, &ctx, vec![], None);+ assert!(!ctx.text_edit_focused());+ native_frame(&mut app, &ctx, vec![], Some("edit.selectAll"));+ assert_eq!(document_items(&app), (2, 2));+ }++ #[test]+ fn command_search_matches_labels_in_the_interface_language() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = "de".into();+ let label = crate::i18n::tr("de", "Group");+ let items = command_search(&app, &label.to_lowercase());+ let group = items.iter().find(|i| i.id == "object.group").unwrap();+ assert_eq!(group.label, label);+ assert_eq!(group.shortcut.as_deref(), Some("Cmd+G"));+ assert!(command_search(&app, "group").iter().any(|i| i.id == "object.group"), "English labels match too");+ assert!(command_search(&app, " ").is_empty());+ assert!(command_search(&app, "e").len() <= 14);+ }++ #[test]+ fn quick_apply_lists_styles_then_commands() {+ let mut s = designcraft_engine::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "Body Copy"})).unwrap();+ let items = quick_apply_items(&s, "body", false);+ assert_eq!(items[0].id, "style.paragraph.apply");+ assert_eq!(items[0].params, json!({"name": "Body Copy"}));+ assert_eq!(items[0].kind, "Paragraph Style");+ assert!(quick_apply_items(&s, "", false).iter().all(|i| i.kind.is_empty()));+ assert!(quick_apply_items(&s, "preferences", false).iter().any(|i| i.id == "app.preferences"));+ }++ #[test]+ fn searched_ui_commands_run_without_parameters_and_keep_preferences() {+ // Without a value these reset a setting or need a place the test host always has.+ let searched: Vec<&str> = quick_commands().map(|c| c.0).collect();+ for id in ["app.flattener", "view.screenMode", "view.zoom", "window.taskBarPin"] {+ assert!(!searched.contains(&id), "{id} is searched");+ }+ // A placed PDF: a graphic with layers.+ let mut scratch = designcraft_engine::Session::new();+ scratch.execute("file.new", &json!({})).unwrap();+ let pdf = scratch.execute("file.exportPdf", &json!({})).unwrap()["base64"].clone();+ let contexts = ["nothing selected", "text insertion point", "text frame selected", "table cell", "placed PDF selected"];+ // A two-page document, a saved workspace and non-default preferences, a host with window+ // controls, and file dialogs that are dismissed.+ let setup = |context: usize| {+ let services = crate::Services { clipboard_text: Some(Box::new(|| None)), ..Default::default() };+ let mut app = DesignApp::new(designcraft_engine::Session::new(), services);+ app.answer_dialogs(crate::app::file_dialogs::testing::answer_with(None));+ app.custom_titlebar = true;+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)));+ app.run("file.new", json!({"pages": 2})).unwrap();+ app.session.prefs.recent_files.push("/nowhere/recent.dcraft".into());+ app.ui.shortcuts.insert("view.rulers", vec!["Ctrl+Alt+R".into()]);+ app.ui.hidden_menu_items.push("view.guides".into());+ app.ui.ui_scale = 1.25;+ app.ui.brightness = crate::theme::Brightness::Light;+ app.ui.task_bar_at = Some([200.0, 200.0]);+ run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap();+ match context {+ 1 => {+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": "One", "caret": true})).unwrap();+ }+ 2 => {+ let f = app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": "One"})).unwrap()["id"].clone();+ app.run("selection.set", json!({"ids": [f]})).unwrap();+ }+ 3 => {+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();+ }+ 4 => {+ let f = app.run("frame.create", json!({"rect": [72, 72, 400, 400]})).unwrap()["id"].clone();+ app.run("file.place", json!({"base64": pdf, "name": "a.pdf", "frame": f})).unwrap();+ app.run("selection.set", json!({"ids": [f]})).unwrap();+ }+ _ => {}+ }+ app.ui.dialog = None;+ app+ };+ let prefs = |app: &DesignApp| {+ let u = &app.ui;+ json!({+ "shortcuts": u.shortcuts, "hiddenMenuItems": u.hidden_menu_items, "uiScale": u.ui_scale,+ "brightness": u.brightness, "workspace": u.workspace, "customWorkspaces": u.custom_workspaces,+ "docking": u.docking, "dockingHidden": u.docking_hidden, "floating": u.floating,+ })+ };+ let quick = quick_apply_items(&setup(0).session, "workspace", false);+ assert!(quick.iter().any(|i| i.id == "window.newWorkspace"));+ // Deleting needs a workspace name: the application bar's workspace menu lists them.+ assert!(!quick.iter().any(|i| i.id == "window.deleteWorkspace"));+ // Each command runs as Quick Apply runs an entry. One that needs a selection may fail+ // without it, but runs in one of the contexts; none changes a preference it wasn't asked to.+ // Opening a panel or collapsing the dock to icons changes where the panels are, as it should.+ let opens_a_panel = [+ "app.tabsPanel",+ "app.characterStylesPanel",+ "app.paragraphStylesPanel",+ "app.characterPanel",+ "app.paragraphPanel",+ "app.glyphsPanel",+ "app.tablePanel",+ "window.collapseToIcons",+ ];+ let arrangement = ["docking", "dockingHidden", "floating"];+ let mut failed = Vec::new();+ for (id, ..) in quick_commands().filter(|(id, ..)| UI_COMMANDS.iter().any(|c| c.0 == *id)) {+ let mut errors = Vec::new();+ for (i, context) in contexts.iter().enumerate() {+ let mut app = setup(i);+ let before = prefs(&app);+ match app.run(id, json!({})) {+ Err(e) => errors.push(format!("{context}: {e}")),+ Ok(_) => {+ let after = prefs(&app);+ let changed: Vec<&String> =+ before.as_object().unwrap().iter().filter(|(k, v)| after.get(k.as_str()) != Some(*v)).map(|(k, _)| k).collect();+ let changed: Vec<&String> =+ changed.into_iter().filter(|k| !(opens_a_panel.contains(&id) && arrangement.contains(&k.as_str()))).collect();+ if !changed.is_empty() {+ failed.push(format!("{id} ({context}): changed {changed:?}"));+ }+ }+ }+ }+ if errors.len() == contexts.len() {+ failed.push(format!("{id}: {errors:?}"));+ }+ }+ assert!(failed.is_empty(), "{failed:#?}");+ }++ #[test]+ fn distribute_rows_menu_dispatches_an_undoable_edit() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let frame = app.run("frame.create", json!({"rect": [72, 72, 500, 700], "content": "text", "text": ""})).unwrap();+ app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();+ app.run("table.setRowHeight", json!({"row": 0, "height": 40, "mode": "exactly"})).unwrap();+ app.run("table.setRowHeight", json!({"row": 1, "height": 80, "mode": "exactly"})).unwrap();+ app.run("table.selectTable", json!({})).unwrap();+ activate(&mut app, "table.distributeRows", &Value::Null);+ assert!(app.ui.dialog.is_none());+ let info = app.run("table.get", json!({})).unwrap();+ assert_eq!(info["rows"][0]["height"], 60.0);+ assert_eq!(info["rows"][1]["height"], 60.0);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.run("table.get", json!({})).unwrap()["rows"][0]["height"], 40.0);+ }++ #[test]+ fn every_menu_entry_is_a_command() {+ let mut all = Vec::new();+ for (_, items) in menu_tree() {+ walk(&items, &mut all);+ }+ assert!(all.len() > 80, "{}", all.len());+ assert!(all.iter().any(|(label, id, _)| label == "Distribute Rows Evenly" && id == "table.distributeRows"));+ for (label, id, params) in &all {+ assert!(ui_label(id).is_some() || designcraft_engine::find_command(id).is_some(), "menu entry {label}: unknown command {id}");+ assert!(!label.is_empty() && label != id, "menu entry {id} has no label");+ if let Some(o) = params.as_object() {+ assert!(!o.is_empty(), "{id}: empty fixed params");+ }+ }+ // Nested submenus parse (Type › Insert Special Character › Symbols › …).+ let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1;+ let special = ty.iter().find_map(|i| match i {+ Item::Sub(n, c) if n == "Insert Special Character" => Some(c.clone()),+ _ => None,+ });+ assert!(special.is_some_and(|c| c.iter().any(|i| matches!(i, Item::Sub(n, _) if n == "Symbols"))));+ // Fixed-parameter variants keep their own labels.+ assert!(all.iter().any(|(l, id, _)| l == "Fill Frame Proportionally" && id == "fit.fillFrameProportionally"));+ }++ #[test]+ fn context_menus_hold_commands_and_menu_bar_submenus() {+ let tree = menu_tree();+ for entries in [CONTEXT_OBJECT, CONTEXT_GRAPHIC_FRAME, CONTEXT_OBJECT_TAIL, CONTEXT_TEXT_FRAME, CONTEXT_TEXT, CONTEXT_CANVAS] {+ for path in entries.iter().filter_map(|e| e.strip_prefix("menu:")) {+ assert!(menu_bar_submenu(&tree, path).is_some(), "no menu bar submenu {path}");+ }+ let mut all = Vec::new();+ for (_, items) in context_parse(entries) {+ walk(&items, &mut all);+ }+ for (label, id, _) in &all {+ assert!(ui_label(id).is_some() || designcraft_engine::find_command(id).is_some(), "context entry {label}: unknown command {id}");+ }+ }+ }+++ #[test]++ fn the_table_menu_follows_indesigns_order() {++ // InDesign's Table menu with a text insertion point (Adobe's "How to make a table").++ let table = menu_tree().into_iter().find(|(m, _)| *m == "Table").unwrap().1;++ let labels: Vec<String> = table++ .iter()++ .map(|i| match i {++ Item::Sep => "-".to_string(),++ Item::Sub(n, _) => format!("{n} >"),++ Item::Cmd { label, .. } => label.clone(),++ })++ .collect();++ let expected = [++ "Insert Table…",++ "Convert Text to Table",++ "Convert Table to Text",++ "-",++ "Cell Options >",++ "-",++ "Insert >",++ "Delete >",++ "Select >",++ "-",++ "Merge Cells",++ "Unmerge Cells",++ "Split Cell Horizontally",++ "Split Cell Vertically",++ "Convert Cell Type >",++ "Convert Rows >",++ "-",++ "Distribute Rows Evenly",++ "Distribute Columns Evenly",++ ];++ assert_eq!(labels, expected);++ // Cmd+Alt+Shift+T opens the dialog, as InDesign's; the engine command has no shortcut of++ // its own. The Table panel is in Window › Type & Tables.++ assert_eq!(ui_label("app.insertTableDialog").and_then(|c| c.1), Some("Cmd+Alt+Shift+T"));++ assert_eq!(designcraft_engine::find_command("table.insert").unwrap().shortcut, None);++ assert_eq!(ui_label("app.tablePanel").and_then(|c| c.1), Some("Shift+F9"));++ }+++ #[test]+ fn the_type_menu_follows_indesigns_order() {+ // InDesign's Type menu, as Chris Nielsen opens it in "Numbering Page Sections" (2:09).+ let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1;+ let labels: Vec<String> = ty+ .iter()+ .map(|i| match i {+ Item::Sep => "-".to_string(),+ Item::Sub(n, _) => format!("{n} >"),+ Item::Cmd { label, .. } => label.clone(),+ })+ .collect();+ let expected = [+ "Size >",+ "-",+ "Character",+ "Paragraph",+ "Tabs",+ "Glyphs",+ "-",+ "Character Styles",+ "Paragraph Styles",+ "-",+ "Create Outlines",+ "Find/Replace Font…",+ "Reload Fonts",+ "Change Case >",+ "-",+ "Type on a Path >",+ "-",+ "Notes >",+ "Track Changes >",+ "-",+ "Insert Footnote",+ "Document Footnote Options…",+ "Insert Endnote",+ ];+ assert_eq!(&labels[..expected.len()], expected, "{labels:?}");+ let pos = |l: &str| labels.iter().position(|x| x == l).unwrap_or_else(|| panic!("{l} in {labels:?}"));+ assert!(pos("Hyperlinks & Cross-References >") < pos("Text Variables >"));+ assert!(pos("Text Variables >") < pos("Bulleted & Numbered Lists >"));+ assert!(pos("Bulleted & Numbered Lists >") < pos("Insert Special Character >"));+ assert!(pos("Insert Special Character >") < pos("Insert White Space >"));+ assert!(pos("Insert Break Character >") < pos("Fill with Placeholder Text"));+ assert!(pos("Fill with Placeholder Text") < pos("Show Hidden Characters"));+ // Alignment, styles and point sizes keep their shortcuts, out of the menu as in InDesign.+ for gone in ["Align Left", "Bold", "Increase Point Size", "Paragraph Rules…"] {+ assert!(!labels.iter().any(|l| l == gone), "{gone}");+ }+ let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let all = effective_shortcuts(&app);+ for (id, sc) in [+ ("type.alignLeft", "Cmd+Shift+L"),+ ("app.characterPanel", "Cmd+T"),+ ("app.paragraphPanel", "Cmd+Alt+T"),+ ("app.insertCurrentPageNumber", "Cmd+Alt+Shift+N"),+ ] {+ assert_eq!(all.iter().find(|(i, _)| i == id).map(|(_, s)| s.as_str()), Some(sc), "{id}");+ }+ // Markers › Current Page Number carries ⌥⇧⌘N.+ let markers = ty+ .iter()+ .find_map(|i| match i {+ Item::Sub(n, c) if n == "Insert Special Character" => {+ c.iter().find_map(|i| if let Item::Sub(n, c) = i { (n == "Markers").then(|| c.clone()) } else { None })+ }+ _ => None,+ })+ .unwrap();+ assert!(matches!(&markers[0], Item::Cmd { label, shortcut: Some("Cmd+Alt+Shift+N"), .. } if label == "Current Page Number"));+ }++ #[test]+ fn type_panel_items_open_their_panels_and_the_marker_shortcut_inserts_a_page_number() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ activate(&mut app, "app.characterPanel", &Value::Null);+ assert!(crate::panel_docking::showing(&app, "character"));+ // Paragraph Styles opens floating, grouped with Character Styles, as in InDesign.+ activate(&mut app, "app.paragraphStylesPanel", &Value::Null);+ let layout = app.ui.docking.as_ref().unwrap();+ assert!(+ layout+ .floating+ .iter()+ .flat_map(crate::panel_docking::window_groups)+ .any(|g| g.panels == ["characterStyles", "paragraphStyles"] && g.active == 1)+ );+ let story = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "Page "})).unwrap()["story"].clone();+ app.run("text.select", json!({"story": story, "anchor": 5, "focus": 5})).unwrap();+ activate(&mut app, "app.insertCurrentPageNumber", &Value::Null);+ let d = &app.session.doc().unwrap().doc;+ assert_eq!(d.story(designcraft_doc::StoryId(story.as_u64().unwrap())).unwrap().text, "Page \u{e000}");+ }++ #[test]+ fn custom_workspaces_save_apply_and_delete() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.dock_tab = "swatches".into();+ app.ui.control_bar = true;+ run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap();+ run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap();+ app.ui.dock_tab = "properties".into();+ run_ui(&mut app, "window.workspace", &json!({"name": "Mine"})).unwrap().unwrap();+ assert_eq!((app.ui.dock_tab.as_str(), app.ui.control_bar, app.ui.workspace.as_str()), ("swatches", true, "Mine"));+ app.ui.dock_tab = "layers".into();+ run_ui(&mut app, "window.resetWorkspace", &json!({})).unwrap().unwrap();+ assert_eq!(app.ui.dock_tab, "swatches", "reset to the saved arrangement");+ run_ui(&mut app, "window.deleteWorkspace", &json!({"name": "Mine"})).unwrap().unwrap();+ assert!(app.ui.custom_workspaces.is_empty());+ assert_eq!(app.ui.workspace, "Essentials");+ }++ /// New Workspace › Capture (Learn Skills Daily's InDesign course, 11:40): Panel Locations and+ /// Menu Customization, both on by default.+ #[test]+ fn new_workspace_captures_panel_locations_and_menu_customization() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ // The dialog offers both, checked.+ run_ui(&mut app, "window.newWorkspace", &json!({})).unwrap().unwrap();+ let d = app.ui.dialog.take().unwrap();+ assert_eq!(+ (d.id.as_str(), d.fields["panelLocations"].clone(), d.fields["menuCustomization"].clone()),+ ("newWorkspace", json!(true), json!(true))+ );+ // Both captured.+ app.ui.dock_tab = "swatches".into();+ app.ui.hidden_menu_items = vec!["Type/Glyphs".into()];+ run_ui(&mut app, "window.newWorkspace", &json!({"name": "All"})).unwrap().unwrap();+ // Menus only: choosing it leaves the panels where they are.+ app.ui.hidden_menu_items = vec!["Layout/Pages".into()];+ run_ui(&mut app, "window.newWorkspace", &json!({"name": "Menus", "panelLocations": false})).unwrap().unwrap();+ // Panels only: the menus stay as they are.+ app.ui.dock_tab = "layers".into();+ run_ui(&mut app, "window.newWorkspace", &json!({"name": "Panels", "menuCustomization": false})).unwrap().unwrap();+ app.ui.dock_tab = "properties".into();+ app.ui.hidden_menu_items.clear();+ run_ui(&mut app, "window.workspace", &json!({"name": "Menus"})).unwrap().unwrap();+ assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("properties", vec!["Layout/Pages".to_string()]));+ run_ui(&mut app, "window.workspace", &json!({"name": "Panels"})).unwrap().unwrap();+ assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("layers", vec!["Layout/Pages".to_string()]));+ run_ui(&mut app, "window.workspace", &json!({"name": "All"})).unwrap().unwrap();+ assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("swatches", vec!["Type/Glyphs".to_string()]));+ // A workspace saved before the options existed restores its panels.+ let old: crate::SavedWorkspace = serde_json::from_value(json!({"name": "Old", "dockTab": "pages"})).unwrap();+ assert!(!old.keep_panels && old.hidden_menu_items.is_none());+ }++ #[test]+ fn essentials_classic_is_the_control_panel_and_iconic_groups() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ run_ui(&mut app, "window.workspace", &json!({"name": "Essentials Classic"})).unwrap().unwrap();+ assert!(app.ui.control_bar && !app.ui.dock_expanded);+ let groups = app.ui.icon_groups.clone().unwrap();+ assert_eq!(groups[0], ["pages", "layers", "links"]);+ assert_eq!(groups.last().unwrap(), &["gradient"]);+ assert_eq!(checked(&app, "window.workspace", &json!({"name": "Essentials Classic"})), Some(true));+ assert_eq!(checked(&app, "window.workspace", &json!({"name": "Essentials"})), Some(false));+ // Window › Pages opens Pages from its icon group, not the Properties stack.+ run_ui(&mut app, "window.panel", &json!({"panel": "pages"})).unwrap().unwrap();+ assert!(crate::panel_docking::showing(&app, "pages"));+ let layout = app.ui.docking.clone().unwrap();+ assert!(!layout.contains(&"properties".to_string()));+ assert_eq!(crate::panel_docking::tab_group(&layout, "pages"), ["pages", "layers", "links"]);+ // A workspace saved from it keeps the groups.+ run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap();+ run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap();+ assert_eq!((app.ui.icon_groups.as_ref(), app.ui.dock_expanded, app.ui.control_bar), (None, true, false));+ run_ui(&mut app, "window.workspace", &json!({"name": "Mine"})).unwrap().unwrap();+ assert_eq!(app.ui.icon_groups, Some(groups));+ }++ #[test]+ fn typography_workspace_opens_its_panels_from_named_icon_groups_and_resets() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ run_ui(&mut app, "window.workspace", &json!({"name":"Typography"})).unwrap().unwrap();+ assert!(app.ui.control_bar);+ assert!(!app.ui.dock_expanded);+ assert!(app.ui.open_panel.is_none());+ let groups = app.ui.icon_groups.clone().unwrap();+ assert_eq!(groups[0], ["pages", "layers", "swatches"]);+ assert_eq!(groups[4], ["paragraph", "paragraphStyles"]);+ assert_eq!(groups[5], ["character", "characterStyles"]);+ for panel in ["pages", "paragraphStyles", "characterStyles"] {+ run_ui(&mut app, "window.panel", &json!({"panel":panel})).unwrap().unwrap();+ assert!(crate::panel_docking::showing(&app, panel), "{panel}");+ assert!(app.ui.docking.as_ref().unwrap().floating.is_empty(), "{panel} opens from its icon group");+ }+ run_ui(&mut app, "window.resetWorkspace", &json!({})).unwrap().unwrap();+ assert_eq!(app.ui.icon_groups, Some(groups));+ assert!(app.ui.open_panel.is_none());+ assert!(!app.ui.dock_expanded);+ run_ui(&mut app, "window.workspace", &json!({"name":"Essentials"})).unwrap().unwrap();+ assert!(app.ui.icon_groups.is_none());+ assert!(app.ui.dock_expanded);+ }++ #[test]+ fn the_window_menu_is_in_indesigns_order_and_reaches_every_panel() {+ let window = menu_tree().into_iter().find(|(m, _)| *m == "Window").unwrap().1;+ let names: Vec<&str> = window+ .iter()+ .filter_map(|i| match i {+ Item::Sub(n, _) => Some(n.as_str()),+ Item::Cmd { label, .. } => Some(label.as_str()),+ Item::Sep => None,+ })+ .collect();+ assert_eq!(&names[..4], ["Arrange", "Workspace", "Articles", "Color"]);+ let sub = |name: &str| {+ window+ .iter()+ .find_map(|i| match i {+ Item::Sub(n, c) if n == name => Some(c.clone()),+ _ => None,+ })+ .unwrap()+ };+ // Window › Workspace › Essentials Classic, Window › Color › Gradient & Swatches.+ assert!(+ sub("Workspace")+ .iter()+ .any(|i| matches!(i, Item::Cmd { id, params, .. } if id == "window.workspace" && params["name"] == "Essentials Classic"))+ );+ let color: Vec<String> = sub("Color").iter().filter_map(|i| if let Item::Cmd { label, .. } = i { Some(label.clone()) } else { None }).collect();+ assert_eq!(color, ["Color", "Gradient", "Swatches"]);+ // Every panel is in the menu.+ fn panels(items: &[Item], out: &mut Vec<String>) {+ for i in items {+ match i {+ Item::Sub(_, c) => panels(c, out),+ Item::Cmd { id, params, .. } if id == "window.panel" => out.extend(params["panel"].as_str().map(str::to_string)),+ _ => {}+ }+ }+ }+ let mut found = Vec::new();+ panels(&window, &mut found);+ for (id, _, _) in crate::dock::DOCK_TABS.iter().chain(crate::dock::ICON_PANELS) {+ assert!(found.iter().any(|p| p == id), "Window menu misses the {id} panel");+ }+ }++ #[test]+ fn interactive_workspaces_show_their_panels() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.dock_expanded = false;+ run_ui(&mut app, "window.workspace", &json!({"name": "Interactive for PDF"})).unwrap().unwrap();+ assert_eq!((app.ui.dock_tab.as_str(), app.ui.dock_expanded, app.ui.open_panel.as_deref()), ("pages", true, Some("buttons")));+ run_ui(&mut app, "window.workspace", &json!({"name": "Digital Publishing"})).unwrap().unwrap();+ assert_eq!((app.ui.dock_tab.as_str(), app.ui.open_panel.as_deref()), ("pages", Some("liquid")));+ run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap();+ assert_eq!(app.ui.open_panel, None);+ }++ #[test]+ fn hide_and_show_menu_items() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let items = all_menu_items();+ let (menu, label) = items.iter().find(|(m, _)| m == "Edit").cloned().expect("Edit items");+ let key = menu_key(&menu, &label);+ run_ui(&mut app, "window.hideMenuItem", &json!({"item": key})).unwrap().unwrap();+ assert!(app.ui.hidden_menu_items.contains(&key));+ run_ui(&mut app, "window.hideMenuItem", &json!({"item": key, "hidden": false})).unwrap().unwrap();+ assert!(app.ui.hidden_menu_items.is_empty());+ assert!(items.len() > 100, "every menu's items are listed: {}", items.len());+ }++ /// The Type menu as drawn: every item label.+ fn drawn_type_menu(app: &mut DesignApp) -> Vec<String> {+ let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1;+ let ctx = egui::Context::default();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 4000.0));+ let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| {+ menu_items(app, ui, &ty, "Type");+ });+ out.textures_delta.clear();+ fn collect(shape: &egui::Shape, out: &mut Vec<String>) {+ match shape {+ egui::Shape::Text(t) => out.push(t.galley.job.text.trim().to_string()),+ egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),+ _ => {}+ }+ }+ let mut labels = Vec::new();+ out.shapes.iter().for_each(|s| collect(&s.shape, &mut labels));+ labels+ }++ /// Tate-Chu-Yoko, Ruby, Kenten and Warichu are in the Type menu of InDesign's Japanese edition+ /// only: they show while Show CJK Features is on, which follows the interface language until+ /// the user sets it. Hidden, they still run.+ #[test]+ fn cjk_menu_items_follow_show_cjk_features() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1;+ let cjk: Vec<String> = ty+ .iter()+ .filter_map(|i| match i {+ Item::Cmd { label, id, .. } if CJK_ONLY.contains(&id.as_str()) => Some(label.clone()),+ _ => None,+ })+ .collect();+ assert_eq!(cjk.len(), 4, "{cjk:?}");+ let drawn = |app: &mut DesignApp| {+ let labels = drawn_type_menu(app);+ assert!(labels.iter().any(|l| l == crate::i18n::tr(&app.ui.language, "Story Direction")), "in both editions: {labels:?}");+ let shown: Vec<bool> = cjk.iter().map(|l| labels.iter().any(|d| d == crate::i18n::tr(&app.ui.language, l))).collect();+ assert!(shown.iter().all(|s| *s == shown[0]), "{shown:?}");+ shown[0]+ };+ for (lang, on) in [("", false), ("de", false), ("ja", true), ("zh", true), ("ko", true)] {+ app.ui.language = lang.into();+ assert_eq!(crate::cjk_features(&app), on, "{lang}");+ assert_eq!(drawn(&mut app), on, "{lang}");+ }+ app.run("prefs.set", json!({"cjkFeatures": false})).unwrap();+ assert!(!drawn(&mut app), "off in a Korean interface");+ app.ui.language = String::new();+ app.run("prefs.set", json!({"cjkFeatures": true})).unwrap();+ assert!(drawn(&mut app), "on in an English interface");+ assert!(quick_apply_items(&app.session, "ruby", crate::cjk_features(&app)).iter().any(|i| i.id == "app.rubyDialog"));+ app.run("prefs.set", json!({"cjkFeatures": false})).unwrap();+ assert!(!drawn(&mut app));+ assert!(!quick_apply_items(&app.session, "ruby", crate::cjk_features(&app)).iter().any(|i| i.id == "app.rubyDialog"));+ app.run("app.rubyDialog", json!({})).unwrap();+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("ruby"), "hidden, not removed");+ }++ /// Preferences › Type › Show CJK Features: left as it is, it keeps following the interface+ /// language; changed, it is kept in prefs.json.+ #[test]+ fn show_cjk_features_is_a_persisted_preference() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = "ja".into();+ run_ui(&mut app, "app.preferences", &json!({})).unwrap().unwrap();+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cjkFeatures"], true);+ crate::dialogs::confirm(&mut app).unwrap();+ assert_eq!(app.session.prefs.cjk_features, None, "untouched: follows the language");+ run_ui(&mut app, "app.preferences", &json!({})).unwrap().unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("cjkFeatures".into(), json!(false));+ crate::dialogs::confirm(&mut app).unwrap();+ assert_eq!(app.session.prefs.cjk_features, Some(false));+ assert!(!crate::cjk_features(&app));+ // prefs.json round trip; a file from before the setting follows the language.+ let saved = serde_json::to_vec(&app.session.prefs).unwrap();+ assert_eq!(serde_json::from_slice::<designcraft_engine::Prefs>(&saved).unwrap().cjk_features, Some(false));+ assert_eq!(serde_json::from_str::<designcraft_engine::Prefs>(r#"{"scaleStrokes": false}"#).unwrap().cjk_features, None);+ assert_eq!(app.run("prefs.set", json!({"cjkFeatures": null})).unwrap()["cjkFeatures"], Value::Null);+ assert!(crate::cjk_features(&app), "follows the Japanese interface again");+ }++ #[test]+ fn menu_button_fits_its_anchor_and_resets_scroll_on_reopen() {+ // Workspace/panel menus may be in the middle; the status-bar zoom menu opens upwards.+ for anchor_y in [0.0, 130.0, 260.0] {+ let ctx = egui::Context::default();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0));+ let mut tick = 0;+ let mut frame = |events: Vec<egui::Event>| {+ tick += 1;+ let mut button = None;+ let mut first = None;+ let mut last = None;+ let mut output =+ ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| {+ ui.add_space(anchor_y);+ let response = menu_button(ui, "Long menu", |ui| {+ for i in 0..60 {+ let response = ui.button(format!("Item {i}"));+ if i == 0 {+ first = Some((response.rect, ui.clip_rect()));+ }+ if i == 59 {+ last = Some((response.rect, ui.clip_rect()));+ }+ }+ });+ button = Some(response.response);+ });+ output.textures_delta.clear();+ (button.expect("menu button"), first, last)+ };+ let click =+ |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };+ frame(vec![]);+ let (button, _, _) = frame(vec![]);+ let anchor = button.rect;+ for pressed in [true, false] {+ frame(vec![egui::Event::PointerMoved(anchor.center()), click(anchor.center(), pressed)]);+ }+ for _ in 0..3 {+ frame(vec![]);+ }+ let popup = ctx.memory(|memory| memory.area_rect(egui::Popup::default_response_id(&button))).expect("open menu");+ assert!(screen.contains_rect(popup), "menu at {anchor_y} fits in the viewport: {popup:?}");+ assert!(+ popup.top() >= anchor.bottom() - 1.0 || popup.bottom() <= anchor.top() + 1.0,+ "menu at {anchor_y} stays on one side of its button: {popup:?}, {anchor:?}"+ );+ let (_, first, last) = frame(vec![]);+ let (first, clip) = first.expect("first row");+ assert!(clip.contains_rect(first), "newly opened menu starts at the first row");+ assert!(!clip.intersects(last.expect("last row").0), "last row starts below the scroll area");++ frame(vec![+ egui::Event::PointerMoved(popup.center()),+ egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: egui::vec2(0.0, -5000.0),+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ source: egui::MouseWheelSource::Unknown,+ },+ ]);+ for _ in 0..60 {+ frame(vec![]);+ }+ let (_, first, last) = frame(vec![]);+ let (last, clip) = last.expect("scrolled last row");+ assert!(popup.contains_rect(last) && clip.contains_rect(last), "last row is reachable: {last:?}, {popup:?}, {clip:?}");+ assert!(!clip.intersects(first.expect("scrolled first row").0), "menu really scrolled away from its start");++ let outside = egui::pos2(screen.right() - 10.0, screen.center().y);+ for pressed in [true, false] {+ frame(vec![egui::Event::PointerMoved(outside), click(outside, pressed)]);+ }+ assert!(!egui::Popup::is_any_open(&ctx), "outside click closes the menu");+ assert!(frame(vec![]).1.is_none(), "closed menu is no longer drawn");+ for pressed in [true, false] {+ frame(vec![egui::Event::PointerMoved(anchor.center()), click(anchor.center(), pressed)]);+ }+ for _ in 0..3 {+ frame(vec![]);+ }+ let (_, first, last) = frame(vec![]);+ let (first, clip) = first.expect("reopened first row");+ assert!(popup.contains_rect(first) && clip.contains_rect(first), "reopening resets to the first row: {first:?}, {clip:?}");+ assert!(!clip.intersects(last.expect("reopened last row").0), "reopening discards the old scroll offset");+ }+ }++ #[test]+ fn tiny_menu_viewport_does_not_force_the_default_scroll_height() {+ let ctx = egui::Context::default();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 100.0));+ let mut tick = 0;+ let mut frame = |events: Vec<egui::Event>| {+ tick += 1;+ let mut button = None;+ let mut output =+ ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| {+ ui.add_space(35.0);+ let response = menu_button(ui, "Long menu", |ui| {+ for i in 0..20 {+ let _ = ui.button(format!("Item {i}"));+ }+ });+ button = Some(response.response);+ });+ output.textures_delta.clear();+ button.expect("menu button")+ };+ frame(vec![]);+ let button = frame(vec![]);+ let pos = button.rect.center();+ for pressed in [true, false] {+ frame(vec![+ egui::Event::PointerMoved(pos),+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ]);+ }+ for _ in 0..3 {+ frame(vec![]);+ }+ let popup = ctx.memory(|memory| memory.area_rect(egui::Popup::default_response_id(&button))).expect("open menu");+ let space = (screen.bottom() - button.rect.bottom()).max(button.rect.top() - screen.top());+ assert!(space < 64.0, "fixture has less space than egui's default minimum scroll height");+ // A complete command row may not fit, but the scroll area's minimum must not make+ // the popup exceed its height budget or cover the button that dismisses it.+ assert!(popup.height() <= space, "tiny menu respects its available height: {popup:?}, {space}");+ assert!(screen.contains_rect(popup), "tiny menu remains inside the viewport: {popup:?}");+ assert!(+ popup.top() >= button.rect.bottom() - 1.0 || popup.bottom() <= button.rect.top() + 1.0,+ "tiny menu stays beside its anchor: {popup:?}, {:?}",+ button.rect+ );+ }++ #[test]+ fn clipped_submenu_does_not_open_when_hovering_outside_menu() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 900.0));+ let entries = vec![Item::Sub("Hidden submenu".into(), vec![cmd_item("app.preferences", Value::Null)])];+ let mut tick = 0;+ let mut frame = |spacing: f32, events: Vec<egui::Event>| {+ tick += 1;+ let mut button_rect = egui::Rect::NOTHING;+ let mut hidden_submenu = None;+ let mut output =+ ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| {+ egui::MenuBar::new().ui(ui, |ui| {+ let response = ui.menu_button("Menu", |ui| {+ egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| {+ ui.add_space(spacing);+ let button_id = ui.next_auto_id();+ menu_items(&mut app, ui, &entries, "Test");+ let response = ui.ctx().read_response(button_id).expect("submenu button response");+ let open = egui::containers::menu::MenuState::from_ui(ui, |state, _| state.open_item.is_some());+ hidden_submenu = Some((response.rect, ui.clip_rect(), open));+ });+ });+ button_rect = response.response.rect;+ });+ });+ output.textures_delta.clear();+ (button_rect, hidden_submenu)+ };+ frame(500.0, vec![]);+ let button = frame(500.0, vec![]).0.center();+ for pressed in [true, false] {+ frame(+ 500.0,+ vec![+ egui::Event::PointerMoved(button),+ egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ for _ in 0..3 {+ frame(500.0, vec![]);+ }+ let (_, Some((hidden, clip, open))) = frame(500.0, vec![]) else { panic!("test menu is open") };+ assert!(!open, "submenu starts closed");+ assert!(screen.contains_rect(hidden), "hidden row remains inside the screen: {hidden:?}");+ assert!(!clip.intersects(hidden), "submenu must be fully clipped: {hidden:?}, {clip:?}");+ let (_, Some((_, _, open))) = frame(500.0, vec![egui::Event::PointerMoved(hidden.center())]) else { panic!("test menu remains open") };+ assert!(!open, "hovering the clipped row's position outside the menu must not open its submenu");++ let partial_spacing = 500.0 - (hidden.top() - clip.bottom()) - 6.0;+ let (_, Some((partial, clip, open))) = frame(partial_spacing, vec![]) else { panic!("test menu remains open") };+ assert!(!open);+ assert!(partial.top() < clip.bottom() && partial.bottom() > clip.bottom(), "row must be partially clipped: {partial:?}, {clip:?}");+ let outside = egui::pos2(partial.center().x, clip.bottom() + 1.0);+ let (_, Some((_, _, open))) = frame(partial_spacing, vec![egui::Event::PointerMoved(outside)]) else { panic!("test menu remains open") };+ assert!(!open, "hovering the clipped portion of a partially visible row must not open its submenu");+ let visible = partial.intersect(clip).center();+ let (_, Some((_, _, open))) = frame(partial_spacing, vec![egui::Event::PointerMoved(visible)]) else { panic!("test menu remains open") };+ assert!(open, "hovering the visible portion still opens the submenu");+ let (_, Some((_, _, open))) = frame(500.0, vec![]) else { panic!("test menu remains open") };+ assert!(!open, "an open submenu closes when its row becomes fully clipped");+ }++ #[test]+ fn native_labels_keep_their_ampersands() {+ assert_eq!(native_label("Numbering & Section Options…"), "Numbering && Section Options…");+ assert_eq!(native_label("A&&B"), "A&&&&B");+ assert_eq!(native_label("Pages"), "Pages");+ }++ #[test]+ fn the_mac_window_menu_minimizes_with_cmd_m() {+ let window = native_menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, e)| e).unwrap_or_default();+ assert!(matches!(window.first(), Some(Item::Cmd { id, shortcut: Some("Cmd+M"), .. }) if id == "window.minimize"), "{:?}", window.first());+ assert!(matches!(window.get(1), Some(Item::Sep)));+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ assert!(run_ui(&mut app, "window.minimize", &Value::Null).is_some_and(|r| r.is_err()), "no host window controls");+ app.native_menu = true;+ assert!(menu_enabled(&app, "window.minimize") && !menu_enabled(&app, "window.maximize"));+ run_ui(&mut app, "window.minimize", &Value::Null).unwrap().unwrap();+ assert_eq!(app.pending_window_commands, [egui::ViewportCommand::Minimized(true)]);+ }++ #[test]+ fn mac_settings_follow_about_in_the_app_menu_and_leave_edit() {+ let pos = |command: &str| MAC_APP_MENU.iter().position(|m| matches!(m, AppMenuItem::Cmd { command: c, .. } if *c == command));+ let (Some(about), Some(settings)) = (pos("help.about"), pos("app.preferences")) else { panic!("About and Settings are in the app menu") };+ assert!(about < settings);+ assert_eq!(MAC_APP_MENU.get(settings - 1), Some(&AppMenuItem::Sep));+ // Language follows Settings, as in the suite's other apps, titled in the interface language.+ assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Language));+ assert_eq!(MAC_APP_MENU.get(settings + 2), Some(&AppMenuItem::Sep));+ let label = |command: &str| {+ MAC_APP_MENU.iter().find_map(|m| match m {+ AppMenuItem::Cmd { label, command: c, .. } if *c == command => Some(*label),+ _ => None,+ })+ };+ assert_eq!(label("app.preferences"), Some("Settings…"));+ let ids = MAC_APP_MENU.iter().filter_map(|m| if let AppMenuItem::Cmd { id, .. } = m { Some(*id) } else { None }).collect::<Vec<_>>();+ assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "native ids are unique: {ids:?}");++ let edit = |tree: Vec<(&'static str, Vec<Item>)>| {+ let mut out = Vec::new();+ walk(&tree.into_iter().find(|(t, _)| *t == "Edit").map(|(_, e)| e).unwrap_or_default(), &mut out);+ out.into_iter().map(|(_, id, _)| id).collect::<Vec<_>>()+ };+ assert!(edit(menu_tree()).iter().any(|id| id == "app.preferences"), "the in-window Edit menu keeps Preferences");+ let native = native_menu_tree();+ let mut all = Vec::new();+ for (_, entries) in &native {+ walk(entries, &mut all);+ }+ assert!(!all.iter().any(|(_, id, _)| id == "app.preferences"), "the macOS menu bar has Settings only in the app menu");+ assert!(edit(native_menu_tree()).iter().any(|id| id == "app.keyboardShortcuts"));+ for (title, entries) in &native {+ assert!(!matches!(entries.first(), Some(Item::Sep)) && !matches!(entries.last(), Some(Item::Sep)), "{title}: separator at an end");+ assert!(entries.windows(2).all(|w| !matches!(w, [Item::Sep, Item::Sep])), "{title}: doubled separator");+ }+ }++ /// Web save: a download that couldn't start is an error and leaves the document unsaved; one+ /// that started marks it saved.+ #[test]+ fn web_save_marks_the_document_saved_only_after_the_download_starts() {+ let dir = tempfile::tempdir().unwrap();+ // The title names a temporary path: on native, file.saveAs writes where the web build doesn't.+ let title = dir.path().join("doc").to_string_lossy().to_string();+ let fails = std::rc::Rc::new(std::cell::Cell::new(true));+ let f = fails.clone();+ let services = crate::Services {+ download: Some(Box::new(move |_: &str, _: &[u8]| if f.get() { Err("blocked".into()) } else { Ok(()) })),+ ..Default::default()+ };+ let mut app = DesignApp::new(designcraft_engine::Session::new(), services);+ app.run("file.new", json!({"title": title})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 300, 200]})).unwrap();+ assert!(app.session.active().unwrap().is_dirty());++ let e = app.run("app.save", json!({})).unwrap_err();+ assert!(e.contains("blocked"), "{e}");+ assert!(app.session.active().unwrap().is_dirty(), "a failed download leaves the document unsaved");++ fails.set(false);+ app.run("app.save", json!({})).unwrap();+ assert!(!app.session.active().unwrap().is_dirty());+ }++ fn start_screen_texts(app: &mut crate::DesignApp) -> Vec<String> {+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx, "");+ let mut shapes = Vec::new();+ for _ in 0..3 {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ shapes = out.shapes;+ }+ shapes+ .iter()+ .filter_map(|s| match &s.shape {+ egui::Shape::Text(t) => Some(t.galley.text().to_string()),+ _ => None,+ })+ .collect()+ }++ /// File › Open Recent: the files first (`app.openRecent {index}`), then Clear Recent Files.+ #[test]+ fn open_recent_lists_the_files_then_clear() {+ let tree = menu_tree();+ let file = &tree.iter().find(|(m, _)| *m == "File").unwrap().1;+ let Some(Item::Sub(name, children)) = file.get(2) else { panic!("Open Recent after Open…: {:?}", file.get(2)) };+ assert_eq!(format!("File/{name}"), OPEN_RECENT);+ assert!(matches!(children.as_slice(), [Item::Cmd { id, .. }] if id == "file.clearRecent"));+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ assert!(recent_items(&app).is_empty());+ assert!(!menu_enabled(&app, "file.clearRecent"));+ app.session.prefs.note_recent_file("/work/a.designcraft");+ app.session.prefs.note_recent_file("/work/b.idml");+ let items = recent_items(&app);+ let labels: Vec<_> = items+ .iter()+ .map(|i| match i {+ Item::Cmd { label, id, params, .. } => format!("{label} {id} {params}"),+ Item::Sep => "-".into(),+ Item::Sub(..) => "sub".into(),+ })+ .collect();+ assert_eq!(labels, ["b.idml app.openRecent {\"index\":0}", "a.designcraft app.openRecent {\"index\":1}", "-"]);+ assert!(menu_enabled(&app, "file.clearRecent"));+ assert!(menu_enabled(&app, "app.openRecent"));+ }++ /// A recent file that is gone says so in an alert (and the start screen still lists it).+ #[test]+ fn open_recent_of_a_missing_file_alerts_and_the_start_screen_lists_recent_files() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ assert!(!start_screen_texts(&mut app).iter().any(|t| t == "Recent files"), "no section without recent files");+ app.session.prefs.note_recent_file("/nonexistent/dc-recent/gone.designcraft");+ assert!(app.run("app.openRecent", json!({"index": 0})).is_err());+ let d = app.ui.dialog.take().expect("an alert");+ assert_eq!(d.fields["title"], "Can't Open the File");+ assert_eq!(d.fields["file"], "gone.designcraft");+ assert!(d.fields["message"].as_str().unwrap().contains("can't be found"));+ assert!(app.run("app.openRecent", json!({"index": 9})).is_err(), "out of range: an error, not a panic");+ app.ui.dialog = None;+ let texts = start_screen_texts(&mut app);+ assert!(texts.iter().any(|t| t == "Recent files"), "{texts:?}");+ assert!(texts.iter().any(|t| t == "gone"), "the card names it without `.designcraft`: {texts:?}");+ }++ /// On a short window (1366 x 768 laptops) the start screen is taller than the window; the part+ /// below the fold has to be reachable by scrolling instead of being cut off.+ #[test]+ fn start_screen_scrolls_when_the_window_is_too_short() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx, "");+ let size = egui::vec2(1366.0, 300.0);+ let mut tile_y = |events: Vec<egui::Event>| {+ let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ out.shapes.iter().find_map(|s| match &s.shape {+ // The preset tiles paint their names even when scrolled out of view (labels skip that).+ egui::Shape::Text(t) if t.galley.text() == "Tabloid" => Some(t.pos.y),+ _ => None,+ })+ };+ let at = egui::pos2(600.0, 150.0);+ let mut before = None;+ for _ in 0..3 {+ before = tile_y(vec![egui::Event::PointerMoved(at)]);+ }+ let before = before.expect("the Tabloid tile is laid out");+ let wheel = egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: egui::vec2(0.0, -400.0),+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ source: egui::MouseWheelSource::Unknown,+ };+ let mut after = tile_y(vec![egui::Event::PointerMoved(at), wheel]);+ for _ in 0..30 {+ after = tile_y(Vec::new());+ }+ let after = after.expect("the Tabloid tile is laid out");+ assert!(after < before - 50.0, "the start screen should scroll: {before} -> {after}");+ }++ // Regression test for #329: on the start screen (no document) the Help menu's links were greyed out.+ #[test]+ fn help_links_are_enabled_without_a_document() {+ let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ assert!(app.session.active().is_none());+ let ids: Vec<&str> = UI_COMMANDS.iter().map(|c| c.0).filter(|id| id.starts_with("help.")).collect();+ assert!(ids.contains(&"help.discord") && ids.contains(&"help.github"), "{ids:?}");+ for id in ids {+ assert!(menu_enabled(&app, id), "{id} must work from the start screen");+ }+ assert!(!menu_enabled(&app, "view.rulers"), "other UI commands still need a document");+ }++ // Regression test for #248: the start screen offered no A6 sheet (it listed only the first ten presets).+ #[test]+ fn start_screen_offers_every_print_preset_including_a6() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let texts = start_screen_texts(&mut app);+ for p in designcraft_doc::build::PRESETS.iter().filter(|p| p.intent == designcraft_doc::Intent::Print) {+ assert!(texts.iter().any(|t| t == p.name), "start screen lacks the {} card: {texts:?}", p.name);+ }+ assert!(texts.iter().any(|t| t == "A6"), "{texts:?}");+ let a6 = designcraft_doc::build::PRESETS.iter().find(|p| p.name == "A6").unwrap();+ assert!((a6.width - 105.0 * 72.0 / 25.4).abs() < 0.01 && (a6.height - 148.0 * 72.0 / 25.4).abs() < 0.01, "{a6:?}");+ let page = crate::panels::properties::PAGE_PRESETS.iter().find(|p| p.0 == "A6").expect("Properties page-size list has A6");+ assert!((page.1 - a6.width).abs() < 0.01 && (page.2 - a6.height).abs() < 0.01, "{page:?} vs {a6:?}");+ }++ // Regression test for #249: a menu row only reacted over its text, not across the whole row.+ #[test]+ fn menu_rows_are_selectable_across_the_full_width() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));+ let entries = vec![cmd_item("app.preferences", Value::Null)];+ let mut tick = 0;+ let mut frame = |app: &mut DesignApp, events: Vec<egui::Event>| {+ tick += 1;+ let mut row = egui::Rect::NOTHING;+ let mut output =+ ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| {+ egui::Area::new(egui::Id::unique("menu_rows")).fixed_pos(egui::pos2(50.0, 50.0)).show(ui.ctx(), |ui| {+ let before = ui.cursor().min;+ menu_column(app, ui, &[("Test", entries.clone())]);+ row = egui::Rect::from_min_max(before, ui.min_rect().max);+ });+ });+ output.textures_delta.clear();+ row+ };+ frame(&mut app, vec![]);+ let row = frame(&mut app, vec![]);+ assert!(row.width() >= 239.0, "the column is at least 240 wide: {row:?}");+ let far = egui::pos2(row.right() - 6.0, row.top() + 8.0);+ for pressed in [true, false] {+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(far),+ egui::Event::PointerButton { pos: far, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ assert!(app.ui.dialog.is_some(), "clicking the empty end of the Preferences… row must choose it");+ }++ /// Quick Apply and the menu search list no unavailable docking command and no label twice+ /// among the UI commands.+ #[test]+ fn searched_ui_commands_are_available_and_named_once() {+ let ui_ids: Vec<&str> = UI_COMMANDS.iter().map(|c| c.0).collect();+ let searched: Vec<(&str, &str)> = quick_commands().filter(|c| ui_ids.contains(&c.0)).map(|c| (c.0, c.1)).collect();+ assert!(!searched.iter().any(|c| matches!(c.0, "window.panel.window" | "window.workspace.lock" | "window.workspace")), "{searched:?}");+ assert!(searched.iter().any(|c| c.0 == "window.collapseToIcons"), "Collapse to Icons is searched");+ // Quick Apply runs an entry as `app.run(id, {})`, so each docking command it lists must+ // work without params.+ let docking = |id: &str| {+ id.starts_with("window.panel")+ || id.starts_with("window.workspace")+ || id.starts_with("ui.dock")+ || matches!(id, "window.floatPanel" | "window.dockPanel" | "window.collapseToIcons" | "window.resetWorkspace")+ };+ let failing: Vec<(&str, String)> = searched+ .iter()+ .filter(|c| docking(c.0))+ .filter_map(|c| {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run(c.0, json!({})).err().map(|e| (c.0, e))+ })+ .collect();+ assert!(failing.is_empty(), "searched docking commands that fail with {{}}: {failing:?}");+ let mut labels: Vec<&str> = searched.iter().map(|c| c.1).collect();+ labels.sort_unstable();+ let before = labels.len();+ labels.dedup();+ assert_eq!(labels.len(), before, "a label twice: {searched:?}");+ }++ /// Keys a floating panel's own OS window left over run the main window's tool shortcuts,+ /// Escape and the active tool's keys.+ #[test]+ fn forwarded_keys_run_shortcuts() {+ use egui::{Event, Key, Modifiers};+ fn press(key: Key) -> Vec<Event> {+ [true, false].map(|pressed| Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE }).to_vec()+ }+ let ctx = egui::Context::default();+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let frame = app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap();+ app.session.execute("selection.set", &json!({"ids": [frame["id"]]})).unwrap();+ forwarded_shortcuts(&mut app, &ctx, press(Key::P), Modifiers::NONE);+ assert_ne!(app.session.tool_id(), "selection", "P picks a tool");+ forwarded_shortcuts(&mut app, &ctx, press(Key::Escape), Modifiers::NONE);+ assert_eq!(app.session.tool_id(), "selection", "Escape goes back to the Selection tool");+ app.session.execute("selection.set", &json!({"ids": [frame["id"]]})).unwrap();+ forwarded_shortcuts(&mut app, &ctx, press(Key::Delete), Modifiers::NONE);+ assert!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(frame["id"].as_u64().unwrap())).is_none(), "Delete clears the selection");+ }diff --cc crates/ui-egui/src/menus/ui_commands.rsindex 000000000,649469f30..e03441668mode 000000,100644..100644--- a/crates/ui-egui/src/menus/ui_commands.rs+++ b/crates/ui-egui/src/menus/ui_commands.rs@@@ -1,0 -1,395 +1,395 @@@+ use super::DesignApp;++ /// Menu and Quick Apply entries that only CJK typesetting uses: hidden unless+ /// [`crate::cjk_features`]. The commands still run from scripts, the control channel and MCP.+ pub const CJK_ONLY: &[&str] = &["type.tateChuYoko", "app.rubyDialog", "type.kenten", "type.warichu"];++ /// Whether command `id` has a menu item or Quick Apply entry in the current interface (CJK-only+ /// ones need [`crate::cjk_features`]).+ pub fn shown(app: &DesignApp, id: &str) -> bool {+ !CJK_ONLY.contains(&id) || crate::cjk_features(app)+ }++ /// UI commands: (id, label, shortcut, params).+ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[+ ("app.newDocumentDialog", "New Document…", Some("Cmd+N"), "{}"),+ ("app.openDialog", "Open…", Some("Cmd+O"), "{path?} — without a path, choose the file in a dialog"),+ ("app.openRecent", "Open Recent File", None, "{index} — file.openRecent, with an alert when the file can't be opened"),+ ("app.placeDialog", "Place…", Some("Cmd+D"), "{path?} — without a path, choose the file in a dialog"),+ ("app.saveDialog", "Save As…", Some("Cmd+Shift+S"), "{path?} — without a path, choose where in a dialog"),+ ("app.save", "Save", Some("Cmd+S"), "{}"),+ ("app.quit", "Quit DesignCraft", Some("Cmd+Q"), "{} — close the window; each document with unsaved changes asks first"),+ ("app.saveCopyDialog", "Save a Copy…", Some("Cmd+Alt+S"), "{path?} — choose where to write a copy (the document stays as it is)"),+ ("app.loadSwatches", "Load Swatches…", None, "{path?} — pick a swatch exchange (.ase) file"),+ (+ "app.loadParagraphStyles",+ "Load Paragraph Styles…",+ None,+ "{} — pick a document (.designcraft or .idml) and choose which of its paragraph styles to load (style.load)",+ ),+ ("app.loadCharacterStyles", "Load Character Styles…", None, "{} — the same for its character styles"),+ ("app.loadTextStyles", "Load All Text Styles…", None, "{} — the same for its paragraph and character styles"),+ (+ "effects.dialog",+ "Effects…",+ None,+ "{page?: transparency|dropShadow|innerShadow|outerGlow|innerGlow|bevel|satin|feather|directionalFeather|gradientFeather} — the Effects dialog for the selected objects",+ ),+ ("app.packageDialog", "Package…", Some("Cmd+Alt+Shift+P"), "{dir?} — choose the package folder to create (file.package)"),+ ("app.saveSwatches", "Save Swatches for Exchange…", None, "{path?} — write the colour swatches as .ase"),+ ("app.exportPng", "Export Page as PNG…", Some("Cmd+E"), "{}"),+ ("app.exportIdml", "Export IDML…", None, "{path?} — InDesign Markup (IDML) package"),+ (+ "app.exportEpub",+ "Export EPUB…",+ None,+ "{path?} — reflowable EPUB 3 (with the first page as its cover); without a path, EPUB Export Options (Split Document) and then the save dialog",+ ),+ (+ "app.exportInteractivePdf",+ "Export PDF (Interactive)…",+ None,+ "{path?, fullScreen?, advanceSeconds?} — single pages fitted, bookmarks panel open, buttons, forms, transitions",+ ),+ ("app.exportFixedEpub", "Export EPUB (Fixed Layout)…", None, "{path?} — pre-paginated EPUB 3"),+ ("app.exportHtml", "Export HTML…", None, "{path?} — one self-contained web page"),+ ("app.exportPptx", "Export PowerPoint…", None, "{path?} — every page as a slide of editable shapes, pictures and text"),+ ("app.exportXml", "Export XML…", None, "{path?} — the tagged content"),+ ("app.printBooklet", "Print Booklet…", None, "{path?} — saddle-stitched printer spreads as PDF"),+ ("app.qrCode", "Generate QR Code…", None, "{} — the QR Code dialog (object.qrCode does the work)"),+ ("app.userDictionary", "User Dictionary…", None, "{} — hyphenation exceptions (hyphenation.* commands)"),+ ("app.fittingOptions", "Frame Fitting Options…", None, "{} — the dialog for object.fittingOptions"),+ ("app.menus", "Menus…", None, "{} — show or hide menu items"),+ ("window.hideMenuItem", "Hide Menu Item", None, "{item: \"Menu/Label\", hidden?: bool}"),+ ("edit.dynamicSpelling", "Dynamic Spelling", None, "{on?: bool} — underline misspelled words on the canvas"),+ (+ "app.language",+ "Interface Language",+ None,+ "{lang?: \"\"|de|fr|es|ja|zh|ar|pt-br|it|uk|ru|cs|pl|ka} — menus and panel names (the macOS menu bar follows at once); without lang, opens Preferences, where it is the first setting",+ ),+ (+ "app.flattener",+ "Transparency Flattener Presets",+ None,+ "{preset: \"\"|high|medium|low} — PDF export rasterises spreads with transparency at 300 / 150 / 72 ppi",+ ),+ ("app.graphicCell", "Convert Cell to Graphic Cell…", None, "{path?} — pick an image for the target table cell"),+ ("app.placeAndLink", "Place and Link", None, "{} — a linked copy of the selected frame's story, beside it"),+ ("app.placeWithOptions", "Place with Import Options…", Some("Cmd+Shift+D"), "{path?} — Word/RTF style mapping before placing"),+ ("app.exportText", "Export Text…", None, "{path?} — the story being edited, as Text Only (.txt) or Rich Text Format (.rtf)"),+ ("app.exportPdf", "Export PDF…", None, "{path?, …file.exportPdf options} — asks for a path when none is given"),+ ("app.palette", "Quick Apply…", Some("Cmd+Return"), "{} — search styles and commands"),+ ("app.preferences", "Preferences…", Some("Cmd+K"), "{}"),+ ("window.uiScale", "UI Scaling", None, "{scale: 0.5–3 (1 = 100%)} — the size of the whole interface"),+ (+ "app.keyboardShortcuts",+ "Keyboard Shortcuts…",+ None,+ "{command?, params?} — view and change the shortcut of any command, and the shortcut sets; with command, the dialog opens on it",+ ),+ (+ "window.shortcutSets",+ "Shortcut Sets",+ None,+ "{select?: name} — the shortcut sets (Default is built in; Edit › Keyboard Shortcuts makes the others); select makes one active → {active, sets, builtIn}",+ ),+ ("window.richBlack", "Appearance of Black", None, "{on: bool} — show 100% black as rich black on screen (off: accurately)"),+ (+ "window.setShortcut",+ "Set Shortcut",+ None,+ "{id, params?, shortcut: \"Cmd+Alt+J\" | \"\" (none) | null (default), steal?} — id is a command; a panel is id \"window.panel\" with params {panel: \"layers\"}, a tool is id \"tool.select\" with params {tool: \"pen\"} (or its tool id, \"pen\"); steal: true takes the keys from the commands holding them → {shortcut, conflicts: [command keys: ids, or `window.panel {\"panel\":\"layers\"}`]}",+ ),+ ("window.resetShortcuts", "Reset Shortcuts", None, "{} — every command of the active shortcut set back to its default shortcut"),+ (+ "window.importShortcuts",+ "Import InDesign Shortcut Set",+ None,+ "{path | text} — a set saved by InDesign's Show Set (.txt), imported as a new shortcut set, which becomes active: matched commands, panels (Window menu items) and tools (Tools items) take its Default shortcuts (an item without Default keys takes its Text keys), or none when every item matched to them has none; other commands lose keys it takes unless they share them as defaults → {set, imported, changed [{id, label, item, line, from, to}], conflictsCleared [{id, label, shortcut}], skipped [{id, item, line, shortcut, takenBy, reason}] (an earlier item whose keys a later one took, or a reserved key), failed [{id, label, change, shortcuts}], unmatched [{item, line, keys, reason: noMatch | ambiguous | tool | context}], unmatchedWithoutShortcut, unreadable [{item, line, keys, reason}], approximated [{item, line, keys, note}] (numeric keypad keys bound as the main keys), suggestions [{item, line, candidates}] (never applied), matchedWithoutChange [{id, label, item, line, reason}] (a keyless panel-menu item that clears nothing), truncated, shortcutSet (the new set's name)}; ids are command keys (`window.panel {\"panel\":\"layers\"}`)",+ ),+ ("app.findChange", "Find/Change…", Some("Cmd+F"), "{}"),- ("app.insertTableDialog", "Create Table…", None, "{} — Insert Table dialog (body/header/footer rows, columns)"),++ ("app.insertTableDialog", "Insert Table…", Some("Cmd+Alt+Shift+T"), "{} — Insert Table dialog (body/header/footer rows, columns, table style)"),+ (+ "app.cellOptionsDialog",+ "Strokes and Fills…",+ None,+ "{} — Cell Options › Strokes and Fills of the target cells: edge proxy, stroke weight, type, colour, tint, gap colour, gap tint, and cell fill (table.setCell)",+ ),+ ("app.footnoteOptionsDialog", "Document Footnote Options…", None, "{} — numbering, formatting and layout of footnotes"),+ ("app.rubyDialog", "Ruby…", None, "{} — the reading set over the selected text"),+ (+ "app.paragraphRulesDialog",+ "Paragraph Rules…",+ None,+ "{rule?: ruleAbove|ruleBelow} — Rule Above / Rule Below of the selected paragraphs (type.para)",+ ),+ (+ "app.paragraphBordersDialog",+ "Paragraph Borders and Shading…",+ None,+ "{tab?: border|shading} — border and shading of the selected paragraphs (type.para)",+ ),+ ("app.spanColumnsDialog", "Span Columns…", None, "{} — span or split columns of the selected paragraphs (type.para)"),+ ("app.keepOptionsDialog", "Keep Options…", None, "{} — Keep with Next and Keep Lines Together of the selected paragraphs (type.para)"),+ (+ "app.nestedStylesDialog",+ "Drop Caps and Nested Styles…",+ None,+ "{} — drop cap, nested styles and nested line styles of the selected paragraphs (type.para)",+ ),+ ("app.grepStylesDialog", "GREP Styles…", None, "{} — GREP styles of the selected paragraphs (type.para)"),+ ("app.bulletsNumberingDialog", "Bullets and Numbering…", None, "{} — bullets or numbers of the selected paragraphs (type.para)"),+ (+ "app.hyphenationDialog",+ "Hyphenation…",+ None,+ "{} — Hyphenation Settings of the selected paragraphs (type.para): limits, zone, Better Spacing ↔ Fewer Hyphens, Preview",+ ),+ (+ "app.justificationDialog",+ "Justification…",+ Some("Cmd+Alt+Shift+J"),+ "{} — word and letter spacing, glyph scaling and composer of the selected paragraphs (type.para)",+ ),+ ("app.findFontDialog", "Find/Replace Font…", None, "{} — fonts used (missing ones flagged) and replacing them"),+ ("app.insertXrefDialog", "Insert Cross-Reference…", None, "{} — New Cross-Reference dialog (paragraph or text anchor, format)"),+ ("app.deleteAllGuides", "Delete All Guides on Spread", None, "{} — the spread in view"),+ ("app.deletePage", "Delete Page", None, "{} — deletes the page in view"),+ ("app.duplicateSpread", "Duplicate Spread", None, "{} — duplicates the spread in view (pages and items)"),+ ("app.tablePanel", "Table Panel", Some("Shift+F9"), "{}"),+ ("app.tabsPanel", "Tabs", Some("Cmd+Shift+T"), "{} — show or hide the Tabs panel (it opens above the selected text frame)"),+ ("app.characterPanel", "Character", Some("Cmd+T"), "{} — the Character panel"),+ ("app.paragraphPanel", "Paragraph", Some("Cmd+Alt+T"), "{} — the Paragraph panel"),+ ("app.glyphsPanel", "Glyphs", Some("Alt+Shift+F11"), "{} — the Glyphs panel"),+ ("app.characterStylesPanel", "Character Styles", Some("Cmd+Shift+F11"), "{} — the Character Styles panel"),+ ("app.paragraphStylesPanel", "Paragraph Styles", Some("Cmd+F11"), "{} — the Paragraph Styles panel"),+ ("app.insertCurrentPageNumber", "Current Page Number", Some("Cmd+Alt+Shift+N"), "{} — the Current Page Number marker at the insertion point"),+ ("app.storyEditor", "Edit in Story Editor", Some("Cmd+Y"), "{story?}"),+ ("view.zoomIn", "Zoom In", Some("Cmd+="), "{}"),+ ("view.zoomOut", "Zoom Out", Some("Cmd+-"), "{}"),+ ("view.fitPage", "Fit Page in Window", Some("Cmd+0"), "{}"),+ ("view.fitSelection", "Fit Selection in Window", Some("Cmd+Alt+="), "{}"),+ ("view.fitSpread", "Fit Spread in Window", Some("Cmd+Alt+0"), "{}"),+ ("view.actualSize", "Actual Size", Some("Cmd+1"), "{}"),+ ("view.entirePasteboard", "Entire Pasteboard", Some("Cmd+Alt+Shift+0"), "{}"),+ ("view.zoom", "Zoom To", None, "{zoom: 1.0 = 100%}"),+ ("view.screenMode", "Screen Mode", None, "{mode: normal|preview|bleed|slug|presentation}"),+ ("view.togglePreview", "Toggle Normal/Preview", Some("W"), "{}"),+ (+ "view.togglePresentation",+ "Toggle Presentation",+ Some("Shift+W"),+ "{} — enters Presentation, or returns to the mode it was entered from; Esc also leaves it",+ ),+ (+ "app.formattingAffectsText",+ "Formatting Affects Text",+ Some("J"),+ "{on?: bool} — with text frames selected, colours go to their text (on) or the frames (off); toggles without `on`",+ ),+ (+ "color.defaultFillStroke",+ "Default Fill and Stroke",+ Some("D"),+ "{} — the selection gets no fill and a black stroke (object.defaultFillStroke); text colour edits (Formatting Affects Text) get a black fill and no stroke",+ ),+ (+ "color.swapFillStroke",+ "Swap Fill and Stroke",+ Some("Shift+X"),+ "{} — each selected object's fill and stroke colours (and tints) trade places (object.swapFillStroke), or the text's with Formatting Affects Text",+ ),+ ("color.toggleFillStroke", "Toggle Fill and Stroke", Some("X"), "{} → {strokeFront} — which of fill and stroke the proxy has in front"),+ (+ "color.applyNone",+ "Apply None",+ Some("/"),+ "{} — [None] for the fill or stroke in front of the proxy, of the objects or the text (Formatting Affects Text)",+ ),+ ("color.applyColor", "Apply Color", Some(","), "{} — the colour applied last ([Black] at first) to the fill or stroke in front of the proxy"),+ (+ "color.applyGradient",+ "Apply Gradient",+ Some("."),+ "{} — the gradient applied last (else the document's first, else white to black) to the fill or stroke in front of the proxy",+ ),+ ("view.frameEdges", "Show/Hide Frame Edges", Some("Cmd+H"), "{}"),+ ("view.rulers", "Show/Hide Rulers", Some("Cmd+R"), "{}"),+ ("view.guides", "Show/Hide Guides", Some("Cmd+;"), "{}"),+ ("view.lockGuides", "Lock Guides", Some("Cmd+Alt+;"), "{on?: bool} — ruler guides can't be dragged; toggles without `on`"),+ ("view.snapToGuides", "Snap to Guides", Some("Cmd+Shift+;"), "{}"),+ ("view.snapToDocumentGrid", "Snap to Document Grid", None, "{}"),+ ("view.smartGuides", "Smart Guides", None, "{}"),+ (+ "view.snapPreferences",+ "Smart Guide Options",+ None,+ "{alignEdges?, alignCenters?, smartDimensions?, smartSpacing?: bool, zone?: px} — what smart guides snap to and how close; returns the current values",+ ),+ ("view.baselineGrid", "Show/Hide Baseline Grid", Some("Cmd+Alt+'"), "{}"),+ ("view.documentGrid", "Show/Hide Document Grid", Some("Cmd+'"), "{}"),+ ("view.textThreads", "Show/Hide Text Threads", Some("Cmd+Alt+Y"), "{}"),+ ("view.hiddenCharacters", "Show Hidden Characters", Some("Cmd+Alt+I"), "{}"),+ ("view.taggedFrames", "Show/Hide Tagged Frames", None, "{} — XML-tagged frames outlined in their tag colour"),+ (+ "view.storyEditorDepthRuler",+ "Show/Hide Depth Ruler",+ None,+ "{} — the Story Editor's vertical ruler of how deep the text reaches in its frames",+ ),+ ("window.hidePanels", "Show/Hide Panels", Some("Tab"), "{} — every panel, the Tools panel included"),+ ("window.hidePanelsExceptTools", "Show/Hide Panels Except Tools", Some("Shift+Tab"), "{}"),+ ("window.nextDocument", "Next Document", Some("Cmd+F6"), "{}"),+ ("window.previousDocument", "Previous Document", Some("Cmd+Shift+F6"), "{}"),+ ("app.layerOptions", "Object Layer Options…", None, "{} — show or hide the layers of the selected placed PDF"),+ (+ "app.layerOptionsDialog",+ "Layer Options…",+ None,+ "{id?} (default: the active layer) — name, colour, show, lock, print, guides, text wrap (layer.set)",+ ),+ ("app.swatchOptionsDialog", "Swatch Options…", None, "{name} — name, colour type, mode and values, tint (swatch.options)"),+ ("app.colorGroupOptionsDialog", "Color Group Options…", None, "{name} — rename a colour group (swatch.renameColorGroup)"),+ ("view.tagMarkers", "Show Tag Markers", None, "{on?: bool} — brackets around inline-tagged text"),+ ("view.flattenerPreview", "Flattener Preview", None, "{on?: bool} — highlight objects that involve transparency"),+ ("view.rotateSpread", "Rotate Spread", None, "{angle: 90 (clockwise) | -90 | 180 | 0 (clear)} — turn the view in quarter turns"),+ ("view.proofColors", "Proof Colors", None, "{on?: bool} — simulate the proof target on screen"),+ (+ "view.proofSetup",+ "Proof Setup",+ None,+ "{target?: workingCmyk|srgb|legacyMacRgb|monitorRgb|protanopia|deuteranopia|cmyk:<profile>, intent?, simulatePaper?: bool|\"toggle\"}",+ ),+ ("app.colorSettings", "Color Settings…", None, "{} — the working spaces, intent and black-point compensation"),+ (+ "view.separations",+ "Separations Preview",+ None,+ "{on?: bool, plate?: all|cyan|magenta|yellow|black|spot ink name|null (null: all inks, and off unless an ink limit stays), inkLimit?: percent|null} — the plates of the PDF Export PDF writes → {on, plate, inkLimit, spread, inks: [{name, spot}], dpi, warning?, error?}",+ ),+ ("view.overprintPreview", "Overprint Preview", Some("Cmd+Alt+Shift+Y"), "{} — show how overprinting inks mix"),+ ("view.fastDisplay", "Fast Display", Some("Cmd+Alt+Shift+Z"), "{} — placed graphics as grey boxes, no effects"),+ ("view.typicalDisplay", "Typical Display", Some("Cmd+Alt+Z"), "{} — low-resolution image proxies"),+ ("view.highQualityDisplay", "High Quality Display", Some("Cmd+Alt+H"), "{} — full-resolution images"),+ ("view.firstPage", "First Page", Some("Cmd+Shift+PageUp"), "{} — scroll to the document's first page (zoom kept)"),+ ("view.previousPage", "Previous Page", Some("Shift+PageUp"), "{} — scroll to the page before the one in view"),+ ("view.nextPage", "Next Page", Some("Shift+PageDown"), "{} — scroll to the page after the one in view"),+ ("view.lastPage", "Last Page", Some("Cmd+Shift+PageDown"), "{} — scroll to the document's last page"),+ ("view.nextSpread", "Next Spread", Some("Alt+PageDown"), "{} — centre the spread after the one in view"),+ ("view.previousSpread", "Previous Spread", Some("Alt+PageUp"), "{} — centre the spread before the one in view"),+ ("view.goToPage", "Go to Page…", Some("Cmd+J"), "{page: number (position) | \"name\" (section page name, or \"+n\" for a position)}"),+ ("view.goBack", "Go Back", Some("Cmd+PageUp"), "{} — show the page viewed before this one in the window"),+ ("view.goForward", "Go Forward", Some("Cmd+PageDown"), "{} — show the page viewed after this one (after Go Back)"),+ (+ "window.panel",+ "Show Panel",+ None,+ "{panel: properties|pages|layers|swatches|paragraphStyles|characterStyles|stroke|character|paragraph|textWrap|links|table|preflight}",+ ),+ ("window.floatPanel", "Float Panel", None, "{panel, x?, y?, width?, height?} — the panel in its own floating window (window.panel.float)"),+ (+ "window.panel.layout",+ "Change Panel Layout",+ None,+ "{action} — serialized docking action, including floating geometry, divider sizes and accordion state",+ ),+ (+ "window.panel.move",+ "Move Panel",+ None,+ "{panel, anchor, zone?: tab|center|left|right|top|bottom|above|below, before?: panel|null, group?, placement?} — group, split or reorder a panel (group: its whole tab group)",+ ),+ (+ "window.panel.float",+ "Float Panel",+ None,+ "{panel, x?, y?, width?, height?, group?, column?} — detach a panel (or its group, or its dock column) into a floating window",+ ),+ (+ "window.panel.dock",+ "Dock Panel",+ None,+ "{panel, anchor?, zone?, before?, group?, column?, side?: Start|End} — dock a floating panel: beside anchor, in a new column at side, or back where it floated from",+ ),+ ("window.panel.activate", "Activate Panel", None, "{panel} — show and select a panel in its current group"),+ ("window.panel.close", "Close Panel", None, "{panel} — hide a panel"),+ ("window.panel.closeGroup", "Close Tab Group", None, "{panel} — hide the panel and the panels tabbed with it"),+ ("window.panel.closeOthers", "Close Other Panels in Group", None, "{panel} — hide the panels tabbed with it"),+ ("window.panel.minimize", "Minimize", None, "{panel, minimized?} — minimize the panel's group to its tab strip (toggles without minimized)"),+ ("window.panel.iconic", "Collapse to Icons", None, "{panel, iconic?} — collapse the panel's dock column to icons (toggles without iconic)"),+ (+ "window.panel.window",+ "Move Panel to New Window",+ None,+ "{panel, native?} — not available: a floating panel has its own window on the desktop and stays in the page on the web",+ ),+ ("window.workspace.new", "New Workspace", None, "{name} — save the current workspace (window.newWorkspace)"),+ ("window.workspace.delete", "Delete Workspace", None, "{name} — delete a saved workspace (window.deleteWorkspace)"),+ ("window.workspace.reset", "Reset Workspace", None, "{} — back to the current workspace as saved (window.resetWorkspace)"),+ ("window.workspace.lock", "Lock Workspace", None, "{locked?} — not available in DesignCraft"),+ (+ "ui.dock",+ "Change Panel Layout",+ None,+ "{action} | {operation: open|close|activate|float|moveFloating|move|setStackOpen|resizeStack|resizeSplit, …} — craft-ui's shared ui.dock shape",+ ),+ ("ui.dock.reset", "Reset Workspace", None, "{} — window.workspace.reset"),+ ("window.collapseToIcons", "Collapse to Icons", None, "{} — the panel dock shrinks to its column of icons"),+ ("window.dockPanel", "Dock Panel", None, "{panel} — back to its place in the dock (window.panel.dock)"),+ ("window.controlBar", "Control", Some("Cmd+Alt+6"), "{}"),+ // Object › Fitting with InDesign's shortcuts (one `object.fit` mode each).+ ("fit.fillFrameProportionally", "Fill Frame Proportionally", Some("Cmd+Alt+Shift+C"), "{} — object.fit {mode: fillProportionally}"),+ ("fit.contentProportionally", "Fit Content Proportionally", Some("Cmd+Alt+Shift+E"), "{} — object.fit {mode: fitProportionally}"),+ ("fit.frameToContent", "Fit Frame to Content", Some("Cmd+Alt+C"), "{} — object.fit {mode: fitFrameToContent}"),+ ("fit.contentToFrame", "Fit Content to Frame", Some("Cmd+Alt+E"), "{} — object.fit {mode: fitContentToFrame}"),+ ("fit.centerContent", "Center Content", Some("Cmd+Shift+E"), "{} — object.fit {mode: centerContent}"),+ ("window.split", "Split Window", None, "{on?: bool} — two views of the document side by side, each with its own zoom and scroll"),+ ("window.newWindow", "New Window", None, "{on?: bool} — another view of the active document in its own window"),+ ("window.minimize", "Minimize Window", None, "{} — minimize the desktop window"),+ ("window.maximize", "Maximize/Restore Window", None, "{on?: bool} — toggle maximization when omitted"),+ ("window.close", "Close Window", None, "{} — request that the desktop window close"),+ ("window.drag", "Move Window", None, "{} — begin a native window drag while the primary mouse button is held"),+ ("window.resize", "Resize Window", None, "{edge: north|south|east|west|northEast|southEast|northWest|southWest} — begin a native edge drag"),+ ("window.taskBar", "Contextual Task Bar", None, "{}"),+ (+ "window.taskBarPin",+ "Pin Bar Position",+ None,+ "{on?: bool, at?: [x, y] (points from the canvas's top-left)} — the Contextual Task Bar stays where it is (or at `at`) instead of following the selection; with neither, toggles",+ ),+ ("window.taskBarReset", "Reset Bar Position", None, "{} — the Contextual Task Bar follows the selection again, under it"),+ ("help.discord", "Join the ArtCraft Discord…", None, "{} — opens https://discord.gg/artcraft in the browser"),+ ("help.appPage", "DesignCraft Website…", None, "{} — opens https://getartcraft.com/apps/designcraft"),+ ("help.github", "DesignCraft on GitHub…", None, "{} — opens https://github.com/storytold/designcraft"),+ ("help.issues", "Report an Issue…", None, "{} — opens the GitHub issue tracker"),+ ("help.website", "ArtCraft Website…", None, "{} — opens https://getartcraft.com"),+ ("help.app", "ArtCraft App Page…", None, "{app} — opens https://getartcraft.com/apps/{app} (e.g. photocraft)"),+ (+ "help.about",+ "About DesignCraft",+ None,+ "{open?: true, tab?: \"about\"|\"contributors\"|\"models\"} — the About window: splash with community links, contributor and model credits (open: false closes it)",+ ),+ ("help.checkForUpdates", "Check for Updates…", None, "{} — checks for newer releases and offers to update"),+ ("window.toolsDoubleColumn", "Tools: Double Column", None, "{}"),+ (+ "window.workspace",+ "Workspace",+ None,+ "{name: Advanced|Book|Digital Publishing|Essentials|Essentials Classic|Interactive for PDF|Printing and Proofing|Typography or a saved workspace}",+ ),+ (+ "window.newWorkspace",+ "New Workspace…",+ None,+ "{name, panelLocations?: bool (default true: the bars and panels), menuCustomization?: bool (default true: the menu items hidden with Edit › Menus)} — saves the workspace",+ ),+ ("window.deleteWorkspace", "Delete Workspace…", None, "{name}"),+ ("window.resetWorkspace", "Reset Workspace", None, "{} — back to the current workspace as saved (or its defaults)"),+ ("window.brightness", "Interface Color Theme", None, "{brightness: dark|mediumDark|mediumLight|light|highContrast}"),+ ];++ pub fn ui_label(id: &str) -> Option<(&'static str, Option<&'static str>)> {+ UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| (c.1, c.2))+ }