diff --git a/.github/scripts/release-rpm-smoke.py b/.github/scripts/release-rpm-smoke.py new file mode 100644 index 0000000000..3d70cca7c1 --- /dev/null +++ b/.github/scripts/release-rpm-smoke.py @@ -0,0 +1,74 @@ +"""Check a real installed release RPM and exercise the GUI control channel.""" + +import json +import os +from pathlib import Path +import secrets +import socket +import subprocess +import time +import tempfile + + +def run_smoke(results): + requirements = (results / "rpm-requires.txt").read_text() + for capability in ( + "libc.so.6()(64bit)", + "libm.so.6(GLIBC_2.35)(64bit)", + "libgcc_s.so.1()(64bit)", + "libxkbcommon.so.0()(64bit)", + "(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))", + ): + if capability not in requirements.splitlines(): + raise RuntimeError(f"Missing RPM requirement: {capability}") + + version = subprocess.check_output(["vectorcraft-cli", "--version"], text=True) + (results / "cli-version.txt").write_text(version) + # Original fixture authored for this package smoke test; no external artwork. + fixture = results / "original-smoke.svg" + fixture.write_text('' + '' + '') + token = secrets.token_hex(32) + with tempfile.TemporaryDirectory(prefix="vectorcraft-runtime-") as runtime, (results / "gui.log").open("w") as log: + env = dict(os.environ, VECTORCRAFT_NO_PREFS="1", XDG_RUNTIME_DIR=runtime, + VECTORCRAFT_CONTROL_TOKEN=token) + app = subprocess.Popen([ + "vectorcraft", "--control", "32180", "--automation-read-root", str(results), + "--automation-write-root", str(results), str(fixture), + ], stdout=log, stderr=subprocess.STDOUT, env=env) + try: + deadline = time.monotonic() + 90 + while True: + if app.poll() is not None: + raise RuntimeError(f"GUI exited during startup: {app.returncode}") + try: + channel = socket.create_connection(("127.0.0.1", 32180), timeout=5) + break + except OSError: + if time.monotonic() >= deadline: + raise RuntimeError("GUI control channel did not become ready") from None + time.sleep(1) + channel.settimeout(30) + with channel, channel.makefile("rwb") as stream: + for request_id, method, params in ( + (0, "auth", {"token": token}), + (1, "ui.inspect", {}), + ): + stream.write((json.dumps(dict(id=request_id, method=method, params=params)) + "\n").encode()) + stream.flush() + response = json.loads(stream.readline()) + (results / f"{method}.json").write_text(json.dumps(response, indent=2)) + if response.get("id") != request_id or response.get("ok") is not True: + raise RuntimeError(f"GUI request failed: {method}") + finally: + app.terminate() + try: + app.wait(timeout=10) + except subprocess.TimeoutExpired: + app.kill() + app.wait() + + +if __name__ == "__main__": + run_smoke(Path("/results")) diff --git a/.github/scripts/tests/test_release_rpm_smoke.py b/.github/scripts/tests/test_release_rpm_smoke.py new file mode 100644 index 0000000000..9d92237534 --- /dev/null +++ b/.github/scripts/tests/test_release_rpm_smoke.py @@ -0,0 +1,116 @@ +"""Exercise failures that an installed-package happy-path check cannot reproduce.""" +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import MagicMock, patch + +spec = importlib.util.spec_from_file_location("rpm_smoke", Path(__file__).parents[1] / "release-rpm-smoke.py") +smoke = importlib.util.module_from_spec(spec) +spec.loader.exec_module(smoke) + + +class SmokeLifecycleTests(unittest.TestCase): + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.results = Path(self.folder.name) + (self.results / "rpm-requires.txt").write_text("\n".join([ + "libc.so.6()(64bit)", "libm.so.6(GLIBC_2.35)(64bit)", + "libgcc_s.so.1()(64bit)", "libxkbcommon.so.0()(64bit)", + "(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))", + ])) + self.app = MagicMock() + self.app.poll.return_value = None + self.channel = MagicMock() + self.stream = self.channel.makefile.return_value.__enter__.return_value + self.stream.readline.side_effect = [ + b'{"id":0,"ok":true}\n', b'{"id":1,"ok":true,"result":{"window":"fixture"}}\n', + ] + self.runtime = None + + def launch(*args, **kwargs): + self.runtime = Path(kwargs["env"]["XDG_RUNTIME_DIR"]) + self.assertTrue(self.runtime.is_dir()) + return self.app + + self.launch = self.start_patch(smoke.subprocess, "Popen", side_effect=launch) + self.start_patch(smoke.subprocess, "check_output", return_value="vectorcraft-cli 0.25.0\n") + self.connect = self.start_patch(smoke.socket, "create_connection", return_value=self.channel) + self.start_patch(smoke.time, "sleep") + + def start_patch(self, owner, name, **kwargs): + patcher = patch.object(owner, name, **kwargs) + result = patcher.start() + self.addCleanup(patcher.stop) + return result + + def assert_cleaned_up(self): + self.app.terminate.assert_called_once() + self.assertFalse(self.runtime.exists()) + + def test_success_records_inspection_and_removes_private_runtime(self): + smoke.run_smoke(self.results) + report = json.loads((self.results / "ui.inspect.json").read_text()) + self.assertEqual(report["result"], {"window": "fixture"}) + requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list] + self.assertEqual(requests[0]["method"], "auth") + self.assertEqual(requests[0]["params"]["token"], self.launch.call_args.kwargs["env"]["VECTORCRAFT_CONTROL_TOKEN"]) + self.assert_cleaned_up() + + def test_missing_runtime_dependency_prevents_launch(self): + (self.results / "rpm-requires.txt").write_text("") + with self.assertRaisesRegex(RuntimeError, "Missing RPM requirement"): + smoke.run_smoke(self.results) + self.launch.assert_not_called() + + def test_child_exit_during_startup_is_a_failure(self): + self.app.poll.return_value = 1 + self.app.returncode = 1 + with self.assertRaisesRegex(RuntimeError, "exited during startup"): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + + def test_connection_is_retried_until_ready(self): + self.connect.side_effect = [OSError("not ready"), self.channel] + smoke.run_smoke(self.results) + self.assertEqual(self.connect.call_count, 2) + self.assert_cleaned_up() + + def test_startup_timeout_stops_child(self): + self.connect.side_effect = OSError("not ready") + self.start_patch(smoke.time, "monotonic", side_effect=[0, 91]) + with self.assertRaisesRegex(RuntimeError, "did not become ready"): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + + def test_auth_refusal_prevents_inspection(self): + self.stream.readline.side_effect = [b'{"id":0,"ok":false}\n'] + with self.assertRaisesRegex(RuntimeError, "request failed: auth"): + smoke.run_smoke(self.results) + self.assertFalse((self.results / "ui.inspect.json").exists()) + self.assert_cleaned_up() + + def test_response_for_another_request_is_rejected(self): + self.stream.readline.side_effect = [b'{"id":0,"ok":true}\n', b'{"id":99,"ok":true}\n'] + with self.assertRaisesRegex(RuntimeError, "request failed: ui.inspect"): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + + def test_malformed_response_still_stops_child(self): + self.stream.readline.side_effect = [b'not json\n'] + with self.assertRaises(json.JSONDecodeError): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + + def test_unresponsive_child_is_killed_after_termination_timeout(self): + self.app.wait.side_effect = [subprocess.TimeoutExpired("vectorcraft", 10), 0] + smoke.run_smoke(self.results) + self.app.kill.assert_called_once() + self.assert_cleaned_up() + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/release-rpm-smoke.yml b/.github/workflows/release-rpm-smoke.yml new file mode 100644 index 0000000000..61948e0f35 --- /dev/null +++ b/.github/workflows/release-rpm-smoke.yml @@ -0,0 +1,114 @@ +name: Release RPM smoke + +on: + workflow_dispatch: + inputs: + run-id: + description: Release run containing both RPM artifacts (empty selects the latest available pair) + type: string + default: "" + pull_request: + paths: + - .github/workflows/release-rpm-smoke.yml + - .github/scripts/release-rpm-smoke.py + - .github/scripts/tests/test_release_rpm_smoke.py + +permissions: {} + +jobs: + source: + permissions: + actions: read + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + run-id: ${{ steps.source.outputs.run-id }} + steps: + - id: source + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ inputs.run-id }} + run: | + candidates="$RUN_ID" + if [ -z "$candidates" ]; then + candidates=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow release.yml --branch release --limit 10 --json databaseId --jq '.[].databaseId') + fi + for candidate in $candidates; do + [[ "$candidate" =~ ^[0-9]+$ ]] + names=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$candidate/artifacts?per_page=100" --jq '.artifacts[] | select(.expired == false) | .name') + if grep -Fxq release-linux-x86_64 <<< "$names" && grep -Fxq release-linux-aarch64 <<< "$names"; then + printf 'run-id=%s\n' "$candidate" >> "$GITHUB_OUTPUT" + exit 0 + fi + done + echo '::error::No release run has both Linux package artifacts available' + exit 1 + smoke: + permissions: + contents: read + actions: read + needs: source + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + platform: + - {arch: x86_64, runner: ubuntu-24.04} + - {arch: aarch64, runner: ubuntu-24.04-arm} + distro: [fedora, rocky, opensuse] + runs-on: ${{ matrix.platform.runner }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - name: Download the release packages + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ needs.source.outputs.run-id }} + ARCH: ${{ matrix.platform.arch }} + run: | + [[ "$RUN_ID" =~ ^[0-9]+$ ]] + mkdir -p packages results + gh run view "$RUN_ID" --json headSha,url > results/source.json + gh run download "$RUN_ID" --name "release-linux-$ARCH" --dir packages + sha256sum packages/*.rpm > results/rpm-sha256.txt + - name: Install and start the RPM on the target distribution + env: + DISTRO: ${{ matrix.distro }} + run: | + sudo apt-get update -qq + sudo apt-get install -y xvfb + Xvfb :99 -screen 0 1440x900x24 -ac -nolisten tcp > results/xvfb.log 2>&1 & + for _attempt in {1..20}; do + [ -S /tmp/.X11-unix/X99 ] && break + sleep 1 + done + [ -S /tmp/.X11-unix/X99 ] + case "$DISTRO" in + fedora) image=fedora:latest ;; + rocky) image=rockylinux:10 ;; + opensuse) image=opensuse/tumbleweed:latest ;; + esac + docker pull "$image" + docker image inspect "$image" --format '{{json .RepoDigests}}' > results/container-digest.json + docker run --rm --ipc=host --name rpm-smoke -e DISTRO -e DISPLAY=:99 -e LIBGL_ALWAYS_SOFTWARE=1 \ + -v /tmp/.X11-unix:/tmp/.X11-unix:ro -v "$PWD/packages:/packages:ro" \ + -v "$PWD/results:/results" -v "$PWD/.github/scripts:/checks:ro" "$image" bash -euc ' + cat /etc/os-release > /results/os-release.txt + if [ "$DISTRO" = opensuse ]; then + zypper --non-interactive refresh + zypper --non-interactive install python3 Mesa-dri Mesa-libEGL1 libX11-6 libXcursor1 libXi6 libXrandr2 libxkbcommon0 libxkbcommon-x11-0 + zypper --non-interactive --no-gpg-checks install /packages/*.rpm + else + dnf -y install python3 mesa-dri-drivers mesa-libEGL libX11 libXcursor libXi libXrandr libxkbcommon libxkbcommon-x11 + dnf -y --nogpgcheck install /packages/*.rpm + fi + rpm -qp --requires /packages/*.rpm > /results/rpm-requires.txt + python3 /checks/release-rpm-smoke.py + ' + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + if: always() + with: + name: rpm-smoke-${{ matrix.distro }}-${{ matrix.platform.arch }} + path: results/ + if-no-files-found: error diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index dde1f6f5a8..98e9c1d00a 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -21,4 +21,7 @@ jobs: # The reusable workflow defaults build-jobs to 2 so a cold instrumented # archive stays within hosted-runner memory (craft-common-actions#333). uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + with: + python-coverage-source: .github/scripts + python-coverage-script: .github/scripts/tests/test_release_rpm_smoke.py secrets: inherit diff --git a/Cargo.lock b/Cargo.lock index 3cb674e4ae..4fce3ecad1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1816,6 +1816,14 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-pages" version = "0.1.0" @@ -8522,6 +8530,7 @@ dependencies = [ "chrono", "clipboard-win", "craft", + "craft-nightly", "eframe", "egui", "egui_extras", diff --git a/Cargo.toml b/Cargo.toml index 7ad3e4cfeb..cc76d129c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,8 @@ craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index d17c96eaf7..3ec7da1b75 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -22,6 +22,7 @@ vectorcraft-text = { workspace = true } # frame policy and placement store (so VectorCraft matches the rest on Linux, see #217), printing and # the update client. craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] } +craft-nightly = { workspace = true } eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } egui = { workspace = true } egui_extras = { workspace = true } diff --git a/apps/vectorcraft/src/build_flavor.rs b/apps/vectorcraft/src/build_flavor.rs index 9450a48972..93876b5cce 100644 --- a/apps/vectorcraft/src/build_flavor.rs +++ b/apps/vectorcraft/src/build_flavor.rs @@ -1,30 +1,13 @@ //! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a -//! stable build, and a nightly build refuses to start without its profile. -use crate::launch_profile::Profile; -use std::ffi::OsString; +//! stable build, and a nightly build self-isolates into its canonical nightly profile root (or the +//! profile root supplied by ArtCraft Launcher). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; pub const COMPILED: BuildFlavor = if cfg!(vectorcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open VectorCraft Nightly from ArtCraft Launcher".to_string()), - (BuildFlavor::Stable, true) => Err("This is a stable VectorCraft build; nightly-v1 requires the nightly build".to_string()), - _ => Ok(()), - } -} - -pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { - desktop_session && flavor == BuildFlavor::NightlyV1 -} - -/// `--version` and `-V` on their own, before any other argument is read. -pub fn version_query(args: &[OsString]) -> bool { +/// An exact plain version query, before resolving any profile or environment paths. +pub fn version_query(args: &[std::ffi::OsString]) -> bool { matches!(args, [arg] if arg == "--version" || arg == "-V") } @@ -37,40 +20,19 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String { #[cfg(test)] mod tests { - use super::*; + use super::{BuildFlavor, version, version_query}; #[test] - fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { - assert!(needs_native_error(BuildFlavor::NightlyV1, true)); - assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); - assert!(!needs_native_error(BuildFlavor::Stable, true)); - assert!(!needs_native_error(BuildFlavor::Stable, false)); - } - - #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); - } - - #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); - assert!(require_profile(BuildFlavor::NightlyV1, &Profile::Stable).is_err()); - } - - #[test] - fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { - assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1"); - assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)"); + fn plain_version_query_is_exact() { assert!(version_query(&["--version".into()])); assert!(version_query(&["-V".into()])); assert!(!version_query(&["--".into(), "--version".into()])); assert!(!version_query(&[])); } + + #[test] + fn version_labels_nightly_without_changing_stable() { + assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)"); + } } diff --git a/apps/vectorcraft/src/launch_profile.rs b/apps/vectorcraft/src/launch_profile.rs index 12615dd81d..d986f28d71 100644 --- a/apps/vectorcraft/src/launch_profile.rs +++ b/apps/vectorcraft/src/launch_profile.rs @@ -1,130 +1,28 @@ -//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state. -//! Stable launches retain their original arguments and directory policy. -//! -//! The protocol is `vectorcraft --launch-profile nightly-v1 --profile-root -- [files…]`: the -//! selector and the root are separate tokens, exactly once each, and everything after `--` is a file -//! even when it looks like one of them. The Launcher's version check -//! (`… --version`) is answered before the root is validated or touched. +//! Nightly-v1 bootstrap backed by [`craft_nightly`]. Selected before logging, updates, fonts or +//! saved state. Stable launches retain their original arguments and directory policy; direct +//! nightly launches self-isolate into [`craft_nightly::canonical_profile_root`], while ArtCraft +//! Launcher can supply `--launch-profile nightly-v1 --profile-root -- [args…]`. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; +pub use craft_nightly::NIGHTLY_V1_CONTRACT as VERSION; +use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} - -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } - - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); +static STABLE: Profile = Profile::Stable; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&STABLE) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string()) -} - -/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook -/// runs here. -pub fn parse(args: Vec) -> Result { - let mut selector = None; - let mut root = None; - let mut other = Vec::new(); - let mut files = Vec::new(); - let mut iter = args.iter(); - let mut delimiter = false; - while let Some(arg) = iter.next() { - if arg == "--" { - delimiter = true; - files.extend(iter.cloned()); - break; - } - if arg == "--launch-profile" || arg == "--profile-root" { - let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; - if slot.is_some() { - return Err("the profile selector and root must each occur exactly once".to_string()); - } - let value = iter.next().filter(|v| !v.is_empty()).ok_or_else(|| "the profile selector/root needs a value".to_string())?; - if value.to_string_lossy().starts_with("--") { - return Err("the profile selector/root needs a value".to_string()); - } - *slot = Some(value.clone()); - } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { - return Err("the nightly protocol requires separate literal selector/root argument tokens".to_string()); - } else { - other.push(arg.clone()); - } - } - match (selector, root) { - (None, None) => Ok(Launch { profile: Profile::Stable, args }), - (Some(version), Some(root)) if version == VERSION => { - if !delimiter || !other.is_empty() { - return Err("nightly-v1 accepts only its selector/root followed by -- and file names".to_string()); - } - let root = PathBuf::from(root); - if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { - return Err("the nightly profile root must be absolute and contain no parent traversal".to_string()); - } - Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) - } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".to_string()), - _ => Err("--launch-profile and --profile-root must be supplied together".to_string()), - } -} - -/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), -/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never -/// validated or touched, and `-- --version` stays a file name. -pub fn version_query(args: &[OsString]) -> bool { - let Some((last, pair)) = args.split_last() else { return false }; - if last != "--version" && last != "-V" { - return false; - } - let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); - matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) -} - -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly root -/// validator, so its portable and config resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::prefs_dir::profile::ensure_writable) +pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + let spec = crate::profile_root::app_profile_spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::default()) } /// The arguments a child of this process starts with: a nightly launch hands its profile on, so the -/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and -/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged. -/// Only `single_instance` starts a child, and macOS does not build it. +/// child opens the same private profile, and `--` keeps a file whose name starts with '-' a file. +/// Stable's child arguments are unchanged. Only `single_instance` starts a child, and macOS does +/// not build it. #[cfg(not(target_os = "macos"))] pub fn child_args(files: &[String]) -> Vec { child_args_for(current(), files) @@ -132,21 +30,24 @@ pub fn child_args(files: &[String]) -> Vec { #[cfg(not(target_os = "macos"))] fn child_args_for(profile: &Profile, files: &[String]) -> Vec { - let mut args: Vec = match profile { - Profile::Stable => Vec::new(), - Profile::NightlyV1(root) => { - vec![OsString::from("--launch-profile"), OsString::from(VERSION), OsString::from("--profile-root"), root.clone().into_os_string()] - } - }; - args.push(OsString::from("--")); - args.extend(files.iter().map(OsString::from)); - args + let delimited: Vec = std::iter::once(OsString::from("--")).chain(files.iter().map(OsString::from)).collect(); + match profile { + Profile::Stable => delimited, + Profile::NightlyV1(root) => craft_nightly::launch_arguments(root, &delimited), + } } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; + use std::ffi::OsString; + use std::path::PathBuf; + + use craft_nightly::{BuildFlavor, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup}; + + use super::VERSION; + #[cfg(not(target_os = "macos"))] + use super::child_args_for; + use crate::profile_root::app_profile_spec; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -156,95 +57,72 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\vectorcraft" } else { "/nightly-data/profiles/vectorcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() { + let spec = app_profile_spec(); for argv in [args(&[]), args(&["--new-instance", "a.svg"]), args(&["--", "--launch-profile", "file.svg"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::default()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + + let nightly_flags = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]); + let err = parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::default()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "art with spaces.svg"])); - let launch = parse(argv).unwrap(); + fn nightly_direct_launch_self_isolates_into_canonical_profile_root() { + let spec = app_profile_spec(); + let expected_root = canonical_profile_root("vectorcraft").unwrap(); + + let empty = parse_startup(BuildFlavor::NightlyV1, &spec, Vec::new(), &StartupOptions::default()).unwrap(); + assert_eq!(empty.profile, Profile::NightlyV1(expected_root.clone())); + assert!(empty.passthrough_args.is_empty()); + + let with_args = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--safe-mode", "art.svg"]), &StartupOptions::default()).unwrap(); + assert_eq!(with_args.profile, Profile::NightlyV1(expected_root)); + assert_eq!(with_args.passthrough_args, args(&["--safe-mode", "art.svg"])); + } + + #[test] + fn explicit_launcher_arguments_preserve_profile_root_and_user_args() { + let spec = app_profile_spec(); + let argv = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--profile-root", "art with spaces.svg"]); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "art with spaces.svg"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "art with spaces.svg"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { - for argv in [ - args(&["--launch-profile", VERSION]), - args(&["--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "../escape", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - ] { - assert!(parse(argv.clone()).is_err(), "{argv:?}"); - } - } - - #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + fn version_queries_are_recognized_plain_and_via_launcher() { + let spec = app_profile_spec(); for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); + for argv in [ + args(&[flag]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag]), + args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", flag]), + ] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap(); + assert!(launch.is_version_query(), "{argv:?}"); } } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); } #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".to_string())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } - - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); - } - - #[test] - fn a_joined_flag_form_is_refused() { - for joined in [format!("--launch-profile={VERSION}"), format!("--profile-root={}", absolute())] { - let argv = vec![OsString::from(joined), OsString::from("--")]; - assert!(parse(argv).is_err()); + fn version_and_document_arguments_are_not_a_version_only_query() { + let spec = app_profile_spec(); + for flag in ["--version", "-V"] { + for argv in [ + args(&[flag, "art with spaces.svg"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag, "art with spaces.svg"]), + args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag, "art with spaces.svg"]), + ] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap(); + assert!(!launch.is_version_query()); + assert_eq!(launch.passthrough_args, args(&[flag, "art with spaces.svg"])); + } } } @@ -258,6 +136,7 @@ mod tests { #[cfg(not(target_os = "macos"))] #[test] fn a_nightly_child_inherits_the_selected_profile() { + let spec = app_profile_spec(); let root = PathBuf::from(absolute()); let child = child_args_for(&Profile::NightlyV1(root.clone()), &["art.svg".to_string()]); let expected = vec![ @@ -266,12 +145,12 @@ mod tests { OsString::from("--profile-root"), root.into_os_string(), OsString::from("--"), + OsString::from("--"), OsString::from("art.svg"), ]; assert_eq!(child, expected); - // The child's own parse finds the same profile and the file list. - let launch = parse(child).unwrap(); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, child, &StartupOptions::default()).unwrap(); assert!(launch.profile.is_nightly()); - assert_eq!(launch.args, args(&["--", "art.svg"])); + assert_eq!(launch.passthrough_args, args(&["--", "art.svg"])); } } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 5a7d3e33ba..601cda01bb 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -384,58 +384,47 @@ fn channel_name() -> &'static str { /// Says why a nightly launch was refused, then exits 2. A window could not have shown it yet: this /// app has no message box of its own before eframe starts (its dialogs are egui windows), so the -/// text goes to standard error, which a Launcher launch records. The desktop-session test still -/// decides whether a daily user would have seen it, for the message's wording. +/// text goes to standard error, which a Launcher launch records. fn report_launch_profile_error(error: &str) { eprintln!("VectorCraft launch profile: {error}"); - let desktop_session = cfg!(windows) - || cfg!(target_os = "macos") - || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); - if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { - eprintln!("VectorCraft Nightly: open it from ArtCraft Launcher, which starts it in its own profile"); - } +} + +fn write_nightly_version() { + use std::io::Write as _; + let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION"))); + let _ = std::io::stdout().write_all(line.as_bytes()); } /// Selects the immutable launch profile before any startup service or side effect, and returns the /// arguments the rest of `main` reads. `None` means the process ends here (`--version` answered). fn prepare_launch() -> Option> { - // The trusted Launcher protocol is decided before the logger, updates, fonts or any saved state. + // The launch profile is decided before the logger, updates, fonts or any saved state. let argv: Vec<_> = std::env::args_os().skip(1).collect(); - // A nightly answers its version before root validation, process identity, IPC or any window: - // plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`. A stable build leaves the answer to `read_command_line`, exactly as before. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) - { - use std::io::Write as _; - let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION"))); - let _ = std::io::stdout().write_all(line.as_bytes()); + // A plain nightly version query does not even need the OS home/data root to resolve. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + write_nightly_version(); + return None; + } + let early = launch_profile::prepare_launch(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // A launcher version query also exits before process identity, IPC or any window. + // `craft_nightly::prepare_launch` skips root preparation for version queries. + // A stable build leaves the answer to `read_command_line`, exactly as before. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { + write_nightly_version(); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| { - launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) - }) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); let nightly = early.profile.is_nightly(); let identity = if nightly { vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { vectorcraft_ui_egui::os_window::LaunchIdentity::Stable }; - let install = launch_profile::install(early.profile).and_then(|()| { - // Every data path follows the selected profile from here on: settings, logs, recovery, the - // user's libraries, plug-ins, caches and the single-instance record. - if let Some(root) = launch_profile::current().root() { - prefs_dir::profile::install_data_root(root.to_path_buf())?; - } - vectorcraft_ui_egui::os_window::select_identity(identity) - }); + // Every data path follows the selected profile from here on: settings, logs, recovery, the + // user's libraries, plug-ins, caches and the single-instance record. + let install = launch_profile::current() + .root() + .map_or(Ok(()), |root| prefs_dir::profile::install_data_root(root.to_path_buf())) + .and_then(|()| vectorcraft_ui_egui::os_window::select_identity(identity)); if let Err(error) = install { report_launch_profile_error(&error); std::process::exit(2); @@ -453,11 +442,11 @@ fn prepare_launch() -> Option> { // The window's identity, not the profile, failed: main's own failure status (1). std::process::exit(1); } - Some(early.args) + Some(early.passthrough_args) } /// The arguments the rest of `main` reads: a nightly's profile tokens were consumed by -/// `prepare_launch`, so what is left is `--` and the files to open. A stable launch reads its +/// `prepare_launch`, leaving any user flags and files to open. A stable launch reads its /// arguments exactly as it always did. fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec { if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() } @@ -520,8 +509,9 @@ fn finish_pending_update(nightly: bool) { } fn main() -> std::process::ExitCode { - // The launch profile first: a nightly build without one is refused here, before the update - // helper, the logger, fonts or any saved state, and `--version` is answered here too. + // The launch profile first: a nightly build self-isolates or uses the Launcher's profile here, + // before the update helper, the logger, fonts or any saved state, and `--version` is answered + // here too. let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS }; let nightly = launch_profile::current().is_nightly(); #[cfg(windows)] diff --git a/apps/vectorcraft/src/profile_root.rs b/apps/vectorcraft/src/profile_root.rs index 7f46e77766..d5ae707a17 100644 --- a/apps/vectorcraft/src/profile_root.rs +++ b/apps/vectorcraft/src/profile_root.rs @@ -1,264 +1,17 @@ -//! App-owned nightly profile fences: a profile every one of VectorCraft's data paths is redirected -//! into ([`crate::prefs_dir::profile::install_data_root`]), and that never overlaps stable's folders, a portable -//! copy or an installation. +//! App-owned nightly profile specification for [`craft_nightly`]: describes VectorCraft's stable +//! directories, forbidden environment variables, portable markers, folder-only profile entries, and +//! extra installation/package boundaries so a nightly profile never overlaps stable state. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::{Path, PathBuf}; -use crate::prefs_dir::profile::PORTABLE_DATA_DIR; +use craft_nightly::AppProfileSpec; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, -} +use crate::prefs_dir::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKERS}; -impl Platform { - fn current() -> Result { - match std::env::consts::OS { - "windows" => Ok(Self::Windows), - "linux" => Ok(Self::Linux), - "macos" => Ok(Self::Mac), - other => Err(format!("nightly-v1 is not defined for this operating system ({other})")), - } - } +const STABLE_DIR_NAMES: [&str; 2] = ["VectorCraft", "vectorcraft"]; - fn ignores_case(self) -> bool { - self != Self::Linux - } -} - -fn absolute(path: PathBuf, label: &str) -> Result { - if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!("{label} must be absolute and contain no parent traversal")); - } - Ok(path) -} - -fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { - let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; - absolute(PathBuf::from(value), key) -} - -fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { - match env(key).filter(|v| !v.is_empty()) { - Some(value) => absolute(PathBuf::from(value), key), - None => Ok(required_base(env, "HOME")?.join(fallback)), - } -} - -/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor -/// is not a missing directory that may be replaced or followed later. -fn canonical_future(path: &Path) -> Result { - let mut parent = path; - let mut missing = Vec::new(); - loop { - match std::fs::symlink_metadata(parent) { - Ok(_) => break, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - missing.push(parent.file_name().ok_or_else(|| "the profile root has no existing ancestor".to_string())?.to_os_string()); - parent = parent.parent().ok_or_else(|| "the profile root has no existing ancestor".to_string())?; - } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), - } - } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -/// A stable entry point may be a dangling link once its target is uninstalled. Its own name is still -/// the fence, so only the folder it lives in is resolved: a link that cannot be resolved would refuse -/// every launch, a valid private profile included. -fn canonical_future_entry(path: &Path) -> Result { - let parent = path.parent().ok_or_else(|| "an entry point has no folder".to_string())?; - let name = path.file_name().ok_or_else(|| "an entry point has no name".to_string())?; - Ok(canonical_future(parent)?.join(name)) -} - -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or_else(|| "cannot establish the installation boundary".to_string())?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned install, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -/// Every folder a stable VectorCraft keeps user state in, on `platform`: the settings folder each -/// platform convention and the portable layout use, the eframe window state, the logs, the recovery -/// copies, the plug-ins, the caches, the install folders and the entry points. A nightly profile that -/// overlapped any of them would read, rewrite or prune stable's own state. -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - // The settings folder (`profile.rs`) and the eframe window state, which eframe puts under - // `%APPDATA%\ai.storyteller.vectorcraft\data` (the window id). - let mut roots = ["APPDATA", "LOCALAPPDATA"] - .into_iter() - .map(|key| required_base(env, key).map(|p| p.join("VectorCraft"))) - .collect::, _>>()?; - roots.push(required_base(env, "APPDATA")?.join("ai.storyteller.vectorcraft")); - // The MSI's default per-user and per-machine folders (install-policy.wxi). A custom - // install folder is not known here; the executable's own folder is fenced below. - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("VectorCraft")); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - if let Some(base) = env(key).filter(|v| !v.is_empty()) { - roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("VectorCraft")); - } - } - roots - } - Platform::Linux => { - let mut roots = - [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] - .into_iter() - .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("vectorcraft"))) - .collect::, _>>()?; - // The eframe window state, under the lowercased window id. - roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("ai.storyteller.vectorcraft")); - roots.push(required_base(env, "HOME")?.join(".config").join("VectorCraft")); - // The same folders at their HOME defaults: an XDG override moves this launch's own paths, - // not stable's, which stays where a launch without the override finds it. - for (directory, app) in - [(".config", "vectorcraft"), (".local/share", "vectorcraft"), (".cache", "vectorcraft"), (".local/state", "vectorcraft")] - { - roots.push(required_base(env, "HOME")?.join(directory).join(app)); - } - // The stable Flatpak keeps its data in its own per-app folder. - roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.vectorcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support/VectorCraft"), - library.join("Application Support/ai.storyteller.vectorcraft"), - library.join("Caches/VectorCraft"), - library.join("Caches/ai.storyteller.vectorcraft"), - library.join("Preferences/VectorCraft"), - library.join("Preferences/ai.storyteller.vectorcraft.plist"), - library.join("Saved Application State/ai.storyteller.vectorcraft.savedState"), - home.join("Applications/VectorCraft.app"), - PathBuf::from("/Applications/VectorCraft.app"), - ] - } - }; - roots.push(installation_boundary(platform, exe)?); - let mut fences = roots.into_iter().map(|p| canonical_future(&p)).collect::, _>>()?; - if platform == Platform::Linux { - for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] { - fences.push(canonical_future_entry(Path::new(entry))?); - } - } - Ok(fences) -} - -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 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")); - } - Ok(child) -} - -/// Every existing entry directly in the profile (settings, logs, the user's libraries and so on) must -/// resolve inside it, so a link there cannot point Nightly's writes at another app's data. -fn entries_stay_inside(root: &Path) -> Result<(), String> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - 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 FORBIDDEN_ENV_VARS: [&str; 2] = ["VECTORCRAFT_CONFIG_DIR", "VECTORCRAFT_NO_PREFS"]; const PROFILE_FOLDERS: [&str; 18] = [ "Data Recovery", @@ -281,397 +34,207 @@ const PROFILE_FOLDERS: [&str; 18] = [ "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. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - path.ancestors().enumerate().any(|(depth, ancestor)| { - crate::prefs_dir::profile::PORTABLE_MARKERS.iter().any(|marker| ancestor.join(marker).is_file()) - && (depth == 0 || ["vectorcraft.exe", "vectorcraft"].iter().any(|exe| ancestor.join(exe).is_file())) - }) || path.components().any(|component| match component { - Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR), - Component::Normal(name) => name == PORTABLE_DATA_DIR, - _ => false, - }) +/// Builds VectorCraft's [`AppProfileSpec`] for [`craft_nightly`]. +pub fn app_profile_spec() -> AppProfileSpec { + AppProfileSpec { + app_id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID, + display_name: vectorcraft_ui_egui::os_window::APP_NAME, + stable_dir_names: &STABLE_DIR_NAMES, + stable_package_id: vectorcraft_ui_egui::os_window::APP_ID, + nightly_package_id: vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID, + profile_root_env: None, + forbidden_env_vars: &FORBIDDEN_ENV_VARS, + portable_markers: &PORTABLE_MARKERS, + folder_only_entries: &PROFILE_FOLDERS, + extra_forbidden_roots: extra_forbidden_roots(), + } } -/// The writable hook is the app's own exclusive probe ([`crate::prefs_dir::profile::ensure_writable`]). Keeping -/// it injected lets the boundary tests exercise the real policy without starting the app. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) +fn non_empty_abs(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key)?; + if value.is_empty() { + return None; + } + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - if env("VECTORCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { - return Err("nightly-v1 cannot be combined with VECTORCRAFT_CONFIG_DIR".to_string()); - } - // The app turns preferences off whenever the variable is present, empty value included. - if env("VECTORCRAFT_NO_PREFS").is_some() { - // A run without preferences keeps nothing: its own profile would stay unused and the app - // would log to standard error only, so it is never a nightly launch. - return Err("nightly-v1 cannot inherit VECTORCRAFT_NO_PREFS".to_string()); - } - let nightly_flatpak = vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID; - if platform != Platform::Windows - && let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty()) - && id.to_string_lossy().as_ref() != nightly_flatpak +fn extra_forbidden_roots() -> Vec { + extra_forbidden_roots_with(|key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) +} + +fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Vec { + let mut roots = Vec::new(); + + #[cfg(target_os = "windows")] { - // `packaging/linux/flatpak-bundle.sh` builds VectorCraft Nightly as its own Flatpak - // (`ai.storyteller.vectorcraft.nightly`), whose sandbox is already a private home. Any other - // instance, the stable app's included, would put this profile inside another app's tree. - return Err(format!("nightly-v1 can only run inside its own Flatpak instance ({nightly_flatpak}), not {}", id.to_string_lossy())); + if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join("VectorCraft")); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs(&env, key) { + roots.push(base.join("ArtCraft").join("VectorCraft")); + } + } } - let chosen = canonical_future(root)?; - if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { - return Err("the nightly root must not use a portable VectorCraft installation or its VectorCraftData settings folder".to_string()); - } - let exe = absolute(exe.ok_or_else(|| "cannot establish the installation boundary".to_string())?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".to_string()); - } - // Data Recovery can read, adopt, overwrite and sweep entries: never let its alias leave the - // private profile. - private_subdirectory(&chosen, "Data Recovery", "recovery folder")?; - entries_stay_inside(&chosen)?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] + + #[cfg(all(unix, not(target_os = "macos")))] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + if let Some(home) = non_empty_abs(&env, "HOME") { + roots.push(home.join(".var").join("app").join(vectorcraft_ui_egui::os_window::APP_ID)); + } + for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] { + roots.push(PathBuf::from(entry)); + } } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".to_string()); + + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs(&env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences").join(format!("{}.plist", vectorcraft_ui_egui::os_window::APP_ID))); + roots.push(library.join("Saved Application State").join(format!("{}.savedState", vectorcraft_ui_egui::os_window::APP_ID))); + roots.push(home.join("Applications").join("VectorCraft.app")); + } + roots.push(PathBuf::from("/Applications/VectorCraft.app")); } - private_subdirectory(&confirmed, "Data Recovery", "recovery folder")?; - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) + + if let Some(exe) = exe { + if let Some(parent) = exe.parent() { + roots.push(parent.join(PORTABLE_DATA_DIR)); + } + #[cfg(target_os = "macos")] + if let Some(bundle_parent) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))).and_then(Path::parent) + { + roots.push(bundle_parent.join(PORTABLE_DATA_DIR)); + } + } + + roots } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; - use std::collections::BTreeMap; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::ffi::OsString; + use std::fs; + #[cfg(unix)] + use std::path::PathBuf; - /// An owned fixture tree: a home, a roaming/local app-data pair and an install folder, so the - /// fence can be checked for every platform on any host. - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } + use craft_nightly::validate_and_prepare_root; - impl Fixture { - fn new() -> Self { - static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("vectorcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); - match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => panic!("cannot create owned fixture: {error}"), - } - }; - let home = root.join("home"); - let exe = root.join("install/vectorcraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } - } - - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - self.check_with(platform, root, |_| Ok(())) - } - - fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result { - validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable) - } - } - - impl Drop for Fixture { - fn drop(&mut self) { - // Only the directory this fixture created is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); - } - } - - const PLATFORMS: [Platform; 3] = [Platform::Windows, Platform::Linux, Platform::Mac]; + use super::{FORBIDDEN_ENV_VARS, PROFILE_FOLDERS, STABLE_DIR_NAMES, app_profile_spec, extra_forbidden_roots_with}; + use crate::prefs_dir::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKERS}; #[test] - fn a_private_profile_is_accepted_on_every_platform() { - let fixture = Fixture::new(); - for platform in PLATFORMS { - let root = fixture.root.join(format!("nightly profiles/{platform:?}/vectorcraft")); - let resolved = fixture.check(platform, &root).unwrap(); - assert!(resolved.is_dir(), "{platform:?}"); - assert_eq!(resolved, std::fs::canonicalize(root).unwrap(), "{platform:?}"); - std::fs::remove_dir_all(fixture.root.join("nightly profiles")).unwrap(); - } + fn spec_preserves_vectorcraft_invariants() { + let spec = app_profile_spec(); + assert_eq!(spec.app_id, "vectorcraft"); + assert_eq!(spec.display_name, "VectorCraft"); + assert_eq!(spec.stable_dir_names, &STABLE_DIR_NAMES); + assert_eq!(spec.stable_package_id, "ai.storyteller.vectorcraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.vectorcraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert_eq!(spec.forbidden_env_vars, &FORBIDDEN_ENV_VARS); + assert_eq!(spec.portable_markers, &PORTABLE_MARKERS); + assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS); } #[test] - fn stable_settings_folders_are_refused_on_every_platform() { - let fixture = Fixture::new(); - let stable = [ - (Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))), - (Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("ai.storyteller.vectorcraft"))), - (Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))), - (Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("Programs/ArtCraft/VectorCraft"))), - (Platform::Linux, Some(fixture.home().join(".config/vectorcraft"))), - (Platform::Linux, Some(fixture.home().join(".local/share/vectorcraft"))), - (Platform::Linux, Some(fixture.home().join(".local/share/ai.storyteller.vectorcraft"))), - (Platform::Linux, Some(fixture.home().join(".cache/vectorcraft"))), - (Platform::Linux, Some(fixture.home().join(".var/app/ai.storyteller.vectorcraft"))), - (Platform::Mac, Some(fixture.home().join("Library/Application Support/VectorCraft"))), - (Platform::Mac, Some(fixture.home().join("Library/Application Support/ai.storyteller.vectorcraft"))), - (Platform::Mac, Some(fixture.home().join("Library/Preferences/ai.storyteller.vectorcraft.plist"))), - ]; - for (platform, stable) in stable { - let stable = stable.unwrap(); - for candidate in [stable.clone(), stable.join("nested nightly")] { - let probed = Cell::new(false); - let result = fixture.check_with(platform, &candidate, |_| { - probed.set(true); - Ok(()) - }); - assert!(result.is_err(), "{platform:?} accepted {candidate:?}"); - assert!(!probed.get(), "a refused root is rejected before the writable probe"); - } - } - } + fn extra_forbidden_roots_fences_platform_installs_and_portable_data() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let exe = tmp.path().join("install/vectorcraft"); + let roots = extra_forbidden_roots_with( + |key| match key { + "HOME" | "LOCALAPPDATA" | "ProgramFiles" => Some(home.clone().into_os_string()), + _ => None, + }, + Some(&exe), + ); + assert!(roots.contains(&tmp.path().join("install").join(PORTABLE_DATA_DIR))); - #[test] - fn the_install_folder_and_the_entry_points_are_refused() { - let fixture = Fixture::new(); - for platform in PLATFORMS { - let install = fixture.exe.parent().unwrap(); - assert!(fixture.check(platform, install).is_err(), "{platform:?}: the install folder"); - assert!(fixture.check(platform, &install.join("NightlyData")).is_err(), "{platform:?}: inside the install"); - } - } - - #[test] - fn an_inherited_config_or_no_prefs_override_is_refused() { - let fixture = Fixture::new(); - let root = fixture.root.join("nightly"); - for (key, value) in [ - ("VECTORCRAFT_CONFIG_DIR", "/elsewhere"), - ("VECTORCRAFT_NO_PREFS", "1"), - // The app turns preferences off on presence, so an empty value is a run too. - ("VECTORCRAFT_NO_PREFS", ""), - ("FLATPAK_ID", "ai.storyteller.vectorcraft"), - ] { - for platform in PLATFORMS { - let result = validate_for( - platform, - &root, - |name| if name == key { Some(value.into()) } else { fixture.get(name) }, - Some(&fixture.exe), - |_| Ok(()), - ); - let refused = result.is_err(); - // A Flatpak instance only keeps the stable app's sockets on native Unix packages. - assert_eq!(refused, !(key == "FLATPAK_ID" && platform == Platform::Windows), "{key} on {platform:?}"); - if refused { - assert!(!root.exists(), "a refused launch creates nothing ({key} on {platform:?})"); - } else if root.exists() { - // The accepted case validated the root, which creates it: start the next one clean. - std::fs::remove_dir_all(&root).expect("remove the accepted launch's root"); - } - } - } - } - - #[test] - fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() { - let fixture = Fixture::new(); - let root = fixture.root.join("flatpak profile"); - for (id, accepted) in - [(vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID, true), ("ai.storyteller.vectorcraft", false), ("io.other.App", false)] + #[cfg(target_os = "windows")] { - let result = validate_for( - Platform::Linux, - &root, - |name| if name == "FLATPAK_ID" { Some(id.into()) } else { fixture.get(name) }, - Some(&fixture.exe), - |_| Ok(()), - ); - assert_eq!(result.is_ok(), accepted, "{id}"); - let _ = std::fs::remove_dir_all(&root); + assert!(roots.contains(&home.join("Programs").join("ArtCraft").join("VectorCraft"))); + assert!(roots.contains(&home.join("ArtCraft").join("VectorCraft"))); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + assert!(roots.contains(&home.join(".var/app/ai.storyteller.vectorcraft"))); + assert!(roots.contains(&PathBuf::from("/usr/bin/vectorcraft"))); + assert!(roots.contains(&PathBuf::from("/usr/local/bin/vectorcraft"))); + assert!(roots.contains(&PathBuf::from("/opt/vectorcraft"))); + } + #[cfg(target_os = "macos")] + { + assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.vectorcraft.plist"))); + assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.vectorcraft.savedState"))); + assert!(roots.contains(&home.join("Applications/VectorCraft.app"))); + assert!(roots.contains(&PathBuf::from("/Applications/VectorCraft.app"))); } } #[test] - fn a_portable_copy_and_its_data_folder_are_refused() { - let fixture = Fixture::new(); - let portable = fixture.root.join("portable copy"); - let data = portable.join(crate::prefs_dir::profile::PORTABLE_DATA_DIR); - std::fs::create_dir_all(&data).unwrap(); - std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap(); - std::fs::write(data.join("config.toml"), b"stable settings must not change").unwrap(); - for platform in PLATFORMS { - for candidate in [&data, &data.join("nested nightly")] { - let probed = Cell::new(false); - let result = fixture.check_with(platform, candidate, |_| { - probed.set(true); - Ok(()) - }); - assert!(result.is_err(), "{platform:?} accepted {candidate:?}"); - assert!(!probed.get()); - assert!(!data.join("nested nightly").exists()); - assert_eq!(std::fs::read(data.join("config.toml")).unwrap(), b"stable settings must not change"); - } + fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_only_entries() { + let tmp = tempfile::tempdir().unwrap(); + let private = tmp.path().join("nightly-reopen"); + let mut spec = app_profile_spec(); + spec.forbidden_env_vars = &[]; + + let canonical = validate_and_prepare_root(&private, &spec).unwrap(); + assert_eq!(canonical, fs::canonicalize(&private).unwrap()); + + for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] { + fs::write(canonical.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + fs::create_dir(canonical.join(name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), canonical); + for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] { + assert_eq!(fs::read(canonical.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen"); + } + + for name in PROFILE_FOLDERS { + let path = canonical.join(name); + fs::remove_dir(&path).unwrap(); + fs::write(&path, b"not a directory").unwrap(); + assert!(validate_and_prepare_root(&private, &spec).is_err(), "{name} must stay a directory"); + fs::remove_file(&path).unwrap(); + fs::create_dir(&path).unwrap(); } - // A merely similar name is not the portable settings folder. - let similar = fixture.root.join("VectorCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &similar).is_ok()); } #[cfg(unix)] #[test] - fn a_link_inside_the_profile_cannot_redirect_recovery_or_a_library() { - let fixture = Fixture::new(); - let root = fixture.root.join("nightly"); - std::fs::create_dir_all(&root).unwrap(); - let external = fixture.root.join("stable-document"); - std::fs::write(&external, b"stable bytes").unwrap(); + fn symlink_inside_profile_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let private = tmp.path().join("nightly"); + fs::create_dir_all(&private).unwrap(); + let external = tmp.path().join("stable-document"); + fs::write(&external, b"stable bytes").unwrap(); + + let mut spec = app_profile_spec(); + spec.forbidden_env_vars = &[]; + for name in ["Data Recovery", "Swatches"] { - let alias = root.join(name); + let alias = private.join(name); std::os::unix::fs::symlink(&external, &alias).unwrap(); - assert!(fixture.check(Platform::Linux, &root).is_err(), "{name} alias"); - std::fs::remove_file(&alias).unwrap(); + assert!(validate_and_prepare_root(&private, &spec).is_err(), "{name} alias"); + fs::remove_file(&alias).unwrap(); } - assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); - } - - #[cfg(unix)] - #[test] - fn a_dangling_link_or_a_linked_ancestor_is_refused() { - let fixture = Fixture::new(); - let elsewhere = fixture.root.join("elsewhere"); - std::fs::create_dir_all(&elsewhere).unwrap(); - let linked = fixture.root.join("nightly"); - std::os::unix::fs::symlink(&elsewhere, &linked).unwrap(); - // Canonical resolution keeps a link's target: a profile reached through one is fine, but it - // is judged (and named) as its target, so nothing is written under the link. - let resolved = fixture.check(Platform::Linux, &linked).unwrap(); - assert_eq!(resolved, std::fs::canonicalize(&elsewhere).unwrap()); - std::fs::remove_file(&linked).unwrap(); - let dangling = fixture.root.join("dangling/nightly"); - std::fs::create_dir_all(dangling.parent().unwrap()).unwrap(); - std::os::unix::fs::symlink(fixture.root.join("missing"), dangling.parent().unwrap().join("nightly")).unwrap(); - assert!(fixture.check(Platform::Linux, &dangling).is_err()); + assert_eq!(fs::read(&external).unwrap(), b"stable bytes"); } #[test] - fn a_home_settings_folder_is_fenced_even_when_the_xdg_override_moves_elsewhere() { - let fixture = Fixture::new(); - let xdg = fixture.root.join("override"); - std::fs::create_dir_all(&xdg).unwrap(); - let config = fixture.home().join(".config/vectorcraft"); - let data = fixture.home().join(".local/share/vectorcraft"); - for stable in [config.clone(), data.clone()] { - for candidate in [stable.clone(), stable.join("nested nightly")] { - let result = validate_for( - Platform::Linux, - &candidate, - |name| match name { - "XDG_CONFIG_HOME" | "XDG_DATA_HOME" => Some(xdg.clone().into_os_string()), - _ => fixture.get(name), - }, - Some(&fixture.exe), - |_| Ok(()), - ); - assert!(result.is_err(), "accepted {candidate:?} with the XDG folders moved to {xdg:?}"); - } - } - assert!(!config.exists() && !data.exists(), "a refused root creates nothing"); - } - - #[cfg(unix)] - #[test] - fn a_dangling_entry_point_keeps_its_fence_instead_of_refusing_every_launch() { - let fixture = Fixture::new(); - let bin = fixture.root.join("entry/bin"); - std::fs::create_dir_all(&bin).unwrap(); - let entry = bin.join("vectorcraft"); - std::os::unix::fs::symlink(fixture.root.join("uninstalled target"), &entry).unwrap(); - // The shared resolver refuses the dangling link, as a profile root must be. - assert!(canonical_future(&entry).is_err()); - assert_eq!(canonical_future_entry(&entry).unwrap(), std::fs::canonicalize(&bin).unwrap().join("vectorcraft")); - } - - #[test] - fn an_unwritable_profile_is_refused_after_the_probe_and_never_used() { - let fixture = Fixture::new(); - let root = fixture.root.join("nightly"); - let result = fixture.check_with(Platform::Linux, &root, |_| Err(std::io::Error::other("read-only"))); - 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(); - let upper = fixture.root.join("NIGHTLY"); - assert!(fixture.check(Platform::Linux, &upper).is_ok()); - let stable_mac = fixture.home().join("library/application support/vectorcraft"); - assert!(fixture.check(Platform::Mac, &stable_mac).is_err(), "macOS compares folders case-insensitively"); + fn non_empty_abs_ignores_empty_and_relative_values() { + let env = |key: &str| match key { + "EMPTY" => Some(OsString::new()), + "RELATIVE" => Some(OsString::from("relative/path")), + _ => None, + }; + assert!(super::non_empty_abs(&env, "EMPTY").is_none()); + assert!(super::non_empty_abs(&env, "RELATIVE").is_none()); + assert!(super::non_empty_abs(&env, "MISSING").is_none()); } } diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs index 249309fa87..4dba61d6b4 100644 --- a/apps/vectorcraft/src/single_instance.rs +++ b/apps/vectorcraft/src/single_instance.rs @@ -155,8 +155,8 @@ pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> { } /// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-' -/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), or the -/// child would refuse to start without one. +/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), so the +/// child opens the same private profile. fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command { let mut command = std::process::Command::new(exe); command.args(super::launch_profile::child_args(files)); diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index bb4dcbd416..2a92cfb160 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -2,6 +2,7 @@ use std::cell::RefCell; use std::collections::{HashMap, HashSet}; +use std::ops::ControlFlow; use std::rc::Rc; use std::sync::{Arc, OnceLock}; @@ -403,6 +404,8 @@ thread_local! { thread_local! { /// How many objects' drawn art [`drawn`] evaluated on this thread. static DRAWN_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times [`has_own_effects`] read an object's effects on this thread. + static OWN_EFFECTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect @@ -527,7 +530,7 @@ fn plain(mask: bool, f: impl FnOnce() -> T) -> T { /// kept alone. fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option)> { let f = DRAWN_ART.get()?; - if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) { + if DRAWN_OFF.get() || !evaluates(n) || !draws_effects(symbols, n) { return None; } let doc = symbols.document(); @@ -568,7 +571,7 @@ fn evaluates(n: &Node) -> bool { match &n.kind { NodeKind::Path { guide, .. } => !guide, NodeKind::Compound { .. } => true, - NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(), + NodeKind::Group { .. } | NodeKind::Layer { .. } => !n.appearance.items.is_empty() || has_own_effects(n), _ => false, } } @@ -1188,23 +1191,24 @@ pub(crate) fn clip_region_inputs() -> (u64, bool) { /// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only /// then can the registered [`ClipRegion`] find a geometry effect in it. fn has_effects(clip: &Node) -> bool { - let mut found = false; - clip.walk(&mut |n| found |= has_own_effects(n)); - found + clip.try_walk(&mut |n| if has_own_effects(n) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }).is_break() } /// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible -/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. +/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. The walk starts +/// at `n`, so its own effects are read once, here, and it ends at the first object with an effect. fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool { - let mut found = false; - n.walk(&mut |c| { - found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol)); - }); - found + n.try_walk(&mut |c| { + let has = has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol)); + if has { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } + }) + .is_break() } /// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes? fn has_own_effects(n: &Node) -> bool { + #[cfg(test)] + OWN_EFFECTS_READ.with(|c| c.set(c.get() + 1)); let visible = |e: &crate::Effect| e.visible; n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)) } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 2f51917dde..a678797ff5 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -3652,6 +3652,48 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() { assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face"); } +/// A hover over empty canvas past many plain paths reads each path's effects once, and the layer's +/// once. +#[test] +fn hovers_past_plain_paths_read_each_paths_effects_once() { + set_drawn_art(shifted_art); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let paths = 100; + for i in 0..paths { + let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0); + d.insert(Some(l), 0, n).unwrap(); + } + let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get); + let before = reads(); + assert!(hit_test(&d, Point::new(900.0, 900.0), HitOptions::default()).is_none()); + let read = reads() - before; + assert_eq!(read, paths + 1, "each path's effects and the layer's are read once"); + assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit"); +} + +/// Whether a compound clipping path, or a compound path, has a live effect is settled by the first +/// object found with one: the members after it are not read. +#[test] +fn an_effect_on_a_compound_path_is_found_without_reading_its_members() { + set_clip_region(moved_clip_region); + set_drawn_art(shifted_art); + let mut d = Document::new(1000.0, 1000.0); + let members: Vec<_> = (0..100) + .map(|i| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(i as f64, 0.0, i as f64 + 5.0, 5.0)), Default::default()))) + .collect(); + let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero }); + mask.appearance.effects.push(test_move()); + let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get); + let before = reads(); + assert!(has_effects(&mask)); + assert_eq!(reads() - before, 1, "the clipping path's own effect ends the search"); + let symbols = d.symbol_boxes(); + let before = reads(); + assert!(draws_effects(&symbols, &mask)); + assert_eq!(reads() - before, 1, "the compound path's own effect ends the search"); +} + /// The pointer resting over empty canvas past many paths reads their anchors for their culling /// boxes on the first hover only: the next hovers use the boxes the paths keep. #[test] diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index b22f6cbfc7..731fba6d34 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -308,16 +308,8 @@ fn resolve_kids( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec, ) -> Vec<(usize, Arc)> { - let mut by_id: Option>> = None; let mut out = vec![]; - for (i, c) in kids.iter().enumerate() { - let o = old.and_then(|old| match old.get(i) { - Some(b) if b.id == c.id => Some(b), - _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), - }); - if o.is_some_and(|o| Arc::ptr_eq(o, c)) { - continue; - } + for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) { let mut c = c.clone(); if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { out.push((i, c)); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 470b0a94c4..6a331c6b77 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize}; pub use metadata::{CopyrightStatus, DocMetadata}; pub use node::Knockout; pub use node::Scaling; +pub use node::changed_nodes; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use orient::OrientedBox; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 87b9a375db..3a4b2abd03 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes}; use crate::text::TextObject; mod attributes; +mod changed; mod clip; mod extras; mod ids; @@ -25,6 +26,9 @@ mod ops; mod wire; pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +#[cfg(test)] +pub(crate) use changed::COUNTERPART_LOOKUPS; +pub use changed::changed_nodes; pub use clip::{ClipPaint, Uniter}; pub use extras::{Extras, ExtrasMut, NodeExtras}; pub use ids::{LAYER_COLORS, LayerColor, NodeId}; diff --git a/crates/doc/src/node/changed.rs b/crates/doc/src/node/changed.rs new file mode 100644 index 0000000000..4aba12f78e --- /dev/null +++ b/crates/doc/src/node/changed.rs @@ -0,0 +1,33 @@ +use std::collections::HashMap; + +use super::{Arc, Node, NodeId}; + +#[cfg(test)] +thread_local! { + /// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread. + pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same +/// list before an edit), with their positions in `after`. A node's counterpart is the node at the +/// same position when it has the same id, else the node in `before` with its id, else `None` (the +/// node is new). A node that is the same node as the one at its position in `before` is skipped +/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node. +pub fn changed_nodes<'a>(before: &'a [Arc], after: &'a [Arc]) -> impl Iterator, Option<&'a Arc>)> { + let mut by_id: Option>> = None; + after.iter().enumerate().filter_map(move |(i, a)| { + if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) { + return None; + } + #[cfg(test)] + COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1)); + let b = match before.get(i) { + Some(b) if b.id == a.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), + }; + if b.is_some_and(|b| Arc::ptr_eq(b, a)) { + return None; + } + Some((i, a, b)) + }) +} diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 8d6520265a..ed2fdb08d9 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() { assert_eq!(flow, ControlFlow::Break(NodeId(3))); assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]); } + +/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one +/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are +/// the same nodes in the same places are passed over by their pointers. +#[test] +fn changed_nodes_looks_up_only_the_nodes_that_changed() { + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let before: Vec> = (0..1000).map(leaf).collect(); + let mut after = before.clone(); + let mut edited = (*after[500]).clone(); + edited.name = Some("edited".into()); + after[500] = Arc::new(edited); + after.push(leaf(5000)); + COUNTERPART_LOOKUPS.with(|c| c.set(0)); + let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect(); + assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]); + assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2); +} + +/// A node that moved to another place in the list is paired with itself by its id and left out +/// when it is the same node; a changed node that moved is paired with its old node, and a node +/// that is gone from the list gives nothing. +#[test] +fn changed_nodes_pairs_moved_nodes_by_id() { + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)]; + let mut edited = (*before[0]).clone(); + edited.locked = true; + let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)]; + let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect(); + assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]); + assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list"); + assert_eq!(changed_nodes(&[], &after).count(), 3); +} diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs index 7fdb0c5c3e..a46818befb 100644 --- a/crates/engine/src/cmd/addons/image/mask.rs +++ b/crates/engine/src/cmd/addons/image/mask.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch}; -use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::Affine; use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process}; @@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc, old: Option<&Arc>) -> bool { } let Some(children) = n.children() else { return false }; let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice); - let mut by_id: Option>> = None; - children.iter().enumerate().any(|(i, c)| { - let b = match before.get(i) { - Some(b) if b.id == c.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), - }; - stale_in(doc, c, b) - }) + changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b)) } /// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked diff --git a/crates/engine/src/cmd/fontfiles.rs b/crates/engine/src/cmd/fontfiles.rs index c13b256210..4cc41982df 100644 --- a/crates/engine/src/cmd/fontfiles.rs +++ b/crates/engine/src/cmd/fontfiles.rs @@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec { /// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this /// computer's when `None`). pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value { - let fonts: Vec = missing_fonts(&st.doc) + let fonts = missing_font_rows(&st.doc); + let mut out = json!({ "count": fonts.len(), "fonts": fonts }); + if let Some(dir) = fonts_next_to_document(st, rules) { + out["fontsNextToDocument"] = json!(dir); + } + out +} + +/// `text.missingFonts`'s `fonts` rows for `d` ([`missing_fonts`]). +pub fn missing_font_rows(d: &Document) -> Vec { + missing_fonts(d) .into_iter() .map(|m| { json!({ @@ -122,26 +132,26 @@ pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Valu "resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })), }) }) - .collect(); - let mut out = json!({ "count": fonts.len(), "fonts": fonts }); + .collect() +} + +/// `text.missingFonts`'s `fontsNextToDocument` for the open document `st`, where searches go by +/// `rules` (this computer's when `None`). +pub fn fonts_next_to_document(st: &DocState, rules: Option<&findfiles::Rules>) -> Option { // File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder // is made absolute against the working folder when the document's path is relative. It is // offered when a search may start there, as far as the rules tell without listing a folder. - if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) { - let dir = super::fileio::absolute_path(&dir.to_string_lossy()); - let system; - let rules = match rules { - Some(rules) => rules, - None => { - system = findfiles::Rules::system(); - &system - } - }; - if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) { - out["fontsNextToDocument"] = json!(dir); + let dir = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir())?; + let dir = super::fileio::absolute_path(&dir.to_string_lossy()); + let system; + let rules = match rules { + Some(rules) => rules, + None => { + system = findfiles::Rules::system(); + &system } - } - out + }; + std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()).then_some(dir) } fn missing(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 81909da76f..7bef1cbc69 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; -use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign}; +use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes}; use super::{ Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json, @@ -226,15 +226,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) { /// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity /// mask art holds such instances (`masked`). fn changed_instances(before: &[Arc], after: &[Arc], natural: &HashMap, ids: &mut Vec, masked: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) { masked.push(a.id); } @@ -423,15 +415,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { /// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the /// walk stops: [`keep_pixel_aligned`] visits what it holds. fn changed_aligned(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) { out.push(a.id); } else if let Some(children) = a.children() { diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index 7dc8aec1c9..299ed5f49c 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -25,12 +25,12 @@ //! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and //! the objects that move up the path after it; Expand). -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::Rect; use super::edit::{roots_of, selected_roots}; @@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool { /// The Objects on Path groups among `after` and inside them that are not the same nodes as before /// (`before`: the same list before the edit), outer ones first. fn changed_groups(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if is_objects_on_path(a) { out.push(a.id); } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 58612c744c..ba2b523f62 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -1231,12 +1231,24 @@ fn queue(s: &mut Session, p: &Value) -> Result { // ---------- queries ---------- -/// The colour mode an image file stores its pixels in. -fn color_mode(bytes: &[u8]) -> &'static str { - match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) { - Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale", - Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK", - _ => "RGB", +/// The colour mode an image file stores its pixels in. A PNG, JPEG, TIFF, PSD, GIF or BMP file's +/// header says it and a WebP file is always RGB, so their pixels are not decoded; the Control bar +/// and the Properties panel ask `image.info` again after every change, each step of a drag +/// included. A file in another format is decoded. +pub(crate) fn color_mode(bytes: &[u8]) -> &'static str { + use craft_image_codecs::{ChannelLayout as L, RasterColorType as T}; + match craft_image_codecs::inspect_raster(bytes) { + Ok(Some(i)) => match i.color_type { + T::Bitmap | T::Gray | T::GrayAlpha => "Grayscale", + T::Cmyk | T::CmykAlpha => "CMYK", + _ => "RGB", + }, + _ if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::WebP) => "RGB", + _ => match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) { + Some(L::Gray | L::GrayA) => "Grayscale", + Some(L::Cmyk | L::CmykA) => "CMYK", + _ => "RGB", + }, } } diff --git a/crates/engine/src/cmd/shaper.rs b/crates/engine/src/cmd/shaper.rs index 228251fa13..93e479033f 100644 --- a/crates/engine/src/cmd/shaper.rs +++ b/crates/engine/src/cmd/shaper.rs @@ -6,12 +6,9 @@ use super::{ CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param, }; use serde_json::{Value, json}; -use std::{ - collections::{BTreeMap, HashMap}, - sync::Arc, -}; +use std::{collections::BTreeMap, sync::Arc}; use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _}; use vectorcraft_pathops as po; use vectorcraft_tools::builder::{self as b, BuilderMap}; @@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc], spec: &ShaperSpec, map: &Build } fn changed_shaper_groups(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().shaper.is_some() { out.push(a.id); } diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 94da32aa01..c38dd53452 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -247,6 +247,62 @@ fn replace_keeps_the_transform_and_the_stacking_place() { assert_eq!(top_children(&s)[0].id.0, first.as_u64().unwrap(), "one undo step brings the old image back"); } +/// `image.info` reads a PNG's colour mode from its header without decoding its pixels: a grayscale +/// PNG whose compressed pixel data is unreadable still says Grayscale. The Control bar asks again +/// after every step of a drag, so a decode there redid a large image's whole decode each step. +#[test] +fn image_color_mode_reads_the_header_without_decoding_the_pixels() { + let raw: Vec = (0..64u32 * 64).map(|i| (i * 7 % 251) as u8).collect(); + let gray = craft_image_codecs::Image::from_raw(64, 64, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap(); + let mut png = craft_image_codecs::encode(&gray, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + assert_eq!(cmd::place::color_mode(&png), "Grayscale"); + // Each IDAT chunk's data zeroed (an invalid zlib stream) under a correct CRC. + let mut at = 8; + let mut idat = 0; + while at + 12 <= png.len() { + let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize; + if &png[at + 4..at + 8] == b"IDAT" { + png[at + 8..at + 8 + len].fill(0); + let crc = crc32fast::hash(&png[at + 4..at + 8 + len]); + png[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes()); + idat += 1; + } + at += 12 + len; + } + assert!(idat > 0, "the PNG has pixel data"); + assert!(craft_image_codecs::decode(&png).is_err(), "the pixels no longer decode"); + assert_eq!(cmd::place::color_mode(&png), "Grayscale", "the header alone gives the colour mode"); +} + +/// The colour mode read from a file's header is the one its decoded pixels have, in every format +/// and channel layout the codecs write. +#[test] +fn image_color_mode_from_the_header_matches_the_decoded_pixels() { + use craft_image_codecs::{ChannelLayout as L, Format as F}; + let decoded = |bytes: &[u8]| match craft_image_codecs::decode(bytes).map(|i| i.layout()) { + Ok(L::Gray | L::GrayA) => "Grayscale", + Ok(L::Cmyk | L::CmykA) => "CMYK", + Ok(_) => "RGB", + Err(e) => panic!("the written file decodes: {e}"), + }; + let mut seen = std::collections::BTreeSet::new(); + let mut checked = 0; + for format in [F::Png, F::Jpeg, F::Tiff, F::Gif, F::Bmp, F::WebP] { + for layout in [L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk] { + let n = 16 * 16 * layout.channels(); + let raw: Vec = (0..n).map(|i| (i * 13 % 256) as u8).collect(); + let img = craft_image_codecs::Image::from_raw(16, 16, layout, craft_image_codecs::SampleType::U8, raw).unwrap(); + let Ok(bytes) = craft_image_codecs::encode(&img, format, &craft_image_codecs::EncodeOptions::default()) else { continue }; + let want = decoded(&bytes); + assert_eq!(cmd::place::color_mode(&bytes), want, "{format:?} written from {layout:?}"); + seen.insert(want); + checked += 1; + } + } + assert!(checked >= 12, "{checked} files written"); + assert_eq!(seen.into_iter().collect::>(), ["CMYK", "Grayscale", "RGB"]); +} + #[test] fn replace_needs_exactly_one_selected_object() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 6cd51a5a1d..4ecff31b3b 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2347,29 +2347,35 @@ static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(()); struct HeldLoad { _lock: std::sync::MutexGuard<'static, ()>, entered: std::sync::Arc, - go: std::sync::Arc, + go: std::sync::Arc<(std::sync::Mutex, std::sync::Condvar)>, gave_up: std::sync::Arc, } impl HeldLoad { - /// Holds the load of the file at `path`. A load the test never lets go gives up after a - /// million yields (so a test of code that waits for it ends) and says so in `gave_up`. + /// Holds the load of the file at `path` until [`HeldLoad::release`] or the drop. A load that + /// runs on the thread that made this one is not held, since nothing could let it go: it goes + /// ahead at once and says so in `gave_up`. fn new(path: std::path::PathBuf) -> HeldLoad { - use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Condvar, Mutex}; let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()); - let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false))); + let (entered, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false))); + let go = Arc::new((Mutex::new(false), Condvar::new())); let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone()); + let test_thread = std::thread::current().id(); *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| { if p != path { return; } e.store(true, Ordering::SeqCst); - if !(0..1_000_000).any(|_| { - std::thread::yield_now(); - g.load(Ordering::SeqCst) - }) { + if std::thread::current().id() == test_thread { q.store(true, Ordering::SeqCst); + return; + } + let (open, opened) = &*g; + let mut open = open.lock().unwrap_or_else(|e| e.into_inner()); + while !*open { + open = opened.wait(open).unwrap_or_else(|e| e.into_inner()); } })); HeldLoad { _lock: lock, entered, go, gave_up } @@ -2380,7 +2386,9 @@ impl HeldLoad { } fn release(&self) { - self.go.store(true, std::sync::atomic::Ordering::SeqCst); + let (open, opened) = &*self.go; + *open.lock().unwrap_or_else(|e| e.into_inner()) = true; + opened.notify_all(); } fn gave_up(&self) -> bool { @@ -2904,6 +2912,7 @@ fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() { #[test] fn a_query_runs_while_the_plugins_load() { let id = "test.engine.background.query"; + assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info")); let (folder, path) = store_with("plugin-background-query", id); let held = HeldLoad::new(path); let mut s = session(); @@ -2917,7 +2926,6 @@ fn a_query_runs_while_the_plugins_load() { let waited = held.gave_up() || !s.plugins_loading(); held.release(); assert!(!waited, "document.info waited for the plug-ins to load"); - assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info")); s.finish_plugin_loads(); assert!(vectorcraft_plugins::registry::remove(id)); } @@ -2935,18 +2943,14 @@ fn stored_plugins_load_without_holding_the_plugin_changes_lock() { while !held.entered() && !held.gave_up() { std::thread::yield_now(); } - // Other tests take the lock for a moment; the load holding it would hold it throughout (a - // tenth of the yields the held load waits before it gives up). - let free = (0..100_000).any(|_| { + // A load run on this thread isn't held, so a free lock then shows nothing. + assert!(!held.gave_up(), "the module loaded on the test's thread"); + // Other tests take the lock for a moment; the held load holding it would hold it until it is let go. + while !crate::cmd::plugin::plugin_changes_free() { std::thread::yield_now(); - crate::cmd::plugin::plugin_changes_free() - }); - // A load that gave up waiting no longer holds anything, so a free lock then shows nothing. - let gave_up = held.gave_up(); + } held.release(); s.finish_plugin_loads(); - assert!(!gave_up, "the held load gave up before the lock was looked at"); - assert!(free, "the lock was held while the module loaded"); assert!(vectorcraft_plugins::registry::remove(id)); } @@ -2974,6 +2978,10 @@ fn canceled_loads_forget_the_grants_of_what_they_installed() { std::thread::yield_now(); } assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads"); + assert!(s.plugins_loading(), "the second module is still loading"); + // Canceling waits for a running load until its deadline; the second module, let go, loads + // while the cancel runs or before it, and doesn't install either way. + held.release(); s.cancel_plugin_loads(); // The file goes once it holds no grant. let listed: Vec = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6271e758d2..84ab44d769 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -134,6 +134,7 @@ impl VectorcraftApp { print_tiling: None, live_paint_gaps: None, find_font: None, + missing_fonts: vec![], hidden_chars: Default::default(), spelling: Default::default(), text_nodes: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6679ecf591..7f0ade064e 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -64,6 +64,10 @@ pub struct CanvasCache { /// version of the document's content and of the available fonts: the dialog reads them every /// frame. pub find_font: Option, + /// The missing fonts of each document whose Missing Fonts dialog waits to open, for a version of + /// the document's content and of the available fonts: the frame that checks whether a dialog + /// waits and the frame's pump that opens it read the same list. + pub missing_fonts: Vec, /// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame /// that does not draw them drops them ([`canvas::show`]). pub hidden_chars: canvas::marks::HiddenChars, @@ -253,6 +257,15 @@ pub struct FindFontCache { pub missing: Option, } +/// [`CanvasCache::missing_fonts`]: a document's `text.missingFonts` rows +/// ([`vectorcraft_engine::cmd::fontfiles::missing_font_rows`]). +#[derive(Clone, Debug)] +pub struct MissingFontsCache { + /// The document and the content and fonts the rows were worked out from. + pub key: FontsKey, + pub fonts: Vec, +} + /// A document's uid, a version of its content (compared by identity) and the font database's /// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's /// allocation, so a later version is never placed at the same address while the key is kept. diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 96a32785e3..bd06b24e40 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -35,6 +35,7 @@ use egui::{Context, Ui}; use serde_json::{Map, Value, json}; use crate::VectorcraftApp; +use crate::caches::{FontsKey, MissingFontsCache}; use crate::file_asks::{self, Owner}; /// The dialog's key and kind: the fonts a document opened without. @@ -327,19 +328,45 @@ fn after_open_for(app: &mut VectorcraftApp, r: &Value, web: bool) { } /// Whether an opened document's Missing Fonts dialog waits for the frame's pump to open it. -pub(crate) fn waiting(app: &VectorcraftApp) -> bool { - app.ui.pending_fonts.iter().any(|&uid| dialog_for(app, uid).is_some()) +pub(crate) fn waiting(app: &mut VectorcraftApp) -> bool { + let queued = app.ui.pending_fonts.clone(); + queued.into_iter().any(|uid| missing_rows(app, uid).is_some_and(|fonts| !fonts.is_empty())) } /// The Missing Fonts dialog of the open document `uid`, when fonts it uses aren't available. -fn dialog_for(app: &VectorcraftApp, uid: u64) -> Option { +fn dialog_for(app: &mut VectorcraftApp, uid: u64) -> Option { + let fonts = missing_rows(app, uid).filter(|f| !f.is_empty())?; let st = app.session.documents().iter().find(|d| d.uid == uid)?; - let r = vectorcraft_engine::cmd::fontfiles::missing_fonts_of(st, app.session.search_rules.as_ref()); - let fonts = r["fonts"].as_array().filter(|f| !f.is_empty())?.clone(); - let next = r["fontsNextToDocument"].as_str().unwrap_or_default().to_string(); + let next = vectorcraft_engine::cmd::fontfiles::fonts_next_to_document(st, app.session.search_rules.as_ref()).unwrap_or_default(); Some(MissingFontsDialog::new(State::new(uid, fonts, next, file_asks::can(app, PickKind::Folder)))) } +#[cfg(test)] +thread_local! { + /// How many times [`missing_rows`] worked out a document's missing fonts. + static ROW_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The `text.missingFonts` rows of the open document `uid` (`None` when it is closed), kept in +/// [`crate::CanvasCache::missing_fonts`] and worked out again only for another version of its +/// content or another font generation. +fn missing_rows(app: &mut VectorcraftApp, uid: u64) -> Option> { + let st = app.session.documents().iter().find(|d| d.uid == uid)?; + // The generation is read first: fonts loaded while the rows are worked out leave the entry + // under the older generation, so the next look works them out again. + let key = FontsKey { uid, doc: std::sync::Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() }; + if let Some(c) = app.canvas.missing_fonts.iter().find(|c| c.key == key) { + return Some(c.fonts.clone()); + } + #[cfg(test)] + ROW_SCANS.set(ROW_SCANS.get() + 1); + let fonts = vectorcraft_engine::cmd::fontfiles::missing_font_rows(&st.doc); + let cache = &mut app.canvas.missing_fonts; + cache.retain(|c| c.key.uid != uid); + cache.push(MissingFontsCache { key, fonts: fonts.clone() }); + Some(fonts) +} + /// Once per frame: run what the finished dialog left to do, follow a running search, stop the search /// of a dialog that is gone, and with no dialog open open the dialog of the first queued document /// that is still open and still misses fonts. @@ -360,6 +387,9 @@ pub(crate) fn open_next(app: &mut VectorcraftApp) { } break; } + // Only the documents that still wait keep their rows. + let queued = &app.ui.pending_fonts; + app.canvas.missing_fonts.retain(|c| queued.contains(&c.key.uid)); } /// Run what `answer` asks, and open the dialog again when it stays open (a search starts, a search diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index dad177950a..de32e2cbe6 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -445,6 +445,40 @@ fn reopening_an_open_document_does_not_ask_about_its_fonts_again() { assert!(!is_open::(&app)); } +/// The frame after an open checks whether a Missing Fonts dialog waits (before a file that finished +/// opening may come to the front) and then opens it: the document's missing fonts are worked out +/// once for both. +#[test] +fn the_frame_after_an_open_works_out_the_missing_fonts_once() { + let root = folder("once"); + let mut app = app_for(&root); + let doc = root.join("doc.vectorcraft"); + save_doc(&mut app, &doc, "No Such Font Family", false); + open(&mut app, &doc); + ROW_SCANS.set(0); + assert!(!crate::opening::may_switch(&mut app), "the dialog waits for the pump"); + pump(&mut app); + assert_eq!(family(&app).as_deref(), Some("No Such Font Family")); + assert_eq!(ROW_SCANS.get(), 1, "one look at the document's fonts"); + assert!(app.canvas.missing_fonts.is_empty(), "the rows go once the dialog opens"); +} + +/// A document changed while its dialog waits lists the fonts of its new content. +#[test] +fn a_document_changed_while_its_dialog_waits_lists_its_new_fonts() { + let root = folder("changed"); + let mut app = app_for(&root); + let doc = root.join("doc.vectorcraft"); + save_doc(&mut app, &doc, "Alpha Missing Family", false); + open(&mut app, &doc); + assert!(!crate::opening::may_switch(&mut app)); + app.run("text.create", json!({"x": 10, "y": 80, "text": "More", "font": "Beta Missing Family"})).unwrap(); + pump(&mut app); + let fonts = fields(&app).expect("the dialog is open")["fonts"].clone(); + let families: Vec<_> = fonts.as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap_or_default()).collect(); + assert_eq!(families, ["Alpha Missing Family", "Beta Missing Family"]); +} + /// A placed document that Links › Edit Original opens asks about its fonts, as File › Open does. #[test] fn edit_original_asks_about_the_placed_documents_fonts() { diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index a3acab8b0b..5d2d8ee72e 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -14,7 +14,6 @@ use craft::ui::contract::{Bind, CollectionEvent, Gap, Props as _, Show as _, Sho use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows}; use craft::ui::pickers::Select; -use craft::ui::runtime::env::LengthUnits; use craft::ui::runtime::env::UnitKind; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::tabs::{Tab, TabKind, TabStrip}; @@ -194,12 +193,11 @@ impl Rows<'_> { self.range(key, label, range, 1, UnitKind::Percent) } - /// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says. + /// A length in points, shown in the general unit as [`length_units`](super::three_d_classic::length_units) says. fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param { - // Stored in points; a pixel is a point, as the rulers count it. - let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0); - let shown = super::three_d_classic::length_unit(self.unit); - self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points)) + let lengths = super::three_d_classic::length_units(self.unit, self.bare_points); + let row = Param::new(key, label, ParamKind::range(range.0, range.1, self.default_number(key), SliderScale::Linear)).resettable(); + super::three_d_classic::as_length(row, lengths) } fn flag(&self, key: &str, label: &'static str) -> Param { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index ceb96018f7..16b99491a6 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -494,10 +494,10 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() { assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent))); } -/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their -/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit. +/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, hold points and show the +/// document's unit: "pt" in a points document, "px" in a pixels one, "mm" in a millimeters one, "in" in an inches one. #[test] -fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { +fn the_3d_length_rows_show_the_document_unit() { use craft::ui::patterns::form_dialogs::DialogFields; use craft::ui::runtime::env::UnitKind; use vectorcraft_doc::Unit; @@ -510,7 +510,13 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit) }; let mut checked = 0; - for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] { + let units = [ + (Unit::Points, UnitKind::Points), + (Unit::Pixels, UnitKind::Pixels), + (Unit::Millimeters, UnitKind::Millimetres), + (Unit::Inches, UnitKind::Inches), + ]; + for (general, shown) in units { for key in ["depth", "bevelWidth", "bevelHeight"] { assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}"); checked += 1; @@ -526,7 +532,56 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { checked += 1; } } - assert_eq!(checked, 21); + assert_eq!(checked, 28); +} + +/// In a millimeters document the 3D dialogs' depth and offset fields show the 72 pt they hold as 25.4 mm, and a +/// number typed there is read in millimeters and kept unrounded; Up steps by a millimeter step. +#[test] +fn a_3d_dialog_in_a_millimeters_document_shows_its_lengths_in_millimeters() { + use craft::ui::contract::Role; + let rows = [ + (CLASSIC_EXTRUDE, "object", "depth", "Depth"), + (CLASSIC_REVOLVE, "object", "offset", "Offset"), + (EXTRUDE, "object", "depth", "Depth"), + (REVOLVE, "rotation", "offset", "Offset"), + ]; + for (effect, page, key, name) in rows { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300,"units":"Millimeters"})).unwrap(); + app.run("path.create", json!({"d": SQUARE})).unwrap(); + let mut h = opened(app, json!({"effect": effect, "item": null})); + h.set("__page", json!(page)); + h.set(key, json!(72.0)); + let field = |h: &ThreeD| { + let tree = h.fixture.tree(); + h.fixture + .by_role(Role::SPIN_BUTTON) + .into_iter() + .find(|t| tree.name_of(t.node) == Some(name)) + .unwrap_or_else(|| panic!("{effect}: no {name} field")) + }; + let shown = h.fixture.tree().value_of(field(&h).node).map(str::to_owned); + assert!(shown.as_deref().is_some_and(|s| s.contains("25.4") && s.contains("mm")), "{effect} {key}: 72 pt shows as 25.4 mm: {shown:?}"); + let target = field(&h); + h.fixture.click(&target); + // Tab commits the field and leaves the dialog open (Enter would press OK). + h.fixture.key(Key::A, Modifiers::COMMAND).type_text("10").key(Key::Tab, Modifiers::NONE); + h.settle(); + let stored = h.json(key); + assert!( + stored.as_f64().is_some_and(|points| (points - 10.0 * 72.0 / 25.4).abs() < 1e-3), + "{effect} {key}: 10 mm is kept in points: {stored:?}" + ); + // Up moves by the shown unit's own step, at least a tenth of a millimeter. + let target = field(&h); + h.fixture.click(&target); + h.fixture.key(Key::ArrowUp, Modifiers::NONE).key(Key::Tab, Modifiers::NONE); + h.settle(); + let moved = h.json(key).as_f64().zip(stored.as_f64()).map(|(after, before)| after - before); + assert!(moved.is_some_and(|by| by >= 0.1 * 72.0 / 25.4 - 1e-6), "{effect} {key}: Up moves at least 0.1 mm: {moved:?}"); + h.cancel(); + } } #[test] diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index f461b3cfe2..1a5acb6f6f 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -20,7 +20,7 @@ use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; use craft::ui::pickers::Select; use craft::ui::primitives::ContentPainterCx; -use craft::ui::runtime::env::{Env, UnitKind}; +use craft::ui::runtime::env::{Env, LengthUnits, UnitKind}; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::style::DataColor; use craft::ui::text::NumberField; @@ -50,13 +50,23 @@ const MAP_SYMBOL: &str = "mapSymbol"; /// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters. pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]]; -/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when -/// that counts the same number (points, or pixels at 72 per inch), and points otherwise. -pub(super) fn length_unit(unit: Unit) -> UnitKind { - match crate::canvas::rulers::unit_kind(unit) { - UnitKind::Pixels => UnitKind::Pixels, - _ => UnitKind::Points, - } +/// The lengths of a 3D length row: stored in points and shown in the general `unit` (a pixel is a point, as the rulers +/// count it), a bare number read as Numbers Without Units Are Points (`bare_points`) says. +pub(super) fn length_units(unit: Unit, bare_points: bool) -> LengthUnits { + crate::fields::bare_points(LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(unit), 72.0), bare_points) +} + +/// `row`, a range row of points with no decimals set, as a length shown in `lengths.shown`. Without set decimals the +/// field keeps the shown unit's own places and step, and the points are kept unrounded, so a value typed in +/// millimeters or inches reads back as typed. +pub(super) fn as_length(row: Param, lengths: LengthUnits) -> Param { + row.unit(lengths.shown).length(lengths) +} + +/// A length row over `range` points with the effect's default, shown as [`as_length`] says. +fn length_row(effect: &str, key: &str, label: &'static str, range: (f64, f64), lengths: LengthUnits) -> Param { + let default = vectorcraft_effects::default_params(effect).and_then(|p| p.get(key).and_then(Value::as_f64)).unwrap_or(range.0); + as_length(Param::new(key, label, ParamKind::range(range.0, range.1, default, SliderScale::Linear)).resettable(), lengths) } /// Where the rows show: the 3D and Materials panel marks its fields with `__panel`. @@ -120,15 +130,15 @@ fn map_art_button(fields: &DialogFields) -> Option { /// Extrude & Bevel (Classic)'s Object page: depth and cap, then the bevel: its shape (a custom one included), its /// height and whether it is added around the shape or carved into it. pub(crate) fn object_params(data: &Data, fields: &DialogFields, effect: &str) -> Vec { - let unit = Some(length_unit(data.unit)); + let lengths = length_units(data.unit, data.bare_points); let shaped: Vec<&str> = options_of(effect, "bevel").into_iter().map(|(value, _)| value).filter(|v| *v != "none").collect(); let mut rows = vec![ Param::section(tl!("Object")), - range_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), unit, 1), + length_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), lengths), cap_row(effect), Param::section(c3("Bevel")), bevel_row(data, CLASSIC_EXTRUDE, place_of(fields)), - range_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), unit, 1).enabled_when_in("bevel", shaped.clone()), + length_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), lengths).enabled_when_in("bevel", shaped.clone()), toggle_row(effect, "bevelInside", tl!("Bevel Inside")).enabled_when_in("bevel", shaped), ]; rows.extend(map_art_button(fields)); @@ -141,7 +151,7 @@ pub(crate) fn revolve_params(data: &Data, fields: &DialogFields, effect: &str) - Param::section(tl!("Object")), range_row(effect, "angle", tl!("Angle"), (0.0, 360.0), Some(UnitKind::Degrees), 1), cap_row(effect), - range_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), Some(length_unit(data.unit)), 1), + length_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), length_units(data.unit, data.bare_points)), choice_row(effect, "edge", tl!("Axis side")), ]; rows.extend(map_art_button(fields)); @@ -272,8 +282,9 @@ fn set_map_value(fields: &mut DialogFields, key: &str, value: Value) -> Result<( let n = value.as_f64().filter(|n| n.is_finite()).ok_or("not a number")?; let mut m = old.ok_or("the surface has no map")?; match key { - "mapX" => m.x = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET), - "mapY" => m.y = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET), + // X and Y arrive in points converted from the document's unit: rounding them would move a typed 10 mm. + "mapX" => m.x = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET), + "mapY" => m.y = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET), "mapScaleX" => m.scale_x = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1), "mapScaleY" => m.scale_y = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1), "mapRotation" => m.rotation = n.clamp(-360.0, 360.0), @@ -370,6 +381,12 @@ fn map_of_box(state: &BoxState, rect: Rect, base: &SurfaceMap) -> SurfaceMap { } } +/// The map a box edit leaves, or none while the box is still the one `map` drew (`drawn`), so a frame without an edit +/// keeps the map's numbers exactly as typed. +fn map_after_edit(state: &BoxState, drawn: &BoxState, rect: Rect, map: &SurfaceMap) -> Option { + (state != drawn).then(|| map_of_box(state, rect, map)).filter(|moved| moved != map) +} + /// The id of Map Art's Done, in the footer as Reset all is on the other pages. pub(crate) const MAP_DONE: &str = "mapDone"; @@ -406,6 +423,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response { } let (Some(m), Some(rect)) = (map.as_ref(), rect) else { return }; let mut state = map_box(m, rect); + let drawn = state; if m.rotation.abs() < 0.01 && let (Some(doc), Some((w, h))) = (flat.doc.as_ref(), flat.art) { @@ -422,8 +440,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response { .reference_point(false) .rotate_zone(RotateZone::border(18.0)) .show_at(ui, body.rect); - let moved = map_of_box(&state, rect, m); - if moved != *m { + if let Some(moved) = map_after_edit(&state, &drawn, rect, m) { edited = Some(moved); } }); @@ -505,7 +522,7 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) - let flat_row = flat.clone(); rows.push(Param::custom("__mapFlat", "", move |ui, fields, _| flat_view(ui, fields, &flat_row)).full_width()); if let Some(m) = &map { - let unit = Some(length_unit(data.unit)); + let lengths = length_units(data.unit, data.bare_points); let values = [m.x, m.y, m.scale_x, m.scale_y, m.rotation]; let labels = ["X", "Y", tl!("Horizontal Scale"), tl!("Vertical Scale"), tl!("Rotation")]; let bounds = [ @@ -515,14 +532,14 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) - GRAPHIC_SCALE_RANGE, (-360.0, 360.0), ]; - let kinds = [unit, unit, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)]; + // X and Y are lengths in points; the scales are shares and the rotation an angle. + let kinds = [None, None, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)]; for i in 0..MAP_KEYS.len() { - let row = Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear)) - .decimals(2) - .on_set(set_map_value); + let row = + Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear)).on_set(set_map_value); rows.push(match kinds[i] { - Some(kind) => row.unit(kind), - None => row, + Some(kind) => row.decimals(2).unit(kind), + None => as_length(row, lengths), }); } } @@ -575,4 +592,26 @@ mod tests { let turned = map(190.0); assert_eq!(map_of_box(&map_box(&turned, rect), rect, &turned).rotation, -170.0, "a turn wraps to ±180"); } + + #[test] + fn map_offsets_keep_the_points_a_document_unit_converts_to() { + // 10 mm, as the X and Y rows hand it over in points. + let ten_mm = 10.0 * 72.0 / 25.4; + let mut fields = DialogFields::new(); + store_map(&mut fields, 1, Some(&map(0.0))); + assert_eq!(set_map_value(&mut fields, "mapX", json!(ten_mm)), Ok(())); + assert_eq!(set_map_value(&mut fields, "mapY", json!(-ten_mm)), Ok(())); + let stored = maps_of(&fields).into_iter().find(|m| m.surface == 1).map(|m| (m.x, m.y)); + assert_eq!(stored, Some((ten_mm, -ten_mm)), "the typed offset is stored unrounded"); + assert_eq!(set_map_value(&mut fields, "mapX", json!(GRAPHIC_MAX_OFFSET * 2.0)), Ok(())); + assert_eq!(maps_of(&fields).first().map(|m| m.x), Some(GRAPHIC_MAX_OFFSET), "the offset still keeps to its bounds"); + + // A frame without a box edit leaves those numbers as they are. + let rect = art_rect((20.0, 10.0)); + let typed = SurfaceMap { x: ten_mm, y: -ten_mm, ..map(0.0) }; + let drawn = map_box(&typed, rect); + assert_eq!(map_after_edit(&drawn, &drawn, rect, &typed), None); + let dragged = drawn.moved(Vec2::new(1.0, 0.0)); + assert!(map_after_edit(&dragged, &drawn, rect, &typed).is_some(), "a drag still edits the map"); + } } diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index f45209ee65..5e72952fe2 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -147,9 +147,12 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver bool { +pub(crate) fn may_switch(app: &mut VectorcraftApp) -> bool { + if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) { + return false; + } let s = &app.session; - !(app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) || s.in_interaction() || (s.tool_busy() && s.pointer_held())) + !(s.in_interaction() || (s.tool_busy() && s.pointer_held())) } /// Open the files that are ready (each frame). Not while a dialog is open: a document that opens diff --git a/sonar-project.properties b/sonar-project.properties index 9523d64b0e..2f69afe794 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -18,3 +18,6 @@ sonar.issue.ignore.multicriteria=pdf_md5 sonar.issue.ignore.multicriteria.pdf_md5.ruleKey=rust:S4790 sonar.issue.ignore.multicriteria.pdf_md5.resourceKey=crates/pdf/src/encrypt.rs sonar.coverage.exclusions=packaging/** + +# Produced by the shared workflow Python coverage step. +sonar.python.coverage.reportPaths=python-coverage.xml