mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
Merge main into docs/rescore-current
This commit is contained in:
commit
bf1ca62e40
108 files changed
+3225
-584
No files matched your search
@@ -123,7 +123,9 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
|
||||
@@ -11,9 +11,9 @@ permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
|
||||
# Enabled for automated scheduled producer completions on main.
|
||||
if: >-
|
||||
false && github.repository == 'storytold/vectorcraft' &&
|
||||
github.repository == 'storytold/vectorcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: VectorCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
# Automated daily nightly builds at 06:30 UTC, plus supervised manual runs by reviewed manual actors.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 6 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
Generated
+181
-179
File diff suppressed because it is too large.
Load diff
+51
-51
@@ -4,57 +4,57 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.25.0"
|
||||
version = "0.25.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
|
||||
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
|
||||
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" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -194,22 +194,22 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -112,6 +112,43 @@ use prefs::{load_prefs, log_dir, open_store, prefs_enabled};
|
||||
const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0];
|
||||
const MIN_SIZE: [f32; 2] = [800.0, 500.0];
|
||||
|
||||
/// Apply the saved main-window placement before the first frame. On a first launch the
|
||||
/// framework maximizes the window when its default size would not fit the current screen.
|
||||
fn restore_main_window(window: &winit::window::Window, store: &Store, legacy: Option<vectorcraft_ui_egui::state::LegacyWindow>, wayland: bool) {
|
||||
use craft::behavior::placement::{Defaults, Placement, place};
|
||||
use craft::behavior::{Monitor, MonitorKey};
|
||||
use winit::dpi::{LogicalSize, PhysicalPosition};
|
||||
|
||||
let handles: Vec<_> = window.available_monitors().collect();
|
||||
let monitors: Vec<_> = handles
|
||||
.iter()
|
||||
.map(|monitor| {
|
||||
let size = monitor.size();
|
||||
let size = [size.width, size.height];
|
||||
let position = monitor.position();
|
||||
Monitor::new(MonitorKey::new(monitor.name().unwrap_or_default(), size), [position.x, position.y], size, monitor.scale_factor() as f32)
|
||||
})
|
||||
.collect();
|
||||
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor));
|
||||
let defaults = Defaults::new(DEFAULT_SIZE, MIN_SIZE).with_no_position(wayland);
|
||||
let saved = store.get(craft::window::restore::MAIN).or_else(|| {
|
||||
let old = legacy?;
|
||||
let mut placement = Placement::new(old.size, window.scale_factor() as f32);
|
||||
placement.position_px = old.pos;
|
||||
placement.maximized = old.maximized;
|
||||
placement.repaired()
|
||||
});
|
||||
let placement = place(saved.as_ref(), &monitors, home, &defaults);
|
||||
if let Some([x, y]) = placement.position_px {
|
||||
window.set_outer_position(PhysicalPosition::new(x, y));
|
||||
}
|
||||
let [width, height] = placement.normal.size;
|
||||
let _ = window.request_inner_size(LogicalSize::new(width, height));
|
||||
if placement.maximized {
|
||||
window.set_maximized(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets
|
||||
/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches
|
||||
/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon.
|
||||
@@ -781,9 +818,13 @@ fn main() -> std::process::ExitCode {
|
||||
Box::new(move |cc| {
|
||||
let ctx = &cc.egui_ctx;
|
||||
let winit_window = cc.winit_window().cloned();
|
||||
let placement = placement_store();
|
||||
if let Some(window) = &winit_window {
|
||||
restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland);
|
||||
}
|
||||
let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows))
|
||||
.app_id(vectorcraft_ui_egui::os_window::app_id())
|
||||
.placement(Arc::new(Mutex::new(placement_store())))
|
||||
.placement(Arc::new(Mutex::new(placement)))
|
||||
.frame(decision);
|
||||
let spec = match start_pen(&winit_window) {
|
||||
Some(pen) => spec.pen(pen),
|
||||
@@ -798,7 +839,7 @@ fn main() -> std::process::ExitCode {
|
||||
};
|
||||
let (files, file_panels) = file_service(wake, folders);
|
||||
let files = Arc::new(files);
|
||||
craft::host::Host::builder(AppInfo {
|
||||
let host = craft::host::Host::builder(AppInfo {
|
||||
id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID,
|
||||
name: vectorcraft_ui_egui::os_window::name(),
|
||||
version: vectorcraft_ui_egui::os_window::version(),
|
||||
@@ -806,7 +847,8 @@ fn main() -> std::process::ExitCode {
|
||||
.i18n(vectorcraft_ui_egui::i18n::shared())
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.files(files.clone())
|
||||
.install(ctx);
|
||||
.build();
|
||||
host.clone().install(ctx);
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
@@ -831,6 +873,7 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_proof_setups(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
|
||||
app.host = Arc::new(host);
|
||||
app.adopt_context(&cc.egui_ctx);
|
||||
// A nightly is updated by the Launcher: it never checks for a stable release, which
|
||||
// would install this program's own updater over the nightly build.
|
||||
|
||||
@@ -874,6 +874,9 @@ pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
/// What the fill and stroke proxies read from the selected objects, kept with the selection
|
||||
/// ([`crate::doc_state::SelectionRecord`]).
|
||||
pub(crate) use paint::SelectionPaints;
|
||||
/// The faces and edges of Live Paint groups among objects that count with their group
|
||||
/// ([`crate::DocState::live_paint_covered_kept`] keeps an empty answer).
|
||||
pub(crate) use paint::live_paint_covered;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ};
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut",
|
||||
["Edit"],
|
||||
Some("Cmd+X"),
|
||||
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
|
||||
"{artboard?: index (the source artboard for copied objects), selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
cut
|
||||
),
|
||||
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy",
|
||||
["Edit"],
|
||||
Some("Cmd+C"),
|
||||
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
|
||||
"{artboard?: index (the source artboard for copied objects; without it, the artboard containing the selection center), selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
copy
|
||||
),
|
||||
@@ -967,7 +967,8 @@ pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
|
||||
}
|
||||
#[cfg(test)]
|
||||
ROOTS_FOUND.set(ROOTS_FOUND.get() + 1);
|
||||
let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc));
|
||||
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
|
||||
let roots = roots_placed(&st.doc, ids, &paths, |_, _| false);
|
||||
*kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone()));
|
||||
roots
|
||||
})
|
||||
@@ -1015,7 +1016,19 @@ pub(crate) fn no_symbol_part(s: &Session) -> std::result::Result<(), String> {
|
||||
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
|
||||
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
|
||||
Ok(roots_placed(&st.doc, ids, &paths, |_, _| true))
|
||||
}
|
||||
|
||||
/// The objects of `objects` that are in `doc`, in paint order as
|
||||
/// [`vectorcraft_doc::Selection::in_paint_order`] gives them, with their places in the tree. One
|
||||
/// walk finds the places for both the order and [`roots_placed`] ([`roots_within`] after
|
||||
/// `in_paint_order` walks the tree twice).
|
||||
fn placed_in_paint_order(doc: &Document, objects: &[NodeId]) -> (Vec<NodeId>, HashMap<NodeId, Vec<usize>>) {
|
||||
let paths = doc.index_paths(objects.iter().copied());
|
||||
let mut ids: Vec<NodeId> = objects.iter().copied().filter(|id| paths.contains_key(id)).collect();
|
||||
ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
|
||||
(ids, paths)
|
||||
}
|
||||
|
||||
/// [`selected_roots`] for the selected objects inside the isolated object `root`
|
||||
@@ -1027,8 +1040,9 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
|
||||
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
|
||||
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
|
||||
let ids = ids.into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
|
||||
Ok(roots_placed(&st.doc, ids, &paths, |compound, _| members || compound == root))
|
||||
}
|
||||
|
||||
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
|
||||
@@ -1042,6 +1056,11 @@ pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
fn roots_within(doc: &Document, ids: Vec<NodeId>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
|
||||
// Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
|
||||
let paths = doc.index_paths(ids.iter().copied());
|
||||
roots_placed(doc, ids, &paths, keep_member)
|
||||
}
|
||||
|
||||
/// [`roots_within`] with `paths`, the places of `ids` in `doc`'s tree, found already.
|
||||
fn roots_placed(doc: &Document, ids: Vec<NodeId>, paths: &HashMap<NodeId, Vec<usize>>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
|
||||
// A compound-path member acts as its compound (compounds are one object).
|
||||
let mut sel: Vec<(NodeId, Option<Vec<usize>>)> = ids
|
||||
.into_iter()
|
||||
@@ -1105,7 +1124,8 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
|
||||
st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m)))
|
||||
})
|
||||
};
|
||||
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound));
|
||||
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
|
||||
let roots = roots_placed(&st.doc, ids, &paths, |compound, _member| in_isolated_compound || !all_members_whole(compound));
|
||||
Ok((direct, roots))
|
||||
}
|
||||
|
||||
@@ -1163,6 +1183,13 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
clip.source_artboard = board.map(|a| a.rect);
|
||||
}
|
||||
if let Some(value) = p.get("artboard") {
|
||||
let board = value
|
||||
.as_u64()
|
||||
.and_then(|v| st.doc.artboards.get(index(v)))
|
||||
.ok_or_else(|| bad("edit.copy", "`artboard` must be the index of an artboard of the document"))?;
|
||||
clip.source_artboard = Some(board.rect);
|
||||
}
|
||||
clip.guides = guides;
|
||||
s.clipboard = clip;
|
||||
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
|
||||
|
||||
@@ -348,6 +348,36 @@ fn direct_selection_cut_timing() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Finding the selected roots (for the menus, for Move and its siblings, for Copy and Cut, and
|
||||
/// inside an isolated group) walks the tree once for the paint order and the roots together, in
|
||||
/// paint order whatever order the objects were selected in.
|
||||
#[test]
|
||||
fn finding_the_selected_roots_walks_the_tree_once() {
|
||||
let mut s = session(2_000, square);
|
||||
let all = crate::tests_large_edits::layer(&s, 0);
|
||||
let reversed: Vec<u64> = all.iter().rev().map(|id| id.0).collect();
|
||||
s.execute("select.set", &json!({"ids": reversed})).unwrap();
|
||||
type Find = fn(&Session) -> Vec<NodeId>;
|
||||
let finds: [(&str, Find); 3] = [
|
||||
("the selected roots", |s| selected_roots(s).unwrap()),
|
||||
("the roots to transform", |s| selected_roots_to_transform(s).unwrap()),
|
||||
("Copy's targets", |s| copy_cut_targets(s).unwrap().1),
|
||||
];
|
||||
for (what, find) in finds {
|
||||
let walks = tree_walks();
|
||||
assert!(find(&s) == all, "{what} in paint order");
|
||||
assert_eq!(tree_walks() - walks, 1, "finding {what} walked the tree {} times", tree_walks() - walks);
|
||||
}
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id;
|
||||
s.execute("select.set", &json!({"ids": reversed})).unwrap();
|
||||
// The first call also builds the lookup cache that the isolation check reads.
|
||||
assert!(selected_roots_inside(&s, group, false).unwrap() == all, "the roots inside the group in paint order");
|
||||
let walks = tree_walks();
|
||||
assert!(selected_roots_inside(&s, group, false).unwrap() == all);
|
||||
assert_eq!(tree_walks() - walks, 1, "finding the roots inside the group walked the tree {} times", tree_walks() - walks);
|
||||
}
|
||||
|
||||
/// The selected roots are found once for a document version and its selected objects, however many enabled checks
|
||||
/// read them, and found again after the selection changes, after an edit, and for another selection.
|
||||
#[test]
|
||||
|
||||
@@ -267,6 +267,8 @@ thread_local! {
|
||||
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread.
|
||||
pub(crate) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many objects [`matches`] looked at on this thread.
|
||||
pub(crate) static OBJECTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl Form {
|
||||
@@ -527,6 +529,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
let mut cache = st.global_edit_forms.0.borrow_mut();
|
||||
let mut pass = cache.forms.pass();
|
||||
super::select::walk_selectable(d, st.isolation, |n| {
|
||||
#[cfg(test)]
|
||||
OBJECTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
if n.id == *id || out.len() >= MAX_MEMBERS {
|
||||
return false;
|
||||
}
|
||||
@@ -1075,34 +1079,178 @@ pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
out
|
||||
}
|
||||
|
||||
/// [`similar`]'s outlines as of a document revision and the options they were found with.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
|
||||
/// [`similar`]'s outlines as of a document revision, with what they were found from.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<Similar>>;
|
||||
|
||||
/// [`similar`]'s outlines and what they were found from.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Similar {
|
||||
revision: u64,
|
||||
options: Options,
|
||||
/// The document, the one selected object and the isolated object they were found with.
|
||||
doc: Arc<Document>,
|
||||
key: NodeId,
|
||||
isolation: Option<NodeId>,
|
||||
out: Arc<Highlights>,
|
||||
}
|
||||
|
||||
/// Before Global Edit starts: with one supported object selected, the outlines of the other
|
||||
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
|
||||
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
|
||||
/// progress, or when fewer than two objects would be taken. Kept per document revision and
|
||||
/// options, as finding them walks the whole document.
|
||||
/// options, as finding them walks the whole document. After an edit that replaced only the
|
||||
/// selected object, and left what the others are compared with as it was (a move), the outlines
|
||||
/// found before are kept without a walk.
|
||||
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
|
||||
// Global Edit is refused while an object of a dynamic symbol instance's art is selected.
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 || super::edit::refuse_symbol_part(s).is_err() {
|
||||
return NO_HIGHLIGHTS.clone();
|
||||
}
|
||||
let o = &s.global_edit_options;
|
||||
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
&& opts == o
|
||||
let key = st.selection.objects[0];
|
||||
if let Some(c) = &mut *st.similar_outlines.borrow_mut()
|
||||
&& c.options == *o
|
||||
&& c.key == key
|
||||
&& c.isolation == st.isolation
|
||||
&& (c.revision == st.revision || Arc::ptr_eq(&c.doc, &st.doc) || only_key_changed(&c.doc, &st.doc, key))
|
||||
{
|
||||
return out.clone();
|
||||
c.revision = st.revision;
|
||||
c.doc = st.doc.clone();
|
||||
return c.out.clone();
|
||||
}
|
||||
let out = Highlights::new(match matches(s, o) {
|
||||
Ok(m) if m.len() >= 2 => outlines(st, &m),
|
||||
_ => vec![],
|
||||
});
|
||||
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
|
||||
*st.similar_outlines.borrow_mut() =
|
||||
Some(Similar { revision: st.revision, options: o.clone(), doc: st.doc.clone(), key, isolation: st.isolation, out: out.clone() });
|
||||
out
|
||||
}
|
||||
|
||||
/// Would [`matches`] find the same objects in `now` as in `then`, with `key` selected in both?
|
||||
/// True when the layers differ only in `key` and in the layers and groups that hold it (the same
|
||||
/// apart from their contents), `key` is compared with the others as before ([`same_key`]), and the
|
||||
/// rest of the document is the same. A group that holds `key` is never like it (its form holds
|
||||
/// `key`'s and more), so the walk looks into it before and after alike.
|
||||
fn only_key_changed(then: &Document, now: &Document, key: NodeId) -> bool {
|
||||
let mut found = None;
|
||||
let same_symbol = |a: &vectorcraft_doc::Symbol, b: &vectorcraft_doc::Symbol| {
|
||||
a.name == b.name && a.dynamic == b.dynamic && (Arc::ptr_eq(&a.art, &b.art) || a.art == b.art)
|
||||
};
|
||||
// Everything else in the document (artboards, symbol settings, editing modes) as it was: the
|
||||
// symbols' art is compared on its own, as one copy when no edit changed it.
|
||||
let rest = |d: &Document| {
|
||||
let mut d = d.clone();
|
||||
d.layers.clear();
|
||||
d.symbols.clear();
|
||||
d
|
||||
};
|
||||
if then.symbols.len() != now.symbols.len()
|
||||
|| !then.symbols.iter().zip(&now.symbols).all(|(a, b)| same_symbol(a, b))
|
||||
|| rest(then) != rest(now)
|
||||
|| !changed_only(&then.layers, &now.layers, key, &mut found)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
found.is_none_or(|(a, b)| same_key(a, b, &now.symbol_boxes()))
|
||||
}
|
||||
|
||||
/// Do `then` and `now` hold the same objects, apart from `key` and the layers and groups on the way
|
||||
/// to it? `found` takes the two versions of `key` when it changed.
|
||||
fn changed_only<'a>(then: &'a [Arc<Node>], now: &'a [Arc<Node>], key: NodeId, found: &mut Option<(&'a Node, &'a Node)>) -> bool {
|
||||
if then.len() != now.len() {
|
||||
return false;
|
||||
}
|
||||
then.iter().zip(now).all(|(a, b)| {
|
||||
if Arc::ptr_eq(a, b) {
|
||||
return true;
|
||||
}
|
||||
if a.id != b.id {
|
||||
return false;
|
||||
}
|
||||
if a.id == key {
|
||||
return found.replace((a, b)).is_none();
|
||||
}
|
||||
match (holder_children(a), holder_children(b)) {
|
||||
(Some(x), Some(y)) => same_holder(a, b) && changed_only(x, y, key, found),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The objects in a layer or a group.
|
||||
fn holder_children(n: &Node) -> Option<&[Arc<Node>]> {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => Some(children),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Are two versions of a layer or a group the same apart from the objects in them?
|
||||
fn same_holder(a: &Node, b: &Node) -> bool {
|
||||
let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a;
|
||||
let kinds = match (kind, &b.kind) {
|
||||
(
|
||||
NodeKind::Layer { color, template, printable, children: _, clip, preview, dim_images },
|
||||
NodeKind::Layer { color: c, template: t, printable: p, children: _, clip: cl, preview: pv, dim_images: di },
|
||||
) => color == c && template == t && printable == p && clip == cl && preview == pv && dim_images == di,
|
||||
(NodeKind::Group { children: _, clip }, NodeKind::Group { children: _, clip: c }) => clip == c,
|
||||
_ => false,
|
||||
};
|
||||
kinds
|
||||
&& *id == b.id
|
||||
&& *name == b.name
|
||||
&& *visible == b.visible
|
||||
&& *locked == b.locked
|
||||
&& *opacity == b.opacity
|
||||
&& *blend == b.blend
|
||||
&& *isolate == b.isolate
|
||||
&& *knockout == b.knockout
|
||||
&& *knockout_shape == b.knockout_shape
|
||||
&& *appearance == b.appearance
|
||||
&& *bbox_angle == b.bbox_angle
|
||||
&& *extras == b.extras
|
||||
}
|
||||
|
||||
/// How far apart two versions of the selected object's form may lie, in its unit box, and how much
|
||||
/// their sizes may differ (relative), for [`similar`] to keep the objects found like the first: a
|
||||
/// millionth of [`SAME`]. A move leaves the form the same but for rounding (the form is placed in
|
||||
/// its unit box by a transform that includes the move), well within this.
|
||||
const KEPT: f64 = 1e-12;
|
||||
|
||||
/// Are two versions of the selected object compared with the other objects in the same way by
|
||||
/// [`matches`]: the same form in a box of the same size and the same geometric size (a perspective
|
||||
/// projection changes that alone), within [`KEPT`], and the same fill and stroke in each object in
|
||||
/// them?
|
||||
fn same_key(a: &Node, b: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool {
|
||||
let near = |x: f64, y: f64| (x - y).abs() <= KEPT * x.abs().max(y.abs()).max(1.0);
|
||||
fn same_look(a: &Node, b: &Node) -> bool {
|
||||
fill_of(a) == fill_of(b)
|
||||
&& stroke_of(a) == stroke_of(b)
|
||||
&& match (a.children(), b.children()) {
|
||||
(Some(x), Some(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_look(p, q)),
|
||||
(x, y) => x.is_none() && y.is_none(),
|
||||
}
|
||||
}
|
||||
if !(supported(a) && supported(b)) {
|
||||
return false;
|
||||
}
|
||||
let (Some(f), Some(g)) = (Form::of(a), Form::of(b)) else { return false };
|
||||
let (fl, gl) = (f.frame.as_coeffs(), g.frame.as_coeffs());
|
||||
let sizes = match (a.geometric_bounds_with(symbols), b.geometric_bounds_with(symbols)) {
|
||||
(Some(x), Some(y)) => near(x.width(), y.width()) && near(x.height(), y.height()),
|
||||
(x, y) => x.is_none() && y.is_none(),
|
||||
};
|
||||
f.tag == g.tag
|
||||
&& f.symbols == g.symbols
|
||||
&& f.points.len() == g.points.len()
|
||||
&& f.points.iter().zip(&g.points).all(|(p, q)| p.distance(*q) <= KEPT)
|
||||
&& fl[..4].iter().zip(&gl[..4]).all(|(x, y)| near(*x, *y))
|
||||
&& sizes
|
||||
&& same_look(a, b)
|
||||
}
|
||||
|
||||
/// The outlines of `members` that are not selected, hold no selected object and sit inside no
|
||||
/// selected object, in their layer's color.
|
||||
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
|
||||
|
||||
@@ -142,6 +142,18 @@ pub(crate) fn keep_compound_aligned(d: &mut Document, id: NodeId, sc: Scaling) {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`keep_compound_aligned`] for the object at `path` in `d`'s tree, found already: the compound
|
||||
/// path is read at the parent's place, without looking either object up by id.
|
||||
pub(crate) fn keep_compound_aligned_at(d: &mut Document, path: &[usize], sc: Scaling) {
|
||||
let Some((_, up)) = path.split_last() else { return };
|
||||
if up.is_empty() || !d.node_at(up).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) {
|
||||
return;
|
||||
}
|
||||
if let Some(n) = d.node_mut_at(up) {
|
||||
snap_object(n, sc);
|
||||
}
|
||||
}
|
||||
|
||||
/// After any edit ([`Session::edit`]): snap each pixel-aligned object that the edit changed or added
|
||||
/// (its node in `doc` is not the one in `before`), with the pixel-aligned art of its linked opacity
|
||||
/// mask, to the pixel grid. Objects the edit did not touch are not visited.
|
||||
|
||||
@@ -66,10 +66,15 @@ pub(super) fn scaling_options(s: &Session, p: &Value) -> Scaling {
|
||||
/// param, else General › Transform Pattern Tiles)? Noted in the journal when they or the art of
|
||||
/// their linked opacity masks use a pattern, so a replay moves their tiles alike whatever the preference is then.
|
||||
pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<bool> {
|
||||
let paths = s.doc()?.doc.index_paths(ids.iter().copied());
|
||||
transform_patterns_at(s, p, ids, &paths)
|
||||
}
|
||||
|
||||
/// [`transform_patterns`] with `paths`, the places of `ids` in the document's tree, found already.
|
||||
fn transform_patterns_at(s: &mut Session, p: &Value, ids: &[NodeId], paths: &std::collections::HashMap<NodeId, Vec<usize>>) -> Result<bool> {
|
||||
let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles);
|
||||
let d = &s.doc()?.doc;
|
||||
let mut uses = false;
|
||||
let paths = d.index_paths(ids.iter().copied());
|
||||
for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) {
|
||||
uses |= uses_pattern_with_masks(n);
|
||||
}
|
||||
@@ -152,7 +157,9 @@ fn apply_transform_moving_guides(
|
||||
let areas = bool_or(p, "typeAreas", false);
|
||||
let objects = transforms_objects(p);
|
||||
let mut sc = if Scaling::factor(xf).is_some() { scaling(s, p) } else { Scaling::default() };
|
||||
sc.patterns = transform_patterns(s, p, &ids)?;
|
||||
// The places of `ids`, found in one walk for Transform Patterns and for the edit below.
|
||||
let paths = s.doc()?.doc.index_paths(ids.iter().copied());
|
||||
sc.patterns = transform_patterns_at(s, p, &ids, &paths)?;
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
let delta = guides.unwrap_or(Vec2::new(c[4], c[5]));
|
||||
@@ -174,8 +181,6 @@ fn apply_transform_moving_guides(
|
||||
// An edit normally preserves the tree positions already found here. Settling an active
|
||||
// typing session can change the document before the edit closure runs, so look up again then.
|
||||
let reindex = copy || (!s.previewing && crate::cmd::typing_in_progress(s));
|
||||
let d = &s.doc()?.doc;
|
||||
let paths = d.index_paths(ids.iter().copied());
|
||||
let none = paths.is_empty() && !has_guides;
|
||||
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
|
||||
let mut interpolate = None;
|
||||
@@ -192,7 +197,11 @@ fn apply_transform_moving_guides(
|
||||
if copy { vec![] } else { ids }
|
||||
} else {
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
// A move of whole objects, not of copies (which `reindex` covers): the document before it,
|
||||
// and the moved objects as the transform left them, for [`moved_by`] to check after the edit.
|
||||
let from = (objects && !areas && !reindex && c[..4] == [1.0, 0.0, 0.0, 1.0]).then(|| s.doc().map(|st| st.doc.clone())).transpose()?;
|
||||
let mut held: Vec<(Vec<usize>, Arc<Node>)> = vec![];
|
||||
let targets = s.edit(label, |d, sel| {
|
||||
let mut targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, untransformed, and the
|
||||
// loop below transforms only the copies.
|
||||
@@ -229,9 +238,14 @@ fn apply_transform_moving_guides(
|
||||
transform_node(n, xf, sc, objects);
|
||||
}
|
||||
}
|
||||
// Holding them makes any later change to them copy them first, which `moved_by` sees.
|
||||
if from.is_some() {
|
||||
held = targets.iter().filter_map(|id| paths.get(id)).filter_map(|p| Some((p.clone(), node_arc(d, p)?))).collect();
|
||||
}
|
||||
if objects {
|
||||
for id in &targets {
|
||||
super::pixelgrid::keep_compound_aligned(d, *id, sc);
|
||||
// The transforms above leave every object at its place, so `paths` still holds them.
|
||||
for p in targets.iter().filter_map(|id| paths.get(id)) {
|
||||
super::pixelgrid::keep_compound_aligned_at(d, p, sc);
|
||||
}
|
||||
// Moving all of the tile art moves the tile as far.
|
||||
if let Some(before) = tile_art {
|
||||
@@ -248,7 +262,10 @@ fn apply_transform_moving_guides(
|
||||
targets.extend(d.transform_ruler_guides(sel, xf));
|
||||
}
|
||||
Ok(targets)
|
||||
})?
|
||||
})?;
|
||||
let st = s.doc_mut()?;
|
||||
st.moved = from.and_then(|from| moved_by(&from, st, &held, Vec2::new(c[4], c[5])));
|
||||
targets
|
||||
};
|
||||
let st = s.doc_mut()?;
|
||||
if st.interaction.is_none() {
|
||||
@@ -266,6 +283,49 @@ fn apply_transform_moving_guides(
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// The node at index path `path` of `d`, shared.
|
||||
fn node_arc(d: &Document, path: &[usize]) -> Option<Arc<Node>> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
let mut cur = d.layers.get(*first)?;
|
||||
for &i in rest {
|
||||
cur = cur.children()?.get(i)?;
|
||||
}
|
||||
Some(cur.clone())
|
||||
}
|
||||
|
||||
/// The [`crate::Moved`] of a move by `by` that took `from` to the document of `st`, given the moved
|
||||
/// objects as the transform left them (`held`, each with its index path). `None` unless every moved
|
||||
/// object is still that node at its path, none is a member of a blend (whose spine follows its
|
||||
/// members), and every object the selection shows, the key object and the key anchor's object
|
||||
/// included, is a moved object or inside one. A pass after the transform that changes a moved
|
||||
/// object, such as the one that snaps moved pixel-aligned objects to the pixel grid again
|
||||
/// ([`super::pixelgrid::refresh`]), copies it first, so it is no longer that node. The checks read
|
||||
/// the nodes at their paths and look nothing up by id.
|
||||
fn moved_by(from: &Arc<Document>, st: &crate::DocState, held: &[(Vec<usize>, Arc<Node>)], by: Vec2) -> Option<crate::Moved> {
|
||||
let d = &st.doc;
|
||||
let unchanged = |(p, n): &(Vec<usize>, Arc<Node>)| d.node_at(p).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n)));
|
||||
if held.is_empty() || !held.iter().all(unchanged) {
|
||||
return None;
|
||||
}
|
||||
// The node at each path is the moved object, so its parent is the node one level up.
|
||||
let in_blend = |p: &[usize]| p.split_last().and_then(|(_, up)| d.node_at(up)).is_some_and(|parent| matches!(parent.kind, NodeKind::Blend { .. }));
|
||||
if held.iter().any(|(p, _)| in_blend(p)) {
|
||||
return None;
|
||||
}
|
||||
let mut moved = std::collections::HashSet::new();
|
||||
for (_, n) in held {
|
||||
n.walk(&mut |c| {
|
||||
moved.insert(c.id);
|
||||
});
|
||||
}
|
||||
let sel = &st.selection;
|
||||
let mut shown = sel.objects.iter().copied().chain(sel.key).chain(sel.key_anchor.map(|(id, _)| id));
|
||||
if !shown.all(|id| moved.contains(&id)) {
|
||||
return None;
|
||||
}
|
||||
Some(crate::Moved { from: Arc::downgrade(from), to: Arc::downgrade(d), by, selection: sel.clone() })
|
||||
}
|
||||
|
||||
/// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction
|
||||
/// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot
|
||||
/// back first). These are the copies the interaction keeps when they were made of that snapshot for
|
||||
|
||||
@@ -185,14 +185,27 @@ fn can_change_mask(s: &Session) -> std::result::Result<(), String> {
|
||||
/// most one outermost object, which it masks with `ids` (a call's `ids` stand in for the selection
|
||||
/// here). A targeted layer is one subject root however many objects it selects. `make` itself
|
||||
/// refuses any single target in those modes, a layer included, so a selection with a target counts
|
||||
/// as one object.
|
||||
/// as one object. The check sorts the selection into paint order for its outermost objects only when it has one
|
||||
/// subject root and no target.
|
||||
fn can_make(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
let Some(st) = s.active() else { return Ok(()) };
|
||||
let roots = super::appearance::subject_roots(s).map_or(0, |r| r.len());
|
||||
let outermost = super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len();
|
||||
let targeted = st.selection.target.is_some();
|
||||
if roots == 1 && (outermost <= 1 || targeted) { super::maskedit::can_edit_mask(s) } else { Ok(()) }
|
||||
if roots != 1 {
|
||||
return Ok(());
|
||||
}
|
||||
let one = st.selection.target.is_some() || {
|
||||
#[cfg(test)]
|
||||
OUTERMOST_FOUND.set(OUTERMOST_FOUND.get() + 1);
|
||||
super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len() <= 1
|
||||
};
|
||||
if one { super::maskedit::can_edit_mask(s) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`can_make`] found the selection's outermost objects on this thread.
|
||||
static OUTERMOST_FOUND: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -485,6 +498,12 @@ impl Session {
|
||||
_ => TransparencyInfo::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first of the objects the Transparency panel shows ([`TransparencyInfo::ids`]), without comparing their
|
||||
/// values.
|
||||
pub fn transparency_target(&self) -> Option<NodeId> {
|
||||
transparency_targets(self, &Value::Null).ok()?.first().copied()
|
||||
}
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -759,4 +778,22 @@ mod tests {
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(back.node(NodeId(a)).unwrap().extras().mask, d.node(NodeId(a)).unwrap().extras().mask);
|
||||
}
|
||||
|
||||
/// Make Opacity Mask's check sorts the selection for its outermost objects only when the selection has one
|
||||
/// subject root; with several roots it is enabled without that sort.
|
||||
#[test]
|
||||
fn the_make_check_sorts_only_a_selection_with_one_root() {
|
||||
let (mut s, a, b) = session_with_two();
|
||||
let found = || OUTERMOST_FOUND.get();
|
||||
select(&mut s, &[a, b]);
|
||||
let before = found();
|
||||
assert_eq!(can_make(&s), Ok(()));
|
||||
assert_eq!(found(), before, "two roots: no paint-order sort");
|
||||
select(&mut s, &[a]);
|
||||
assert_eq!(can_make(&s), Ok(()));
|
||||
assert_eq!(found(), before + 1, "one root: the outermost objects are found");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(can_make(&s), Ok(()));
|
||||
assert_eq!(found(), before + 1, "no roots: no sort");
|
||||
}
|
||||
}
|
||||
@@ -1470,12 +1470,13 @@ fn in_live_paint(d: &Document, id: NodeId) -> bool {
|
||||
|
||||
impl DocState {
|
||||
/// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none
|
||||
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group.
|
||||
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group,
|
||||
/// else as [`DocState::live_paint_covered_kept`] keeps it for this version of the document.
|
||||
pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
if self.selection_paints().is_some_and(|p| !p.in_live_paint()) {
|
||||
return std::collections::HashSet::new();
|
||||
}
|
||||
live_paint_covered(&self.doc, ids)
|
||||
self.live_paint_covered_kept(ids)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -242,6 +242,58 @@ fn the_question_marks_read_only_the_selected_objects() {
|
||||
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
|
||||
}
|
||||
|
||||
/// How many times this thread read the groups around selected objects for their Live Paint faces
|
||||
/// and edges ([`DocState::live_paint_covered_kept`]).
|
||||
fn cover_reads() -> usize {
|
||||
crate::doc_state::LIVE_PAINT_COVER_READS.with(Cell::get)
|
||||
}
|
||||
|
||||
/// After an edit the selection keeps no record of what it holds, and the proxies, the Stroke panel
|
||||
/// and the "?" ask on every frame whether its objects lie in a Live Paint group. They read the
|
||||
/// objects' groups once for each version of the document and selection, not once for each question.
|
||||
/// A Live Paint group selected with one of its faces still counts the face with its group.
|
||||
#[test]
|
||||
fn live_paint_faces_are_looked_for_once_per_document_version() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let ids: Vec<NodeId> = (0..20).map(|i| rect(&mut s, 10.0 + 30.0 * f64::from(i), "#ff0000", "#000000")).collect();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
assert!(s.active().unwrap().selection_paints().is_none(), "the edit leaves the selection without a record");
|
||||
let ask = |s: &Session| {
|
||||
for _ in 0..3 {
|
||||
s.proxy_paints();
|
||||
s.shown_stroke();
|
||||
s.proxy_mixed();
|
||||
s.active().unwrap().stroke_mixed();
|
||||
}
|
||||
};
|
||||
let before = cover_reads();
|
||||
ask(&s);
|
||||
assert_eq!(cover_reads() - before, 1, "one read for this version of the document");
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = cover_reads();
|
||||
ask(&s);
|
||||
assert_eq!(cover_reads() - before, 1, "an edit reads them again, once");
|
||||
s.execute("select.set", &json!({"ids": [ids[0].0, ids[1].0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = cover_reads();
|
||||
ask(&s);
|
||||
assert_eq!(cover_reads() - before, 1, "another selection reads them again, once");
|
||||
|
||||
// A Live Paint group with one of its edges selected too: the edge counts with its group on every ask.
|
||||
s.execute("livePaint.make", &json!({"ids": [ids[2].0, ids[3].0]})).unwrap();
|
||||
let group = s.active().unwrap().selection.objects[0];
|
||||
let edge = vectorcraft_tools::builder::edges(s.active().unwrap().doc.node(group).unwrap())[0].id;
|
||||
s.execute("select.set", &json!({"ids": [group.0, edge.0]})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
assert!(covered.contains(&edge));
|
||||
for _ in 0..2 {
|
||||
assert_eq!(st.selection_live_paint_covered(&st.selection.objects), covered);
|
||||
}
|
||||
}
|
||||
|
||||
/// Random selections of a document with nested groups answer as a walk does.
|
||||
#[test]
|
||||
fn random_selections_match_a_walk_of_the_document() {
|
||||
|
||||
@@ -725,6 +725,8 @@ impl Session {
|
||||
for e in self.prefs.keep_folders(&mut p) {
|
||||
log::warn!("{e}");
|
||||
}
|
||||
// Tool settings saved by an earlier version are updated once.
|
||||
p.migrate_tool_settings();
|
||||
// Saved gradient presets get names no built-in preset or other saved one has.
|
||||
for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) {
|
||||
log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name");
|
||||
|
||||
@@ -1027,6 +1027,84 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
|
||||
used.into_iter().map(|(_, u)| u).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many objects [`several_colors`] read on this thread.
|
||||
static SEVERAL_COLORS_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether [`used_colors`] lists more than one color for the objects `ids`. The objects are read
|
||||
/// until a second color turns up.
|
||||
fn several_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> bool {
|
||||
struct Seen<'a> {
|
||||
first: Option<ColorKey>,
|
||||
several: bool,
|
||||
patterns: Vec<&'a str>,
|
||||
}
|
||||
impl<'a> Seen<'a> {
|
||||
fn read(&mut self, m: &'a Node) {
|
||||
#[cfg(test)]
|
||||
SEVERAL_COLORS_READS.with(|c| c.set(c.get() + 1));
|
||||
let (first, several) = (&mut self.first, &mut self.several);
|
||||
paints(
|
||||
m,
|
||||
&mut |c, _, _, _| {
|
||||
let k = ColorKey::of(c);
|
||||
match first {
|
||||
None => *first = Some(k),
|
||||
Some(f) => *several |= *f != k,
|
||||
}
|
||||
},
|
||||
&mut self.patterns,
|
||||
);
|
||||
}
|
||||
fn read_tree(&mut self, n: &'a Node, only: Option<&BTreeSet<NodeId>>) {
|
||||
if self.several || only.is_some_and(|o| !o.contains(&n.id)) {
|
||||
return;
|
||||
}
|
||||
self.read(n);
|
||||
for c in n.children().into_iter().flatten() {
|
||||
self.read_tree(c, only);
|
||||
if self.several {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = Seen { first: None, several: false, patterns: vec![] };
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
seen.read_tree(n, only);
|
||||
if seen.several {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let mut next = 0;
|
||||
while !seen.several
|
||||
&& let Some(&name) = seen.patterns.get(next)
|
||||
{
|
||||
next += 1;
|
||||
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
|
||||
let _ = a.try_walk(&mut |m| {
|
||||
seen.read(m);
|
||||
if seen.several { std::ops::ControlFlow::Break(()) } else { std::ops::ControlFlow::Continue(()) }
|
||||
});
|
||||
if seen.several {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
seen.several
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Whether the objects `recolor.colors` reads without `ids` use more than one color: the
|
||||
/// selection, or with nothing selected the objects Select All takes. False without a document.
|
||||
pub fn several_colors_used(&self) -> bool {
|
||||
let Ok((ids, only)) = scope_ids(self, &Value::Null, "recolor.colors") else { return false };
|
||||
self.doc().is_ok_and(|st| several_colors(&st.doc, &ids, only.as_ref()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
|
||||
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
|
||||
/// add the patterns it is painted with to `patterns`.
|
||||
@@ -2050,6 +2128,69 @@ mod tests {
|
||||
assert!(has(&t, RED), "P100 read again at the top");
|
||||
}
|
||||
|
||||
/// How many objects [`several_colors`] read on this thread.
|
||||
fn several_reads() -> usize {
|
||||
SEVERAL_COLORS_READS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// Whether more than one color is used ([`Session::several_colors_used`]), checked against the
|
||||
/// length of `recolor.colors`'s list, with how many objects the answer read.
|
||||
fn several(s: &mut Session, what: &str) -> (bool, usize) {
|
||||
let before = several_reads();
|
||||
let several = s.several_colors_used();
|
||||
let reads = several_reads() - before;
|
||||
let listed = s.execute("recolor.colors", &json!({})).unwrap()["colors"].as_array().map_or(0, Vec::len);
|
||||
assert_eq!(several, listed > 1, "{what}: {listed} colors listed");
|
||||
(several, reads)
|
||||
}
|
||||
|
||||
/// The Recolor quick action asks on every change whether the selection uses more than one
|
||||
/// color. The answer matches `recolor.colors`, pattern tiles and Select All's objects included,
|
||||
/// and the objects are read only until a second color turns up.
|
||||
#[test]
|
||||
fn several_colors_stop_at_the_second_color() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let ids: Vec<u64> = (0..30)
|
||||
.map(|i| {
|
||||
let id =
|
||||
s.execute("shape.rectangle", &json!({"x": 10 + 20 * i, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [id], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
|
||||
id
|
||||
})
|
||||
.collect();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
assert_eq!(several(&mut s, "one red"), (false, 30), "one color: every object is read");
|
||||
// A blue object in the middle: the objects are read up to it, from either end.
|
||||
s.execute("paint.setFill", &json!({"ids": [ids[15]], "color": "#0000ff"})).unwrap();
|
||||
let (found, reads) = several(&mut s, "a blue in the middle");
|
||||
assert!(found && matches!(reads, 15 | 16), "{reads} objects read");
|
||||
s.execute("paint.setFill", &json!({"ids": [ids[0], ids[29]], "color": "#00ff00"})).unwrap();
|
||||
assert_eq!(several(&mut s, "green at both ends"), (true, 2), "the second object holds the second color");
|
||||
s.execute("select.set", &json!({"ids": &ids[1..15]})).unwrap();
|
||||
assert!(!several(&mut s, "the red ones").0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(several(&mut s, "Select All's objects").0);
|
||||
|
||||
// A red object filled with a pattern too: its tile's color counts.
|
||||
for (tile, expect) in [(BLUE, true), (RED, false)] {
|
||||
let filled = NodeId(ids[1]);
|
||||
s.edit("t", |d, _| {
|
||||
let art = square(d, 0.0, Paint::solid(tile));
|
||||
d.patterns.retain(|p| p.name != "Tile");
|
||||
d.patterns.push(PatternDef::new("Tile", vec![art]));
|
||||
if let Some(n) = d.node_mut(filled) {
|
||||
n.appearance.set_fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY });
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [ids[1], ids[2]]})).unwrap();
|
||||
assert_eq!(several(&mut s, "a pattern tile").0, expect, "a tile of {tile:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern tile's symbol instances charge the same limit as the art around it.
|
||||
#[test]
|
||||
fn pattern_tiles_charge_the_symbol_limit() {
|
||||
|
||||
@@ -5,7 +5,9 @@ use super::{NodeId, Value, cmd, find_command};
|
||||
/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on
|
||||
/// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art
|
||||
/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none.
|
||||
pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
|
||||
pub const ON_ACTIVE_ARTBOARD: [&str; 10] = [
|
||||
"edit.copy",
|
||||
"edit.cut",
|
||||
"edit.pasteInPlace",
|
||||
"edit.pasteInFront",
|
||||
"edit.pasteInBack",
|
||||
@@ -35,7 +37,9 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 35] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 37] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
("edit.newDocumentFromState", "created"),
|
||||
("document.save", "modified"),
|
||||
|
||||
@@ -203,6 +203,36 @@ pub struct DocState {
|
||||
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
|
||||
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
|
||||
pub(crate) selection_record: Option<SelectionRecord>,
|
||||
/// The objects that [`DocState::live_paint_covered_kept`] last found no face or edge of a Live
|
||||
/// Paint group among, with the document it read. Not saved.
|
||||
outside_live_paint: std::cell::RefCell<Option<OutsideLivePaint>>,
|
||||
/// The last move of the selected objects that changed nothing else they show ([`Moved`]).
|
||||
/// Not saved.
|
||||
pub moved: Option<Moved>,
|
||||
}
|
||||
|
||||
/// Objects that hold no face or edge of a Live Paint group that counts with its group
|
||||
/// ([`cmd::live_paint_covered`] is empty for them), with the document they were read in, held as
|
||||
/// [`EmptyArtboards::doc`] holds it.
|
||||
#[derive(Clone, Debug)]
|
||||
struct OutsideLivePaint {
|
||||
doc: std::sync::Weak<Document>,
|
||||
ids: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// A move of whole objects that took document `from` to document `to`: each object the selection
|
||||
/// shows, the key object and the key anchor included, is the one in `from` moved by `by`, and
|
||||
/// nothing else they are drawn from changed (no member snapped to the pixel grid, no blend spine
|
||||
/// they follow, no pass after the edit). A view that drew the selection of `from` can
|
||||
/// move what it drew by `by` instead of building it again. It holds the documents as
|
||||
/// [`SelectionRecord::doc`] holds one, so a document changed in place no longer matches.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Moved {
|
||||
pub from: std::sync::Weak<Document>,
|
||||
pub to: std::sync::Weak<Document>,
|
||||
pub by: vectorcraft_geom::Vec2,
|
||||
/// The selection the move was made with, which is also the selection after it.
|
||||
pub selection: Selection,
|
||||
}
|
||||
|
||||
/// A selection of objects alone ([`objects_only`]) with the document it was checked or read in:
|
||||
@@ -302,6 +332,8 @@ thread_local! {
|
||||
pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread.
|
||||
pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`DocState::live_paint_covered_kept`] read the objects' groups on this thread.
|
||||
pub(crate) static LIVE_PAINT_COVER_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
@@ -522,6 +554,8 @@ impl DocState {
|
||||
measured_in_own: None,
|
||||
inline_resolved: None,
|
||||
selection_record: None,
|
||||
outside_live_paint: Default::default(),
|
||||
moved: None,
|
||||
}
|
||||
}
|
||||
/// The [`SelectionRecord`] of the selection now: `None` when the document or the selected
|
||||
@@ -539,6 +573,25 @@ impl DocState {
|
||||
pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> {
|
||||
self.selection_record().and_then(|r| r.paints.as_ref())
|
||||
}
|
||||
/// The faces and edges of Live Paint groups among `ids` that count with their group
|
||||
/// ([`cmd::live_paint_covered`]). An empty answer is kept for this version of the document and
|
||||
/// these objects, so the proxies and the Stroke panel, which ask on every frame, read the
|
||||
/// objects' groups once after an edit.
|
||||
pub(crate) fn live_paint_covered_kept(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
let kept = |k: &OutsideLivePaint| std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc)) && k.ids == ids;
|
||||
if self.outside_live_paint.try_borrow().is_ok_and(|k| k.as_ref().is_some_and(kept)) {
|
||||
return std::collections::HashSet::new();
|
||||
}
|
||||
#[cfg(test)]
|
||||
LIVE_PAINT_COVER_READS.with(|c| c.set(c.get() + 1));
|
||||
let covered = cmd::live_paint_covered(&self.doc, ids);
|
||||
if covered.is_empty()
|
||||
&& let Ok(mut k) = self.outside_live_paint.try_borrow_mut()
|
||||
{
|
||||
*k = Some(OutsideLivePaint { doc: Arc::downgrade(&self.doc), ids: ids.to_vec() });
|
||||
}
|
||||
covered
|
||||
}
|
||||
/// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with
|
||||
/// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same
|
||||
/// document: the objects that leave the selection are taken out of its paints and the objects
|
||||
|
||||
@@ -10,6 +10,9 @@ pub struct Interaction {
|
||||
pub doc: Arc<Document>,
|
||||
/// The selection the previews start from (shared, so a preview frame copies nothing).
|
||||
pub selection: Arc<Selection>,
|
||||
/// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's
|
||||
/// revision, and this value stays the same until the interaction ends.
|
||||
pub revision: u64,
|
||||
pub preview: Option<(String, Value)>,
|
||||
/// The active tool began it (a drag): a command from outside the tool runs as a step of its
|
||||
/// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an
|
||||
@@ -52,6 +55,13 @@ pub struct Interaction {
|
||||
pub keep_on_switch: bool,
|
||||
}
|
||||
|
||||
impl Interaction {
|
||||
/// The active tool began it (a drag).
|
||||
pub fn by_tool(&self) -> bool {
|
||||
self.tool
|
||||
}
|
||||
}
|
||||
|
||||
/// An interaction that a command from outside the tool set aside while it runs
|
||||
/// ([`crate::Session::outside_interaction`]).
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -512,7 +512,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView};
|
||||
pub use doc_state::{DocState, LayersReveal, Moved, OpenRows, RecalledSelection, WindowView};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
use history::history_budget_for;
|
||||
|
||||
@@ -438,6 +438,12 @@ pub struct Prefs {
|
||||
/// resetting the preferences keeps them; `tool.setOption` edits them.
|
||||
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub tool_settings: std::collections::BTreeMap<String, serde_json::Map<String, Value>>,
|
||||
/// The version of [`Self::tool_settings`]: [`TOOL_SETTINGS_VERSION`] once this version stores
|
||||
/// or updates a tool setting, 0 while none is stored and in preferences saved without one.
|
||||
/// [`Prefs::migrate_tool_settings`] updates older tool settings once. Not a Preferences dialog
|
||||
/// field: resetting the preferences keeps it.
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub tool_settings_version: u32,
|
||||
/// View → Perspective Grid presets: the user's (the built-in ones aren't stored). A local
|
||||
/// library, not a Preferences dialog field: resetting the preferences keeps it;
|
||||
/// `perspective.presets.*` edit it.
|
||||
@@ -464,7 +470,36 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
|
||||
/// The range of the Hold Shortcut Delay, in seconds.
|
||||
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
|
||||
|
||||
/// The version of the tool settings these preferences write ([`Prefs::tool_settings_version`]).
|
||||
/// Version 1 makes Color Swatches the Shape Builder's Pick Color From.
|
||||
pub const TOOL_SETTINGS_VERSION: u32 = 1;
|
||||
|
||||
fn is_zero(v: &u32) -> bool {
|
||||
*v == 0
|
||||
}
|
||||
|
||||
impl Prefs {
|
||||
/// Update tool settings saved by an earlier version to [`TOOL_SETTINGS_VERSION`], once. Before
|
||||
/// version 1, leaving the Shape Builder saved its `pickColorFrom` whether or not it was
|
||||
/// changed, so a saved `artwork` becomes `swatches`. Without tool settings, nothing changes; a
|
||||
/// version newer than this one is kept.
|
||||
pub fn migrate_tool_settings(&mut self) {
|
||||
if self.tool_settings_version < 1
|
||||
&& let Some(saved) = self.tool_settings.get_mut("shapeBuilder")
|
||||
&& saved.get("pickColorFrom").and_then(Value::as_str) == Some("artwork")
|
||||
{
|
||||
saved.insert("pickColorFrom".into(), Value::from("swatches"));
|
||||
}
|
||||
self.mark_tool_settings_current();
|
||||
}
|
||||
|
||||
/// Record that [`Self::tool_settings`], when any is stored, is in this version's form.
|
||||
pub(crate) fn mark_tool_settings_current(&mut self) {
|
||||
if !self.tool_settings.is_empty() {
|
||||
self.tool_settings_version = self.tool_settings_version.max(TOOL_SETTINGS_VERSION);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
|
||||
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
|
||||
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
|
||||
@@ -672,6 +707,7 @@ impl Default for Prefs {
|
||||
use_registration_point_for_symbol: false,
|
||||
show_on_shape_creation: false,
|
||||
tool_settings: Default::default(),
|
||||
tool_settings_version: 0,
|
||||
perspective_presets: vec![],
|
||||
blend_options: None,
|
||||
perspective_widget: Default::default(),
|
||||
|
||||
@@ -545,6 +545,7 @@ impl Session {
|
||||
effect: None,
|
||||
doc: st.doc.clone(),
|
||||
selection: Arc::new(st.selection.clone()),
|
||||
revision: st.revision,
|
||||
preview: None,
|
||||
tool: false,
|
||||
paint,
|
||||
|
||||
@@ -118,6 +118,7 @@ mod livecorners;
|
||||
mod maskview;
|
||||
pub(super) mod menucmds;
|
||||
mod mesh_picks;
|
||||
mod moved;
|
||||
mod nativefile;
|
||||
mod newart;
|
||||
mod newdoc;
|
||||
|
||||
@@ -1753,7 +1753,8 @@ fn shape_builder_swatches_keep_the_current_fill_and_the_first_covered_objects_lo
|
||||
}
|
||||
|
||||
/// The Shape Builder tool sends the point where the drag started first and the point where it
|
||||
/// ended last, so a drag from the hole into the square takes the square's look.
|
||||
/// ended last, so with Pick Color From Artwork a drag from the hole into the square takes the
|
||||
/// square's look.
|
||||
#[test]
|
||||
fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() {
|
||||
let mut s = session();
|
||||
@@ -1762,6 +1763,7 @@ fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() {
|
||||
select_ids(&mut s, &bars.iter().copied().chain([red]).collect::<Vec<_>>());
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 85.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 50.0), v).unwrap();
|
||||
@@ -1853,6 +1855,7 @@ fn shape_builder_arrow_keys_step_the_current_fill_through_the_swatches() {
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
let chips = |s: &mut Session| s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Swatch { .. })).count();
|
||||
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap();
|
||||
assert!(!s.tool_claims_key(ToolKey::Right, v), "Artwork leaves the arrows to nudging");
|
||||
let values = json!({"pickColorFrom": "swatches", "cursorSwatchPreview": true});
|
||||
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": values})).unwrap();
|
||||
@@ -2071,6 +2074,31 @@ fn shape_builder_fill_preview_is_put_back_by_a_cancel() {
|
||||
assert_eq!(s.paint.fill, before, "the cancel puts the fill back");
|
||||
}
|
||||
|
||||
/// With the Shape Builder's default options, a fill picked while it is active (a swatch or a
|
||||
/// color) fills the next merge: the tool sends `pickColorFrom: "swatches"`, and the merged shape
|
||||
/// is not the red or blue of the art.
|
||||
#[test]
|
||||
fn shape_builder_default_merge_fills_with_the_picked_fill() {
|
||||
let v = ViewInfo::default();
|
||||
for pick in [json!({"swatch": "Leaf"}), json!({"color": "#ff8800"})] {
|
||||
let mut s = session();
|
||||
two(&mut s);
|
||||
s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
s.execute("paint.setFill", &pick).unwrap();
|
||||
let picked = s.paint.fill.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
|
||||
let (cmd, params) = s.journal.last().unwrap().clone();
|
||||
assert_eq!((cmd.as_str(), ¶ms["pickColorFrom"]), ("shapeBuilder.merge", &json!("swatches")), "{pick}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let fills: Vec<Paint> = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect();
|
||||
assert_eq!(fills, vec![picked], "{pick}: the two squares merged into one shape with the picked fill");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder
|
||||
/// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient.
|
||||
#[test]
|
||||
|
||||
@@ -137,7 +137,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = made();
|
||||
assert_eq!(highlights(&s).len(), 39);
|
||||
assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged");
|
||||
assert_eq!(since(before), (2, 0), "the selected object before and after the move only: the copies are unchanged");
|
||||
sel(&mut s, &[copies[0]]);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
sel(&mut s, &[copies[1]]);
|
||||
@@ -156,6 +156,207 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
|
||||
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_to_the_selected_object_alone_keeps_the_similar_objects_without_a_walk() {
|
||||
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
|
||||
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
|
||||
// The outlines `highlights` gives, and how many objects it looked at for them.
|
||||
let shown = |s: &Session| {
|
||||
let before = walked();
|
||||
let out = highlights(s);
|
||||
(out, walked() - before)
|
||||
};
|
||||
// The outlines in each layer color.
|
||||
let paths = |h: &crate::cmd::globaledit::Highlights| h.groups.iter().map(|(c, p)| (*c, p.to_vec())).collect::<Vec<_>>();
|
||||
// The outlines a walk finds, the options set again so that nothing is kept.
|
||||
let fresh = |s: &mut Session| {
|
||||
let size = s.global_edit_options.size;
|
||||
s.execute("select.globalEditOptions", &json!({"size": !size})).unwrap();
|
||||
highlights(s);
|
||||
s.execute("select.globalEditOptions", &json!({"size": size})).unwrap();
|
||||
let before = walked();
|
||||
let out = highlights(s);
|
||||
assert!(walked() > before, "a walk");
|
||||
paths(&out)
|
||||
};
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.37, 0.91, 10.3, 10.3);
|
||||
let copies: Vec<NodeId> = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.3, 10.3)).collect();
|
||||
sel(&mut s, &[key]);
|
||||
let (first, n) = shown(&s);
|
||||
assert_eq!(first.len(), 39);
|
||||
assert!(n >= 40, "the first preview walks every object");
|
||||
|
||||
// The move rounds the form in its unit box differently; the same objects are like it.
|
||||
s.execute("object.move", &json!({"dx": 3.17, "dy": 1.29})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert_eq!(n, 0, "a move of the selected object alone compares the others as before");
|
||||
assert!(std::sync::Arc::ptr_eq(&out, &first), "the canvas keeps the outlines it stroked");
|
||||
assert_eq!(paths(&out), fresh(&mut s));
|
||||
|
||||
// Another object moved: it is shown where it is now.
|
||||
sel(&mut s, &[copies[0]]);
|
||||
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0, "another object changed");
|
||||
let moved = node(&s, copies[0]).stroke_path().unwrap();
|
||||
assert!(out.groups.iter().flat_map(|(_, p)| p.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
|
||||
assert_eq!(paths(&out), fresh(&mut s));
|
||||
|
||||
// The selected object took another shape: none of the squares is like it.
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0 && out.is_empty(), "the widened square matches none of the squares");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(shown(&s).0.len(), 39);
|
||||
|
||||
// With Size, a larger copy of the selected square is another size.
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
assert_eq!(shown(&s).0.len(), 39);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0 && out.is_empty(), "the enlarged square has the size of none of them");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
|
||||
|
||||
// With Appearance, another fill on the selected square leaves the others out.
|
||||
s.execute("select.globalEditOptions", &json!({"appearance": true})).unwrap();
|
||||
assert_eq!(shown(&s).0.len(), 39);
|
||||
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0 && out.is_empty(), "the others have another fill now");
|
||||
s.execute("select.globalEditOptions", &json!({"appearance": false})).unwrap();
|
||||
|
||||
// Reflected, the selected kite keeps its size but is no longer like its copy.
|
||||
let lone = kite(&mut s, 0.0, 500.0, 1.0);
|
||||
kite(&mut s, 200.0, 500.0, 1.0);
|
||||
sel(&mut s, &[lone]);
|
||||
assert_eq!(shown(&s).0.len(), 1);
|
||||
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0 && out.is_empty(), "a reflected copy is not like it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_layer_locked_leaves_its_objects_out_of_the_similar_objects() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
let other = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
rect(&mut s, 40.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 60.0, 0.0, 10.0, 10.0);
|
||||
sel(&mut s, &[key]);
|
||||
assert_eq!(highlights(&s).len(), 3);
|
||||
s.execute("layer.setProps", &json!({"id": other.0, "locked": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [key]);
|
||||
assert_eq!(highlights(&s).len(), 1, "the squares on the locked layer are left out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_artboard_brings_the_objects_on_it_into_the_similar_objects() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 1100.0, 100.0, 10.0, 10.0);
|
||||
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert_eq!(highlights(&s).len(), 1, "the square on the canvas is left out");
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert_eq!(highlights(&s).len(), 2, "the square is on an artboard now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_redrawn_brings_its_instances_onto_the_artboard() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("symbol.place", &json!({"name": "Tile", "x": 1000, "y": 300})).unwrap();
|
||||
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert!(highlights(&s).is_empty(), "the other instance is on the canvas");
|
||||
// The symbol's art drawn 400 pt to the left: the other instance lies on the artboard.
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let art = std::sync::Arc::make_mut(&mut d.symbols[0].art);
|
||||
art.transform(Affine::translate((-400.0, 0.0)), vectorcraft_doc::Scaling::default());
|
||||
st.revision += 1;
|
||||
assert_eq!(highlights(&s).len(), 1, "the other instance is on the artboard now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_instance_put_in_perspective_has_another_size() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
|
||||
let r = rect(&mut s, 450.0, 300.0, 100.0, 100.0);
|
||||
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("symbol.place", &json!({"name": "Tile", "x": 100, "y": 100})).unwrap();
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert_eq!(highlights(&s).len(), 1);
|
||||
let size = |s: &Session| bounds(s, key).size();
|
||||
let was = size(&s);
|
||||
s.execute("perspective.attach", &json!({"ids": [key.0], "plane": "right"})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert_ne!(size(&s), was, "the projection changes the instance's size");
|
||||
assert!(highlights(&s).is_empty(), "the other instance has the size the selected one had");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_of_a_dynamic_symbol_instance_selected_shows_no_similar_objects() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
let inst = NodeId(s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("symbol.place", &json!({"name": "Pair", "x": 300, "y": 300})).unwrap();
|
||||
sel(&mut s, &[inst]);
|
||||
assert_eq!(highlights(&s).len(), 1);
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [inst]);
|
||||
assert!(highlights(&s).is_empty(), "Global Edit does not take a part of the art");
|
||||
sel(&mut s, &[inst]);
|
||||
assert_eq!(highlights(&s).len(), 1, "the whole instance again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_selected_inside_a_group_keeps_its_similar_objects_after_a_move() {
|
||||
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
|
||||
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
|
||||
let mut s = session();
|
||||
let group = |s: &mut Session, ids: &[NodeId]| {
|
||||
sel(s, ids);
|
||||
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
// A group of two squares inside an outer group with a third square, and a copy of both: the
|
||||
// copy's inner group is like the selected inner group.
|
||||
let a = [rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0)];
|
||||
let inner = group(&mut s, &a);
|
||||
let third = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
|
||||
let outer = group(&mut s, &[inner, third]);
|
||||
let b = [rect(&mut s, 0.0, 100.0, 10.0, 10.0), rect(&mut s, 20.0, 100.0, 10.0, 10.0)];
|
||||
let inner_copy = group(&mut s, &b);
|
||||
let third_copy = rect(&mut s, 40.0, 100.0, 10.0, 10.0);
|
||||
group(&mut s, &[inner_copy, third_copy]);
|
||||
sel(&mut s, &[inner]);
|
||||
let first = highlights(&s);
|
||||
assert_eq!(crate::cmd::globaledit::match_count(&s), 2, "the copy's inner group; the outer group {outer} holds the selected one");
|
||||
assert!(!first.is_empty());
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = walked();
|
||||
assert!(std::sync::Arc::ptr_eq(&highlights(&s), &first));
|
||||
assert_eq!(walked(), before, "the outer group changed with the selected group only");
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
|
||||
assert_eq!(highlights(&s).groups, first.groups, "a walk finds the same");
|
||||
assert!(walked() > before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -253,6 +253,24 @@ fn transform_each_with_copy_of_50000_objects_takes_few_tree_walks() {
|
||||
undo_gives_back(&mut s, &before);
|
||||
}
|
||||
|
||||
/// A move of 10,000 selected objects walks the tree once for the paint order and the top-level
|
||||
/// objects, once for Transform Patterns and the edit, and once for the selection's check after the
|
||||
/// edit. It reads each object's compound path at the object's place, so the only lookups by id are
|
||||
/// the range check's, one per object.
|
||||
#[test]
|
||||
fn moving_10000_selected_objects_walks_the_tree_three_times() {
|
||||
let n = 10_000;
|
||||
let mut s = session(n, square);
|
||||
let ids = layer(&s, 0);
|
||||
let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups());
|
||||
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
|
||||
let (walks, lookups) = (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups);
|
||||
assert_eq!(walks, 3, "walked the tree {walks} times");
|
||||
assert!(lookups <= n as u64, "{lookups} lookups by id for {n} objects");
|
||||
assert_eq!(bounds(&s, ids[n - 1]), square_at(n - 1) + vectorcraft_geom::Vec2::new(3.0, 0.0));
|
||||
assert!(selected(&s, &ids));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_path_of_50000_objects_takes_few_tree_walks() {
|
||||
let s = session(50_000, square);
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! [`DocState::moved`]: a move of whole objects names the documents before and after it and how far
|
||||
//! it went, and only when every object the selection shows is the one before it, moved that far.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 30, "height": 20})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn doc(s: &Session) -> Arc<Document> {
|
||||
s.doc().unwrap().doc.clone()
|
||||
}
|
||||
|
||||
/// The move [`DocState::moved`] names, when it took `from` to the document now.
|
||||
fn moved_from(s: &Session, from: &Arc<Document>) -> Option<Vec2> {
|
||||
let st = s.doc().unwrap();
|
||||
let m = st.moved.as_ref()?;
|
||||
(m.from.as_ptr() == Arc::as_ptr(from) && m.to.as_ptr() == Arc::as_ptr(&st.doc) && m.selection == st.selection).then_some(m.by)
|
||||
}
|
||||
|
||||
// A move of the selection, a nudge and each step of a drag name the move; the drag's steps all start from the
|
||||
// document the drag began with.
|
||||
#[test]
|
||||
fn a_move_of_whole_objects_names_the_documents_and_the_distance() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
|
||||
select(&mut s, &[a, b]);
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 12, "dy": -5})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), Some(Vec2::new(12.0, -5.0)), "Object › Transform › Move");
|
||||
let before = doc(&s);
|
||||
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), Some(Vec2::new(s.prefs.keyboard_increment, 0.0)), "a nudge");
|
||||
|
||||
let start = doc(&s);
|
||||
s.begin_interaction("Move").unwrap();
|
||||
for dx in [3.0, 7.5] {
|
||||
s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 2], "copy": false})).unwrap();
|
||||
assert_eq!(moved_from(&s, &start), Some(Vec2::new(dx, 2.0)), "a drag's step by {dx}");
|
||||
}
|
||||
}
|
||||
|
||||
// A copy, a transform that is not a move, a move of patterns alone, a move that also resizes type areas, and a move
|
||||
// of part of what the selection shows name no move.
|
||||
#[test]
|
||||
fn a_copy_a_scale_and_a_move_of_part_of_the_selection_name_no_move() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
|
||||
select(&mut s, &[a, b]);
|
||||
let cases = [
|
||||
("object.move", json!({"dx": 12, "dy": 0, "copy": true})),
|
||||
("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})),
|
||||
("object.move", json!({"dx": 12, "dy": 0, "objects": false, "patterns": true})),
|
||||
("object.move", json!({"dx": 12, "dy": 0, "typeAreas": true})),
|
||||
("object.transform", json!({"matrix": [1, 0, 0, 1, 5, 0], "ids": [a.0]})),
|
||||
];
|
||||
for (cmd, p) in cases {
|
||||
select(&mut s, &[a, b]);
|
||||
let before = doc(&s);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None, "{cmd} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
// The key object is shown too: a move that leaves it where it was names no move.
|
||||
#[test]
|
||||
fn a_key_object_left_where_it_was_names_no_move() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
|
||||
select(&mut s, &[a]);
|
||||
s.active_mut().unwrap().selection.key = Some(b);
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None);
|
||||
}
|
||||
|
||||
// A pixel-aligned path snaps to the pixel grid after the transform, and an instance of a symbol aligned to the pixel
|
||||
// grid snaps after the edit: neither is the object before the move moved by its distance.
|
||||
#[test]
|
||||
fn objects_that_snap_to_the_pixel_grid_name_no_move() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None, "a pixel-aligned path");
|
||||
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 20.0);
|
||||
let made = s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0], "alignToPixelGrid": true})).unwrap();
|
||||
select(&mut s, &[id_of(&made)]);
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None, "an instance of a symbol aligned to the pixel grid");
|
||||
}
|
||||
|
||||
// A member of a blend moved on its own changes the blend's spine.
|
||||
#[test]
|
||||
fn a_member_of_a_blend_names_no_move() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 200.0));
|
||||
s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None);
|
||||
}
|
||||
@@ -235,7 +235,7 @@ fn shift_click_direct_selection_and_hover_on_a_drop_shadow_pass_through_it() {
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::Move);
|
||||
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::SelectionMove);
|
||||
assert_eq!(s.cursor(Point::new(110.0, 50.0), Mods::default(), v), Cursor::Arrow);
|
||||
assert_eq!(s.cursor(Point::new(92.0, 50.0), Mods::default(), v), Cursor::Arrow);
|
||||
}
|
||||
|
||||
@@ -698,3 +698,55 @@ fn a_parametric_shape_kind_and_its_values_set_together() {
|
||||
assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Shape Builder picks colors from the color swatches by default: a fresh session, and saved
|
||||
/// preferences that hold other Shape Builder options but no `pickColorFrom`, give `swatches`.
|
||||
/// Preferences saved without `toolSettingsVersion` read a saved `artwork` as `swatches` once and
|
||||
/// are then written with the version, so a later `artwork` is kept. A saved `swatches` is kept.
|
||||
#[test]
|
||||
fn shape_builder_pick_color_from_defaults_to_swatches_and_migrates_a_saved_artwork_once() {
|
||||
let mut s = session();
|
||||
select(&mut s, "shapeBuilder");
|
||||
assert_eq!(s.tool_options()["pickColorFrom"], json!("swatches"), "a fresh session");
|
||||
select(&mut s, "selection");
|
||||
assert_eq!(s.prefs.to_json()["toolSettingsVersion"], json!(1), "stored settings are written with the version");
|
||||
let load = |version: Option<u32>, saved: &Value| {
|
||||
let mut prefs = Prefs::default().to_json();
|
||||
prefs["toolSettings"] = json!({ "shapeBuilder": saved });
|
||||
let fields = prefs.as_object_mut().unwrap();
|
||||
match version {
|
||||
Some(v) => fields.insert("toolSettingsVersion".into(), json!(v)),
|
||||
None => fields.remove("toolSettingsVersion"),
|
||||
};
|
||||
let mut next = session();
|
||||
next.apply_prefs(serde_json::from_str(&prefs.to_string()).unwrap());
|
||||
next
|
||||
};
|
||||
for (version, saved, want) in [
|
||||
(None, json!({"highlightFill": false}), "swatches"),
|
||||
(None, json!({"pickColorFrom": "artwork"}), "swatches"),
|
||||
(None, json!({"pickColorFrom": "swatches"}), "swatches"),
|
||||
(Some(1), json!({"pickColorFrom": "artwork"}), "artwork"),
|
||||
(Some(1), json!({"pickColorFrom": "swatches"}), "swatches"),
|
||||
(Some(1), json!({"highlightFill": false}), "swatches"),
|
||||
] {
|
||||
let mut next = load(version, &saved);
|
||||
assert_eq!(next.prefs.tool_settings_version, 1, "the version is written: {version:?} {saved}");
|
||||
select(&mut next, "shapeBuilder");
|
||||
assert_eq!(next.tool_options()["pickColorFrom"], json!(want), "saved {version:?} {saved}");
|
||||
select(&mut next, "selection");
|
||||
assert_eq!(next.prefs.tool_settings["shapeBuilder"]["pickColorFrom"], json!(want), "stored again: {version:?} {saved}");
|
||||
}
|
||||
// Artwork picked after the update, or in a session that started without saved settings, is
|
||||
// kept at the next launch.
|
||||
for mut next in [load(None, &json!({"pickColorFrom": "artwork"})), session()] {
|
||||
select(&mut next, "shapeBuilder");
|
||||
next.set_tool_option("pickColorFrom", &json!("artwork"));
|
||||
select(&mut next, "selection");
|
||||
let saved_text = serde_json::to_string(&next.prefs).unwrap();
|
||||
let mut later = session();
|
||||
later.apply_prefs(serde_json::from_str(&saved_text).unwrap());
|
||||
select(&mut later, "shapeBuilder");
|
||||
assert_eq!(later.tool_options()["pickColorFrom"], json!("artwork"), "picked after the update: {saved_text}");
|
||||
}
|
||||
}
|
||||
@@ -581,6 +581,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
prefs.mark_tool_settings_current();
|
||||
}
|
||||
|
||||
/// Keep the active tool's persistent options for the next time it, or a tool sharing them, is
|
||||
|
||||
@@ -338,32 +338,78 @@ fn made_content(infos: &[SlotInfo], made: Vec<Option<Made>>, laid: bool) -> Vec<
|
||||
/// it, as far as strokes round type reach) as type the page draws. How many of the page's text
|
||||
/// objects no made type takes, shown or not: none that holds a piece of the object has its words
|
||||
/// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`).
|
||||
///
|
||||
/// The page can draw two text objects as one word: a word and a letter set apart from it (a swash
|
||||
/// "h" after "Spirit") come out of the page as one piece, "Spirith", that neither spells. A word
|
||||
/// left that is the last word of one text object holding the piece joined to the first word of
|
||||
/// another that holds it and draws after it, along the first one's lines, is theirs
|
||||
/// ([`joined_by_two`]).
|
||||
fn see_page_type(content: &mut [Content], shown: &[Vec<Arc<Node>>]) -> Option<usize> {
|
||||
let texts = |o: &[Arc<Node>]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::<Vec<_>>();
|
||||
// Each object's pieces of type, and the words of them that no made type holding it has yet.
|
||||
let mut objects: Vec<(Vec<Rect>, Vec<String>, bool)> =
|
||||
shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect();
|
||||
let pieces: usize = objects.iter().map(|o| o.0.len()).sum();
|
||||
if content.len().saturating_mul(pieces) > MAX_PAIRS {
|
||||
return None;
|
||||
}
|
||||
let mut budget = MAX_PAIRS.checked_sub(content.len().checked_mul(pieces)?)?;
|
||||
let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9);
|
||||
for c in content {
|
||||
let Content::Made(node, region, seen) = c else { continue };
|
||||
// The made type holding each object, in order: where it draws and its words.
|
||||
let mut holders: Vec<Vec<Arc<Holder>>> = vec![vec![]; objects.len()];
|
||||
let mut seen_slots = Vec::new();
|
||||
for (slot, c) in content.iter().enumerate() {
|
||||
let Content::Made(node, region, _) = c else { continue };
|
||||
// Hidden made type has no region: where it draws, shown, is its own box.
|
||||
let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue };
|
||||
let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() };
|
||||
for (rects, words, held) in &mut objects {
|
||||
let (spelled, holder) = match &node.kind {
|
||||
NodeKind::Text(t) => {
|
||||
let text = t.plain_text();
|
||||
let [a, b, ..] = t.xf.as_coeffs();
|
||||
(spelling(&text), Some(Arc::new((drawn.center(), (a, b), word_pieces(&text).map(spelling).filter(|w| !w.is_empty()).collect()))))
|
||||
}
|
||||
_ => (String::new(), None),
|
||||
};
|
||||
for ((rects, words, held), by) in objects.iter_mut().zip(&mut holders) {
|
||||
if rects.iter().any(|r| holds(drawn, r)) {
|
||||
*held = true;
|
||||
*seen |= region.is_some();
|
||||
if region.is_some() && seen_slots.last() != Some(&slot) {
|
||||
seen_slots.push(slot);
|
||||
}
|
||||
words.retain(|w| !spelled.contains(w.as_str()));
|
||||
by.extend(holder.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for ((_, words, _), by) in objects.iter_mut().zip(&holders) {
|
||||
if !words.is_empty() && !by.is_empty() {
|
||||
// Each unmatched word can visit every ordered pair of holders, plus the first-holder scan.
|
||||
budget = budget.checked_sub(words.len().checked_mul(by.len())?.checked_mul(by.len().checked_add(1)?)?)?;
|
||||
words.retain(|w| !joined_by_two(w, by));
|
||||
}
|
||||
}
|
||||
for slot in seen_slots {
|
||||
if let Content::Made(_, _, seen) = &mut content[slot] {
|
||||
*seen = true;
|
||||
}
|
||||
}
|
||||
Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count())
|
||||
}
|
||||
|
||||
/// A made text object that holds a piece of the page's type: the centre of where it draws, the
|
||||
/// way its lines run (the first column of its transform) and its words ([`spelling`]).
|
||||
type Holder = (Point, (f64, f64), Vec<String>);
|
||||
|
||||
/// Is `word` (a [`spelling`]) the last word of one of `by` joined to the first word of another of
|
||||
/// them that draws after it, along the first one's lines? Each part is a whole word of its text
|
||||
/// object, so a piece is never made up of bits of words.
|
||||
fn joined_by_two(word: &str, by: &[Arc<Holder>]) -> bool {
|
||||
by.iter().map(Arc::as_ref).any(|(at, (a, b), first)| {
|
||||
let Some(head) = first.last().filter(|h| word.len() > h.len() && word.starts_with(h.as_str())) else { return false };
|
||||
let tail = &word[head.len()..];
|
||||
by.iter()
|
||||
.map(Arc::as_ref)
|
||||
.any(|(next, _, second)| (next.x - at.x) * a + (next.y - at.y) * b > 0.0 && second.first().is_some_and(|w| w == tail))
|
||||
})
|
||||
}
|
||||
|
||||
/// What goes into each of `infos`' slots when the file's text document can't make the type of every
|
||||
/// slot that shows: type made from the text document (`made`) where it can, else the page's type that
|
||||
/// the text document puts where the page has it, else the page's type in a copy that a layer's or
|
||||
|
||||
@@ -8663,3 +8663,35 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() {
|
||||
let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12000.0, 14400.0), vec![], false, true, 1.0);
|
||||
assert!(!read, "the uncapped dimension must still match: {w:?}");
|
||||
}
|
||||
|
||||
/// The page's "2014" drawn as one piece 20 points across the art, and two text objects "20" and
|
||||
/// "14" anchored at `twenty` and `fourteen`, set in the bundled Source Sans 3 at 14 points (a digit
|
||||
/// 6.958 points wide) so that where they draw doesn't hang on the fonts installed.
|
||||
fn word_of_two_text_objects(fourteen: f64, twenty: f64) -> crate::import::Imported {
|
||||
let stories = [("20\r", 0, (twenty, 8180.0), (0.0, 0.0), 0.0), ("14\r", 0, (fourteen, 8180.0), (0.0, 0.0), 0.0)];
|
||||
let doc = text_document(&stories).replacen("/0 (Helvetica)", "/0 (SourceSans3-Regular)", 1);
|
||||
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc);
|
||||
let page = "0 1 0 0 setcmykcolor /SourceSans3-Regular findfont 14 scalefont setfont 20 61.5 moveto (2014) show";
|
||||
import(&eps(page, &art)).unwrap()
|
||||
}
|
||||
|
||||
/// The page can draw two text objects as one word: "20" and "14" set one after the other come out
|
||||
/// of the page as one piece, "2014", that neither spells. The word is the last word of the one
|
||||
/// joined to the first word of the one after it, so the page's type is theirs and nothing is noted
|
||||
/// as left out.
|
||||
#[test]
|
||||
fn a_word_the_page_draws_from_two_text_objects_in_a_row_is_their_type() {
|
||||
let r = word_of_two_text_objects(8161.5 + 13.916, 8161.5);
|
||||
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
|
||||
let texts: Vec<String> = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect();
|
||||
assert_eq!(texts, ["20", "14"], "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// The two text objects the other way round ("14" before "20") don't make the page's "2014": its
|
||||
/// word keeps the loss note.
|
||||
#[test]
|
||||
fn two_text_objects_the_other_way_round_arent_the_word_the_page_draws() {
|
||||
let r = word_of_two_text_objects(8161.5, 8161.5 + 13.916);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("some of the page's type has no text object in the layers")), "{:?}", r.warnings);
|
||||
}
|
||||
@@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"tool.options",
|
||||
"Tool Options…",
|
||||
"",
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options,
Line truncated
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options,
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
|
||||
@@ -801,7 +801,7 @@ fn digits_unnamed(text: &str) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing "�". This subset font
|
||||
/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing `\u{FFFD}`. This subset font
|
||||
/// has no character map of its own, but the font is installed: each digit is found by its outline
|
||||
/// there, so the whole text stays one type object, with no outlines left behind.
|
||||
#[test]
|
||||
|
||||
@@ -8,35 +8,5 @@
|
||||
startup | Noto Sans Arabic | Regular
|
||||
startup | Noto Sans Thai | Regular
|
||||
startup | Noto Sans Georgian | Regular
|
||||
background | Cairo | Regular
|
||||
background | Tajawal | ExtraLight
|
||||
background | Tajawal | Light
|
||||
background | Tajawal | Regular
|
||||
background | Tajawal | Medium
|
||||
background | Tajawal | Bold
|
||||
background | Tajawal | ExtraBold
|
||||
background | Tajawal | Black
|
||||
background | Almarai | Light
|
||||
background | Almarai | Regular
|
||||
background | Almarai | Bold
|
||||
background | Almarai | ExtraBold
|
||||
background | IBM Plex Sans Arabic | Thin
|
||||
background | IBM Plex Sans Arabic | ExtraLight
|
||||
background | IBM Plex Sans Arabic | Light
|
||||
background | IBM Plex Sans Arabic | Regular
|
||||
background | IBM Plex Sans Arabic | Medium
|
||||
background | IBM Plex Sans Arabic | SemiBold
|
||||
background | IBM Plex Sans Arabic | Bold
|
||||
background | Noto Kufi Arabic | Regular
|
||||
background | Amiri | Regular
|
||||
background | Amiri | Italic
|
||||
background | Amiri | Bold
|
||||
background | Amiri | Bold Italic
|
||||
background | Alexandria | Regular
|
||||
background | Fustat | Regular
|
||||
background | Reem Kufi | Regular
|
||||
background | Aref Ruqaa | Regular
|
||||
background | Aref Ruqaa | Bold
|
||||
background | Gulzar | Regular
|
||||
demand | NanumGothic | Regular
|
||||
demand | Noto Sans Devanagari | Regular
|
||||
@@ -66,11 +66,12 @@ pub struct ShapeBuilderOptions {
|
||||
/// region as if an invisible edge closed it. When it is off, the path cuts the regions it crosses
|
||||
/// as a line does.
|
||||
pub open_filled_as_closed: bool,
|
||||
/// Pick Color From Color Swatches (`pickColorFrom: "swatches"`; off: `"artwork"`): a merge
|
||||
/// Pick Color From Color Swatches (`pickColorFrom: "swatches"`, on; off: `"artwork"`): a merge
|
||||
/// fills the new shape with the current fill, and the Left and Right arrow keys step the current
|
||||
/// fill through the document's color swatches. With Artwork, the shape takes the look of the
|
||||
/// object where the drag starts, else of the one where it ends, else of the front-most selected
|
||||
/// object.
|
||||
/// object. A saved `pickColorFrom` is kept, except that preferences saved by an earlier version
|
||||
/// read a saved Artwork as Color Swatches once; preferences without one take Color Swatches.
|
||||
pub swatches: bool,
|
||||
/// Cursor Swatch Preview (`cursorSwatchPreview`, off): with Color Swatches, the current fill
|
||||
/// and the swatches before and after it show as chips above the pointer while no drag is on.
|
||||
@@ -105,7 +106,7 @@ impl Default for ShapeBuilderOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
open_filled_as_closed: true,
|
||||
swatches: false,
|
||||
swatches: true,
|
||||
cursor_swatch_preview: false,
|
||||
straight_line: false,
|
||||
highlight_fill: true,
|
||||
|
||||
@@ -17,6 +17,8 @@ pub enum Cursor {
|
||||
GroupSelection,
|
||||
/// Alt-dragging a copy with the Selection or Direct Selection tool: a double arrowhead.
|
||||
SelectionCopy,
|
||||
/// The Selection arrow over movable artwork.
|
||||
SelectionMove,
|
||||
Move,
|
||||
Crosshair,
|
||||
ResizeH,
|
||||
|
||||
@@ -129,11 +129,20 @@ shown_when = [
|
||||
hotspot = "The arrow's tip."
|
||||
look = "Arrow with a small x badge (nothing to select)."
|
||||
|
||||
[[cursor]]
|
||||
id = "SelectionMove"
|
||||
group = "Selection"
|
||||
shown_when = [
|
||||
"The Selection tool over a selected object or its movable source artwork, or over its visible centre point without Cmd/Ctrl held.",
|
||||
"The Selection tool over artwork while Alt is held, before the copy drag begins.",
|
||||
]
|
||||
hotspot = "The arrow's tip."
|
||||
look = "The Selection arrow with a small move badge."
|
||||
|
||||
[[cursor]]
|
||||
id = "Move"
|
||||
group = "Selection"
|
||||
shown_when = [
|
||||
"The Selection tool over a selected object, or over any object with Alt held (once an Alt-drag starts, SelectionCopy shows).",
|
||||
"The shape tools over a selected object's centre point (Attributes › Show Center), before a press there moves it (while the drag runs the arrow is plain, SelectionCopy with Alt, ArrowHollow while it snaps).",
|
||||
"Reshape over a path or while dragging.",
|
||||
"Inside the Free Transform and Crop Image boxes.",
|
||||
|
||||
@@ -1552,7 +1552,7 @@ impl Tool for SelectionTool {
|
||||
// take the pointer too (on a thin box the centre lies within a handle's reach), and with
|
||||
// Cmd/Ctrl held the press selects the object behind instead.
|
||||
if near_selected && !m.cmd && hit_center(cx, p, cx.point_tol()).is_some() {
|
||||
return Cursor::Move;
|
||||
return Cursor::SelectionMove;
|
||||
}
|
||||
// View → Snap to Point: over an anchor a press would grab the object by, the arrow turns
|
||||
// hollow.
|
||||
@@ -1560,11 +1560,11 @@ impl Tool for SelectionTool {
|
||||
return Cursor::ArrowHollow;
|
||||
}
|
||||
if selected_source_hit(cx, p).is_some() {
|
||||
return Cursor::Move;
|
||||
return Cursor::SelectionMove;
|
||||
}
|
||||
if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) {
|
||||
if selected_under(cx, &h, h.top_object(cx.isolation)).is_some() || m.alt {
|
||||
return Cursor::Move;
|
||||
return Cursor::SelectionMove;
|
||||
}
|
||||
return Cursor::Arrow;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ fn a_press_on_a_selected_shaper_source_moves_it_while_a_mask_is_edited() {
|
||||
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
|
||||
for x in [75.0, 125.0] {
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::Move, "at {x}");
|
||||
assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::SelectionMove, "at {x}");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, x, 350.0));
|
||||
assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "at {x}: {down:?}");
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, x + 20.0, 350.0));
|
||||
@@ -45,7 +45,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() {
|
||||
s.set([rect, ids[1]]);
|
||||
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move);
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove);
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 350.0));
|
||||
assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "{down:?}");
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 350.0));
|
||||
@@ -55,7 +55,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() {
|
||||
d.insert(Some(layer), 2, Node::path(front, square, Appearance::default_art())).unwrap();
|
||||
s.set([ids[1]]);
|
||||
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
|
||||
assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move);
|
||||
assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove);
|
||||
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 350.0));
|
||||
assert!(down.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{down:?}");
|
||||
}
|
||||
@@ -1042,7 +1042,7 @@ fn hidden_box_handles_take_no_press_while_anchors_are_selected() {
|
||||
s.anchors.entry(id).or_default().insert((0, 1));
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::Move);
|
||||
assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::SelectionMove);
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 150.0, 100.0));
|
||||
assert!(!down.contains(&Action::Begin("Scale".into())), "{down:?}");
|
||||
assert!(!crate::select::bbox_handle_at(&c, top_middle));
|
||||
@@ -3006,9 +3006,9 @@ fn a_press_on_the_centre_point_moves_an_unfilled_shape() {
|
||||
let c = ToolContext { path_only: true, ..cx(&d, &s, &p) };
|
||||
let centre = Point::new(150.0, 150.0);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move);
|
||||
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::SelectionMove);
|
||||
// Cmd/Ctrl selects the object behind, not the centre point, so the pointer says neither.
|
||||
assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::Move);
|
||||
assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::SelectionMove);
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y)).is_empty());
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0));
|
||||
assert_eq!(a.first(), Some(&Action::Begin("Move".into())), "{a:?}");
|
||||
@@ -3102,7 +3102,7 @@ fn a_ruler_guide_under_the_centre_point_keeps_the_pointer() {
|
||||
assert!(hit_center(&c, centre, c.point_tol()).is_some());
|
||||
let mut t = SelectionTool::default();
|
||||
let cursor = t.cursor(&c, centre, Mods::default());
|
||||
assert_ne!(cursor, Cursor::Move, "the guide's cursor, not the move arrow");
|
||||
assert_ne!(cursor, Cursor::SelectionMove, "the guide's cursor, not the move arrow");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y));
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0));
|
||||
assert!(drag.iter().any(|a| matches!(a, Action::Preview(cmd, _) if cmd == "guide.move")), "the guide drags: {down:?} {drag:?}");
|
||||
@@ -3177,7 +3177,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
|
||||
s.set(picked.iter().copied());
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "{picked:?}");
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "{picked:?}");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
|
||||
assert!(!is_select(&down), "{picked:?}: {down:?}");
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 125.0));
|
||||
@@ -3218,7 +3218,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
|
||||
s.anchors.insert(a, [(0, 0), (0, 1), (0, 2), (0, 3)].into_iter().collect());
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "every anchor");
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "every anchor");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
|
||||
assert!(!is_select(&down), "every anchor: {down:?}");
|
||||
}
|
||||
|
||||
@@ -104,6 +104,7 @@ vectorcraft-testkit = { workspace = true }
|
||||
vectorcraft-tools = { workspace = true, features = ["testing"] }
|
||||
# A variable font built in code (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
vectorcraft-plugins = { workspace = true, features = ["test-steady"] }
|
||||
wat = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -139,6 +139,8 @@ impl VectorcraftApp {
|
||||
spelling: Default::default(),
|
||||
text_nodes: Default::default(),
|
||||
momentary: None,
|
||||
hand: None,
|
||||
zoom_tool: None,
|
||||
selection_box: None,
|
||||
selection_bounds: None,
|
||||
selection_marks: None,
|
||||
@@ -379,7 +381,12 @@ impl VectorcraftApp {
|
||||
}
|
||||
|
||||
/// A window's raw input, before egui and the keys read it (the host's `raw_input_hook`).
|
||||
pub fn raw_input(&self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
pub fn raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
// AppKit consumes the key-down and winit can already have queued its key-up.
|
||||
// Poll before the runtime orders the press and release in this frame's input.
|
||||
if let Some(menu) = self.services.native_menu.as_mut() {
|
||||
menu.poll(ctx);
|
||||
}
|
||||
crate::type_editing::keep_layout_text(self, ctx, raw);
|
||||
}
|
||||
|
||||
@@ -716,7 +723,13 @@ impl VectorcraftApp {
|
||||
export_progress::show(self, ui);
|
||||
// After every window this pass may open, and before the palette's field takes the keyboard.
|
||||
panel_docking::close_overlays_for_modal(self, &ctx);
|
||||
let drawn_document = self.session.active().map(|st| (st.uid, st.revision));
|
||||
dialogs::host::pump(self, &ctx);
|
||||
// The canvas has already painted. A dialog can apply or roll back its preview
|
||||
// on the final input frame, with no further mouse movement to wake the window.
|
||||
if self.session.active().map(|st| (st.uid, st.revision)) != drawn_document {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
prefs_dialog::show(self, ui);
|
||||
crate::shortcut_editor::show(self, ui);
|
||||
credits::open_taken_link(self);
|
||||
@@ -823,6 +836,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
|
||||
root.escape_leaves_fields = true;
|
||||
// A held key repeats its command (Cmd+= keeps zooming in).
|
||||
root.shortcuts_repeat = true;
|
||||
// The wheel steps a focused number field only while the pointer is over it; elsewhere it scrolls what is under the
|
||||
// pointer.
|
||||
root.pointer_scoped_field_wheel = true;
|
||||
root
|
||||
}
|
||||
|
||||
|
||||
@@ -129,11 +129,12 @@ impl VectorcraftApp {
|
||||
/// document without artboards they get neither.
|
||||
fn add_active_artboard(&self, id: &str, params: &mut Value) {
|
||||
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
|
||||
let clipboard_command = paste || matches!(id, "edit.copy" | "edit.cut");
|
||||
if (vectorcraft_engine::ON_ACTIVE_ARTBOARD.contains(&id) || id == "command.batch")
|
||||
&& params.get("artboard").is_none()
|
||||
&& !(paste && params.get("artboards").is_some())
|
||||
&& self.view().is_some()
|
||||
&& let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !paste)
|
||||
&& let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !clipboard_command)
|
||||
&& let Some(p) = params.as_object_mut()
|
||||
{
|
||||
let picked = panels::artboards::picked(self, n);
|
||||
|
||||
@@ -81,6 +81,9 @@ pub struct CanvasCache {
|
||||
/// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between
|
||||
/// passes; the tool adapter takes it out for its call and puts it back.
|
||||
pub momentary: Option<craft::ui::canvas::Momentary>,
|
||||
pub hand: Option<craft::ui::canvas::HandTool>,
|
||||
/// The selected Zoom tool keeps its press and drag rectangle between canvas passes.
|
||||
pub zoom_tool: Option<craft::ui::canvas::ZoomTool>,
|
||||
/// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and
|
||||
/// Measure Type by Glyph Bounds).
|
||||
pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option<vectorcraft_doc::OrientedBox>)>,
|
||||
|
||||
@@ -278,8 +278,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
|
||||
pressed
|
||||
}
|
||||
|
||||
/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the
|
||||
/// picture last.
|
||||
/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks and the
|
||||
/// display-only widgets over it, the picture last.
|
||||
fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body {
|
||||
let live = kind == BodyKind::Live;
|
||||
let presenting = app.ui.screen_mode == 3;
|
||||
@@ -299,11 +299,12 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
|
||||
crate::dialogs::simplify_slider::show(app, ui, &space.view);
|
||||
}
|
||||
guides::show(app, ui, space, win, kind);
|
||||
widgets::show_hollow_corners(app, ui, space, kind);
|
||||
// The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this
|
||||
// frame's pointer event, from the document as the event leaves it.
|
||||
// The hollow Live Corners, the selection's marks, and the bounding box, Live Corners and shape widgets paint here
|
||||
// in that order, under the 3D handles and the bars. All of them are display only and are drawn after the tool host
|
||||
// has taken this frame's pointer event, from the document as the event leaves it.
|
||||
let hollow = PaintSlot::reserve(ui.painter());
|
||||
let marks = PaintSlot::reserve(ui.painter());
|
||||
widgets::show(app, ui, space, win, kind);
|
||||
let shown_widgets = PaintSlot::reserve(ui.painter());
|
||||
if !presenting && !revolve_editing(app) {
|
||||
crate::panels::three_d::handles::show(app, ui, space);
|
||||
}
|
||||
@@ -339,14 +340,21 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
|
||||
crate::type_editing::show(app, ui);
|
||||
}
|
||||
}
|
||||
let after = PaintSlot::reserve(ui.painter());
|
||||
selection::show(app, ui, space, win, kind);
|
||||
marks.extend(ui.ctx(), after.take_after(ui.ctx()));
|
||||
paint_into(ui, hollow, |ui| widgets::show_hollow_corners(app, ui, space, kind));
|
||||
paint_into(ui, marks, |ui| selection::show(app, ui, space, win, kind));
|
||||
paint_into(ui, shown_widgets, |ui| widgets::show(app, ui, space, win, kind));
|
||||
drops::show(app, ui, win, kind);
|
||||
raster::picture(app, ui, space, win, kind);
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs `draw` now and moves the shapes it paints on `ui`'s layer to `slot`, their place in the paint order.
|
||||
fn paint_into(ui: &mut Ui, slot: PaintSlot, draw: impl FnOnce(&mut Ui)) {
|
||||
let after = PaintSlot::reserve(ui.painter());
|
||||
draw(ui);
|
||||
slot.extend(ui.ctx(), after.take_after(ui.ctx()));
|
||||
}
|
||||
|
||||
/// The keys held now, as the engine's tools read them, with `space` set while Space is down.
|
||||
pub(crate) fn held_mods(ctx: &egui::Context) -> vectorcraft_tools::Mods {
|
||||
let (m, space) = ctx.input(|i| (i.modifiers, i.key_down(egui::Key::Space)));
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(super) fn checker_of(setup: &vectorcraft_doc::DocSetup) -> Checker {
|
||||
}
|
||||
|
||||
/// The page frames of document `st` seen through `view`: one per artboard, named "01 - name" with the
|
||||
/// Artboard tool or several boards, filled with its paper or the transparency grid (nothing in Outline).
|
||||
/// Artboard tool or several boards, filled with its paper or the transparency grid (white in Outline).
|
||||
/// Empty while the artboards are hidden.
|
||||
pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, view: &View, outline: bool) -> Vec<PageFrame> {
|
||||
if !shows_artboards(app) {
|
||||
@@ -51,7 +51,7 @@ pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, vi
|
||||
frame = frame.name(format!("{:02} - {}", i + 1, ab.name));
|
||||
}
|
||||
if outline {
|
||||
frame
|
||||
frame.fill(DataColor::new(Color32::WHITE))
|
||||
} else if grid {
|
||||
frame.checker(checker_of(setup))
|
||||
} else {
|
||||
|
||||
@@ -47,13 +47,13 @@ fn shift_clicking_a_name_toggles_selection_and_a_plain_click_activates() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_has_a_white_canvas_line_edges_and_no_paper() {
|
||||
fn outline_has_white_artboards_on_a_white_canvas_with_line_edges() {
|
||||
let _view = crate::testing::DefaultProofView::new();
|
||||
let app = app_with(2);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(pasteboard_color(&app, st, true), PasteboardColor::Custom(DataColor::new(Color32::WHITE)));
|
||||
assert_eq!(border(true), PageBorder::Line);
|
||||
assert!(frames_of(&app, true).iter().all(|f| f.fill.is_none()));
|
||||
assert!(frames_of(&app, true).iter().all(|f| f.fill == Some(PageFill::Color(DataColor::new(Color32::WHITE)))));
|
||||
assert_eq!(pasteboard_color(&app, st, false), PasteboardColor::Default);
|
||||
assert_eq!(border(false), PageBorder::DropShadow);
|
||||
assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some()));
|
||||
|
||||
@@ -35,7 +35,8 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
|
||||
let options = super::selection::path_options(&app.session.prefs);
|
||||
let quiet = tool_adapter::in_gesture(app, ui.ctx()) || tool_adapter::view_tool_held(app);
|
||||
let lists = [extra, overlays];
|
||||
for (i, o) in extra.iter().chain(overlays).enumerate() {
|
||||
// Only the overlays that are controls get a child `Ui`: a list of 10,000 path marks makes none.
|
||||
for (i, o) in extra.iter().chain(overlays).enumerate().filter(|(_, o)| is_control(o)) {
|
||||
ui.push_id(("tool-control", i), |ui| show_control(ui, rect, o));
|
||||
}
|
||||
for (i, list) in lists.into_iter().enumerate() {
|
||||
@@ -48,6 +49,26 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether `o` is shown as a framework control of its own ([`show_control`]) rather than painted by [`ToolMarks`].
|
||||
fn is_control(o: &Overlay) -> bool {
|
||||
match o {
|
||||
Overlay::Marquee(_) | Overlay::SelectionMarquee { .. } | Overlay::SharedPath { .. } | Overlay::Outlines { .. } | Overlay::Distance { .. } => {
|
||||
true
|
||||
}
|
||||
Overlay::Path { .. }
|
||||
| Overlay::Line { .. }
|
||||
| Overlay::Anchor { .. }
|
||||
| Overlay::CurvePoint { .. }
|
||||
| Overlay::Handle { .. }
|
||||
| Overlay::Label { .. }
|
||||
| Overlay::Measure { .. }
|
||||
| Overlay::Highlight { .. }
|
||||
| Overlay::Swatch { .. }
|
||||
| Overlay::GridLine { .. }
|
||||
| Overlay::HoverText { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The framework control `o` stands for, if it is one: a marquee, a settled outline, a set of outlines or a distance.
|
||||
fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
|
||||
match o {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::{DefaultHasher, Entry};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use craft::behavior::Input;
|
||||
use craft::behavior::Metrics;
|
||||
@@ -18,9 +19,9 @@ use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline};
|
||||
use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _};
|
||||
use craft::ui::style::{ComponentStyle, DataColor, StyleCx};
|
||||
use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
use vectorcraft_engine::{DocState, Prefs, ViewInfo};
|
||||
use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point};
|
||||
use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point, Vec2};
|
||||
use vectorcraft_tools::Mods;
|
||||
|
||||
use super::cursor::ViewKey;
|
||||
@@ -632,9 +633,13 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
|
||||
HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect);
|
||||
}
|
||||
let key = marks_key(app, st, tool, tool_points);
|
||||
let view = view_key(app, st, tool, tool_points);
|
||||
let marks = match app.canvas.selection_marks.take() {
|
||||
Some(kept) if kept.key == key => kept,
|
||||
_ => SelectionMarks::build(app, st, tool, tool_points, key),
|
||||
Some(kept) if kept.view == view && kept.selection == st.selection => {
|
||||
kept.follow(st, key).unwrap_or_else(|| SelectionMarks::build(app, st, tool, tool_points, (key, view)))
|
||||
}
|
||||
_ => SelectionMarks::build(app, st, tool, tool_points, (key, view)),
|
||||
};
|
||||
for o in &marks.outlines {
|
||||
let mut outline = SelectionOutline::solid("Selection", &o.paths).color(DataColor::new(o.color)).revision(o.revision);
|
||||
@@ -663,29 +668,99 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
|
||||
}
|
||||
|
||||
/// The outlines, anchors and dots `show` draws, kept between passes while their [`marks_key`] stays: a frame with
|
||||
/// nothing changed walks no selected object.
|
||||
/// nothing changed walks no selected object. They are also kept while the document and the selection stay the same
|
||||
/// under another revision, and moved with the selection when a move ([`vectorcraft_engine::Moved`]) took the document
|
||||
/// they show to the one now.
|
||||
pub(crate) struct SelectionMarks {
|
||||
key: u64,
|
||||
/// [`view_key`] of the state they were made for.
|
||||
view: u64,
|
||||
/// The selection they show.
|
||||
selection: vectorcraft_doc::Selection,
|
||||
/// The document they show.
|
||||
doc: Weak<Document>,
|
||||
/// A document they show moved by a distance: the one they were built for and no distance, or the document the
|
||||
/// last move they followed started from and its distance. Each step of a drag starts from the document the drag
|
||||
/// began with ([`SelectionMarks::follow`]).
|
||||
from: (Weak<Document>, Vec2),
|
||||
outlines: Vec<Outlined>,
|
||||
anchors: Anchors,
|
||||
dots: Dots,
|
||||
}
|
||||
|
||||
impl SelectionMarks {
|
||||
fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, key: u64) -> Self {
|
||||
fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, (key, view): (u64, u64)) -> Self {
|
||||
#[cfg(test)]
|
||||
tests::MARKS_BUILT.with(|built| built.set(built.get() + 1));
|
||||
Self { key, outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st) }
|
||||
let doc = Arc::downgrade(&st.doc);
|
||||
Self {
|
||||
key,
|
||||
view,
|
||||
selection: st.selection.clone(),
|
||||
from: (doc.clone(), Vec2::ZERO),
|
||||
doc,
|
||||
outlines: outlines(app, st),
|
||||
anchors: anchors(app, st, tool, tool_points),
|
||||
dots: dots(app, st),
|
||||
}
|
||||
}
|
||||
|
||||
/// The marks of `st`, whose [`marks_key`] is `key`, from these marks of the same selection and view: these marks
|
||||
/// when `st` shows the same document, these marks moved by `st`'s move when it took the document they show, or the
|
||||
/// document of [`SelectionMarks::from`], to the one `st` shows, else `None`.
|
||||
fn follow(mut self, st: &DocState, key: u64) -> Option<Self> {
|
||||
let now = Arc::as_ptr(&st.doc);
|
||||
if self.doc.as_ptr() != now {
|
||||
let moved = st.moved.as_ref().filter(|m| m.to.as_ptr() == now && m.selection == st.selection)?;
|
||||
let by = if moved.from.ptr_eq(&self.doc) {
|
||||
moved.by
|
||||
} else if moved.from.ptr_eq(&self.from.0) {
|
||||
moved.by - self.from.1
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
self.translate(by);
|
||||
self.from = (moved.from.clone(), moved.by);
|
||||
self.doc = moved.to.clone();
|
||||
}
|
||||
self.key = key;
|
||||
Some(self)
|
||||
}
|
||||
|
||||
/// Moves every mark by `by`.
|
||||
fn translate(&mut self, by: Vec2) {
|
||||
let shift = vectorcraft_geom::Affine::translate(by);
|
||||
for o in &mut self.outlines {
|
||||
o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift));
|
||||
o.revision = outline_revision(&o.paths, o.key.as_ref(), o.color.to_array());
|
||||
}
|
||||
for knot in self.anchors.paths.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) {
|
||||
knot.anchor += by;
|
||||
knot.in_ctrl += by;
|
||||
knot.out_ctrl += by;
|
||||
}
|
||||
let dots = &mut self.dots;
|
||||
for (at, _) in dots.origins.iter_mut().chain(&mut dots.centers).chain(&mut dots.key_anchor) {
|
||||
*at += by;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the selection's marks are built from: the document and its selection (its uid and revision), the parts the
|
||||
/// view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points, and the
|
||||
/// Selection & Anchor Display preferences.
|
||||
/// What the selection's marks are built from: the document and its selection (its uid and revision), and what
|
||||
/// [`view_key`] hashes.
|
||||
fn marks_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
(st.revision, view_key(app, st, tool, tool_points)).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// What the selection's marks are built from besides the document's content and the selection: the document (its
|
||||
/// uid), the parts the view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points,
|
||||
/// and the Selection & Anchor Display preferences.
|
||||
fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
let hides = ViewHides::of(app);
|
||||
(st.uid, st.revision, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h);
|
||||
(st.uid, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h);
|
||||
let prefs = &app.session.prefs;
|
||||
(prefs.anchor_size, prefs.show_handles_multiple_anchors, prefs.handle_style.as_str()).hash(&mut h);
|
||||
h.finish()
|
||||
|
||||
@@ -918,3 +918,75 @@ fn the_canvas_builds_the_selection_marks_once_per_change() {
|
||||
app.select_tool("directSelection");
|
||||
assert_eq!(frames(&mut app, 5), 1, "another tool builds the marks once");
|
||||
}
|
||||
|
||||
/// Every point of the outlines, the anchors and their handles, and the dots, in order.
|
||||
fn points_of(outlines: &[Outlined], anchors: &Anchors, dots: &Dots) -> Vec<Point> {
|
||||
let mut out = vec![];
|
||||
for path in outlines.iter().flat_map(|o| o.paths.iter().chain(&o.key)) {
|
||||
for el in path.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(a) | PathEl::LineTo(a) => out.push(a),
|
||||
PathEl::QuadTo(a, b) => out.extend([a, b]),
|
||||
PathEl::CurveTo(a, b, c) => out.extend([a, b, c]),
|
||||
PathEl::ClosePath => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for knot in anchors.paths.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots) {
|
||||
out.extend([knot.anchor, knot.in_ctrl, knot.out_ctrl]);
|
||||
}
|
||||
out.extend(dots.origins.iter().chain(&dots.centers).chain(&dots.key_anchor).map(|(at, _)| *at));
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the marks the canvas keeps are, to rounding, the ones the builders give for the state now.
|
||||
fn kept_marks_are_current(app: &VectorcraftApp) -> bool {
|
||||
let kept = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks");
|
||||
let st = app.session.active().unwrap();
|
||||
let now = points_of(&outlines(app, st), &anchors(app, st, app.session.tool_id(), false), &dots(app, st));
|
||||
let was = points_of(&kept.outlines, &kept.anchors, &kept.dots);
|
||||
now.len() == was.len() && now.iter().zip(&was).all(|(a, b)| (*a - *b).hypot() < 1e-9)
|
||||
}
|
||||
|
||||
// Whole-app frames keep the selection's marks through a new revision of the same document and selection, and move
|
||||
// them with a move of the selection instead of building them: a move command, each step of a drag, and the drag's end
|
||||
// build nothing and keep the marks of the state now. A scale and an undo still build them once.
|
||||
#[test]
|
||||
fn a_move_of_the_selection_moves_its_marks_without_building_them() {
|
||||
let (mut app, _) = scene();
|
||||
let ctx = crate::testing::ui_context();
|
||||
let frames = |app: &mut VectorcraftApp, n: usize| {
|
||||
let before = MARKS_BUILT.with(std::cell::Cell::get);
|
||||
for _ in 0..n {
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0));
|
||||
crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() });
|
||||
}
|
||||
MARKS_BUILT.with(std::cell::Cell::get) - before
|
||||
};
|
||||
frames(&mut app, 3);
|
||||
let layer = app.session.active().unwrap().doc.layers[0].id;
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
app.run("layer.setCurrent", json!({"id": layer.0})).unwrap();
|
||||
assert_ne!(app.session.active().unwrap().revision, revision, "a new revision");
|
||||
assert_eq!(frames(&mut app, 3), 0, "a new revision of the same document and selection");
|
||||
app.run("object.move", json!({"dx": 12.25, "dy": -5})).unwrap();
|
||||
assert_eq!(frames(&mut app, 3), 0, "a move command");
|
||||
assert!(kept_marks_are_current(&app), "after a move command");
|
||||
|
||||
app.session.begin_interaction("Move").unwrap();
|
||||
for dx in [3.0, 7.5, -2.0] {
|
||||
app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 4], "copy": false})).unwrap();
|
||||
assert_eq!(frames(&mut app, 2), 0, "a drag's step by {dx}");
|
||||
assert!(kept_marks_are_current(&app), "after a drag's step by {dx}");
|
||||
}
|
||||
app.session.commit_interaction().unwrap();
|
||||
assert_eq!(frames(&mut app, 2), 0, "the drag's end");
|
||||
assert!(kept_marks_are_current(&app), "after the drag");
|
||||
|
||||
app.run("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})).unwrap();
|
||||
assert_eq!(frames(&mut app, 3), 1, "a scale");
|
||||
assert!(kept_marks_are_current(&app), "after a scale");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(frames(&mut app, 3), 1, "an undo");
|
||||
assert!(kept_marks_are_current(&app), "after an undo");
|
||||
}
|
||||
@@ -303,7 +303,22 @@ fn press(at: Pos2, pressed: bool) -> egui::Event {
|
||||
/// object has after that frame's event, and none at the corner it had before it.
|
||||
#[test]
|
||||
fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() {
|
||||
selection_drag_marks_follow(drag_app());
|
||||
}
|
||||
|
||||
/// With Show Bounding Box While Moving and Drawing on, a Selection tool drag draws the bounding box and its handles in
|
||||
/// the frame the pointer moves: at the corner the object has after that frame's event, and none at the corner it had
|
||||
/// before it.
|
||||
#[test]
|
||||
fn a_selection_drag_draws_its_bounding_box_in_the_frame_the_pointer_moves() {
|
||||
let mut app = drag_app();
|
||||
app.session.prefs.bounding_box_while_moving_and_drawing = true;
|
||||
selection_drag_marks_follow(app);
|
||||
}
|
||||
|
||||
/// Drags a selected rectangle with the Selection tool in six frames and checks each frame that moved it: a mark at
|
||||
/// its corner after the frame's event, none at its corner before.
|
||||
fn selection_drag_marks_follow(mut app: VectorcraftApp) {
|
||||
let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("selection");
|
||||
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
@@ -411,6 +426,23 @@ fn a_click_activates_its_artboard_and_paste_in_place_goes_onto_it() {
|
||||
assert_eq!((b.x0, b.y0), (boards[2].x0 + 10.0, boards[2].y0 + 15.0));
|
||||
}
|
||||
|
||||
/// Copy uses the active board as its origin even when selected art lies on a different board.
|
||||
#[test]
|
||||
fn copy_and_paste_use_the_active_source_and_destination_artboards() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap();
|
||||
let boards: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let origin = Point::new(boards[1].x0 + 10.0, boards[1].y0 + 15.0);
|
||||
app.run("shape.rectangle", json!({"x": origin.x, "y": origin.y, "width": 20, "height": 20})).unwrap();
|
||||
app.views[0].artboard = 0;
|
||||
app.run("edit.copy", json!({})).unwrap();
|
||||
app.views[0].artboard = 2;
|
||||
let pasted = app.run("edit.pasteInPlace", json!({})).unwrap();
|
||||
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
|
||||
let bounds = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap();
|
||||
assert_eq!(bounds.origin(), origin + (boards[2].origin() - boards[0].origin()));
|
||||
}
|
||||
|
||||
/// A Shift-click with the Selection tool on an empty spot inside an artboard makes it the active
|
||||
/// one and keeps the selection, and Align to Artboard then aligns the objects to it unless the
|
||||
/// call names another artboard.
|
||||
@@ -865,6 +897,58 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() {
|
||||
assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it");
|
||||
}
|
||||
|
||||
/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its
|
||||
/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the
|
||||
/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts
|
||||
/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new
|
||||
/// app, at most 20 times, until the other catalogs held still through it.
|
||||
#[test]
|
||||
fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() {
|
||||
let fonts = vectorcraft_text::FontDb::global();
|
||||
let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins());
|
||||
let catalogs = || {
|
||||
(
|
||||
crate::menus::plugin_revision(),
|
||||
fonts.generation(),
|
||||
fonts.installed_fonts_ready(),
|
||||
crate::scripts_menu::revision(),
|
||||
crate::dialogs::proof_setup::saved_revision(),
|
||||
)
|
||||
};
|
||||
let run = || {
|
||||
let (mut app, ctx, xf) = rectangle_tool();
|
||||
let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("selection");
|
||||
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0)));
|
||||
app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
|
||||
for _ in 0..2 {
|
||||
app_step(&mut app, &ctx, vec![]);
|
||||
}
|
||||
let none = egui::Modifiers::NONE;
|
||||
let mut steps = vec![vec![primary(from, true, none)]];
|
||||
steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))]));
|
||||
steps.push(vec![primary(to, false, none)]);
|
||||
steps.extend([vec![], vec![], vec![]]);
|
||||
let mut rebuilt = vec![];
|
||||
for events in steps {
|
||||
let before = app.menus.rebuilds;
|
||||
app_step(&mut app, &ctx, events);
|
||||
rebuilt.push(app.menus.rebuilds - before);
|
||||
}
|
||||
(app, rebuilt)
|
||||
};
|
||||
let (app, rebuilt) = (0..20)
|
||||
.find_map(|_| {
|
||||
let before = catalogs();
|
||||
let out = run();
|
||||
(catalogs() == before).then_some(out)
|
||||
})
|
||||
.unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs"));
|
||||
assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle");
|
||||
assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle");
|
||||
}
|
||||
|
||||
/// #6369: only the selection box remains over the temporary halftone, and the original
|
||||
/// selection's outlines come back when Preview is turned off or the dialog is cancelled.
|
||||
#[test]
|
||||
@@ -4859,6 +4943,25 @@ fn a_flip_during_a_press_waits_for_the_release() {
|
||||
assert_eq!(app.session.tool_id(), "eraser", "the frame after the release");
|
||||
}
|
||||
|
||||
/// A selected Hand tracks its drag in the framework, outside the document tool's grab.
|
||||
#[test]
|
||||
fn turning_the_pen_during_a_hand_drag_waits_for_release() {
|
||||
let (mut app, stylus, ctx) = pen_app();
|
||||
app.select_tool("hand");
|
||||
let at = app.canvas_view().unwrap().rect.center();
|
||||
let to = at + egui::vec2(30.0, 20.0);
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
stylus.set(tip(0.5));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(at, true)]);
|
||||
stylus.set(eraser_end(0.5));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]);
|
||||
assert_eq!(app.session.tool_id(), "hand");
|
||||
frame(&mut app, &ctx, vec![button(to, false)]);
|
||||
assert_eq!(app.session.tool_id(), "hand");
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.tool_id(), "eraser");
|
||||
}
|
||||
|
||||
/// #764: a tool chosen while the eraser end stands in (the toolbar and shortcuts call
|
||||
/// `select_tool`; menus and MCP run `tool.select`) stays when the tip comes back.
|
||||
#[test]
|
||||
|
||||
@@ -127,13 +127,69 @@ fn a_hand_drag_held_near_the_edge_does_not_scroll_on() {
|
||||
let (mut app, ctx, _) = zoomed_in("hand");
|
||||
let rect = app.canvas_view().unwrap().rect;
|
||||
let start = rect.center();
|
||||
let before = center(&app);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
|
||||
let edge = pos2(rect.right() - 4.0, start.y);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]);
|
||||
let c0 = center(&app);
|
||||
assert!(c0.x < before.x, "dragging the selected Hand right must pan the view");
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
}
|
||||
assert_eq!(center(&app), c0);
|
||||
frame(&mut app, &ctx, vec![button(edge, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_freehand_stroke_at_the_edge_keeps_the_artwork_stationary() {
|
||||
let (mut app, ctx, original) = zoomed_in("pencil");
|
||||
let rect = app.canvas_view().unwrap().rect;
|
||||
let start = rect.center() - vec2(120.0, 60.0);
|
||||
let edge = pos2(rect.right() - 2.0, start.y + 40.0);
|
||||
let initial = center(&app);
|
||||
let nodes = |app: &VectorcraftApp| {
|
||||
let mut count = 0;
|
||||
app.session.active().unwrap().doc.walk(|_| count += 1);
|
||||
count
|
||||
};
|
||||
let before = nodes(&app);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(15.0, 25.0))]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]);
|
||||
for _ in 0..5 {
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(center(&app), initial);
|
||||
}
|
||||
frame(&mut app, &ctx, vec![button(edge, false)]);
|
||||
assert!(nodes(&app) > before, "the pencil drew a new path");
|
||||
assert!(app.session.active().unwrap().doc.node(original).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_zoom_tool_clicks_option_clicks_and_drags_a_marquee() {
|
||||
let (mut app, ctx, _) = zoomed_in("zoom");
|
||||
app.session.prefs.animated_zoom = false;
|
||||
let rect = app.canvas_view().unwrap().rect;
|
||||
let position = rect.center();
|
||||
let zoom = |app: &VectorcraftApp| app.view().unwrap().zoom;
|
||||
let initial = zoom(&app);
|
||||
for pressed in [true, false] {
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(position), button(position, pressed)]);
|
||||
}
|
||||
let enlarged = zoom(&app);
|
||||
assert!(enlarged > initial, "click should zoom in: {initial} -> {enlarged}");
|
||||
let modifiers = egui::Modifiers::ALT;
|
||||
for pressed in [true, false] {
|
||||
let event = egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers };
|
||||
frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(modifiers), event]);
|
||||
}
|
||||
frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
|
||||
let reduced = zoom(&app);
|
||||
assert!(reduced < enlarged, "Option-click should zoom out: {enlarged} -> {reduced}");
|
||||
let start = position - vec2(90.0, 65.0);
|
||||
let end = position + vec2(80.0, 55.0);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
|
||||
frame(&mut app, &ctx, vec![button(end, false)]);
|
||||
assert!(zoom(&app) > reduced, "the marquee should fit its region to the view");
|
||||
}
|
||||
@@ -590,7 +590,9 @@ impl CanvasTool for SessionTool<'_> {
|
||||
}
|
||||
|
||||
fn autoscrolls(&self) -> bool {
|
||||
!self.carrying.get() && !self.view_only()
|
||||
// Sampled freehand tools trace the pointer on the artwork. Scrolling
|
||||
// under a held pen would extend the stroke without another sample.
|
||||
!self.carrying.get() && !self.view_only() && !self.app().session.tool_wants_samples()
|
||||
}
|
||||
|
||||
fn view_only(&self) -> bool {
|
||||
@@ -629,6 +631,7 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
|
||||
// the release, and a pointer over another window for the pointer to come in.
|
||||
if ui.ctx().current_pass_index() == 0
|
||||
&& app.canvas.grab.is_none()
|
||||
&& !ToolHost::in_gesture(ui.ctx(), pass.id)
|
||||
&& ui.input(|i| i.pointer.has_pointer())
|
||||
&& crate::stylus::sync_eraser_tool(app)
|
||||
{
|
||||
@@ -650,7 +653,30 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
|
||||
let mut picked = ToolHostResponse::default();
|
||||
let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) {
|
||||
picked
|
||||
} else if matches!(app.session.tool_id(), "hand" | "zoom") && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() {
|
||||
let options = crate::app::view::navigation(&app.session.prefs);
|
||||
let response = if app.session.tool_id() == "zoom" {
|
||||
app.canvas.hand = None;
|
||||
let mut zoom = app.canvas.zoom_tool.take().unwrap_or_else(|| craft::ui::canvas::ZoomTool::new(options));
|
||||
zoom.options = options;
|
||||
let response = host_run(app, ui, pass, &mut zoom);
|
||||
app.canvas.zoom_tool = Some(zoom);
|
||||
response
|
||||
} else {
|
||||
app.canvas.zoom_tool = None;
|
||||
let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options));
|
||||
hand.options = options;
|
||||
let response = host_run(app, ui, pass, &mut hand);
|
||||
app.canvas.hand = Some(hand);
|
||||
response
|
||||
};
|
||||
if response.gesture.is_some() && !view_tool_held(app) && ui.input(|i| i.pointer.primary_down() || i.pointer.primary_pressed()) {
|
||||
crate::shortcuts::note_tool_use(app);
|
||||
}
|
||||
response
|
||||
} else {
|
||||
app.canvas.hand = None;
|
||||
app.canvas.zoom_tool = None;
|
||||
let mut tool = SessionTool::new(app, view_info, ui);
|
||||
let response = host_run_session(&mut tool, ui, pass);
|
||||
drop(tool);
|
||||
|
||||
@@ -89,6 +89,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor {
|
||||
Cursor::DirectAnchorSelected => tool("cursor-direct-anchor-selected", TIP, None),
|
||||
Cursor::ReshapeSegment => tool("cursor-reshape-segment", TIP, None),
|
||||
Cursor::GroupSelection => badged(CursorBadge::Add),
|
||||
Cursor::SelectionMove => badged(CursorBadge::Move),
|
||||
Cursor::SelectionCopy => badged(CursorBadge::Copy),
|
||||
Cursor::Move => system(CursorIcon::Move),
|
||||
Cursor::Crosshair => PaintedCursor::Crosshair.into(),
|
||||
@@ -195,7 +196,7 @@ pub(crate) fn request_busy(app: &crate::VectorcraftApp, ctx: &egui::Context) {
|
||||
|
||||
/// Every cursor with a look: its own, or the one it borrows.
|
||||
#[cfg(test)]
|
||||
const GLYPHS: [Cursor; 99] = [
|
||||
const GLYPHS: [Cursor; 100] = [
|
||||
Cursor::Hand,
|
||||
Cursor::HandGrab,
|
||||
Cursor::ZoomIn,
|
||||
@@ -207,6 +208,7 @@ const GLYPHS: [Cursor; 99] = [
|
||||
Cursor::ReshapeSegment,
|
||||
Cursor::GroupSelection,
|
||||
Cursor::SelectionCopy,
|
||||
Cursor::SelectionMove,
|
||||
Cursor::Move,
|
||||
Cursor::Crosshair,
|
||||
Cursor::ResizeH,
|
||||
|
||||
@@ -114,11 +114,19 @@ pub(super) fn render_preview(
|
||||
app: &mut VectorcraftApp,
|
||||
ctx: &egui::Context,
|
||||
doc: &vectorcraft_engine::doc::Document,
|
||||
) -> Option<Arc<egui::ColorImage>> {
|
||||
render_page_preview(&mut app.canvas.renderer, ctx.pixels_per_point(), doc)
|
||||
}
|
||||
|
||||
fn render_page_preview(
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
pixels_per_point: f32,
|
||||
doc: &vectorcraft_engine::doc::Document,
|
||||
) -> Option<Arc<egui::ColorImage>> {
|
||||
let region = doc.artboards.first()?.rect;
|
||||
let px = PREVIEW_PX * ctx.pixels_per_point() as f64;
|
||||
let px = PREVIEW_PX * pixels_per_point as f64;
|
||||
let scale = px / region.width().max(region.height()).max(1.0);
|
||||
let img = app.canvas.renderer.render_region(doc, region, scale, true);
|
||||
let img = renderer.render_region(doc, region, scale, true);
|
||||
Some(Arc::new(crate::canvas::color_image(&img)))
|
||||
}
|
||||
|
||||
@@ -286,6 +294,8 @@ pub(super) struct ImportPdfDialog {
|
||||
/// The preview shown for a (page, crop, text) revision; `None` for a page that could not be read, which is
|
||||
/// not asked for again.
|
||||
preview: Option<(Revision, Option<Arc<egui::ColorImage>>)>,
|
||||
/// One preview at a time. Page changes coalesce while the worker finishes.
|
||||
pending_preview: Option<(Revision, std::sync::mpsc::Receiver<Option<Arc<egui::ColorImage>>>)>,
|
||||
/// Why the last password did not open the file.
|
||||
password_error: Option<String>,
|
||||
/// The OK the pump has not answered.
|
||||
@@ -294,7 +304,7 @@ pub(super) struct ImportPdfDialog {
|
||||
|
||||
impl ImportPdfDialog {
|
||||
fn new(s: State) -> Self {
|
||||
ImportPdfDialog { id: dialog_id(KIND), s, preview: None, password_error: None, held: HeldAnswer::new() }
|
||||
ImportPdfDialog { id: dialog_id(KIND), s, preview: None, pending_preview: None, password_error: None, held: HeldAnswer::new() }
|
||||
}
|
||||
|
||||
/// The preview to render next: the revision of the shown page, crop and text, when the stored one differs.
|
||||
@@ -700,7 +710,14 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> {
|
||||
if s.links_on() {
|
||||
p["linkPages"] = json!(true);
|
||||
}
|
||||
io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ())
|
||||
if crate::opening::available()
|
||||
&& let Some(path) = s.path.as_deref()
|
||||
{
|
||||
crate::opening::start_with(app, path, s.file.bytes.clone(), p);
|
||||
Ok(())
|
||||
} else {
|
||||
io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ())
|
||||
}
|
||||
};
|
||||
// Asked only for the password, the dialog showed no Text choice to keep; the choice for a `.ai`
|
||||
// or `.ait` file is not kept for PDFs.
|
||||
@@ -711,10 +728,10 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// The preview of the page and boxes `s` shows; `None` for a page that can't be read.
|
||||
fn preview_image(app: &mut VectorcraftApp, ctx: &egui::Context, s: &State) -> Option<Arc<egui::ColorImage>> {
|
||||
fn preview_image(renderer: &mut vectorcraft_render::Renderer, pixels_per_point: f32, s: &State) -> Option<Arc<egui::ColorImage>> {
|
||||
let opts = fileio::LoadOptions { crop: s.crop, password: s.password(), text_as: s.preview_text_as(), ..Default::default() };
|
||||
let (doc, _) = fileio::page_document(&s.file.bytes, s.page().saturating_sub(1), &opts).ok()?;
|
||||
render_preview(app, ctx, &doc)
|
||||
render_page_preview(renderer, pixels_per_point, &doc)
|
||||
}
|
||||
|
||||
/// The host pump: judges the OK the dialog holds (opening or placing the file; a refusal keeps the dialog open with
|
||||
@@ -730,10 +747,44 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
dialog.answer_ok(answer);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
let wanted = dialogs.with(|host| host.get::<ImportPdfDialog>().and_then(|d| Some((d.wanted_preview()?, d.s.clone()))));
|
||||
if let Some((revision, s)) = wanted {
|
||||
let image = preview_image(app, ctx, &s);
|
||||
let wanted = dialogs.with(|host| {
|
||||
let dialog = host.get_mut::<ImportPdfDialog>()?;
|
||||
if let Some((revision, pending)) = &dialog.pending_preview {
|
||||
let image = match pending.try_recv() {
|
||||
Ok(image) => image,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => return None,
|
||||
};
|
||||
if dialog.wanted_preview() == Some(*revision) {
|
||||
dialog.set_preview(*revision, image);
|
||||
}
|
||||
dialog.pending_preview = None;
|
||||
}
|
||||
Some((dialog.wanted_preview()?, dialog.s.clone()))
|
||||
});
|
||||
let Some((revision, state)) = wanted else { return };
|
||||
let pixels_per_point = ctx.pixels_per_point();
|
||||
if crate::opening::available() {
|
||||
let (sender, pending) = std::sync::mpsc::channel();
|
||||
dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<ImportPdfDialog>() {
|
||||
dialog.pending_preview = Some((revision, pending));
|
||||
}
|
||||
});
|
||||
let wake = ctx.clone();
|
||||
let scope = vectorcraft_engine::file_access::ScopeHandle::capture();
|
||||
app.jobs().spawn(
|
||||
"vectorcraft-pdf-preview",
|
||||
Box::new(move || {
|
||||
let image = scope.run(|| preview_image(&mut vectorcraft_render::Renderer::new(), pixels_per_point, &state));
|
||||
let _ = sender.send(image);
|
||||
wake.request_repaint();
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
let image = preview_image(&mut app.canvas.renderer, pixels_per_point, &state);
|
||||
dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<ImportPdfDialog>() {
|
||||
dialog.set_preview(revision, image);
|
||||
|
||||
@@ -631,7 +631,7 @@ pub(super) mod tests {
|
||||
tool: "shapeBuilder",
|
||||
opens_on: vec![
|
||||
("openFilledAsClosed", json!(true)),
|
||||
("pickColorFrom", json!("artwork")),
|
||||
("pickColorFrom", json!("swatches")),
|
||||
("cursorSwatchPreview", json!(false)),
|
||||
("selection", json!("freeform")),
|
||||
("highlightFill", json!(true)),
|
||||
|
||||
@@ -42,7 +42,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft::menu::Node;
|
||||
use craft::ui::contract::Show as _;
|
||||
use craft::ui::contract::{Bind, Show as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog};
|
||||
@@ -548,7 +548,13 @@ pub(super) fn heading(plugin: &str, command: Option<&str>, gone: &str) -> String
|
||||
/// The builder of a hosted plug-in dialog over its values: the rows of `all` whose parameter is
|
||||
/// shown for the values (`m.visible`), after the description. The rows are made again in the UI
|
||||
/// language when it changes while the dialog is open; the field values stay as they are.
|
||||
fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
|
||||
fn build(
|
||||
key: &'static str,
|
||||
m: Manifest,
|
||||
all: Arc<[Param]>,
|
||||
look: Look,
|
||||
canvas: Option<egui::Id>,
|
||||
) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
|
||||
let rows_in = std::sync::Mutex::new((lang(), all));
|
||||
move |fields| {
|
||||
let all = {
|
||||
@@ -564,7 +570,10 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl
|
||||
rows.push(Param::read_only_text("description", "", look.description.clone()).full_width());
|
||||
}
|
||||
rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned());
|
||||
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews);
|
||||
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews).values(Bind::bound(fields));
|
||||
if let Some(canvas) = canvas.filter(|_| look.previews) {
|
||||
dialog = dialog.canvas(canvas);
|
||||
}
|
||||
if let Some(ok) = look.ok {
|
||||
dialog = dialog.ok_label(ok.into());
|
||||
}
|
||||
@@ -592,7 +601,8 @@ fn open_hosted(
|
||||
close_open(app);
|
||||
let all: Arc<[Param]> = form::plugin_params(&m, &values).into();
|
||||
let fields = form::fields_of(&all, &values);
|
||||
let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look)).instance(instance.to_string());
|
||||
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
|
||||
let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look, canvas)).instance(instance.to_string());
|
||||
let id = dialogs.with(|host| host.open(dialog));
|
||||
Ok((id, all))
|
||||
}
|
||||
|
||||
@@ -117,6 +117,20 @@ fn pdf_page_footer_ok_opens_the_chosen_range() {
|
||||
assert_eq!(artboard_widths(h.state()), [200.0, 300.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirming_a_desktop_pdf_import_queues_the_read_and_closes_the_dialog() {
|
||||
crate::opening::tests::with_threads(|| {
|
||||
let mut app = app();
|
||||
io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("three.pdf".into())).unwrap();
|
||||
set(&mut app, "allPages", json!(false));
|
||||
set(&mut app, "range", json!("2-3"));
|
||||
confirm(&mut app).unwrap();
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(app.opening.pending.len(), 1);
|
||||
assert_eq!(app.opening.pending[0].path, "three.pdf");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_multi_page_pdf_asks_for_the_pages() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -150,11 +150,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: Kind, tool: &Value) {
|
||||
let document = app.session.active().map(|doc| (doc.uid, doc.reverts));
|
||||
let rows = rows(app, kind, &opening);
|
||||
let fields = fields_of(&rows, &opening);
|
||||
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
|
||||
let dialog = HostedParamDialog::new(&ctx, kind.command(), fields, move |f| {
|
||||
if kind == Kind::Move {
|
||||
link_distance_and_angle(f);
|
||||
}
|
||||
let dialog = ParamDialog::new(kind.command(), kind.title(), rows.clone()).previews(true).values(Bind::bound(f));
|
||||
let dialog = match canvas {
|
||||
Some(canvas) => dialog.canvas(canvas),
|
||||
None => dialog,
|
||||
};
|
||||
if kind == Kind::Move { dialog.remember(MOVE_KEY) } else { dialog }
|
||||
});
|
||||
// A dialog this one replaces leaves its preview behind otherwise.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Panel bodies: what the dock area ([`crate::panel_docking`]) draws inside a docked, floating or
|
||||
//! flyout panel.
|
||||
|
||||
use craft::ui::contract::{Props as _, Scroll, ShowContainer as _};
|
||||
use craft::ui::layout_components::Stack;
|
||||
use egui::Ui;
|
||||
|
||||
use crate::state::DockTab;
|
||||
@@ -13,6 +15,28 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
|
||||
Some(DockTab::Properties) => panels::properties::show(app, ui),
|
||||
Some(DockTab::Layers) => panels::layers::show(app, ui),
|
||||
Some(DockTab::Libraries) => panels::libraries(app, ui),
|
||||
None if matches!(
|
||||
id,
|
||||
"align"
|
||||
| "attributes"
|
||||
| "blend"
|
||||
| "character"
|
||||
| "color"
|
||||
| "magicWand"
|
||||
| "openType"
|
||||
| "paragraph"
|
||||
| "pathfinder"
|
||||
| "patternOptions"
|
||||
| "stroke"
|
||||
| "tabs"
|
||||
| "transform"
|
||||
| "transparency"
|
||||
) =>
|
||||
{
|
||||
// These panels lay out forms. Collection panels own their scrolling viewport
|
||||
// and reserve their own footer outside it.
|
||||
Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| panels::show_icon_panel(app, ui, id));
|
||||
}
|
||||
None => panels::show_icon_panel(app, ui, id),
|
||||
}
|
||||
}
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn family_picker<'a>(
|
||||
.filters(filters)
|
||||
.sets(sets)
|
||||
.scripts(&FontScript::ALL)
|
||||
.filter_layout(FilterLayout::Chips)
|
||||
.filter_layout(FilterLayout::Toolbar)
|
||||
}
|
||||
|
||||
/// What one pass of a picker reads of the app, for a host that has no `app` while it draws (a dialog).
|
||||
|
||||
@@ -92,6 +92,8 @@ pub use run::{check_params, run_ui_command};
|
||||
pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number};
|
||||
#[cfg(test)]
|
||||
use slots::RECENT_FONT_IDS;
|
||||
#[cfg(test)]
|
||||
pub(crate) use state::WHY_OFF_ASKED;
|
||||
pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state};
|
||||
pub(crate) use state::{command_shortcuts, shown_state_with, why_off};
|
||||
pub(crate) use submenus::PATH_EFFECTS;
|
||||
|
||||
@@ -89,8 +89,10 @@ pub(crate) fn translate_label(english: &'static str) -> String {
|
||||
/// button pressed or released or a key pressed ([`last_press`]), changes once for each, which covers what the hash
|
||||
/// doesn't list (panels shown, a tool picked). While an
|
||||
/// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's
|
||||
/// preview, or a typing session), the revision, which each of its previews changes, is left out:
|
||||
/// the hash changes as the interaction begins and as it ends.
|
||||
/// preview, or a typing session), the hash takes the revision the interaction began from in place of the current one,
|
||||
/// which each of its previews changes, and changes as it ends. The hash stays the same as a tool's drag begins. An
|
||||
/// interaction that a dialog, a panel or the font menu begins changes the hash as it begins, since commands that check
|
||||
/// for an open interaction change state then and the menus stay open while it previews.
|
||||
pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
input.hash(&mut h);
|
||||
@@ -101,8 +103,9 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
|
||||
let s = &app.session;
|
||||
(s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h);
|
||||
if let Some(d) = s.active() {
|
||||
let revision = d.interaction.is_none().then_some(d.revision);
|
||||
(d.uid, revision, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h);
|
||||
let revision = d.interaction.as_ref().map_or(d.revision, |it| it.revision);
|
||||
let previewing = d.interaction.as_ref().is_some_and(|it| !it.by_tool());
|
||||
(d.uid, revision, previewing, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h);
|
||||
}
|
||||
(app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h);
|
||||
// Apply Last Filter and Last Filter… are named after the filter that ran last.
|
||||
@@ -257,7 +260,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
|
||||
// The Glyphs panel menu's East Asian glyph forms read the faces that draw the selected text from the layout this keeps.
|
||||
crate::panels::glyphs::refresh_form_faces(app);
|
||||
let listed = Listed::of(app);
|
||||
let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new() };
|
||||
let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new(), checks: Checks::default() };
|
||||
let menus: Vec<Menu> = menu_tree_named(app.session.prefs.font_names_in_english, &listed)
|
||||
.into_iter()
|
||||
.map(|(title, nodes)| {
|
||||
@@ -267,7 +270,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
|
||||
if translated { menu.english(title) } else { menu }
|
||||
})
|
||||
.collect();
|
||||
let Build { mut states, refs, .. } = build;
|
||||
let Build { mut states, refs, mut checks, .. } = build;
|
||||
|
||||
// The catalog is built again only when what its rows are made from changed; edits and selection changes change
|
||||
// the rows' states alone.
|
||||
@@ -291,7 +294,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
|
||||
CatalogRows { inputs, defs, known, accepted }
|
||||
}
|
||||
};
|
||||
row_states(app, &rows, &mut states);
|
||||
row_states(app, &rows, &mut states, &mut checks);
|
||||
crate::panels::panel_menu_states(app, &mut states);
|
||||
|
||||
let bar = MenuBar::new(menus);
|
||||
@@ -395,10 +398,10 @@ fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft:
|
||||
|
||||
/// The state of every catalog row the tree did not set, and of the engine commands the palette lists that no row
|
||||
/// names.
|
||||
fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates) {
|
||||
fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates, checks: &mut Checks) {
|
||||
for d in &rows.defs {
|
||||
if states.get(&d.command).is_none() {
|
||||
states.set(d.command.clone(), row_state(app, &d.command, &d.label));
|
||||
states.set(d.command.clone(), row_state(app, &d.command, &d.label, checks));
|
||||
}
|
||||
}
|
||||
// The engine commands the palette lists and no row names (Asset Export's Remove and Rename) are dimmed there and say
|
||||
@@ -406,11 +409,28 @@ fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStat
|
||||
for c in crate::palette::listed_engine_commands().filter(|c| !rows.known.contains(c.id)) {
|
||||
let command = CommandRef::new(c.id);
|
||||
if states.get(&command).is_none() {
|
||||
states.set(command.clone(), row_state(app, &command, c.label));
|
||||
states.set(command.clone(), row_state(app, &command, c.label, checks));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`why_off`] answered for each command id during one rebuild. The answer depends on the id and the app's state,
|
||||
/// not on the row's params, so the rows that share an id (Effect's dialogs, Window's panels, the interface languages)
|
||||
/// run their command's check once.
|
||||
#[derive(Default)]
|
||||
struct Checks(std::collections::HashMap<String, Option<Option<String>>>);
|
||||
|
||||
impl Checks {
|
||||
fn why_off(&mut self, app: &VectorcraftApp, id: &str) -> Option<Option<String>> {
|
||||
if let Some(why) = self.0.get(id) {
|
||||
return why.clone();
|
||||
}
|
||||
let why = why_off(app, id);
|
||||
self.0.insert(id.to_owned(), why.clone());
|
||||
why
|
||||
}
|
||||
}
|
||||
|
||||
/// `defs` without the commands a linked framework set defines (Undo, Redo, Cut, Copy, Paste and Tab's panels toggles):
|
||||
/// the set's definition is the command's. With them, the keys each has beyond the set's, as the set's keys and those
|
||||
/// (Cut, Copy and Paste's F2, F3 and F4 outside macOS).
|
||||
@@ -445,10 +465,9 @@ fn linked_defaults(command: &CommandRef) -> Option<Vec<Binding>> {
|
||||
|
||||
/// The state of the row `command`, named `label` in the catalog: on or dimmed with its reason, checked, and its title
|
||||
/// where the app shows another.
|
||||
fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> CommandState {
|
||||
fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str, checks: &mut Checks) -> CommandState {
|
||||
let state_id = crate::keymap::state_id(command);
|
||||
let why = why_off(app, state_id);
|
||||
let (enabled, checked) = shown_state_with(app, state_id, &command.params, &why).unwrap_or((false, None));
|
||||
let (enabled, checked) = shown_state_with(app, state_id, &command.params, &mut |id| checks.why_off(app, id)).unwrap_or((false, None));
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(on) = checked {
|
||||
state = state.checked(on);
|
||||
@@ -458,7 +477,7 @@ fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> Command
|
||||
state = state.title(shown.clone());
|
||||
}
|
||||
if !enabled {
|
||||
state = state.hint(off_reason_with(app, command, &shown, why));
|
||||
state = state.hint(off_reason_with(app, command, &shown, checks.why_off(app, state_id)));
|
||||
}
|
||||
state
|
||||
}
|
||||
@@ -493,6 +512,7 @@ struct Build<'a> {
|
||||
states: CommandStates,
|
||||
/// Every command reference the tree holds, its English label, and whether it is checkable.
|
||||
refs: Vec<(CommandRef, String, bool)>,
|
||||
checks: Checks,
|
||||
}
|
||||
|
||||
impl Build<'_> {
|
||||
@@ -548,22 +568,25 @@ impl Build<'_> {
|
||||
return Some(item);
|
||||
}
|
||||
let (id, params) = (command.id.as_str(), &command.params);
|
||||
let why = why_off(self.app, id);
|
||||
let (enabled, checked) = shown_state_with(self.app, id, params, &why)?;
|
||||
let (app, checks) = (self.app, &mut self.checks);
|
||||
let (enabled, checked) = shown_state_with(app, id, params, &mut |id| checks.why_off(app, id))?;
|
||||
let title = self.item_title(id, params, &item.label);
|
||||
let mut state = CommandState::new().enabled(enabled).title(title.clone());
|
||||
if let Some(on) = checked {
|
||||
state = state.checked(on);
|
||||
}
|
||||
let mut item = item;
|
||||
let tip = if id == "ui.expandDialog" && vectorcraft_engine::cmd::expand::has_appearance(&self.app.session) {
|
||||
Some(crate::i18n::tr(self.lang, crate::dialogs::expand::appearance_first()).to_string())
|
||||
// Expand… dimmed for appearance attributes says so in its tooltip; `why` holds what its check found, kept from
|
||||
// the state above.
|
||||
let appearance_first = crate::dialogs::expand::appearance_first();
|
||||
let why = if id == "ui.expandDialog" { self.checks.why_off(self.app, id) } else { None };
|
||||
let tip = if why.as_ref().is_some_and(|w| w.as_deref() == Some(appearance_first)) {
|
||||
Some(crate::i18n::tr(self.lang, appearance_first).to_string())
|
||||
} else if enabled {
|
||||
None
|
||||
} else {
|
||||
// The reason reads the check of the command's state id, which is `id` but for the framework's own rows.
|
||||
let state_id = crate::keymap::state_id(&command);
|
||||
let why = if state_id == id { why } else { why_off(self.app, state_id) };
|
||||
let why = self.checks.why_off(self.app, crate::keymap::state_id(&command));
|
||||
Some(off_reason_with(self.app, &command, &title, why))
|
||||
};
|
||||
if let Some(tip) = tip {
|
||||
@@ -658,6 +681,23 @@ mod tests {
|
||||
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled));
|
||||
}
|
||||
|
||||
/// A rebuild runs the check of a command that many rows share once: Effect's dialogs, Window's panels, the
|
||||
/// interface languages and Envelope Distort's Release, which decides whether Make or Reset is shown.
|
||||
#[test]
|
||||
fn a_rebuild_checks_a_shared_command_once() {
|
||||
let (mut app, ctx) = app_with_document();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
super::super::state::WHY_OFF_ASKED.with_borrow_mut(Vec::clear);
|
||||
refresh(&mut app, &ctx);
|
||||
let asked = super::super::state::WHY_OFF_ASKED.take();
|
||||
for id in ["effect.dialog", "window.panel", "app.language", "object.envelope.release"] {
|
||||
assert_eq!(asked.iter().filter(|a| *a == id).count(), 1, "{id}");
|
||||
}
|
||||
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled), "the states follow the selection");
|
||||
}
|
||||
|
||||
/// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together.
|
||||
#[test]
|
||||
fn a_rebuild_checks_each_dimmed_row_once() {
|
||||
@@ -677,4 +717,30 @@ mod tests {
|
||||
assert!(app.menus.states.get(&CommandRef::new(id)).is_some_and(|s| !s.is_enabled()), "{id} is still dimmed");
|
||||
}
|
||||
}
|
||||
|
||||
/// A rebuild walks the selection's appearance once for Object › Expand…, for its state and its tooltip together.
|
||||
#[test]
|
||||
fn a_rebuild_walks_the_appearance_once_for_expand() {
|
||||
let (mut app, ctx) = app_with_document();
|
||||
let expand = CommandRef::new("ui.expandDialog");
|
||||
let tooltip = |app: &VectorcraftApp| app.menus.bar.items().into_iter().find(|it| it.command == expand).and_then(|it| it.tooltip.clone());
|
||||
let walks = |app: &mut VectorcraftApp| {
|
||||
super::super::state::APPEARANCE_WALKS.set(0);
|
||||
refresh(app, &ctx);
|
||||
super::super::state::APPEARANCE_WALKS.get()
|
||||
};
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
assert_eq!(walks(&mut app), 1, "a plain rectangle");
|
||||
assert!(app.menus.states.get(&expand).is_some_and(CommandState::is_enabled));
|
||||
assert_eq!(tooltip(&app), None);
|
||||
app.run("appearance.addFill", json!({})).unwrap();
|
||||
assert_eq!(walks(&mut app), 1, "two fills");
|
||||
assert!(app.menus.states.get(&expand).is_some_and(|s| !s.is_enabled()));
|
||||
assert_eq!(tooltip(&app).as_deref(), Some(crate::dialogs::expand::appearance_first()));
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert_eq!(walks(&mut app), 0, "nothing selected");
|
||||
// Dimmed with nothing selected, the row keeps the general reason as its tooltip, as before.
|
||||
let tip = tooltip(&app);
|
||||
assert!(tip.as_deref().is_some_and(|t| t != crate::dialogs::expand::appearance_first()), "{tip:?}");
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,6 @@ pub(crate) fn run(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let gate =
|
||||
Gate::default().modal(app.file_dialog_open()).recording_shortcut(recording_shortcut(app)).text_editing(ctx.egui_wants_keyboard_input());
|
||||
let Some(menu) = app.services.native_menu.as_mut() else { return };
|
||||
menu.poll(ctx);
|
||||
menu.set_gate(gate);
|
||||
let clicks = menu.take_clicks(ctx);
|
||||
// A menu opening reads the Scripts folder again.
|
||||
|
||||
@@ -153,13 +153,14 @@ pub(super) fn hidden_when_disabled(id: &str) -> bool {
|
||||
|
||||
/// Menu items another item stands in for right now: Envelope Distort's Reset with Warp and Reset
|
||||
/// with Mesh take the place of Make with Warp and Make with Mesh while an envelope is selected.
|
||||
fn swapped_out(app: &VectorcraftApp, id: &str) -> bool {
|
||||
/// `why_off` answers [`why_off`] for Release's id.
|
||||
fn swapped_out(id: &str, why_off: &mut dyn FnMut(&str) -> Option<Option<String>>) -> bool {
|
||||
let reset = match id {
|
||||
"object.envelope.makeWithWarp" | "object.envelope.makeWithMesh" => false,
|
||||
"object.envelope.resetWithWarp" | "object.envelope.resetWithMesh" => true,
|
||||
_ => return false,
|
||||
};
|
||||
enabled(app, "object.envelope.release") != reset
|
||||
why_off("object.envelope.release").is_none() != reset
|
||||
}
|
||||
|
||||
/// Menu items shown only with Preferences › Type › Show East Asian Options on: Type › Composite
|
||||
@@ -173,16 +174,21 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool {
|
||||
/// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden
|
||||
/// ([`east_asian_hidden`]).
|
||||
pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option<bool>)> {
|
||||
shown_state_with(app, id, p, &why_off(app, id))
|
||||
shown_state_with(app, id, p, &mut |id| why_off(app, id))
|
||||
}
|
||||
|
||||
/// [`shown_state`] from `why`, what [`why_off`] answered for `id`: a caller that also writes the reason a dimmed row
|
||||
/// gives runs the command's check once.
|
||||
pub(crate) fn shown_state_with(app: &VectorcraftApp, id: &str, p: &Value, why: &Option<Option<String>>) -> Option<(bool, Option<bool>)> {
|
||||
let en = why.is_none()
|
||||
/// [`shown_state`] with `why_off` answering [`why_off`] for each command id it asks about: a caller that keeps the
|
||||
/// answers runs each command's check once.
|
||||
pub(crate) fn shown_state_with(
|
||||
app: &VectorcraftApp,
|
||||
id: &str,
|
||||
p: &Value,
|
||||
why_off: &mut dyn FnMut(&str) -> Option<Option<String>>,
|
||||
) -> Option<(bool, Option<bool>)> {
|
||||
let en = why_off(id).is_none()
|
||||
&& (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p))
|
||||
&& (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p));
|
||||
if (!en && hidden_when_disabled(id)) || swapped_out(app, id) || east_asian_hidden(app, id) {
|
||||
if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) {
|
||||
return None;
|
||||
}
|
||||
Some((en, checked(app, id, p)))
|
||||
@@ -295,9 +301,30 @@ pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option<Option<String>>
|
||||
Err(why) => Some(Some(why)),
|
||||
};
|
||||
}
|
||||
if id == "ui.expandDialog" {
|
||||
return expand_dialog_off(app);
|
||||
}
|
||||
(!ui_enabled(app, id)).then_some(None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`expand_dialog_off`] walked the selection's appearance on this thread.
|
||||
pub(crate) static APPEARANCE_WALKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Why Object › Expand… can't open now: dimmed with nothing selected, and with
|
||||
/// [`crate::dialogs::expand::appearance_first`] for appearance attributes, which Expand Appearance expands first
|
||||
/// (#3089). The selection's appearance is walked once, for the row's state and its tooltip together.
|
||||
fn expand_dialog_off(app: &VectorcraftApp) -> Option<Option<String>> {
|
||||
if !app.session.active().is_some_and(|d| !d.selection.is_empty()) {
|
||||
return Some(None);
|
||||
}
|
||||
#[cfg(test)]
|
||||
APPEARANCE_WALKS.set(APPEARANCE_WALKS.get() + 1);
|
||||
vectorcraft_engine::cmd::expand::has_appearance(&app.session).then(|| Some(crate::dialogs::expand::appearance_first().to_string()))
|
||||
}
|
||||
|
||||
/// Can UI command `id` run now?
|
||||
fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
|
||||
match id {
|
||||
@@ -388,10 +415,6 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
|
||||
id if id.starts_with(crate::panels::symbols::USER_SLOT) => crate::panels::symbols::user_library(app, id).is_some(),
|
||||
"ui.saveBrushLibrary" => crate::panels::brushes::has_brushes(app),
|
||||
id if id.starts_with(crate::panels::brushes::USER_SLOT) => crate::panels::brushes::user_library(app, id).is_some(),
|
||||
// Dimmed for appearance attributes, which Expand Appearance expands first (#3089).
|
||||
"ui.expandDialog" => {
|
||||
app.session.active().is_some_and(|d| !d.selection.is_empty()) && !vectorcraft_engine::cmd::expand::has_appearance(&app.session)
|
||||
}
|
||||
"ui.spotColors" => app.session.active().is_some(),
|
||||
"ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
|
||||
"ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app),
|
||||
|
||||
@@ -1193,7 +1193,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"tool.options",
|
||||
"Tool Options…",
|
||||
"",
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options,
Line truncated
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options,
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
|
||||
@@ -681,13 +681,35 @@ pub(crate) fn mixed_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (bool,
|
||||
match pstate::<Option<(Key, (bool, bool))>>(ctx, "proxy-mixed") {
|
||||
Some((k, mixed)) if k == key => mixed,
|
||||
_ => {
|
||||
let mixed = app.session.proxy_mixed();
|
||||
let mixed = walk_mixed_paints(app);
|
||||
set_pstate(ctx, "proxy-mixed", Some((key, mixed)));
|
||||
mixed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`mixed_paints`] for readers without a `Ui`, such as the panel menus' states: from the same cache while the app
|
||||
/// has its interface context, else from a walk of the selection.
|
||||
pub(crate) fn mixed_paints_now(app: &VectorcraftApp) -> (bool, bool) {
|
||||
match &app.ui_ctx {
|
||||
Some(ctx) => mixed_paints(app, ctx),
|
||||
None => walk_mixed_paints(app),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`vectorcraft_engine::Session::proxy_mixed`], which walks the selection.
|
||||
fn walk_mixed_paints(app: &VectorcraftApp) -> (bool, bool) {
|
||||
#[cfg(test)]
|
||||
MIXED_PAINT_WALKS.set(MIXED_PAINT_WALKS.get() + 1);
|
||||
app.session.proxy_mixed()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`walk_mixed_paints`] walked the selection on this thread.
|
||||
pub(crate) static MIXED_PAINT_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The stroke the Stroke panel, Control bar and Properties show: while the Type tool edits text,
|
||||
/// the selected characters' stroke, else [`vectorcraft_engine::Session::shown_stroke`].
|
||||
pub(crate) fn current_stroke(app: &VectorcraftApp) -> Option<StrokeLayer> {
|
||||
@@ -1108,6 +1130,31 @@ pub(crate) fn popover_body<R>(ui: &mut Ui, mut body: impl FnMut(&mut Ui) -> R) -
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The panel menus' states (the Color and Color Wheel menus) read whether the fill and stroke differ from the
|
||||
/// proxies' cache: one walk of the selection for each revision, which the proxies read too.
|
||||
#[test]
|
||||
fn panel_menu_states_walk_the_mixed_paints_once_per_revision() {
|
||||
let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
for x in [10, 60, 110] {
|
||||
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
}
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let walks = || MIXED_PAINT_WALKS.get();
|
||||
let start = walks();
|
||||
let mut states = CommandStates::new();
|
||||
panel_menu_states(&app, &mut states);
|
||||
assert_eq!(walks(), start + 1, "the menus walk the selection once");
|
||||
panel_menu_states(&app, &mut states);
|
||||
assert_eq!(mixed_paints(&app, &ctx), (false, false));
|
||||
assert_eq!(walks(), start + 1, "the same revision is not walked again, by the menus or the proxies");
|
||||
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
|
||||
panel_menu_states(&app, &mut states);
|
||||
assert_eq!(walks(), start + 2, "an edit is walked again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_events_run_their_commands() {
|
||||
let ran = |activated, double, swap, defaults| -> Vec<(&'static str, Value)> { proxy_commands(activated, double, swap, defaults) };
|
||||
|
||||
@@ -158,7 +158,7 @@ pub(crate) fn step_place(step: usize, in_batch: Option<usize>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a status message shows it: control characters become `�`, and text past 80
|
||||
/// `text` as a status message shows it: control characters become `\u{FFFD}`, and text past 80
|
||||
/// characters ends in `…`.
|
||||
pub(crate) fn shown_text(text: &str) -> String {
|
||||
const MAX: usize = 80;
|
||||
|
||||
@@ -89,7 +89,9 @@ fn actions_play_on_the_artboard_active_when_they_play() {
|
||||
app.ui.actions.push(Action { set, ..Action::new(name, steps) }).unwrap();
|
||||
set_actions(app, 0).len() - 1
|
||||
};
|
||||
app.view_mut().unwrap().artboard = 1;
|
||||
app.run("edit.copy", json!({})).unwrap();
|
||||
app.view_mut().unwrap().artboard = 0;
|
||||
let align = record(&mut app, "Align Left", "object.align", json!({"horizontal": "left", "to": "artboard"}));
|
||||
assert_eq!(bounds(&app, &[rect]).x0, boards[0].x0, "aligned to artboard 0 while recording");
|
||||
let paste = record(&mut app, "Paste in Place", "edit.pasteInPlace", json!({}));
|
||||
|
||||
@@ -34,8 +34,8 @@ use craft::theme::Variant;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::buttons::{Button, IconButton};
|
||||
use craft::ui::contract::{
|
||||
Bind, CollectionEvent, Entry, Props as _, RowAlign, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, TooltipSpec, clicked,
|
||||
request_rename,
|
||||
Bind, CollectionEvent, Entry, Props as _, RowAlign, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, TooltipSpec,
|
||||
clicked, request_rename,
|
||||
};
|
||||
use craft::ui::dialog::StackDialog as _;
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
@@ -524,13 +524,22 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let (selection, saving) = (&mut model.selection, &mut model.saving);
|
||||
let (mut export_clicked, mut footer, mut screens) = (false, None, false);
|
||||
// The grid takes the room the settings, Export and the footer bar leave.
|
||||
// The settings scroll in at most half the panel's height, so a long list of format rows stays reachable.
|
||||
// The preset name row stays below them, in view when Save As Preset opens it.
|
||||
let settings_room = ui.available_height() / 2.0;
|
||||
let settings_id = ui.scope_id().with(("asset-export-settings", uid));
|
||||
let footed = Stack::new().fill().footer(|ui, _| {
|
||||
crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| {
|
||||
let (change, files_each) = settings(ui, st);
|
||||
(seen.change, seen.files_each) = (change, files_each);
|
||||
seen.format_3d = format_3d(ui, st, &sel_or_all(&shown_sel, &all));
|
||||
seen.save = save_row(ui, saving);
|
||||
});
|
||||
Stack::new().id(settings_id).label(tl!("Export Settings")).fill_width().scroll(Scroll::vertical()).room_height(settings_room).show(
|
||||
ui,
|
||||
|ui, _| {
|
||||
crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| {
|
||||
let (change, files_each) = settings(ui, st);
|
||||
(seen.change, seen.files_each) = (change, files_each);
|
||||
seen.format_3d = format_3d(ui, st, &sel_or_all(&shown_sel, &all));
|
||||
});
|
||||
},
|
||||
);
|
||||
seen.save = save_row(ui, saving);
|
||||
Row::new().fill_width().align(RowAlign::End).show(ui, |ui, _| {
|
||||
let label = if shown_sel.is_empty() || shown_sel.len() == all.len() {
|
||||
tl!("Export").to_string()
|
||||
|
||||
@@ -6,7 +6,6 @@ use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::time::SystemTime;
|
||||
|
||||
// PLAN: assumed the framework paths below (craft::text::ui re-exports, craft_ui widgets and runtime, craft::font_manager).
|
||||
use craft::behavior::EditEvent;
|
||||
@@ -47,12 +46,15 @@ use crate::font_menu;
|
||||
/// attributes of the paragraph the selection starts in (else of the first paragraph).
|
||||
/// Font/paragraph controls and named-style capture use this; dimensional fields use `shared_effective`.
|
||||
pub(crate) fn text_style(app: &VectorcraftApp) -> Option<(CharStyle, vectorcraft_doc::ParaStyle)> {
|
||||
let state = app.session.active()?;
|
||||
// Hover changes the canvas, but the picker compares its next row click against the committed font.
|
||||
let doc = state.interaction.as_ref().filter(|_| app.font_preview_owner.is_some()).map_or(&state.doc, |preview| &preview.doc);
|
||||
if let Some((id, a, b)) = text_editing(app)
|
||||
&& let Some(NodeKind::Text(t)) = app.session.active().and_then(|d| d.doc.node(id)).map(|n| &n.kind)
|
||||
&& let Some(NodeKind::Text(t)) = doc.node(id).map(|n| &n.kind)
|
||||
{
|
||||
return Some((vectorcraft_text::edit::insertion_style(&t.runs, a, b), t.para_at(t.paragraphs_in(a, a).start).clone()));
|
||||
}
|
||||
let t = first_selected_text(app)?;
|
||||
let NodeKind::Text(t) = &first_selected_text_node_in(state, doc)?.kind else { return None };
|
||||
Some((t.first_style(), t.para_at(0).clone()))
|
||||
}
|
||||
|
||||
@@ -68,7 +70,11 @@ pub(crate) fn first_selected_text(app: &VectorcraftApp) -> Option<&vectorcraft_d
|
||||
/// their descendants, in selection order, then paint order within each selected object.
|
||||
pub(crate) fn first_selected_text_node(app: &VectorcraftApp) -> Option<&vectorcraft_doc::Node> {
|
||||
let st = app.session.active()?;
|
||||
for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
|
||||
first_selected_text_node_in(st, &st.doc)
|
||||
}
|
||||
|
||||
fn first_selected_text_node_in<'a>(state: &DocState, doc: &'a vectorcraft_doc::Document) -> Option<&'a vectorcraft_doc::Node> {
|
||||
for node in state.selection.objects.iter().filter_map(|id| doc.node(*id)) {
|
||||
let mut text = None;
|
||||
node.walk(&mut |n| {
|
||||
if text.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
@@ -1219,19 +1225,17 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
|
||||
let languages: Option<Vec<(String, String)>> =
|
||||
rows.contains(CharacterRows::STYLE_TOGGLES).then(|| LANGUAGES.iter().map(|(name, _, _)| (name.to_string(), name.to_string())).collect());
|
||||
let catalog = vectorcraft_text::FontDb::global().catalog();
|
||||
let before = font_menu::picker_settings(app);
|
||||
let mut settings = before.clone();
|
||||
let document = font_menu::document_family_set(app);
|
||||
let recent = font_menu::recently_added_set(app, SystemTime::now());
|
||||
let sets = font_menu::family_sets(Some(&document[..]), &recent[..]);
|
||||
let mut hold = font_menu::hold(app);
|
||||
let before = hold.settings.clone();
|
||||
let sets = font_menu::family_sets(hold.document.as_deref(), &hold.recently_added);
|
||||
let sample = font_menu::sample_text(app);
|
||||
let unit = type_unit(app);
|
||||
let mut source = FontPickerSource::new(catalog)
|
||||
.settings(Bind::bound(&mut settings))
|
||||
.filters(Bind::bound(&mut app.ui.font_filters))
|
||||
.settings(Bind::bound(&mut hold.settings))
|
||||
.filters(Bind::bound(&mut hold.filters))
|
||||
.sets(&sets)
|
||||
.scripts(&FontScript::ALL)
|
||||
.filter_layout(FilterLayout::Chips);
|
||||
.filter_layout(FilterLayout::Toolbar);
|
||||
if let Some(text) = &sample {
|
||||
source = source.preview_text(text);
|
||||
}
|
||||
@@ -1248,7 +1252,7 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
|
||||
controls = controls.axes(FaceAxes::new(axes, instances).italic(face_of(¤t.font_style).2));
|
||||
}
|
||||
let out = controls.show(ui);
|
||||
font_menu::store_picker_settings(app, &before, settings);
|
||||
hold.store(app, &before);
|
||||
let CharacterControlsOutput { picker, preview_family, edits, .. } = out;
|
||||
if let Some(owner) = picker {
|
||||
font_menu::apply_preview(app, owner, preview_family);
|
||||
|
||||
@@ -314,14 +314,14 @@ fn target(app: &VectorcraftApp, ui: &Ui) -> Target {
|
||||
target_with(app, super::active_mixed(app, ui.ctx()))
|
||||
}
|
||||
|
||||
/// Whether the active proxy is "?", read from the session (the panel reads its per-frame cache).
|
||||
/// Whether the active proxy is "?", from the proxies' cache ([`super::mixed_paints_now`]).
|
||||
fn mixed_now(app: &VectorcraftApp) -> bool {
|
||||
let (fill, stroke) = app.session.proxy_mixed();
|
||||
let (fill, stroke) = super::mixed_paints_now(app);
|
||||
if app.session.fill_active { fill } else { stroke }
|
||||
}
|
||||
|
||||
/// [`target`] with `mixed` for a "?" active proxy: the panel reads it from its per-frame cache,
|
||||
/// `ui.colorPanel` from the session.
|
||||
/// `ui.colorPanel` and the panel menus through [`mixed_now`].
|
||||
fn target_with(app: &VectorcraftApp, mixed: bool) -> Target {
|
||||
if mixed {
|
||||
return Target::Paint(None, None);
|
||||
@@ -440,7 +440,7 @@ pub(crate) fn apply_output(app: &mut VectorcraftApp, out: &ColorPanelOutput) {
|
||||
apply_with(app, &tgt, out);
|
||||
}
|
||||
|
||||
/// [`target`] with the session's "?" state, for callers without the panel's pass.
|
||||
/// [`target`] with the "?" state of [`mixed_now`], for callers without the panel's pass.
|
||||
pub(crate) fn target_now(app: &VectorcraftApp) -> Target {
|
||||
target_with(app, mixed_now(app))
|
||||
}
|
||||
@@ -616,8 +616,9 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
|
||||
/// The checks, titles and enabled states of [`menu_rows`]: the mode the panel shows is checked, and
|
||||
/// the rows that need a colour are off without one.
|
||||
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
|
||||
let tgt = target_now(app);
|
||||
let has_color = tgt.color().is_some() || mixed_now(app);
|
||||
let mixed = mixed_now(app);
|
||||
let tgt = target_with(app, mixed);
|
||||
let has_color = tgt.color().is_some() || mixed;
|
||||
for (command, state) in ColorPanelMenu::states(LAYOUT, &app.ui.color_panel, &shown(app, &tgt), has_color) {
|
||||
let state = if command == ColorPanelCommand::NewSwatch && !crate::menus::enabled(app, "swatch.new") { state.enabled(false) } else { state };
|
||||
states.set(command, state);
|
||||
|
||||
@@ -618,14 +618,15 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
|
||||
/// without a solid color, and CSS oklch() also while the active document's RGB space is not sRGB.
|
||||
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
|
||||
let srgb = cms::active().rgb_is_srgb();
|
||||
for item in items(&app.ui.color_wheel, srgb, target_now(app).color()) {
|
||||
let color = target_now(app).color();
|
||||
for item in items(&app.ui.color_wheel, srgb, color) {
|
||||
let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked);
|
||||
if let Some(hint) = item.hint {
|
||||
state = state.hint(hint);
|
||||
}
|
||||
states.set(CommandRef::new(row_id(&item.id)), state);
|
||||
}
|
||||
let has_color = target_now(app).color().is_some();
|
||||
let has_color = color.is_some();
|
||||
for (notation, label) in copy_notations() {
|
||||
let oklch = notation == "oklch";
|
||||
let mut state = CommandState::new().title(label.to_string()).enabled(has_color && (srgb || !oklch));
|
||||
|
||||
@@ -59,6 +59,12 @@ pub(crate) fn copy_value(ui: &mut Ui, label: &str, value: &str, mono: bool) -> b
|
||||
/// The same guarded full-value copy for an already shown readout. An elided path remains
|
||||
/// static text: selection indices must describe the text actually shown by the framework.
|
||||
pub(crate) fn copy_shown(ui: &mut Ui, shown: &egui::Response, value: &str) -> bool {
|
||||
// A container's measuring run shows the readout in an invisible sizing pass before the frame's real run, with the
|
||||
// same id and the same input. It neither copies nor reads or clears the remembered press: clearing it there would
|
||||
// leave the real run's release without its press.
|
||||
if ui.is_sizing_pass() {
|
||||
return false;
|
||||
}
|
||||
// The click's own position and keys: a move or a key change after the release in the same
|
||||
// frame leaves the pointer and the held keys elsewhere. A frame with more than one release
|
||||
// copies nothing, since the click flags below do not say which release they describe.
|
||||
|
||||
@@ -182,8 +182,9 @@ pub struct LayersUi {
|
||||
/// The selection square clicked last in each open document, by the document's `uid`: where a Shift-click on another
|
||||
/// square starts.
|
||||
pub art_anchors: HashMap<u64, NodeId>,
|
||||
/// The active document's rows with the [`LayerRows::key`] they were listed at.
|
||||
rows: Option<(u64, Tracked<LayerRows>)>,
|
||||
/// The active document's rows with the [`LayerRows::key`] they were listed at and the document's `uid` and
|
||||
/// `reverts`.
|
||||
rows: Option<(u64, (u64, u64), Tracked<LayerRows>)>,
|
||||
}
|
||||
|
||||
impl Default for LayersUi {
|
||||
@@ -223,7 +224,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
thumbnails.hold(app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy());
|
||||
let settings = app.ui.layers_panel.settings();
|
||||
refresh_rows(app);
|
||||
let (Some(st), Some((_, kept))) = (app.session.active(), &app.ui.layers_ui.rows) else { return };
|
||||
let (Some(st), Some((_, _, kept))) = (app.session.active(), &app.ui.layers_ui.rows) else { return };
|
||||
let tree = DocLayers::of(st, kept);
|
||||
let source = thumbs::LayerThumbs { doc: &st.doc };
|
||||
let mut panel = LayersPanel::new(kept)
|
||||
@@ -294,13 +295,23 @@ fn unrevealed<T>(app: &mut VectorcraftApp, f: impl FnOnce(&mut VectorcraftApp) -
|
||||
r
|
||||
}
|
||||
|
||||
/// Lists the active document's rows again when what they are listed from changed.
|
||||
/// Lists the active document's rows again when what they are listed from changed. The new rows go into the kept
|
||||
/// [`Tracked`] while the document is the same, so the panel keeps its display order when the
|
||||
/// [order revision](LayerRows::order_of) stays; another document, or the same one after File › Revert, gets a new one.
|
||||
fn refresh_rows(app: &mut VectorcraftApp) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let key = LayerRows::key(app, st);
|
||||
if app.ui.layers_ui.rows.as_ref().is_none_or(|(kept, _)| *kept != key) {
|
||||
let rows = Tracked::new(LayerRows::new(app, st));
|
||||
app.ui.layers_ui.rows = Some((key, rows));
|
||||
let doc = (st.uid, st.reverts);
|
||||
if app.ui.layers_ui.rows.as_ref().is_some_and(|(kept, _, _)| *kept == key) {
|
||||
return;
|
||||
}
|
||||
let new = LayerRows::new(app, st);
|
||||
match &mut app.ui.layers_ui.rows {
|
||||
Some((kept, of, rows)) if *of == doc => {
|
||||
rows.edit(|rows| *rows = new);
|
||||
*kept = key;
|
||||
}
|
||||
slot => *slot = Some((key, doc, Tracked::new(new))),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ impl Outcome for CellOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// A row's target circle: a ring, doubled while the row is targeted, with a dot when it has an
|
||||
/// A row's target circle: a ring, doubled while the row is targeted, with a diamond when it has an
|
||||
/// appearance or transparency of its own ([`target_marks`]).
|
||||
#[derive(Component, Props)]
|
||||
#[component(sample = TargetCircle::sample)]
|
||||
@@ -107,7 +107,13 @@ pub(super) struct TargetCircle {
|
||||
|
||||
impl TargetCircle {
|
||||
fn new(document: (u64, u64), id: NodeId, targeted: bool, styled: bool) -> Self {
|
||||
Self { common: Common::new(), document, id, targeted, styled, held: false, pick: None }
|
||||
let state = match (targeted, styled) {
|
||||
(true, true) => tl!("Target appearance: targeted, additional appearance or transparency"),
|
||||
(true, false) => tl!("Target appearance: targeted, basic appearance"),
|
||||
(false, true) => tl!("Target appearance: not targeted, additional appearance or transparency"),
|
||||
(false, false) => tl!("Target appearance: not targeted, basic appearance"),
|
||||
};
|
||||
Self { common: Common::new(), document, id, targeted, styled, held: false, pick: None }.tooltip(state).description(state).selected(targeted)
|
||||
}
|
||||
|
||||
/// A targeted circle with an appearance, for the suite.
|
||||
@@ -186,12 +192,13 @@ impl Component for TargetCircle {
|
||||
let draw = ui.draw();
|
||||
let (ring, width) = if self.held { (cx.style.accent, StrokeWidth::Medium) } else { (cx.style.ink, StrokeWidth::Thin) };
|
||||
draw.stroke(&PaintShape::Circle(center, TARGET_RADIUS), width, ring);
|
||||
let (inner, dot) = target_marks(self.targeted, self.styled);
|
||||
let (inner, mark) = target_marks(self.targeted, self.styled);
|
||||
if let Some(radius) = inner {
|
||||
draw.stroke(&PaintShape::Circle(center, radius), StrokeWidth::Thin, cx.style.ink);
|
||||
}
|
||||
if let Some(radius) = dot {
|
||||
draw.fill(&PaintShape::Circle(center, radius), cx.style.ink);
|
||||
if let Some(radius) = mark {
|
||||
let points = vec![center - vec2(0.0, radius), center + vec2(radius, 0.0), center + vec2(0.0, radius), center - vec2(radius, 0.0)];
|
||||
draw.stroke(&PaintShape::Polygon(points), StrokeWidth::Thin, cx.style.ink);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -202,6 +202,14 @@ pub(super) struct LayerRows {
|
||||
/// In isolation mode, the isolated node: the top row.
|
||||
#[plain_data(assume = "a node id is an integer")]
|
||||
root: Option<NodeId>,
|
||||
/// What the display order is built from ([`LayerRows::order_of`]).
|
||||
order: u64,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`LayerRows::children`] was asked on this thread.
|
||||
pub(super) static CHILDREN_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// [`LayerRows`] with the editing state of their document, for the panel's host code in one pass.
|
||||
@@ -243,7 +251,9 @@ impl LayerRows {
|
||||
let guide_rows = ruler.iter().enumerate().filter_map(|(i, g)| Some((g.id?, i))).collect();
|
||||
let blends = st.selection.objects.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. })));
|
||||
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let root = st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id);
|
||||
Self {
|
||||
order: Self::order_of(doc, &st.layers_open, app.ui.layers_panel.layers_only, root),
|
||||
doc: doc.clone(),
|
||||
opts: app.ui.layers_panel.clone(),
|
||||
xml_id: by_xml_id(app),
|
||||
@@ -258,10 +268,20 @@ impl LayerRows {
|
||||
holding: super::rows::holding(doc, &selected),
|
||||
selected,
|
||||
blends: blends.collect(),
|
||||
root: st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id),
|
||||
root,
|
||||
}
|
||||
}
|
||||
|
||||
/// A hash of everything the display order reads ([`LayerTree::children`] and [`LayerTree::is_open`]): the
|
||||
/// document, which an edit replaces and a selection change keeps (its ruler guides and an opacity mask being
|
||||
/// edited are in it), the open rows, Show Layers Only and the isolated node. The selection, the highlighted rows,
|
||||
/// the current layer, the names and the other Panel Options are not in it.
|
||||
fn order_of(doc: &Arc<Document>, open: &OpenRows, layers_only: bool, root: Option<NodeId>) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(Arc::as_ptr(doc) as usize, open.generation(), layers_only, root).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// What the rows of `st` are listed from: the document and its revision (which every edit and
|
||||
/// selection change moves), the open rows, isolation mode, the highlighted rows and the current
|
||||
/// layer, the Panel Options, Identify Objects By and the language.
|
||||
@@ -461,6 +481,8 @@ impl LayerTree for LayerRows {
|
||||
/// The top rows are the layers (only the opacity mask's while one is edited), or in isolation
|
||||
/// mode the isolated layer, sublayer, group or object.
|
||||
fn children(&self, parent: Option<&RowId>) -> Vec<RowId> {
|
||||
#[cfg(test)]
|
||||
CHILDREN_CALLS.with(|c| c.set(c.get() + 1));
|
||||
match parent {
|
||||
None => match self.root {
|
||||
Some(root) => vec![RowId::Node(root)],
|
||||
@@ -491,6 +513,11 @@ impl LayerTree for LayerRows {
|
||||
false
|
||||
}
|
||||
|
||||
/// The display order changes only with what [`LayerRows::order_of`] hashes: a selection change keeps it.
|
||||
fn order_revision(&self) -> Option<u64> {
|
||||
Some(self.order)
|
||||
}
|
||||
|
||||
fn info(&self, id: &RowId) -> LayerInfo {
|
||||
match *id {
|
||||
RowId::Node(id) => match self.doc.node(id) {
|
||||
|
||||
@@ -246,23 +246,20 @@ fn listed_nodes(tree: &DocLayers<'_>, filter: &LayerFilter) -> Vec<NodeId> {
|
||||
pub(super) const TARGET_RADIUS: f32 = 5.0;
|
||||
/// The radius of the inner ring of a targeted item's target circle (the double ring).
|
||||
pub(super) const TARGET_RING: f32 = 2.8;
|
||||
// PLAN: the sheet keeps `TARGET_STROKE`; the circle's rings take the theme's thin stroke (`StrokeWidth::Thin`), so it is gone.
|
||||
/// The radius of the dot filling the circle of an item that has an appearance of its own and is
|
||||
/// not targeted.
|
||||
pub(super) const TARGET_DOT: f32 = 3.2;
|
||||
/// The radius of that dot inside a targeted item's inner ring: clear of the ring, so a targeted
|
||||
/// item with an appearance of its own shows both (#8711).
|
||||
pub(super) const TARGET_DOT_IN_RING: f32 = 1.5;
|
||||
/// The radius of the outlined diamond marking an item's own appearance or transparency.
|
||||
pub(super) const APPEARANCE_MARK: f32 = 2.5;
|
||||
/// A mitered thin stroke extends a diamond's corner by width / sqrt(2). Radius 1 keeps
|
||||
/// the diamond clear of the targeted ring's inner edge (#8711).
|
||||
pub(super) const APPEARANCE_MARK_IN_RING: f32 = 1.0;
|
||||
|
||||
/// The marks inside a target circle's outer ring: the inner ring's radius when the item is
|
||||
/// `targeted`, and the appearance dot's radius when it is `styled` (has an appearance of its own).
|
||||
/// Each of the four combinations looks different, as the Layers panel's target icons do.
|
||||
/// The inner target ring's radius and the own-appearance diamond's radius. Each of the four
|
||||
/// combinations differs, and the diamond inside a targeted ring leaves that ring visible.
|
||||
pub(super) fn target_marks(targeted: bool, styled: bool) -> (Option<f32>, Option<f32>) {
|
||||
let dot = if targeted { TARGET_DOT_IN_RING } else { TARGET_DOT };
|
||||
(targeted.then_some(TARGET_RING), styled.then_some(dot))
|
||||
let mark = if targeted { APPEARANCE_MARK_IN_RING } else { APPEARANCE_MARK };
|
||||
(targeted.then_some(TARGET_RING), styled.then_some(mark))
|
||||
}
|
||||
|
||||
/// Whether an object's target circle is filled: its appearance is not basic (a group or layer:
|
||||
/// Whether an object's target circle shows its appearance mark: its appearance is not basic (a group or layer:
|
||||
/// it has fills, strokes or effects of its own) or its transparency (opacity, blend mode,
|
||||
/// isolation, knockout or an opacity mask) is not the default.
|
||||
pub(super) fn has_styled_target(n: &Node) -> bool {
|
||||
|
||||
@@ -74,21 +74,15 @@ fn answer(app: &mut VectorcraftApp, ctx: &egui::Context, ok: bool) {
|
||||
crate::dialogs::host::pump(app, ctx);
|
||||
}
|
||||
|
||||
/// The target-mark rule: each of the four looks (neither, targeted, an appearance, both) differs,
|
||||
/// and the dot sits clear of the inner ring, drawn in the theme's thin stroke, when both show.
|
||||
/// The four target/appearance combinations remain distinct, with the appearance diamond clear of
|
||||
/// the inner target ring in the theme's thin stroke.
|
||||
#[test]
|
||||
fn target_circle_marks_follow_targeted_and_styled() {
|
||||
use rows::{TARGET_DOT, TARGET_DOT_IN_RING, TARGET_RING, target_marks};
|
||||
use rows::{APPEARANCE_MARK, APPEARANCE_MARK_IN_RING, TARGET_RING, target_marks};
|
||||
assert_eq!(target_marks(false, false), (None, None));
|
||||
assert_eq!(target_marks(true, false), (Some(TARGET_RING), None));
|
||||
assert_eq!(target_marks(false, true), (None, Some(TARGET_DOT)));
|
||||
let (ring, dot) = target_marks(true, true);
|
||||
assert_eq!((ring, dot), (Some(TARGET_RING), Some(TARGET_DOT_IN_RING)));
|
||||
let thin = std::rc::Rc::new(std::cell::Cell::new(f32::INFINITY));
|
||||
let seen = std::rc::Rc::clone(&thin);
|
||||
let mut fixture = craft::ui::testing::Fixture::new(move |ui| seen.set(craft::ui::runtime::env::Env::of(ui).tokens.stroke.thin));
|
||||
fixture.root(crate::app::root_env(&vectorcraft_engine::Prefs::default(), 1.0, None)).frame(vec![]);
|
||||
assert!(TARGET_DOT_IN_RING + 0.5 < TARGET_RING - thin.get() / 2.0, "the dot covers the ring");
|
||||
assert_eq!(target_marks(false, true), (None, Some(APPEARANCE_MARK)));
|
||||
assert_eq!(target_marks(true, true), (Some(TARGET_RING), Some(APPEARANCE_MARK_IN_RING)));
|
||||
}
|
||||
|
||||
/// A document with two rectangles on one layer → (app, layer, [bottom, top]).
|
||||
@@ -1329,6 +1323,156 @@ fn a_target_circle_drop_after_file_revert_leaves_the_restored_appearance_in_plac
|
||||
assert_eq!(fill(&panel.app(), b), red, "a target circle drag started after the revert still moves the appearance");
|
||||
}
|
||||
|
||||
/// The cardinal four-point outline actually painted by the native cell, independently of its constants.
|
||||
fn appearance_diamond(shape: &egui::Shape) -> Option<(egui::Pos2, f32, f32)> {
|
||||
let egui::Shape::Path(path) = shape else { return None };
|
||||
if !path.closed || path.fill != egui::Color32::TRANSPARENT || path.points.len() != 4 {
|
||||
return None;
|
||||
}
|
||||
let c = egui::pos2((path.points[0].x + path.points[2].x) / 2.0, (path.points[0].y + path.points[2].y) / 2.0);
|
||||
let r = path.points[0].distance(c);
|
||||
if ![2.5, 1.0].iter().any(|expected| (r - expected).abs() < 1e-4) {
|
||||
return None;
|
||||
}
|
||||
let expected = [c - egui::vec2(0.0, r), c + egui::vec2(r, 0.0), c + egui::vec2(0.0, r), c - egui::vec2(r, 0.0)];
|
||||
path.points.iter().zip(expected).all(|(a, b)| a.distance(b) < 1e-4).then_some((c, r, path.stroke.width))
|
||||
}
|
||||
|
||||
/// The actual native cell's marks at `name`, read from the fixture's paint output: radius, diamond, width.
|
||||
fn target_marks_painted(panel: &mut crate::tests::panel_harness::Panel, name: &str) -> Vec<(f32, bool, f32)> {
|
||||
let center = panel.rect(name).center();
|
||||
let (shapes, _) = panel.paint_at(1.0);
|
||||
let ink = shapes
|
||||
.iter()
|
||||
.find_map(|shape| match shape {
|
||||
egui::Shape::Circle(circle) if circle.center.distance(center) < 0.01 && (circle.radius - 5.0).abs() < 1e-4 => Some(circle.stroke.color),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the cell's outer target ring");
|
||||
for shape in &shapes {
|
||||
if appearance_diamond(shape).is_some_and(|(at, _, _)| at.distance(center) < 0.01)
|
||||
&& let egui::Shape::Path(path) = shape
|
||||
{
|
||||
assert_eq!(path.stroke.color, egui::epaint::ColorMode::Solid(ink), "the native marker keeps the target ring's themed ink");
|
||||
assert_eq!(path.stroke.kind, egui::StrokeKind::Middle, "the diamond's stroke is centered on its outline");
|
||||
}
|
||||
}
|
||||
let mut marks: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match shape {
|
||||
egui::Shape::Circle(circle)
|
||||
if circle.center.distance(center) < 0.01 && circle.radius < 5.0 && circle.fill == egui::Color32::TRANSPARENT =>
|
||||
{
|
||||
Some((circle.radius, false, circle.stroke.width))
|
||||
}
|
||||
shape => appearance_diamond(shape).filter(|(at, _, _)| at.distance(center) < 0.01).map(|(_, r, width)| (r, true, width)),
|
||||
})
|
||||
.collect();
|
||||
marks.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
marks
|
||||
}
|
||||
|
||||
/// Retain #8757's historical regression name: the own-appearance diamond leaves the actual inner
|
||||
/// ring visible, and neither, targeted, styled and both paint four different looks.
|
||||
#[test]
|
||||
fn a_targeted_circle_with_an_appearance_shows_both_ring_and_dot() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let (mut app, _, [a, _]) = two_rects();
|
||||
name_row(&mut app, a, "A");
|
||||
let mut panel = Panel::new(app, show);
|
||||
let neither = target_marks_painted(&mut panel, "Target A");
|
||||
panel.click("Target A");
|
||||
let targeted = target_marks_painted(&mut panel, "Target A");
|
||||
panel.app().session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
|
||||
panel.frame();
|
||||
let both = target_marks_painted(&mut panel, "Target A");
|
||||
panel.app().session.execute("select.none", &json!({})).unwrap();
|
||||
panel.frame();
|
||||
let styled = target_marks_painted(&mut panel, "Target A");
|
||||
let ring = both.iter().find(|m| (m.0 - 2.8).abs() < 1e-4 && !m.1).expect("the actual inner ring");
|
||||
let mark = both.iter().find(|m| m.1).expect("the actual hollow diamond");
|
||||
let outer_extent = mark.0 + mark.2 * std::f32::consts::FRAC_1_SQRT_2;
|
||||
assert!(outer_extent < ring.0 - ring.2 / 2.0 - 0.5, "the diamond {mark:?} covers the ring {ring:?}");
|
||||
assert!((mark.0 - 1.0).abs() < 1e-4);
|
||||
assert_eq!(mark.2, ring.2, "the marker retains the theme's thin stroke");
|
||||
let alone = styled.iter().find(|m| m.1).expect("the standalone diamond");
|
||||
assert!((alone.0 - 2.5).abs() < 1e-4);
|
||||
let looks = [&neither, &targeted, &styled, &both];
|
||||
for (i, x) in looks.iter().enumerate() {
|
||||
for y in &looks[i + 1..] {
|
||||
assert_ne!(x, y, "all four actual cell looks differ");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hover and accessibility explain the mark without replacing the contextual row name; the same
|
||||
/// native cell still targets its art, while selecting other art leaves its own appearance intact.
|
||||
#[test]
|
||||
fn appearance_marker_names_its_state_and_keeps_targeting_actions() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
struct RestoreLanguage(crate::i18n::Lang);
|
||||
impl Drop for RestoreLanguage {
|
||||
fn drop(&mut self) {
|
||||
crate::i18n::set_current(self.0);
|
||||
}
|
||||
}
|
||||
let _language = RestoreLanguage(crate::i18n::current());
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let (mut app, _, [a, b]) = two_rects();
|
||||
name_row(&mut app, a, "A");
|
||||
name_row(&mut app, b, "B");
|
||||
app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let idle = "Target appearance: not targeted, additional appearance or transparency";
|
||||
let active = "Target appearance: targeted, additional appearance or transparency";
|
||||
assert_eq!(panel.description("Target A").as_deref(), Some(idle));
|
||||
assert_eq!(panel.description("Target B").as_deref(), Some("Target appearance: not targeted, basic appearance"));
|
||||
assert_eq!(panel.toggled("Target A"), Some(craft::behavior::Mixed::Same(false)));
|
||||
let before = {
|
||||
let app = panel.app();
|
||||
(app.session.active().unwrap().selection.clone(), undo_len(&app))
|
||||
};
|
||||
panel.hover("Target A");
|
||||
panel.advance(2.0);
|
||||
panel.frame();
|
||||
let (shapes, _) = panel.paint_at(1.0);
|
||||
assert!(shapes.iter().any(|s| matches!(s, egui::Shape::Text(t) if t.galley.text() == idle)), "the native tooltip explains the mark");
|
||||
{
|
||||
let app = panel.app();
|
||||
assert_eq!((app.session.active().unwrap().selection.clone(), undo_len(&app)), before, "hover changes no selection or history");
|
||||
}
|
||||
panel.click("Target A");
|
||||
assert_eq!(targeted(&panel.app()), (Some(a), vec![a]));
|
||||
assert_eq!(panel.description("Target A").as_deref(), Some(active));
|
||||
assert_eq!(panel.toggled("Target A"), Some(craft::behavior::Mixed::Same(true)));
|
||||
panel.click("Target B");
|
||||
assert_eq!(panel.description("Target A").as_deref(), Some(idle));
|
||||
assert_eq!(panel.description("Target B").as_deref(), Some("Target appearance: targeted, basic appearance"));
|
||||
assert_eq!(panel.toggled("Target B"), Some(craft::behavior::Mixed::Same(true)));
|
||||
assert!(target_marks_painted(&mut panel, "Target A").iter().any(|m| m.1), "the appearance stays after targeting other art");
|
||||
}
|
||||
|
||||
/// The marker's native cell retains appearance move and Alt-copy admission and payloads.
|
||||
#[test]
|
||||
fn dragging_a_target_circle_moves_or_copies_the_appearance() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let (mut app, layer, [a, b]) = two_rects();
|
||||
name_row(&mut app, layer, "Layer");
|
||||
name_row(&mut app, a, "A");
|
||||
name_row(&mut app, b, "B");
|
||||
app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let opacity = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().opacity;
|
||||
panel.drag("Target A", "Target B", egui::Modifiers::ALT);
|
||||
{
|
||||
let app = panel.app();
|
||||
assert!((opacity(&app, a) - 0.3).abs() < 1e-6 && (opacity(&app, b) - 0.3).abs() < 1e-6);
|
||||
}
|
||||
panel.drag("Target B", "Target Layer", egui::Modifiers::NONE);
|
||||
let app = panel.app();
|
||||
assert!((opacity(&app, layer) - 0.3).abs() < 1e-6 && opacity(&app, b) == 1.0);
|
||||
}
|
||||
|
||||
/// The rows find which nodes hold selected art once per revision: frames that change nothing walk no node for the
|
||||
/// selection squares, and a new selection walks the tree once.
|
||||
#[test]
|
||||
@@ -1352,3 +1496,78 @@ fn idle_frames_walk_no_node_for_the_selection_squares() {
|
||||
}
|
||||
assert!((1..=12).contains(&(visits() - before)), "a new selection walks the tree once: {}", visits() - before);
|
||||
}
|
||||
|
||||
/// A selection change keeps the panel's display order: no row is asked for the rows inside it. Closing a row, Show
|
||||
/// Layers Only and an edit build the order again, and the rows follow.
|
||||
#[test]
|
||||
fn a_selection_change_keeps_the_display_order() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let calls = || super::model::CHILDREN_CALLS.with(std::cell::Cell::get);
|
||||
let (mut app, [_, sub, _, b, a, c]) = nested();
|
||||
for (id, name) in [(sub, "Sub"), (b, "B"), (a, "A"), (c, "C")] {
|
||||
name_row(&mut app, id, name);
|
||||
}
|
||||
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.frame();
|
||||
let before = calls();
|
||||
panel.app().session.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for _ in 0..3 {
|
||||
panel.frame();
|
||||
}
|
||||
assert_eq!(calls() - before, 0, "a selection change asks no row for its rows");
|
||||
assert!(panel.shows("A") && panel.shows("B"), "the rows stay");
|
||||
|
||||
expand(&mut panel.app(), &json!({"ids": [sub.0], "open": false})).unwrap();
|
||||
let before = calls();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(calls() > before, "closing a row builds the order again");
|
||||
assert!(!panel.shows("A") && panel.shows("Sub") && panel.shows("C"), "the closed sublayer's rows are gone");
|
||||
|
||||
panel.app().ui.layers_panel.layers_only = true;
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(!panel.shows("C") && panel.shows("Sub"), "Show Layers Only leaves the objects out");
|
||||
|
||||
panel.app().ui.layers_panel.layers_only = false;
|
||||
panel.app().session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(panel.shows("Sub") && !panel.shows("C"), "isolation mode lists only the isolated sublayer");
|
||||
panel.app().session.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
expand(&mut panel.app(), &json!({"ids": [sub.0], "open": true})).unwrap();
|
||||
let made = panel.app().session.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap();
|
||||
let d = NodeId(made["id"].as_u64().unwrap());
|
||||
name_row(&mut panel.app(), d, "D");
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(panel.shows("D") && panel.shows("C"), "an edit lists the new object");
|
||||
}
|
||||
|
||||
/// The order revision stays through a selection change and moves with the document, the open rows, Show Layers Only
|
||||
/// and isolation mode.
|
||||
#[test]
|
||||
fn the_order_revision_follows_what_the_display_order_reads() {
|
||||
let order = |app: &VectorcraftApp| LayerRows::new(app, app.session.active().unwrap()).order_revision();
|
||||
let (mut app, [_, sub, g, b, a, _]) = nested();
|
||||
let first = order(&app);
|
||||
assert!(first.is_some(), "the rows report an order revision");
|
||||
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
assert_eq!(order(&app), first, "a selection change keeps it");
|
||||
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
|
||||
let isolated = order(&app);
|
||||
assert_ne!(isolated, first, "isolation mode moves it");
|
||||
app.session.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let left = order(&app);
|
||||
assert_ne!(left, isolated, "leaving isolation mode moves it");
|
||||
app.ui.layers_panel.layers_only = true;
|
||||
assert_ne!(order(&app), left, "Show Layers Only moves it");
|
||||
app.ui.layers_panel.layers_only = false;
|
||||
assert_eq!(order(&app), left, "and turning it off gives it back");
|
||||
expand(&mut app, &json!({"ids": [g.0], "open": false})).unwrap();
|
||||
let closed = order(&app);
|
||||
assert_ne!(closed, left, "closing a row moves it");
|
||||
name_row(&mut app, a, "A");
|
||||
assert_ne!(order(&app), closed, "an edit moves it");
|
||||
}
|
||||
@@ -267,6 +267,30 @@ mod tests {
|
||||
Panel::new(app, show)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrolling_a_short_docked_form_reaches_its_last_action() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.run("object.pattern.make", json!({"name": "Dots"})).unwrap();
|
||||
let mut panel = Panel::new(app, |app, ui| crate::dock::panel_body(app, ui, "patternOptions"));
|
||||
let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0));
|
||||
panel.room(viewport.size());
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let before = panel.rect("Done");
|
||||
assert!(before.center().y > viewport.bottom(), "Done starts at {before:?} in {viewport:?}");
|
||||
for _ in 0..20 {
|
||||
panel.scroll_at(egui::pos2(30.0, 30.0), -120.0);
|
||||
panel.advance(0.2);
|
||||
panel.frame();
|
||||
}
|
||||
let after = panel.rect("Done");
|
||||
assert!(viewport.contains(after.center()), "Done moved from {before:?} to {after:?} in {viewport:?}");
|
||||
panel.click("Done");
|
||||
assert!(editing(&panel.app()).is_none());
|
||||
}
|
||||
|
||||
/// Shift+Enter in the Name field renames the pattern and keeps the field active; Enter then
|
||||
/// renames it again and ends the editing.
|
||||
#[test]
|
||||
@@ -309,4 +333,44 @@ mod tests {
|
||||
assert_eq!(panel.value("Name").as_deref(), Some("Dots"));
|
||||
assert!(panel.app().session.active().unwrap().doc.pattern("Dots").is_some());
|
||||
}
|
||||
|
||||
/// The tile's width and height of the pattern "Dots".
|
||||
fn tile_size(panel: &Panel) -> (f64, f64) {
|
||||
let app = panel.app();
|
||||
let tile = &app.session.active().unwrap().doc.pattern("Dots").unwrap().tile;
|
||||
(tile.width(), tile.height())
|
||||
}
|
||||
|
||||
/// With the Width field focused, a wheel notch steps it only while the pointer is over it: over another control,
|
||||
/// or over the unfocused Height field, the wheel scrolls the panel and the tile keeps its size.
|
||||
#[test]
|
||||
fn the_wheel_steps_the_focused_number_field_only_under_the_pointer() {
|
||||
use craft::ui::contract::Role;
|
||||
let mut panel = editing_panel();
|
||||
panel.room(egui::vec2(220.0, 320.0));
|
||||
panel.frame();
|
||||
assert_eq!(tile_size(&panel), (10.0, 10.0));
|
||||
panel.click_role("Width", Role::SPIN_BUTTON);
|
||||
assert!(panel.focused("Width"), "the click focuses Width");
|
||||
|
||||
// One notch at `at`, then the frame after the wheel gesture's gap, which ends the gesture.
|
||||
let notch = |panel: &mut Panel, at: egui::Pos2| {
|
||||
panel.scroll_at(at, -30.0);
|
||||
panel.advance(1.0);
|
||||
panel.frame();
|
||||
};
|
||||
|
||||
let check = panel.rect("Size Tile to Art").center();
|
||||
notch(&mut panel, check);
|
||||
assert_eq!(tile_size(&panel), (10.0, 10.0), "a notch over Size Tile to Art leaves the focused Width alone");
|
||||
assert!(panel.focused("Width"), "Width keeps the focus");
|
||||
|
||||
let height = panel.rect_role("Height", Role::SPIN_BUTTON).center();
|
||||
notch(&mut panel, height);
|
||||
assert_eq!(tile_size(&panel), (10.0, 10.0), "a notch over the unfocused Height steps neither field");
|
||||
|
||||
let width = panel.rect_role("Width", Role::SPIN_BUTTON).center();
|
||||
notch(&mut panel, width);
|
||||
assert_eq!(tile_size(&panel), (9.0, 10.0), "a notch over the focused Width steps it");
|
||||
}
|
||||
}
|
||||
@@ -291,8 +291,9 @@ fn can_merge_live_paint(app: &VectorcraftApp) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the selection uses more than one colour (`recolor.colors`), which offers the Recolor
|
||||
/// quick action; memoised per document revision.
|
||||
/// Whether the selection uses more than one colour (`recolor.colors` lists more than one,
|
||||
/// [`vectorcraft_engine::Session::several_colors_used`]), which offers the Recolor quick action;
|
||||
/// memoised per document revision.
|
||||
pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool {
|
||||
let Some(st) = app.session.active() else { return false };
|
||||
let key = (st.uid, st.revision);
|
||||
@@ -301,8 +302,7 @@ pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool {
|
||||
{
|
||||
return multi;
|
||||
}
|
||||
let r = app.session.execute("recolor.colors", &json!({})).unwrap_or_default();
|
||||
let multi = r["colors"].as_array().is_some_and(|c| c.len() > 1);
|
||||
let multi = app.session.several_colors_used();
|
||||
app.canvas.multi_color = Some((key, multi));
|
||||
multi
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! The Properties panel's Document sections, shown with nothing selected.
|
||||
|
||||
use craft::behavior::IconId;
|
||||
use craft::behavior::{EditEvent, IconId};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::buttons::{Button, ToggleButton};
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft::ui::contract::{Bind, Entry, MemoProps, MemoView, Outbox, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::{Grid, Row};
|
||||
use craft::ui::pickers::Select;
|
||||
@@ -17,84 +17,215 @@ use vectorcraft_doc::Unit;
|
||||
use super::artboard_sections::rearrange_button;
|
||||
use super::object_sections::HALVES;
|
||||
use crate::VectorcraftApp;
|
||||
use crate::edits::EditPath;
|
||||
use crate::panels::transform;
|
||||
|
||||
/// The panel with nothing selected: the document's units, Document Setup and artboards, the
|
||||
/// Appearance fill and stroke, the view's rulers, grids, guides and snapping, the keyboard
|
||||
/// increment and Scale Strokes & Effects, and Quick Actions.
|
||||
///
|
||||
/// The body of every section but Appearance shows in a `MemoView` keyed on what it reads, so a
|
||||
/// frame that changes none of it replays the body. What a body picks comes back through an `Outbox`
|
||||
/// and runs after its section.
|
||||
pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let lang = crate::i18n::current();
|
||||
let units = app.session.general_unit();
|
||||
let unit = Unit::ALL.iter().position(|u| *u == units).unwrap_or(usize::MAX);
|
||||
let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let mut picked_units = Vec::new();
|
||||
super::section(tl!("Document")).show(ui, |ui, _| {
|
||||
Field::new(tl!("Units")).show(ui, |ui, _| {
|
||||
let entries: Vec<Entry<Unit>> = Unit::ALL.iter().map(|u| Entry::new(*u, u.label())).collect();
|
||||
let out = Select::new(tl!("Units"), Bind::given(units), &entries).show(ui);
|
||||
if let Some(u) = out.events.committed() {
|
||||
app.run("document.setUnits", json!({ "units": u.label() })).ok();
|
||||
}
|
||||
});
|
||||
Grid::new(&HALVES).show(ui, |ui, _| {
|
||||
Button::command(CommandRef::new("file.documentSetup")).label(tl!("Document Setup")).sizing(Sizing::FillWidth).show(ui);
|
||||
Button::command(CommandRef::with_params("tool.select", json!({ "tool": "artboard" })))
|
||||
.label(tl!("Edit Artboards"))
|
||||
.sizing(Sizing::FillWidth)
|
||||
.show(ui);
|
||||
if artboards > 1 {
|
||||
rearrange_button(ui, artboards);
|
||||
}
|
||||
});
|
||||
let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) };
|
||||
let _ = MemoView::new("properties-document", document, document_body).show(ui);
|
||||
});
|
||||
if let Some(u) = picked_units.pop() {
|
||||
app.run("document.setUnits", json!({ "units": u.label() })).ok();
|
||||
}
|
||||
super::section(tl!("Appearance")).show(ui, |ui, _| super::appearance_section::fill_stroke_rows(app, ui));
|
||||
super::section(tl!("Rulers & Grids")).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
// The checked and enabled states and the tooltips come from the commands (Trim View turns the grid off).
|
||||
for (command, icon) in [("view.rulers", "ruler"), ("view.grid", "grid-3x3"), ("view.transparencyGrid", "square-dashed")] {
|
||||
ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui);
|
||||
}
|
||||
});
|
||||
let _ = MemoView::new("properties-rulers", Language { lang }, rulers_body).show(ui);
|
||||
});
|
||||
super::section(tl!("Guides")).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
for (command, icon) in [("view.guides", "layout-grid"), ("view.smartGuides", "sparkles")] {
|
||||
ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui);
|
||||
}
|
||||
});
|
||||
let _ = MemoView::new("properties-guides", Language { lang }, guides_body).show(ui);
|
||||
});
|
||||
let mut snaps = Vec::new();
|
||||
let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid);
|
||||
super::section(tl!("Snap Options")).show(ui, |ui, _| {
|
||||
let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid);
|
||||
for (command, label, on) in [("view.snapToPoint", tl!("Snap to Point"), point), ("view.snapToGrid", tl!("Snap to Grid"), grid)] {
|
||||
if Checkbox::new(Bind::given(on)).label(label).show(ui).value().is_some() {
|
||||
app.run(command, json!({})).ok();
|
||||
}
|
||||
}
|
||||
let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) };
|
||||
let _ = MemoView::new("properties-snap", snap, snap_body).show(ui);
|
||||
});
|
||||
for command in snaps {
|
||||
app.run(command, json!({})).ok();
|
||||
}
|
||||
let mut prefs = Vec::new();
|
||||
// Read again after the Units commit above, so the key and `lengths` come from the same General unit.
|
||||
let general = app.session.general_unit();
|
||||
let unit = Unit::ALL.iter().position(|u| *u == general).unwrap_or(usize::MAX);
|
||||
let (increment, scale) = (app.session.prefs.keyboard_increment, app.session.prefs.scale_strokes);
|
||||
let (bare_points, lengths) = (app.session.prefs.numbers_without_units_are_points, crate::canvas::rulers::general_lengths(app));
|
||||
super::section(tl!("Preferences")).show(ui, |ui, _| {
|
||||
Field::new(tl!("Keyboard Increment")).show(ui, |ui, _| {
|
||||
// PLAN: assumed `canvas::rulers::general_lengths(app) -> LengthUnits` (cv.B5b)
|
||||
let lengths: LengthUnits = crate::canvas::rulers::general_lengths(app);
|
||||
// The engine's own range for the preference (`prefscmds.rs`): a larger value is an error.
|
||||
let out = NumberField::length(tl!("Keyboard Increment"), Bind::given(Some(app.session.prefs.keyboard_increment)), lengths)
|
||||
.range(0.001..=1296.0)
|
||||
.show(ui);
|
||||
crate::edits::apply_edits(app, &out.edit, crate::edits::EditPath::Scope, |app, v: &Option<f64>, _| {
|
||||
if let Some(value) = *v {
|
||||
app.run("prefs.set", json!({ "key": "keyboardIncrement", "value": value })).ok();
|
||||
}
|
||||
});
|
||||
});
|
||||
let scale = app.session.prefs.scale_strokes;
|
||||
let out = Checkbox::new(Bind::given(scale)).label(tl!("Scale Strokes & Effects")).show(ui);
|
||||
if let Some(on) = out.value().copied() {
|
||||
transform::set_pref(app, "scaleStrokes", on);
|
||||
let picked = Outbox::new(&mut prefs);
|
||||
let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked };
|
||||
let _ = MemoView::new("properties-preferences", preferences, preferences_body).show(ui);
|
||||
});
|
||||
for pick in prefs {
|
||||
match pick {
|
||||
PreferencePick::Increment(event) => {
|
||||
crate::edits::apply_event(app, &event, &EditPath::Scope, &mut |app, v: &Option<f64>, _| {
|
||||
if let Some(value) = *v {
|
||||
app.run("prefs.set", json!({ "key": "keyboardIncrement", "value": value })).ok();
|
||||
}
|
||||
});
|
||||
}
|
||||
PreferencePick::ScaleStrokes(on) => transform::set_pref(app, "scaleStrokes", on),
|
||||
}
|
||||
}
|
||||
super::section(tl!("Quick Actions")).show(ui, |ui, _| {
|
||||
let _ = MemoView::new("properties-quick-actions", Language { lang }, quick_actions_body).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// What a section that reads only command states reads besides them: the interface language of its labels.
|
||||
#[derive(MemoProps)]
|
||||
struct Language {
|
||||
#[memo_props(hash = "an interface language: an index into the languages offered")]
|
||||
lang: crate::i18n::Lang,
|
||||
}
|
||||
|
||||
/// What the Document section reads: the document's units and how many artboards it has.
|
||||
#[derive(MemoProps)]
|
||||
struct DocumentProps<'a> {
|
||||
/// The index of `units` in [`Unit::ALL`].
|
||||
unit: usize,
|
||||
#[memo_props(covered_by = "unit", reason = "the unit's index in Unit::ALL")]
|
||||
units: Unit,
|
||||
/// How many artboards the document has (Rearrange All shows for more than one).
|
||||
artboards: usize,
|
||||
#[memo_props(hash = "an interface language: an index into the languages offered")]
|
||||
lang: crate::i18n::Lang,
|
||||
/// The units chosen in the Units menu.
|
||||
picked: Outbox<'a, Unit>,
|
||||
}
|
||||
|
||||
/// The Document section's body: Units, Document Setup, Edit Artboards and Rearrange All.
|
||||
fn document_body(p: &mut DocumentProps<'_>, ui: &mut Ui) {
|
||||
#[cfg(test)]
|
||||
tests::count_run();
|
||||
Field::new(tl!("Units")).show(ui, |ui, _| {
|
||||
let entries: Vec<Entry<Unit>> = Unit::ALL.iter().map(|u| Entry::new(*u, u.label())).collect();
|
||||
let out = Select::new(tl!("Units"), Bind::given(p.units), &entries).show(ui);
|
||||
if let Some(u) = out.events.committed() {
|
||||
p.picked.send(*u);
|
||||
}
|
||||
});
|
||||
super::section(tl!("Quick Actions")).show(ui, |ui, _| {
|
||||
Grid::new(&HALVES).show(ui, |ui, _| {
|
||||
// The reference panel's buttons name the dialog without the menu's ellipsis.
|
||||
for (command, label) in [("file.documentSetup", tl!("Document Setup")), ("edit.preferences", tl!("Preferences"))] {
|
||||
Button::command(CommandRef::new(command)).label(label).sizing(Sizing::FillWidth).show(ui);
|
||||
}
|
||||
});
|
||||
Grid::new(&HALVES).show(ui, |ui, _| {
|
||||
Button::command(CommandRef::new("file.documentSetup")).label(tl!("Document Setup")).sizing(Sizing::FillWidth).show(ui);
|
||||
Button::command(CommandRef::with_params("tool.select", json!({ "tool": "artboard" })))
|
||||
.label(tl!("Edit Artboards"))
|
||||
.sizing(Sizing::FillWidth)
|
||||
.show(ui);
|
||||
if p.artboards > 1 {
|
||||
rearrange_button(ui, p.artboards);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The Rulers & Grids section's body. The checked and enabled states and the tooltips come from the commands (Trim
|
||||
/// View turns the grid off).
|
||||
fn rulers_body(_: &mut Language, ui: &mut Ui) {
|
||||
#[cfg(test)]
|
||||
tests::count_run();
|
||||
Row::new().show(ui, |ui, _| {
|
||||
for (command, icon) in [("view.rulers", "ruler"), ("view.grid", "grid-3x3"), ("view.transparencyGrid", "square-dashed")] {
|
||||
ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The Guides section's body: Show Guides and Smart Guides, from their commands.
|
||||
fn guides_body(_: &mut Language, ui: &mut Ui) {
|
||||
#[cfg(test)]
|
||||
tests::count_run();
|
||||
Row::new().show(ui, |ui, _| {
|
||||
for (command, icon) in [("view.guides", "layout-grid"), ("view.smartGuides", "sparkles")] {
|
||||
ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// What the Snap Options section reads: whether Snap to Point and Snap to Grid are on.
|
||||
#[derive(MemoProps)]
|
||||
struct SnapProps<'a> {
|
||||
point: bool,
|
||||
grid: bool,
|
||||
#[memo_props(hash = "an interface language: an index into the languages offered")]
|
||||
lang: crate::i18n::Lang,
|
||||
/// The command of each checkbox clicked.
|
||||
picked: Outbox<'a, &'static str>,
|
||||
}
|
||||
|
||||
/// The Snap Options section's body: Snap to Point and Snap to Grid.
|
||||
fn snap_body(p: &mut SnapProps<'_>, ui: &mut Ui) {
|
||||
#[cfg(test)]
|
||||
tests::count_run();
|
||||
for (command, label, on) in [("view.snapToPoint", tl!("Snap to Point"), p.point), ("view.snapToGrid", tl!("Snap to Grid"), p.grid)] {
|
||||
if Checkbox::new(Bind::given(on)).label(label).show(ui).value().is_some() {
|
||||
p.picked.send(command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Preferences section reads: the keyboard increment in the General unit, and Scale Strokes & Effects.
|
||||
#[derive(MemoProps)]
|
||||
struct PreferencesProps<'a> {
|
||||
/// The keyboard increment, in points.
|
||||
increment: f64,
|
||||
/// The index of the General unit in [`Unit::ALL`].
|
||||
unit: usize,
|
||||
/// Numbers without units are points (Preferences › Units).
|
||||
bare_points: bool,
|
||||
#[memo_props(covered_by = "unit", reason = "made from the General unit and bare_points alone (canvas::rulers::lengths)")]
|
||||
lengths: LengthUnits,
|
||||
/// Scale Strokes & Effects is on.
|
||||
scale: bool,
|
||||
#[memo_props(hash = "an interface language: an index into the languages offered")]
|
||||
lang: crate::i18n::Lang,
|
||||
/// The keyboard increment's edits and the Scale Strokes & Effects choice.
|
||||
picked: Outbox<'a, PreferencePick>,
|
||||
}
|
||||
|
||||
/// What the Preferences section reports: an edit of the keyboard increment, or Scale Strokes & Effects turned on or
|
||||
/// off.
|
||||
enum PreferencePick {
|
||||
Increment(EditEvent<Option<f64>>),
|
||||
ScaleStrokes(bool),
|
||||
}
|
||||
|
||||
/// The Preferences section's body: Keyboard Increment and Scale Strokes & Effects.
|
||||
fn preferences_body(p: &mut PreferencesProps<'_>, ui: &mut Ui) {
|
||||
#[cfg(test)]
|
||||
tests::count_run();
|
||||
Field::new(tl!("Keyboard Increment")).show(ui, |ui, _| {
|
||||
// The engine's own range for the preference (`prefscmds.rs`): a larger value is an error.
|
||||
let out = NumberField::length(tl!("Keyboard Increment"), Bind::given(Some(p.increment)), p.lengths).range(0.001..=1296.0).show(ui);
|
||||
for event in out.edit.events.iter() {
|
||||
p.picked.send(PreferencePick::Increment(event.clone()));
|
||||
}
|
||||
});
|
||||
let out = Checkbox::new(Bind::given(p.scale)).label(tl!("Scale Strokes & Effects")).show(ui);
|
||||
if let Some(on) = out.value().copied() {
|
||||
p.picked.send(PreferencePick::ScaleStrokes(on));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Quick Actions section's body: Document Setup and Preferences. The reference panel's buttons name the dialog
|
||||
/// without the menu's ellipsis.
|
||||
fn quick_actions_body(_: &mut Language, ui: &mut Ui) {
|
||||
#[cfg(test)]
|
||||
tests::count_run();
|
||||
Grid::new(&HALVES).show(ui, |ui, _| {
|
||||
for (command, label) in [("file.documentSetup", tl!("Document Setup")), ("edit.preferences", tl!("Preferences"))] {
|
||||
Button::command(CommandRef::new(command)).label(label).sizing(Sizing::FillWidth).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -104,6 +235,19 @@ mod tests {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
thread_local! {
|
||||
/// How many times this thread ran a memoized Document section.
|
||||
static SECTION_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
pub(super) fn count_run() {
|
||||
SECTION_RUNS.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
|
||||
fn runs() -> u64 {
|
||||
SECTION_RUNS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canceling_the_units_popup_leaves_the_document_unchanged() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
@@ -135,4 +279,79 @@ mod tests {
|
||||
assert_eq!(panel.app().session.active().unwrap().doc.units, next, "Enter applies the chosen document unit");
|
||||
assert_eq!(panel.app().session.general_unit(), next);
|
||||
}
|
||||
|
||||
/// Frames that change nothing the sections show replay them instead of laying them out again. A change one of
|
||||
/// them reads, from a command run elsewhere, runs it again, and it shows the change.
|
||||
#[test]
|
||||
fn idle_frames_replay_the_document_sections() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
let mut panel = Panel::new(app, document_sections);
|
||||
panel.room(egui::vec2(400.0, 1000.0));
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let before = runs();
|
||||
for _ in 0..10 {
|
||||
panel.frame();
|
||||
}
|
||||
assert_eq!(runs() - before, 0, "idle frames run the memoized sections no more");
|
||||
let point = panel.app().ui.view.snap_to_point;
|
||||
panel.app().run("view.snapToPoint", json!({})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(runs() > before, "a new snap setting runs the sections again");
|
||||
assert_eq!(panel.app().ui.view.snap_to_point, !point);
|
||||
assert_eq!(panel.toggled("Snap to Point"), Some(craft::behavior::Mixed::Same(!point)), "and the checkbox shows it");
|
||||
panel.app().run("view.rulers", json!({})).unwrap();
|
||||
let mut per_frame = Vec::new();
|
||||
for _ in 0..12 {
|
||||
let at = runs();
|
||||
panel.frame();
|
||||
per_frame.push(runs() - at);
|
||||
}
|
||||
// A toggled button animates over the next frames, and a section runs while an animation in it has not ended.
|
||||
assert_eq!(per_frame[6..], [0; 6], "idle frames after a command run them no more: {per_frame:?}");
|
||||
}
|
||||
|
||||
/// The frame that picks new units in the Units menu shows the Keyboard Increment in them: the Preferences
|
||||
/// section's key reads the General unit after the pick runs, as its lengths do.
|
||||
#[test]
|
||||
fn the_frame_that_picks_units_shows_the_increment_in_them() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
let initial = app.session.general_unit();
|
||||
let mut panel = Panel::new(app, document_sections);
|
||||
panel.room(egui::vec2(400.0, 1000.0));
|
||||
panel.frame();
|
||||
let before = panel.value("Keyboard Increment");
|
||||
panel.click_role("Units", Role::COMBO_BOX);
|
||||
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
let enter =
|
||||
|pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
panel.frame_with(vec![enter(true), enter(false)]);
|
||||
assert_ne!(panel.app().session.general_unit(), initial, "Enter applies the chosen unit");
|
||||
let picked = panel.value("Keyboard Increment");
|
||||
panel.frame();
|
||||
let settled = panel.value("Keyboard Increment");
|
||||
assert_ne!(settled, before, "the increment shows in the new unit");
|
||||
assert_eq!(picked, settled, "the frame of the pick already shows the increment in the new unit");
|
||||
}
|
||||
|
||||
/// The memoized sections still take input: a click on Snap to Grid turns it on, once, and Scale Strokes & Effects
|
||||
/// sets its preference.
|
||||
#[test]
|
||||
fn the_memoized_sections_run_their_picks() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
let grid = app.ui.view.snap_to_grid;
|
||||
let scale = app.session.prefs.scale_strokes;
|
||||
let mut panel = Panel::new(app, document_sections);
|
||||
panel.room(egui::vec2(400.0, 1000.0));
|
||||
panel.frame();
|
||||
panel.click("Snap to Grid");
|
||||
assert_eq!(panel.app().ui.view.snap_to_grid, !grid, "the click toggles Snap to Grid once");
|
||||
panel.click("Scale Strokes & Effects");
|
||||
assert_eq!(panel.app().session.prefs.scale_strokes, !scale);
|
||||
}
|
||||
}
|
||||
@@ -421,6 +421,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let lit: Vec<String> = highlighted(&st.doc, &base).into_iter().map(str::to_string).collect();
|
||||
let doc = Arc::clone(&st.doc);
|
||||
let start = dnd::DragStart::of(st);
|
||||
// The row menu, the drop rules and the drag payload read the document, its reverts and the drag start alone, so
|
||||
// the browser's rows replay while this version holds.
|
||||
let host = start.version(st.revision);
|
||||
let document = st.uid;
|
||||
let reverts = st.reverts;
|
||||
let foot = Footer::of(app, &model, held);
|
||||
@@ -448,6 +451,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
.row_items(|key| row_items(shown_app, key))
|
||||
.takes_drop::<PanelDrag>(DropPlace::Between, |drag, _| dnd::accepts(drag, document, reverts))
|
||||
.takes_drop::<PanelDrag>(DropPlace::Onto, |drag, _| dnd::accepts(drag, document, reverts))
|
||||
.host_version(host)
|
||||
.select(SelectMode::Multi)
|
||||
.search(search)
|
||||
.reveal(focus.clone().map(SwatchKey::Swatch))
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use super::{Document, Paint, PanelDrag, REGISTRATION, Swatch, Value, VectorcraftApp, json, name_of, swatch_params};
|
||||
@@ -126,6 +127,15 @@ impl DragStart {
|
||||
DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), steps: steps(st), back }
|
||||
}
|
||||
|
||||
/// A version of this start in the document's `revision` ([`DocState::revision`]): it changes with
|
||||
/// the document, its count of File › Revert and its newest undo and redo steps, which are what the
|
||||
/// panel's row menu, drop rules and drag payload read.
|
||||
pub(super) fn version(&self, revision: u64) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
(self.uid, self.reverts, revision, self.steps).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Rows `names` as this document holds them.
|
||||
fn rows(&self, names: &[String]) -> HeldRows {
|
||||
let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, n))).collect();
|
||||
|
||||
@@ -1623,3 +1623,35 @@ fn the_swatch_libraries_menu_fits_its_rows_like_a_library_panels_menu() {
|
||||
let panel_menu = panel.rect_role("Swatch Libraries Menu", Role::MENU);
|
||||
assert_eq!(footer_menu.width(), panel_menu.width(), "footer menu {footer_menu:?}, library panel menu {panel_menu:?}");
|
||||
}
|
||||
|
||||
/// Frames that change nothing replay the swatch rows instead of running them again; deleting a swatch and undoing it
|
||||
/// each run them, the rows show the change, and the frames after replay them again.
|
||||
#[test]
|
||||
fn idle_frames_replay_the_swatch_rows() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::testing::{MemoRun, last_frame_memo_runs};
|
||||
let runs =
|
||||
|panel: &Panel| last_frame_memo_runs(panel.ctx()).iter().filter(|(name, _, run)| name.contains("ListProps") && *run == MemoRun::Ran).count();
|
||||
let idle = |panel: &mut Panel, after: &str| {
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
for _ in 0..5 {
|
||||
panel.frame();
|
||||
assert_eq!(runs(panel), 0, "an idle frame {after} replays the swatch rows");
|
||||
}
|
||||
};
|
||||
let red = "Red, #ed1c24";
|
||||
let mut panel = Panel::new(app(), show);
|
||||
idle(&mut panel, "of a new document");
|
||||
assert!(panel.shows(red), "the rows show Red");
|
||||
panel.app().run("swatch.delete", json!({"names": ["Red"]})).unwrap();
|
||||
panel.frame();
|
||||
assert!(runs(&panel) > 0, "deleting a swatch runs the rows");
|
||||
assert!(!panel.shows(red), "and they no longer show it");
|
||||
idle(&mut panel, "after a delete");
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
panel.frame();
|
||||
assert!(runs(&panel) > 0, "an undo runs the rows");
|
||||
assert!(panel.shows(red), "and they show the swatch again");
|
||||
idle(&mut panel, "after an undo");
|
||||
}
|
||||
@@ -1016,6 +1016,42 @@ fn the_scale_row_fits_the_panel_width() {
|
||||
}
|
||||
}
|
||||
|
||||
/// In a short panel with many format rows, the Export Settings heading and the first row stay inside the panel, and
|
||||
/// the settings scroll above Export and the footer bar.
|
||||
#[test]
|
||||
fn the_settings_scroll_inside_a_short_panel() {
|
||||
use craft::ui::contract::Role;
|
||||
let (mut app, _, [a, _]) = app(true);
|
||||
app.run("assets.add", json!({"ids": [a]})).unwrap();
|
||||
let mut p = panel(app);
|
||||
p.room(egui::vec2(300.0, 1600.0));
|
||||
p.frame();
|
||||
for _ in 0..7 {
|
||||
p.click("+ Add Scale");
|
||||
}
|
||||
assert_eq!(settings(&p)["formats"].as_array().unwrap().len(), 8);
|
||||
p.room(egui::vec2(300.0, 280.0));
|
||||
p.frame();
|
||||
p.frame();
|
||||
let heading = p.painted("Export Settings");
|
||||
assert!(!heading.is_empty(), "the Export Settings heading is painted");
|
||||
for rect in heading {
|
||||
assert!(rect.top() >= -0.5 && rect.bottom() <= 280.5, "the Export Settings heading at {rect:?} is outside a 280 pt panel");
|
||||
}
|
||||
let scale = p.rect_role("Scale", Role::COMBO_BOX);
|
||||
assert!(p.in_view("Scale") && scale.top() >= -0.5, "the first format row at {scale:?} is outside the panel");
|
||||
let export = p.rect("Export");
|
||||
assert!(export.top() >= -0.5 && export.bottom() <= 280.5, "Export at {export:?} is outside a 280 pt panel");
|
||||
// The wheel over the settings brings the last row's Add Scale into view, and Export stays where it was.
|
||||
for _ in 0..20 {
|
||||
p.scroll_at(scale.center(), -120.0);
|
||||
p.frame();
|
||||
}
|
||||
let add = p.rect("+ Add Scale");
|
||||
assert!(p.in_view("+ Add Scale") && add.bottom() <= 280.5, "Add Scale at {add:?} is not reachable");
|
||||
assert_eq!(p.rect("Export"), export, "Export moved while the settings scrolled");
|
||||
}
|
||||
|
||||
/// The menu adds the selected artwork as one asset or one per object (an object that is an asset already keeps its
|
||||
/// asset), and is off with no artwork selected.
|
||||
#[test]
|
||||
|
||||
@@ -380,11 +380,13 @@ fn mask_items(mask: Option<&OpacityMask>, can_make: bool) -> [(&'static str, &'s
|
||||
}
|
||||
|
||||
/// The masked object's mask, also while editing it (the selection then is the mask art), whether the
|
||||
/// object controls apply, and whether Make is possible.
|
||||
/// object controls apply, and whether Make is possible. Make's check runs only for an object without a mask, the one
|
||||
/// case whose rows read it ([`mask_items`]).
|
||||
fn menu_context(app: &VectorcraftApp) -> (Option<Arc<Node>>, bool, bool) {
|
||||
let editing = app.session.active().is_some_and(|d| d.doc.mask_edit.is_some());
|
||||
let n = first_node(app, &app.session.transparency_info());
|
||||
let can_make = n.is_some() && !editing && crate::menus::enabled(app, "transparency.makeOpacityMask");
|
||||
let n = app.session.transparency_target().and_then(|id| super::layers::node_arc(&app.session.active()?.doc, id));
|
||||
let unmasked = n.as_ref().is_some_and(|n| n.extras().mask.is_none());
|
||||
let can_make = unmasked && !editing && crate::menus::enabled(app, "transparency.makeOpacityMask");
|
||||
(n, object_controls(app, editing), can_make)
|
||||
}
|
||||
|
||||
@@ -452,6 +454,30 @@ mod tests {
|
||||
app
|
||||
}
|
||||
|
||||
/// The menu's states check Make Opacity Mask only for a first object without a mask: a masked one shows Release,
|
||||
/// Disable and Unlink instead, and Make dimmed without its check.
|
||||
#[test]
|
||||
fn the_menu_checks_make_only_for_an_object_without_a_mask() {
|
||||
let mut app = new_app();
|
||||
let rectangle = |app: &mut VectorcraftApp, x| run_cmd(app, "shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20}));
|
||||
let masked = rectangle(&mut app, 10)["id"].clone();
|
||||
let art = rectangle(&mut app, 12)["id"].clone();
|
||||
let plain = rectangle(&mut app, 50)["id"].clone();
|
||||
run_cmd(&mut app, "transparency.makeOpacityMask", json!({"ids": [masked, art]}));
|
||||
// How many times the states asked for Make's check, and whether Make is enabled.
|
||||
let asked = |app: &VectorcraftApp| {
|
||||
let mut states = CommandStates::new();
|
||||
crate::menus::WHY_OFF_ASKED.with_borrow_mut(Vec::clear);
|
||||
menu_states(app, &mut states);
|
||||
let make = crate::menus::WHY_OFF_ASKED.take().iter().filter(|a| *a == "transparency.makeOpacityMask").count();
|
||||
(make, states.get(&CommandRef::new("transparency.makeOpacityMask")).is_some_and(CommandState::is_enabled))
|
||||
};
|
||||
run_cmd(&mut app, "select.set", json!({"ids": [masked]}));
|
||||
assert_eq!(asked(&app), (0, false), "a masked object: Make is dimmed without its check");
|
||||
run_cmd(&mut app, "select.set", json!({"ids": [plain]}));
|
||||
assert_eq!(asked(&app), (1, true), "an object without a mask: Make's check runs once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_shows_each_selected_symbol_parts_values() {
|
||||
let mut app = new_app();
|
||||
|
||||
@@ -490,6 +490,15 @@ pub struct ContextSpelling {
|
||||
pub suggestions: Vec<String>,
|
||||
}
|
||||
|
||||
/// The main window as saved in the UI preferences through 0.24.1. Positions are desktop pixels.
|
||||
#[derive(Clone, Copy, Debug, Deserialize)]
|
||||
pub struct LegacyWindow {
|
||||
pub pos: Option<[i32; 2]>,
|
||||
pub size: [f32; 2],
|
||||
#[serde(default)]
|
||||
pub maximized: bool,
|
||||
}
|
||||
|
||||
/// Two states are equal when they save the same: the settings store writes only a changed saved form,
|
||||
/// and the panels' session state is no change to save.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -500,6 +509,9 @@ pub struct UiState {
|
||||
/// it is never written back.
|
||||
#[serde(rename = "language", skip_serializing)]
|
||||
pub legacy_language: Option<String>,
|
||||
/// Used until the shared window store has recorded the main window.
|
||||
#[serde(rename = "window", skip_serializing)]
|
||||
pub legacy_window: Option<LegacyWindow>,
|
||||
pub brightness: Brightness,
|
||||
/// The panel arrangement: docks, floating windows, closed panels and where each goes back. One
|
||||
/// `Arc` the dock area keeps across frames; writers change it through `Arc::make_mut`.
|
||||
@@ -1448,6 +1460,7 @@ impl Default for UiState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
legacy_language: None,
|
||||
legacy_window: None,
|
||||
brightness: Brightness::MediumDark,
|
||||
dock_workspace: std::sync::Arc::new(crate::panel_docking::default_workspace(&[])),
|
||||
tools_last_used: Default::default(),
|
||||
|
||||
@@ -86,6 +86,11 @@ fn preview_changes_the_text_live_and_only_a_choice_is_a_step() {
|
||||
let before = steps(&app);
|
||||
apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into()));
|
||||
assert_eq!(font_of(&app, id), "Source Serif 4", "previewed on the text");
|
||||
assert_eq!(
|
||||
crate::panels::character::values(&mut app).family.as_deref(),
|
||||
Some("Inter"),
|
||||
"the picker must still be able to commit the previewed row"
|
||||
);
|
||||
apply_preview(&mut app, owner(), Preview::Shows("Source Sans 3".into()));
|
||||
assert_eq!(font_of(&app, id), "Source Sans 3");
|
||||
apply_preview(&mut app, owner(), Preview::Ended);
|
||||
|
||||
@@ -355,10 +355,11 @@ fn a_control_port_cancel_of_a_dialog_preview_reads_the_menus() {
|
||||
}
|
||||
|
||||
/// OK applies the rotation a dialog previews as one undo step: the menus are read then, with Undo
|
||||
/// naming it, and not for the angles previewed before.
|
||||
/// naming it, and not for the angles previewed before. Once the dialog's angle field no longer takes
|
||||
/// the keys, the menus are sent once more without the text-editing gate.
|
||||
#[test]
|
||||
fn applying_a_dialog_preview_reads_the_menus() {
|
||||
let (m, (read, synced, closed, after)) = undisturbed(|m| {
|
||||
let (m, (read, synced, applied, closed, after)) = undisturbed(|m| {
|
||||
m.rotate_preview();
|
||||
let read = m.angles(4);
|
||||
let synced = m.fake.synced();
|
||||
@@ -367,12 +368,21 @@ fn applying_a_dialog_preview_reads_the_menus() {
|
||||
// gone two frames later.
|
||||
m.frame(vec![]);
|
||||
m.frame(vec![]);
|
||||
let applied = m.fake.synced();
|
||||
// The frame after the field gives up the keys sets the gate.
|
||||
for _ in 0..4 {
|
||||
if !m.ctx.egui_wants_keyboard_input() {
|
||||
break;
|
||||
}
|
||||
m.frame(vec![]);
|
||||
}
|
||||
m.frame(vec![]);
|
||||
(read, synced, !m.app.session.in_interaction() && !m.app.any_dialog_open(), m.fake.synced())
|
||||
(read, synced, applied, !m.app.session.in_interaction() && !m.app.any_dialog_open(), m.fake.synced())
|
||||
});
|
||||
assert_eq!(read, 0, "the menus weren't read while the dialog previewed the angles");
|
||||
assert!(closed);
|
||||
assert_eq!(after, synced + 1, "the menus were read");
|
||||
assert_eq!(applied, synced + 1, "the menus were read");
|
||||
assert_eq!(after, synced + 2, "and sent once more when the gate changed");
|
||||
assert_eq!(find(&m.fake.last(), "edit.undo").label, "Undo Rotate");
|
||||
}
|
||||
|
||||
@@ -448,3 +458,24 @@ fn a_key_equivalent_paste_pastes_a_picture_from_another_app() {
|
||||
assert_eq!(images(&m), n, "press {n} pastes one picture");
|
||||
}
|
||||
}
|
||||
|
||||
/// AppKit handles a menu shortcut's key-down before winit delivers the matching key-up.
|
||||
/// The two must reach the same input batch, even if this frame can have only one pass.
|
||||
#[test]
|
||||
fn a_native_undo_and_redo_key_equivalent_each_change_the_canvas_once() {
|
||||
let mut m = Mac::new(true);
|
||||
m.ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::MIN);
|
||||
let id = m.app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
let id = vectorcraft_doc::NodeId(id);
|
||||
m.frame(vec![]);
|
||||
for (chord, shift, present) in [("Cmd+Z", false, false), ("Cmd+Shift+Z", true, true)] {
|
||||
let mut modifiers = if crate::keymap::platform().is_mac() { Modifiers::MAC_CMD } else { Modifiers::CTRL };
|
||||
modifiers.command = true;
|
||||
modifiers.shift = shift;
|
||||
m.fake.report(MenuEvent::Key(Chord::parse(chord).unwrap()));
|
||||
m.frame(vec![Event::Key { key: Key::Z, physical_key: Some(Key::Z), pressed: false, repeat: false, modifiers }]);
|
||||
assert_eq!(m.app.session.active().unwrap().doc.node(id).is_some(), present, "{chord} with the native key-up");
|
||||
m.frame(vec![]);
|
||||
assert_eq!(m.app.session.active().unwrap().doc.node(id).is_some(), present, "{chord} was applied once");
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,12 @@ impl Panel {
|
||||
self.aim(name, target)
|
||||
}
|
||||
|
||||
/// Moves the pointer over `name` without pressing a button.
|
||||
pub(crate) fn hover(&mut self, name: &str) {
|
||||
let at = self.find_aimed(name).center();
|
||||
self.frame_with(vec![Event::PointerMoved(at)]);
|
||||
}
|
||||
|
||||
/// Clicks the control named `name`.
|
||||
pub(crate) fn click(&mut self, name: &str) {
|
||||
let target = self.find_aimed(name);
|
||||
|
||||
@@ -181,7 +181,9 @@ fn plugins_are_listed_in_the_object_and_effect_menus() {
|
||||
|
||||
#[test]
|
||||
fn filter_dialog_previews_and_commits_one_undo_step() {
|
||||
let mut h = window(app());
|
||||
let mut app = app();
|
||||
app.canvas.worker_started = true; // Canvas uploads finish within the frame being asserted.
|
||||
let mut h = window(app);
|
||||
h.state_mut().run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(DESATURATE)})).unwrap();
|
||||
let id = red_rect(h.state_mut());
|
||||
let undo = h.state().session.doc().unwrap().history.undo.len();
|
||||
@@ -189,12 +191,36 @@ fn filter_dialog_previews_and_commits_one_undo_step() {
|
||||
step(&mut h);
|
||||
assert!(top(h.state()).is_some(), "dialog open");
|
||||
assert_eq!(fields(h.state())["amount"], json!(100.0));
|
||||
// A click in the visible slider must reach the same values the live preview reads.
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
// Let the modal finish its opening placement before reading a widget's screen bounds.
|
||||
for _ in 0..3 {
|
||||
step(&mut h);
|
||||
}
|
||||
let at = h.get_by_role(egui::accesskit::Role::Dialog).get_by_role(egui::accesskit::Role::Slider).rect().center();
|
||||
h.input_mut().events.push(egui::Event::PointerMoved(at));
|
||||
step(&mut h);
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(egui::Event::PointerButton {
|
||||
pos: at,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
});
|
||||
step(&mut h);
|
||||
}
|
||||
let clicked = fields(h.state());
|
||||
assert!(clicked["amount"].as_f64().is_some_and(|amount| amount > 0.0 && amount < 100.0), "slider at {at:?}: {clicked}");
|
||||
// Agents set fields like `ui.dialog.set` does; the frame previews them.
|
||||
set_field(&mut h, "amount", json!(50)).unwrap();
|
||||
step(&mut h);
|
||||
assert!(h.state().session.in_interaction(), "previewing");
|
||||
let [r, g, _] = fill_rgb(h.state(), id);
|
||||
assert!(r < 1.0 && g > 0.0, "half desaturated on the canvas: {r} {g}");
|
||||
step(&mut h);
|
||||
let (shown, _) = h.state().canvas.shown.as_ref().expect("a rendered canvas frame");
|
||||
let shown_fill = shown.node(id).unwrap().appearance.fill_paint().color().unwrap().to_rgb_uncalibrated();
|
||||
assert_eq!(shown_fill, fill_rgb(h.state(), id), "the canvas showed the preview before OK");
|
||||
answer(&mut h, true);
|
||||
assert!(top(h.state()).is_none());
|
||||
let st = h.state().session.doc().unwrap();
|
||||
|
||||
@@ -166,10 +166,14 @@ const SIZES: &[u8] = br#"{
|
||||
"size.page.button_side": 16,
|
||||
"size.page.link": 24
|
||||
},
|
||||
"comfortable": {
|
||||
"size.icon.lg": 26
|
||||
},
|
||||
"compact": {
|
||||
"size.control.md": 26,
|
||||
"size.button": 24,
|
||||
"size.icon.glyph_md": 16,
|
||||
"size.icon.lg": 24,
|
||||
"size.rail.width": 38,
|
||||
"size.dock.column": 310,
|
||||
"size.bar.column": 14,
|
||||
|
||||
@@ -823,7 +823,7 @@ fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, footer: RailFooter) {
|
||||
None => button,
|
||||
};
|
||||
// Small in two columns, where the three sit side by side in the rail's width.
|
||||
let button = if two { button.size(ControlSize::Sm) } else { button };
|
||||
let button = if two { button.size(ControlSize::Sm).glyphs(craft::ui::style::GlyphRole::Tool) } else { button };
|
||||
button.show(ui).clicked()
|
||||
};
|
||||
let mut run = None;
|
||||
|
||||
@@ -432,6 +432,7 @@ Stop opacity on translated artboards remains outside this regression coverage.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-30 | minor | `.ai` and EPS import: a word the page draws from two text objects in a row is their type. Where the text document makes the type of every text object that shows, a word of the page's type is the type of the made type holding its piece when that type spells it. The page can draw two text objects as one word: a word and a letter set apart from it (a swash "h" after "Spirit") come out of the page as one piece, "Spirith", that neither spells. It was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), though both text objects come in and draw it. Now a word left that is the last word of one text object holding the piece joined to the first word of another holding it that draws after it, along the first one's lines, is theirs (`joined_by_two` in `see_page_type`). Each part is a whole word of its text object, and the two the other way round don't make the word. Tests: `a_word_the_page_draws_from_two_text_objects_in_a_row_is_their_type`, `two_text_objects_the_other_way_round_arent_the_word_the_page_draws`. |
|
||||
| 2026-11-27 | minor | `.ai` save: type in a spot ink, a global process colour or Registration keeps its swatch link and its tint. Its fill and stroke in the text document name (key 5 of the paint) an art style of one paint, `0 1 Xd`, whose paint is the colour as a path's fill writes it (`x`, `Xx`, `Xk`, `Xs`), the form `.ai` import reads since the change below; key 0 still holds the process values at the tint. Each style is read back before it is written and kept only when the reader gives the same swatch and tint, so such type no longer counts among the attributes of type left out; a link to a process swatch that isn't global still does. Test `ai_editing::tests::type_in_spot_and_global_colors_reads_back_linked_at_its_tint` |
|
||||
| 2026-11-27 | minor | `.ai` and EPS import: type set in a spot ink or a global process colour keeps its ink. In the text document a character's fill or stroke is a colour (key 0: grey, RGB or CMYK) and the name of an art style (key 5). In users' files (used locally, never committed) that style is one paint (`/SimpleStyle`), always its fill's, for a stroke too; for a spot ink or a global process colour it is `c m y k (name) tint x`, `Xx` or `Xk`, and key 0 keeps only the ink's process values at that tint. Such type came in as that process colour, so it separated onto the process plates, and white type in a white ink onto none. It now takes the style's paint: the colour at its tint, linked to the document's swatch of that name, which the style's colour makes when the art doesn't (after the art's colours, before the header's custom colours). A style whose paint is a process colour or a gradient, one that also sets a stroke's colour or pattern (before or after the fill's) or another fill paint after it, one whose `Xd` doesn't turn on its fill alone, and a paint that names no style of the file, keep the colour of key 0 as before; type filled with a gradient still comes in black. Tests `type_set_in_a_spot_ink_takes_it_from_the_art_style_its_paint_names` in `crates/eps/src/import/tests_native.rs`, `a_run_painted_by_a_swatch_colours_art_style_takes_the_swatch` in `crates/eps/src/import/ate.rs` and `only_a_style_of_one_swatch_colour_holds_it_for_type` in `crates/eps/src/import/ai/style/tests.rs`. Scores and estimates unchanged. |
|
||||
| 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. The page comparison takes the same box for the layers' type areas (`type_areas` in `compare.rs`): made point type that differs from the page (laid out again, or in another font) counts as type where it draws, whatever its alignment. Counted as art beside the estimate, it could send the file to its PDF part or page, or be noted as art that differs. A file whose layers failed the comparison that way and opened without it now passes it and shows its notes. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws`, `centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws` and `right_aligned_point_type_that_differs_from_the_page_differs_as_type` in `crates/eps/src/import/tests_native.rs`, and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/slots.rs`. Scores and estimates unchanged. |
|
||||
|
||||
+4
-1
@@ -1,7 +1,7 @@
|
||||
# Gaps
|
||||
|
||||
> Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged.
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as lLine truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as lLine truncated
|
||||
|
||||
> Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged.
|
||||
|
||||
@@ -23,6 +23,8 @@ Properties panel Quick Actions follow the whole selection (G12). Ungroup (`objec
|
||||
|
||||
History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged.
|
||||
|
||||
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
|
||||
|
||||
OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged.
|
||||
|
||||
- **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged.
|
||||
@@ -1047,6 +1049,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv
|
||||
| 2026-11-20 | minor | G3: shadows from the first light and graphics on 3D surfaces moved from Missing to Done, as three-d.md documents them, and angular cut caps dropped from Missing, as Revolve's Cap closes a partial sweep's cut sides ([revolve.md](revolve.md)) (#8312); estimate unchanged |
|
||||
| 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. |
|
||||
| 2026-11-20 | minor | G12: Appearance panel: right-click item context menus for rows (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. |
|
||||
|
||||
+9
-5
@@ -12490,7 +12490,9 @@ Open Location after Export run these two (sub-folders sort the pictures; `assets
|
||||
folder itself), and its Format Settings… opens Export for Screens on the first row's format
|
||||
settings. `document.exportForScreens {assets: [id…]}` does the same with its own params
|
||||
(the dialog's Assets tab). An asset's crop, and the crop of `export` with `selection: true`, is the bounds the
|
||||
renderer measures for what the art draws, its effects included.
|
||||
renderer measures for what the art draws, its effects included. In the panel, Export Settings takes at most half the
|
||||
panel's height and scrolls on its own, so every format row can be reached in a short panel while Export and the footer
|
||||
bar stay in place.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"assets.add","params":{"multiple":true}}}
|
||||
@@ -15725,10 +15727,12 @@ a flare into a plain group of its parts. The document saves a flare's settings.
|
||||
The Shape Builder tool's options are its Shape Builder Tool Options (dialog `shapeBuilderOptions`):
|
||||
`openFilledAsClosed` (on: a filled open path bounds a region as if an invisible edge closed it; a path counts as
|
||||
filled when any of its fill rows is shown, painted and above 0% opacity, whichever row is on top; off: it cuts regions
|
||||
as an unfilled path does), `pickColorFrom` (`artwork`, the default: a merged shape takes the appearance, opacity and
|
||||
blending mode of the front-most selected object under the drag's first point, else of the one under its last point,
|
||||
else of the front-most selected object; `swatches`: the current fill, and the Left and Right arrow keys without
|
||||
Shift, Alt or Cmd/Ctrl step the current fill through the document's color swatches), `cursorSwatchPreview` (off; with `swatches`, chips above the
|
||||
as an unfilled path does), `pickColorFrom` (`swatches`, the default: a merged shape fills with the current fill, and
|
||||
the Left and Right arrow keys without Shift, Alt or Cmd/Ctrl step the current fill through the document's color
|
||||
swatches; `artwork`: a merged shape takes the appearance, opacity and blending mode of the front-most selected object
|
||||
under the drag's first point, else of the one under its last point, else of the front-most selected object; a
|
||||
`pickColorFrom` saved with the preferences is kept, except that preferences saved by an earlier version, without
|
||||
`toolSettingsVersion`, read a saved `artwork` as `swatches` once; preferences saved without one take `swatches`), `cursorSwatchPreview` (off; with `swatches`, chips above the
|
||||
pointer show the current fill and the swatches before and after it), `selection` (`freeform`, the default, or
|
||||
`straightLine`: a drag touches what the line from its first point to the pointer crosses), `highlightFill` (on by
|
||||
default; when it is off, merge mode shades no regions), `gapDetection` (off) with `gapLength` (pt, 0 to 72; 3), `clickStrokeSplitsPath` (In Merge Mode,
|
||||
|
||||
+5
-2
@@ -1,7 +1,7 @@
|
||||
# Roadmap: milestones and what's next
|
||||
|
||||
> Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged.
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (M2: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a gLine truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (M2: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a gLine truncated
|
||||
|
||||
> Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged.
|
||||
|
||||
@@ -34,6 +34,8 @@
|
||||
|
||||
Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged.
|
||||
|
||||
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
|
||||
|
||||
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged.
|
||||
|
||||
Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending.
|
||||
@@ -192,7 +194,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| # | Milestone | Status | Est. remaining, one agent (h) |
|
||||
|---|---|---|---|
|
||||
| M0 | Skeleton + vertical slice | ✅ done | — |
|
||||
| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 |
|
||||
| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 |
|
||||
| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors the topmost, newest objects keep their Smart Guides targets (#8531) | 12–18 |
|
||||
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 |
|
||||
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF importLine truncated
|
||||
@@ -262,6 +264,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours
|
||||
| 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged |
|
||||
| 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688). Scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | M14/G12: Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides); regression tests in crates/ui-egui/src/panels/text_styles/tests.rs; scores and estimates unchanged. |
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user