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/cursor_theme.rs b/apps/vectorcraft/src/cursor_theme.rs index b23d1099db..ce044dded4 100644 --- a/apps/vectorcraft/src/cursor_theme.rs +++ b/apps/vectorcraft/src/cursor_theme.rs @@ -7,11 +7,17 @@ //! fails in a Flatpak sandbox (`XCURSOR_PATH` unset, no cursor theme in the runtime) and where the //! `default` theme is a dangling symlink; the desktop's own setting names a theme that loads. //! +//! Where no cursor theme can be found at all (KDE or sway without gsettings), the env fix does +//! nothing: [`shell_caps`] leaves out [`Caps::SYSTEM_CURSOR`], and the framework keeps the system +//! pointer and paints no tool cursor beside it (#5311). +//! //! This reads the desktop's cursor theme and size and sets what the user left unset, once, before //! any thread starts and before the window opens. #![cfg_attr(not(target_os = "linux"), allow(dead_code))] +use craft::host::target::Caps; use std::ffi::OsString; +use std::path::{Path, PathBuf}; /// Where a Flatpak sandbox mounts the host's cursor themes (user and system). const FLATPAK_HOST_ICONS: [&str; 2] = ["/run/host/user-share/icons", "/run/host/share/icons"]; @@ -48,6 +54,74 @@ pub fn plan(var: impl Fn(&str) -> Option, host_icons: &[&str], desktop out } +/// Xcursor's default search path when `XCURSOR_PATH` is unset (relative entries are in `$HOME`). +const DEFAULT_ICON_DIRS: [&str; 5] = ["~/.local/share/icons", "~/.icons", "/usr/share/icons", "/usr/share/pixmaps", "/usr/X11R6/lib/X11/icons"]; + +/// The themes `index.theme` lists after `Inherits=`. +fn inherits(index: &str) -> Vec { + index + .lines() + .find_map(|l| l.trim().strip_prefix("Inherits=")) + .map(|v| v.split([',', ';']).map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect()) + .unwrap_or_default() +} + +/// Can Xcursor load a pointer for the environment's theme (`XCURSOR_THEME`, else `default`)? It does +/// when the theme, or one it inherits from, has a `default` or `left_ptr` cursor file in a folder of +/// `XCURSOR_PATH` (else Xcursor's default folders). `read` returns a file's text, `exists` tells +/// whether a file is there. +pub fn theme_usable( + var: impl Fn(&str) -> Option, + home: Option<&Path>, + read: impl Fn(&Path) -> Option, + exists: impl Fn(&Path) -> bool, +) -> bool { + let dirs: Vec = match var("XCURSOR_PATH").filter(|v| !v.is_empty()) { + Some(v) => std::env::split_paths(&v).collect(), + None => DEFAULT_ICON_DIRS + .iter() + .filter_map(|d| match d.strip_prefix("~/") { + Some(rest) => home.map(|h| h.join(rest)), + None => Some(PathBuf::from(d)), + }) + .collect(), + }; + let first = var("XCURSOR_THEME").and_then(|v| v.into_string().ok()).filter(|t| !t.is_empty()).unwrap_or_else(|| "default".into()); + let mut todo = vec![first]; + let mut seen: Vec = Vec::new(); + while let Some(theme) = todo.pop() { + // Bounded: themes inherit in short chains, and a cycle must end. + if seen.contains(&theme) || seen.len() >= 16 { + continue; + } + for dir in &dirs { + let base = dir.join(&theme); + if ["default", "left_ptr"].iter().any(|c| exists(&base.join("cursors").join(c))) { + return true; + } + if let Some(index) = read(&base.join("index.theme")) { + todo.extend(inherits(&index)); + } + } + seen.push(theme); + } + false +} + +/// On this machine, after [`apply`]: is there no cursor theme Xcursor can load? Then winit never +/// sets a pointer, and a hidden system pointer does not come back (#2450). +pub fn theme_missing() -> bool { + let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from); + !theme_usable(|n| std::env::var_os(n), home.as_deref(), |p| std::fs::read_to_string(p).ok(), |p| p.exists()) +} + +/// The shell's capabilities `caps`, without [`Caps::SYSTEM_CURSOR`] when the window opens on +/// Wayland and `theme_missing` finds no cursor theme. The framework then keeps the system pointer +/// and paints no tool cursor beside it (#5311). `theme_missing` runs only on Wayland. +pub fn shell_caps(caps: Caps, wayland: bool, theme_missing: impl FnOnce() -> bool) -> Caps { + if wayland && theme_missing() { caps.difference(Caps::SYSTEM_CURSOR) } else { caps } +} + /// The value of a `gsettings get` line: `'Adwaita'` becomes `Adwaita`, `24` stays `24`. fn gsettings_value(output: &str) -> &str { output.trim().trim_matches('\'') @@ -113,6 +187,43 @@ mod tests { assert!(plan(env(&[("WAYLAND_DISPLAY", "wayland-0")]), &[], odd).is_empty()); } + #[test] + fn a_theme_is_usable_directly_or_through_inherits_and_missing_otherwise() { + let files = ["/i/Bibata/cursors/left_ptr", "/i/Breeze/index.theme", "/i/Loop/index.theme"]; + // Compared as paths, so the joins match on Windows too, where they use `\`. + let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p); + let read = |p: &Path| { + if p == Path::new("/i/Breeze/index.theme") { + Some("[Icon Theme]\nInherits=Other, Bibata\n".to_owned()) + } else if p == Path::new("/i/Loop/index.theme") { + Some("Inherits=Loop\n".to_owned()) + } else { + None + } + }; + let with = |theme: &'static str| { + move |n: &str| (n == "XCURSOR_PATH").then(|| OsString::from("/i")).or((n == "XCURSOR_THEME").then(|| OsString::from(theme))) + }; + assert!(theme_usable(with("Bibata"), None, read, exists)); + assert!(theme_usable(with("Breeze"), None, read, exists)); + // No such theme, a theme without cursors, an inheritance loop: nothing to load. + assert!(!theme_usable(with("Nope"), None, read, exists)); + assert!(!theme_usable(with("Loop"), None, read, exists)); + // Unset: Xcursor's default folders and the `default` theme. + assert!(!theme_usable(|_| None, Some(Path::new("/home/u")), read, exists)); + } + + #[test] + fn without_a_cursor_theme_on_wayland_the_system_pointer_stays_alone() { + let native = Caps::native(craft::host::target::Os::Linux); + assert!(native.contains(Caps::SYSTEM_CURSOR)); + let without = shell_caps(native, true, || true); + assert!(!without.contains(Caps::SYSTEM_CURSOR), "Wayland with no cursor theme: no painted cursor beside the system pointer"); + assert_eq!(without.union(Caps::SYSTEM_CURSOR), native, "only the system cursor is left out"); + assert_eq!(shell_caps(native, true, || false), native, "Wayland with a theme"); + assert_eq!(shell_caps(native, false, || panic!("the theme is looked up only on Wayland")), native, "X11 and XWayland"); + } + #[test] fn gsettings_output_is_unquoted() { assert_eq!(gsettings_value("'Adwaita'\n"), "Adwaita"); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 872753f9d7..7812264ac0 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -667,6 +667,11 @@ fn main() -> std::process::ExitCode { // framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and // Preferences › User Interface › System Title Bar. let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() }; + // On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted + // beside it (#2450, #5311). + let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland; + let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing); + let shell_info = shell_info.caps(caps); let titlebar_pref = if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated }; let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref); 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/brush/src/colorize.rs b/crates/brush/src/colorize.rs index b48c43294c..47211426f6 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -267,10 +267,13 @@ fn turned(c: &Color, degrees: f32) -> Option { } } -/// Replace a solid paint's color with what `adjust` gives for it, dropping its swatch link. +/// Replace a solid paint's color with what `adjust` gives for it, dropping its swatch link. A +/// color that comes back unchanged (an amount too small to move its components) keeps the paint +/// and its link. fn recolor_paint(p: &mut Paint, adjust: &dyn Fn(&Color) -> Option) { if let Paint::Solid { color, .. } = p && let Some(c) = adjust(color) + && c != *color { *p = Paint::solid(c); } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 0b6cbf6011..2a39d50010 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1599,6 +1599,30 @@ fn jitter_at_a_limit_keeps_the_swatch_link() { } } +/// A hue or saturation jitter too small to move a Lab color's components gives each copy the color +/// it had, and the copies keep the swatch link. +#[test] +fn jitter_too_small_to_change_a_color_keeps_the_swatch_link() { + let linked = Paint::Solid { color: Color::lab(50.0, 64.0, 0.0), swatch: Some("Spot".into()), tint: 1.0 }; + // 1e-50 degrees turns a and b by less than an f32 holds; 1e-6 points scales the chroma by + // 1 + 1.6e-8, which rounds back to the same f32 components. + type Jitter = fn(&mut [Node], f64, u64); + let jitters: [(&str, Jitter, f64); 2] = [("hue", crate::colorize::jitter_hues, 1e-50), ("saturation", crate::colorize::jitter_saturations, 1e-6)]; + for (name, jitter, amount) in jitters { + let mut copies: Vec = (0..8) + .map(|_| { + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + art + }) + .collect(); + jitter(&mut copies, amount, 7); + for n in &copies { + assert_eq!(n.appearance.fill_paint(), linked, "{name}"); + } + } +} + /// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its /// swatch links. #[test] 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/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 9e4d188ddc..52df74f8cf 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -33,6 +33,7 @@ use vectorcraft_engine::doc::Document; use super::cleanup::Positional; use crate::VectorcraftApp; +use crate::edits::{EditPath, apply_edits}; use crate::menus::{Sep, c, cp}; use crate::panels::empty_state; @@ -302,31 +303,39 @@ pub(crate) fn open_dialog(app: &mut VectorcraftApp) -> Result { } /// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle -/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which -/// takes away the angles of their own. +/// they all fold at (empty when they differ), which sets theirs as it is typed, as one undo step +/// that a cancel takes back, and Reset, which takes away the angles of their own. fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) { if !kept.selection || kept.fold_lines == 0 { return; } - let mut call = None; + let mut edit = None; + let mut reset = false; let _ = Line::new().fill_width().show(ui, |ui, _| { Field::new(tl!("Fold Angle")).show(ui, |ui, _| { let field = NumberField::new(tl!("Fold Angle"), Bind::given(kept.angle)) .unit_kind(UnitKind::Degrees) .range(FOLD_ANGLES) .max_decimals(angle_places(kept.angle)); - if let Some(a) = field.id_salt("fold-angle").show(ui).value().copied().flatten() { - call = Some(json!({ "angle": a })); + edit = Some(field.id_salt("fold-angle").show(ui).edit); + }); + reset = clicked(&Button::new(tl!("Reset")).enabled(kept.stored_angles > 0).show(ui)); + }); + let run = |app: &mut VectorcraftApp, p: Value| { + if let Err(e) = app.run(SET_FOLD_ANGLE, p) { + app.status(e); + } + }; + // One undo step per edit of the field; a cancel reverts it. + if let Some(edit) = edit { + apply_edits(app, &edit, EditPath::Scope, |app, a: &Option, _| { + if let Some(a) = a { + run(app, json!({ "angle": a })); } }); - if clicked(&Button::new(tl!("Reset")).enabled(kept.stored_angles > 0).show(ui)) { - call = Some(json!({ "reset": true })); - } - }); - if let Some(p) = call - && let Err(e) = app.run(SET_FOLD_ANGLE, p) - { - app.status(e); + } + if reset { + run(app, json!({ "reset": true })); } } diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 8222b179d5..086ac45e1a 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use egui::{Key, Modifiers}; use serde_json::json; use vectorcraft_engine::Session; @@ -207,3 +208,45 @@ fn the_panel_shows_the_selected_lines_fold_angle_and_what_reset_takes_away() { let text = crate::tests_labels::painted_text(&mut app, show); assert!(!text.contains("Fold Angle"), "{text}"); } + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +#[test] +fn canceling_a_fold_angle_edit_restores_the_angle_and_enter_is_one_undo_step() { + // (the angle the second line folds at first, the text typed, the angle the lines then fold at): one angle, angles + // that differ, and a typed angle the field holds to its range. + for (second, text, typed) in [(None, "135", 135.0), (Some(-45.0), "135", 135.0), (None, "200", 180.0)] { + for cancel in [false, true] { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a, b]})).unwrap(); + if let Some(angle) = second { + app.run(SET_FOLD_ANGLE, json!({"angle": angle, "ids": [b]})).unwrap(); + } + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let mut panel = Panel::new(app, show); + let doc = panel.app().session.active().unwrap().doc.clone(); + let angle = read_rows(&mut panel.app()).angle; + let undo = undo_len(&panel.app()); + // The role list fills the panel's height, so the field below it takes the focus as a screen reader gives it. + panel.focus("Fold Angle"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(text); + panel.frame(); + assert_eq!(read_rows(&mut panel.app()).angle, Some(typed), "{second:?} {text}: the lines fold at the angle while it is typed"); + panel.key(if cancel { Key::Escape } else { Key::Enter }, Modifiers::NONE); + panel.frame(); + assert!(panel.shows("Fold Angle"), "{text}: the field stays"); + let mut app = panel.app(); + if cancel { + assert_eq!(app.session.active().unwrap().doc, doc, "{second:?} {text}: Escape restores the lines"); + assert_eq!(read_rows(&mut app).angle, angle, "{second:?} {text}: Escape restores the angle"); + assert_eq!(undo_len(&app), undo, "{second:?} {text}: Escape leaves no undo step"); + } else { + assert_eq!(read_rows(&mut app).angle, Some(typed), "{second:?} {text}: Enter keeps the angle"); + assert_eq!(undo_len(&app), undo + 1, "{second:?} {text}: the edit is one undo step"); + } + } + } +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 2b4ba91076..324f907615 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -5,7 +5,8 @@ //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog //! ([`tangent_circle_radius`]). Everything acts through `addon.pathtools.*` and `tool.setOption`, except that the radius -//! dialog draws its circle with `shape.circleThroughPoints`. +//! dialog draws its circle with `shape.circleThroughPoints`. Canceling an Anchor Inspector field edit restores its +//! opening value: an anchor edit is one undo step that the cancel takes back. pub mod bridge; pub mod corner; @@ -16,7 +17,7 @@ pub mod shared_edge; pub mod tangent_circle; pub mod tangent_circle_radius; -use craft::behavior::ColumnWidth; +use craft::behavior::{ColumnWidth, EditEvents}; use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked}; @@ -35,6 +36,7 @@ use vectorcraft_tools::addons::{anchor_eraser, extend_path, measure_inspect, par use crate::canvas::rulers::general_lengths; use crate::dialogs::host::open_held; +use crate::edits::{EditPath, apply_event}; use crate::menus::{Sep, c, cp}; use crate::panels::empty_state; use crate::{VectorcraftApp, fields}; @@ -73,14 +75,22 @@ const EXTEND_MODES: [(&str, &str); 3] = [("straight", "Straight"), ("bezier", "S pub(crate) struct Inspector { /// How many points Add Points puts on each segment. pub points_per_segment: u32, + /// The In and Out Angle fields' last typed values while their edits run; each field shows its handle's angle in + /// that value's turn, so `200` stays `200` rather than `-160`. + pub angles: [Option; 2], } impl Default for Inspector { fn default() -> Self { - Inspector { points_per_segment: 1 } + Inspector { points_per_segment: 1, angles: [None; 2] } } } +/// `degrees` moved by whole turns to lie nearest `near`; unchanged with no `near`. +fn in_turn_of(degrees: f64, near: Option) -> f64 { + near.map_or(degrees, |near| degrees + 360.0 * ((near - degrees) / 360.0).round()) +} + /// The first selected anchor as the panel shows it: positions less the ruler origin, handles as length and angle. pub(crate) struct AnchorReadout { pub x: f64, @@ -204,36 +214,38 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { let lengths = general_lengths(app); let origin = app.ruler_origin(); let mut points = app.addon_panels.inspector.points_per_segment; - let mut set: Option = None; + // Each anchor field's edits this pass, as the `addon.pathtools.setAnchor` params they send. + let mut edits: Vec>> = Vec::new(); let mut action: Option<(&str, Value)> = None; match anchor { Some(_) => Text::new(crate::i18n::fmt(tl!("Anchors selected: {count}"), &[("count", &readout.count.to_string())])).show(ui), None => Text::new(tl!("Direct-select anchor points to edit them.")).show(ui), }; let enabled = anchor.is_some(); - let length = |ui: &mut Ui, salt: &'static str, field: NumberField<'static>| typed(field.id_salt(salt).enabled(enabled).show(ui).value()); + // A cleared field sends no params, and its gesture still begins and ends. + let length = |ui: &mut Ui, salt: &'static str, field: NumberField<'static>, to: &dyn Fn(f64) -> Value| { + field.id_salt(salt).enabled(enabled).show(ui).edit.events.map(|v| v.map(to)) + }; + let mut typed_angles = app.addon_panels.inspector.angles; let angle = |ui: &mut Ui, salt: &'static str, v: Option| { let field = NumberField::new(tl!("Angle"), Bind::given(v)).unit_kind(UnitKind::Degrees).fixed_decimals(1); - typed(field.id_salt(salt).enabled(enabled).show(ui).value()) + field.id_salt(salt).enabled(enabled).show(ui).edit.events }; let _ = Grid::new(&COLUMNS).show(ui, |ui, _| { for (label, key, v, o) in [("X", "x", anchor.map(|a| a.x), origin.x), ("Y", "y", anchor.map(|a| a.y), origin.y)] { Text::new(tl!(label)).show(ui); - if let Some(v) = length(ui, key, NumberField::length(tl!(label), Bind::given(v), lengths)) { - set = Some(json!({ key: v + o })); - } + edits.push(length(ui, key, NumberField::length(tl!(label), Bind::given(v), lengths), &|v| json!({ key: v + o }))); } for (label, side, i) in [("In", "in", 0), ("Out", "out", 1)] { Text::new(tl!(label)).show(ui); // A handle's length is a size: `50%` is half of it. let len = fields::size_field(ui, tl!("Length"), anchor.map(|a| a.lengths[i]), lengths); - if let Some(v) = length(ui, if i == 0 { "in-length" } else { "out-length" }, len) { - set = Some(json!({ format!("{side}Length"): v })); - } + edits.push(length(ui, if i == 0 { "in-length" } else { "out-length" }, len, &|v| json!({ format!("{side}Length"): v }))); Text::new("∠").show(ui); - if let Some(v) = angle(ui, if i == 0 { "in-angle" } else { "out-angle" }, anchor.and_then(|a| a.angles[i])) { - set = Some(json!({ format!("{side}Angle"): v })); - } + let shown = anchor.and_then(|a| a.angles[i]).map(|v| in_turn_of(v, typed_angles[i])); + let events = angle(ui, if i == 0 { "in-angle" } else { "out-angle" }, shown); + typed_angles[i] = if events.ended().is_some() { None } else { events.value().copied().flatten().or(typed_angles[i]) }; + edits.push(events.map(|v| v.map(|v| json!({ format!("{side}Angle"): v })))); } }); Divider::horizontal().show(ui); @@ -247,7 +259,8 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { action = Some(("addon.pathtools.addPoints", json!({ "count": f64::from(points) }))); } let field = NumberField::new(tl!("Points per segment"), Bind::given(Some(f64::from(points)))).range(1.0..=100.0).fixed_decimals(0); - if let Some(v) = typed(field.id_salt("points-per-segment").enabled(selected).show(ui).value()) { + // The value the field holds after its events: a cancel's is the opening value. + if let Some(v) = typed(field.id_salt("points-per-segment").enabled(selected).show(ui).edit.events.landed()) { points = v as u32; } }); @@ -261,8 +274,14 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { } }); app.addon_panels.inspector.points_per_segment = points; - if let Some(p) = set { - run(app, "addon.pathtools.setAnchor", p); + app.addon_panels.inspector.angles = typed_angles; + // One undo step per gesture; a cancel reverts it. + for event in edits.iter().flatten() { + apply_event(app, event, &EditPath::Scope, &mut |app, p: &Option, _| { + if let Some(p) = p { + run(app, "addon.pathtools.setAnchor", p.clone()); + } + }); } if let Some((id, p)) = action { run(app, id, p); diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index b516412e61..895026b03c 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -1,4 +1,6 @@ +use craft::ui::contract::Role; use craft::ui::patterns::form_dialogs::{FieldValue, HostedParamDialog}; +use egui::{Key, Modifiers}; use serde_json::json; use vectorcraft_engine::Session; use vectorcraft_tools::addons::parametric_shape::ShapeKind; @@ -70,6 +72,81 @@ fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() { assert!(anchor.lengths.iter().all(|length| *length > 0.0)); } +/// The Anchor Inspector's anchor fields with what each test types: the field's name, which of the fields with that name +/// it is (In, then Out) and the text typed. +const ANCHOR_TYPED: [(&str, usize, &str); 6] = + [("X", 0, "40"), ("Y", 0, "60"), ("Length", 0, "30"), ("Angle", 0, "45"), ("Length", 1, "25"), ("Angle", 1, "200")]; + +/// An app whose open path's middle anchor is direct-selected and has both handles, from Make Smooth. +fn app_with_smooth_anchor() -> VectorcraftApp { + let mut app = app(); + let r = app.run("path.create", json!({"anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}], "closed": false})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + app.run("addon.pathtools.smooth", json!({})).unwrap(); + app +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +#[test] +fn canceling_an_anchor_field_restores_the_anchor_and_enter_is_one_undo_step() { + for (label, nth, text) in ANCHOR_TYPED { + for cancel in [false, true] { + let mut panel = Panel::new(app_with_smooth_anchor(), super::show); + let doc = panel.app().session.active().unwrap().doc.clone(); + let undo = undo_len(&panel.app()); + panel.click_role_nth(label, Role::SPIN_BUTTON, nth); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(text); + panel.frame(); + let proposed = panel.app().session.active().unwrap().doc.clone(); + assert_ne!(proposed, doc, "{label} {nth} changes the anchor while typing"); + let shown = readout(&panel.app()).anchor.unwrap(); + panel.key(if cancel { Key::Escape } else { Key::Enter }, Modifiers::NONE); + panel.frame(); + assert!(panel.shows(label), "{label} {nth}: the panel stays open"); + let app = panel.app(); + if cancel { + assert_eq!(app.session.active().unwrap().doc, doc, "{label} {nth} restores the anchor on Escape"); + assert_eq!(undo_len(&app), undo, "{label} {nth}: Escape leaves no undo step"); + } else { + // Enter applies the typed value once more, which can move a handle by a rounding error. + let kept = readout(&app).anchor.unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + let angles = kept.angles.iter().zip(shown.angles).all(|(a, b)| a.zip(b).is_some_and(|(a, b)| near(a, b))); + let lengths = kept.lengths.iter().zip(shown.lengths).all(|(a, b)| near(*a, b)); + assert!(near(kept.x, shown.x) && near(kept.y, shown.y) && lengths && angles, "{label} {nth}: Enter keeps the edit"); + assert_eq!(undo_len(&app), undo + 1, "{label} {nth}: the edit is one undo step"); + } + } + } +} + +#[test] +fn canceling_points_per_segment_restores_its_value_and_enter_keeps_it() { + for cancel in [false, true] { + let mut panel = Panel::new(app_with_smooth_anchor(), super::show); + let undo = undo_len(&panel.app()); + panel.click_role("Points per segment", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + panel.key(if cancel { Key::Escape } else { Key::Enter }, Modifiers::NONE); + panel.frame(); + assert!(panel.shows("Points per segment"), "the panel stays open"); + let kept = if cancel { 1 } else { 5 }; + assert_eq!(panel.app().addon_panels.inspector.points_per_segment, kept, "canceled: {cancel}"); + assert_eq!(undo_len(&panel.app()), undo, "the field adds no undo step"); + } +} + /// Runs `f` on the held options dialog, `None` when none is open. fn held(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R { app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::())) 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.rs b/crates/ui-egui/src/chrome.rs index 291177c9e2..d32ec78d67 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -10,7 +10,7 @@ use craft::ui::contract::{Bind, BodyCx, Gap, Props, Show, ShowContainer}; use craft::ui::display::Picture; use craft::ui::layout_components::Row; use craft::ui::primitives::IconSpec; -use craft::ui::runtime::windows::WindowHost; +use craft::ui::runtime::windows::{WindowAction, WindowHost}; use craft::ui::shell::{Frame, Title, TitleBar}; use craft::ui::style::{SurfaceKind, Variant}; use egui::Ui; @@ -142,11 +142,18 @@ pub fn app_bar(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut VectorcraftApp) { let end = |ui: &mut Ui, _: &mut BodyCx<'_>| trailing(ui, &mut app.borrow_mut()); // A nightly's window and Dock entry carry its own name, so they never read as the stable app's. let title = if crate::os_window::stable_services_allowed() { tl!("VectorCraft") } else { crate::os_window::name() }; - let _ = if titled { + let out = if titled { TitleBar::new().surface(SurfaceKind::Background).show_titled(ui, Title::new(title), start, end) } else { TitleBar::new().surface(SurfaceKind::Background).show_fitted(ui, start, end) }; + // The title bar reports a caption Close click in its output and never acts on it. The window host sends the close, + // and a close of the main window goes through the app's close guard, so the unsaved-changes prompt runs as it does + // for an OS close. + if out.close_requested { + let ctx = ui.ctx().clone(); + WindowHost::of(&ctx).act(ctx.viewport_id(), WindowAction::Close); + } } /// The OS window title: the active document's name suffixed with the app name (a `*` prefix diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 9848d86f1a..51834cb232 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; @@ -12,6 +14,7 @@ use craft::ui::pickers::{Select, SelectLook}; use craft::ui::runtime::env::Env; use craft::ui::style::TypeRole; use craft::ui::text::ZoomField; +use vectorcraft_engine::WindowView; /// Shows the status bar: zoom, rotation, artboard navigator, the info field with its Show menu, the readouts, Stop, /// the background-work progress and last the message, so a narrow bar elides the message before anything else. @@ -22,33 +25,32 @@ 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 shown_zoom = view.map(|v| crate::state::zoom_display_percent(v.zoom, print)); - 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 +92,22 @@ 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, + shown_zoom, + 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,10 +142,33 @@ 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 preset_pick, mut rotate_to, mut go) = (None, 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::Preset(preset) => preset_pick = Some(preset), + 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(); } + match preset_pick { + Some(ZoomPreset::Percent(zoom)) => { + app.run("view.setZoom", json!({ "zoom": zoom })).ok(); + } + Some(ZoomPreset::FitOnScreen) => { + app.run("view.fitArtboard", json!({})).ok(); + } + Some(ZoomPreset::FitAll) => { + app.run("view.fitAll", json!({})).ok(); + } + None => {} + } if let Some(&(_, angle)) = rotate_to.and_then(|i| ROTATE_VIEW_ANGLES.get(i)) { app.run("view.rotate", json!({"angle": angle})).ok(); } @@ -196,10 +187,132 @@ 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, + /// The view's zoom percentage, which the Zoom Presets menu checks. + shown_zoom: 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 entry chosen in the Zoom Presets menu. + Preset(ZoomPreset), + /// 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 presets = zoom_presets(p.shown_zoom, p.print); + let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui); + if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked { + p.picked.send(NavigationPick::Preset(preset)); + } + 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::*; use crate::tests::panel_harness::Panel; + use craft::ui::canvas::ViewCommands; use craft::ui::contract::Role; #[test] @@ -272,6 +385,121 @@ 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 the_zoom_presets_menu_sets_a_stop_and_fits_the_view() { + 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)); + app.run("view.setZoom", json!({"zoom": 800})).unwrap(); + app.view_mut().unwrap().request = None; + // The canvas applies a fit on its next frame; the status bar alone leaves the request queued. + let requested = |panel: &Panel| panel.app().view().and_then(|v| v.request.map(|(r, _)| r.command())); + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, status_bar); + // Room for the whole menu, so the entries at its foot are on screen. + panel.room(egui::vec2(1200.0, 1600.0)); + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("200%", Role::MENU_ITEM_RADIO); + let print = panel.app().print_ppi(); + assert!((crate::state::zoom_display_percent(panel.app().view().unwrap().zoom, print) - 200.0).abs() < 1e-6, "a stop sets its zoom"); + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("Fit on Screen", Role::MENU_ITEM_RADIO); + assert_eq!(requested(&panel), Some(ViewCommands::FitArtboard), "Fit on Screen runs view.fitArtboard"); + panel.app().view_mut().unwrap().request = None; + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("Fit All", Role::MENU_ITEM_RADIO); + assert_eq!(requested(&panel), Some(ViewCommands::FitOnScreen), "Fit All runs view.fitAll"); + + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "zooming records no undo step"); + } + + #[test] + fn the_zoom_presets_list_the_stops_from_the_highest_and_check_the_shown_zoom() { + let presets = zoom_presets(Some(200.0), None); + let labels: Vec = presets.iter().filter(|e| e.is_item()).map(|e| e.label().as_str().to_owned()).collect(); + assert_eq!(labels.first().map(String::as_str), Some("64000%")); + assert_eq!(labels.iter().rev().take(3).rev().map(String::as_str).collect::>(), ["3.13%", "Fit on Screen", "Fit All"]); + let checked: Vec<_> = presets.iter().filter(|e| e.is_checked()).filter_map(|e| e.value().copied()).collect(); + assert_eq!(checked, [ZoomPreset::Percent(200.0)]); + assert!(zoom_presets(None, None).iter().all(|e| !e.is_checked()), "without a view no stop is checked"); + } + + /// With Display Print Size on, 100% is more or less than one screen point per document point, so the stops at + /// the ends of the list can fall outside the view's zoom range; the menu lists only the stops a pick sets exactly. + #[test] + fn the_zoom_presets_leave_out_stops_outside_the_zoom_range_at_print_size() { + let percents = |print: Option| -> Vec { + zoom_presets(None, print) + .iter() + .filter_map(|e| match e.value() { + Some(ZoomPreset::Percent(pct)) => Some(*pct), + _ => None, + }) + .collect() + }; + let stops: Vec = crate::state::zoom_stop_percents().collect(); + let n = stops.len(); + assert_eq!(percents(None).len(), n, "at 1:1 every stop is in range"); + let dense = crate::state::print_ppi(true, Some(96.0)); + assert_eq!(percents(dense).first(), Some(&stops[n - 2]), "64000% at 96 PPI is past the highest zoom, 25600% is not"); + assert_eq!(percents(dense).last(), Some(&stops[0]), "3.13% at 96 PPI is in range"); + let sparse = crate::state::print_ppi(true, Some(40.0)); + assert_eq!(percents(sparse).first(), Some(&stops[n - 1]), "64000% at 40 PPI is in range"); + assert_eq!(percents(sparse).last(), Some(&stops[2]), "3.13% and 4.17% at 40 PPI are below the lowest zoom, 6.25% is not"); + let (min, max) = WindowView::ZOOM_RANGE; + for print in [None, dense, sparse] { + for pct in percents(print) { + let zoom = crate::state::zoom_from_display_percent(pct, print); + let set = crate::state::zoom_display_percent(zoom.clamp(min, max), print); + assert!((set - pct).abs() < 1e-6, "{pct}% at {print:?} sets {set}%"); + } + } + } + #[test] fn with_no_document_the_artboard_navigator_shows_a_dash() { let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -295,6 +523,41 @@ fn busy_labels(app: &VectorcraftApp) -> Vec<&str> { .collect() } +/// An entry of the Zoom Presets menu beside the status bar's zoom field. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ZoomPreset { + /// A zoom stop, in the percent `view.setZoom` takes. + Percent(f64), + /// Fit on Screen (`view.fitArtboard`). + FitOnScreen, + /// Fit All (`view.fitAll`). + FitAll, +} + +/// The Zoom Presets menu: the zoom stops from the highest, the one at the `shown` percent checked, then Fit on Screen +/// and Fit All. A stop whose zoom falls outside the view's zoom range ([`WindowView::ZOOM_RANGE`]) at the `print` +/// setting is left out, since `view.setZoom` would set the nearest end of the range instead. +fn zoom_presets(shown: Option, print: Option) -> Vec> { + let (min, max) = WindowView::ZOOM_RANGE; + let reachable = |pct: &f64| { + let zoom = crate::state::zoom_from_display_percent(*pct, print); + zoom >= min * (1.0 - 1e-9) && zoom <= max * (1.0 + 1e-9) + }; + let stops = crate::state::zoom_stop_percents(); + let mut entries: Vec> = stops + .rev() + .filter(reachable) + .map(|pct| { + let label = crate::state::zoom_label(crate::state::zoom_from_display_percent(pct, print), print); + Entry::new(ZoomPreset::Percent(pct), label).checked(shown.is_some_and(|s| (s - pct).abs() < 0.01)) + }) + .collect(); + entries.push(Entry::separator()); + entries.push(Entry::new(ZoomPreset::FitOnScreen, tl!("Fit on Screen"))); + entries.push(Entry::new(ZoomPreset::FitAll, tl!("Fit All"))); + entries +} + /// What the status bar's info field shows, chosen from the Show menu that a click on the field /// opens (`view.statusBarShow`). Kept with the UI state ([`crate::UiState::status_bar_show`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index a06ee63300..8fe7f3e43f 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -473,6 +473,59 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() { assert!(widest.zip(narrowest).is_some_and(|(w, n)| n >= w - 0.5), "the search keeps its width until it goes: {search_widths:?}"); } +/// A click on the title bar's Close caption button asks the window to close, and the close reaches the app's close guard +/// as an OS close does: with a modified document the window stays and the Unsaved Changes question shows. +#[test] +fn the_title_bars_close_button_closes_the_window() { + use craft::window::policy::{Backend, Desktop, Frame, Os, Runtime, TitleBarPref, WindowKind, decide}; + crate::i18n::set_current(crate::i18n::Lang::EN); + // The window the desktop host opens on Windows: decorations off, and the title bar draws the caption buttons. + let desktop = Desktop::detect(Backend::X11); + let decision = decide(Os::Windows, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None); + assert!(matches!(decision.frame, Frame::Integrated(_)), "{:?}", decision.frame); + let ctx = egui::Context::default(); + craft::ui::shell::embed::install(&ctx, craft::ui::testing::install_spec().frame(decision), &crate::ui_fonts()).expect("the runtime installs"); + craft::ui::testing::windows::set_os(&ctx, Os::Windows); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.session.add_document(vectorcraft_doc::Document::new(612.0, 792.0), None); + app.sync_views(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + let room = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 600.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let out = crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect: Some(room), events, ..Default::default() }); + out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|root| root.commands.contains(&egui::ViewportCommand::Close)) + }; + // The Close button sits at the bar's right end, flush with the window's top right corner. + let at = egui::pos2(room.right() - 4.0, 4.0); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let mut closed = false; + for events in [vec![], vec![], vec![egui::Event::PointerMoved(at)]] { + closed |= frame(&mut app, events); + } + assert!(!closed, "no close before the click"); + for events in [vec![button(true)], vec![button(false)], vec![]] { + closed |= frame(&mut app, events); + } + assert!(closed, "the Close caption button asks the main window to close"); + // The host answers the close with the window's close event, which `embed::logic` takes to the app's close guard. + let mut raw = egui::RawInput { screen_rect: Some(room), ..Default::default() }; + raw.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + let mut decision = None; + ctx.run_ui(raw, |ui| { + app.ui(ui); + craft::ui::shell::embed::logic(ui.ctx(), || { + let answer = app.close_decision(); + decision = Some(answer); + answer + }); + }) + .textures_delta + .clear(); + assert_eq!(decision, Some(craft::ui::shell::embed::CloseDecision::Hold), "the modified document keeps the window open"); + let asks = app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some())); + assert!(asks, "the close asks about the modified document"); +} + /// The app bar's right-hand controls stand at least `space.gap.item` apart, the gap between neighboring controls in a /// bar, so a hovered control's highlight does not touch the one beside it. #[test] 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