mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:59:43 +01:00
Merge commit '5c7bbeecaa1e9481eb784f1ffc2062529872505d' into fix/graph-data-original-document
This commit is contained in:
commit
e8ffebefc6
38 files changed
+1428
-209
No files matched your search
+121
-14
@@ -1,5 +1,7 @@
|
||||
//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed
|
||||
//! or interrupted write never leaves a damaged file behind (the old one stays as it was).
|
||||
//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination.
|
||||
//! A failure while writing or flushing the temporary file leaves the original file unchanged.
|
||||
//! On Unix, saves also flush the destination directory after the complete file is written.
|
||||
//! An error at that step reports that the file was written.
|
||||
//! [`write_new_with`] creates a file the same way without ever replacing one.
|
||||
//!
|
||||
//! Where a folder refuses the temporary file or the rename (some network shares, a file another
|
||||
@@ -22,11 +24,29 @@ use std::io::{self, Write as _};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Whether the returned write error refuses this location. Recovery errors must still be shown:
|
||||
/// their message names copies the user may need, even when their kind is PermissionDenied.
|
||||
/// Reports whether a write error identifies a read-only location.
|
||||
/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied.
|
||||
pub fn read_only_location(error: &io::Error) -> bool {
|
||||
matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied)
|
||||
&& !error.get_ref().is_some_and(|e| e.is::<RecoveryError>())
|
||||
&& !error.get_ref().is_some_and(|e| e.is::<RecoveryError>() || e.is::<WrittenError>())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WrittenError {
|
||||
path: PathBuf,
|
||||
error: io::Error,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for WrittenError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for WrittenError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
Some(&self.error)
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks the existing recovery message without changing its text or the returned error kind.
|
||||
@@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
write_atomic_with(path, |f| f.write_all(bytes))
|
||||
}
|
||||
|
||||
/// Write `path` atomically with `fill`, which writes the content into the temporary file. When
|
||||
/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the
|
||||
/// temporary file is removed and `path` is left untouched. When the
|
||||
/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see
|
||||
/// the module docs).
|
||||
/// This function writes `path` atomically with `fill`, which writes content into a temporary file.
|
||||
/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged.
|
||||
/// Cleanup attempts to remove the temporary file and ignores removal errors.
|
||||
/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs).
|
||||
pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
|
||||
// Replacing a file: its staging copy starts owner-only, so a private document is never readable
|
||||
// beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode.
|
||||
@@ -97,7 +116,7 @@ fn write_atomic_stepping(
|
||||
// Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none
|
||||
// to keep.
|
||||
let _ = keep_permissions(&target, &tmp);
|
||||
let Err(e) = rename(&tmp, &target) else { return Ok(()) };
|
||||
let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) };
|
||||
e
|
||||
}
|
||||
};
|
||||
@@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
|
||||
if let Some(old) = old {
|
||||
let _ = std::fs::remove_file(old);
|
||||
}
|
||||
Ok(())
|
||||
sync_written_parent(target)
|
||||
}
|
||||
(Err(e), Some(old)) => Err(io::Error::new(
|
||||
e.kind(),
|
||||
@@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result<File> {
|
||||
/// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was
|
||||
/// taken meanwhile). The file appears whole or not at all. Where hard links fail for another
|
||||
/// reason, `path` is created with `create_new` and the content copied in; a failed copy removes
|
||||
/// it. The temporary file is always removed.
|
||||
/// it. Cleanup attempts to remove the temporary file and ignores removal errors.
|
||||
pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
|
||||
write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path))
|
||||
}
|
||||
@@ -189,7 +208,31 @@ fn write_new_linking(
|
||||
});
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
placed
|
||||
placed.and_then(|()| sync_written_parent(path))
|
||||
}
|
||||
|
||||
fn sync_written_parent(path: &Path) -> io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error }))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = path;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// This function flushes the directory containing `path` with `fsync`.
|
||||
/// It returns errors from opening or flushing the directory.
|
||||
#[cfg(unix)]
|
||||
pub fn sync_parent(path: &Path) -> io::Result<()> {
|
||||
#[cfg(test)]
|
||||
if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
|
||||
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed"));
|
||||
}
|
||||
let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
|
||||
rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from)
|
||||
}
|
||||
|
||||
/// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has
|
||||
@@ -272,6 +315,8 @@ const ENOTTY: i32 = 25;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
#[cfg(unix)]
|
||||
static DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: every full flush on this thread fails as on an SMB share mounted by macOS.
|
||||
static REFUSE_FULL_SYNC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: the plain `fsync` fallback fails too, with this OS error.
|
||||
@@ -472,6 +517,68 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_directory_sync_failure_reports_the_completed_replacement() {
|
||||
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace");
|
||||
let path = directory.join("doc.vectorcraft");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
let result = write_atomic(&path, b"new");
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
assert!(result.is_err(), "a failed directory flush was reported as success");
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert!(error.to_string().contains("The file was written to"), "{error}");
|
||||
assert!(!read_only_location(&error), "the file was already replaced: {error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
assert!(leftovers(&directory, "doc.vectorcraft").is_empty());
|
||||
write_atomic(&path, b"retried").unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"retried");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_directory_sync_failure_preserves_the_completed_new_file() {
|
||||
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create");
|
||||
let path = directory.join("doc.vectorcraft");
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
let result = write_new_with(&path, |file| file.write_all(b"created"));
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
assert!(result.is_err(), "a failed directory flush was reported as success");
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert!(error.to_string().contains("The file was written to"), "{error}");
|
||||
assert!(!read_only_location(&error), "the file was already created: {error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"created");
|
||||
assert!(leftovers(&directory, "doc.vectorcraft").is_empty());
|
||||
let result = write_new_with(&path, |file| file.write_all(b"replacement"));
|
||||
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"created");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_directory_sync_failure_is_reported_after_copy_fallbacks() {
|
||||
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy");
|
||||
let path = directory.join("doc.vectorcraft");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied());
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
let error = replaced.unwrap_err();
|
||||
assert!(!read_only_location(&error), "the file was already replaced: {error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
let new_path = directory.join("new.vectorcraft");
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied());
|
||||
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
let error = created.unwrap_err();
|
||||
assert!(!read_only_location(&error), "the file was already created: {error}");
|
||||
assert_eq!(std::fs::read(&new_path).unwrap(), b"created");
|
||||
assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2);
|
||||
}
|
||||
|
||||
/// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the
|
||||
/// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before,
|
||||
/// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain
|
||||
|
||||
@@ -55,6 +55,8 @@ use serde::{Deserializer, Serialize};
|
||||
use vectorcraft_brush::stored_art::StoredArt;
|
||||
use vectorcraft_doc::{Document, ImageBlob};
|
||||
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
pub use atomic::sync_parent;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
use craft_gzip::Gz;
|
||||
|
||||
+46
-17
@@ -30,6 +30,7 @@ pub enum Data {
|
||||
}
|
||||
|
||||
/// How much one crossing may carry.
|
||||
/// Host receivers, their handles and explicit arguments share these limits.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct DataLimits {
|
||||
/// How deeply arrays and objects may nest.
|
||||
@@ -265,9 +266,7 @@ impl Interp {
|
||||
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
|
||||
}
|
||||
let shape = match &self.object(id)?.class {
|
||||
Class::Host(_) if r.hosted => {
|
||||
return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into()));
|
||||
}
|
||||
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
|
||||
Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")),
|
||||
Class::Array { length, .. } => Shape::Array(*length),
|
||||
Class::Ordinary => {
|
||||
@@ -299,6 +298,14 @@ impl Interp {
|
||||
out
|
||||
}
|
||||
|
||||
fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult<Data> {
|
||||
let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) };
|
||||
self.charge_entries(r, len.saturating_add(2))?;
|
||||
let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8);
|
||||
self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?;
|
||||
self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into()))
|
||||
}
|
||||
|
||||
fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult<Data> {
|
||||
self.charge_entries(r, length as usize)?;
|
||||
let mut items = Vec::with_capacity(length as usize);
|
||||
@@ -407,16 +414,8 @@ impl Interp {
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, this: &Value, args: &[Value], how: &ArgRead) -> JsResult<Value> {
|
||||
let data = match how {
|
||||
ArgRead::Site => site_data(self.call_site()),
|
||||
ArgRead::Hosted => {
|
||||
let this = match this {
|
||||
Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined),
|
||||
_ => Data::Undefined,
|
||||
};
|
||||
let mut data = vec![this];
|
||||
data.extend(self.read_args(name, args, how)?);
|
||||
data
|
||||
}
|
||||
_ => self.read_args(name, args, how)?,
|
||||
ArgRead::Hosted => self.read_args(name, Some(this), args, how)?,
|
||||
_ => self.read_args(name, None, args, how)?,
|
||||
};
|
||||
// Only the script's own code, in a run that can pause, can wait for a result, and a host
|
||||
// class's constructor called with `new` cannot.
|
||||
@@ -463,7 +462,7 @@ impl Interp {
|
||||
name: &Rc<str>,
|
||||
args: &[Value],
|
||||
) -> JsResult<Value> {
|
||||
let data = self.read_args(name, args, &ArgRead::Data)?;
|
||||
let data = self.read_args(name, None, args, &ArgRead::Data)?;
|
||||
let source = match f(data) {
|
||||
Ok(Data::String(source)) => source,
|
||||
Ok(d) => return self.write_data(d, 0, false),
|
||||
@@ -505,8 +504,8 @@ impl Interp {
|
||||
r
|
||||
}
|
||||
|
||||
/// The arguments of host function `name` as [`Data`], read as `how` says.
|
||||
fn read_args(&mut self, name: &Rc<str>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
|
||||
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
|
||||
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
|
||||
let mut reading = Reading {
|
||||
limits: self.data_limits,
|
||||
bytes: 0,
|
||||
@@ -520,7 +519,14 @@ impl Interp {
|
||||
ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args),
|
||||
_ => args,
|
||||
};
|
||||
let mut data = Vec::with_capacity(args.len());
|
||||
let mut data = Vec::with_capacity(args.len() + 1);
|
||||
if let Some(this) = this {
|
||||
let this = match this {
|
||||
Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?,
|
||||
_ => Data::Undefined,
|
||||
};
|
||||
data.push(this);
|
||||
}
|
||||
// A conversion can run the script's own `toString`, which may collect garbage.
|
||||
let mark = self.temp_roots.len();
|
||||
if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) {
|
||||
@@ -552,6 +558,29 @@ impl Interp {
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult<Vec<Data>> {
|
||||
let mut reading = Reading {
|
||||
limits: self.data_limits,
|
||||
bytes: 0,
|
||||
entries: 0,
|
||||
ancestors: Vec::new(),
|
||||
path: Vec::new(),
|
||||
function: Rc::from("host indexer"),
|
||||
hosted: true,
|
||||
};
|
||||
let receiver = self.read_host_ref(id, &mut reading)?;
|
||||
match &key {
|
||||
Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?,
|
||||
Data::Number(_) => {}
|
||||
_ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())),
|
||||
}
|
||||
let mut args = vec![receiver, key];
|
||||
if probe {
|
||||
args.push(Data::Bool(true));
|
||||
}
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// What host error `e` throws, or the limit it ends the run with. A function that waits
|
||||
/// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal
|
||||
/// error.
|
||||
|
||||
@@ -172,6 +172,12 @@ impl Interp {
|
||||
Ok(Some(host_ref(&name, &h.handle)))
|
||||
}
|
||||
|
||||
pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult<Option<(usize, usize)>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?;
|
||||
Ok(Some((name, h.handle.len())))
|
||||
}
|
||||
|
||||
/// The object of a host class that `d`, which a host function gave, stands for.
|
||||
pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult<Value> {
|
||||
let Some((name, handle)) = host_ref_parts(d) else {
|
||||
@@ -220,11 +226,10 @@ impl Interp {
|
||||
/// gets `true` as a third argument.
|
||||
pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult<Value> {
|
||||
self.use_fuel()?;
|
||||
let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) };
|
||||
let mut args = vec![this, k];
|
||||
if probe {
|
||||
args.push(Data::Bool(true));
|
||||
if self.host_ref_size(id)?.is_none() {
|
||||
return Ok(Value::Undefined);
|
||||
}
|
||||
let args = self.read_index_args(id, k, probe)?;
|
||||
match f(args) {
|
||||
Ok(d) => self.write_hosted(d),
|
||||
Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())),
|
||||
|
||||
@@ -11,6 +11,57 @@ fn realm(fuel: u64) -> Realm {
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_indexer_keys_reach_the_host_unchanged() {
|
||||
let mut r = realm(1_000_000);
|
||||
let index: HostFunction = Rc::new(|args| {
|
||||
assert!(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()), "{args:?}");
|
||||
Ok(Data::Bool(true))
|
||||
});
|
||||
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None };
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap();
|
||||
let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_receivers_obey_limits_lowered_after_the_object_was_created() {
|
||||
for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] {
|
||||
for expression in ["it[0]", "0 in it", "it.method()", "it.take(it)"] {
|
||||
let mut r = realm(1_000_000);
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let called = calls.clone();
|
||||
let function: HostFunction = Rc::new(move |_| {
|
||||
called.set(called.get() + 1);
|
||||
Ok(Data::Undefined)
|
||||
});
|
||||
let class = HostClass {
|
||||
name: "Indexed".into(),
|
||||
parent: None,
|
||||
members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))],
|
||||
index: Some(function),
|
||||
construct: None,
|
||||
};
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0, 2.0, 3.0]))]).unwrap();
|
||||
r.set_data_limits(limits);
|
||||
let source = format!("var result = 'called'; try {{ {expression}; }} catch (e) {{ result = e.name; }} result");
|
||||
assert_eq!(r.run(&source).unwrap(), JsValue::String("RangeError".into()), "{expression}: {limits:?}");
|
||||
assert_eq!(calls.get(), 0, "{expression}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_keys_share_the_receivers_data_budget() {
|
||||
let mut r = realm(1_000_000);
|
||||
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None };
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap();
|
||||
r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 });
|
||||
assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true));
|
||||
let source = "var result = 'called'; try { it[new Array(71).join('x')]; } catch (e) { result = e.name; } result";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into()));
|
||||
}
|
||||
|
||||
/// A realm with `host.take(value)`, which records what it was given and returns it.
|
||||
fn with_take(r: &mut Realm) -> Rc<RefCell<Vec<Data>>> {
|
||||
let seen: Rc<RefCell<Vec<Data>>> = Rc::default();
|
||||
|
||||
@@ -17,10 +17,10 @@ pub mod tangent_circle;
|
||||
use craft::behavior::ColumnWidth;
|
||||
use craft::menu::Node;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
|
||||
use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked};
|
||||
use craft::ui::display::{Divider, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::{Grid, Row};
|
||||
use craft::ui::layout_components::{Grid, Row, Stack};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
|
||||
use craft::ui::runtime::env::{Label, LengthUnits, UnitKind};
|
||||
use craft::ui::text::NumberField;
|
||||
@@ -192,6 +192,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
empty_state(ui, "dc-anchor-smooth", tl!("No document"), tl!("Open a document to edit its anchor points."));
|
||||
return;
|
||||
}
|
||||
Stack::new().label(tl!("Anchor Inspector")).fill().scroll(Scroll::vertical()).show(ui, |ui, _| show_inspector(app, ui));
|
||||
}
|
||||
|
||||
fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let readout = readout(app);
|
||||
let anchor = readout.anchor.as_ref();
|
||||
let selected = app.session.active().is_some_and(|st| !st.selection.is_empty());
|
||||
|
||||
@@ -44,6 +44,32 @@ fn the_inspector_shows_the_selected_anchor_and_its_buttons_edit() {
|
||||
assert!(a.lengths.iter().all(|l| *l > 0.0) && a.angles.iter().all(|d| d.is_some()), "{:?} {:?}", a.lengths, a.angles);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() {
|
||||
let mut app = app();
|
||||
let path = app.run("path.create", json!({ "anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}] })).unwrap();
|
||||
let id = vectorcraft_doc::NodeId(path["id"].as_u64().unwrap());
|
||||
app.session
|
||||
.select(|_, sel| {
|
||||
sel.set([id]);
|
||||
sel.anchors.insert(id, [(0, 1)].into_iter().collect());
|
||||
})
|
||||
.unwrap();
|
||||
let mut panel = Panel::new(app, super::show);
|
||||
let room = egui::vec2(220.0, 215.0);
|
||||
panel.room(room).frame();
|
||||
panel.frame();
|
||||
let action = "Remove Points, Keep Shape";
|
||||
assert!(panel.rect(action).bottom() > room.y, "the action starts clipped");
|
||||
panel.focus(action);
|
||||
let rect = panel.rect(action);
|
||||
assert!(panel.focused(action) && rect.top() >= 0.0 && rect.bottom() <= room.y, "focus reveals the action: {rect:?}");
|
||||
panel.focus("Make Smooth");
|
||||
panel.click("Make Smooth");
|
||||
let anchor = readout(&panel.app()).anchor.unwrap();
|
||||
assert!(anchor.lengths.iter().all(|length| *length > 0.0));
|
||||
}
|
||||
|
||||
/// Runs `f` on the held options dialog, `None` when none is open.
|
||||
fn held<R>(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R {
|
||||
app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::<HostedParamDialog>()))
|
||||
|
||||
@@ -235,6 +235,7 @@ impl VectorcraftApp {
|
||||
told: Default::default(),
|
||||
missing_font_edit_token: None,
|
||||
held: Default::default(),
|
||||
document_setup_source: None,
|
||||
edit_scopes: Default::default(),
|
||||
command_dialog: Default::default(),
|
||||
effect_dialogs: Default::default(),
|
||||
|
||||
@@ -137,8 +137,7 @@ impl ArtboardOptionsValue {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the dialog shows but does not edit; read from the app when it opens, since a modal dialog's
|
||||
/// document, presets and preferences cannot change while it is open.
|
||||
/// What the dialog shows but does not edit, read from the app when it opens.
|
||||
struct Setup {
|
||||
/// The lengths the fields keep and show.
|
||||
lengths: LengthUnits,
|
||||
@@ -152,9 +151,17 @@ struct Setup {
|
||||
fit_bounds: [Option<Rect>; 2],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Target {
|
||||
document: u64,
|
||||
/// The current artboard's ID, or no ID while creating a new artboard.
|
||||
artboard: Option<u32>,
|
||||
}
|
||||
|
||||
/// Artboard Options on the dialog host: the artboard's value, the held OK and the color requests.
|
||||
pub struct ArtboardOptionsDialog {
|
||||
id: DialogId,
|
||||
target: Target,
|
||||
value: ArtboardOptionsValue,
|
||||
setup: Setup,
|
||||
held: HeldAnswer<ArtboardOptionsValue>,
|
||||
@@ -162,8 +169,8 @@ pub struct ArtboardOptionsDialog {
|
||||
}
|
||||
|
||||
impl ArtboardOptionsDialog {
|
||||
fn new(value: ArtboardOptionsValue, setup: Setup) -> Self {
|
||||
ArtboardOptionsDialog { id: dialog_id(KIND), value, setup, held: HeldAnswer::new(), requests: HostRequests::new() }
|
||||
fn new(target: Target, value: ArtboardOptionsValue, setup: Setup) -> Self {
|
||||
ArtboardOptionsDialog { id: dialog_id(KIND), target, value, setup, held: HeldAnswer::new(), requests: HostRequests::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -546,13 +553,15 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize {
|
||||
|
||||
/// Opens the dialog over `value`, with the preferences, the shared reference point and what the dialog
|
||||
/// shows read from the app.
|
||||
fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result<Value, String> {
|
||||
fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option<u32>) -> Result<Value, String> {
|
||||
let host = app.dialogs().ok_or("no window")?;
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let target = Target { document: st.uid, artboard };
|
||||
let artwork = vectorcraft_render::encode::art_bounds(&st.doc);
|
||||
let [(_, fade), (_, update_while_dragging)] = global_fields(app);
|
||||
(value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point);
|
||||
let fills = fill_colors(app);
|
||||
value.seed_customs(&fills);
|
||||
let artwork = app.session.active().and_then(|st| vectorcraft_render::encode::art_bounds(&st.doc));
|
||||
let setup = Setup {
|
||||
lengths: crate::canvas::rulers::general_lengths(app),
|
||||
origin: app.ruler_origin(),
|
||||
@@ -560,7 +569,7 @@ fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result<
|
||||
fills,
|
||||
fit_bounds: [artwork, app.selection_bounds()],
|
||||
};
|
||||
host.with(|h| h.open(ArtboardOptionsDialog::new(value, setup)));
|
||||
host.with(|h| h.open(ArtboardOptionsDialog::new(target, value, setup)));
|
||||
Ok(json!({ "dialog": KIND }))
|
||||
}
|
||||
|
||||
@@ -569,6 +578,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let index = active_index(app);
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let a = st.doc.artboards.get(index).ok_or("no artboard")?;
|
||||
let artboard = a.id;
|
||||
let r = a.rect;
|
||||
let value = ArtboardOptionsValue {
|
||||
index,
|
||||
@@ -585,7 +595,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
pixel_aspect: a.video_ruler_pixel_aspect_ratio,
|
||||
..Default::default()
|
||||
};
|
||||
present(app, value)
|
||||
present(app, value, Some(artboard))
|
||||
}
|
||||
|
||||
/// `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard): Artboard Options for a new
|
||||
@@ -605,7 +615,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
pixel_aspect: 1.0,
|
||||
..Default::default()
|
||||
};
|
||||
present(app, value)
|
||||
present(app, value, None)
|
||||
}
|
||||
|
||||
/// Runs once per frame after the shell pass: runs the artboard command of a filed OK and answers it
|
||||
@@ -613,12 +623,15 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
/// point picked in the dialog.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
let Some(host) = app.dialogs() else { return };
|
||||
let Some((held, reference)) = host.with(|h| h.get_mut::<ArtboardOptionsDialog>().map(|d| (d.held.take(), d.value.reference))) else { return };
|
||||
let Some((target, held, reference)) = host.with(|h| h.get_mut::<ArtboardOptionsDialog>().map(|d| (d.target, d.held.take(), d.value.reference)))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if app.ui.transform_panel.reference_point != reference {
|
||||
app.ui.transform_panel.reference_point = reference;
|
||||
}
|
||||
if let Some(value) = held {
|
||||
let answer = confirm(app, &value).map(drop).map_err(Label::from);
|
||||
let answer = confirm(app, target, &value).map(drop).map_err(Label::from);
|
||||
host.with(|h| {
|
||||
if let Some(d) = h.get_mut::<ArtboardOptionsDialog>() {
|
||||
d.held.answer(answer);
|
||||
@@ -633,21 +646,28 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
/// used (its column and row), all in one undo step. Fitting applies only to this artboard and never
|
||||
/// moves its artwork. The Global checkboxes' preferences are set only after the artboard command
|
||||
/// succeeds, so an error leaves them as they were.
|
||||
fn confirm(app: &mut VectorcraftApp, v: &ArtboardOptionsValue) -> Result<Value, String> {
|
||||
fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -> Result<Value, String> {
|
||||
let st = app
|
||||
.session
|
||||
.active()
|
||||
.filter(|st| st.uid == target.document)
|
||||
.ok_or(tl!("Artboard Options can only change the document where it was opened."))?;
|
||||
let globals = global_changes(app, v);
|
||||
if v.new {
|
||||
let r = confirm_new(app, v)?;
|
||||
set_globals(app, globals)?;
|
||||
return Ok(r);
|
||||
}
|
||||
let p = v.params();
|
||||
let was = app.session.active().and_then(|st| st.doc.artboards.get(v.index)).map(|a| a.rect);
|
||||
let changed = |k: &str, old: Option<f64>| p[k].as_f64().filter(|n| old.is_some_and(|old| (n - old).abs() > 1e-6));
|
||||
let (w, h) = (changed("width", was.map(|r| r.width())), changed("height", was.map(|r| r.height())));
|
||||
let (index, board) =
|
||||
st.doc.artboards.iter().enumerate().find(|(_, board)| Some(board.id) == target.artboard).ok_or(tl!("This artboard was removed."))?;
|
||||
let mut p = v.params();
|
||||
p["index"] = json!(index);
|
||||
let changed = |k: &str, old: f64| p[k].as_f64().filter(|n| (n - old).abs() > 1e-6);
|
||||
let (w, h) = (changed("width", board.rect.width()), changed("height", board.rect.height()));
|
||||
let refi = v.ref_y.min(2) * 3 + v.ref_x.min(2);
|
||||
let mut entries = vec![];
|
||||
if !v.fit && (v.size_choice.is_some() || w.is_some() || h.is_some()) {
|
||||
for i in crate::panels::artboards::resized_with(app, v.index).into_iter().filter(|i| *i != v.index) {
|
||||
for i in crate::panels::artboards::resized_with(app, index).into_iter().filter(|i| *i != index) {
|
||||
if let Some(r) = app.session.active().and_then(|st| st.doc.artboards.get(i)).map(|a| a.rect) {
|
||||
let (w, h) = if let Some(choice) = v.size_choice {
|
||||
let Some((w, h)) = choice.size_for(r.width(), r.height()) else { continue };
|
||||
@@ -753,6 +773,69 @@ mod tests {
|
||||
app.session.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmation_follows_the_original_artboard_after_reorder() {
|
||||
let mut app = app();
|
||||
app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap();
|
||||
crate::panels::artboards::select(&mut app, 0);
|
||||
let original = app.session.active().unwrap().doc.artboards[0].id;
|
||||
open(&mut app).unwrap();
|
||||
set(&app, &[("name", json!("Renamed"))]).unwrap();
|
||||
|
||||
app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc.artboards[1].id, original);
|
||||
let undo = undo_len(&app);
|
||||
ok(&mut app).unwrap();
|
||||
let artboards = &app.session.active().unwrap().doc.artboards;
|
||||
assert_eq!((artboards[0].name.as_str(), artboards[1].name.as_str()), ("Artboard 2", "Renamed"));
|
||||
assert_eq!(undo_len(&app), undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmation_refuses_to_edit_or_add_artboards_in_another_document() {
|
||||
for create in [false, true] {
|
||||
let mut app = app();
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
if create {
|
||||
open_new(&mut app).unwrap();
|
||||
} else {
|
||||
open(&mut app).unwrap();
|
||||
}
|
||||
set(&app, &[("name", json!("Source"))]).unwrap();
|
||||
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
let undo = undo_len(&app);
|
||||
let answer = ok(&mut app);
|
||||
let artboards = &app.session.active().unwrap().doc.artboards;
|
||||
assert_eq!((artboards.len(), artboards[0].name.as_str()), (1, "Artboard 1"));
|
||||
assert_eq!(undo_len(&app), undo);
|
||||
assert!(answer.is_err() && is_open(&app));
|
||||
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
ok(&mut app).unwrap();
|
||||
let artboards = &app.session.active().unwrap().doc.artboards;
|
||||
assert_eq!(artboards.len(), if create { 2 } else { 1 });
|
||||
assert_eq!(artboards.last().unwrap().name, "Source");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmation_refuses_to_edit_a_deleted_artboards_replacement() {
|
||||
let mut app = app();
|
||||
app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap();
|
||||
crate::panels::artboards::select(&mut app, 0);
|
||||
open(&mut app).unwrap();
|
||||
set(&app, &[("name", json!("Renamed"))]).unwrap();
|
||||
|
||||
app.run("artboard.delete", json!({"index": 0})).unwrap();
|
||||
let undo = undo_len(&app);
|
||||
let answer = ok(&mut app);
|
||||
assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 2");
|
||||
assert_eq!(undo_len(&app), undo);
|
||||
assert!(answer.is_err() && is_open(&app));
|
||||
}
|
||||
|
||||
/// A new X moves the art only with Move Artwork with Artboard on, and Undo restores the document.
|
||||
#[test]
|
||||
fn position_moves_art_only_with_the_tool_option_on() {
|
||||
|
||||
@@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into()));
|
||||
fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into()));
|
||||
fields["convertColors"] = json!(true);
|
||||
let (mode, setup) = (st.doc.color_mode, st.doc.setup.clone());
|
||||
let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone());
|
||||
let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) };
|
||||
let presets: Vec<String> = app.session.flattener_presets().into_iter().map(|p| p.name).collect();
|
||||
let display = app.display_profile.transform(app.session.prefs.monitor_profile_display);
|
||||
@@ -82,6 +82,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
PropertiesDialog::new(KIND, tl!("Document Setup"), tabs.clone(), values)
|
||||
});
|
||||
super::host::open_held(app, dialog, |app, fields| confirm(app, fields).map(|_| ())).ok_or("no window to show the dialog in")?;
|
||||
app.document_setup_source = Some(source);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -185,6 +186,9 @@ fn color_commands(app: &VectorcraftApp, fields: &Map<String, Value>) -> Result<V
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result<Value, String> {
|
||||
if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) {
|
||||
return Err(tl!("Document Setup can only change the document where it was opened.").to_owned());
|
||||
}
|
||||
let map = json_map(fields);
|
||||
let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect());
|
||||
let color = color_commands(app, &map)?;
|
||||
@@ -220,9 +224,12 @@ fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option<String>
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let id = dialog_id(KIND);
|
||||
let edit = dialogs.with(|host| {
|
||||
host.get_by_id::<HostedPropertiesDialog>(id).filter(|d| d.fields().bool("editArtboards") == Some(true)).map(|d| d.fields().clone())
|
||||
});
|
||||
let Some(edit) = dialogs.with(|host| {
|
||||
host.get_by_id::<HostedPropertiesDialog>(id).map(|d| (d.fields().bool("editArtboards") == Some(true)).then(|| d.fields().clone()))
|
||||
}) else {
|
||||
app.document_setup_source = None;
|
||||
return;
|
||||
};
|
||||
if let Some(fields) = edit {
|
||||
match confirm(app, &fields) {
|
||||
Ok(_) => {
|
||||
@@ -645,6 +652,54 @@ mod tests {
|
||||
app.session.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn check_source_document(edit_artboards: bool) {
|
||||
let (mut app, ctx) = new_app();
|
||||
let source = app.session.active().unwrap().uid;
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let destination = app.session.active().unwrap().uid;
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("file.documentSetup", json!({})).unwrap();
|
||||
set(&app, &ctx, "bleed", json!([9, 9, 9, 9]));
|
||||
set(&app, &ctx, "colorMode", json!("cmyk"));
|
||||
|
||||
let apply = |app: &mut VectorcraftApp| {
|
||||
if edit_artboards {
|
||||
set(app, &ctx, "editArtboards", json!(true));
|
||||
super::pump(app, &ctx);
|
||||
!is_open(app)
|
||||
} else {
|
||||
press_ok(app, &ctx)
|
||||
}
|
||||
};
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
let undo = undo_steps(&app);
|
||||
let accepted = apply(&mut app);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.uid, destination);
|
||||
assert_eq!((st.doc.setup.bleed, st.doc.color_mode), ([0.0; 4], ColorMode::Rgb), "the other document keeps its settings");
|
||||
assert_eq!(undo_steps(&app), undo);
|
||||
assert_eq!(app.session.tool_id(), "selection");
|
||||
assert!(!accepted && is_open(&app));
|
||||
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
assert!(apply(&mut app));
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.uid, source);
|
||||
assert_eq!((st.doc.setup.bleed, st.doc.color_mode, undo_steps(&app)), ([9.0; 4], ColorMode::Cmyk, 1));
|
||||
assert_eq!(app.session.tool_id(), if edit_artboards { "artboard" } else { "selection" });
|
||||
assert!(!is_open(&app));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_document_is_required_to_confirm_document_setup() {
|
||||
check_source_document(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_document_is_required_to_edit_artboards_from_document_setup() {
|
||||
check_source_document(true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_artboards_applies_settings_and_closes_the_dialog() {
|
||||
let (mut app, ctx) = setup_open();
|
||||
|
||||
@@ -996,17 +996,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
|
||||
let key = app.session.active().map(|st| (st.uid, st.revision));
|
||||
let pdf_presets = pdf::presets(&app.session);
|
||||
let saved = &app.session.prefs.screen_export_presets;
|
||||
let Some((stale, pending, rename, filed)) = dialogs.with(|host| {
|
||||
let Some((shown, pending, rename, filed)) = dialogs.with(|host| {
|
||||
let d = host.get_mut_by_id::<ExportForScreensDialog>(id)?;
|
||||
screen_formats::preset_list(&mut d.presets, saved);
|
||||
if d.pdf_presets != pdf_presets {
|
||||
d.pdf_presets = pdf_presets;
|
||||
}
|
||||
Some((d.doc.as_ref().map(|s| s.key) != key, d.pending.take(), d.rename.take(), d.held.take()))
|
||||
Some((d.doc.as_ref().map(|s| s.key), d.pending.take(), d.rename.take(), d.held.take()))
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
if stale {
|
||||
if shown != key {
|
||||
let (doc, thumbs) = document_view(app, ctx);
|
||||
dialogs.with(|host| {
|
||||
if let Some(d) = host.get_mut_by_id::<ExportForScreensDialog>(id) {
|
||||
@@ -1031,7 +1031,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
|
||||
rename_artboard(app, board, &name);
|
||||
}
|
||||
if let Some(fields) = filed {
|
||||
let answer = params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from);
|
||||
// OK validated its selection against the document the dialog showed before refreshing.
|
||||
let answer = if shown.map(|(uid, _)| uid) == app.session.active().map(|st| st.uid) {
|
||||
params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from)
|
||||
} else {
|
||||
Err(Label::from(tl!("The active document changed. Review the export selection and try again.")))
|
||||
};
|
||||
dialogs.with(|host| {
|
||||
if let Some(d) = host.get_mut_by_id::<ExportForScreensDialog>(id) {
|
||||
d.held.answer(answer);
|
||||
|
||||
@@ -55,8 +55,14 @@ type Info = Map<String, Value>;
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?;
|
||||
let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?;
|
||||
let ok = |app: &mut VectorcraftApp, fields: &Info| app.run("file.info", Value::Object(fields.clone())).map(|_| ());
|
||||
crate::dialogs::host::open_held(app, FileInfoDialog::new(fields), ok).ok_or("no window")?;
|
||||
let document = app.session.active().ok_or("no document")?.uid;
|
||||
let ok = |app: &mut VectorcraftApp, (document, fields): &(u64, Info)| {
|
||||
if !app.session.active().is_some_and(|active| active.uid == *document) {
|
||||
return Err(tl!("File Info can only change the document it was opened for.").to_owned());
|
||||
}
|
||||
app.run("file.info", Value::Object(fields.clone())).map(|_| ())
|
||||
};
|
||||
crate::dialogs::host::open_held(app, FileInfoDialog::new(document, fields), ok).ok_or("no window")?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -215,6 +221,7 @@ impl Templates {
|
||||
/// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app.
|
||||
pub(crate) struct FileInfoDialog {
|
||||
id: DialogId,
|
||||
document: u64,
|
||||
open: bool,
|
||||
/// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]).
|
||||
hold: bool,
|
||||
@@ -230,9 +237,10 @@ pub(crate) struct FileInfoDialog {
|
||||
}
|
||||
|
||||
impl FileInfoDialog {
|
||||
fn new(value: Info) -> Self {
|
||||
fn new(document: u64, value: Info) -> Self {
|
||||
FileInfoDialog {
|
||||
id: dialog_id(KEY),
|
||||
document,
|
||||
open: true,
|
||||
hold: false,
|
||||
value,
|
||||
@@ -371,15 +379,15 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option<bool> {
|
||||
}
|
||||
|
||||
impl HoldsOk for FileInfoDialog {
|
||||
type Answer = Info;
|
||||
type Answer = (u64, Info);
|
||||
|
||||
fn held_ok(mut self) -> Self {
|
||||
self.hold = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn take_ok(&mut self) -> Option<Info> {
|
||||
self.held.take()
|
||||
fn take_ok(&mut self) -> Option<Self::Answer> {
|
||||
self.held.take().map(|fields| (self.document, fields))
|
||||
}
|
||||
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
@@ -674,6 +682,58 @@ mod tests {
|
||||
assert!(with_dialog(&app, |_| ()).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_info_confirmation_stays_with_its_document() {
|
||||
let mut app = windowed();
|
||||
for (title, author) in [("Source", "Ada"), ("Destination", "Grace")] {
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("file.info", json!({"title": title, "author": author})).unwrap();
|
||||
}
|
||||
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
|
||||
activate(&mut app, 0);
|
||||
let a_undo = app.session.active().unwrap().history.undo.len();
|
||||
app.run("ui.fileInfoDialog", json!({})).unwrap();
|
||||
set(&app, "title", json!("Revised Source")).unwrap();
|
||||
set(&app, PENDING, json!("print")).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KEY))), "the edit waits for the application");
|
||||
|
||||
activate(&mut app, 1);
|
||||
let before = app.session.active().unwrap();
|
||||
let document = before.doc.clone();
|
||||
let b_undo = before.history.undo.len();
|
||||
crate::dialogs::host::pump(&mut app, &ctx);
|
||||
let after = app.session.active().unwrap();
|
||||
assert_eq!(after.doc.info_title(), document.info_title(), "the destination's title stays untouched");
|
||||
assert_eq!(after.doc.metadata, document.metadata, "the destination's metadata stays untouched");
|
||||
assert_eq!(after.history.undo.len(), b_undo);
|
||||
assert!(matches!(held_state(&app), Some(HeldOk::Refused(_))));
|
||||
|
||||
activate(&mut app, 0);
|
||||
assert!(press_ok(&mut app), "a fresh confirmation can apply the original draft");
|
||||
let source = app.session.active().unwrap();
|
||||
assert_eq!(source.doc.info_title(), "Revised Source");
|
||||
assert_eq!(source.doc.metadata.author, "Ada");
|
||||
assert_eq!(source.doc.metadata.keywords, ["print"]);
|
||||
assert_eq!(source.history.undo.len(), a_undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reopened_file_info_confirmation_uses_the_new_drafts_document() {
|
||||
let mut app = windowed();
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("ui.fileInfoDialog", json!({})).unwrap();
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
app.run("ui.fileInfoDialog", json!({})).unwrap();
|
||||
set(&app, "title", json!("Revised Destination")).unwrap();
|
||||
assert!(press_ok(&mut app));
|
||||
assert_eq!(app.session.active().unwrap().doc.info_title(), "Revised Destination");
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
assert!(app.session.active().unwrap().history.undo.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template");
|
||||
|
||||
@@ -249,8 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue {
|
||||
|
||||
/// Opens the dialog on `value`.
|
||||
fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result<Value, String> {
|
||||
let document = app.session.active().ok_or("no document open")?.uid;
|
||||
let dialogs = app.dialogs().ok_or("no window")?;
|
||||
dialogs.with(|host| host.open(LayerOptionsDialog::new(value)));
|
||||
dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value)));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -410,6 +411,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) {
|
||||
/// the dialog open with the reason under its rows.
|
||||
pub(crate) struct LayerOptionsDialog {
|
||||
id: DialogId,
|
||||
document: u64,
|
||||
open: bool,
|
||||
value: LayerOptionsValue,
|
||||
held: HeldAnswer<LayerOptionsValue>,
|
||||
@@ -421,8 +423,8 @@ pub(crate) struct LayerOptionsDialog {
|
||||
|
||||
impl LayerOptionsDialog {
|
||||
/// The dialog over `value`.
|
||||
fn new(value: LayerOptionsValue) -> Self {
|
||||
LayerOptionsDialog { id: dialog_id(KEY), open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None }
|
||||
fn new(document: u64, value: LayerOptionsValue) -> Self {
|
||||
LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None }
|
||||
}
|
||||
|
||||
/// The OK filed by the user, once.
|
||||
@@ -571,7 +573,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
// The closed dialog's answer was run when OK was filed.
|
||||
let _ = dialogs.with(|host| host.take::<LayerOptionsDialog>());
|
||||
let Some(value) = dialogs.with(|host| host.get_mut::<LayerOptionsDialog>().and_then(LayerOptionsDialog::take_filed)) else { return };
|
||||
let Some((document, value)) = dialogs.with(|host| {
|
||||
let dialog = host.get_mut::<LayerOptionsDialog>()?;
|
||||
Some((dialog.document, dialog.take_filed()?))
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let (cmd, p) = params(&value);
|
||||
let sublayer = match cmd {
|
||||
"layer.new" => Some(false),
|
||||
@@ -579,8 +586,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
_ => None,
|
||||
};
|
||||
// Isolation mode can start while the dialog is open.
|
||||
let answer = match sublayer {
|
||||
Some(sublayer) if app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => {
|
||||
let answer = match app.session.active().filter(|st| st.uid == document) {
|
||||
None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))),
|
||||
Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => {
|
||||
Err(Label::from("exit isolation mode first"))
|
||||
}
|
||||
_ => {
|
||||
@@ -681,6 +689,48 @@ mod tests {
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_options_and_new_layers_follow_their_document() {
|
||||
for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] {
|
||||
let mut app = app();
|
||||
let source_id = app.session.active().unwrap().doc.layers[0].id;
|
||||
app.run("file.new", json!({"width": 160, "height": 160})).unwrap();
|
||||
let destination_id = app.session.active().unwrap().doc.layers[0].id;
|
||||
assert_eq!(destination_id, source_id, "the two documents reuse a layer ID");
|
||||
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
|
||||
activate(&mut app, 0);
|
||||
app.run(command, arguments).unwrap();
|
||||
set(&mut app, "name", json!("Source Draft"));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let dialog = open_id(&app);
|
||||
app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog));
|
||||
|
||||
let layers = |app: &VectorcraftApp| {
|
||||
let mut names = vec![];
|
||||
app.session.active().unwrap().doc.walk(|node| {
|
||||
if node.is_layer() {
|
||||
names.push(node.display_name());
|
||||
}
|
||||
});
|
||||
names
|
||||
};
|
||||
activate(&mut app, 1);
|
||||
let before = layers(&app);
|
||||
let b_undo = app.session.active().unwrap().history.undo.len();
|
||||
pump(&mut app, &ctx);
|
||||
assert_eq!(layers(&app), before, "the destination's layers stay unchanged for {command}");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo);
|
||||
assert!(matches!(app.dialogs().unwrap().with(|host| host.held_state(dialog)), Some(HeldOk::Refused(_))));
|
||||
|
||||
activate(&mut app, 0);
|
||||
let a_undo = app.session.active().unwrap().history.undo.len();
|
||||
ok(&mut app);
|
||||
assert!(!app.any_dialog_open());
|
||||
assert!(layers(&app).iter().any(|name| name == "Source Draft"));
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two layers with different options, the first plain and the second green, locked, in
|
||||
/// outline view and dimmed to 30%.
|
||||
fn two_layers(app: &mut VectorcraftApp) -> (NodeId, NodeId) {
|
||||
|
||||
@@ -134,6 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res
|
||||
let dialog = GridDialog::new(
|
||||
def,
|
||||
mode,
|
||||
app.session.active().map(|st| st.uid),
|
||||
(general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points),
|
||||
app.session.perspective_presets(),
|
||||
app.session.new_perspective_preset_name(),
|
||||
@@ -171,6 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) -
|
||||
pub(super) struct GridDialog {
|
||||
id: DialogId,
|
||||
mode: GridMode,
|
||||
/// The document whose grid Define Grid edits.
|
||||
source_document: Option<u64>,
|
||||
draft: GridDraft,
|
||||
/// The presets the Preset row offers, as the document and the preferences have them.
|
||||
presets: Vec<GridDefinition>,
|
||||
@@ -190,10 +193,18 @@ pub(super) struct GridDialog {
|
||||
}
|
||||
|
||||
impl GridDialog {
|
||||
fn new(def: GridDefinition, mode: GridMode, (ppi, bare_points): (f64, bool), presets: Vec<GridDefinition>, new_name: String) -> Self {
|
||||
fn new(
|
||||
def: GridDefinition,
|
||||
mode: GridMode,
|
||||
source_document: Option<u64>,
|
||||
(ppi, bare_points): (f64, bool),
|
||||
presets: Vec<GridDefinition>,
|
||||
new_name: String,
|
||||
) -> Self {
|
||||
let mut dialog = GridDialog {
|
||||
id: dialog_id(KIND),
|
||||
mode,
|
||||
source_document,
|
||||
draft: GridDraft { def },
|
||||
presets: Vec::new(),
|
||||
rows: Vec::new(),
|
||||
@@ -516,9 +527,12 @@ enum Next {
|
||||
Presets(String),
|
||||
}
|
||||
|
||||
fn file(app: &mut VectorcraftApp, mode: &GridMode, def: &GridDefinition) -> Result<Next, String> {
|
||||
fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option<u64>, def: &GridDefinition) -> Result<Next, String> {
|
||||
let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?;
|
||||
if *mode == GridMode::Define {
|
||||
if app.session.active().map(|st| st.uid) != source_document {
|
||||
return Err(tl!("Define Grid can only change the document where it was opened.").to_owned());
|
||||
}
|
||||
app.run("perspective.grid.define", params)?;
|
||||
return Ok(Next::Close);
|
||||
}
|
||||
@@ -546,10 +560,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
let filed = dialogs.with(|host| {
|
||||
let dialog = host.get_mut::<GridDialog>()?;
|
||||
dialog.set_presets(presets, new_name);
|
||||
dialog.held.take().map(|def| (dialog.mode.clone(), def))
|
||||
dialog.held.take().map(|def| (dialog.mode.clone(), dialog.source_document, def))
|
||||
});
|
||||
let Some((mode, def)) = filed else { return };
|
||||
let next = file(app, &mode, &def);
|
||||
let Some((mode, source_document, def)) = filed else { return };
|
||||
let next = file(app, &mode, source_document, &def);
|
||||
if let Err(why) = &next {
|
||||
app.status(why.clone());
|
||||
}
|
||||
|
||||
@@ -19,14 +19,15 @@ pub(crate) const CMD: &str = "artboard.rename";
|
||||
/// for several.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window")?;
|
||||
let (indices, name) = app.session.active().map_or((vec![], String::new()), |st| {
|
||||
let indices = crate::panels::artboards::picked(app, st.doc.artboards.len());
|
||||
let name = match indices.as_slice() {
|
||||
[one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()),
|
||||
_ => "",
|
||||
};
|
||||
(indices, name.to_owned())
|
||||
});
|
||||
let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?;
|
||||
let document = st.uid;
|
||||
let selected: Vec<_> =
|
||||
crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect();
|
||||
let name = match selected.as_slice() {
|
||||
[one] => one.name.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let artboards: Vec<_> = selected.iter().map(|board| board.id).collect();
|
||||
let mut fields = DialogFields::new();
|
||||
fields.set("name", name);
|
||||
let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| {
|
||||
@@ -39,6 +40,13 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
if name.trim().is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let st =
|
||||
app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?;
|
||||
let indices = artboards
|
||||
.iter()
|
||||
.map(|id| st.doc.artboards.iter().position(|board| board.id == *id))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?;
|
||||
if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) {
|
||||
app.status(e);
|
||||
}
|
||||
@@ -105,6 +113,51 @@ mod tests {
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_follows_the_original_artboards_after_reordering() {
|
||||
let mut app = app();
|
||||
app.session.set_tool_option("selected", &json!([0, 2]));
|
||||
open(&mut app).unwrap();
|
||||
app.run("artboard.reorder", json!({"index": 0, "to": 2})).unwrap();
|
||||
assert_eq!(names(&app), ["Artboard 2", "Artboard 3", "Artboard 1"]);
|
||||
let steps = app.session.active().unwrap().history.undo.len();
|
||||
rename(&mut app, "Page");
|
||||
assert_eq!(names(&app), ["Artboard 2", "Page-1", "Page-2"]);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_waits_for_the_document_it_opened_in() {
|
||||
let mut app = app();
|
||||
open(&mut app).unwrap();
|
||||
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
|
||||
let steps = app.session.active().unwrap().history.undo.len();
|
||||
rename(&mut app, "Source only");
|
||||
assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), steps);
|
||||
assert!(app.any_dialog_open(), "the original document can still answer");
|
||||
|
||||
app.session.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
rename(&mut app, "Source only");
|
||||
assert_eq!(names(&app), ["Source only", "Artboard 2", "Artboard 3"]);
|
||||
assert!(!app.any_dialog_open());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() {
|
||||
let mut app = app();
|
||||
app.session.set_tool_option("selected", &json!([0, 2]));
|
||||
open(&mut app).unwrap();
|
||||
app.run("artboard.delete", json!({"index": 2})).unwrap();
|
||||
app.run("artboard.duplicate", json!({"index": 1})).unwrap();
|
||||
let before = names(&app);
|
||||
let steps = app.session.active().unwrap().history.undo.len();
|
||||
rename(&mut app, "Page");
|
||||
assert_eq!(names(&app), before);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), steps);
|
||||
assert!(app.any_dialog_open());
|
||||
}
|
||||
|
||||
/// OK with an empty name or the name the artboard already has records no undo step.
|
||||
#[test]
|
||||
fn nothing_changes_for_an_empty_or_unchanged_name() {
|
||||
|
||||
@@ -137,6 +137,7 @@ impl ItemSource<usize> for Shown<'_> {}
|
||||
/// The saved-names dialog of one kind.
|
||||
pub(crate) struct SavedNamesDialog {
|
||||
id: DialogId,
|
||||
document: u64,
|
||||
names: SavedNames,
|
||||
draft: NamesDraft,
|
||||
/// The picked row, by its index in the draft; one at most.
|
||||
@@ -147,10 +148,10 @@ pub(crate) struct SavedNamesDialog {
|
||||
|
||||
impl SavedNamesDialog {
|
||||
/// The dialog over `list`, with the first name picked.
|
||||
fn new(names: SavedNames, list: Vec<String>) -> Self {
|
||||
fn new(document: u64, names: SavedNames, list: Vec<String>) -> Self {
|
||||
let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) };
|
||||
let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect();
|
||||
SavedNamesDialog { id: id_of(names.kind), names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() }
|
||||
SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() }
|
||||
}
|
||||
|
||||
/// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for
|
||||
@@ -326,8 +327,9 @@ impl StackDialog for SavedNamesDialog {
|
||||
/// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them).
|
||||
pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec<String>) -> Result<(), String> {
|
||||
list.truncate(names.max);
|
||||
let document = app.session.active().ok_or("no document open")?.uid;
|
||||
let dialogs = app.dialogs().ok_or("no window")?;
|
||||
dialogs.with(|host| host.open(SavedNamesDialog::new(names, list)));
|
||||
dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -335,18 +337,22 @@ pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec<St
|
||||
/// closes when the command took the edits, and stays open with the reason when it refused them.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let filed: Vec<(DialogId, &'static str, Vec<Value>)> = dialogs.with(|host| {
|
||||
let filed: Vec<_> = dialogs.with(|host| {
|
||||
host.open_dialogs()
|
||||
.into_iter()
|
||||
.filter_map(|open| {
|
||||
let dialog = host.get_mut_by_id::<SavedNamesDialog>(open.id)?;
|
||||
let edits = dialog.held.take()?;
|
||||
Some((open.id, dialog.names.command, edits))
|
||||
Some((open.id, dialog.document, dialog.names.command, edits))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
for (id, command, edits) in filed {
|
||||
let outcome = app.run(command, json!({ "edits": edits }));
|
||||
for (id, document, command, edits) in filed {
|
||||
let outcome = if app.session.active().is_some_and(|active| active.uid == document) {
|
||||
app.run(command, json!({ "edits": edits }))
|
||||
} else {
|
||||
Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned())
|
||||
};
|
||||
if let Err(reason) = &outcome {
|
||||
app.status(reason.clone());
|
||||
}
|
||||
@@ -357,3 +363,62 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn saved_names_edits_stay_with_their_document() {
|
||||
for is_view in [false, true] {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
|
||||
for size in [100, 200] {
|
||||
app.run("file.new", json!({"width": size, "height": size})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
for name in ["Shared", "Spare"] {
|
||||
app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap();
|
||||
}
|
||||
}
|
||||
let names = |app: &mut VectorcraftApp| {
|
||||
if is_view {
|
||||
let views = &app.session.active().unwrap().doc.views;
|
||||
json!(views.iter().map(|view| &view.name).collect::<Vec<_>>())
|
||||
} else {
|
||||
app.run("select.savedList", json!({})).unwrap()
|
||||
}
|
||||
};
|
||||
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
|
||||
activate(&mut app, 0);
|
||||
let kind = if is_view {
|
||||
crate::dialogs::edit_views::open(&mut app).unwrap();
|
||||
crate::dialogs::edit_views::KIND
|
||||
} else {
|
||||
crate::dialogs::edit_selection::open(&mut app).unwrap();
|
||||
crate::dialogs::edit_selection::KIND
|
||||
};
|
||||
let id = id_of(kind);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let host = app.dialogs().unwrap();
|
||||
host.with(|h| {
|
||||
h.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap();
|
||||
h.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap();
|
||||
h.confirm_by_id(&ctx, id);
|
||||
});
|
||||
|
||||
activate(&mut app, 1);
|
||||
let b_undo = app.session.active().unwrap().history.undo.len();
|
||||
pump(&mut app, &ctx);
|
||||
assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "the destination's saved names stay unchanged for {kind}");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo);
|
||||
assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
|
||||
|
||||
activate(&mut app, 0);
|
||||
let a_undo = app.session.active().unwrap().history.undo.len();
|
||||
host.with(|h| h.confirm_by_id(&ctx, id));
|
||||
pump(&mut app, &ctx);
|
||||
assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted)));
|
||||
assert_eq!(names(&mut app), json!(["Revised"]));
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,39 @@ fn define_grid_opens_on_the_grid_and_applies_its_fields() {
|
||||
assert_eq!((grid(&app).cell, grid(&app).viewing_angle()), (n.cell, n.viewing_angle()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn define_grid_applies_only_to_the_document_where_it_opened() {
|
||||
let mut app = app();
|
||||
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
|
||||
let destination = app.session.active().unwrap();
|
||||
let destination_uid = destination.uid;
|
||||
let destination_undo = destination.history.undo.len();
|
||||
let destination_grid = grid(&app);
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
let source_uid = app.session.active().unwrap().uid;
|
||||
app.run("ui.perspectiveGridDialog", json!({})).unwrap();
|
||||
set(&mut app, "rightColor", json!("#112233")).unwrap();
|
||||
let ctx = window(&app);
|
||||
let id = dialog_id(super::perspective_grid::KIND);
|
||||
host(&app, |h| {
|
||||
assert!(!h.confirm_by_id(&ctx, id));
|
||||
assert_eq!(h.held_state(id), Some(HeldOk::Waiting));
|
||||
});
|
||||
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
super::perspective_grid::pump(&mut app, &ctx);
|
||||
assert_eq!(app.session.active().unwrap().uid, destination_uid);
|
||||
assert_eq!(grid(&app), destination_grid, "the first document's draft leaves the active grid alone");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), destination_undo);
|
||||
assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_))));
|
||||
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().uid, source_uid);
|
||||
ok(&mut app);
|
||||
assert_eq!(kind(&app), None);
|
||||
assert_eq!(grid(&app).right_color.hex(), "#112233");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn define_grid_loads_and_saves_presets() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -67,6 +67,36 @@ fn stays_open(app: &mut VectorcraftApp) {
|
||||
assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_queued_export_requires_fresh_confirmation_after_switching_documents() {
|
||||
use craft::ui::dialog::{HeldOk, dialog_id};
|
||||
|
||||
let (mut app, log) = app(1, true);
|
||||
let source = app.session.active().unwrap().uid;
|
||||
app.run("file.new", json!({"width": 40, "height": 30})).unwrap();
|
||||
app.run("artboard.rename", json!({"indices": [0], "name": "Destination"})).unwrap();
|
||||
let destination = app.session.active().unwrap().uid;
|
||||
app.run("window.previousDocument", json!({})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().uid, source);
|
||||
open(&mut app);
|
||||
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let dialogs = app.dialogs().unwrap();
|
||||
let id = dialog_id(export_for_screens::KIND);
|
||||
dialogs.with(|host| {
|
||||
assert!(!host.confirm_by_id(&ctx, id));
|
||||
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
|
||||
});
|
||||
app.run("window.nextDocument", json!({})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().uid, destination);
|
||||
export_for_screens::pump(&mut app, &ctx);
|
||||
|
||||
assert!(log.borrow().is_empty(), "the earlier OK cannot download from the destination tab");
|
||||
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
|
||||
try_confirm(&mut app).unwrap();
|
||||
assert_eq!(log.borrow().iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), ["Destination.png"]);
|
||||
}
|
||||
|
||||
fn temp_folder(tag: &str) -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("vc-efs-{tag}-{}", std::process::id()))
|
||||
}
|
||||
|
||||
@@ -273,6 +273,8 @@ pub struct VectorcraftApp {
|
||||
pub(crate) missing_font_edit_token: Option<u64>,
|
||||
/// The hosted dialogs whose OK the app answers, one record each.
|
||||
pub(crate) held: dialogs::host::Held,
|
||||
/// The document whose settings the open Document Setup dialog edits.
|
||||
pub(crate) document_setup_source: Option<u64>,
|
||||
/// The undo step each value gesture in progress edits under: a scrub or a slider drag is one
|
||||
/// step however many values it sets.
|
||||
pub(crate) edit_scopes: HashMap<GestureId, UndoScope>,
|
||||
|
||||
@@ -41,6 +41,8 @@ pub enum PanelDrag {
|
||||
/// panel order.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SwatchRows {
|
||||
/// The document whose rows the drag started on.
|
||||
pub document: u64,
|
||||
pub grabbed: String,
|
||||
pub names: Vec<String>,
|
||||
/// The names are colour groups.
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::contract::{Scroll, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Props as _, Scroll, Show as _, ShowContainer as _};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::menu::PanelRow;
|
||||
@@ -132,19 +132,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let opts = app.ui.css_properties_panel.options.clone();
|
||||
let all = !selected && app.ui.css_properties_panel.all;
|
||||
let Some(shown) = shown(app, &opts, all) else { return };
|
||||
Stack::new().fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| {
|
||||
let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe")));
|
||||
if shown.rules > 0 {
|
||||
SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui);
|
||||
} else if selected {
|
||||
let hint = tl!("The selected objects have no CSS of their own (see below).");
|
||||
Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui);
|
||||
} else {
|
||||
let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document.");
|
||||
Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui);
|
||||
}
|
||||
});
|
||||
let notes = (shown.more > 0)
|
||||
let notes: Vec<_> = (shown.more > 0)
|
||||
.then(|| crate::i18n::tn(shown.more as u64, "{n} more rule: Export writes it.", "{n} more rules: Export writes every one."))
|
||||
.into_iter()
|
||||
.chain((shown.skipped > 0).then(|| {
|
||||
@@ -154,23 +142,50 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
"{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu.",
|
||||
)
|
||||
}))
|
||||
.chain(shown.warnings.iter().map(|w| sentence(w)));
|
||||
for n in notes {
|
||||
Text::new(n).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
.chain(shown.warnings.iter().map(|w| sentence(w)))
|
||||
.collect();
|
||||
let has_css = shown.rules > 0;
|
||||
let scope = if all { "all" } else { "selection" };
|
||||
// Generate at the start edge; Export at the end edge with Copy before it.
|
||||
let footer = FooterBar::actions([
|
||||
let actions = [
|
||||
FooterAction::new(IconId::new("sparkles"), tl!("Generate CSS: the whole document's CSS while nothing is selected"))
|
||||
.pressed(all)
|
||||
.enabled(!selected),
|
||||
FooterAction::new(IconId::new("save"), if all { tl!("Export All…") } else { tl!("Export Selected CSS…") }).enabled(has_css),
|
||||
FooterAction::new(IconId::new("copy"), if all { tl!("Copy All Styles") } else { tl!("Copy Selected Style") }).enabled(has_css),
|
||||
])
|
||||
.at_start(1)
|
||||
.show_footer(ui);
|
||||
match footer.picked {
|
||||
];
|
||||
let mut picked = None;
|
||||
let notes_room = (ui.available_height() / 3.0).min(72.0);
|
||||
Stack::new()
|
||||
.fill()
|
||||
.footer(|ui, _| {
|
||||
if !notes.is_empty() {
|
||||
Stack::new().label(tl!("Notes")).fill_width().scroll(Scroll::vertical()).room_height(notes_room).show(ui, |ui, _| {
|
||||
for note in ¬es {
|
||||
Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
let footer = FooterBar::actions(actions.clone()).at_start(1).show_footer(ui);
|
||||
if !ui.is_sizing_pass() {
|
||||
picked = footer.picked;
|
||||
}
|
||||
})
|
||||
.show(ui, |ui, _| {
|
||||
Stack::new().label(tl!("CSS Properties")).fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| {
|
||||
let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe")));
|
||||
if shown.rules > 0 {
|
||||
SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui);
|
||||
} else if selected {
|
||||
let hint = tl!("The selected objects have no CSS of their own (see below).");
|
||||
Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui);
|
||||
} else {
|
||||
let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document.");
|
||||
Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui);
|
||||
}
|
||||
});
|
||||
});
|
||||
match picked {
|
||||
Some(0) => {
|
||||
crate::menus::invoke(app, GENERATE, json!({}));
|
||||
}
|
||||
@@ -311,3 +326,39 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Resul
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
#[test]
|
||||
fn generated_css_notices_keep_the_actions_in_a_short_panel() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({ "width": 100, "height": 100 })).unwrap();
|
||||
for card in 0..12 {
|
||||
let id = app.run("shape.rectangle", json!({ "x": 0, "y": 0, "width": 20, "height": 20 })).unwrap()["id"].clone();
|
||||
app.run("layer.setProps", json!({ "id": id, "name": format!("Card-{card}") })).unwrap();
|
||||
}
|
||||
app.run("shape.ellipse", json!({ "x": 30, "y": 0, "width": 20, "height": 20 })).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let options = CssOptions { unnamed: false, ..CssOptions::default() };
|
||||
let styles = shown(&mut app, &options, true).unwrap();
|
||||
assert_eq!((styles.rules, styles.skipped), (12, 1));
|
||||
app.ui.css_properties_panel = CssPropertiesPanel { options, all: true };
|
||||
|
||||
let mut panel = Panel::new(app, show);
|
||||
let room = egui::vec2(220.0, 220.0);
|
||||
panel.room(room).frame();
|
||||
panel.frame();
|
||||
for name in ["Copy All Styles", "Export All…"] {
|
||||
let action = panel.rect(name);
|
||||
assert!(action.bottom() <= room.y && action.right() <= room.x, "{name} overflows the panel at {action:?}");
|
||||
assert!(panel.enabled(name), "{name} is enabled when there is CSS");
|
||||
}
|
||||
let notice = panel.rect("1 unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.");
|
||||
assert!(notice.top() >= 0.0 && notice.bottom() <= panel.rect("Copy All Styles").top(), "the notice fits above the actions: {notice:?}");
|
||||
assert!(notice.left() >= 0.0 && notice.right() <= room.x, "the notice wraps within the panel: {notice:?}");
|
||||
}
|
||||
}
|
||||
@@ -13,9 +13,9 @@ use std::sync::Arc;
|
||||
|
||||
use craft::behavior::CanvasTransform;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::menu::PanelRow;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView, PreviewZoom};
|
||||
use craft::ui::pickers::Select;
|
||||
@@ -200,30 +200,43 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
// The highlighted art takes the theme's error colour.
|
||||
let highlight = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.solid);
|
||||
let compact = ui.available_width() < Env::of(ui).tokens.size.plot.width;
|
||||
let mut set = app.ui.flattener_preview.clone();
|
||||
let mut refresh_now = false;
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Row::new().fill_width().wrap(true).show(ui, |ui, _| {
|
||||
refresh_now = Button::new(tl!("Refresh")).tooltip(tl!("Preview the document as it is now")).show(ui).clicked();
|
||||
let entries = Highlight::ALL.map(|h| Entry::new(h, h.label()));
|
||||
Select::new(tl!("Highlight"), Bind::bound(&mut set.highlight), &entries).show(ui);
|
||||
let picker = Select::new(tl!("Highlight"), Bind::bound(&mut set.highlight), &entries);
|
||||
let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker };
|
||||
picker.show(ui);
|
||||
});
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Row::new().fill_width().wrap(true).show(ui, |ui, _| {
|
||||
Text::new(tl!("Overprints:")).shade(Shade::Muted).show(ui);
|
||||
let entries = Overprints::ALL.map(|o| Entry::new(o, o.label()));
|
||||
Select::new(tl!("Overprints"), Bind::bound(&mut set.overprints), &entries).show(ui);
|
||||
let picker = Select::new(tl!("Overprints"), Bind::bound(&mut set.overprints), &entries);
|
||||
let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker };
|
||||
picker.show(ui);
|
||||
});
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let preset_id = ui.scope_id().with("flattener-preset-row");
|
||||
let mut preset = |ui: &mut Ui| {
|
||||
Text::new(tl!("Preset:")).shade(Shade::Muted).show(ui);
|
||||
let names = flatten::preset_names(app);
|
||||
let mut fields = DialogFields::from_pairs([("preset", set.preset.clone())]);
|
||||
flatten::preset_picker(ui, &mut fields, "preset", &names, custom(app));
|
||||
if let Some(name) = fields.text("preset")
|
||||
&& name != set.preset
|
||||
let is_custom = custom(app);
|
||||
let current = if is_custom { String::new() } else { set.preset.clone() };
|
||||
let mut fields = DialogFields::from_pairs([("preset", current.clone())]);
|
||||
flatten::preset_picker(ui, &mut fields, "preset", &names, is_custom);
|
||||
if !ui.is_sizing_pass()
|
||||
&& let Some(name) = fields.text("preset").filter(|name| *name != current)
|
||||
&& let Some(p) = app.session.flattener_preset(name)
|
||||
{
|
||||
(set.preset, set.options) = (p.name, p.options);
|
||||
}
|
||||
});
|
||||
};
|
||||
if compact {
|
||||
Stack::new().id(preset_id).fill_width().show(ui, |ui, _| preset(ui));
|
||||
} else {
|
||||
Row::new().id(preset_id).fill_width().wrap(true).show(ui, |ui, _| preset(ui));
|
||||
}
|
||||
if set.show_options {
|
||||
Divider::horizontal().show(ui);
|
||||
let params = flatten::option_params(&[], "");
|
||||
@@ -285,11 +298,16 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32,
|
||||
// At scale 1 the picture is the fit of the well (width `w`, height `w / ASPECT`), so the zoom reads relative to the fit.
|
||||
let s = (f64::from(w) / shot.fit.width()).min(f64::from(w / ASPECT) / shot.fit.height());
|
||||
let size = vec2((shot.fit.width() * s) as f32, (shot.fit.height() * s) as f32);
|
||||
let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view)
|
||||
let pane = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view)
|
||||
.aspect(ASPECT)
|
||||
.click_centres(false)
|
||||
.tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit"))
|
||||
.show(ui);
|
||||
.tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit"));
|
||||
let out = if w < Env::of(ui).tokens.size.plot.width {
|
||||
let (_, room) = ui.allocate_space(vec2(w, w / ASPECT));
|
||||
pane.show_at(ui, room)
|
||||
} else {
|
||||
pane.show(ui)
|
||||
};
|
||||
*view = match out.clicked {
|
||||
Some(at) => {
|
||||
let factor = if craft::ui::runtime::pointer::frame(ui.ctx()).pick_mods.alt { 0.5 } else { 2.0 };
|
||||
@@ -484,6 +502,65 @@ mod tests {
|
||||
assert_eq!(back.flattener_preview, app.ui.flattener_preview);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flattener_selectors_and_preview_fit_a_narrow_dock() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app(), show);
|
||||
let width = 100.0;
|
||||
panel.room(vec2(width, 520.0)).frame();
|
||||
panel.frame();
|
||||
for name in ["Highlight", "Overprints", "Preset:"] {
|
||||
let rect = panel.rect_role(name, Role::COMBO_BOX);
|
||||
assert!(rect.left() >= 0.0 && rect.right() <= width, "{name} overflows the dock at {rect:?}");
|
||||
}
|
||||
let pane = panel.rect("Flattener Preview");
|
||||
assert!(pane.left() >= 0.0 && pane.right() <= width, "preview overflows the dock at {pane:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flattener_selectors_keep_their_caption_rows_when_the_panel_is_wide() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app(), show);
|
||||
panel.room(vec2(440.0, 600.0)).frame();
|
||||
panel.frame();
|
||||
for (caption, role, picker) in
|
||||
[("Refresh", Role::BUTTON, "Highlight"), ("Overprints:", Role::LABEL, "Overprints"), ("Preset:", Role::LABEL, "Preset:")]
|
||||
{
|
||||
let row = panel.rect_role(caption, role);
|
||||
let field = panel.rect_role(picker, Role::COMBO_BOX);
|
||||
assert!(field.left() >= row.right() && field.center().y >= row.top() && field.center().y <= row.bottom(), "{picker} is below {caption}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_compact_flattener_applies_a_preset_and_refreshes_the_snapshot() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let mut app = app();
|
||||
command(&mut app, &json!({"preset": "high", "options": {"balance": 12}})).unwrap();
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
|
||||
panel.room(vec2(100.0, 520.0)).frame();
|
||||
panel.frame();
|
||||
panel.click_role("Preset:", Role::COMBO_BOX);
|
||||
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
assert_eq!(panel.app().ui.flattener_preview.options.balance, 12.0);
|
||||
panel.click_role("Preset:", Role::COMBO_BOX);
|
||||
panel.click("High Resolution");
|
||||
let expected = FlattenOptions::preset("high").unwrap();
|
||||
assert_eq!(panel.app().ui.flattener_preview.options, expected);
|
||||
panel.app().run("select.all", json!({})).unwrap();
|
||||
panel.app().run("transparency.set", json!({"opacity": 100})).unwrap();
|
||||
assert!(stale(&panel.app()), "the live document changed");
|
||||
panel.click("Refresh");
|
||||
assert!(!stale(&panel.app()), "Refresh takes a new snapshot");
|
||||
let well = panel.rect("Flattener Preview");
|
||||
panel.click_at(well.center());
|
||||
assert!(!panel.app().flattener_preview.view.fit, "the compact preview still zooms");
|
||||
}
|
||||
|
||||
/// The panel in a fixture, and the preview pane's bounds.
|
||||
fn shown_pane() -> (std::rc::Rc<std::cell::RefCell<VectorcraftApp>>, craft::ui::testing::Fixture, egui::Rect) {
|
||||
let app = std::rc::Rc::new(std::cell::RefCell::new(app()));
|
||||
|
||||
@@ -14,21 +14,26 @@ use std::sync::Arc;
|
||||
// PLAN: assumed import paths of the framework items below: `craft::ui::primitives::IconId`,
|
||||
// `craft::ui::runtime::commands::{CommandState, CommandStates}`, `craft::ui::menu::PanelRow`,
|
||||
// `craft::ui::patterns::presets::*`, `crate::edits` (widgets-w13) and `crate::chrome::rank` (chrome-w16).
|
||||
use craft::behavior::IconId;
|
||||
use craft::behavior::{IconId, Metrics, Proposal, ScrollPos, Sense};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::buttons::{Button, IconButton, SplitButton, SplitMenu, ToggleButton};
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{
|
||||
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Entry, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing,
|
||||
};
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
use craft::ui::form::{Field, SliderField, SliderFieldLayout};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::layout::BodyLayout;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::menu::PanelRow;
|
||||
use craft::ui::patterns::presets::{
|
||||
NameCheck, NamedPresetEvent, NamedPresetRow, NamedPresetStyle, PickerField, PresetError, PresetPicker, PresetRow, PresetSource, PresetState,
|
||||
};
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::commands::{CommandState, CommandStates};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::sections::Section;
|
||||
use craft::ui::style::{ComponentStyle, StyleCx};
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView};
|
||||
@@ -786,7 +791,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
st.preset = "Default".into();
|
||||
st.params = list.presets.first().map(|p| p.1.clone()).unwrap_or_default();
|
||||
}
|
||||
let (is_trace, is_image, any_trace) = (t.is_trace, t.is_image, t.any_trace);
|
||||
// The saved preset changes since the last frame apply to the panel's settings before the selected object's
|
||||
// settings, which `sync_with_object` resolves against every change, are adopted.
|
||||
follow_preset_changes(app, &mut st, &list.presets);
|
||||
@@ -794,6 +798,135 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect();
|
||||
sync_with_object(&mut st, t.stored.clone(), t.object, &list.presets, &changes)
|
||||
};
|
||||
let preview = app.ui.image_trace_preview;
|
||||
let mut actions = (false, false, false);
|
||||
let stack = Stack::new().label(tl!("Image Trace")).fill().scroll(Scroll::vertical());
|
||||
let env = Env::of(ui);
|
||||
let settings_row = env.tokens.size.control.md + env.tokens.space.gap.row;
|
||||
let footer = Stack::new().id_salt("trace-footer-measure").measure_in(ui, Proposal::Width(ui.available_width()), |ui, _| {
|
||||
show_footer(ui, preview, &t);
|
||||
});
|
||||
let compact_offset = ui.scope_id().with("trace-compact-offset");
|
||||
let settings = if ui.available_height() >= footer.y + settings_row {
|
||||
if !ui.is_sizing_pass() {
|
||||
ui.ctx().data_mut(|data| data.remove::<ScrollPos>(compact_offset));
|
||||
}
|
||||
stack.footer(|ui, _| actions = show_footer(ui, preview, &t)).show(ui, |ui, _| show_settings(app, ui, &mut st, &list, &t))
|
||||
} else {
|
||||
// When the footer moves into the scroll area, start with its actions in view.
|
||||
let before = ui.ctx().data(|data| data.get_temp(compact_offset)).unwrap_or_default();
|
||||
let mut offset = before;
|
||||
let shown = CompactSettings::new(Bind::bound(&mut offset)).show(ui, |ui, _| {
|
||||
actions = show_actions(ui, preview, &t);
|
||||
Divider::horizontal().show(ui);
|
||||
show_settings(app, ui, &mut st, &list, &t)
|
||||
});
|
||||
if offset != before && !ui.is_sizing_pass() {
|
||||
ui.ctx().data_mut(|data| data.insert_temp(compact_offset, offset));
|
||||
}
|
||||
shown
|
||||
};
|
||||
let (mut retrace, held) = settings.inner.unwrap_or_default();
|
||||
let (preview_toggled, trace_clicked, expand_clicked) = actions;
|
||||
if !ui.is_sizing_pass() {
|
||||
hold_source(app, t.any_trace && held);
|
||||
}
|
||||
if preview_toggled {
|
||||
run_reporting(app, "imageTrace.preview", json!({}));
|
||||
}
|
||||
if trace_clicked {
|
||||
trace(app, &mut st);
|
||||
}
|
||||
if expand_clicked {
|
||||
run_reporting(app, "imageTrace.expand", json!({}));
|
||||
}
|
||||
// Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is
|
||||
// traced with the settings that waited in the panel. With no Image Trace object selected, it is
|
||||
// traced when it is selected again. An object whose settings waited while another object was
|
||||
// selected is traced when it is selected again with Preview on.
|
||||
let preview = app.ui.image_trace_preview;
|
||||
retrace |= preview && (st.preview_off || restored) && t.is_trace && st.params != st.synced["params"];
|
||||
if t.is_trace || !preview {
|
||||
st.preview_off = !preview;
|
||||
}
|
||||
cancel_disabled_ignore_sampler(app, &st.params);
|
||||
if retrace && t.is_trace && preview {
|
||||
trace(app, &mut st);
|
||||
}
|
||||
app.ui.image_trace_panel.shown = st;
|
||||
}
|
||||
|
||||
/// The very short layout needs a bound offset so returning to it shows the actions first.
|
||||
#[derive(craft::ui::contract::Component, craft::ui::contract::Props)]
|
||||
#[component(container, unregistered)]
|
||||
struct CompactSettings<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
#[container]
|
||||
props: ContainerProps,
|
||||
offset: Bind<'a, ScrollPos>,
|
||||
}
|
||||
|
||||
impl<'a> CompactSettings<'a> {
|
||||
fn new(offset: Bind<'a, ScrollPos>) -> Self {
|
||||
let props = ContainerProps::new().sizing(Sizing::Fill).layout(BodyLayout::stack()).scroll(Scroll::vertical());
|
||||
Self { common: Common::new(), props, offset }.label(tl!("Image Trace"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
struct CompactSettingsStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
impl Component for CompactSettings<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
type Style = CompactSettingsStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: CompactSettingsStyleKey) -> CompactSettingsStyle {
|
||||
CompactSettingsStyle { metrics: Metrics::new() }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn scroll(&mut self) -> Option<BindMut<'_, ScrollPos>> {
|
||||
Some(self.offset.reborrow())
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Container for CompactSettings<'_> {}
|
||||
|
||||
fn show_footer(ui: &mut Ui, preview: bool, target: &Target) -> (bool, bool, bool) {
|
||||
Divider::horizontal().show(ui);
|
||||
show_actions(ui, preview, target)
|
||||
}
|
||||
|
||||
fn show_actions(ui: &mut Ui, preview: bool, target: &Target) -> (bool, bool, bool) {
|
||||
let mut value = preview;
|
||||
let mut trace_clicked = false;
|
||||
let mut expand_clicked = false;
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui);
|
||||
let can_trace = target.is_trace || target.is_image;
|
||||
let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace);
|
||||
if !can_trace {
|
||||
trace_button = trace_button.tooltip(tl!("Select an image to trace"));
|
||||
}
|
||||
trace_clicked = trace_button.show(ui).clicked();
|
||||
expand_clicked = Button::new(tl!("Expand")).enabled(target.any_trace).show(ui).clicked();
|
||||
});
|
||||
(value != preview, trace_clicked, expand_clicked)
|
||||
}
|
||||
|
||||
fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list: &PresetList, t: &Target) -> (bool, bool) {
|
||||
let mut retrace = false;
|
||||
|
||||
// A preset button chooses its preset as the Preset row does; the button of the panel's
|
||||
@@ -804,7 +937,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let mut on = was;
|
||||
ToggleButton::new(label, Bind::bound(&mut on)).tooltip(preset_label(name)).show(ui);
|
||||
if on && !was {
|
||||
retrace |= choose_preset(&mut st, &list.presets, name);
|
||||
retrace |= choose_preset(st, &list.presets, name);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -824,7 +957,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
.show(ui);
|
||||
for event in preset_row.events {
|
||||
match event {
|
||||
NamedPresetEvent::Apply(name) => retrace |= choose_preset(&mut st, &list.presets, &name),
|
||||
NamedPresetEvent::Apply(name) => retrace |= choose_preset(st, &list.presets, &name),
|
||||
NamedPresetEvent::Create { name, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": name, "params": st.params })),
|
||||
NamedPresetEvent::Rename { key, text, .. } => run_reporting(app, "imageTrace.presets.save", json!({ "name": key, "newName": text })),
|
||||
NamedPresetEvent::Delete(name) => run_reporting(app, "imageTrace.presets.delete", json!({ "name": name })),
|
||||
@@ -845,21 +978,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
picked = view_pick(ui, st.view);
|
||||
let tip = tl!("Press and hold to view the source image");
|
||||
held =
|
||||
IconButton::new(IconId::new("eye")).label(tip).tooltip(tip).selected(app.ui.trace_hold_source.is_some()).enabled(any_trace).show(ui).held;
|
||||
held = IconButton::new(IconId::new("eye"))
|
||||
.label(tip)
|
||||
.tooltip(tip)
|
||||
.selected(app.ui.trace_hold_source.is_some())
|
||||
.enabled(t.any_trace)
|
||||
.show(ui)
|
||||
.held;
|
||||
});
|
||||
if let Some(v) = picked {
|
||||
st.view = v;
|
||||
if any_trace {
|
||||
if t.any_trace {
|
||||
set_view(app, v);
|
||||
}
|
||||
}
|
||||
hold_source(app, any_trace && held);
|
||||
split_row(app, ui);
|
||||
|
||||
let data = RowsData::of(app);
|
||||
let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel);
|
||||
let sampler = Sampler { enabled: is_trace || is_image, armed: app.ui.trace_ignore_sampler.is_some() };
|
||||
let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() };
|
||||
let advanced = Section::new(tl!("Advanced"))
|
||||
.open(Bind::bound(&mut app.ui.image_trace_advanced))
|
||||
.show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler)))
|
||||
@@ -880,7 +1017,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
cancel_ignore_sampler(app, true);
|
||||
}
|
||||
|
||||
Divider::horizontal().show(ui);
|
||||
if let Some((p, a, c)) = st.info {
|
||||
Text::new(crate::i18n::fmt(
|
||||
tl!("Paths: {paths} Anchors: {anchors} Colors: {colors}"),
|
||||
@@ -889,43 +1025,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
.shade(Shade::Muted)
|
||||
.show(ui);
|
||||
}
|
||||
let (mut preview_toggled, mut trace_clicked, mut expand_clicked) = (false, false, false);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let preview = app.ui.image_trace_preview;
|
||||
let mut value = preview;
|
||||
Checkbox::new(Bind::bound(&mut value)).label(tl!("Preview")).show(ui);
|
||||
preview_toggled = value != preview;
|
||||
let can_trace = is_trace || is_image;
|
||||
let mut trace_button = Button::new(tl!("Trace")).enabled(can_trace);
|
||||
if !can_trace {
|
||||
trace_button = trace_button.tooltip(tl!("Select an image to trace"));
|
||||
}
|
||||
trace_clicked = trace_button.show(ui).clicked();
|
||||
expand_clicked = Button::new(tl!("Expand")).enabled(any_trace).show(ui).clicked();
|
||||
});
|
||||
if preview_toggled {
|
||||
run_reporting(app, "imageTrace.preview", json!({}));
|
||||
}
|
||||
if trace_clicked {
|
||||
trace(app, &mut st);
|
||||
}
|
||||
if expand_clicked {
|
||||
run_reporting(app, "imageTrace.expand", json!({}));
|
||||
}
|
||||
// Preview turned on (the checkbox, `imageTrace.preview` or `ui.set`): the selected object is
|
||||
// traced with the settings that waited in the panel. With no Image Trace object selected, it is
|
||||
// traced when it is selected again. An object whose settings waited while another object was
|
||||
// selected is traced when it is selected again with Preview on.
|
||||
let preview = app.ui.image_trace_preview;
|
||||
retrace |= preview && (st.preview_off || restored) && is_trace && st.params != st.synced["params"];
|
||||
if is_trace || !preview {
|
||||
st.preview_off = !preview;
|
||||
}
|
||||
cancel_disabled_ignore_sampler(app, &st.params);
|
||||
if retrace && is_trace && preview {
|
||||
trace(app, &mut st);
|
||||
}
|
||||
app.ui.image_trace_panel.shown = st;
|
||||
(retrace, held)
|
||||
}
|
||||
|
||||
/// The panel menu's rows: Release and Expand act on the selected Image Trace objects.
|
||||
|
||||
@@ -99,6 +99,90 @@ fn traced_app_with_ink(ink: u8) -> VectorcraftApp {
|
||||
app
|
||||
}
|
||||
|
||||
fn scroll_settings(panel: &mut Panel, dy: f32) {
|
||||
panel.scroll_at(egui::pos2(30.0, 30.0), dy);
|
||||
panel.advance(1.0);
|
||||
panel.frame();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_trace_and_expand_stay_reachable_in_a_compact_panel() {
|
||||
let mut app = traced_app();
|
||||
app.run("imageTrace.release", json!({})).unwrap();
|
||||
app.ui.image_trace_advanced = true;
|
||||
let source = first_selected(&app).unwrap();
|
||||
assert!(matches!(source.kind, NodeKind::Image(_)));
|
||||
let mut panel = panel_over(app);
|
||||
assert!(panel.rect_role("Image Trace", craft::ui::contract::Role::GROUP).is_positive());
|
||||
for size in [egui::vec2(148.0, 480.0), egui::vec2(240.0, 170.0), egui::vec2(148.0, 170.0)] {
|
||||
panel.room(size);
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let room = egui::Rect::from_min_size(egui::Pos2::ZERO, size);
|
||||
for label in ["Preview", "Trace", "Expand"] {
|
||||
assert!(panel.in_view(label), "{label} is clipped at {size:?}");
|
||||
let rect = panel.rect(label);
|
||||
assert!(room.contains_rect(rect), "the whole {label} control {rect:?} fits at {size:?}");
|
||||
}
|
||||
assert!(panel.enabled("Trace"));
|
||||
assert!(!panel.enabled("Expand"));
|
||||
}
|
||||
let preview = panel.app().ui.image_trace_preview;
|
||||
panel.click("Preview");
|
||||
assert_ne!(panel.app().ui.image_trace_preview, preview);
|
||||
|
||||
let action = panel.rect("Trace");
|
||||
let first_preset = panel.rect("Auto Color").top();
|
||||
scroll_settings(&mut panel, -1000.0);
|
||||
assert!(!panel.shows("Auto Color") || panel.rect("Auto Color").top() < first_preset, "the settings scroll");
|
||||
assert_eq!(panel.rect("Trace"), action, "scrolling settings leaves the action in place");
|
||||
let ignore = shown(&panel).params["ignoreWhite"].clone();
|
||||
panel.click("Ignore Color");
|
||||
assert_ne!(shown(&panel).params["ignoreWhite"], ignore, "scrolling reaches the end of Advanced");
|
||||
|
||||
panel.click("Trace");
|
||||
assert!(selected_trace(&panel.app()).is_some());
|
||||
assert!(panel.enabled("Expand"));
|
||||
panel.click("Expand");
|
||||
assert!(selected_trace(&panel.app()).is_none());
|
||||
assert!(!is_trace(&first_selected(&panel.app()).unwrap()));
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
assert!(selected_trace(&panel.app()).is_some());
|
||||
|
||||
// A single action row needs less height than the wrapped footer in the narrow panel.
|
||||
panel.room(egui::vec2(240.0, 100.0));
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
scroll_settings(&mut panel, 1000.0);
|
||||
let action = panel.rect("Trace");
|
||||
let first_preset = panel.rect("Auto Color").top();
|
||||
scroll_settings(&mut panel, -1000.0);
|
||||
assert!(!panel.shows("Auto Color") || panel.rect("Auto Color").top() < first_preset, "the short settings viewport scrolls");
|
||||
assert!(panel.in_view("Trace"));
|
||||
assert_eq!(panel.rect("Trace"), action, "a short panel still pins the footer when the actions fit on one line");
|
||||
|
||||
// Shorten the panel while the settings-only body remains scrolled to Advanced.
|
||||
panel.room(egui::vec2(148.0, 68.0));
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let preview = panel.app().ui.image_trace_preview;
|
||||
panel.click("Preview");
|
||||
assert_ne!(panel.app().ui.image_trace_preview, preview, "Preview starts in view in a very short panel");
|
||||
let ignore = shown(&panel).params["ignoreWhite"].clone();
|
||||
scroll_settings(&mut panel, -1000.0);
|
||||
panel.click("Ignore Color");
|
||||
assert_ne!(shown(&panel).params["ignoreWhite"], ignore, "a very short panel still scrolls to the last setting");
|
||||
|
||||
panel.room(egui::vec2(240.0, 100.0));
|
||||
panel.frame();
|
||||
panel.room(egui::vec2(148.0, 68.0));
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let preview = panel.app().ui.image_trace_preview;
|
||||
panel.click("Preview");
|
||||
assert_ne!(panel.app().ui.image_trace_preview, preview, "shrinking a second time starts at the actions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source() {
|
||||
let mut app = traced_app();
|
||||
|
||||
@@ -96,7 +96,8 @@ pub(crate) struct LinksModel {
|
||||
pub(super) show: Option<(u64, u64)>,
|
||||
nested: NestedPicks,
|
||||
selection: Selection<u64>,
|
||||
menu: Option<u64>,
|
||||
/// The document uid and row ID whose context menu is open.
|
||||
menu: Option<(u64, u64)>,
|
||||
}
|
||||
|
||||
/// `links.list` and the first selected image's `links.info`, with what they were fetched for.
|
||||
@@ -710,13 +711,16 @@ fn act(app: &mut VectorcraftApp, act: Act, target: Option<u64>) {
|
||||
/// The Links panel: the images as a list with a footer of link actions and the Link Info section.
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
drop_stale_picks(app);
|
||||
let uid = app.session.active().map(|st| st.uid);
|
||||
if app.ui.links.menu.is_some_and(|(document, _)| Some(document) != uid) {
|
||||
app.ui.links.menu = None;
|
||||
}
|
||||
let Some(mut cache) = cached(app, ui.ctx()) else {
|
||||
Panel::new(tl!("Links")).show(ui, |ui, _| {
|
||||
Text::new(tl!("No document")).shade(Shade::Muted).show(ui);
|
||||
});
|
||||
return;
|
||||
};
|
||||
let uid = app.session.active().map(|st| st.uid);
|
||||
let reveal = app.ui.links.show.take().filter(|(doc, _)| Some(*doc) == uid).map(|(_, id)| id);
|
||||
let listed = |cache: &Cache, id: u64| cache.list["links"].as_array().is_some_and(|rows| rows.iter().any(|r| r["id"].as_u64() == Some(id)));
|
||||
// A Show filter that leaves the requested row out goes back to Show All.
|
||||
@@ -730,7 +734,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let selected = selected_links(app);
|
||||
let mut selection = std::mem::take(&mut app.ui.links.selection);
|
||||
selection.items = selected.clone();
|
||||
let open_menu = app.ui.links.menu;
|
||||
let open_menu = app.ui.links.menu.map(|(_, row)| row);
|
||||
let units = app.session.general_unit();
|
||||
|
||||
let view: &VectorcraftApp = app;
|
||||
@@ -808,8 +812,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let items = app.ui.links.selection.items.clone();
|
||||
apply_selection(app, rows_of(&cache), items);
|
||||
}
|
||||
if menu_for.is_some() {
|
||||
app.ui.links.menu = menu_for;
|
||||
if let Some(row) = menu_for {
|
||||
app.ui.links.menu = uid.map(|document| (document, row));
|
||||
}
|
||||
if let Some(id) = activated {
|
||||
go_to(app, id);
|
||||
@@ -828,7 +832,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
if let Some((a, id)) = row_act {
|
||||
app.ui.links.menu = None;
|
||||
act(app, a, Some(id));
|
||||
if app.session.active().map(|st| st.uid) == uid {
|
||||
act(app, a, Some(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,8 +44,10 @@ fn row(app: &mut VectorcraftApp, ui: &mut Ui, o: &Value, label: &'static str, fl
|
||||
app.run("magicWand.set", json!({ flag: now })).ok();
|
||||
}
|
||||
if let Some((key, field)) = tol {
|
||||
Field::new(tl!("Tolerance:")).id_salt(key).enabled(on).show(ui, |ui, _| {
|
||||
if let Some(n) = field().enabled(on).show(ui).value().copied().flatten() {
|
||||
let caption = tl!("Tolerance:");
|
||||
Field::new(caption).id_salt(key).enabled(on).show(ui, |ui, _| {
|
||||
let name = format!("{caption} {label}");
|
||||
if let Some(n) = field().label(name).keeps_name(true).enabled(on).show(ui).value().copied().flatten() {
|
||||
app.run("magicWand.set", json!({ key: n })).ok();
|
||||
}
|
||||
});
|
||||
@@ -114,6 +116,19 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_tolerance_field_has_its_own_accessible_name() {
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::testing::Fixture;
|
||||
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let mut fixture = Fixture::new(move |ui| show(&mut app, ui));
|
||||
fixture.settle();
|
||||
let names: Vec<_> = fixture.by_role(Role::SPIN_BUTTON).into_iter().filter_map(|field| fixture.tree().name_of(field.node)).collect();
|
||||
assert_eq!(names, ["Tolerance: Fill Color", "Tolerance: Stroke Color", "Tolerance: Stroke Weight", "Tolerance: Opacity"]);
|
||||
assert_eq!(fixture.texts().iter().filter(|run| run.text == "Tolerance:").count(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_tolerance_fields_go_to_100_in_a_cmyk_document() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
|
||||
@@ -100,9 +100,9 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[(
|
||||
/// Whether a stroke that `stroke.set` edits has a width profile
|
||||
/// ([`vectorcraft_engine::Session::edited_strokes_profiled`]), cached per document revision and
|
||||
/// active Appearance row in `PropertiesUi::edited_profiled`. False while the Type tool edits text or
|
||||
/// the Live Paint Bucket is active, when the list edits the stroke the panel shows.
|
||||
/// a tool paints the stroke ([`vectorcraft_engine::Session::tool_paints`]), when the list edits the stroke the panel shows.
|
||||
fn edited_strokes_profiled(app: &mut VectorcraftApp) -> bool {
|
||||
if panels::character::text_editing(app).is_some() || app.session.bucket_paints() {
|
||||
if panels::character::text_editing(app).is_some() || app.session.tool_paints(true) {
|
||||
return false;
|
||||
}
|
||||
let Some(st) = app.session.active() else { return false };
|
||||
|
||||
@@ -136,7 +136,7 @@ pub(crate) fn builtin_arrow_name(label: &str) -> &str {
|
||||
crate::i18n::tr_ctx(crate::i18n::current(), "arrowhead", label)
|
||||
}
|
||||
|
||||
/// The preview cache key of `a`: its name, and for a custom head its art.
|
||||
/// The preview cache key of `a`: its name, and for a custom head its art and where the stroke ends.
|
||||
fn arrow_key(a: Option<&Arrowhead>) -> String {
|
||||
match a {
|
||||
Some(Arrowhead::Custom(c)) => {
|
||||
@@ -148,6 +148,7 @@ fn arrow_key(a: Option<&Arrowhead>) -> String {
|
||||
(p.x.to_bits(), p.y.to_bits()).hash(&mut h);
|
||||
}
|
||||
}
|
||||
c.stop().to_bits().hash(&mut h);
|
||||
format!("custom:{}:{:x}", c.name, h.finish())
|
||||
}
|
||||
_ => format!("{a:?}"),
|
||||
@@ -487,8 +488,13 @@ pub(super) fn arrow_doc(mut a: Option<Arrowhead>, start: bool, w: f64, h: f64) -
|
||||
let weight = fit(w - 6.0, long).min(fit(h / 2.0 - 1.0, half)).min(2.5);
|
||||
inset = -b.x0.min(0.0) * weight;
|
||||
if weight < LEAST {
|
||||
let path = c.path.transformed(vectorcraft_geom::Affine::scale(weight / LEAST));
|
||||
a = Some(Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(c.name.clone(), path))));
|
||||
let shrink = weight / LEAST;
|
||||
let path = c.path.transformed(vectorcraft_geom::Affine::scale(shrink));
|
||||
let mut head = vectorcraft_doc::CustomArrowhead::new(c.name.clone(), path);
|
||||
if let Some(stop) = c.stop {
|
||||
head = head.with_stop(stop * shrink);
|
||||
}
|
||||
a = Some(Arrowhead::Custom(std::sync::Arc::new(head)));
|
||||
}
|
||||
scale = scale.min(weight.max(LEAST) / WIDTH * 100.0);
|
||||
}
|
||||
@@ -735,6 +741,26 @@ mod tests {
|
||||
assert!(top.iter().chain(&bottom).all(|p| (p.y - r.center().y).abs() <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_arrowhead_thumbnails_preserve_where_the_stroke_ends() {
|
||||
use vectorcraft_doc::CustomArrowhead;
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
|
||||
let outline = PathData::single(SubPath::polyline(&[Point::new(0.0, -60.0), Point::new(4.0, 60.0), Point::new(4.0, -60.0)], true));
|
||||
let custom = CustomArrowhead::new("Wide Flag".into(), outline);
|
||||
let halfway = Arrowhead::Custom(std::sync::Arc::new(custom.clone()));
|
||||
let explicit_stop = Arrowhead::Custom(std::sync::Arc::new(custom.with_stop(0.75)));
|
||||
assert_ne!(arrow_key(Some(&halfway)), arrow_key(Some(&explicit_stop)), "each stroke attachment needs its own thumbnail");
|
||||
|
||||
let preview = arrow_doc(Some(explicit_stop), true, 56.0, 22.0).unwrap();
|
||||
let node = preview.node(preview.selectable_art()[0]).unwrap();
|
||||
let Some(Arrowhead::Custom(head)) = &node.appearance.stroke().unwrap().start_arrow else {
|
||||
panic!("the preview should draw the custom arrowhead");
|
||||
};
|
||||
// The preview has 10 points above the line. At the minimum weight, 60 units would need 15.
|
||||
assert_eq!(head.stop, Some(0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn while_typing_the_panel_strokes_the_selected_characters() {
|
||||
use vectorcraft_doc::{LineJoin, NodeKind};
|
||||
|
||||
@@ -409,8 +409,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let dragged_doc = Arc::clone(&thumbs.doc);
|
||||
let document = st.uid;
|
||||
let shown_app: &VectorcraftApp = app;
|
||||
let out = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0))
|
||||
.drag_payload(move |drag: &ListDrag<SwatchKey>| Some(dnd::drag_of(&dragged_doc, &drag.grabbed, dragged_rows(drag))))
|
||||
let browser = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0))
|
||||
.drag_payload(move |drag: &ListDrag<SwatchKey>| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag))))
|
||||
.thumb(thumbs, thumb)
|
||||
.row_icons(|key| match key {
|
||||
SwatchKey::Swatch(name) => row_icons(shown_app, name),
|
||||
@@ -422,8 +422,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
.select(SelectMode::Multi)
|
||||
.search(model.show_find)
|
||||
.reveal(focus.map(SwatchKey::Swatch))
|
||||
.footer(None)
|
||||
.show(ui);
|
||||
.footer(None);
|
||||
// A list drag is keyed by its browser ID. Each document has its own browser.
|
||||
let out = ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner;
|
||||
app.ui.swatches_panel = model;
|
||||
let shown = shown_keys(&data);
|
||||
if let Some((at, _, alt)) = out.used
|
||||
@@ -766,7 +767,8 @@ fn footer(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let opts = actions::editable(app, &sel);
|
||||
let group = actions::selected_group(app, &sel).filter(|_| opts.is_none());
|
||||
let icon = |id: &'static str| IconSpec::svg(IconId::new(id));
|
||||
let rows_drag = |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(_), .. });
|
||||
let document = app.session.active().map(|state| state.uid);
|
||||
let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document);
|
||||
let edit = if group.is_some() {
|
||||
FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group"))
|
||||
} else {
|
||||
|
||||
@@ -4,9 +4,10 @@ use craft::color_ui::ui::SwatchKey;
|
||||
use craft::keymap::Mods;
|
||||
use craft::ui::contract::{DropAt, ReorderMove};
|
||||
|
||||
/// Swatches take paint payloads and artwork from the current document's canvas.
|
||||
/// Swatches take paints, and take swatch rows or canvas art from the current document.
|
||||
pub(super) fn accepts(drag: &PanelDrag, document: u64) -> bool {
|
||||
match drag {
|
||||
PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document,
|
||||
PanelDrag::Paint { .. } => true,
|
||||
PanelDrag::Art { document: source, .. } => *source == document,
|
||||
_ => false,
|
||||
@@ -53,7 +54,7 @@ impl Drop {
|
||||
|
||||
/// The drag a row of `key` starts, moving rows `names`. Colour groups have no paint of their own
|
||||
/// (the chip under the pointer draws Registration's mark for Registration).
|
||||
pub(super) fn drag_of(d: &Document, key: &SwatchKey, names: Vec<String>) -> PanelDrag {
|
||||
pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec<String>) -> PanelDrag {
|
||||
let name = name_of(key);
|
||||
let (paint, params) = match key {
|
||||
SwatchKey::Swatch(_) if name == REGISTRATION => (Paint::registration(), swatch_params(d, name)),
|
||||
@@ -63,7 +64,7 @@ pub(super) fn drag_of(d: &Document, key: &SwatchKey, names: Vec<String>) -> Pane
|
||||
},
|
||||
_ => (Paint::None, Value::Null),
|
||||
};
|
||||
let rows = SwatchRows { grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) };
|
||||
let rows = SwatchRows { document, grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)) };
|
||||
PanelDrag::Paint { paint, params, rows: Some(rows), library: None }
|
||||
}
|
||||
|
||||
@@ -124,6 +125,9 @@ pub(super) enum FooterTarget {
|
||||
/// the button does. Other drags are left to their own targets.
|
||||
pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, drag: &PanelDrag) {
|
||||
let PanelDrag::Paint { rows: Some(r), .. } = drag else { return };
|
||||
if !app.session.active().is_some_and(|state| state.uid == r.document) {
|
||||
return;
|
||||
}
|
||||
let rows = footer_rows(app, r);
|
||||
match target {
|
||||
FooterTarget::Delete => {
|
||||
|
||||
@@ -96,7 +96,61 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) {
|
||||
|
||||
/// The drag the row `name` starts, carrying rows `names`.
|
||||
fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag {
|
||||
dnd::drag_of(&doc(app), &key_of(app, name), names.iter().map(|n| n.to_string()).collect())
|
||||
let document = app.session.active().unwrap().uid;
|
||||
dnd::drag_of(&doc(app), document, &key_of(app, name), names.iter().map(|n| n.to_string()).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_row_drag_reorders_only_its_source_document() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::{ListDrag, Role};
|
||||
use craft::ui::runtime::drag;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
let mut app = app();
|
||||
let source = app.session.active().unwrap().uid;
|
||||
let before_source = names_of(&app, None);
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let destination = app.session.active().unwrap().uid;
|
||||
let before_destination = names_of(&app, None);
|
||||
app.run("window.previousDocument", json!({})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().uid, source);
|
||||
|
||||
let mut panel = Panel::new(app, show);
|
||||
let drag_red = |panel: &mut Panel| {
|
||||
let red = "Red, #ed1c24";
|
||||
let from = panel.rect(red).center();
|
||||
let to = panel.rect("Green, #39b54a").center();
|
||||
panel.drag_hold_role(red, Role::LIST_ITEM, to - from);
|
||||
let grabbed = drag::active::<ListDrag<SwatchKey>>(panel.ctx()).map(|d| d.grabbed.clone());
|
||||
assert_eq!(grabbed, Some(SwatchKey::Swatch("Red".into())));
|
||||
};
|
||||
drag_red(&mut panel);
|
||||
panel.key(Key::F6, Modifiers::COMMAND);
|
||||
assert_eq!(panel.app().session.active().unwrap().uid, destination);
|
||||
panel.release();
|
||||
assert_eq!(names_of(&panel.app(), None), before_destination);
|
||||
|
||||
panel.key(Key::F6, Modifiers::COMMAND);
|
||||
assert_eq!(panel.app().session.active().unwrap().uid, source);
|
||||
assert_eq!(names_of(&panel.app(), None), before_source);
|
||||
drag_red(&mut panel);
|
||||
panel.release();
|
||||
assert_ne!(names_of(&panel.app(), None), before_source);
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(names_of(&panel.app(), None), before_source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() {
|
||||
let mut app = app();
|
||||
let drag = rows_drag(&app, "Red", &["Red"]);
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let before = doc(&app);
|
||||
assert!(!dnd::accepts(&drag, app.session.active().unwrap().uid));
|
||||
dropped_below(&mut app, drag.clone(), none());
|
||||
dropped(&mut app, drag, "Green", alt());
|
||||
assert_eq!(doc(&app).swatches, before.swatches);
|
||||
}
|
||||
|
||||
/// Art `ids` dragged off the canvas.
|
||||
@@ -551,6 +605,22 @@ fn drops_on_the_buttons_and_the_panel_run_their_commands() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footer_drops_ignore_rows_from_another_document() {
|
||||
let mut app = app();
|
||||
let drag = rows_drag(&app, "Orange", &["Orange"]);
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("swatch.new", json!({"name": "Orange", "color": "#ff8000"})).unwrap();
|
||||
let before = doc(&app);
|
||||
let undo = undo_steps(&app);
|
||||
for target in [dnd::FooterTarget::New, dnd::FooterTarget::Delete] {
|
||||
dnd::on_footer_drop(&mut app, target, &drag);
|
||||
assert_eq!(doc(&app), before);
|
||||
assert_eq!(undo_steps(&app), undo);
|
||||
assert!(!dialog_open(&app, crate::dialogs::confirm::KIND));
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected swatch dragged onto New Swatch or Delete Swatch carries the selected swatches that
|
||||
/// the find field hides, which the browser leaves out of the drag, as a click on Delete Swatch
|
||||
/// takes them too. The copies are selected in panel order. A grabbed swatch outside the selection
|
||||
|
||||
@@ -663,6 +663,41 @@ fn unembed_writes_several_images_to_one_picked_folder() {
|
||||
assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_documents_dismisses_a_links_row_menu() {
|
||||
let dir = Folder::new("context-switched-document");
|
||||
let (mut app, first, _) = app(&dir);
|
||||
let source = app.session.active().unwrap().uid;
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let path = dir.file("other.png", &png(40, 20));
|
||||
let second = app.run("file.place", json!({"path": path, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let destination = app.session.active().unwrap().uid;
|
||||
assert_eq!(first, second, "the two documents have different images at the same local ID");
|
||||
app.run("window.previousDocument", json!({})).unwrap();
|
||||
|
||||
let mut panel = Panel::new(app, super::links::show);
|
||||
let activate = |panel: &mut Panel, index, document| {
|
||||
panel.app().session.execute("document.activate", &json!({"index": index})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().uid, document);
|
||||
};
|
||||
panel.secondary_click("linked.png");
|
||||
assert!(panel.menu_item_enabled("Embed Image"));
|
||||
activate(&mut panel, 1, destination);
|
||||
assert!(!panel.shows("Embed Image"), "the other document must not inherit the row menu");
|
||||
assert_eq!(panel.app().run("links.info", json!({"id": second})).unwrap()["linked"], true);
|
||||
|
||||
activate(&mut panel, 0, source);
|
||||
assert!(!panel.shows("Embed Image"), "switching back must not revive the menu");
|
||||
assert_eq!(panel.app().run("links.info", json!({"id": first})).unwrap()["linked"], true);
|
||||
|
||||
activate(&mut panel, 1, destination);
|
||||
panel.secondary_click("other.png");
|
||||
panel.click_menu_item("Embed Image");
|
||||
assert_eq!(panel.app().run("links.info", json!({"id": second})).unwrap()["status"], "embedded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_click_context_menu_in_links_panel() {
|
||||
let dir = Folder::new("context-menu");
|
||||
|
||||
@@ -74,7 +74,15 @@ fn the_document_info_rows_wrap_in_a_narrow_panel_in_german() {
|
||||
|
||||
#[test]
|
||||
fn the_magic_wand_rows_wrap_in_a_narrow_panel_in_french() {
|
||||
let past = past_a_narrow_panel("magicWand", "fr", &["Tolerance:"]);
|
||||
use crate::i18n::{Lang, LangExt as _, tr};
|
||||
|
||||
let captions = ["Tolerance:"];
|
||||
let panel = floated(app_with_rect(), "magicWand", "fr", Place::Floating(PANEL_MIN_WIDTH), &captions);
|
||||
let prefix = format!("{} ", tr(Lang::from_code("fr").unwrap(), "Tolerance:"));
|
||||
let fields: Vec<_> = panel.nodes.iter().filter(|(name, _)| name.starts_with(&prefix)).cloned().collect();
|
||||
assert_eq!(fields.len(), 4, "{fields:?}");
|
||||
let mut past = panel.past_named(&captions);
|
||||
past.extend(panel.past(fields));
|
||||
assert!(past.is_empty(), "past the panel: {past:?}");
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,8 @@ impl StylesPanels {
|
||||
pub(crate) struct StylesPanel {
|
||||
/// The uid of the document the highlight was made in.
|
||||
document: Option<u64>,
|
||||
/// Changes when the panel switches documents, so reopening a document cannot restore its old popup.
|
||||
scope_generation: u64,
|
||||
/// The highlighted styles, in the order they were picked.
|
||||
highlight: Vec<String>,
|
||||
/// The selection's lead style.
|
||||
@@ -83,7 +85,7 @@ fn highlighted(app: &mut VectorcraftApp, kind: Kind, listed: &[&str]) -> Vec<Str
|
||||
let document = app.session.active().map(|st| st.uid);
|
||||
let panel = app.ui.text_styles.of(kind);
|
||||
if panel.document.is_some_and(|made| Some(made) != document) {
|
||||
*panel = StylesPanel::default();
|
||||
*panel = StylesPanel { scope_generation: panel.scope_generation.wrapping_add(1), ..StylesPanel::default() };
|
||||
}
|
||||
panel.document = document;
|
||||
panel.highlight.retain(|n| listed.contains(&n.as_str()));
|
||||
@@ -253,6 +255,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) {
|
||||
let names = highlighted(app, kind, &listed);
|
||||
let panel = app.ui.text_styles.of(kind);
|
||||
let (lead, anchor, reveal) = (panel.lead.clone(), panel.anchor.clone(), panel.reveal.take());
|
||||
let scope = (panel.document, panel.scope_generation);
|
||||
let mut sel = Selection::new(names.iter().filter_map(|n| id_of(n)).collect(), lead.as_deref().and_then(id_of), anchor.as_deref().and_then(id_of));
|
||||
let rows: Vec<TextStyleRow> =
|
||||
listed.iter().enumerate().map(|(i, name)| TextStyleRow::new(i as u64, super::label_or_name(name, i == 0))).collect();
|
||||
@@ -271,7 +274,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) {
|
||||
if let Some(id) = reveal.as_deref().and_then(id_of) {
|
||||
list = list.reveal(id);
|
||||
}
|
||||
let out = list.show(ui);
|
||||
// The framework's row menu and footer drag use list indices that are local to this document.
|
||||
let out = ui.push_id(("text-styles-document", kind.panel_kind(), scope), |ui| list.show(ui)).inner;
|
||||
let name_of = |id: &u64| listed.get(*id as usize).map(|n| n.to_string());
|
||||
let panel = app.ui.text_styles.of(kind);
|
||||
panel.highlight = sel.items.iter().filter_map(name_of).collect();
|
||||
|
||||
@@ -4,6 +4,54 @@ use crate::tests::picks::{answer_dialog, cancel_dialog, open_dialogs, poll, scri
|
||||
use crate::tests::synthetic::key_frame;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
#[test]
|
||||
fn switching_documents_dismisses_text_styles_row_menus() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
for kind in [Kind::Char, Kind::Para] {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
let command = format!("{}.new", kind.prefix());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run(&command, json!({"name": "First Style"})).unwrap();
|
||||
let first = style_id(&mut app, kind, "First Style");
|
||||
let source = app.session.active().unwrap().uid;
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run(&command, json!({"name": "Second Style"})).unwrap();
|
||||
let second = style_id(&mut app, kind, "Second Style");
|
||||
let destination = app.session.active().unwrap().uid;
|
||||
assert_eq!(first, second, "the two documents carry styles at the same list index");
|
||||
app.run("window.previousDocument", json!({})).unwrap();
|
||||
|
||||
let draw: fn(&mut VectorcraftApp, &mut Ui) = match kind {
|
||||
Kind::Char => |app, ui| show(app, ui, Kind::Char),
|
||||
Kind::Para => |app, ui| show(app, ui, Kind::Para),
|
||||
};
|
||||
let mut panel = Panel::new(app, draw);
|
||||
let activate = |panel: &mut Panel, index, document| {
|
||||
panel.app().session.execute("document.activate", &json!({"index": index})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().uid, document);
|
||||
};
|
||||
let has_copy = |panel: &Panel, name: &str| styles(&mut panel.app(), kind).iter().any(|style| style.0 == name);
|
||||
panel.secondary_click("First Style");
|
||||
assert!(panel.menu_item_enabled("Duplicate Style"));
|
||||
activate(&mut panel, 1, destination);
|
||||
assert!(!panel.shows("Duplicate Style"), "the new document does not inherit the row menu");
|
||||
assert!(!has_copy(&panel, "Second Style copy"));
|
||||
|
||||
activate(&mut panel, 0, source);
|
||||
assert!(!panel.shows("Duplicate Style"), "the old row menu does not reappear");
|
||||
assert!(!has_copy(&panel, "First Style copy"));
|
||||
|
||||
activate(&mut panel, 1, destination);
|
||||
panel.secondary_click("Second Style");
|
||||
panel.click_menu_item("Duplicate Style");
|
||||
assert!(has_copy(&panel, "Second Style copy"));
|
||||
}
|
||||
}
|
||||
|
||||
// PLAN: assumed type-w19 items reachable through `super::*`: `run_action(app, kind, action)`,
|
||||
// `StylesPanel { highlight: Vec<String>, .. }` and `StylesPanels { char, para, made }` at
|
||||
// `app.ui.text_styles`, `highlighted(app, kind, listed: &[&str]) -> Vec<String>`, `TextStyleAction`, and a
|
||||
|
||||
@@ -224,6 +224,13 @@ impl Panel {
|
||||
self.after();
|
||||
}
|
||||
|
||||
/// Turns the wheel by `dy` points over `at`.
|
||||
pub(crate) fn scroll_at(&mut self, at: Pos2, dy: f32) {
|
||||
self.frame_with(vec![Event::PointerMoved(at)]);
|
||||
self.frame_with(vec![craft::ui::testing::pointer::wheel(dy)]);
|
||||
self.after();
|
||||
}
|
||||
|
||||
/// Drags from the control named `from` to the one named `to`.
|
||||
pub(crate) fn drag(&mut self, from: &str, to: &str, mods: Modifiers) {
|
||||
let to = self.find(to).center();
|
||||
|
||||
+6
-3
@@ -1393,9 +1393,12 @@ Each coordinate goes to the nearest step of its stored binary value, and a value
|
||||
zero (`0.125` at 2 places is `0.13`); `1.005` is stored as slightly less than that and is written as `1.0`. Each anchor is rounded on
|
||||
its own, so a closed path stays closed and a shape smaller than one step keeps its anchors on one point. Opening the
|
||||
file and saving it again does not bring back the dropped digits. The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores
|
||||
`precision`. A save writes
|
||||
a temporary file and renames it over the old one, so a failed save never damages the file; only the images the
|
||||
document uses are written, and document keys written by a newer version are kept.
|
||||
`precision`. A save first writes and flushes a temporary file, then renames it over the destination or copies the complete
|
||||
content into the destination. The copy path keeps a flushed copy of any existing content before overwriting it.
|
||||
A failure during that copy reports the locations of the new content and any saved original.
|
||||
Only the images the document uses are written, and document keys written by a newer version are kept.
|
||||
On Unix, a save flushes the destination directory after writing or replacing the file. If that flush fails,
|
||||
the save reports an error stating that the file was written.
|
||||
An uncompressed file is indented JSON when the document has at most 2,000 layers and objects and the indented
|
||||
document, as the chosen version writes it, is at most 1 MiB; otherwise the file is compact JSON.
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Parity with Adobe Illustrator
|
||||
|
||||
Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written.
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only 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: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; 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: 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: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; 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: 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: 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: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: 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, and edits that go on once the view is still don't put off its render (#8688); 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: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; 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: 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: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and esLine truncated
|
||||
>
|
||||
> Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5).
|
||||
|
||||
Reference in new issue
Block a user