diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index d60a898fd1..507caffe10 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1398097510, "producer_workflow_id": 430275079, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 3b79c61ba5..6cc6f885a2 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,12 +34,26 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: vectorcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} # No secrets: inherit or raw platform values in this caller. Only the isolated native # callee job may bind the release environment and export its keys; that environment must # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 989d6974dd..0e963e43e1 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: vectorcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 @@ -32,3 +32,4 @@ jobs: # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/apps/vectorcraft/src/profile_root.rs b/apps/vectorcraft/src/profile_root.rs index f8cf51eaeb..7f46e77766 100644 --- a/apps/vectorcraft/src/profile_root.rs +++ b/apps/vectorcraft/src/profile_root.rs @@ -175,7 +175,16 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let child = canonical_future(&chosen.join(name))?; + let target = chosen.join(name); + match std::fs::symlink_metadata(&target) { + Ok(metadata) if !metadata.is_dir() => { + return Err(format!("the nightly {label} must be a directory inside its selected profile")); + } + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")), + } + let child = canonical_future(&target)?; if child == chosen || !child.starts_with(&chosen) { return Err(format!("the nightly {label} must stay inside its selected profile")); } @@ -192,11 +201,86 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> { }; for entry in entries { let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - private_subdirectory(root, entry.file_name(), "profile entry")?; + let path = entry.path(); + let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + // Settings and session state are ordinary files, not directories. Keep the existing + // directory-boundary check for folders (including the known folder-only entries). + let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); + if metadata.is_file() && !folder_only { + private_regular_file(&path, &metadata)?; + } else { + private_subdirectory(root, entry.file_name(), "profile entry")?; + } } Ok(()) } +/// Persisted files must have their own ordinary file identity, not an alias to other data. +fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + if metadata.nlink() != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(all(windows, feature = "wgpu"))] + { + use winsafe::{HFILE, co}; + let (file, _) = HFILE::CreateFile( + path.to_str().ok_or("the nightly profile file path is not textual")?, + co::GENERIC::default(), + Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), + None, + co::DISPOSITION::OPEN_EXISTING, + co::FILE_ATTRIBUTE::NORMAL, + Some(co::FILE_FLAG::OPEN_REPARSE_POINT), + None, + None, + ) + .map_err(|e| e.to_string())?; + let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; + if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) || info.dwFileAttributes.has(co::FILE_ATTRIBUTE::DIRECTORY) { + return Err("the nightly profile file must not be an alias or directory".into()); + } + if info.nNumberOfLinks != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(all(windows, not(feature = "wgpu")))] + { + use std::os::windows::fs::MetadataExt as _; + const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 { + return Err("the nightly profile file must not be an alias or directory".into()); + } + } + let _ = (path, metadata); + Ok(()) +} + +const PROFILE_FOLDERS: [&str; 18] = [ + "Data Recovery", + "Fonts", + "logs", + "Launch", + "Color Profiles", + "Plug-ins", + "Scripts", + "Startup Scripts", + "Metadata Templates", + "New Document Profiles", + "Proof Setups", + "Script Data", + "PDF Presets", + "Swatches", + "Graphic Styles", + "Symbols", + "Brushes", + "Libraries", +]; + /// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to /// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated /// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile. @@ -557,6 +641,31 @@ mod tests { assert!(result.unwrap_err().contains("not writable")); } + #[test] + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + let fixture = Fixture::new(); + for platform in PLATFORMS { + let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); + assert_eq!(fixture.check(platform, &private).unwrap(), private); + for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(fixture.check(platform, &private).unwrap(), private); + assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data"); + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + } + } + #[test] fn the_platform_case_rules_are_the_file_systems_ones() { let fixture = Fixture::new(); diff --git a/crates/cad/src/expansion_test.rs b/crates/cad/src/expansion_test.rs new file mode 100644 index 0000000000..f5ae09e915 --- /dev/null +++ b/crates/cad/src/expansion_test.rs @@ -0,0 +1,22 @@ +use std::cell::Cell; + +thread_local! { + static USED: Cell = const { Cell::new(0) }; +} + +pub(crate) fn initial_used() -> u64 { + USED.with(Cell::get) +} + +pub(crate) fn with_used(used: u64, action: impl FnOnce() -> T) -> T { + struct Reset<'a>(&'a Cell, u64); + impl Drop for Reset<'_> { + fn drop(&mut self) { + self.0.set(self.1); + } + } + USED.with(|value| { + let _reset = Reset(value, value.replace(used)); + action() + }) +} diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index d951e92681..d46275a74c 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -588,6 +588,9 @@ impl<'a> Walk<'a> { clip_tests: 0, warnings: vec![], nest: 0, + #[cfg(test)] + symbol_nodes: crate::expansion_test::initial_used(), + #[cfg(not(test))] symbol_nodes: 0, generated: 0, scratch: None, @@ -740,7 +743,6 @@ impl<'a> Walk<'a> { } Some(None) => {} None => { - self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; self.warn(SYMBOLS_LEFT_OUT); } } diff --git a/crates/cad/src/hpgl/write/tests.rs b/crates/cad/src/hpgl/write/tests.rs index b371c832db..12bfd93c7d 100644 --- a/crates/cad/src/hpgl/write/tests.rs +++ b/crates/cad/src/hpgl/write/tests.rs @@ -870,6 +870,31 @@ fn symbols_nested_too_deep_are_left_out_with_a_warning() { assert_eq!(text(&out), "IN;PU;SP0;"); } +#[test] +fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() { + let mut d = doc_with(|_| vec![]); + let leaf = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) }); + let mut first = None; + for name in ["big", "small"] { + let id = d.alloc_id(); + first.get_or_insert(id); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let mut expected = d.clone(); + expected.remove(first.unwrap()).unwrap(); + crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || { + let actual = plot(&d, &opts(&d)); + let control = plot(&expected, &opts(&expected)); + assert!(actual.warnings.iter().any(|w| w == SYMBOLS_LEFT_OUT), "{:?}", actual.warnings); + assert_ne!(text(&control), "IN;PU;SP0;"); + assert_eq!(text(&actual), text(&control), "HP-GL keeps the later fitting instance"); + }); +} + /// A symbol instance stained by its fill draws in the stained color. #[test] fn a_stained_symbol_instance_takes_its_stain() { diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 8aefe61a0d..b54d9022bf 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -23,6 +23,8 @@ //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. mod aci; +#[cfg(test)] +mod expansion_test; pub mod hpgl; pub mod import; mod scene; diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 700632313e..26025f2544 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -561,8 +561,10 @@ impl<'a> Scene<'a> { extents: None, opacity: 1.0, nest: 0, - // Tests spend all but a million of it up front. - symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 }, + #[cfg(test)] + symbol_nodes: crate::expansion_test::initial_used(), + #[cfg(not(test))] + symbol_nodes: 0, } } @@ -711,7 +713,6 @@ impl<'a> Scene<'a> { } Some(None) => {} None => { - self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; self.warn(SYMBOLS_LEFT_OUT); } } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index b2d5d4db3e..dd80644279 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1503,11 +1503,36 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { let art = Node::group(d.alloc_id(), children); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) }); } - let out = export(&d, &opts(&d)).unwrap(); + let out = crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000, || export(&d, &opts(&d)).unwrap()); assert!(entities(&out).is_empty()); assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings); } +#[test] +fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() { + let mut d = doc_with(|_| vec![]); + let leaf = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 40.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) }); + let mut first = None; + for name in ["big", "small"] { + let id = d.alloc_id(); + first.get_or_insert(id); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let mut expected = d.clone(); + expected.remove(first.unwrap()).unwrap(); + crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || { + let actual = export(&d, &opts(&d)).unwrap(); + let control = export(&expected, &opts(&expected)).unwrap(); + assert!(actual.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", actual.warnings); + assert!(!entities(&control).is_empty()); + assert_eq!(kinds(&actual), kinds(&control), "DXF keeps the later fitting instance"); + }); +} + #[test] fn export_bytes_match_shared_writer_goldens() { use std::path::PathBuf; diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index 7a39d6cbb2..4038d04b42 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -192,14 +192,18 @@ pub enum Arrowhead { /// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as /// the other heads. LineArrow, + /// A slender filled head, a little over half as wide as it is long, whose sides bend in + /// halfway back, with a V-shaped notch in its back: the arrow of mathematical diagrams. + NotchedArrow, /// A head the user drew, with its art. Custom(Arc), } impl Arrowhead { /// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks). - pub const ALL: [Arrowhead; 41] = [ + pub const ALL: [Arrowhead; 42] = [ Arrowhead::Arrow, + Arrowhead::NotchedArrow, Arrowhead::ArrowOpen, Arrowhead::LineArrow, Arrowhead::Barbed, @@ -322,6 +326,7 @@ impl Arrowhead { Arrowhead::TriangleBar => "Triangle to Bar", Arrowhead::Oval => "Oval", Arrowhead::LineArrow => "Line Arrow", + Arrowhead::NotchedArrow => "Notched Arrow", Arrowhead::Custom(_) => "Custom", } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index c91348d57f..787c864b2f 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -316,7 +316,7 @@ fn profile_presets_round_trip_their_ids() { #[test] fn arrowhead_names_are_stable_and_every_one_is_listed_once() { // Saved files store these names: they may only ever be appended to. - const SAVED: [&str; 41] = [ + const SAVED: [&str; 42] = [ "Triangle", "TriangleOpen", "Circle", @@ -358,6 +358,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() { "TriangleBar", "Oval", "LineArrow", + "NotchedArrow", ]; for name in SAVED { let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap(); diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index 1047e4d0dd..bd1511ab8c 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -289,6 +289,8 @@ fn local_stop(kind: &Arrowhead) -> Stop { Arrowhead::DoubleSlash => Stop::At(1.05), Arrowhead::DoubleArrow => Stop::At(1.7), Arrowhead::HalfCircle => Stop::At(1.0), + // Between the bend in its sides and its notch, where it is wider than the line at 100 %. + Arrowhead::NotchedArrow => Stop::At(2.7), Arrowhead::Concave => Stop::At(2.6), Arrowhead::Hexagon => Stop::At(HEX / 2.0), _ => Stop::At(2.0), @@ -395,6 +397,9 @@ fn local(kind: &Arrowhead) -> BezPath { let t = FRAC_1_SQRT_2; poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]); } + // Barbs 1.2 out at the back; each side bends in at (2.1, ±0.5), as wide as the line at + // 100 %, so the sides are concave; the notch reaches 0.7 into the back. + Arrowhead::NotchedArrow => poly(&mut p, &[(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)]), Arrowhead::Custom(c) => p = c.path.to_bezpath(), // The first ten are drawn by `shape`. Arrowhead::Triangle diff --git a/crates/effects/src/stroke/tests_arrows.rs b/crates/effects/src/stroke/tests_arrows.rs index a32a70245b..2a54ddb462 100644 --- a/crates/effects/src/stroke/tests_arrows.rs +++ b/crates/effects/src/stroke/tests_arrows.rs @@ -4,20 +4,26 @@ use kurbo::{BezPath, PathEl, Point, Shape}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer}; +use vectorcraft_doc::{ArrowAlign, Arrowhead, LineCap, StrokeLayer}; -use super::stroke_pieces; +use super::{line_outline, stroke_pieces}; /// A 2 pt line along +x ending at (100, 0) with `kind` at its end, tip on the end point: heads /// of weight 2, so 8 long and 8 wide. fn head(kind: Arrowhead) -> super::Arrow { + head_and_line(kind, LineCap::Butt).0 +} + +/// [`head`] and the outline of the line under it, drawn with `cap`. +fn head_and_line(kind: Arrowhead, cap: LineCap) -> (super::Arrow, BezPath) { let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); - st.end_arrow = Some(kind); - st.arrow_align = ArrowAlign::Tip; + (st.end_arrow, st.arrow_align, st.cap) = (Some(kind), ArrowAlign::Tip, cap); let mut l = BezPath::new(); l.move_to((0.0, 0.0)); l.line_to((100.0, 0.0)); - stroke_pieces(&l, &st).heads.remove(0) + let mut p = stroke_pieces(&l, &st); + let line = line_outline(&p.line, &st, st.width, 1e-3); + (p.heads.remove(0), line) } /// The outline's closed contours as polygons (curves flattened). @@ -105,6 +111,53 @@ fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() { } } +#[test] +fn the_notched_arrow_is_slender_with_concave_sides_and_a_v_notch() { + // Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt. + let h = head(Arrowhead::NotchedArrow); + let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y); + // Six corners: the tip, a bend in each side, a barb on each side and the notch between them. + let pts: Vec = contours(&h.outline).concat(); + let corners = [(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)].map(|(x, y)| at(x, y)); + assert_eq!(pts.len(), corners.len(), "{pts:?}"); + for c in corners { + assert!(pts.iter().any(|p| p.distance(c) < 1e-9), "corner {c:?} in {pts:?}"); + } + for side in [1.0, -1.0] { + // Concave: at the bend, the straight line from the tip to the barb (0.63 out) is outside. + assert_eq!(h.outline.winding(at(2.1, side * 0.6)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(2.1, side * 0.45)), 0, "side {side}"); + // Slender: 2.4 units across at the barbs, not the 4 of the other arrows. + assert_eq!(h.outline.winding(at(3.9, side * 1.2)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(3.9, side * 1.1)), 0, "side {side}"); + } + // Open in the notch, solid in front of it. + assert_eq!(h.outline.winding(at(3.5, 0.0)), 0); + assert_ne!(h.outline.winding(at(3.1, 0.0)), 0); + // The line stops between the bend and the notch, 2.7 units back from the tip. + assert!((h.inset - 5.4).abs() < 1e-9, "inset {}", h.inset); +} + +#[test] +fn the_line_under_the_notched_arrow_stays_inside_it_in_front_of_the_notch() { + // With every cap, no part of the 2 pt line between the notch and the tip shows beside the + // head, though the head is barely wider than the line at its bends. + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let (h, line) = head_and_line(Arrowhead::NotchedArrow, cap); + let mut covered = 0; + for i in 0..=132 { + for j in -25..=25 { + let p = Point::new(100.0 - 6.6 + f64::from(i) * 0.05, f64::from(j) * 0.04); + if line.winding(p) != 0 { + assert_ne!(h.outline.winding(p), 0, "{cap:?}: the line shows at {p:?}"); + covered += 1; + } + } + } + assert!(covered > 500, "{cap:?}: the line reaches under the head ({covered} samples)"); + } +} + #[test] fn half_arrows_barb_on_their_own_side() { // Pointing along +x on a y-down page, left is −y. diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 4fb4537ee4..d319e0d2a4 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -253,6 +253,8 @@ pub(crate) fn item_target(s: &Session, p: &Value, cmd: &str) -> Result Result { let aligned = aligned(p, cmd)?; + // Read `target` whatever names the objects, so that a bad one is refused with `ids` or `id` too. + let contents = targets_contents(p)?; match p.get(key) { Some(Value::Null) => Ok(ItemTarget::Top), Some(v) => v @@ -260,7 +262,7 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re .map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned }) .ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))), // The active item is a row of the first selected object's own stack. - None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top), + None if p.get("ids").is_some() || p.get("id").is_some() || contents => Ok(ItemTarget::Top), // A row of a graph design's art in a series stands for nothing: the commands leave that art out. None if s.active().and_then(|st| st.selection.subjects().first().map(|id| super::graph::is_design_art(&st.doc, *id))) == Some(true) => { Ok(ItemTarget::Top) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 0606ba0130..b8136e8cf5 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -945,6 +945,10 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; let for_tool = tool_color_params(s, p, cmd, !fill)?; let p = for_tool.as_ref().unwrap_or(p); + // A bad `target` or `aligned` is refused for every kind of target: selected characters take + // the paint before `item_target` reads either. + super::appearance::aligned(p, cmd)?; + super::appearance::targets_contents(p)?; let focus = switch_or(p, "focus", true, cmd)?; // An opacity alone places no gradient, so `span` may only be "object" with it. let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; @@ -1470,8 +1474,6 @@ fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 38ce7b6a0d..fd88ff8e27 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -513,6 +513,23 @@ fn a_bad_target_is_refused_with_an_id_or_selected_characters() { } } +/// The other commands that name their appearance item the same way refuse a bad `target` with an +/// `id` or `ids` too, and leave the document alone; a good one still edits the object. +#[test] +fn a_stroke_edit_refuses_a_bad_target_with_an_id() { + let mut s = session(); + let r = rect(&mut s, 10.0); + select(&mut s, &[r]); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"weight": 9, "target": "content", "id": r.0}), json!({"weight": 9, "target": "content", "ids": [r.0]})] { + let e = s.execute("stroke.set", &p).unwrap_err(); + assert!(e.to_string().contains("`target` must be"), "{p}: {e}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{p}"); + } + s.execute("stroke.set", &json!({"weight": 9, "target": "object", "id": r.0})).unwrap(); + assert_ne!(*s.doc().unwrap().doc, *doc); +} + /// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows /// it; the object's fill item and the other points stay as they were. #[test] diff --git a/crates/engine/src/tests/strokegeom.rs b/crates/engine/src/tests/strokegeom.rs index 524dabef3e..af3eb52936 100644 --- a/crates/engine/src/tests/strokegeom.rs +++ b/crates/engine/src/tests/strokegeom.rs @@ -2,7 +2,7 @@ //! the width-profile presets. use serde_json::json; -use vectorcraft_doc::{ArrowAlign, StrokeLayer, WidthProfile}; +use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer, WidthProfile}; use crate::*; @@ -58,6 +58,19 @@ fn profiles_come_from_the_preset_catalogue() { } } +#[test] +fn the_notched_arrow_survives_the_native_format() { + let (mut s, id) = session_with_line(); + s.execute("stroke.set", &json!({"startArrow": "NotchedArrow", "endArrow": "NotchedArrow"})).unwrap(); + let st = stroke(&s, id); + assert_eq!((st.start_arrow, st.end_arrow), (Some(Arrowhead::NotchedArrow), Some(Arrowhead::NotchedArrow))); + let doc = &s.doc().unwrap().doc; + let text = String::from_utf8(vectorcraft_format::save(doc, true)).unwrap(); + assert_eq!(text.matches("\"NotchedArrow\"").count(), 2, "saved by name"); + let back = vectorcraft_format::load(text.as_bytes()).unwrap(); + assert_eq!(back.node(id).unwrap().appearance.stroke().unwrap(), &stroke(&s, id)); +} + #[test] fn arrow_align_and_profiles_survive_the_native_format() { let (mut s, id) = session_with_line(); diff --git a/crates/text/src/fontdb/wanted.rs b/crates/text/src/fontdb/wanted.rs index 31539737ad..8d72bdc3ab 100644 --- a/crates/text/src/fontdb/wanted.rs +++ b/crates/text/src/fontdb/wanted.rs @@ -35,7 +35,7 @@ impl WantedFonts { pub fn new(fonts: &[WantedFont]) -> Self { let mut by_name: HashMap> = HashMap::new(); for (i, w) in fonts.iter().enumerate() { - let mut names = vec![w.family.to_ascii_lowercase(), norm(&w.family)]; + let mut names = vec![w.family.to_ascii_lowercase(), norm(&w.family), joined(w)]; names.extend(w.installed.as_ref().map(|c| c.to_ascii_lowercase())); names.sort(); names.dedup(); @@ -136,6 +136,22 @@ fn provides(w: &WantedFont, faces: &[FaceStyle]) -> bool { }) { return true; } - // A legacy family with another style: that style of the family. - faces.iter().find(|f| f.keys.legacy.iter().any(|(family, _)| *family == key)).is_some_and(|f| styled(&f.family)) + // A legacy family with another style: that style of the family, among every face of the + // legacy family (in a collection they can be of different families). Once installed, the + // legacy family resolves the name, and `FontDb::canonical` doesn't join it. + let mut legacy = faces.iter().filter(|f| f.keys.legacy.iter().any(|(family, _)| *family == key)).peekable(); + if legacy.peek().is_some() { + return legacy.any(|f| styled(&f.family)); + } + // A family and style split from a PostScript name by an importer that didn't have the font + // (`Gilroy-Black` → Gilroy, Black), as `FontDb::canonical` joins them again: a face whose + // PostScript name is that name, whatever family and style the file gives it. Of a cataloged + // face, `canonical` reads the PostScript name only, so a full name alone isn't enough. + let joined = joined(w); + !sk.is_empty() && faces.iter().any(|f| f.keys.postscript.contains(&joined)) +} + +/// The family and style of `w` as one normalized name (`Gilroy` and `Black` → `gilroyblack`). +fn joined(w: &WantedFont) -> String { + format!("{}{}", norm(&w.family), norm(&w.style)) } diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 4ba72ee107..261cc1c54c 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -1257,3 +1257,64 @@ fn a_name_asked_for_before_its_font_is_installed_finds_it_after_a_rescan() { } let _ = std::fs::remove_dir_all(dir); } + +/// A document names `Gilroy-Black` as the family Gilroy in the style Black. A file whose own family is +/// `Gilroy-Black`, with no style, is that face, once cataloged and in a search of a folder. +#[test] +fn a_search_finds_the_file_of_a_postscript_name_split_into_family_and_style() { + let data = named(&[(3, EN, 1, "Gilroy-Black"), (3, EN, 4, "Gilroy-Black"), (3, EN, 6, "Gilroy-Black")]); + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-split-ps", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Gilroy-Black.ttf"); + std::fs::write(&file, &data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let (face, matched) = db.resolve("Gilroy", "Black").unwrap(); + assert_eq!(matched, FontMatch::Exact, "{face:?}"); + let wanted = |style: &str| WantedFonts::new(&[WantedFont { family: "Gilroy".into(), style: style.into(), installed: None }]); + assert_eq!(wanted("Black").provided_by(&file), [0]); + assert!(wanted("Bold").provided_by(&file).is_empty(), "another style of the family is another file"); + assert!(wanted("").provided_by(&file).is_empty(), "without a style, the family alone is not the PostScript name"); + let _ = std::fs::remove_dir_all(dir); + // The search offers a file only when installing it resolves the name exactly: not when the + // joined name is only a full name, and not when a legacy family of the same name resolves it + // first, to another style. + let cases = [ + ("full-name", vec![(3, EN, 1, "Gilroy Black"), (3, EN, 4, "Gilroy Black"), (3, EN, 6, "GilroyBlk")]), + ( + "legacy", + vec![(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Display"), (3, EN, 17, "Regular"), (3, EN, 6, "Gilroy-Black")], + ), + ]; + for (name, records) in cases { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-split-ps-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join(format!("{name}.ttf")); + std::fs::write(&file, named(&records)).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let exact = db.resolve("Gilroy", "Black").is_some_and(|(_, matched)| matched == FontMatch::Exact); + assert!(!exact, "{name}: installing the file doesn't resolve Gilroy Black exactly"); + assert!(wanted("Black").provided_by(&file).is_empty(), "{name}: so the search doesn't offer it"); + let _ = std::fs::remove_dir_all(dir); + } +} + +/// In a collection whose faces share a legacy family but not a typographic one, the search looks +/// for the style asked for in each face's family, in either order. +#[test] +fn a_search_finds_a_style_among_the_faces_of_a_shared_legacy_family() { + let regular = named(&[(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Text"), (3, EN, 17, "Regular")]); + let black = + named(&[(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Display"), (3, EN, 17, "Black"), (3, EN, 6, "Gilroy-Black")]); + for (order, faces) in [("regular-first", [regular.clone(), black.clone()]), ("black-first", [black.clone(), regular.clone()])] { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-shared-legacy-{order}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("shared.ttc"); + std::fs::write(&file, collection(&faces)).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let (face, matched) = db.resolve("Gilroy", "Black").unwrap(); + assert_eq!(matched, FontMatch::Exact, "{order}: {face:?}"); + let wanted = WantedFonts::new(&[WantedFont { family: "Gilroy".into(), style: "Black".into(), installed: None }]); + assert_eq!(wanted.provided_by(&file), [0], "{order}"); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 66e2eea0b0..5a92f70faa 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -2,7 +2,8 @@ //! //! Add: click a segment to insert an anchor without changing the shape (Alt = delete). //! Delete: click an anchor to remove it, re-fitting the neighbouring curve (Alt = add). -//! Anchor Point: click a smooth anchor → corner; drag an anchor → pull out smooth handles; click a +//! Anchor Point: click a smooth anchor → corner; drag an anchor → pull out smooth handles (Shift +//! pressed once the drag is under way: at 45° steps round the anchor); click a //! handle end → retract that handle only (#2267); drag a handle → move it independently (Shift: at //! 45° steps round its anchor; Alt: link it with the opposite handle, the anchor made smooth, except //! when the Pen lends the tool); drag a segment → reshape the curve, a selected blend's spine's too, @@ -278,6 +279,37 @@ impl AnchorTool { cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) } + /// Where anchor `ai` is in the document a preview edits: the document as the interaction + /// began, since each preview runs on that, otherwise the document `cx` shows. + fn began_anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option { + let d = cx.interaction_doc.unwrap_or(cx.doc); + d.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) + } + + /// Where a blend's spine point `ai` is in the spine a spine edit changes: the spine pinned + /// from the document as the interaction began (otherwise the document `cx` shows), as + /// `object.blend.spine.*` pins it. + fn spine_pos(cx: &ToolContext, id: NodeId, ai: usize) -> Option { + let d = cx.interaction_doc.unwrap_or(cx.doc); + match d.node(id).map(|n| &n.kind) { + Some(vectorcraft_doc::NodeKind::Blend { children, spec }) => { + let (path, _) = vectorcraft_doc::live::pin_spine(children, spec)?; + path.subpaths.first()?.anchors.get(ai).map(|a| a.p) + } + _ => None, + } + } + + /// Where handles pulled out of an anchor to `p` go: with Shift held, at 45° steps round the + /// anchor (`anchor` finds it) from General › Constrain Angle, as the Pen pulls handles out; + /// otherwise, or when the anchor is gone, `p`. + fn pulled_out(cx: &ToolContext, p: Point, shift: bool, anchor: impl FnOnce() -> Option) -> Point { + if !shift { + return p; + } + anchor().map_or(p, |a| a + constrain_angle_from(p - a, 45.0, cx.constrain_angle)) + } + /// Nearest point of this eligible spine, in document coordinates. fn spine_point(path: &vectorcraft_geom::PathData, p: Point, tol: f64) -> Option { path.anchors() @@ -582,10 +614,15 @@ impl Tool for AnchorTool { } let preview = match self.state { State::Idle => return out, - State::Convert { id, si, ai, .. } => Action::Preview( - "path.convertAnchor".into(), - json!({"id": id.0, "subpath": si, "anchor": ai, "to": "smooth", "x": p.x, "y": p.y}), - ), + State::Convert { id, si, ai, .. } => { + // Shift pressed once the drag is under way keeps the pulled-out handles at + // 45° steps; Shift at the press moved the anchor instead (`moving`). + let q = Self::pulled_out(cx, p, ev.mods.shift, || Self::began_anchor_pos(cx, id, si, ai)); + Action::Preview( + "path.convertAnchor".into(), + json!({"id": id.0, "subpath": si, "anchor": ai, "to": "smooth", "x": q.x, "y": q.y}), + ) + } State::Move { id, si, ai, from, start, .. } => { let d = Self::move_delta(cx, start, p, ev.mods.shift); self.measure = Some((p, d.x, d.y)); @@ -598,10 +635,13 @@ impl Tool for AnchorTool { let q = from + d; Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": id.0, "anchor": ai, "x": q.x, "y": q.y})) } - State::SpineConvert { id, ai, .. } => Action::Preview( - "object.blend.spine.convertAnchor".into(), - json!({"id": id.0, "anchor": ai, "to": "smooth", "x": p.x, "y": p.y}), - ), + State::SpineConvert { id, ai, .. } => { + let q = Self::pulled_out(cx, p, ev.mods.shift, || Self::spine_pos(cx, id, ai)); + Action::Preview( + "object.blend.spine.convertAnchor".into(), + json!({"id": id.0, "anchor": ai, "to": "smooth", "x": q.x, "y": q.y}), + ) + } State::SpineHandle { id, ai, out, .. } => { // Shift keeps the handle at 45-degree steps round its anchor, as for // ordinary Anchor Point handles. The spine anchor is a blend point, not diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index b2cbd22c03..9f66d7162c 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -821,6 +821,75 @@ fn anchor_point_shift_drag_moves_the_anchor() { assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 300.0).with_mods(shift)).is_empty()); } +/// Shift pressed once a drag from an anchor is under way keeps the handles it pulls out at 45° +/// steps round the anchor, on a path and on a selected blend's spine; released, it frees them. +#[test] +fn anchor_point_shift_mid_drag_constrains_pulled_out_handles() { + let shift = Mods { shift: true, ..Mods::default() }; + // The handle point a drag's preview gives `cmd`. + let target = |a: &[Action], cmd: &str| match a.last() { + Some(Action::Preview(c, v)) if c == cmd => v["x"].as_f64().zip(v["y"].as_f64()).map(|(x, y)| Point::new(x, y)), + _ => None, + }; + // The rectangle's corner at (100, 100). + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = AnchorTool::new("anchorPoint"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 140.0, 92.0)); + assert_eq!(target(&a, "path.convertAnchor"), Some(Point::new(140.0, 92.0)), "free without Shift: {a:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 140.0, 92.0).with_mods(shift)); + let q = target(&a, "path.convertAnchor").unwrap_or_default(); + assert!((q.y - 100.0).abs() < 1e-9 && q.x > 100.0, "level with the anchor: {a:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 106.0, 140.0).with_mods(shift)); + let q = target(&a, "path.convertAnchor").unwrap_or_default(); + assert!((q.x - 100.0).abs() < 1e-9 && q.y > 100.0, "straight below the anchor: {a:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 106.0, 140.0)); + assert_eq!(target(&a, "path.convertAnchor"), Some(Point::new(106.0, 140.0)), "free again once Shift is up: {a:?}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 106.0, 140.0)), vec![Action::Commit]); + // A selected blend's spine corner at (160, 310). + let (d, _, sel) = blend_spine_doc(false); + let c = cx(&d, &sel, &p); + let mut t = AnchorTool::new("anchorPoint"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 160.0, 340.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 200.0, 318.0).with_mods(shift)); + let q = target(&a, "object.blend.spine.convertAnchor").unwrap_or_default(); + assert!((q.y - 310.0).abs() < 1e-9 && q.x > 160.0, "level with the spine point: {a:?}"); +} + +/// Shift on handles pulled out of an anchor constrains them round the anchor in the document a +/// preview edits (the document as the interaction began), not round where the last preview +/// showed it, so the handles the command makes stay on the 45° steps. +#[test] +fn anchor_point_shift_pulls_out_round_the_anchor_the_preview_edits() { + let shift = Mods { shift: true, ..Mods::default() }; + // The rectangle's corner at (100, 100) as the interaction began. + let (began, id) = doc_with_rect(); + // The document shown: every anchor moved by (10, 20), as a previewed edit left them. + let mut shown = began.clone(); + if let Some(pd) = shown.node_mut(id).and_then(|n| n.path_data_mut()) { + for sp in &mut pd.subpaths { + for a in &mut sp.anchors { + a.p = Point::new(a.p.x + 10.0, a.p.y + 20.0); + } + } + } + let (s, p) = (Selection::default(), paint()); + let mut t = AnchorTool::new("anchorPoint"); + t.pointer(&cx(&began, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + let c = ToolContext { interaction_doc: Some(&began), ..cx(&shown, &s, &p) }; + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 140.0, 92.0).with_mods(shift)); + match a.last() { + Some(Action::Preview(cmd, v)) if cmd == "path.convertAnchor" => { + let y = v["y"].as_f64().unwrap_or(f64::NAN); + assert!((y - 100.0).abs() < 1e-9, "level with the anchor as the interaction began: {a:?}"); + } + other => panic!("expected a path.convertAnchor preview, got {other:?}"), + } +} + /// #3694: Space held mid-drag on a convert moves the anchor, handles and all. #[test] fn anchor_point_space_mid_drag_moves_the_anchor() { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index df93dc6bac..2d2f5e9f4c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -140,7 +140,7 @@ impl VectorcraftApp { momentary: None, selection_box: None, selection_bounds: None, - content_bounds: None, + content_bounds: Vec::new(), variable_rows: None, three_d_exportable: None, pixel_aligned: None, diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 1e1de5ae93..a1ab70c788 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -482,16 +482,32 @@ impl VectorcraftApp { /// The art and the artboards together, the span of the canvas's scroll bars: measured once /// per revision, as the canvas reads it every frame. pub fn content_bounds(&mut self) -> Option { - let st = self.session.active()?; + let index = self.session.active_index()?; + self.content_bounds_of(index) + } + + /// The art and the artboards together of the document at `index`, the size each of its windows' canvases fits + /// and scrolls in: measured once per revision of each open document, as every canvas pass reads it. + pub(crate) fn content_bounds_of(&mut self, index: usize) -> Option { + let docs = self.session.documents(); + let st = docs.get(index)?; let key = (st.uid, st.revision); - if let Some((k, b)) = self.canvas.content_bounds - && k == key - { - return b; + if let Some((_, b)) = self.canvas.content_bounds.iter().find(|(k, _)| *k == key) { + return *b; } + #[cfg(test)] + CONTENT_MEASURES.with(|n| n.set(n.get() + 1)); let boards = st.doc.artboards.iter().map(|a| a.rect).reduce(|r, a| r.union(a)); let b = vectorcraft_geom::union_opt(st.doc.art_bounds(), boards); - self.canvas.content_bounds = Some((key, b)); + // An older revision of this document and the documents that have closed leave the cache. + self.canvas.content_bounds.retain(|((uid, _), _)| *uid != key.0 && docs.iter().any(|d| d.uid == *uid)); + self.canvas.content_bounds.push((key, b)); b } } + +#[cfg(test)] +thread_local! { + /// How many times this thread measured a document's content bounds ([`VectorcraftApp::content_bounds_of`]). + pub(crate) static CONTENT_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6907b7ce17..dfac727639 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -82,8 +82,8 @@ pub struct CanvasCache { pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, /// [`VectorcraftApp::selection_bounds`] for (document uid, revision). pub selection_bounds: Option<((u64, u64), Option)>, - /// [`VectorcraftApp::content_bounds`] for (document uid, revision). - pub content_bounds: Option<((u64, u64), Option)>, + /// [`VectorcraftApp::content_bounds_of`] for (document uid, revision), one entry for each open document. + pub content_bounds: Vec<((u64, u64), Option)>, /// Whether the 3D and Materials panel's Export 3D Object button is available (a selected /// object has a 3D effect that `assets.add3D` exports) for (document uid, revision). pub three_d_exportable: Option<((u64, u64), bool)>, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2efe7e984a..49878cb2d8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -429,13 +429,13 @@ fn scroll_bars(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Op } /// The size of the art and the artboards together, and the artboard Fit Artboard shows (the view's, -/// the first when it has gone). -pub(crate) fn view_target(app: &VectorcraftApp, win: Win) -> ViewTarget { +/// the first when it has gone). The size is measured once per document revision ([`VectorcraftApp::content_bounds_of`]). +pub(crate) fn view_target(app: &mut VectorcraftApp, win: Win) -> ViewTarget { + let all = app.content_bounds_of(win.0); let (Some(st), Some(view)) = (app.session.documents().get(win.0), doc_windows::view(app, win)) else { return ViewTarget::new(Size::new(1.0, 1.0)); }; - let boards = st.doc.artboards.iter().map(|a| a.rect).reduce(|r, a| r.union(a)); - let target = ViewTarget::new(document_size(vectorcraft_geom::union_opt(st.doc.art_bounds(), boards))); + let target = ViewTarget::new(document_size(all)); match st.doc.artboards.get(view.artboard).or(st.doc.artboards.first()) { Some(a) => target.artboard(a.rect), None => target, diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 48f036012e..480497d7b9 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -987,7 +987,15 @@ fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, view: &CanvasV let old = CanvasView::new(old_rect, Point::new(k.cx, k.cy), k.zoom).rotation(rotation); let a = view.to_screen(old.to_doc(old_rect.min)); let b = view.to_screen(old.to_doc(old_rect.max)); - let placed = snapped_rect(a, b - a, painter.pixels_per_point()); + // A frame shown for the view, size and pixel density it was rendered for lands on + // whole device pixels so its strokes stay sharp. A cached frame shown while the + // canvas is panned, zoomed, resized or moved to another display keeps its exact + // document mapping until the replacement arrives. + let device_ppp = painter.pixels_per_point(); + let current = (k.ppp - device_ppp).abs() < 1e-4 + && (k.cx, k.cy, k.zoom) == (view.center.x, view.center.y, view.zoom) + && (old_rect.size() - rect.size()).abs().max_elem() < 1.0; + let placed = if current { snapped_rect(a, b - a, device_ppp) } else { egui::Rect::from_min_max(a, b) }; painter.image(tex.id(), placed, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } // The view turned after the last frame was rendered, and the worker renders the frame at diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3f1eddb392..3fc37f6433 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6700,3 +6700,42 @@ fn a_move_stops_snapping_to_guides_hidden_during_it() { assert!((centre - xf.to_doc(near).x).abs() < 1e-4 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}"); } } + +/// The canvas measures the art and the artboards once per document revision, not in every pass: frames that change +/// nothing measure nothing, an edit measures once, and two open documents keep a measure each. +#[test] +fn the_canvas_measures_the_document_once_per_revision() { + let measures = || crate::app::view::CONTENT_MEASURES.with(std::cell::Cell::get); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..20 { + let x = f64::from(i) * 15.0; + app.session.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 10, "height": 10})).unwrap(); + } + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + let before = measures(); + for _ in 0..10 { + app_step(&mut app, &ctx, vec![]); + } + assert_eq!(measures() - before, 0, "frames that change nothing measure nothing"); + app.session.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 10, "height": 10})).unwrap(); + for _ in 0..5 { + app_step(&mut app, &ctx, vec![]); + } + assert_eq!(measures() - before, 1, "an edit measures once"); + let win = crate::doc_windows::current(&app).unwrap(); + let size = super::view_target(&mut app, win).document; + assert!(size.width >= 510.0 && size.height >= 410.0, "the new rectangle is in the size: {size:?}"); + + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let before = measures(); + for _ in 0..5 { + for index in 0..2 { + let _ = super::view_target(&mut app, (index, 0)); + } + } + assert_eq!(measures() - before, 1, "the new document is measured once, and the first keeps its measure"); +} diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 9848d86f1a..6a922f0c41 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -1,9 +1,11 @@ use super::{ROTATE_VIEW_ANGLES, Ui, VectorcraftApp, json}; -use craft::behavior::IconId; use craft::behavior::kurbo::Size; +use craft::behavior::{CanvasView, IconId}; use craft::ui::bars::{Bar, BarKind, StatusMessage, StatusProgress}; use craft::ui::buttons::{Button, IconButton}; -use craft::ui::contract::{Bind, BodyCx, Entry, Gap, LabelKind, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger}; +use craft::ui::contract::{ + Bind, BodyCx, Entry, Gap, LabelKind, MemoProps, MemoView, Outbox, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger, +}; use craft::ui::display::{Divider, Elide, Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row; @@ -22,33 +24,31 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); } let print = app.print_ppi(); - let nab = app.session.active().map(|d| d.doc.artboards.len()).unwrap_or(0); + let st = app.session.active(); + let nab = st.map_or(0, |d| d.doc.artboards.len()); let cur = crate::panels::artboards::selected(app, nab); - // PLAN: assumed Artboard::rect has `width()` and `height()`. - let document = - app.session.active().and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height())); - let boards: Vec> = app - .session - .active() - .map(|d| d.doc.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect()) - .unwrap_or_default(); - let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); let view = app.view(); let rotation = view.map_or(0.0, |v| v.rotation); + let lang = crate::i18n::current(); + let canvas_view = app.canvas_view(); + // PLAN: assumed Artboard::rect has `width()` and `height()`. + let document = st.and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height())); + let scaling = app.ui_scaling(); let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX); // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 // turns the -0 of a small negative angle into 0. - let angle = format!("{}°", rotation.round() + 0.0); + let degrees = rotation.round() + 0.0; + let revision = st.map(|d| (d.uid, d.revision)); + let artboards = st.map_or(&[][..], |d| d.doc.artboards.as_slice()); + let mut picks = Vec::new(); let shows: Vec> = StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect(); let unit = app.session.general_unit(); - let lang = crate::i18n::current(); let render = crate::i18n::tr_ctx(lang, "diagnostics", "render"); let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui"); let busy = busy_labels(app); - let (mut zoom_to, mut rotate_to, mut go, mut show_pick, mut stop) = (None, None, None, None, false); - let mut invalid_zoom = None; + let (mut show_pick, mut stop) = (None, false); let mut snapping = None; // Convenience controls leave first: direct toggles, then the menu. The existing timings and pointer position // retain their priority, and all trailing groups leave before the navigation, info field or message narrows. @@ -90,56 +90,21 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { }; // PLAN: assumed VectorcraftApp::canvas_view() -> Option (cv.S4) and the label msgid "Status Bar". Bar::new(tl!("Status Bar"), BarKind::Status).trailing(readouts).show(ui, |ui, _| { - let zoom = Field::new(tl!("Zoom")) - .side(SideLabel::new().kind(LabelKind::Hidden)) - .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui)); - // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. - if let Some(zoom) = zoom.inner { - if let Some(view) = zoom.view.committed() { - zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, app.ui_scaling()), print)); - } - invalid_zoom = zoom.invalid_zoom.map(|invalid| invalid.message(&Env::of(ui))); - } - Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { - // Entries are keyed by index: an angle is not a hashable value. - rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) - .placeholder(angle.clone()) - .look(SelectLook::Filled) - .enabled(view.is_some()) - .show(ui) - .events - .committed() - .copied(); - }); - Divider::vertical().show(ui); - for (icon, to, tip, enabled) in - [("chevrons_left", "first", tl!("First Artboard"), cur > 0), ("chevron_left", "previous", tl!("Previous Artboard"), cur > 0)] - { - if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { - go = Some(json!(to)); - } - } - Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { - // With no document the navigator shows a dash, as the info readout does. - if let Some(i) = Select::new(tl!("Artboard"), Bind::given(cur), &boards) - .placeholder("\u{2013}") - .look(SelectLook::Filled) - .enabled(nab > 0) - .show(ui) - .events - .committed() - .copied() - { - go = Some(json!(i)); - } - }); - for (icon, to, tip, enabled) in - [("chevron_right", "next", tl!("Next Artboard"), cur + 1 < nab), ("chevrons_right", "last", tl!("Last Artboard"), cur + 1 < nab)] - { - if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { - go = Some(json!(to)); - } - } + let navigation = Navigation { + view: canvas_view, + document, + scaling, + print, + has_view: view.is_some(), + turned, + degrees, + cur, + revision, + artboards, + lang, + picked: Outbox::new(&mut picks), + }; + let _ = MemoView::new("status-bar-navigation", navigation, show_navigation).show(ui); Divider::vertical().show(ui); // An empty readout shows a dash. let shown = if info.is_empty() { "\u{2013}" } else { info.as_str() }; @@ -174,6 +139,16 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some((id, params)) = snapping { crate::menus::invoke(app, id, params); } + // The last choice of each kind counts, as the controls report one choice of each in a pass. + let (mut zoom_to, mut invalid_zoom, mut rotate_to, mut go) = (None, None, None, None); + for pick in picks { + match pick { + NavigationPick::Zoom(zoom) => zoom_to = Some(zoom), + NavigationPick::InvalidZoom(message) => invalid_zoom = Some(message), + NavigationPick::Rotate(i) => rotate_to = Some(i), + NavigationPick::Artboard(to) => go = Some(to), + } + } // It fails only without a document, when there is no view to turn or zoom. if let Some(zoom) = zoom_to { app.run("view.setZoom", json!({"zoom": zoom})).ok(); @@ -196,6 +171,118 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// What the status bar's navigation controls read: the Zoom field, the Rotation menu and the artboard navigator. The +/// bar replays them while these hold still and nothing reaches them (`MemoView`), as most frames only move the +/// readouts. +#[derive(MemoProps)] +struct Navigation<'a> { + /// The canvas view the Zoom field shows and edits. + view: Option, + /// The size of the artboard the navigator shows, which the Zoom field fits. + document: Size, + /// UI Scaling, which divides the canvas view's zoom. + scaling: f32, + /// The density zoom percentages count from ([`VectorcraftApp::print_ppi`]). + print: Option, + /// Whether the active document has a view to turn. + has_view: bool, + /// The Rotate View preset the view is turned to, else `usize::MAX`. + turned: usize, + /// The view's angle in whole degrees, shown when it is between the presets. + degrees: f64, + /// The artboard the navigator shows. + cur: usize, + /// The active document's uid and revision. + revision: Option<(u64, u64)>, + #[memo_props(covered_by = "revision", reason = "a document's uid and revision change with every edit of it")] + artboards: &'a [vectorcraft_doc::Artboard], + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, + /// What the controls chose in the pass. + picked: Outbox<'a, NavigationPick>, +} + +/// A choice made in the status bar's navigation controls ([`Navigation`]). +enum NavigationPick { + /// The view's zoom percentage the Zoom field committed (`view.setZoom`). + Zoom(f64), + /// The message of a zoom the Zoom field could not read. + InvalidZoom(String), + /// The Rotate View preset chosen (an index into [`ROTATE_VIEW_ANGLES`]). + Rotate(usize), + /// The `index` of `view.goToArtboard`: an artboard's index, or first, previous, next or last. + Artboard(serde_json::Value), +} + +/// The Zoom field, the Rotation menu and the artboard navigator of the status bar, from [`Navigation`]. +fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::NAVIGATION_RUNS.with(|n| n.set(n.get() + 1)); + let (view, document) = (p.view, p.document); + let zoom = Field::new(tl!("Zoom")) + .side(SideLabel::new().kind(LabelKind::Hidden)) + .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).show(ui)); + // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. + if let Some(zoom) = zoom.inner { + if let Some(view) = zoom.view.committed() { + let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print); + p.picked.send(NavigationPick::Zoom(percent)); + } + if let Some(invalid) = zoom.invalid_zoom { + p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui)))); + } + } + let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); + let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view); + let mut rotate_to = None; + Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { + // Entries are keyed by index: an angle is not a hashable value. + rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) + .placeholder(angle.clone()) + .look(SelectLook::Filled) + .enabled(has_view) + .show(ui) + .events + .committed() + .copied(); + }); + if let Some(i) = rotate_to { + p.picked.send(NavigationPick::Rotate(i)); + } + Divider::vertical().show(ui); + let (cur, nab) = (p.cur, p.artboards.len()); + for (icon, to, tip, enabled) in + [("chevrons_left", "first", tl!("First Artboard"), cur > 0), ("chevron_left", "previous", tl!("Previous Artboard"), cur > 0)] + { + if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { + p.picked.send(NavigationPick::Artboard(json!(to))); + } + } + let boards: Vec> = p.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect(); + let mut go = None; + Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { + // With no document the navigator shows a dash, as the info readout does. + go = Select::new(tl!("Artboard"), Bind::given(cur), &boards) + .placeholder("\u{2013}") + .look(SelectLook::Filled) + .enabled(nab > 0) + .show(ui) + .events + .committed() + .copied(); + }); + if let Some(i) = go { + p.picked.send(NavigationPick::Artboard(json!(i))); + } + for (icon, to, tip, enabled) in + [("chevron_right", "next", tl!("Next Artboard"), cur + 1 < nab), ("chevrons_right", "last", tl!("Last Artboard"), cur + 1 < nab)] + { + if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { + p.picked.send(NavigationPick::Artboard(json!(to))); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -272,6 +359,44 @@ mod tests { } } + thread_local! { + /// How many times this thread ran the status bar's navigation controls ([`show_navigation`]). + pub(super) static NAVIGATION_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// Frames that change nothing the navigation controls show replay them instead of laying them out again; a new + /// zoom or a new artboard runs them once, and they show it. + #[test] + fn idle_frames_replay_the_navigation_controls() { + let runs = || NAVIGATION_RUNS.with(std::cell::Cell::get); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let mut panel = Panel::new(app, status_bar); + panel.room(egui::vec2(1200.0, 300.0)); + panel.frame(); + panel.frame(); + let before = runs(); + for _ in 0..10 { + panel.frame(); + } + assert_eq!(runs() - before, 0, "idle frames run the navigation controls no more"); + panel.app().run("view.setZoom", json!({"zoom": 200})).unwrap(); + panel.frame(); + panel.frame(); + assert!(runs() > before, "a new zoom runs them again"); + assert_eq!(panel.value("Zoom").as_deref(), Some("200%"), "and the field shows it"); + panel.app().run("artboard.new", json!({"x": 400, "y": 50, "width": 100, "height": 80, "name": "Back"})).unwrap(); + panel.frame(); + panel.frame(); + let before = runs(); + for _ in 0..10 { + panel.frame(); + } + assert_eq!(runs() - before, 0, "idle frames after an edit run them no more"); + assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard"); + } + #[test] fn with_no_document_the_artboard_navigator_shows_a_dash() { let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 9bff24d03e..dd09594490 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -404,7 +404,7 @@ impl BulletsDialog { let entries = [Entry::new(0usize, tl!("Left")), Entry::new(1, tl!("Right"))]; let current = self.fields.get("listAlign").and_then(Value::as_str).and_then(|a| ALIGNS.iter().position(|x| *x == a)); let edit = Select::new(tl!("Alignment:"), Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui); - if let Some(&i) = edit.value() + if let Some(&i) = edit.events.committed() && let Some(a) = ALIGNS.get(i) { self.fields.insert("listAlign".into(), json!(a)); @@ -924,6 +924,48 @@ mod tests { assert!(app.run("ui.bulletsAndNumbering", json!({})).is_err(), "no type selected"); } + /// Alignment: an entry highlighted with the arrow keys changes no field and leaves the type as it was, Escape + /// closes the list with the dialog open and nothing changed, and Enter applies the entry. + #[test] + fn a_highlighted_alignment_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 10, "text": "One\nTwo", "area": {"width": 200, "height": 100}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + panel.app().run("ui.bulletsAndNumbering", json!({})).unwrap(); + panel.frame(); + panel.frame(); + let state = |panel: &Panel| { + let app = panel.app(); + (fields(&app)["listAlign"].clone(), first(&app, id)) + }; + let before = state(&panel); + assert_eq!(before.0, "left"); + panel.click_role("Alignment:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted alignment changes no field and leaves the type as it was"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "Escape closes the list, not the dialog"); + assert_eq!(state(&panel), before, "Escape leaves the alignment as it was"); + panel.click_role("Alignment:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "Enter in the list keeps the dialog open"); + assert_eq!(state(&panel).0, "right", "Enter applies the alignment"); + } + /// Cancel puts back what the preview changed: the list, its alignment and the indents. #[test] fn cancel_puts_the_type_back_as_it_was() { diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 50e4cb9e31..584964e0c4 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -826,7 +826,7 @@ fn paint_row(key: &'static str, label: &'static str, swatches: Vec<(String, Valu entries.push(Entry::new(selected.clone(), Label::from(shown))); } let out = Select::new(Label::from(label), Bind::given(selected), &entries).show(ui); - if let Some(id) = out.value().cloned() { + if let Some(id) = out.events.committed().cloned() { let paint = match id.as_str() { "" => Some(Value::Null), "none" => Some(json!({"type": "none"})), diff --git a/crates/ui-egui/src/dialogs/char_style_options/tests.rs b/crates/ui-egui/src/dialogs/char_style_options/tests.rs index 4c54feadf6..258d925608 100644 --- a/crates/ui-egui/src/dialogs/char_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/char_style_options/tests.rs @@ -1007,6 +1007,46 @@ fn color_and_features_preview_cancel_commit_and_new_style() { assert!(t.runs.iter().all(|r| r.style.style_name.as_deref() == Some("Body"))); } +/// Character Color's Fill and Stroke: a paint highlighted with the arrow keys changes no field and leaves the +/// document as it was, Escape closes the list with the dialog open and nothing changed, and Enter sets the paint. +#[test] +fn a_highlighted_character_color_paint_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + for (name, key) in [("Fill", "fill"), ("Stroke", "stroke")] { + let mut app = app(); + styled(&mut app, json!({"size": 24.0}), "Text"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app(), "Body"); + set::(&panel.app(), "tab", json!("color")); + panel.frame(); + panel.frame(); + let state = |panel: &Panel| { + let app = panel.app(); + (fields::(&app), app.session.doc().unwrap().doc.clone()) + }; + let before = state(&panel); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted {name} paint changes nothing"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert!(is_open::(&panel.app()), "Escape closes the {name} list, not the dialog"); + assert_eq!(state(&panel), before, "Escape leaves {name} as it was"); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert!(is_open::(&panel.app()), "Enter in the {name} list keeps the dialog open"); + assert_ne!(state(&panel).0[key], before.0[key], "Enter sets the {name} paint"); + } +} + /// A size or leading below the minimum is refused by OK and runs no preview. #[test] fn size_and_leading_below_minimum_do_not_preview_or_commit() { diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 3ab762bfc5..0465d1e322 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -604,7 +604,7 @@ impl CompositeFontsDialog { } }) .cell_field(STYLE, style, move |out| { - if let Some(style) = out.value().cloned() { + if let Some(style) = out.events.committed().cloned() { edits.borrow_mut().push((at, PartEdit::Style(style))); } }); diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index 3a56a41c23..48070f0b41 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -612,6 +612,44 @@ fn custom_character_sets_draw_their_characters_and_the_buttons() { } } +/// The parts table's Style: a style highlighted with the arrow keys leaves the font's parts as they were, Escape closes +/// the list with nothing changed, and Enter sets the style. +#[test] +fn a_highlighted_part_style_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut p = Panel::new(app(), crate::tests::picks::dialogs); + p.room(egui::vec2(1280.0, 1100.0)); + open(&mut p.app()).unwrap(); + new_font(&mut p.app()); + dialog(&mut p.app(), |d| { + for class in CharClass::ALL { + d.edit_part(row(class), PartEdit::Font("Source Sans 3".into(), Some("Regular".into()))); + } + }); + p.frame(); + p.frame(); + let parts = |p: &Panel| dialog(&mut p.app(), |d| d.font().map(|f| f.parts.clone())); + let before = parts(&p); + p.click_role("Style", Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + p.frame(); + assert_eq!(parts(&p), before, "a highlighted style changes no part"); + p.key(Key::Escape, Modifiers::NONE); + p.frame(); + assert!(is_open(&p.app()), "Escape closes the list, not the dialog"); + assert_eq!(parts(&p), before, "Escape leaves the parts as they were"); + p.click_role("Style", Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert!(is_open(&p.app()), "Enter in the list keeps the dialog open"); + assert_ne!(parts(&p), before, "Enter sets the style"); +} + #[test] fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 9c4ee9e4f4..1f330a64b6 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -87,8 +87,11 @@ fn dialog<'a>(relative: bool, lengths: LengthUnits) -> ParamDialog<'a> { Param::number("radius", tl!("Radius:"), 0.0, 1.0, 3).length(lengths).bounds(Some(0.0), None) }; let radii = vec![("relative".to_owned(), tl!("Relative").into()), ("absolute".to_owned(), tl!("Absolute").into())]; - let params = - vec![Param::new("kind", tl!("Corner:"), ParamKind::radio(kinds, None)), Param::new("radii", "", ParamKind::radio(radii, None)), radius]; + let params = vec![ + Param::new("kind", tl!("Corner:"), ParamKind::radio(kinds, None)), + Param::new("radii", "", ParamKind::radio(radii, None)).options_in_row(), + radius, + ]; ParamDialog::new(KIND, tl!("Corners"), params) } diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index e8eeacd29c..9ba4858116 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -58,7 +58,7 @@ fn sized_row(key: &str, label: Label, default: f64, relative: bool, lengths: Len /// the flag's JSON values, which `form::json_of` writes back as a bool. pub(super) fn relative_radio(label: impl Into