DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Guides: select ruler guides and set their position (#1282) (#1445)
aiongg3be2736d0a05
diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rsindex 2d28bf2c2..11c4e2ab1 100644--- a/crates/doc/src/selection.rs+++ b/crates/doc/src/selection.rs@@ -2,9 +2,19 @@use serde::{Deserialize, Serialize};+use crate::edit::SpreadRef;use crate::ids::{ItemId, StoryId};use crate::table::CellRange;+/// A selected ruler guide: index `index` in the guides of page `page` of spread `spread`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct GuideSel {+ pub spread: SpreadRef,+ pub page: usize,+ pub index: usize,+}+/// A table cell: the table (in the selection's story) and the owning cell's grid position.#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -83,6 +93,10 @@ pub struct Selection {/// The page selected with the Page tool (absolute index).#[serde(default, skip_serializing_if = "Option::is_none")]pub page: Option<usize>,+ /// Selected ruler guides. Never together with items, text or cells: selecting one clears+ /// the other.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub guides: Vec<GuideSel>,}impl Selection {diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rsindex 9ee963317..e5a2d2296 100644--- a/crates/engine/src/cmd/edit.rs+++ b/crates/engine/src/cmd/edit.rs@@ -256,28 +256,39 @@ pub fn specs() -> Vec<CommandSpec> {st.bump_revision();ok()}),- cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{ids?} — delete selected items (or the selected text)", has_doc, |s, p| {- if s.doc()?.selection.text.is_some() && p.get("ids").is_none() {- return super::text::delete_selection(s);- }- let ids = super::targets(s, p)?;- // With a placed graphic itself selected (Direct Selection), only the graphic goes: its- // frame stays, empty and selected (as in InDesign). Other items are deleted.- let content = s.doc()?.selection.content && p.get("ids").is_none();- s.edit(|d, sel| {- let mut kept = Vec::new();- for id in &ids {- if let Some(it) = d.item_mut(*id).filter(|it| content && matches!(it.content, designcraft_doc::Content::Graphic(_))) {- it.content = designcraft_doc::Content::Unassigned;- kept.push(*id);- } else {- let _ = d.remove_item(*id);- }+ cmd!(+ "edit.clear",+ "Clear",+ ["Edit"],+ Some("Delete"),+ "{ids?} — delete selected items (or the selected text or ruler guides)",+ has_doc,+ |s, p| {+ if s.doc()?.selection.text.is_some() && p.get("ids").is_none() {+ return super::text::delete_selection(s);}- *sel = Selection::items(kept);- Ok(json!({"deleted": ids.len()}))- })- }),+ if p.get("ids").is_none() && s.doc()?.selection.items.is_empty() && !s.doc()?.selection.guides.is_empty() {+ return s.execute("guide.delete", &json!({}));+ }+ let ids = super::targets(s, p)?;+ // With a placed graphic itself selected (Direct Selection), only the graphic goes: its+ // frame stays, empty and selected (as in InDesign). Other items are deleted.+ let content = s.doc()?.selection.content && p.get("ids").is_none();+ s.edit(|d, sel| {+ let mut kept = Vec::new();+ for id in &ids {+ if let Some(it) = d.item_mut(*id).filter(|it| content && matches!(it.content, designcraft_doc::Content::Graphic(_))) {+ it.content = designcraft_doc::Content::Unassigned;+ kept.push(*id);+ } else {+ let _ = d.remove_item(*id);+ }+ }+ *sel = Selection::items(kept);+ Ok(json!({"deleted": ids.len()}))+ })+ }+ ),cmd!(noundo "edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{} → {text} when text is selected (with formatting, footnotes, markers)", has_selection_or_text, |s, _| {if let Some(text) = copy_text(s)? {return Ok(json!({"text": text}));diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rsindex e8be163ef..97bf4e9cc 100644--- a/crates/engine/src/cmd/guides.rs+++ b/crates/engine/src/cmd/guides.rs@@ -1,18 +1,28 @@-//! Ruler guides: add (dragged from the rulers), move, delete, list; Layout › Create Guides.+//! Ruler guides: add (dragged from the rulers), select, move, delete, list; Layout › Create+//! Guides.//!//! Guides are stored on their page in spread coordinates; a spread guide (dropped on the//! pasteboard) lives on the spread's first page with `spread: true` and crosses the pasteboard.+//! Selected guides are [`Selection::guides`], addressed as (spread, page, index): the commands+//! that delete guides renumber it, and [`keep_selection_valid`] drops what another command made+//! stale.-use designcraft_doc::{Document, Guide, Orientation, SpreadRef};+use std::collections::{HashMap, HashSet};++use designcraft_doc::{Document, Guide, GuideSel, Orientation, Selection, SpreadRef};use designcraft_geom::Rect;use serde_json::{Value, json};-use super::{CommandSpec, bad, cmd, has_doc, str_param};-use crate::{Result, Session};+use super::{CommandSpec, bad, bool_or, cmd, has_doc, str_param};+use crate::{DocState, Result, Session};const MAX_GUIDE_DIVISIONS: u64 = 1000;const MAX_GUIDES_CREATED: usize = 10_000;const MAX_GUIDE_GUTTER: f64 = 1_000_000.0;+/// The farthest a guide may be from the spread origin, in points, either way.+const MAX_GUIDE_POSITION: f64 = 1_000_000.0;+/// The most guides one `guides` list may name.+const MAX_GUIDES_NAMED: usize = 10_000;pub fn specs() -> Vec<CommandSpec> {vec![@@ -21,34 +31,87 @@ pub fn specs() -> Vec<CommandSpec> {"New Guide",[],None,- "{orientation: horizontal|vertical, position (spread coordinate), spread?, page? (index in the spread; default: the page under `at` or the position), at? (the other coordinate), spreadGuide?: bool, liquid?: bool (a liquid guide, as the Page tool draws from the rulers)} or {orientation: both, point: [x, y], spread?, page?, spreadGuide?: bool, liquid?: bool} → {page, index}; `both` adds a horizontal guide through y and a vertical guide through x as one undo step → {guides: [{page, index}, {page, index}]}",+ "{orientation: horizontal|vertical, position (spread coordinate, at most 1000000 pt either way), spread?, page? (index in the spread; default: the page under `at` or the position), at? (the other coordinate), spreadGuide?: bool, liquid?: bool (a liquid guide, as the Page tool draws from the rulers)} or {orientation: both, point: [x, y], spread?, page?, spreadGuide?: bool, liquid?: bool} → {page, index}; `both` adds a horizontal guide through y and a vertical guide through x as one undo step → {guides: [{page, index}, {page, index}]}. The new guides become the selection; objects are deselected",has_doc,add),- cmd!("guide.move", "Move Guide", [], None, "{spread?, page, index, position}", has_doc, move_guide),- cmd!("guide.delete", "Delete Guide", [], None, "{spread?, page, index}", has_doc, delete),+ cmd!("guide.move", "Move Guide", [], None, "{spread?, page, index, position (at most 1000000 pt either way)}", has_doc, move_guide),+ cmd!(+ "guide.moveBy",+ "Move Guides",+ [],+ None,+ "{dx?, dy?, guides?: [{spread?, page, index}] (default: the selected guides)} — vertical guides move by dx, horizontal ones by dy, as one undo step",+ has_doc,+ move_by+ ),+ cmd!(+ "guide.delete",+ "Delete Guide",+ [],+ None,+ "{spread?, page, index}, or {} for the selected guides; an address without page or index is an error",+ has_doc,+ delete+ ),cmd!("guide.deleteAll", "Delete All Guides on Spread", ["View", "Grids & Guides"], None, "{spread?}", has_doc, |s, p| {let r = super::spread_param(p, "guide.deleteAll")?;- s.edit(|d, _| {+ s.edit(|d, sel| {let sp = d.spread_mut(r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?;let mut n = 0;for pg in &mut sp.pages {n += pg.guides.len();pg.guides.clear();}+ sel.guides.retain(|g| g.spread != r);Ok(json!({"deleted": n}))})}),- cmd!(query "guide.list", "Guides", [], None, "{spread?} → [{page, index, orientation, position, spread}]", has_doc, |s, p| {- let d = &s.doc()?.doc;- let sp = d.spread(super::spread_param(p, "guide.list")?).ok_or_else(|| bad("guide.list", "no such spread"))?;- let mut out = Vec::new();- for (pi, pg) in sp.pages.iter().enumerate() {- for (i, g) in pg.guides.iter().enumerate() {- out.push(json!({"page": pi, "index": i, "orientation": g.orientation, "position": g.position, "spread": g.spread}));+ cmd!(+ query "guide.list",+ "Guides",+ [],+ None,+ "{spread?} → [{page, index, orientation, position, spread, selected}]",+ has_doc,+ |s, p| {+ let st = s.doc()?;+ let r = super::spread_param(p, "guide.list")?;+ let sp = st.doc.spread(r).ok_or_else(|| bad("guide.list", "no such spread"))?;+ let picked: HashSet<GuideSel> = st.selection.guides.iter().copied().collect();+ let mut out = Vec::new();+ for (pi, pg) in sp.pages.iter().enumerate() {+ for (i, g) in pg.guides.iter().enumerate() {+ let selected = picked.contains(&GuideSel { spread: r, page: pi, index: i });+ out.push(json!({"page": pi, "index": i, "orientation": g.orientation, "position": g.position, "spread": g.spread, "selected": selected}));+ }}+ Ok(Value::Array(out))}- Ok(Value::Array(out))+ ),+ cmd!(+ noundo "guide.select",+ "Select Guide",+ [],+ None,+ "{spread?, page, index, guides?: [{spread?, page, index}] (several, in place of page and index), add?: bool (keep the guides already selected), toggle?: bool (deselect a selected guide instead: Shift-click)} — selects ruler guides and deselects objects → {selected: n}",+ has_doc,+ select+ ),+ cmd!(+ noundo "guide.selectAll",+ "Select All Guides",+ ["Edit"],+ Some("Cmd+Alt+G"),+ "{spread?} — every guide on the spread that is not locked or on a locked or hidden layer → {selected: n}",+ has_doc,+ select_all+ ),+ cmd!(noundo "guide.deselect", "Deselect Guides", [], None, "{}", has_doc, |s, _| {+ let st = s.doc_mut()?;+ st.selection.guides.clear();+ st.bump_revision();+ super::ok()}),cmd!("layout.createGuides",@@ -80,6 +143,14 @@ fn finite_number(p: &Value, key: &str, command: &str) -> Result<Option<f64>> {Ok(Some(number))}+/// `position` as a guide position: finite and within [`MAX_GUIDE_POSITION`] of the origin.+fn guide_position(position: f64, command: &str) -> Result<f64> {+ if !position.is_finite() || position.abs() > MAX_GUIDE_POSITION {+ return Err(bad(command, format!("a guide position must be between -{MAX_GUIDE_POSITION} and {MAX_GUIDE_POSITION}")));+ }+ Ok(position)+}+fn orientation(p: &Value) -> Result<Orientation> {match str_param(p, "orientation") {Some("horizontal") => Ok(Orientation::Horizontal),@@ -115,6 +186,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {};vec![(o, pos, x)]};+ for (_, pos, _) in &guides {+ guide_position(*pos, "guide.add")?;+ }let d = &s.doc()?.doc;let placed: Vec<(Orientation, f64, usize)> = guides.into_iter()@@ -128,11 +202,13 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {}).collect();let layer = s.doc()?.active_layer;- s.edit(|d, _| {+ s.edit(|d, sel| {let sp = d.spread_mut(r).ok_or_else(|| bad("guide.add", "no such spread"))?;let mut out = Vec::new();+ let mut added = Vec::new();for (o, pos, pi) in placed {let pg = sp.pages.get_mut(pi).ok_or_else(|| bad("guide.add", "no such page"))?;+ let index = pg.guides.len();pg.guides.push(Guide {orientation: o,position: pos,@@ -141,8 +217,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {layer: Some(layer),liquid: liquid && !spread_guide,});- out.push(json!({"page": pi, "index": pg.guides.len() - 1}));+ out.push(json!({"page": pi, "index": index}));+ added.push(GuideSel { spread: r, page: pi, index });}+ // A new guide is selected, as in InDesign; nothing else stays selected.+ *sel = Selection { guides: added, ..Default::default() };match <[Value; 1]>::try_from(out) {Ok([one]) => Ok(one),Err(out) => Ok(json!({"guides": out})),@@ -168,6 +247,7 @@ fn check_editable(d: &Document, r: SpreadRef, pi: usize, i: usize, command: &strfn move_guide(s: &mut Session, p: &Value) -> Result<Value> {let (r, pi, i) = guide_ref(p, "guide.move")?;let pos = finite_number(p, "position", "guide.move")?.ok_or_else(|| bad("guide.move", "missing position"))?;+ let pos = guide_position(pos, "guide.move")?;s.edit(|d, _| {check_editable(d, r, pi, i, "guide.move")?;let g = d@@ -181,18 +261,209 @@ fn move_guide(s: &mut Session, p: &Value) -> Result<Value> {}fn delete(s: &mut Session, p: &Value) -> Result<Value> {- let (r, pi, i) = guide_ref(p, "guide.delete")?;+ // An address names one guide: a partial one (only `spread`, say) is an error, not the selection.+ let targets = if ["spread", "page", "index"].iter().all(|k| p.get(k).is_none()) {+ s.doc()?.selection.guides.clone()+ } else {+ let (spread, page, index) = guide_ref(p, "guide.delete")?;+ vec![GuideSel { spread, page, index }]+ };+ if targets.is_empty() {+ return Err(bad("guide.delete", "no guide selected"));+ }+ s.edit(|d, sel| {+ for g in &targets {+ check_editable(d, g.spread, g.page, g.index, "guide.delete")?;+ }+ let deleted = remove_guides(d, sel, &targets, "guide.delete")?;+ Ok(json!({"deleted": deleted}))+ })+}++/// Removes `targets` (existing guides; repeats count once) and renumbers the guide selection to+/// match. Returns how many guides it removed.+fn remove_guides(d: &mut Document, sel: &mut Selection, targets: &[GuideSel], command: &str) -> Result<usize> {+ let gone: HashSet<GuideSel> = targets.iter().copied().collect();+ // Per page, the removed indices in ascending order.+ let mut by_page: HashMap<(SpreadRef, usize), Vec<usize>> = HashMap::new();+ for g in &gone {+ by_page.entry((g.spread, g.page)).or_default().push(g.index);+ }+ for ((spread, page), indices) in &mut by_page {+ indices.sort_unstable();+ let pg = d.spread_mut(*spread).and_then(|sp| sp.pages.get_mut(*page)).ok_or_else(|| bad(command, "no such page"))?;+ for &i in indices.iter().rev() {+ if i >= pg.guides.len() {+ return Err(bad(command, "no such guide"));+ }+ pg.guides.remove(i);+ }+ }+ sel.guides = sel+ .guides+ .iter()+ .filter(|g| !gone.contains(g))+ .map(|g| {+ let below = by_page.get(&(g.spread, g.page)).map_or(0, |indices| indices.partition_point(|&i| i < g.index));+ GuideSel { index: g.index.saturating_sub(below), ..*g }+ })+ .collect();+ Ok(gone.len())+}++/// The guides a `guides: [{spread?, page, index}]` list names, if the params have one.+fn guides_param(p: &Value, command: &str) -> Result<Option<Vec<GuideSel>>> {+ let Some(list) = p.get("guides") else { return Ok(None) };+ let list = list.as_array().ok_or_else(|| bad(command, "`guides` must be a list of {spread?, page, index}"))?;+ if list.len() > MAX_GUIDES_NAMED {+ return Err(bad(command, format!("`guides` may name at most {MAX_GUIDES_NAMED} guides")));+ }+ list.iter()+ .map(|g| {+ let (spread, page, index) = guide_ref(g, command)?;+ Ok(GuideSel { spread, page, index })+ })+ .collect::<Result<Vec<_>>>()+ .map(Some)+}++/// The guide `g` addresses, if there is one.+fn guide_of(d: &Document, g: GuideSel) -> Option<&Guide> {+ d.spread(g.spread)?.pages.get(g.page)?.guides.get(g.index)+}++/// A guide that can be selected: it exists, and neither it nor its layer is locked or hidden.+pub(crate) fn selectable(d: &Document, g: GuideSel) -> bool {+ guide_of(d, g).is_some_and(|guide| guide.editable_in(d))+}++fn select(s: &mut Session, p: &Value) -> Result<Value> {+ let named = match guides_param(p, "guide.select")? {+ Some(list) => list,+ None => {+ let (spread, page, index) = guide_ref(p, "guide.select")?;+ vec![GuideSel { spread, page, index }]+ }+ };+ let (add, toggle) = (bool_or(p, "add", false), bool_or(p, "toggle", false));+ let st = s.doc_mut()?;+ for g in &named {+ check_editable(&st.doc, g.spread, g.page, g.index, "guide.select")?;+ }+ let mut guides = if add || toggle { st.selection.guides.clone() } else { Vec::new() };+ let mut have: HashSet<GuideSel> = guides.iter().copied().collect();+ let mut seen = HashSet::new();+ let mut dropped = HashSet::new();+ for g in named.into_iter().filter(|g| seen.insert(*g)) {+ if !have.insert(g) {+ if toggle {+ dropped.insert(g);+ }+ } else {+ guides.push(g);+ }+ }+ guides.retain(|g| !dropped.contains(g));+ let n = guides.len();+ st.selection = Selection { guides, ..Default::default() };+ st.bump_revision();+ Ok(json!({"selected": n}))+}++fn select_all(s: &mut Session, p: &Value) -> Result<Value> {+ let r = super::spread_param(p, "guide.selectAll")?;+ let st = s.doc_mut()?;+ let sp = st.doc.spread(r).ok_or_else(|| bad("guide.selectAll", "no such spread"))?;+ let guides: Vec<GuideSel> = sp+ .pages+ .iter()+ .enumerate()+ .flat_map(|(page, pg)| (0..pg.guides.len()).map(move |index| GuideSel { spread: r, page, index }))+ .filter(|g| selectable(&st.doc, *g))+ .collect();+ let n = guides.len();+ st.selection = Selection { guides, ..Default::default() };+ st.bump_revision();+ Ok(json!({"selected": n}))+}++fn move_by(s: &mut Session, p: &Value) -> Result<Value> {+ let dx = finite_number(p, "dx", "guide.moveBy")?.unwrap_or(0.0);+ let dy = finite_number(p, "dy", "guide.moveBy")?.unwrap_or(0.0);+ let mut targets = match guides_param(p, "guide.moveBy")? {+ Some(list) => list,+ None => s.doc()?.selection.guides.clone(),+ };+ let mut seen = HashSet::new();+ targets.retain(|g| seen.insert(*g));+ if targets.is_empty() {+ return Err(bad("guide.moveBy", "no guide selected"));+ }s.edit(|d, _| {- check_editable(d, r, pi, i, "guide.delete")?;- let pg = d.spread_mut(r).and_then(|sp| sp.pages.get_mut(pi)).ok_or_else(|| bad("guide.delete", "no such page"))?;- if i >= pg.guides.len() {- return Err(bad("guide.delete", "no such guide"));+ for g in &targets {+ check_editable(d, g.spread, g.page, g.index, "guide.moveBy")?;}- pg.guides.remove(i);- Ok(Value::Null)+ for g in &targets {+ let guide = d+ .spread_mut(g.spread)+ .and_then(|sp| sp.pages.get_mut(g.page))+ .and_then(|pg| pg.guides.get_mut(g.index))+ .ok_or_else(|| bad("guide.moveBy", "no such guide"))?;+ let to = guide.position+ + match guide.orientation {+ Orientation::Vertical => dx,+ Orientation::Horizontal => dy,+ };+ guide.position = guide_position(to, "guide.moveBy").map_err(|_| bad("guide.moveBy", "the guide would move out of range"))?;+ }+ Ok(json!({"moved": targets.len()}))})}+/// After a command: guides stay selected only while nothing else is (objects, text, cells, a+/// page), and only those that are still there and can be selected. A command that changed+/// which guides a page holds without keeping the guide selection up to date clears it, since+/// its (page, index) addresses may name other guides now. `before` is the document and+/// selection before the command, when it ran on the same document.+pub(crate) fn keep_selection_valid(st: &mut DocState, before: Option<(&Document, &Selection)>, id: &str) {+ let sel = &mut st.selection;+ if sel.guides.is_empty() {+ return;+ }+ if !sel.items.is_empty() || sel.text.is_some() || sel.cells.is_some() || sel.page.is_some() {+ sel.guides.clear();+ return;+ }+ let kept_up = id.starts_with("guide.") || matches!(id, "edit.undo" | "edit.redo") || before.is_some_and(|(_, old)| old.guides != sel.guides);+ if !kept_up+ && let Some((old, _)) = before+ && !std::ptr::eq(old, st.doc.as_ref())+ && !same_guide_addresses(old, &st.doc)+ {+ sel.guides.clear();+ return;+ }+ let mut seen = HashSet::new();+ sel.guides.retain(|g| selectable(&st.doc, *g) && seen.insert(*g));+}++/// Every (spread, page, index) of `old` still names a guide of the same orientation on the same+/// page in `new`: guides were only added at the end of their pages, or moved.+fn same_guide_addresses(old: &Document, new: &Document) -> bool {+ let same = |a: &[std::sync::Arc<designcraft_doc::Spread>], b: &[std::sync::Arc<designcraft_doc::Spread>]| {+ a.len() == b.len()+ && a.iter().zip(b).all(|(a, b)| {+ a.pages.len() == b.pages.len()+ && a.pages.iter().zip(&b.pages).all(|(a, b)| {+ a.id == b.id+ && a.guides.len() <= b.guides.len()+ && a.guides.iter().zip(&b.guides).all(|(a, b)| a.orientation == b.orientation)+ })+ })+ };+ same(&old.spreads, &new.spreads) && same(&old.parents, &new.parents)+}+fn guide_divisions(p: &Value, key: &str) -> Result<u64> {let Some(value) = p.get(key) else { return Ok(0) };let count = value.as_u64().ok_or_else(|| bad("layout.createGuides", format!("`{key}` must be an integer")))?;@@ -273,7 +544,11 @@ fn create_guides(s: &mut Session, p: &Value) -> Result<Value> {.filter(|count| *count <= MAX_GUIDES_CREATED).ok_or_else(|| bad("layout.createGuides", format!("a single command may create at most {MAX_GUIDES_CREATED} guides")))?;let layer = s.doc()?.active_layer;- s.edit(|d, _| {+ s.edit(|d, sel| {+ if remove {+ // The cleared pages' guide addresses name the new guides now.+ sel.guides.retain(|g| g.spread != r || only.is_some_and(|o| o != g.page));+ }let sp = d.spread_mut(r).ok_or_else(|| bad("layout.createGuides", "no such spread"))?;let mut n = 0usize;for (pi, pg) in sp.pages.iter_mut().enumerate() {@@ -390,6 +665,214 @@ mod tests {}}+#[cfg(test)]+mod selection_tests {+ use serde_json::{Value, json};++ use crate::Session;++ /// A page with vertical guides at 100, 200, 300 and a horizontal one at 400.+ fn guides() -> Session {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ for x in [100.0, 200.0, 300.0] {+ s.execute("guide.add", &json!({"orientation": "vertical", "position": x})).unwrap();+ }+ s.execute("guide.add", &json!({"orientation": "horizontal", "position": 400.0})).unwrap();+ s+ }++ fn selected(s: &Session) -> Vec<usize> {+ s.doc().unwrap().selection.guides.iter().map(|g| g.index).collect()+ }++ fn positions(s: &mut Session) -> Vec<f64> {+ let l = s.execute("guide.list", &json!({})).unwrap();+ l.as_array().unwrap().iter().map(|g| g["position"].as_f64().unwrap()).collect()+ }++ #[test]+ fn selecting_guides_clears_objects_and_the_other_way_round() {+ let mut s = guides();+ let id = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].clone();+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();+ s.execute("guide.select", &json!({"page": 0, "index": 1})).unwrap();+ assert!(s.doc().unwrap().selection.items.is_empty());+ assert_eq!(selected(&s), [1]);+ // Shift-click adds, Shift-click again removes.+ s.execute("guide.select", &json!({"page": 0, "index": 3, "toggle": true})).unwrap();+ assert_eq!(selected(&s), [1, 3]);+ s.execute("guide.select", &json!({"page": 0, "index": 1, "toggle": true})).unwrap();+ assert_eq!(selected(&s), [3]);+ let r = s.execute("guide.select", &json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}], "add": true})).unwrap();+ assert_eq!(r["selected"], 3);+ let l = s.execute("guide.list", &json!({})).unwrap();+ assert_eq!(l.as_array().unwrap().iter().map(|g| g["selected"] == true).collect::<Vec<_>>(), [true, false, true, true]);+ // Selecting an object (Shift-click too) deselects the guides.+ s.execute("selection.toggle", &json!({"id": id})).unwrap();+ assert!(selected(&s).is_empty());+ s.execute("guide.select", &json!({"page": 0, "index": 0})).unwrap();+ s.execute("edit.deselectAll", &json!({})).unwrap();+ assert!(selected(&s).is_empty());+ s.execute("guide.selectAll", &json!({})).unwrap();+ s.execute("guide.deselect", &json!({})).unwrap();+ assert!(selected(&s).is_empty());+ // No such guide.+ assert!(s.execute("guide.select", &json!({"page": 0, "index": 9})).is_err());+ assert!(s.execute("guide.select", &json!({"page": 3, "index": 0})).is_err());+ assert!(s.execute("guide.select", &json!({"guides": "all"})).is_err());+ }++ #[test]+ fn select_all_guides_skips_locked_ones() {+ let mut s = guides();+ let layer = s.execute("layer.new", &json!({"name": "Grid"})).unwrap()["id"].as_u64().unwrap();+ s.execute("layer.activate", &json!({"id": layer})).unwrap();+ s.execute("guide.add", &json!({"orientation": "vertical", "position": 500.0})).unwrap();+ s.execute("layer.set", &json!({"id": layer, "locked": true})).unwrap();+ assert_eq!(s.execute("guide.selectAll", &json!({})).unwrap()["selected"], 4);+ assert_eq!(selected(&s), [0, 1, 2, 3]);+ assert!(s.execute("guide.select", &json!({"page": 0, "index": 4})).is_err());+ // Locking the layer of a selected guide deselects it.+ s.execute("layer.set", &json!({"id": layer, "locked": false})).unwrap();+ s.execute("guide.selectAll", &json!({})).unwrap();+ s.execute("layer.set", &json!({"id": layer, "locked": true})).unwrap();+ assert_eq!(selected(&s), [0, 1, 2, 3]);+ let spec = crate::cmd::find_command("guide.selectAll").unwrap();+ assert_eq!((spec.menu, spec.shortcut), (&["Edit"][..], Some("Cmd+Alt+G")));+ }++ #[test]+ fn selected_guides_move_and_delete_as_one_undo_step() {+ let mut s = guides();+ s.execute("guide.select", &json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}, {"page": 0, "index": 3}]})).unwrap();+ // Vertical guides move by dx, horizontal ones by dy.+ s.execute("guide.moveBy", &json!({"dx": 10.0, "dy": -5.0})).unwrap();+ assert_eq!(positions(&mut s), [110.0, 200.0, 310.0, 395.0]);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(positions(&mut s), [100.0, 200.0, 300.0, 400.0]);+ assert_eq!(selected(&s), [0, 2, 3]);+ // Delete (edit.clear, as the Delete key) takes all three; the guide left is the one at 200.+ assert_eq!(s.execute("edit.clear", &json!({})).unwrap()["deleted"], 3);+ assert_eq!(positions(&mut s), [200.0]);+ assert!(selected(&s).is_empty());+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(positions(&mut s), [100.0, 200.0, 300.0, 400.0]);+ assert_eq!(selected(&s), [0, 2, 3]);+ s.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(positions(&mut s), [200.0]);+ assert!(s.execute("guide.moveBy", &json!({"dx": 1.0})).is_err(), "nothing selected");+ // A guide stays within 1000000 pt of the origin.+ assert!(s.execute("guide.moveBy", &json!({"dx": f64::MAX, "guides": [{"page": 0, "index": 0}]})).is_err());+ assert!(s.execute("guide.moveBy", &json!({"dx": 1e6, "guides": [{"page": 0, "index": 0}]})).is_err());+ assert_eq!(positions(&mut s), [200.0]);+ s.execute("guide.moveBy", &json!({"dx": -1e6 - 200.0, "guides": [{"page": 0, "index": 0}]})).unwrap();+ assert_eq!(positions(&mut s), [-1e6]);+ assert!(s.execute("guide.move", &json!({"page": 0, "index": 0, "position": 1e6 + 1.0})).is_err());+ assert!(s.execute("guide.add", &json!({"orientation": "vertical", "position": -2e6})).is_err());+ assert!(s.execute("guide.add", &json!({"orientation": "both", "point": [0.0, 1e300]})).is_err());+ assert_eq!(positions(&mut s), [-1e6]);+ }++ #[test]+ fn the_guide_selection_follows_deletes_and_drops_stale_guides() {+ let mut s = guides();+ s.execute("guide.select", &json!({"guides": [{"page": 0, "index": 2}, {"page": 0, "index": 3}]})).unwrap();+ // Deleting a guide before them renumbers them.+ s.execute("guide.delete", &json!({"page": 0, "index": 0})).unwrap();+ assert_eq!(selected(&s), [1, 2]);+ assert_eq!(positions(&mut s), [200.0, 300.0, 400.0]);+ // Deleting a selected one deselects it.+ s.execute("guide.delete", &json!({"page": 0, "index": 1})).unwrap();+ assert_eq!(selected(&s), [1]);+ // Undo puts back the selection that went with the document.+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(selected(&s), [1, 2]);+ // A new guide is the selection.+ s.execute("guide.add", &json!({"orientation": "vertical", "position": 50.0})).unwrap();+ assert_eq!(selected(&s), [3]);+ // Undoing the add to before the first delete: those addresses held other guides then.+ s.execute("edit.undo", &json!({})).unwrap();+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(selected(&s), [2, 3]);+ // Create Guides replacing the page's guides: their addresses name new guides, so the+ // selection goes.+ s.execute("layout.createGuides", &json!({"columns": 2, "removeExisting": true})).unwrap();+ assert!(selected(&s).is_empty());+ s.execute("edit.undo", &json!({})).unwrap();+ s.execute("guide.select", &json!({"page": 0, "index": 0})).unwrap();+ s.execute("layout.createGuides", &json!({"columns": 2, "columnGutter": 0})).unwrap();+ assert_eq!(selected(&s), [0], "guides only added: the addresses still hold");+ s.execute("edit.undo", &json!({})).unwrap();+ s.execute("guide.selectAll", &json!({})).unwrap();+ s.execute("guide.deleteAll", &json!({})).unwrap();+ assert!(selected(&s).is_empty());+ // Deleting the page goes with it.+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ s.execute("guide.add", &json!({"spread": 1, "orientation": "vertical", "position": 100.0})).unwrap();+ s.execute("guide.selectAll", &json!({"spread": 1})).unwrap();+ assert_eq!(selected(&s), [0]);+ s.execute("layout.pages.delete", &json!({"pages": [1]})).unwrap();+ assert!(selected(&s).is_empty());+ let _: Value = s.execute("guide.list", &json!({})).unwrap();+ }+}++#[cfg(test)]+mod new_guide_tests {+ use designcraft_doc::GuideSel;+ use serde_json::json;++ use crate::Session;++ fn selected(s: &Session) -> Vec<GuideSel> {+ s.doc().unwrap().selection.guides.clone()+ }++ #[test]+ fn a_new_guide_is_the_selection() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].clone();+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();+ s.execute("guide.add", &json!({"orientation": "vertical", "position": 100.0})).unwrap();+ let spread = s.doc().unwrap().selection.guides[0].spread;+ assert_eq!(selected(&s), [GuideSel { spread, page: 0, index: 0 }]);+ assert!(s.doc().unwrap().selection.items.is_empty(), "objects are deselected");+ // Both ways (Cmd-drag from the ruler corner): the two new guides.+ s.execute("guide.add", &json!({"orientation": "both", "point": [50.0, 60.0], "spreadGuide": true})).unwrap();+ assert_eq!(selected(&s), [GuideSel { spread, page: 0, index: 1 }, GuideSel { spread, page: 0, index: 2 }]);+ // Undo gives back the selection from before.+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(selected(&s), [GuideSel { spread, page: 0, index: 0 }]);+ }++ #[test]+ fn delete_takes_a_whole_address_or_the_selection() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ for spread in [0, 1] {+ s.execute("guide.add", &json!({"spread": spread, "orientation": "vertical", "position": 100.0})).unwrap();+ }+ s.execute("guide.select", &json!({"spread": 1, "page": 0, "index": 0})).unwrap();+ // A spread without page and index is not "the selection".+ assert!(s.execute("guide.delete", &json!({"spread": 0})).is_err());+ assert!(s.execute("guide.delete", &json!({"spread": 1, "page": 0})).is_err());+ assert_eq!(selected(&s).len(), 1);+ // A selection naming a guide twice, apart, deletes it once.+ s.execute("guide.add", &json!({"spread": 1, "orientation": "vertical", "position": 200.0})).unwrap();+ s.execute("guide.add", &json!({"spread": 1, "orientation": "vertical", "position": 300.0})).unwrap();+ let spread = selected(&s)[0].spread;+ let at = |index| GuideSel { spread, page: 0, index };+ s.doc_mut().unwrap().selection.guides = vec![at(0), at(2), at(0)];+ assert_eq!(s.execute("guide.delete", &json!({})).unwrap()["deleted"], 2);+ let left = s.execute("guide.list", &json!({"spread": 1})).unwrap();+ assert_eq!(left.as_array().unwrap().iter().map(|g| g["position"].as_f64().unwrap()).collect::<Vec<_>>(), [200.0]);+ assert_eq!(s.execute("guide.list", &json!({"spread": 0})).unwrap().as_array().unwrap().len(), 1);+ }+}+#[cfg(test)]mod layer_tests {use serde_json::json;diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 3b16b9cfc..a4d5413bb 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -20,7 +20,7 @@ pub(crate) mod find;pub use find::same_find_domain;pub(crate) mod flex;mod fonts;-mod guides;+pub(crate) mod guides;mod index;mod inspect;mod interactive;diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 183b81c5c..d16dc9dd1 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -571,6 +571,7 @@ impl Session {Ok(r) => r,Err(e) => {// What it did before it failed can be undone too.+ self.keep_guide_selection_valid(before.as_ref(), id);self.record_undo_step(spec, before, nested);return Err(e);}@@ -613,6 +614,7 @@ impl Session {}}}+ self.keep_guide_selection_valid(before.as_ref(), id);self.record_undo_step(spec, before, nested);if spec.journal {self.journal.push((id.to_string(), params.clone()));@@ -621,6 +623,15 @@ impl Session {Ok(r)}+ /// Drops selected guides the command `id` made stale, against the document as it will be+ /// recorded: after the passes that run with the command (smart reflow, live captions, autosize).+ fn keep_guide_selection_valid(&mut self, before: Option<&(u64, Arc<Document>, Selection)>, id: &str) {+ if let Some(st) = self.active_mut() {+ let old = before.filter(|(uid, _, _)| *uid == st.uid).map(|(_, d, sel)| (d.as_ref(), sel));+ cmd::guides::keep_selection_valid(st, old, id);+ }+ }+/// Record undo if the document changed (and we're not previewing an interaction), with the/// selection from before the command. A command run by an undoable one leaves the step to it:/// one command is one undo step.diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 9aacf469d..42f57b3a1 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -294,8 +294,9 @@ fn cmd_move_does_not_snap() {fn cmd_resize_still_snaps_to_a_guide() {use designcraft_tools::{PointerEvent, PointerKind};let mut s = session();- s.execute("frame.create", &json!({"rect": [100.0, 100.0, 200.0, 180.0], "content": "unassigned"})).unwrap();+ // The new guide is selected: the frame created after it is the selection.s.execute("guide.add", &json!({"orientation": "vertical", "position": 250.0, "page": 0})).unwrap();+ s.execute("frame.create", &json!({"rect": [100.0, 100.0, 200.0, 180.0], "content": "unassigned"})).unwrap();s.set_tool("selection");let v = ViewInfo::at_zoom(1.0);let b0 = s.doc().unwrap().doc.spreads[0].items[0].bounds();diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rsindex a92f1c132..b5153e183 100644--- a/crates/tools/src/lib.rs+++ b/crates/tools/src/lib.rs@@ -140,6 +140,9 @@ pub struct SnapView {pub smart_dimensions: bool,pub smart_spacing: bool,pub zone_px: f64,+ /// View › Grids & Guides › Lock Guides: ruler guides can't be selected or moved.+ #[serde(default)]+ pub guides_locked: bool,}impl SnapView {@@ -153,6 +156,7 @@ impl SnapView {smart_dimensions: true,smart_spacing: true,zone_px: 4.0,+ guides_locked: false,};pub const OFF: Self = Self {snap_to_guides: false,@@ -164,6 +168,7 @@ impl SnapView {smart_dimensions: false,smart_spacing: false,zone_px: 4.0,+ guides_locked: false,};/// Guides, the document grid, or smart guides are on.diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rsindex 891f1d4ab..b3d3780f2 100644--- a/crates/tools/src/select.rs+++ b/crates/tools/src/select.rs@@ -2,7 +2,8 @@//!//! Click selects the frontmost item (Shift toggles), drag moves (Alt duplicates, Shift constrains),//! the 8 bounding-box handles resize (Shift keeps proportions, Alt from centre, Cmd scales content),-//! empty-canvas drags make a marquee, double-clicking a text frame switches to the Type tool and+//! empty-canvas drags make a marquee (it selects the ruler guides it crosses when it touches no+//! object), double-clicking a text frame switches to the Type tool and//! double-clicking a handle fits the frame to its content (corner: both sides, edge: that one).//! A click on a selected text frame's in or out port loads the text cursor (see [`crate::thread`]).//!@@ -179,6 +180,42 @@ fn spread_delta_to_canvas(xf: Affine, d: Vec2) -> Vec2 {(xf * Point::new(d.x, d.y)) - (xf * Point::ORIGIN)}+/// The ruler guides a marquee `r` (canvas) crosses that can be selected, as `guide.select`+/// takes them: none while guides are hidden or locked.+fn guides_crossing(cx: &ToolContext, r: Rect) -> Vec<Value> {+ if !cx.snap.show_guides || cx.snap.guides_locked {+ return vec![];+ }+ let mut out = Vec::new();+ for slot in &cx.layout.slots {+ let Some(sp) = cx.doc.spread(slot.spread) else { continue };+ let pasteboard = slot.xf.inverse().transform_rect_bbox(cx.layout.pasteboard);+ for (pi, pg) in sp.pages.iter().enumerate() {+ for (gi, g) in pg.guides.iter().enumerate() {+ if !g.editable_in(cx.doc) {+ continue;+ }+ // The line as the canvas draws it: a spread guide crosses the pasteboard (a+ // vertical one the spread's height and a little), a page guide its page.+ let span = match (g.spread, g.orientation) {+ (false, _) => pg.bounds(),+ (true, designcraft_doc::Orientation::Horizontal) => pasteboard,+ (true, designcraft_doc::Orientation::Vertical) => sp.bounds().inflate(0.0, 36.0),+ };+ let line = match g.orientation {+ designcraft_doc::Orientation::Horizontal => Rect::new(span.x0, g.position, span.x1, g.position),+ designcraft_doc::Orientation::Vertical => Rect::new(g.position, span.y0, g.position, span.y1),+ };+ let b = slot.xf.transform_rect_bbox(line);+ if b.x0 <= r.x1 && b.x1 >= r.x0 && b.y0 <= r.y1 && b.y1 >= r.y0 {+ out.push(json!({"spread": slot.spread, "page": pi, "index": gi}));+ }+ }+ }+ }+ out+}+pub struct SelectionTool {direct: bool,drag: Drag,@@ -1112,7 +1149,12 @@ impl Tool for SelectionTool {}}}- vec![Action::Exec("selection.set".into(), json!({"ids": ids, "add": ev.mods.shift}))]+ let guides = if ids.is_empty() { guides_crossing(cx, r) } else { vec![] };+ if guides.is_empty() {+ vec![Action::Exec("selection.set".into(), json!({"ids": ids, "add": ev.mods.shift}))]+ } else {+ vec![Action::Exec("guide.select".into(), json!({"guides": guides, "add": ev.mods.shift}))]+ }}Drag::None | Drag::Place { .. } => vec![],}@@ -1133,7 +1175,20 @@ impl Tool for SelectionTool {}let mv = |dx: f64, dy: f64| vec![Action::Exec("transform.move".into(), json!({"dx": dx, "dy": dy, "copy": mods.alt}))];if cx.selection.items.is_empty() {- return vec![];+ // Selected ruler guides: the arrows nudge them, Delete deletes them.+ if cx.selection.guides.is_empty() {+ return vec![];+ }+ let nudge = |dx: f64, dy: f64| vec![Action::Exec("guide.moveBy".into(), json!({"dx": dx, "dy": dy}))];+ return match key {+ ToolKey::Left => nudge(-inc, 0.0),+ ToolKey::Right => nudge(inc, 0.0),+ ToolKey::Up => nudge(0.0, -inc),+ ToolKey::Down => nudge(0.0, inc),+ ToolKey::Delete | ToolKey::Backspace => vec![Action::Exec("edit.clear".into(), json!({}))],+ ToolKey::Escape => vec![Action::Exec("guide.deselect".into(), json!({}))],+ _ => vec![],+ };}match key {ToolKey::Left => mv(-inc, 0.0),diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 8d94f099f..322f75d80 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2,7 +2,7 @@//! selection, text ports and threads, the text caret, rulers, and pointer/keyboard input.use designcraft_compose as compose;-use designcraft_doc::{Content, Document, Item, SpreadRef};+use designcraft_doc::{Content, Document, GuideSel, Item, SpreadRef};use designcraft_engine::doc::Selection;use designcraft_geom::{Affine, Point, Rect as DRect, Vec2 as DVec2};use designcraft_tools::{CanvasLayout, Cursor, Mods, Overlay, PointerEvent, PointerKind, SpreadSlot, ToolKey};@@ -531,8 +531,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {painter.rect_stroke(xf.rect(slot.bounds), 0.0, Stroke::new(hair, Color32::from_rgb(0x4a, 0x4a, 0x4a)), StrokeKind::Outside);}if !preview {- draw_guides(app, &painter, &xf, &doc, &layout, &t);- if let Some(g) = ui.data(|d| d.get_temp::<GuideDrag>(egui::Id::new(GUIDE_DRAG)))+ let drag = ui.data(|d| d.get_temp::<GuideDrag>(egui::Id::new(GUIDE_DRAG)));+ let press = ui.data(|d| d.get_temp::<GuidePress>(egui::Id::new(GUIDE_PRESS)));+ let moving = drag.as_ref().zip(press).and_then(|(g, press)| moving_guides(app, &xf, rect, g, press));+ draw_guides(app, &painter, &xf, &doc, &layout, &t, moving.as_ref());+ if let Some(g) = drag&& let Some(p) = g.at{let col = Color32::from_rgb(74, 227, 255);@@ -546,6 +549,15 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {} else {painter.line_segment([a, b], Stroke::new(1.0, col));}+ // Where it is, beside the pointer (#1282).+ if let Some(text) = guide_readout(app, &xf, &g) {+ let galley = painter.layout_no_wrap(text, egui::FontId::proportional(11.0), t.text);+ let at = readout_at(p, galley.size(), rect);+ let bg = Rect::from_min_size(at, galley.size()).expand(3.0);+ painter.rect_filled(bg, 2.0, t.panel);+ painter.rect_stroke(bg, 2.0, Stroke::new(1.0, t.border), StrokeKind::Inside);+ painter.galley(at, galley, t.text);+ }}draw_frames(app, &painter, &xf, &doc, &layout);if app.ui.hidden_characters {@@ -950,8 +962,11 @@ fn shown_area(app: &DesignApp, doc: &Document, xf: &Xf, slot: &SpreadSlot) -> Reboxes.iter().filter_map(|o| sp.outset_rect(*o)).map(|r| xf.rect(slot.xf.transform_rect_bbox(r))).fold(trim, |a, b| a.union(b))}-fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout, t: &Tokens) {+/// `moving`: guides being dragged, drawn where they would be dropped instead of where they are.+fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout, t: &Tokens, moving: Option<&MovingGuides>) {let s = &doc.settings;+ let selection: std::collections::HashSet<GuideSel> =+ app.session.active().map(|st| st.selection.guides.iter().copied().collect()).unwrap_or_default();for slot in &layout.slots {let Some(sp) = doc.spread(slot.spread) else { continue };// Everything below is in spread coordinates, placed through the slot (which may be turned).@@ -1007,8 +1022,21 @@ fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document}}}- // The page's own guides, then those it shows from its parent page.- for g in p.guides.iter().cloned().chain(doc.parent_guides(p)).filter(|g| g.visible_in(doc)) {+ // The page's own guides, then those it shows from its parent page. Selected guides are+ // drawn thicker, in their layer's color.+ let own = p.guides.len();+ for (gi, mut g) in p.guides.iter().cloned().chain(doc.parent_guides(p)).enumerate().filter(|(_, g)| g.visible_in(doc)) {+ let key = GuideSel { spread: slot.spread, page: pi, index: gi };+ let selected = gi < own && selection.contains(&key);+ if gi < own+ && let Some(m) = moving+ && m.guides.contains(&key)+ {+ g.position += match g.orientation {+ designcraft_doc::Orientation::Vertical => m.dx,+ designcraft_doc::Orientation::Horizontal => m.dy,+ };+ }// Spread guides cross the pasteboard; page guides their page.let span = if g.spread { pasteboard } else { pr };let (a, bb) = match g.orientation {@@ -1018,7 +1046,12 @@ fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document(Point::new(g.position, span.y0), Point::new(g.position, span.y1))}};- let stroke = Stroke::new(hair(painter), Color32::from_rgb(74, 227, 255));+ let stroke = if selected {+ let color = g.layer.and_then(|l| doc.layer(l)).map_or(Color32::from_rgb(79, 153, 255), |l| c32(l.color));+ Stroke::new(2.0, color)+ } else {+ Stroke::new(hair(painter), Color32::from_rgb(74, 227, 255))+ };if g.liquid {// Liquid guides are dashed.painter.extend(egui::Shape::dashed_line(&[pt(a), pt(bb)], stroke, 6.0, 3.0));@@ -2013,6 +2046,11 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf,/// coordinates: the ruler origin (one per page for a page origin) moved by zero point `zp`.fn ruler_pieces(app: &DesignApp, doc: &Document, layout: &CanvasLayout, zp: [f64; 2]) -> Vec<(f64, f64, Point)> {let Some(slot) = current_slot(app, layout).and_then(|i| layout.slots.get(i)) else { return Vec::new() };+ ruler_pieces_of(doc, slot, zp)+}++/// [`ruler_pieces`] for the spread in `slot`.+fn ruler_pieces_of(doc: &Document, slot: &SpreadSlot, zp: [f64; 2]) -> Vec<(f64, f64, Point)> {let x = |v: f64, y: f64| if v.is_finite() { slot.to_canvas(Point::new(v, y)).x } else { v };doc.ruler_pieces(slot.spread).into_iter()@@ -2375,6 +2413,10 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rif !space && !menu_open && xf.rot == 0 && zero_point_drag(app, ui, resp, rect, &xf) {return;}+ // Hidden or locked guides can't stay selected.+ if (!app.ui.guides || app.ui.guides_locked) && app.session.active().is_some_and(|st| !st.selection.guides.is_empty()) {+ let _ = app.run("guide.deselect", json!({}));+ }if !space && !menu_open && xf.rot == 0 && guide_drag(app, ui, resp, rect, &xf) {return;}@@ -2841,6 +2883,66 @@ struct GuideDrag {at: Option<Pos2>,}+const GUIDE_PRESS: &str = "canvas_guide_press";++/// A press on an existing guide: where it was (screen) and whether Shift was down. Released+/// where it was pressed, it is a click, which selects the guide.+#[derive(Clone, Copy, Debug)]+struct GuidePress {+ origin: Pos2,+ shift: bool,+}++/// How far (screen pixels) the pointer may move between press and release for a click.+const GUIDE_CLICK_SLOP: f32 = 3.0;++/// Where a dragged guide is, as the rulers measure it (#1282): `X: …` for a vertical guide, `Y: …`+/// for a horizontal one, from the zero point (and the page origin, when rulers restart per page)+/// in the document's ruler units. `None` with no document or rulers.+fn guide_readout(app: &DesignApp, xf: &Xf, g: &GuideDrag) -> Option<String> {+ let (label, value, unit) = guide_measure(app, xf, g)?;+ Some(format!("{label}: {}", designcraft_geom::units::format_measure(value, unit)))+}++/// Where a pointer readout of `size` goes for a pointer at `p`: below right of it, on the other+/// side where that would leave the canvas `area` (near its right or bottom edge), and kept inside+/// it (with the label's 3-point frame) however small the canvas is.+fn readout_at(p: Pos2, size: egui::Vec2, area: Rect) -> Pos2 {+ const GAP: f32 = 12.0;+ const PAD: f32 = 3.0;+ let x = if p.x + GAP + size.x + PAD > area.max.x { p.x - GAP - size.x } else { p.x + GAP };+ let y = if p.y + GAP + size.y + PAD > area.max.y { p.y - GAP - size.y } else { p.y + GAP };+ let clamp = |v: f32, lo: f32, hi: f32| if hi < lo { lo } else { v.clamp(lo, hi) };+ pos2(clamp(x, area.min.x + PAD, area.max.x - PAD - size.x), clamp(y, area.min.y + PAD, area.max.y - PAD - size.y))+}++/// [`guide_readout`]'s parts: the axis label, the value (points) and its unit.+fn guide_measure(app: &DesignApp, xf: &Xf, g: &GuideDrag) -> Option<(&'static str, f64, designcraft_geom::Unit)> {+ let p = g.at?;+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let c = xf.to_canvas(p);+ // Measured on the spread under the pointer, which the guide is dropped on (`guide_drag`),+ // as the rulers measure that spread: not the one in the middle of the view.+ let slot = layout.spread_at(c).and_then(|(r, _)| layout.slot(r)).or_else(|| current_slot(app, &layout).and_then(|i| layout.slots.get(i)))?;+ // An existing guide moves only on its own spread (`guide_drag`): over another, dropping it+ // leaves it where it was, so there is no place to show.+ if g.from.is_some_and(|(r, _, _)| r != slot.spread) {+ return None;+ }+ let pieces = ruler_pieces_of(&st.doc, slot, st.doc.zero_point());+ let first = pieces.first()?;+ let (label, value, unit) = match g.orientation {+ designcraft_doc::Orientation::Vertical => {+ // The horizontal ruler restarts at each page: the piece under the guide measures it.+ let o = pieces.iter().find(|(from, to, _)| *from <= c.x && c.x < *to).unwrap_or(first).2;+ ("X", c.x - o.x, st.doc.settings.horizontal_units)+ }+ designcraft_doc::Orientation::Horizontal => ("Y", c.y - first.2.y, st.doc.settings.vertical_units),+ };+ value.is_finite().then_some((label, value, unit))+}+/// The guide under a screen point (within 3 px), as (spread, page, index, orientation).fn guide_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<(designcraft_doc::SpreadRef, usize, usize, designcraft_doc::Orientation)> {let st = app.session.active()?;@@ -2870,8 +2972,10 @@ fn guide_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<(designcraft_doc::SpreaNone}-/// Ruler guides: drag one out of a ruler, drag an existing one (Selection tools, not over an-/// object) to move it, drop it back on a ruler to delete it. Returns true while it owns the pointer.+/// Ruler guides: drag one out of a ruler, drag an existing one (Selection tools) to move it, drop+/// it back on a ruler to delete it. A press near an unlocked guide takes it even over an object:+/// the guide is selected and the object is not. Returns true from the press to the release, so+/// the tools never see that press.fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect, xf: &Xf) -> bool {let id = egui::Id::new(GUIDE_DRAG);let (pressed, released, origin, latest) =@@ -2896,17 +3000,14 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec&& matches!(app.session.tool_id(), "selection" | "directSelection")&& let Some((r, pi, gi, orientation)) = guide_at(app, xf, o){- // Objects take precedence over the guides behind them.- let over_item = app.session.active().is_some_and(|st| {- let layout = CanvasLayout::new(&st.doc, st.editing_parents);- layout.spread_at(xf.to_canvas(o)).is_some_and(|(sr, p)| match sr {- designcraft_doc::SpreadRef::Doc(si) => st.doc.hit_item(si, p, 3.0 / xf.zoom).is_some(),- _ => false,- })- });- if !over_item {- drag = Some(GuideDrag { orientation, from: Some((r, pi, gi)), at: Some(o) });+ let shift = ui.input(|i| i.modifiers.shift);+ // A press on a guide selects it (Shift: on release, as a click adds or removes it).+ let selected = app.session.active().is_some_and(|st| st.selection.guides.contains(&GuideSel { spread: r, page: pi, index: gi }));+ if !shift && !selected {+ let _ = app.run("guide.select", json!({"spread": r, "page": pi, "index": gi}));}+ ui.data_mut(|d| d.insert_temp(egui::Id::new(GUIDE_PRESS), GuidePress { origin: o, shift }));+ drag = Some(GuideDrag { orientation, from: Some((r, pi, gi)), at: Some(o) });}}let Some(mut g) = drag else { return false };@@ -2922,7 +3023,23 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, recreturn true;}ui.data_mut(|d| d.remove::<GuideDrag>(id));+ let press: Option<GuidePress> = ui.data_mut(|d| {+ let press = d.get_temp(egui::Id::new(GUIDE_PRESS));+ d.remove::<GuidePress>(egui::Id::new(GUIDE_PRESS));+ press+ });let Some(p) = g.at else { return true };+ if let (Some((r, pi, gi)), Some(press)) = (g.from, press)+ && (p - press.origin).length() <= GUIDE_CLICK_SLOP+ {+ // A click: the guide is selected (at the press); Shift adds it or removes it.+ if press.shift {+ let _ = app.run("guide.select", json!({"spread": r, "page": pi, "index": gi, "toggle": true}));+ }+ return true;+ }+ // Dragging one of several selected guides moves (or deletes) them all.+ let group = g.from.is_some_and(|(spread, page, index)| drags_group(app, GuideSel { spread, page, index }));let on_canvas = rect.contains(p);let target = app.session.active().and_then(|st| {let layout = CanvasLayout::new(&st.doc, st.editing_parents);@@ -2941,9 +3058,17 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec};match (g.from, on_canvas, target) {// Dropped back on a ruler: delete.+ (Some(_), false, _) if group => {+ let _ = app.run("guide.delete", json!({}));+ }(Some((r, pi, gi)), false, _) => {let _ = app.run("guide.delete", json!({"spread": r, "page": pi, "index": gi}));}+ (Some((r, _, _)), true, Some((tr, _, _))) if tr == r && group => {+ if let Some((dx, dy)) = press.and_then(|press| guide_drag_delta(app, xf, &g, press.origin, p)) {+ let _ = app.run("guide.moveBy", json!({"dx": dx, "dy": dy}));+ }+ }(Some((r, pi, gi)), true, Some((tr, sp, _))) if tr == r => {let _ = app.run("guide.move", json!({"spread": r, "page": pi, "index": gi, "position": pos_of(sp)}));}@@ -2962,6 +3087,55 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rectrue}+/// Whether dragging guide `from` takes the other selected guides along: it is one of several+/// selected.+fn drags_group(app: &DesignApp, from: GuideSel) -> bool {+ app.session.active().is_some_and(|st| st.selection.guides.len() > 1 && st.selection.guides.contains(&from))+}++/// How far a drag of the existing guide `g.from`, pressed at `origin` and now at `p` (screen),+/// moves guides, in spread coordinates: the dragged guide goes to the pointer, the other selected+/// guides as far along their own axis as the pointer moved. `None` while the pointer is not over+/// the guide's own spread, where a drop leaves it in place.+fn guide_drag_delta(app: &DesignApp, xf: &Xf, g: &GuideDrag, origin: Pos2, p: Pos2) -> Option<(f64, f64)> {+ let (r, pi, gi) = g.from?;+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let (tr, sp) = layout.spread_at(xf.to_canvas(p))?;+ if tr != r {+ return None;+ }+ let start = layout.slot(r)?.to_spread(xf.to_canvas(origin));+ let at = st.doc.spread(r)?.pages.get(pi)?.guides.get(gi)?.position;+ let (dx, dy) = match g.orientation {+ designcraft_doc::Orientation::Vertical => (sp.x - at, sp.y - start.y),+ designcraft_doc::Orientation::Horizontal => (sp.x - start.x, sp.y - at),+ };+ (dx.is_finite() && dy.is_finite()).then_some((dx, dy))+}++/// Guides being dragged on the canvas and how far they have moved (spread coordinates).+struct MovingGuides {+ guides: std::collections::HashSet<GuideSel>,+ dx: f64,+ dy: f64,+}++/// What a drag of an existing guide moves, for the preview: the dragged guide, or every selected+/// guide when it is one of several selected. `None` before the drag leaves the click distance,+/// over a ruler (a drop there deletes) and off the guide's spread.+fn moving_guides(app: &DesignApp, xf: &Xf, rect: Rect, g: &GuideDrag, press: GuidePress) -> Option<MovingGuides> {+ let (spread, page, index) = g.from?;+ let p = g.at?;+ if !rect.contains(p) || (p - press.origin).length() <= GUIDE_CLICK_SLOP {+ return None;+ }+ let (dx, dy) = guide_drag_delta(app, xf, g, press.origin, p)?;+ let from = GuideSel { spread, page, index };+ let guides = if drags_group(app, from) { app.session.active()?.selection.guides.iter().copied().collect() } else { [from].into_iter().collect() };+ Some(MovingGuides { guides, dx, dy })+}+/// Presses in a row on the canvas: the last press's count, and where and when it was released/// (`at` is −∞ while the button is down).#[derive(Clone, Copy, Debug)]@@ -2991,6 +3165,10 @@ fn release_clicks(press: Clicks, pos: Pos2, now: f64, dist: f32) -> Clicks {#[path = "parent_canvas_tests.rs"]mod parent_canvas_tests;+#[cfg(test)]+#[path = "guide_selection_tests.rs"]+mod guide_selection_tests;+#[cfg(test)]mod tests {use designcraft_geom::Unit;@@ -4033,6 +4211,105 @@ mod tests {assert_eq!(doc.settings.zero_point, [0.0, 0.0], "the zero point stays");}+ /// A guide being dragged out of a ruler says where it is, as the rulers measure it (#1282):+ /// from the zero point, in the ruler units, and the label follows the pointer while it moves.+ #[test]+ fn a_dragged_guide_shows_where_it_is() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();+ let mut h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let dest = rect.min + vec2(160.0, 110.0);+ let (xf, at) = {+ let app = h.state();+ let xf = Xf::new(rect, app.view().unwrap());+ let st = app.session.active().unwrap();+ (xf, CanvasLayout::new(&st.doc, false).spread_at(xf.to_canvas(dest)).unwrap().1)+ };+ let units = h.state().session.doc().unwrap().doc.settings.horizontal_units;+ for (orientation, label, want) in+ [(designcraft_doc::Orientation::Vertical, "X", at.x - 100.0), (designcraft_doc::Orientation::Horizontal, "Y", at.y - 50.0)]+ {+ let g = GuideDrag { orientation, from: None, at: Some(dest) };+ let (l, v, _) = guide_measure(h.state(), &xf, &g).unwrap();+ assert_eq!(l, label);+ assert!((v - want).abs() < 1e-6, "{label}: {v} vs {want}");+ let text = guide_readout(h.state(), &xf, &g).unwrap();+ assert_eq!(text, format!("{label}: {}", designcraft_geom::units::format_measure(v, units)));+ }+ // While a guide is actually being dragged out of the top ruler, the readout is there.+ let ruler = pos2(rect.min.x + 200.0, rect.min.y - RULER / 2.0);+ h.hover_at(ruler);+ h.step();+ primary(&mut h, ruler, true);+ h.event(egui::Event::PointerMoved(dest));+ h.run_steps(2);+ let g = h.ctx.data(|d| d.get_temp::<GuideDrag>(egui::Id::new(GUIDE_DRAG))).expect("dragging");+ assert_eq!(g.orientation, designcraft_doc::Orientation::Horizontal);+ assert!(guide_readout(h.state(), &xf, &g).is_some_and(|t| t.starts_with("Y: ")));+ primary(&mut h, dest, false);+ }++ /// Over a spread other than the one in the middle of the view, the readout measures that+ /// spread, the one the guide is dropped on: it reads the position the guide gets.+ #[test]+ fn the_guide_readout_measures_the_spread_under_the_pointer() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 5})).unwrap();+ app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();+ let h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let xf = Xf::new(rect, h.state().view().unwrap());+ let st = h.state().session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, false);+ let current = current_slot(h.state(), &layout).unwrap();+ // A point inside the last spread, well away from the one in view.+ let last = layout.slots.last().unwrap();+ assert_ne!(layout.slots.iter().position(|s| s.spread == last.spread), Some(current), "the last spread isn't the one in view");+ let inside = Point::new(last.bounds.center().x, last.bounds.y0 + (last.bounds.y1 - last.bounds.y0) * 0.3);+ let (r, sp) = layout.spread_at(inside).unwrap();+ assert_eq!(r, last.spread);+ let g = GuideDrag { orientation: designcraft_doc::Orientation::Horizontal, from: None, at: Some(xf.to_screen(inside)) };+ let (label, v, _) = guide_measure(h.state(), &xf, &g).unwrap();+ assert_eq!(label, "Y");+ // The guide would be stored at `sp.y` on that spread, which its ruler reads from the zero point.+ // (To screen and back in f32: a few hundred-thousandths of a point.)+ assert!((v - (sp.y - 50.0)).abs() < 1e-3, "{v} vs {}", sp.y - 50.0);+ // An existing guide of another spread can't be dropped there (it only moves on its own+ // spread): no readout over this one, a readout over its own.+ let first = layout.slots[current].spread;+ let moving = GuideDrag { orientation: designcraft_doc::Orientation::Horizontal, from: Some((first, 0, 0)), at: Some(xf.to_screen(inside)) };+ assert!(guide_measure(h.state(), &xf, &moving).is_none(), "an existing guide over another spread");+ let own = layout.slots[current].bounds;+ let over_own = Point::new(own.center().x, own.y0 + (own.y1 - own.y0) * 0.3);+ let moving_here = GuideDrag { at: Some(xf.to_screen(over_own)), ..moving };+ assert!(guide_measure(h.state(), &xf, &moving_here).is_some(), "over its own spread");+ }++ /// The guide readout stays on the canvas: below right of the pointer in the open, flipped+ /// left or up near the right or bottom edge, and inside the canvas in every corner.+ #[test]+ fn the_guide_readout_stays_inside_the_canvas() {+ let area = Rect::from_min_max(pos2(50.0, 40.0), pos2(850.0, 640.0));+ let size = vec2(80.0, 14.0);+ let inside = |at: Pos2| {+ let r = Rect::from_min_size(at, size).expand(3.0);+ r.min.x >= area.min.x - 1e-3 && r.min.y >= area.min.y - 1e-3 && r.max.x <= area.max.x + 1e-3 && r.max.y <= area.max.y + 1e-3+ };+ assert_eq!(readout_at(pos2(400.0, 300.0), size, area), pos2(412.0, 312.0), "in the open: below right");+ let right = readout_at(pos2(845.0, 300.0), size, area);+ assert!(right.x + size.x < 845.0 && inside(right), "near the right edge: left of the pointer, {right:?}");+ let bottom = readout_at(pos2(400.0, 636.0), size, area);+ assert!(bottom.y + size.y < 636.0 && inside(bottom), "near the bottom: above it, {bottom:?}");+ for p in [area.min, pos2(area.max.x, area.min.y), area.max, pos2(area.min.x, area.max.y), pos2(-500.0, 2000.0)] {+ assert!(inside(readout_at(p, size, area)), "{p:?}");+ }+ // A canvas narrower than the label: pinned to its top left, not past it.+ let tiny = Rect::from_min_max(pos2(0.0, 0.0), pos2(40.0, 10.0));+ assert_eq!(readout_at(pos2(20.0, 5.0), size, tiny), pos2(3.0, 3.0));+ }+#[test]fn rulers_and_xy_fields_measure_from_the_zero_point_on_every_spread() {let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());diff --git a/crates/ui-egui/src/guide_selection_tests.rs b/crates/ui-egui/src/guide_selection_tests.rsnew file mode 100644index 000000000..23ad14c91--- /dev/null+++ b/crates/ui-egui/src/guide_selection_tests.rs@@ -0,0 +1,258 @@+//! Ruler guides selected like objects (#1282): click, Shift-click, marquee, drag, keys, and the+//! X/Y fields.++use egui::{Event, Modifiers, PointerButton};+use egui_kittest::Harness;++use super::*;++fn harness(app: DesignApp) -> Harness<'static, DesignApp> {+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ h+}++/// A page with vertical guides at x 200 and 300 and a horizontal one at y 400.+fn with_guides() -> Harness<'static, DesignApp> {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ for (orientation, position) in [("vertical", 200.0), ("vertical", 300.0), ("horizontal", 400.0)] {+ app.run("guide.add", json!({"orientation": orientation, "position": position})).unwrap();+ }+ harness(app)+}++/// Screen position of spread 0's point (x, y).+fn screen_of(h: &Harness<'_, DesignApp>, x: f64, y: f64) -> Pos2 {+ let app = h.state();+ let st = app.session.active().unwrap();+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ xf.to_screen(CanvasLayout::new(&st.doc, st.editing_parents).xf(SpreadRef::Doc(0)) * Point::new(x, y))+}++fn press(h: &mut Harness<'_, DesignApp>, pos: Pos2, pressed: bool, mods: Modifiers) {+ h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: mods });+ h.run_steps(2);+}++fn click(h: &mut Harness<'_, DesignApp>, pos: Pos2, mods: Modifiers) {+ h.event(Event::ModifiersChanged(mods));+ h.hover_at(pos);+ h.step();+ press(h, pos, true, mods);+ press(h, pos, false, mods);+ h.event(Event::ModifiersChanged(Modifiers::NONE));+ h.run_steps(2);+}++fn drag(h: &mut Harness<'_, DesignApp>, a: Pos2, b: Pos2) {+ h.hover_at(a);+ h.step();+ press(h, a, true, Modifiers::NONE);+ for k in 1..=4 {+ h.hover_at(a + (b - a) * (k as f32 / 4.0));+ h.step();+ }+ press(h, b, false, Modifiers::NONE);+ h.run_steps(2);+}++fn selected(h: &Harness<'_, DesignApp>) -> Vec<usize> {+ h.state().session.doc().unwrap().selection.guides.iter().map(|g| g.index).collect()+}++fn positions(h: &Harness<'_, DesignApp>) -> Vec<f64> {+ h.state().session.doc().unwrap().doc.spreads[0].pages[0].guides.iter().map(|g| g.position).collect()+}++#[test]+fn clicking_guides_selects_them_and_shift_click_adds_or_removes() {+ let mut h = with_guides();+ let id = h.state_mut().run("frame.create", json!({"rect": [400, 100, 500, 200]})).unwrap()["id"].as_u64().unwrap();+ h.state_mut().run("selection.set", json!({"ids": [id]})).unwrap();+ let at = screen_of(&h, 200.0, 600.0);+ click(&mut h, at, Modifiers::NONE);+ assert_eq!(selected(&h), [0]);+ assert!(h.state().session.doc().unwrap().selection.items.is_empty(), "the object is deselected");+ assert_eq!(positions(&h), [200.0, 300.0, 400.0], "a click doesn't move the guide");+ let at = screen_of(&h, 100.0, 400.0);+ click(&mut h, at, Modifiers::SHIFT);+ assert_eq!(selected(&h), [0, 2]);+ let at = screen_of(&h, 200.0, 650.0);+ click(&mut h, at, Modifiers::SHIFT);+ assert_eq!(selected(&h), [2]);+ // A click on empty canvas, or on an object, clears the guide selection.+ let at = screen_of(&h, 550.0, 650.0);+ click(&mut h, at, Modifiers::NONE);+ assert!(selected(&h).is_empty());+ let at = screen_of(&h, 300.0, 600.0);+ click(&mut h, at, Modifiers::NONE);+ assert_eq!(selected(&h), [1]);+ let at = screen_of(&h, 450.0, 150.0);+ click(&mut h, at, Modifiers::NONE);+ assert!(selected(&h).is_empty());+ assert_eq!(h.state().session.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)]);+ // With View › Lock Guides on, guides can't be selected, and selected ones are deselected.+ h.state_mut().run("guide.selectAll", json!({})).unwrap();+ h.state_mut().ui.guides_locked = true;+ h.run_steps(2);+ assert!(selected(&h).is_empty());+ let at = screen_of(&h, 200.0, 600.0);+ click(&mut h, at, Modifiers::NONE);+ assert!(selected(&h).is_empty());+}++#[test]+fn dragging_a_selected_guide_moves_all_selected_guides_as_one_step() {+ let mut h = with_guides();+ h.state_mut().run("guide.select", json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}]})).unwrap();+ let undo = h.state().session.doc().unwrap().history.undo.len();+ let (a, b) = (screen_of(&h, 200.0, 600.0), screen_of(&h, 250.0, 620.0));+ drag(&mut h, a, b);+ let p = positions(&h);+ assert!((p[0] - 250.0).abs() < 1.0 && p[1] == 300.0 && (p[2] - 420.0).abs() < 1.0, "{p:?}");+ assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1);+ assert_eq!(selected(&h), [0, 2]);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(positions(&h), [200.0, 300.0, 400.0]);+ // Dragging an unselected guide selects it and moves only it.+ let (a, b) = (screen_of(&h, 300.0, 600.0), screen_of(&h, 350.0, 600.0));+ drag(&mut h, a, b);+ assert_eq!(selected(&h), [1]);+ let p = positions(&h);+ assert!(p[0] == 200.0 && (p[1] - 350.0).abs() < 1.0 && p[2] == 400.0, "{p:?}");+}++#[test]+fn a_marquee_selects_guides_only_when_it_touches_no_object() {+ let mut h = with_guides();+ // Across both vertical guides, below the horizontal one, on empty page.+ let (a, b) = (screen_of(&h, 150.0, 500.0), screen_of(&h, 350.0, 550.0));+ drag(&mut h, a, b);+ assert_eq!(selected(&h), [0, 1]);+ let id = h.state_mut().run("frame.create", json!({"rect": [220, 520, 260, 540]})).unwrap()["id"].as_u64().unwrap();+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();+ let (a, b) = (screen_of(&h, 150.0, 500.0), screen_of(&h, 350.0, 550.0));+ drag(&mut h, a, b);+ assert!(selected(&h).is_empty());+ assert_eq!(h.state().session.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)]);+}++#[test]+fn keys_nudge_and_delete_selected_guides() {+ let mut h = with_guides();+ h.state_mut().run("guide.select", json!({"guides": [{"page": 0, "index": 1}, {"page": 0, "index": 2}]})).unwrap();+ let inc = h.state().session.doc().unwrap().doc.settings.keyboard_increment;+ let vi = h.state().view_info();+ let key = |h: &mut Harness<'_, DesignApp>, k: ToolKey, shift: bool| {+ let m = Mods { shift, alt: false, cmd: false, ctrl: false, space: false };+ assert!(h.state_mut().session.tool_key(k, m, vi).unwrap());+ };+ key(&mut h, ToolKey::Right, false);+ key(&mut h, ToolKey::Down, true);+ assert_eq!(positions(&h), [200.0, 300.0 + inc, 400.0 + 10.0 * inc]);+ key(&mut h, ToolKey::Delete, false);+ assert_eq!(positions(&h), [200.0]);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(positions(&h).len(), 3);+ assert_eq!(selected(&h), [1, 2]);+ key(&mut h, ToolKey::Escape, false);+ assert!(selected(&h).is_empty());+}++#[test]+fn the_guide_field_measures_from_the_zero_point() {+ let mut h = with_guides();+ h.state_mut().run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();+ h.state_mut().run("guide.select", json!({"page": 0, "index": 0})).unwrap();+ let f = crate::panels::guide_field(h.state()).unwrap();+ assert_eq!((f.row(), f.value), (0, 100.0));+ h.state_mut().run("guide.move", f.move_to(36.0)).unwrap();+ assert_eq!(positions(&h)[0], 136.0);+ h.state_mut().run("guide.select", json!({"page": 0, "index": 2})).unwrap();+ let f = crate::panels::guide_field(h.state()).unwrap();+ assert_eq!((f.row(), f.value), (1, 350.0));+ // Several guides: no field value.+ h.state_mut().run("guide.selectAll", json!({})).unwrap();+ assert!(crate::panels::guide_field(h.state()).is_none());+}++#[test]+fn select_all_guides_is_in_the_edit_menu_on_the_spread_in_view() {+ let mut h = with_guides();+ assert_eq!(crate::menus::default_shortcut("guide.selectAll"), Some("Cmd+Alt+G"));+ crate::menus::activate(h.state_mut(), "guide.selectAll", &serde_json::Value::Null);+ assert_eq!(selected(&h), [0, 1, 2]);+ assert_eq!(crate::i18n::tr("de", "Select All Guides"), "Alle Hilfslinien auswählen");+ for (code, _) in crate::i18n::LANGUAGES.iter().filter(|(c, _)| !c.is_empty()) {+ assert_ne!(crate::i18n::tr(code, "Select All Guides"), "Select All Guides", "{code}");+ assert_ne!(crate::i18n::tr(code, "Ruler Guide"), "Ruler Guide", "{code}");+ }+ h.state_mut().ui.guides = false;+ assert!(!crate::menus::menu_enabled(h.state(), "guide.selectAll"));+}++#[test]+fn a_guide_over_a_frame_takes_the_click() {+ let mut h = with_guides();+ h.state_mut().run("guide.deselect", json!({})).unwrap();+ // The vertical guide at x 200 crosses the frame.+ let id = h.state_mut().run("frame.create", json!({"rect": [150, 500, 260, 560]})).unwrap()["id"].as_u64().unwrap();+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();+ let bounds = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].items[0].bounds();+ let before = bounds(&h);+ let at = screen_of(&h, 200.0, 530.0);+ click(&mut h, at, Modifiers::NONE);+ assert_eq!(selected(&h), [0]);+ assert!(h.state().session.doc().unwrap().selection.items.is_empty(), "the frame is not selected");+ // Dragging it there moves the guide, not the frame.+ let (a, b) = (screen_of(&h, 200.0, 530.0), screen_of(&h, 230.0, 530.0));+ drag(&mut h, a, b);+ assert!((positions(&h)[0] - 230.0).abs() < 1.0, "{:?}", positions(&h));+ assert_eq!(bounds(&h), before);+ assert!(h.state().session.doc().unwrap().selection.items.is_empty());+ // Away from the guide, a click inside the frame selects it.+ let at = screen_of(&h, 160.0, 530.0);+ click(&mut h, at, Modifiers::NONE);+ assert_eq!(h.state().session.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)]);+ assert!(selected(&h).is_empty());+}++#[test]+fn a_guide_dragged_out_of_a_ruler_is_the_selection() {+ let mut h = with_guides();+ h.state_mut().run("guide.select", json!({"page": 0, "index": 0})).unwrap();+ let rect = h.state().canvas_rect.unwrap();+ let ruler = pos2(rect.min.x + 200.0, rect.min.y - RULER / 2.0);+ let dest = screen_of(&h, 250.0, 500.0);+ drag(&mut h, ruler, dest);+ let p = positions(&h);+ assert!(p.len() == 4 && (p[3] - 500.0).abs() < 1.0, "{p:?}");+ assert_eq!(selected(&h), [3]);+}++#[test]+fn dragging_one_of_several_selected_guides_previews_them_all() {+ let mut h = with_guides();+ h.state_mut().run("guide.select", json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}]})).unwrap();+ let (a, b) = (screen_of(&h, 200.0, 600.0), screen_of(&h, 250.0, 620.0));+ let g = GuideDrag { orientation: designcraft_doc::Orientation::Vertical, from: Some((SpreadRef::Doc(0), 0, 0)), at: Some(b) };+ let press = GuidePress { origin: a, shift: false };+ let app = h.state();+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ let m = moving_guides(app, &xf, app.canvas_rect.unwrap(), &g, press).expect("moving");+ assert!((m.dx - 50.0).abs() < 1.0 && (m.dy - 20.0).abs() < 1.0, "{} {}", m.dx, m.dy);+ let mut moved: Vec<usize> = m.guides.iter().map(|g| g.index).collect();+ moved.sort_unstable();+ assert_eq!(moved, [0, 2]);+ // The drop moves them by the same amounts.+ let (dx, dy) = guide_drag_delta(app, &xf, &g, a, b).unwrap();+ assert_eq!((dx, dy), (m.dx, m.dy));+}diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rsindex c2abdb9a9..91c6db7de 100644--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@ -318,6 +318,11 @@ const TABLE: &[(&str, [&str; 5])] = &[("Duplicate", ["Duplizieren", "Dupliquer", "Duplicar", "複製", "重复"]),("Select All", ["Alles auswählen", "Tout sélectionner", "Seleccionar todo", "すべてを選択", "全选"]),("Deselect All", ["Auswahl aufheben", "Tout désélectionner", "Deseleccionar todo", "すべての選択を解除", "取消全选"]),+ (+ "Select All Guides",+ ["Alle Hilfslinien auswählen", "Sélectionner tous les repères", "Seleccionar todas las guías", "すべてのガイドを選択", "选择所有参考线"],+ ),+ ("Ruler Guide", ["Hilfslinie", "Repère de règle", "Guía de regla", "定規ガイド", "标尺参考线"]),("Find/Change…", ["Suchen/Ersetzen …", "Rechercher/Remplacer…", "Buscar/Cambiar…", "検索と置換…", "查找/更改…"]),("Check Spelling…", ["Rechtschreibprüfung …", "Vérifier l'orthographe…", "Revisar ortografía…", "スペルチェック…", "拼写检查…"]),("Preferences…", ["Voreinstellungen …", "Préférences…", "Preferencias…", "環境設定…", "首选项…"]),diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rsindex b050de38b..11a01c1cc 100644--- a/crates/ui-egui/src/i18n/ar.rs+++ b/crates/ui-egui/src/i18n/ar.rs@@ -147,6 +147,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "تكرار"),("Select All", "تحديد الكل"),("Deselect All", "إلغاء تحديد الكل"),+ ("Select All Guides", "تحديد كل الأدلة"),+ ("Ruler Guide", "دليل المسطرة"),("Find/Change…", "البحث/التغيير…"),("Find/Change", "البحث/التغيير"),("Check Spelling…", "تدقيق إملائي…"),diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rsindex e77e72a1c..b295e5e5b 100644--- a/crates/ui-egui/src/i18n/cs.rs+++ b/crates/ui-egui/src/i18n/cs.rs@@ -37,6 +37,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "Duplikovat"),("Select All", "Vybrat vše"),("Deselect All", "Zrušit výběr"),+ ("Select All Guides", "Vybrat všechna vodítka"),+ ("Ruler Guide", "Vodítko pravítka"),("Find/Change…", "Najít/Změnit…"),("Check Spelling…", "Zkontrolovat pravopis…"),("Preferences…", "Předvolby…"),diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rsindex efc128858..7a5c5d17e 100644--- a/crates/ui-egui/src/i18n/de.rs+++ b/crates/ui-egui/src/i18n/de.rs@@ -64,6 +64,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "Duplizieren"),("Select All", "Alles auswählen"),("Deselect All", "Auswahl aufheben"),+ ("Select All Guides", "Alle Hilfslinien auswählen"),+ ("Ruler Guide", "Hilfslinie"),("Find/Change…", "Suchen/Ersetzen …"),("Check Spelling…", "Rechtschreibprüfung …"),("Preferences…", "Voreinstellungen …"),diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rsindex a918a9829..e74d445fb 100644--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@ -143,6 +143,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "Duplica"),("Select All", "Seleziona tutto"),("Deselect All", "Deseleziona tutto"),+ ("Select All Guides", "Seleziona tutte le guide"),+ ("Ruler Guide", "Guida del righello"),("Find/Change…", "Trova/Sostituisci…"),("Check Spelling…", "Controllo ortografico…"),("Preferences…", "Preferenze…"),diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rsindex 5647ca940..072c188ff 100644--- a/crates/ui-egui/src/i18n/ja.rs+++ b/crates/ui-egui/src/i18n/ja.rs@@ -145,6 +145,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "複製"),("Select All", "すべてを選択"),("Deselect All", "すべての選択を解除"),+ ("Select All Guides", "すべてのガイドを選択"),+ ("Ruler Guide", "定規ガイド"),("Find/Change…", "検索と置換…"),("Check Spelling…", "スペルチェック…"),("Preferences…", "環境設定…"),diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rsindex d938c2dc7..df9fabc07 100644--- a/crates/ui-egui/src/i18n/ka.rs+++ b/crates/ui-egui/src/i18n/ka.rs@@ -66,6 +66,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "დუბლირება"),("Select All", "ყველაფრის მონიშვნა"),("Deselect All", "ყველა მონიშვნის მოხსნა"),+ ("Select All Guides", "ყველა დამხმარე ხაზის მონიშვნა"),+ ("Ruler Guide", "სახაზავის დამხმარე ხაზი"),("Find/Change…", "ძებნა/ჩანაცვლება…"),("Check Spelling…", "მართლწერის შემოწმება…"),("Preferences…", "პარამეტრები…"),diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rsindex 68d685d99..fca29c211 100644--- a/crates/ui-egui/src/i18n/pl.rs+++ b/crates/ui-egui/src/i18n/pl.rs@@ -33,6 +33,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "Powiel"),("Select All", "Zaznacz wszystko"),("Deselect All", "Usuń zaznaczenie"),+ ("Select All Guides", "Zaznacz wszystkie linie pomocnicze"),+ ("Ruler Guide", "Linia pomocnicza"),("Find/Change…", "Znajdź/zmień…"),("Check Spelling…", "Sprawdź pisownię…"),("Preferences…", "Preferencje…"),diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rsindex 8521de594..6d3a05793 100644--- a/crates/ui-egui/src/i18n/pt_br.rs+++ b/crates/ui-egui/src/i18n/pt_br.rs@@ -154,6 +154,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "Duplicar"),("Select All", "Selecionar tudo"),("Deselect All", "Desmarcar tudo"),+ ("Select All Guides", "Selecionar todas as guias"),+ ("Ruler Guide", "Guia da régua"),("Find/Change…", "Localizar/alterar…"),("Find/Change", "Localizar/alterar"),("Check Spelling…", "Verificar ortografia…"),diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rsindex 251555ca5..dc518b60c 100644--- a/crates/ui-egui/src/i18n/ru.rs+++ b/crates/ui-egui/src/i18n/ru.rs@@ -37,6 +37,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "Дублировать"),("Select All", "Выделить все"),("Deselect All", "Снять выделение"),+ ("Select All Guides", "Выделить все направляющие"),+ ("Ruler Guide", "Направляющая"),("Find/Change…", "Найти/заменить…"),("Check Spelling…", "Проверка орфографии…"),("Preferences…", "Установки…"),diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rsindex dd4a1434d..223dba543 100644--- a/crates/ui-egui/src/i18n/uk.rs+++ b/crates/ui-egui/src/i18n/uk.rs@@ -146,6 +146,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Duplicate", "Дублювати"),("Select All", "Виділити все"),("Deselect All", "Зняти всі виділення"),+ ("Select All Guides", "Виділити всі напрямні"),+ ("Ruler Guide", "Напрямна"),("Find/Change…", "Знайти й замінити…"),("Check Spelling…", "Перевірити орфографію…"),("Preferences…", "Налаштування…"),diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex cb98cac7f..0844b95a4 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -457,6 +457,7 @@ impl UiState {smart_dimensions: self.smart_dimensions,smart_spacing: self.smart_spacing,zone_px: self.snap_zone,+ guides_locked: self.guides_locked,}}}diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex c455b718d..da5819e6f 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -366,6 +366,7 @@ pub const MENUS: &[(&str, &[&str])] = &["cmd:edit.stepAndRepeat","-","cmd:edit.selectAll",+ "cmd:guide.selectAll","cmd:edit.deselectAll","-","ui:app.findChange",@@ -1320,16 +1321,7 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<ValueOk(Value::Null)}"app.deleteAllGuides" => {- let Some(st) = app.session.active() else { return Some(Err("no document open".into())) };- let page = crate::canvas::current_page(app).unwrap_or(0);- let spread = if st.editing_parents {- // The parent spread the canvas shows.- let layout = designcraft_tools::CanvasLayout::new(&st.doc, true);- let shown = crate::canvas::current_slot(app, &layout).and_then(|i| layout.slots.get(i)).map(|s| s.spread);- json!(shown.unwrap_or(designcraft_doc::SpreadRef::Parent(0)))- } else {- json!(st.doc.page_loc(page).map_or(0, |l| l.0))- };+ let Some(spread) = guide_spread(app) else { return Some(Err("no document open".into())) };return Some(app.run("guide.deleteAll", json!({"spread": spread})));}"app.deletePage" | "app.duplicateSpread" => {@@ -2443,6 +2435,9 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool {if id.starts_with("fit.") {return enabled(app, "object.fit");}+ if id == "guide.selectAll" && (!app.ui.guides || app.ui.guides_locked) {+ return false;+ }if ui_label(id).is_some() {return app.session.active().is_some() || id.starts_with("app.") || id.starts_with("window.") || id.starts_with("help.");}@@ -2544,6 +2539,16 @@ fn activate_inner(app: &mut DesignApp, id: &str, params: &Value) {app.ui.dialog = Some(crate::dialogs::Dialog::new(&format!("cmd:{id}"), json!({})));return;}+ // Select All Guides: on the spread in view, while guides are shown and not locked.+ if params.is_null() && id == "guide.selectAll" {+ if app.ui.guides+ && !app.ui.guides_locked+ && let Some(spread) = guide_spread(app)+ {+ let _ = app.run(id, json!({"spread": spread}));+ }+ return;+ }let p = if params.is_null() { json!({}) } else { params.clone() };// Update Link asks before replacing edits made to linked text in the layout.if id == "links.update" {@@ -2553,6 +2558,20 @@ fn activate_inner(app: &mut DesignApp, id: &str, params: &Value) {let _ = app.run(id, p);}+/// The spread the guide commands of the menus act on: the one in view (a parent spread while+/// parents are edited).+fn guide_spread(app: &DesignApp) -> Option<Value> {+ let st = app.session.active()?;+ let page = crate::canvas::current_page(app).unwrap_or(0);+ Some(if st.editing_parents {+ let layout = designcraft_tools::CanvasLayout::new(&st.doc, true);+ let shown = crate::canvas::current_slot(app, &layout).and_then(|i| layout.slots.get(i)).map(|s| s.spread);+ json!(shown.unwrap_or(designcraft_doc::SpreadRef::Parent(0)))+ } else {+ json!(st.doc.page_loc(page).map_or(0, |l| l.0))+ })+}+/// A menu button whose popup stays within the viewport and scrolls when needed./// All menu buttons share this wrapper, including workspace, zoom and panel menus.pub fn menu_button<'a, R>(diff --git a/crates/ui-egui/src/object_control.rs b/crates/ui-egui/src/object_control.rsindex 7c2634e23..0a845a38d 100644--- a/crates/ui-egui/src/object_control.rs+++ b/crates/ui-egui/src/object_control.rs@@ -64,6 +64,8 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) {let selected = info.is_some();let reference = app.ui.ref_point.min(8);let geometry = info.as_ref().map(|i| i.page_rect);+ // One ruler guide selected: X (vertical guide) or Y (horizontal guide) is where it is.+ let guide = panels::guide_field(app);group(ui, "reference", 26.0, |ui, rect| {let proxy = Rect::from_center_size(rect.center(), vec2(26.0, 26.0));if let Some(point) = properties::ref_point_proxy(ui, proxy, reference) {@@ -81,10 +83,17 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) {for (column, (label, id, key, index)) in fields.into_iter().enumerate() {let x = column as f32 * 108.0;cell(ui, rect, x, row, 14.0, true, |ui| widgets::caption_w(ui, label, 14.0));- let value = values.map(|v| v[index]);- if let Some(v) = cell(ui, rect, x + 15.0, row, 86.0, selected, |ui| {- NumField::measure(id, value, units).width(86.0).spinner().enabled(selected).show(ui)+ let on_guide = guide.filter(|g| g.row() == index);+ let value = if guide.is_some() { on_guide.map(|g| g.value) } else { values.map(|v| v[index]) };+ let enabled = selected || on_guide.is_some();+ let unit = on_guide.map_or(units, |g| g.unit);+ if let Some(v) = cell(ui, rect, x + 15.0, row, 86.0, enabled, |ui| {+ NumField::measure(id, value, unit).width(86.0).spinner().enabled(enabled).show(ui)}) {+ if let Some(g) = on_guide {+ let _ = app.run("guide.move", g.move_to(v));+ continue;+ }set.insert(key.into(), json!(v));if constrain&& column == 1diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex 7c40f3b1b..f2229b604 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -117,6 +117,49 @@ pub fn sel_tint(app: &DesignApp, stroke: bool) -> f32 {st.selection.items.first().and_then(|id| st.doc.item(*id)).map_or(1.0, |it| if stroke { it.stroke.tint } else { it.fill.tint })}+/// The one selected ruler guide, as the X field (vertical guide) or Y field (horizontal guide)+/// of the Control and Properties panels shows it: measured as the rulers measure, from the zero+/// point (and the page, when rulers restart per page), in that ruler's units.+#[derive(Clone, Copy, Debug)]+pub struct GuideField {+ pub guide: designcraft_doc::GuideSel,+ pub orientation: designcraft_doc::Orientation,+ /// Points from the ruler origin.+ pub value: f64,+ /// Where `value` 0 is: a spread x for a vertical guide, a y for a horizontal one.+ pub origin: f64,+ pub unit: designcraft_geom::Unit,+}++impl GuideField {+ /// Which field shows it: 0 for X, 1 for Y.+ pub fn row(&self) -> usize {+ match self.orientation {+ designcraft_doc::Orientation::Vertical => 0,+ designcraft_doc::Orientation::Horizontal => 1,+ }+ }+ /// The `guide.move` params that put it at `value` (as the field reads).+ pub fn move_to(&self, value: f64) -> Value {+ let g = self.guide;+ json!({"spread": g.spread, "page": g.page, "index": g.index, "position": value + self.origin})+ }+}++/// [`GuideField`] when exactly one ruler guide is selected.+pub fn guide_field(app: &DesignApp) -> Option<GuideField> {+ let st = app.session.active()?;+ let [g] = st.selection.guides.as_slice() else { return None };+ let pg = st.doc.spread(g.spread)?.pages.get(g.page)?;+ let guide = pg.guides.get(g.index)?;+ let (origin, unit) = match guide.orientation {+ designcraft_doc::Orientation::Vertical => (st.doc.ruler_origin(g.spread, guide.position)?.x, st.doc.settings.horizontal_units),+ designcraft_doc::Orientation::Horizontal => (st.doc.ruler_origin(g.spread, pg.x + pg.width / 2.0)?.y, st.doc.settings.vertical_units),+ };+ let value = guide.position - origin;+ value.is_finite().then_some(GuideField { guide: *g, orientation: guide.orientation, value, origin, unit })+}+pub fn sel_info(app: &DesignApp) -> Option<SelInfo> {let st = app.session.active()?;if st.selection.items.is_empty() {diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rsindex 44acf6e2c..399cc34e7 100644--- a/crates/ui-egui/src/panels/properties.rs+++ b/crates/ui-egui/src/panels/properties.rs@@ -59,6 +59,9 @@ fn selection_title(app: &DesignApp, info: &Option<SelInfo>) -> String {if st.selection.text.is_some() {return crate::i18n::tr(&app.ui.language, "Characters").into();}+ if info.is_none() && !st.selection.guides.is_empty() {+ return crate::i18n::tr(&app.ui.language, "Ruler Guide").into();+ }match info {None => crate::i18n::tr(&app.ui.language, "No Selection").into(),Some(i) if i.count > 1 => crate::i18n::tr(&app.ui.language, "Multiple Objects").into(),@@ -106,6 +109,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {quick_actions_text(app, ui);return;}+ if info.is_none() && app.session.active().is_some_and(|st| !st.selection.guides.is_empty()) {+ section(ui, crate::i18n::tr(&app.ui.language, "Transform"), true);+ guide_section(app, ui);+ return;+ }// The Page tool with no objects selected: the page's own settings, as InDesign's.if info.is_none() && app.session.tool_id() == "page" {let page = app.session.active().and_then(|st| st.selection.page).or_else(|| crate::canvas::current_page(app));@@ -613,6 +621,27 @@ fn transform_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) {}}+/// Properties › Transform for selected ruler guides: X for one vertical guide, Y for one+/// horizontal guide; with several guides both fields are empty.+fn guide_section(app: &mut DesignApp, ui: &mut Ui) {+ let guide = super::guide_field(app);+ let b = block(ui, 2.0 * FIELD_H + 4.0);+ for (row, (label, key)) in [("X:", "gx"), ("Y:", "gy")].into_iter().enumerate() {+ let yy = row as f32 * 25.0;+ let on = guide.filter(|g| g.row() == row);+ place(ui, sub(b, 40.0, yy, 18.0, FIELD_H), |ui| widgets::caption_w(ui, label, 18.0));+ let typed = place(ui, sub(b, 59.0, yy, 135.0, FIELD_H), |ui| {+ if on.is_none() {+ ui.disable();+ }+ measure(ui, key, on.map(|g| g.value), on.map_or_else(|| units(app), |g| g.unit), 135.0)+ });+ if let (Some(v), Some(g)) = (typed, on) {+ let _ = app.run("guide.move", g.move_to(v));+ }+ }+}+/// Properties › Transform, below X/Y/W/H as in InDesign: rotation and shear angles beside the/// X and Y scales (totals, as Transformations are Totals), then rotate a quarter turn and flip.fn transform_angles(app: &mut DesignApp, ui: &mut Ui, rp: u8) {diff --git a/docs/target-app-parity.md b/docs/target-app-parity.mdindex cdd6da689..89fe4d401 100644--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@ -283,7 +283,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level- Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands.- Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus.- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands.-- Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands.+- Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; selected like objects with the Selection tools (click, Shift-click, a marquee that touches no object, Edit › Select All Guides ⌥⌘G), drawn highlighted, moved together by dragging or the arrow keys, deleted with Delete, and placed exactly with the X or Y field of the Control and Properties panels; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands.- Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands.- Linked text files: `file.place {link: true}` or Preferences › File Handling › Create Links When Placing Text Files keeps a placed .docx/.rtf/.txt story linked to its file (path, size and hash, and the style map and conflict option used). The Links panel shows it OK / Modified / Missing; Update imports the file again into the same frames and thread with the saved style map, replacing edits made in the layout (the Links panel and menu ask first; the `links.update` command updates and returns a warning; undoable); Relink, Go To and Unlink. Saved in the native format; IDML exports the text unlinked.- Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`. Type › Reload Fonts (`font.reload`) scans the font folders again and reads again the installed font files edited or removed since they were read, then recomposes the open documents: a font installed or edited while DesignCraft runs needs no restart (#328, #547). InDesign notices such changes by itself.