Merge main into fix/live-corners-anchor-add-delete

This commit is contained in:
dotCooCoo committed 2026-12-05 04:31:47 -08:00
commit f26f8601e3
111 files changed
+6618 -356

No files matched your search

+10
View File
@@ -227,6 +227,16 @@ impl Node {
}
}
/// The path whose anchors the anchor tools edit, in document space: a path's, or the path of
/// type on a path outside perspective (Add, Delete and Anchor Point tools, Pen + Alt).
pub fn anchor_path(&self) -> Option<std::borrow::Cow<'_, PathData>> {
match &self.kind {
NodeKind::Path { path, .. } => Some(std::borrow::Cow::Borrowed(path)),
NodeKind::Text(t) if self.extras().perspective.is_none() => t.type_path().map(std::borrow::Cow::Owned),
_ => None,
}
}
pub fn path_data_mut(&mut self) -> Option<&mut PathData> {
match &mut self.kind {
NodeKind::Path { path, .. } => Some(path),
+18 -7
View File
@@ -368,18 +368,29 @@ impl Document {
}
}
/// Whether any fill or stroke of `n`'s subtree overprints, characters' too.
fn overprints_anywhere(n: &Node) -> bool {
/// Whether any fill or stroke of `n`'s subtree overprints, characters' too, and with `images` an
/// image's color.
fn overprints_anywhere(n: &Node, images: bool) -> bool {
n.appearance.items.iter().any(|i| i.overprint())
|| n.extras().colorize_overprint
|| (images && n.extras().colorize_overprint)
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|| n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c)))
|| n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c, images)))
}
/// Stop every fill and stroke of `a`'s subtree overprinting (characters' too), copying only the
/// nodes on the way to them.
pub fn clear_overprints(a: &mut Arc<Node>) {
if !overprints_anywhere(a) {
clear(a, true);
}
/// [`clear_overprints`] for fills, strokes and characters only: the colors of images keep their
/// overprint ([`crate::NodeExtras::colorize_overprint`]).
pub fn clear_paint_overprints(a: &mut Arc<Node>) {
clear(a, false);
}
fn clear(a: &mut Arc<Node>, images: bool) {
if !overprints_anywhere(a, images) {
return;
}
let n = Arc::make_mut(a);
@@ -392,11 +403,11 @@ pub fn clear_overprints(a: &mut Arc<Node>) {
}
}
// Also the flag an image keeps after its color is removed.
if n.extras().colorize_overprint {
if images && n.extras().colorize_overprint {
n.extras_mut().colorize_overprint = false;
}
for c in n.children_mut().into_iter().flatten() {
clear_overprints(c);
clear(c, images);
}
}
+10
View File
@@ -487,6 +487,16 @@ impl TextObject {
true
})
}
/// Replace type on a path's path with `path`, given in document space; the brackets keep their
/// fractions of the path. False, changing nothing, for other type, a degenerate `xf` or a path
/// that would not be finite.
pub fn set_type_path(&mut self, path: &PathData) -> bool {
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|frame, to_text| {
*frame = path.transformed(to_text);
true
})
}
/// Edit a copy of the area frame with `f` (given the document → text space map) and keep it
/// when `f` succeeds and the result is finite.
fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool {
+2
View File
@@ -18,6 +18,7 @@ pub mod colormgmt;
pub mod colortheme;
pub mod compositefonts;
mod compoundshape;
pub mod conceptvector;
pub(crate) mod create;
mod css;
mod cut;
@@ -365,6 +366,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(panelcmds::specs());
v.extend(artboardalign::specs());
v.extend(buildcmds::specs());
v.extend(conceptvector::specs());
v.extend(shaper::specs());
v.extend(brushsym::specs());
v.extend(patterncmds::specs());
+830
View File
@@ -0,0 +1,830 @@
//! Concept to Vector (`conceptVector.*`): vector variations of one selected image, made by a
//! provider ([`crate::concept_vector`]), compared, and inserted beside the image.
//!
//! `conceptVector.generate` asks the named provider for one variation per style and keeps them as a
//! job of this session; it changes nothing in the document. `conceptVector.insert` puts the chosen
//! variations to the right of the image as one undo step. A job is kept until it is canceled, its
//! document closes, or [`KEEP_JOBS`] newer ones replace it; it is never saved.
use std::collections::VecDeque;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
use vectorcraft_doc::{Appearance, ImageObject, Node, NodeId, NodeKind};
use vectorcraft_geom::{Affine, Rect};
use super::buildcmds::TRACE_NAME;
use super::edit::selected_roots;
use super::pathops::shape_node;
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_id, cmd, has_doc, text_param};
use crate::concept_vector::{self as cv, MAX_STYLES, Output, Provider, ProviderError, Request, Variation};
/// The most jobs a session keeps; a new one drops the oldest.
pub const KEEP_JOBS: usize = 4;
/// The gap, in points, between the image and the first inserted variation, and between variations.
pub const GAP: f64 = 24.0;
/// A job's variations, or that it was canceled.
#[derive(Clone)]
enum Outcome {
Done(Arc<Vec<Variation>>),
Canceled,
}
/// What `conceptVector.generate` made, and what it was made of.
#[derive(Clone)]
pub(crate) struct Job {
id: u64,
/// The document ([`crate::DocState::uid`]) and the object (an image or an Image Trace object).
doc: u64,
source: NodeId,
image: ImageObject,
bytes: Arc<Vec<u8>>,
provider: String,
outcome: Outcome,
}
/// The session's providers and jobs.
pub(crate) struct ConceptState {
pub(crate) registry: cv::Registry,
jobs: VecDeque<Job>,
next: u64,
}
impl Default for ConceptState {
fn default() -> Self {
Self { registry: cv::Registry::default(), jobs: VecDeque::new(), next: 1 }
}
}
impl Session {
/// The Concept to Vector providers this session calls by id.
pub fn concept_providers(&self) -> &cv::Registry {
&self.concept.registry
}
/// The providers, to register another ([`cv::Registry::register`]).
pub fn concept_providers_mut(&mut self) -> &mut cv::Registry {
&mut self.concept.registry
}
/// Job `job`'s variations and the size in pixels of the image they were made of; `None` for a
/// job this session does not keep, or one that was canceled.
pub fn concept_variations(&self, job: u64) -> Option<(&[Variation], (u32, u32))> {
let j = self.concept.jobs.iter().find(|j| j.id == job)?;
match &j.outcome {
Outcome::Done(v) => Some((v.as_slice(), (j.image.width, j.image.height))),
Outcome::Canceled => None,
}
}
/// The document ([`crate::DocState::uid`]) job `job` was made in; `None` for a job this session
/// does not keep.
pub fn concept_job_doc(&self, job: u64) -> Option<u64> {
self.concept.jobs.iter().find(|j| j.id == job).map(|j| j.doc)
}
/// The jobs, for a batch to put back when a step fails. Job numbers are not reused.
pub(crate) fn concept_jobs_snapshot(&self) -> VecDeque<Job> {
self.concept.jobs.clone()
}
/// Puts back the jobs that [`Self::concept_jobs_snapshot`] took.
pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque<Job>) {
self.concept.jobs = jobs;
}
/// Exchanges the jobs with `jobs`: a script works on a copy of them, which becomes the
/// session's only when the script ends without an error.
pub(crate) fn swap_concept_jobs(&mut self, jobs: &mut VecDeque<Job>) {
std::mem::swap(&mut self.concept.jobs, jobs);
}
/// The number the next job gets.
pub(crate) fn next_concept_job(&self) -> u64 {
self.concept.next
}
/// Takes in what the app did to the jobs while a script ran, `others` being the jobs as the app
/// left them: a job canceled there is canceled here too, and the jobs numbered `from` or higher
/// that this session does not keep (those the app made) are added. Then keeps the
/// [`KEEP_JOBS`] newest of open documents.
pub(crate) fn merge_concept_jobs(&mut self, others: VecDeque<Job>, from: u64) {
for j in others {
match self.concept.jobs.iter_mut().find(|k| k.id == j.id) {
Some(k) if matches!(j.outcome, Outcome::Canceled) => k.outcome = Outcome::Canceled,
Some(_) => {}
None if j.id >= from => self.concept.jobs.push_back(j),
None => {}
}
}
self.concept.jobs.make_contiguous().sort_by_key(|j| j.id);
self.prune_concept_jobs();
while self.concept.jobs.len() > KEEP_JOBS {
self.concept.jobs.pop_front();
}
}
/// Drops the jobs of document `doc` (its `uid`), when it closes.
pub(crate) fn forget_concept_jobs(&mut self, doc: u64) {
self.concept.jobs.retain(|j| j.doc != doc);
}
/// Drops the jobs whose document is closed.
/// In a batch, nothing is dropped until the batch ends without an error.
pub(crate) fn prune_concept_jobs(&mut self) {
if self.batch_stash.is_some() {
return;
}
let open: Vec<u64> = self.documents().iter().map(|d| d.uid).collect();
self.concept.jobs.retain(|j| open.contains(&j.doc));
}
}
/// The image `n` shows: its own, or the source image of an Image Trace object that wasn't expanded.
fn shown_image(n: &Node) -> Option<&ImageObject> {
match &shown_image_node(n)?.kind {
NodeKind::Image(i) => Some(i),
_ => None,
}
}
/// The image object [`shown_image`] reads: `n` itself, or the first member of its Image Trace object.
fn shown_image_node(n: &Node) -> Option<&Node> {
match &n.kind {
NodeKind::Image(_) => Some(n),
NodeKind::Group { clip: false, .. } if n.name.as_deref() == Some(TRACE_NAME) => {
n.children()?.first().map(|i| &**i).filter(|i| matches!(i.kind, NodeKind::Image(_)))
}
_ => None,
}
}
/// Is `n` a group whose members are made or placed from data it holds (a graph, an Objects on
/// Path, Shaper, dimension, flare or Live Paint group, a compound shape, a plug-in's generated
/// art), so that a member added to it would be placed again, replaced or combined with the others?
fn generated(n: &Node) -> bool {
let e = n.extras();
e.generated.is_some()
|| e.graph.is_some()
|| e.objects_on_path.is_some()
|| e.shaper.is_some()
|| e.dimension.is_some()
|| e.flare.is_some()
|| e.compound_shape
|| vectorcraft_tools::builder::is_live_paint(n)
}
const NO_SOURCE: &str = "select one image or an unexpanded Image Trace object";
const LOCKED: &str = "the image is locked or hidden";
/// The object `id` names, else the one selected: an image or an unexpanded Image Trace object,
/// shown and unlocked with every layer and group around it, and not on a locked artboard → it, its
/// image and the image's bytes.
fn source(s: &Session, c: &str, p: &Value) -> Result<(NodeId, ImageObject, Arc<Vec<u8>>)> {
let id = match p.get("id").filter(|v| !v.is_null()) {
Some(v) => checked_id(s, v, c)?,
None => match selected_roots(s)?.as_slice() {
[one] => *one,
_ => return Err(bad(c, NO_SOURCE)),
},
};
let d = &s.doc()?.doc;
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let image = shown_image(n).ok_or_else(|| bad(c, NO_SOURCE))?;
if !d.is_editable(id) {
return Err(bad(c, LOCKED));
}
let blob = d.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?;
Ok((id, image.clone(), Arc::clone(&blob.bytes)))
}
/// A generation prepared from the session, which runs without it ([`ConceptRun::run`]), on any
/// thread, and is kept as a job with [`ConceptRun::finish`].
pub struct ConceptRun {
provider: Arc<dyn Provider>,
/// The provider's id, as it was registered.
provider_id: &'static str,
request: Request,
doc: u64,
source: NodeId,
image: ImageObject,
}
impl ConceptRun {
/// What `conceptVector.generate` with params `p` makes in the active document, checked as the
/// command checks it.
pub fn prepare(s: &Session, p: &Value) -> Result<ConceptRun> {
const C: &str = "conceptVector.generate";
let name = text_param(p, "provider", C)?.ok_or_else(|| bad(C, "missing `provider` (see conceptVector.providers)"))?;
let found =
s.concept.registry.get(name).ok_or_else(|| bad(C, format!("no Concept to Vector provider `{name}` (see conceptVector.providers)")))?;
let (caps, pid, provider) = (&found.capabilities, found.id, Arc::clone(&found.provider));
let styles_error = || bad(C, format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)"));
// The count is checked before any id is copied or scanned for repeats.
let styles: Vec<String> = match p.get("styles") {
Some(Value::Array(a)) if (1..=MAX_STYLES).contains(&a.len()) => {
a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<_>>().ok_or_else(styles_error)?
}
_ => return Err(styles_error()),
};
let known = |id: &String| caps.styles.iter().any(|st| st.id == id);
let unique = styles.iter().enumerate().all(|(i, id)| !styles.get(..i).unwrap_or_default().contains(id));
if !unique || !styles.iter().all(known) {
return Err(styles_error());
}
let prompt = text_param(p, "prompt", C)?.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);
// Results are vector paths, inserted as vector art, whatever else a provider makes.
let output = match text_param(p, "output", C)? {
None | Some("vector") => Output::Vector,
Some(_) => return Err(bad(C, "`output` must be \"vector\"")),
};
if !caps.image_input {
return Err(bad(C, format!("`{pid}` does not take an image")));
}
if !caps.vector_output {
return Err(bad(C, format!("`{pid}` does not make vector art")));
}
if prompt.is_some() && !caps.prompt {
return Err(bad(C, format!("`{pid}` takes no prompt")));
}
let detail = match p.get("detail") {
None => 50,
Some(v) => v.as_u64().filter(|d| *d <= 100).ok_or_else(|| bad(C, "`detail` must be a whole number from 0 to 100"))? as u8,
};
let (source, image, bytes) = source(s, C, p)?;
let request = Request { image: bytes, width: image.width, height: image.height, prompt, styles, detail, output };
Ok(ConceptRun { provider, provider_id: pid, request, doc: s.doc()?.uid, source, image })
}
/// The document it was prepared in ([`crate::DocState::uid`]).
pub fn doc(&self) -> u64 {
self.doc
}
/// The image or Image Trace object it makes variations of.
pub fn source(&self) -> NodeId {
self.source
}
/// Asks the provider for the variations and checks them ([`cv::check_result`]), telling `steps`
/// how far it has got; it touches no document. A panic in the provider is an error.
pub fn run(&self, steps: cv::Steps) -> std::result::Result<Vec<Variation>, ProviderError> {
let made = crate::guard::catch_panic(|| self.provider.generate(&self.request, steps)).map_err(ProviderError::Internal)??;
cv::check_result(&self.request, &made)?;
Ok(made)
}
/// How many styles it makes.
pub fn style_count(&self) -> usize {
self.request.styles.len()
}
/// Does the next part of the run kept in `run`, for a caller with no thread for
/// [`ConceptRun::run`] (the web build), which can run other work, or stop, between the parts
/// → whether every style is made ([`PartRun::made`]). A provider that makes parts
/// ([`cv::Provider::parts`]) does one of its own; the others make one style alone, and the
/// styles made so far are checked together ([`cv::check_result`]) after each one, so the
/// totals stop the run as soon as they are passed. A panic in the provider is an error.
pub fn run_part(&self, run: &mut PartRun, steps: cv::Steps) -> std::result::Result<bool, ProviderError> {
let guard = ProviderError::Internal;
if run.parts.is_none() {
run.parts = Some(crate::guard::catch_panic(|| self.provider.parts(&self.request)).map_err(guard)?);
}
if let Some(Some(parts)) = &mut run.parts {
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
if !steps(run.done as u64, self.style_count() as u64) {
return Err(ProviderError::Canceled);
}
let Some(made) = crate::guard::catch_panic(|| parts.step()).map_err(guard)?? else {
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
return Ok(false);
};
cv::check_result(&self.request, &made)?;
run.made = made;
return Ok(true);
}
let Some(style) = self.request.styles.get(run.made.len()) else { return Ok(true) };
let one = Request { styles: vec![style.clone()], ..self.request.clone() };
let next = crate::guard::catch_panic(|| self.provider.generate(&one, steps)).map_err(guard)??;
cv::check_result(&one, &next)?;
// A style that takes the totals past their limits is dropped, so `run` keeps only the
// styles that passed.
let kept = run.made.len();
run.made.extend(next);
let so_far = Request { styles: self.request.styles.get(..run.made.len()).unwrap_or_default().to_vec(), ..one };
if let Err(e) = cv::check_result(&so_far, &run.made) {
run.made.truncate(kept);
return Err(e);
}
Ok(run.made.len() == self.request.styles.len())
}
/// Keeps `variations` as a new job of `s` → the job, as `conceptVector.results` gives it;
/// `None`, keeping nothing, when the document it was prepared in has closed.
pub fn finish(self, s: &mut Session, variations: Vec<Variation>) -> Option<Value> {
s.prune_concept_jobs();
if !s.documents().iter().any(|d| d.uid == self.doc) {
return None;
}
let id = s.concept.next;
s.concept.next += 1;
let job = Job {
id,
doc: self.doc,
source: self.source,
image: self.image,
bytes: self.request.image,
provider: self.provider_id.to_string(),
outcome: Outcome::Done(Arc::new(variations)),
};
let out = job_json(&s.concept.registry, &job);
s.concept.jobs.push_back(job);
while s.concept.jobs.len() > KEEP_JOBS {
s.concept.jobs.pop_front();
}
Some(out)
}
}
/// How far a run made a part at a time ([`ConceptRun::run_part`]) has got.
#[derive(Default)]
pub struct PartRun {
/// The provider's parts, once asked for (`None` inside: it makes one style at a time).
parts: Option<Option<Box<dyn cv::Parts>>>,
/// The styles the provider's parts had made when last asked, inside the panic guard.
done: usize,
made: Vec<Variation>,
}
impl PartRun {
/// The styles made so far.
pub fn styles_done(&self) -> usize {
if self.made.is_empty() { self.done } else { self.made.len() }
}
/// The variations made: all of them once [`ConceptRun::run_part`] has said so.
pub fn made(self) -> Vec<Variation> {
self.made
}
}
/// `e` as the engine's error.
pub fn provider_error(e: ProviderError) -> EngineError {
match e {
ProviderError::Canceled => EngineError::Cancelled,
e => EngineError::Other(e.to_string()),
}
}
/// The English name of style `style` of provider `provider`, else the id.
fn style_label(registry: &cv::Registry, provider: &str, style: &str) -> String {
let caps = registry.get(provider).map(|p| &p.capabilities);
caps.and_then(|c| c.styles.iter().find(|s| s.id == style).map(|s| s.label.to_string())).unwrap_or_else(|| style.to_string())
}
/// Where `style` comes in the styles `provider` lists; after them when it lists no such style.
fn style_rank(registry: &cv::Registry, provider: &str, style: &str) -> usize {
let caps = registry.get(provider).map(|p| &p.capabilities);
caps.and_then(|c| c.styles.iter().position(|s| s.id == style)).unwrap_or(usize::MAX)
}
/// Where `image`'s pixels lie in the document.
fn image_rect(image: &ImageObject) -> Option<Rect> {
let r = Rect::new(0.0, 0.0, f64::from(image.width.max(1)), f64::from(image.height.max(1)));
let pts = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| image.xf * kurbo::Point::new(x, y));
let mut out = Rect::from_points(pts[0], pts[0]);
for q in &pts[1..] {
out = out.union_pt(*q);
}
[out.x0, out.y0, out.x1, out.y1].iter().all(|v| v.is_finite()).then_some(out)
}
fn job_json(registry: &cv::Registry, j: &Job) -> Value {
let (state, variations) = match &j.outcome {
Outcome::Done(v) => ("done", v.as_slice()),
Outcome::Canceled => ("canceled", &[][..]),
};
let variations: Vec<Value> = variations
.iter()
.map(|v| {
let bounds = v.paths.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b));
json!({
"style": v.style,
"label": style_label(registry, &j.provider, &v.style),
"paths": v.paths.len(),
"anchors": v.anchors(),
"bounds": bounds.map(|b| [b.x0, b.y0, b.x1, b.y1]),
"warnings": v.warnings,
})
})
.collect();
json!({ "job": j.id, "provider": j.provider, "source": j.source.0, "state": state, "variations": variations })
}
/// The `job` param of command `c`.
fn job_param(c: &str, p: &Value) -> Result<u64> {
p.get("job").and_then(Value::as_u64).ok_or_else(|| bad(c, "`job` must be a job number from conceptVector.generate"))
}
/// The error of command `c` for a job the session does not keep.
fn no_job(c: &str, job: u64) -> EngineError {
bad(c, format!("no Concept to Vector job {job}: it was never made, or was dropped (see conceptVector.results)"))
}
/// The index of job `job` among those `s` keeps.
fn job_index(s: &mut Session, c: &str, job: u64) -> Result<usize> {
s.prune_concept_jobs();
s.concept.jobs.iter().position(|j| j.id == job).ok_or_else(|| no_job(c, job))
}
fn providers(s: &mut Session, _: &Value) -> Result<Value> {
let list: Vec<Value> = s
.concept
.registry
.iter()
.map(|p| {
let c = &p.capabilities;
json!({
"id": p.id,
"name": p.name,
"available": true,
"offline": c.offline,
"imageInput": c.image_input,
"vectorOutput": c.vector_output,
"prompt": c.prompt,
"rasterOutput": c.raster_output,
"maxStyles": MAX_STYLES,
"styles": c.styles,
})
})
.collect();
let selected = s.concept.registry.iter().next().map(|p| p.id);
Ok(json!({ "providers": list, "selected": selected }))
}
fn generate(s: &mut Session, p: &Value) -> Result<Value> {
let run = ConceptRun::prepare(s, p)?;
// A script's run stops when the script is asked to stop, and keeps no job.
let stop = s.script_in_run.then(|| s.script_interrupt());
let stopped = || stop.as_ref().is_some_and(|i| i.is_set());
let made = run.run(&|_, _| !stopped()).map_err(provider_error)?;
if stopped() {
return Err(EngineError::Cancelled);
}
run.finish(s, made).ok_or(EngineError::NoDocument)
}
fn results(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "conceptVector.results";
let job = job_param(C, p)?;
let at = job_index(s, C, job)?;
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
Ok(job_json(&s.concept.registry, j))
}
/// The error of an insert or cancel played from recorded steps: a job lives only in this session,
/// and a job number from another one may name other results.
const REPLAYED: &str = "Concept to Vector jobs are not saved, so a recorded insert or cancel does not play again: generate again";
fn cancel(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "conceptVector.cancel";
if s.replaying() {
return Err(bad(C, REPLAYED));
}
let job = job_param(C, p)?;
let at = job_index(s, C, job)?;
if let Some(j) = s.concept.jobs.get_mut(at) {
j.outcome = Outcome::Canceled;
}
Ok(json!({ "job": job, "state": "canceled" }))
}
/// The appearance of variation path `p`, its widths scaled by `unit` (points per pixel).
fn appearance_of(p: &cv::VectorPath, unit: f64) -> Appearance {
let solid = |c: [u8; 3]| Paint::solid(Color::rgb8(c[0], c[1], c[2]));
let mut items = vec![];
if let Some(c) = p.fill {
items.push(AppearanceItem::Fill(FillLayer::new(solid(c))));
}
if let Some((c, w)) = p.stroke {
let cap = if p.square_caps { LineCap::Square } else { LineCap::Round };
items.push(AppearanceItem::Stroke(StrokeLayer { cap, join: LineJoin::Round, ..StrokeLayer::new(solid(c), w * unit) }));
}
Appearance { items, ..Default::default() }
}
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "conceptVector.insert";
if s.replaying() {
return Err(bad(C, REPLAYED));
}
let job = job_param(C, p)?;
let at = job_index(s, C, job)?;
let list_error = || bad(C, format!("`variations` must list different style ids of job {job}"));
let listed = match p.get("variations") {
Some(Value::Array(a)) if !a.is_empty() => a,
_ => return Err(list_error()),
};
let stale = || bad(C, format!("job {job} no longer applies: its document, image or image placement changed, so generate again"));
let (doc, source, image, bytes, picked, label_of) = {
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
let Outcome::Done(all) = &j.outcome else { return Err(bad(C, format!("job {job} has no results to insert: it was canceled"))) };
// The count is checked before the ids are read or scanned for repeats.
if listed.len() > all.len() {
return Err(list_error());
}
let chosen: Vec<&str> = listed.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(list_error)?;
let unique = chosen.iter().enumerate().all(|(i, id)| !chosen.get(..i).unwrap_or_default().contains(id));
let mut picked: Vec<Variation> = all.iter().filter(|v| chosen.contains(&v.style.as_str())).cloned().collect();
if !unique || picked.len() != chosen.len() {
return Err(list_error());
}
// In the provider's order, whatever order they were listed or generated in.
picked.sort_by_key(|v| style_rank(&s.concept.registry, &j.provider, &v.style));
let labels: Vec<String> = picked.iter().map(|v| style_label(&s.concept.registry, &j.provider, &v.style)).collect();
(j.doc, j.source, j.image.clone(), Arc::clone(&j.bytes), picked, labels)
};
// The same document, the same object showing the same pixels where they were.
let st = s.doc()?;
let now = st.doc.node(source).and_then(shown_image);
let same_pixels = || st.doc.images.get(&image.key).is_some_and(|b| Arc::ptr_eq(&b.bytes, &bytes) || *b.bytes == *bytes);
let current = st.uid == doc && now.is_some_and(|i| i.key == image.key && i.xf == image.xf && i.width == image.width && i.height == image.height);
if !current || !same_pixels() {
return Err(stale());
}
if !st.doc.is_editable(source) {
return Err(bad(C, LOCKED));
}
// The results go above the outermost group around the image that clips or masks it, so that
// it hides none of them, and above the outermost envelope, blend, repeat or other live object,
// the outermost group whose members it makes or places ([`generated`]), and the outermost
// group with effects or fills and strokes of its own, so that its content and the place its
// effects measure from stay as they are. A layer that clips or masks its art, or has effects,
// fills or strokes of its own, leaves them nowhere to go. An effect that moves or reshapes
// the image, its own or a group's around it, shows it away from its placement, which the
// results are placed by.
let ancestry = st.doc.ancestry(source).ok_or_else(stale)?;
let moves = |id: &NodeId| st.doc.node(*id).is_some_and(|n| !n.is_layer() && vectorcraft_render::effects::has_geometry(&n.appearance.effects));
if ancestry.iter().any(moves) {
return Err(bad(C, "the image or a group around it has effects that move or reshape it, so the results would not go beside it"));
}
// A distorted image ([`Node::image_quad`]) is drawn at its corners, not by its transform.
if st.doc.node(source).and_then(shown_image_node).is_some_and(Node::is_distorted_image) {
return Err(bad(C, "the image is distorted, so the results would not go beside it"));
}
let mut anchor = source;
for &id in ancestry.iter().rev().skip(1) {
let n = st.doc.node(id).ok_or_else(stale)?;
let masked = n.extras().mask.as_ref().is_some_and(|m| !m.disabled);
if matches!(n.kind, NodeKind::Layer { clip: true, .. }) {
return Err(bad(C, "the image is on a layer with a clipping mask, which would hide the results"));
}
if n.is_layer() && masked {
return Err(bad(C, "the image is on a layer with an opacity mask, which would hide the results"));
}
let styled = !n.appearance.items.is_empty() || !n.appearance.effects.is_empty();
if n.is_layer() && !n.appearance.effects.is_empty() {
return Err(bad(C, "the image is on a layer with effects of its own, which would apply to the results"));
}
// A layer's fills and strokes paint over its members, the results included.
if n.is_layer() && !n.appearance.items.is_empty() {
return Err(bad(C, "the image is on a layer with fills or strokes of its own, which would apply to the results"));
}
let live = !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || generated(n);
if !n.is_layer() && (masked || live || styled || matches!(n.kind, NodeKind::Group { clip: true, .. })) {
anchor = id;
}
}
let src = image_rect(&image).ok_or_else(stale)?;
// A variation with no paths adds nothing: it is left out, and with none left nothing changes.
let (picked, label_of): (Vec<Variation>, Vec<String>) = picked.into_iter().zip(label_of).filter(|(v, _)| !v.paths.is_empty()).unzip();
if picked.is_empty() {
return Ok(json!({ "ids": [] }));
}
let unit = image.xf.determinant().abs().sqrt();
// Each chosen variation's box over the image: the image's box and the variation's painted
// bounds, which may reach past it. A square cap's corner lies half the width along the path
// and half across it from the end, so up to √2 times half the width past it on an axis.
let boxes: Vec<Rect> = picked
.iter()
.map(|v| {
v.paths
.iter()
.filter_map(|vp| {
let reach = if vp.square_caps { std::f64::consts::SQRT_2 } else { 1.0 };
let half = vp.stroke.map_or(0.0, |(_, w)| w * unit / 2.0 * reach);
vp.path.transformed(image.xf).bounds().map(|b| b.inflate(half, half))
})
.fold(src, |a, b| a.union(b))
})
.collect();
// How far each variation's box is moved past the first's: each box starts GAP to the right of
// the one before it (`width + GAP` further right for boxes the image's size).
let mut offsets = Vec::with_capacity(boxes.len());
let mut next = 0.0;
for (k, b) in boxes.iter().enumerate() {
if let Some(prev) = k.checked_sub(1).and_then(|j| boxes.get(j)) {
next += prev.x1 - b.x0 + GAP;
}
offsets.push(next);
}
// The first box's left edge, which may lie left of the image's where its variation paints there.
let first = boxes.first().map_or(src.x0, |b| b.x0);
// The boxes with the first one's left edge moved to `x0`, the others after it.
let row = |x0: f64| -> Vec<Rect> {
boxes
.iter()
.zip(&offsets)
.map(|(b, off)| {
let dx = x0 + off - first;
Rect::new(b.x0 + dx, b.y0, b.x1 + dx, b.y1)
})
.collect()
};
// The painted bounds of every visible object (the source's too: an Image Trace object's traced
// art and effects can reach past the image), and the image's own box. A layer or group that
// paints nothing of its own is measured by its members (an opacity mask only hides them); one
// that clips, by its members after the clipping path, cut to what it paints.
let mut obstacles: Vec<Rect> = vec![src];
// One lookup of the symbols for the whole walk, so each symbol's art is measured once.
let symbols = st.doc.symbol_boxes();
let mut stack: Vec<(&Arc<Node>, Option<Rect>)> = st.doc.layers.iter().map(|l| (l, None)).collect();
while let Some((node, within)) = stack.pop() {
if !node.visible {
continue;
}
let cut = |b: Rect| match within {
Some(w) => Some(b.intersect(w)).filter(|i| i.width() > 0.0 && i.height() > 0.0),
None => Some(b),
};
let painted = || vectorcraft_render::painted_bounds_with(&symbols, node).and_then(cut);
if node.id == source {
obstacles.extend(painted());
continue;
}
let clips = matches!(node.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
let by_members = (node.is_layer() || matches!(node.kind, NodeKind::Group { .. }))
&& node.appearance.items.is_empty()
&& node.appearance.effects.is_empty();
if by_members {
// A clipping path paints its fills and strokes when they are set (`Node::clip_paint`),
// its strokes outside the clip too, whether or not it is shown.
if clips && let Some(path) = node.children().into_iter().flatten().next() {
let paint = path.clip_paint();
for part in [paint.fill, paint.stroke].into_iter().flatten() {
if let Some(b) = vectorcraft_render::painted_bounds_with(&symbols, &part).and_then(cut) {
obstacles.push(b);
}
}
}
let within = if clips {
// Nothing of a clipping group shows outside what it paints.
let Some(shown) = painted() else { continue };
Some(shown)
} else {
within
};
stack.extend(node.children().into_iter().flatten().skip(usize::from(clips)).map(|c| (c, within)));
} else if let Some(b) = painted() {
obstacles.push(b);
}
}
let placed = place_row(&row, src.x1 + GAP, &obstacles);
let room = || bad(C, "there is no room for the results to the right of the image");
let Some(x0) = placed.filter(|x0| x0.is_finite()) else {
return Err(room());
};
let right = row(x0).iter().map(|r| r.x1).fold(f64::NEG_INFINITY, f64::max);
if right > crate::MAX_COORD {
return Err(room());
}
let ids = s.edit("Concept to Vector", |d, sel| {
let mut groups = vec![];
for ((v, label), off) in picked.into_iter().zip(label_of).zip(&offsets) {
let dx = x0 + off - first;
let xf = Affine::translate((dx, 0.0)) * image.xf;
let mut members = Vec::with_capacity(v.paths.len());
for vp in &v.paths {
let path = vp.path.transformed(xf);
if path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().any(|c| c.abs() > crate::MAX_COORD)) {
return Err(room());
}
let mut node = shape_node(d, path, None);
node.appearance = appearance_of(vp, unit).into();
members.push(Arc::new(node));
}
let mut g = Node::group(d.alloc_id(), members);
g.name = Some(label);
groups.push(g);
}
let ids: Vec<NodeId> = groups.iter().map(|g| g.id).collect();
d.insert_beside(vec![(anchor, groups)], false)?;
sel.set(ids.iter().copied());
Ok(ids)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
#[cfg(test)]
thread_local! {
/// How many times [`place_row`] has looked at an object on this thread.
pub(crate) static LOOKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Where the left edge of the row's first box goes, from `start` rightward, so that no box meets
/// one of `obstacles`: a box in the way moves GAP past the rightmost object it meets. `row(x0)`
/// gives the boxes with the first one's left edge at `x0`. `None` when the moves run out.
pub(crate) fn place_row(row: &dyn Fn(f64) -> Vec<Rect>, start: f64, obstacles: &[Rect]) -> Option<f64> {
// Each box's objects: those level with it, by their left edges. The row only moves right, so
// each object joins its box's list once, when the box's right edge passes its left edge, and
// stays: of those joined, only the rightmost right edge matters, and the box meets that object
// exactly when the edge is right of the box's left edge.
let lanes: Vec<Vec<Rect>> = row(start)
.iter()
.map(|b| {
let mut lane: Vec<Rect> = obstacles.iter().filter(|o| o.y0 < b.y1 && b.y0 < o.y1).copied().collect();
lane.sort_by(|a, b| a.x0.total_cmp(&b.x0));
lane
})
.collect();
let mut joined = vec![0usize; lanes.len()];
let mut reach = vec![f64::NEG_INFINITY; lanes.len()];
let mut x0 = start;
// Each move takes a box past every object joined to it, so another move of that box needs a
// new object to join.
for _ in 0..=lanes.iter().map(Vec::len).sum::<usize>() {
let mut shift = None;
for ((r, lane), (j, far)) in row(x0).iter().zip(&lanes).zip(joined.iter_mut().zip(reach.iter_mut())) {
while let Some(o) = lane.get(*j).filter(|o| o.x0 < r.x1) {
#[cfg(test)]
LOOKS.with(|n| n.set(n.get() + 1));
*far = far.max(o.x1);
*j += 1;
}
// The first box in the way, moved past the rightmost object it meets.
if shift.is_none() && *far > r.x0 {
shift = Some(*far + GAP - r.x0);
}
}
match shift {
None => return Some(x0),
Some(by) => x0 += by,
}
}
None
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "conceptVector.providers",
"Concept to Vector Providers",
[],
None,
"{} → {providers: [{id, name, available, offline, imageInput, vectorOutput, prompt, rasterOutput, maxStyles: 8, styles: [{id, label}]}], selected: the id the panel uses} the providers conceptVector.generate can call by id; the built-in offline.traceStyles makes its styles with Image Trace on this computer (outline, inkLines, flatColor, detailedColor, grayTones), takes no prompt and makes vector art only",
always,
providers
),
cmd!(
query "conceptVector.generate",
"Generate Concept to Vector Styles",
[],
None,
"{id?: image or unexpanded Image Trace object (default: the one selected object), provider: id (conceptVector.providers; no other provider is used in its place), styles: [style id…] (1 to 8 different ids of that provider), detail?: 0-100 (50: how much of the image's detail each style keeps), prompt?: text (an error for a provider without prompts unless empty), output?: \"vector\" (the only output; any other value is an error)} one variation of the image for each style, kept by this session as a job and not put in the document; a provider that takes no image, makes no vector art or takes no prompt when one is given is refused with that reason; an object that is locked or hidden, itself or by a layer or group around it, or on a locked artboard, is refused → {job, provider, source: id, state: \"done\", variations: [{style, label, paths, anchors, bounds: [x0,y0,x1,y1] in the image's pixels, warnings: [text…]}]}",
has_doc,
generate
),
cmd!(
query "conceptVector.results",
"Concept to Vector Results",
[],
None,
"{job} a job conceptVector.generate made, as it returned it, or with state \"canceled\" and no variations; the session keeps the 4 newest jobs, until their document closes → {job, provider, source, state, variations}",
has_doc,
results
),
cmd!(
query "conceptVector.cancel",
"Cancel Concept to Vector Job",
[],
None,
"{job} drop a job's variations, so that it can't be inserted; canceling it again does the same; an error when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved → {job, state: \"canceled\"}",
has_doc,
cancel
),
cmd!(
"conceptVector.insert",
"Insert Concept to Vector Styles",
[],
None,
"{job, variations: [style id…] (different styles of the job)} put a group of each chosen variation, named after its style and in the provider's order, in a row to the right of the job's image, each the image's size with 24 pt between them, moved further right past other visible art in their way, where a variation reaches past its box too (the next one then starts 24 pt past what it paints); the groups go above the outermost clip group or opacity-masked group around the image, and above the outermost envelope, blend, repeat or other live object, the outermost group whose members it makes or places (a graph, an Objects on Path, Shaper, dimension, flare or Live Paint group, a compound shape) and the outermost group with effects or fills and strokes of its own around it; the image and other art stay as they are; one undo step; a variation with no paths is left out, and when every chosen one has none nothing changes (no undo step, ids []); an error when the job's document is not the active one, the object, its image or its placement changed, the object is now locked or hidden, or it is on a layer with a clipping mask, an opacity mask, or effects, fills or strokes of its own, or it or a group around it has effects that move or reshape it, or its image is distorted (Perspective Distort or Free Distort), and when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved →{ids: the groups, selected}",
has_doc,
insert
),
]
}
+1 -1
View File
@@ -33,6 +33,6 @@ mod smooth;
pub(super) use anchors::remove_anchors_following;
pub use commands::specs;
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt, with_anchor_path};
pub(super) use cut::{components, erase_outline};
pub(super) use freehand::freehand_brushed;
+44 -24
View File
@@ -1,4 +1,4 @@
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound};
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, with_anchor_path, within_input_bound};
use super::{
Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2,
add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or,
@@ -111,6 +111,24 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let ai = usize_req(p, "anchor", C)?;
let curvature = switch_or(p, "curvature", false, C)?;
let removed = s.edit("Delete Anchor Point", |d, sel| {
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
// Type on a path keeps its path: the anchor goes only while two or more stay.
with_anchor_path(d, id, |path| {
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
if ai >= sp.anchors.len() {
return Err(EngineError::Other("no such anchor".into()));
}
if curvature {
vectorcraft_tools::draw2::curvature_remove(sp, ai);
} else {
po::remove_anchors(sp, &[ai]);
}
Ok(())
})?;
sel.anchors.remove(&id);
sel.segments.remove(&id);
return Ok(false);
}
let path = match d.node(id).map(|n| &n.kind) {
Some(NodeKind::Path { path, .. }) => path,
Some(_) => return Err(EngineError::Other(format!("object {id} is not a path"))),
@@ -312,23 +330,24 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "x and y must be finite"));
}
s.edit("Convert Anchor Point", |d, _| {
let path = path_mut(d, id)?;
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
if smooth && target.is_none() {
if ai >= sp.anchors.len() {
return Err(EngineError::Other("no such anchor".into()));
with_anchor_path(d, id, |path| {
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
if smooth && target.is_none() {
if ai >= sp.anchors.len() {
return Err(EngineError::Other("no such anchor".into()));
}
// Without a handle position the anchor curves as the Curvature tool curves a point; one
// with no direction to take stays as it is.
vectorcraft_tools::draw2::curvature_smooth(sp, ai);
return Ok(());
}
// Without a handle position the anchor curves as the Curvature tool curves a point; one
// with no direction to take stays as it is.
vectorcraft_tools::draw2::curvature_smooth(sp, ai);
return Ok(());
}
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
match target {
Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t),
_ => a.retract(),
}
Ok(())
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
match target {
Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t),
_ => a.retract(),
}
Ok(())
})
})?;
ok()
}
@@ -345,13 +364,14 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
}
let perpendicular = switch_or(p, "perpendicular", false, C)?;
s.edit("Reshape", |d, _| {
let path = path_mut(d, id)?;
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) };
if !bent {
return Err(EngineError::Other("no such segment".into()));
}
Ok(())
with_anchor_path(d, id, |path| {
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) };
if !bent {
return Err(EngineError::Other("no such segment".into()));
}
Ok(())
})
})?;
ok()
}
+3 -3
View File
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Anchor Point",
[],
None,
"{id, subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); on a path with rounded Live Corners, the corner the anchor belongs to is removed and the other corners stay live",
"{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least; on a path with rounded Live Corners, the corner the anchor belongs to is removed and the other corners stay live",
has_doc,
remove_anchor
),
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Anchor Point",
[],
None,
"{id, subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)",
"{id (a path, or type on a path), subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)",
has_doc,
convert_anchor
),
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reshape Segment",
[],
None,
"{id, subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does",
"{id (a path, or type on a path), subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does",
has_doc,
reshape_segment
),
+23
View File
@@ -308,6 +308,29 @@ pub(super) fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> {
}
}
/// Run `f` on the anchors the anchor tools edit on `id` ([`Node::anchor_path`]): a path's, as
/// [`path_mut`] gives them, or type on a path's path in document space. The type keeps the edited
/// path and lays out again; an edit that leaves a subpath with fewer than two anchors, or a path
/// that is not finite or reaches past the canvas, is an error and changes nothing.
pub(in super::super) fn with_anchor_path<R>(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result<R>) -> Result<R> {
if !matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
return f(path_mut(d, id)?);
}
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
let mut path = n.anchor_path().map(std::borrow::Cow::into_owned).ok_or_else(|| EngineError::Other(format!("object {id} is not a path")))?;
let r = f(&mut path)?;
let within = path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD));
if path.subpaths.is_empty() || path.subpaths.iter().any(|sp| sp.anchors.len() < 2) || !within {
return Err(EngineError::Other(format!("type on a path keeps at least two anchors on its path, within the canvas (object {id})")));
}
let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::NoNode(id)) };
if !t.set_type_path(&path) {
return Err(EngineError::Other(format!("the path of object {id} would not be finite")));
}
crate::cmd::typecmd::refresh_bounds(t);
Ok(r)
}
pub(super) fn path_of(d: &Document, id: NodeId) -> Result<(PathData, FillRule)> {
match d.node(id).map(|n| &n.kind) {
Some(NodeKind::Path { path, rule, .. }) => Ok((path.clone(), *rule)),
+5 -1
View File
@@ -14,7 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
// The active artboard the app passes, for the steps that act on it.
let artboard = p.get("artboard").and_then(Value::as_u64);
// What an error rolls back besides the documents: session-level state a step may change
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group).
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group, the
// Concept to Vector jobs).
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
// would otherwise run inside it and take its baseline as theirs (#1697).
if s.active().is_some() && !s.previewing {
@@ -24,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
}
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
let (clipboard_copied, copies) = (s.clipboard_copied, s.copies);
let concept_jobs = s.concept_jobs_snapshot();
// The documents as they are now, whole: what a failed step brings back. Their art, history,
// file, format and saved state share their data with the open ones until a step changes them.
let start = s.docs.clone();
@@ -42,6 +44,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
Ok(results) => {
s.notify_text_tool("batch.end");
s.batch_steps = Some(grouped);
s.prune_concept_jobs();
results
}
Err(e) => {
@@ -59,6 +62,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
(s.clipboard_copied, s.copies) = (clipboard_copied, copies);
s.pending_paint = None;
s.restore_concept_jobs(concept_jobs);
return Err(e);
}
};
+8 -6
View File
@@ -308,10 +308,12 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool {
/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part
/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages'
/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its
/// type as text?
/// trim boxes by default, with its type as text?
fn reads_layers_alone(opts: &LoadOptions) -> bool {
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
reads_editing_copy(opts)
&& !opts.explicit_crop_box
&& opts.crop == vectorcraft_pdf::CropTo::Crop
&& opts.text_as != vectorcraft_pdf::TextAs::Outlines
}
/// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts`
@@ -475,8 +477,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// The file is read and checked once, for the document it carries, its pages, the
// editor's copy and its File Info.
let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref());
// Saved with Preserve Editing: the document it carries, unless some pages are picked.
let editing = (opts.pages.is_none() && opts.native)
// Restore the preserved document when opening all pages at their original size.
let editing = (opts.pages.is_none() && opts.native && !opts.explicit_crop_box)
.then(|| opened.as_ref().ok().and_then(|o| o.editing()))
.flatten()
.map(|e| (e.intact, move || Some(e.data)));
@@ -524,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
}
None => None,
};
let alone = (r.only_text || empty)
let alone = (!opts.explicit_crop_box && (r.only_text || empty))
.then(copy_alone)
.flatten()
.and_then(|read| read.ok())
+7 -1
View File
@@ -173,7 +173,13 @@ impl LoadOptions {
/// box, a password, without its hidden layers, without the VectorCraft document it carries, its
/// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name).
pub fn is_partial(&self) -> bool {
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
self.pages.is_some()
|| self.crop != CropTo::default()
|| self.explicit_crop_box
|| self.password.is_some()
|| !self.layers
|| !self.native
|| self.link_pages
}
/// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible
@@ -1395,8 +1395,7 @@ fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
let _ = std::fs::remove_dir_all(&d);
}
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
/// Linked pages default to the trim box with the bleed and honor an explicit Crop Box.
#[test]
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
@@ -1416,6 +1415,13 @@ fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
s.execute("document.open", &json!({"path": path, "linkPages": true, "cropTo": "crop"})).unwrap();
let cropped = &s.doc().unwrap().doc;
assert!(cropped.artboards[0].rect.width() > board.width());
let placed = &cropped.layers[0].children().unwrap()[0];
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
assert_eq!(p.page_box, vectorcraft_doc::PageBox::Crop);
let _ = std::fs::remove_dir_all(&d);
}
+87 -51
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Direction Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
"{id (a path, or type on a path), subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
has_doc,
set_handle
),
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Anchor Point",
[],
None,
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
"{id (a path, or type on a path), subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
has_doc,
move_anchor
),
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Anchor Point",
[],
None,
"{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; on a path with rounded Live Corners, an anchor added on a side keeps the corners live (the selection follows its corners), and one added on a corner's arc makes the path plain and answers with a warning",
"{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection); on a path with rounded Live Corners, an anchor added on a side keeps the corners live (the selection follows its corners), and one added on a corner's arc makes the path plain and answers with a warning",
has_doc,
insert_anchor
),
@@ -719,39 +719,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
s.edit("Reshape", |d, _| {
let path = path_mut(d, id)?;
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
let old_point = a.p;
let old_handle = if out { a.h_out } else { a.h_in };
if let Some(to) = at {
a.translate(to - a.p);
}
let handle = if out { a.h_out } else { a.h_in };
let kind_changes = independent && a.kind != AnchorKind::Corner;
// Ordinary decimal moves can round `at - old_point` differently from the handle's
// translation. Within that calculation's roundoff, place the selected point exactly
// without realigning the other stored Smooth handle. Real edits still use set_handle.
let translation_roundoff = at.is_some_and(|to| {
let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| {
let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0);
(actual - requested).abs() <= 4.0 * f64::EPSILON * scale
};
to != old_point && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y)
});
if !kind_changes && (handle == pos || translation_roundoff) {
if out {
a.h_out = pos;
} else {
a.h_in = pos;
super::draw2::with_anchor_path(d, id, |path| {
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
let old_point = a.p;
let old_handle = if out { a.h_out } else { a.h_in };
if let Some(to) = at {
a.translate(to - a.p);
}
} else {
a.set_handle(out, pos, independent);
}
if symmetric {
let opposite = a.p - (pos - a.p);
if out { a.h_in = opposite } else { a.h_out = opposite }
}
Ok(())
let handle = if out { a.h_out } else { a.h_in };
let kind_changes = independent && a.kind != AnchorKind::Corner;
// Ordinary decimal moves can round `at - old_point` differently from the handle's
// translation. Within that calculation's roundoff, place the selected point exactly
// without realigning the other stored Smooth handle. Real edits still use set_handle.
let translation_roundoff = at.is_some_and(|to| {
let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| {
let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0);
(actual - requested).abs() <= 4.0 * f64::EPSILON * scale
};
to != old_point
&& matches(handle.x, pos.x, old_point.x, old_handle.x, to.x)
&& matches(handle.y, pos.y, old_point.y, old_handle.y, to.y)
});
if !kind_changes && (handle == pos || translation_roundoff) {
if out {
a.h_out = pos;
} else {
a.h_in = pos;
}
} else {
a.set_handle(out, pos, independent);
}
if symmetric {
let opposite = a.p - (pos - a.p);
if out { a.h_in = opposite } else { a.h_out = opposite }
}
Ok(())
})
})?;
ok()
}
@@ -852,22 +855,26 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
if s.script_running() {
return Err(EngineError::Busy);
}
let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| {
sp.anchors.get(ai).is_some_and(|a| {
let mut linked = *a;
linked.link_handle(out, pos, sp.has_segment(ai, !out));
linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos))
let unchanged = s.doc()?.doc.node(id).and_then(Node::anchor_path).is_some_and(|pd| {
pd.subpaths.get(si).is_some_and(|sp| {
sp.anchors.get(ai).is_some_and(|a| {
let mut linked = *a;
linked.link_handle(out, pos, sp.has_segment(ai, !out));
linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos))
})
})
});
if unchanged {
return ok();
}
s.edit("Reshape", |d, _| {
let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
let pull_out = sp.has_segment(ai, !out);
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
a.link_handle(out, pos, pull_out);
Ok(())
super::draw2::with_anchor_path(d, id, |path| {
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
let pull_out = sp.has_segment(ai, !out);
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
a.link_handle(out, pos, pull_out);
Ok(())
})
})?;
ok()
}
@@ -958,6 +965,13 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
s.edit("Move", |d, sel| {
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
return super::draw2::with_anchor_path(d, id, |path| {
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
Ok(())
});
}
let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p);
let before = corner_sources(d, id);
let moved = BTreeSet::from([(si, ai)]);
@@ -975,24 +989,25 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path that has it.
/// Busy while a script runs, as [`Session::edit`] is.
/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path, or type
/// on a path ([`Node::anchor_path`], in document space), that has it. Busy while a script runs, as
/// [`Session::edit`] is.
fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anchor>> {
if s.script_running() {
return Err(EngineError::Busy);
}
let d = &s.doc()?.doc;
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
Ok(d.node(id).and_then(Node::anchor_path).and_then(|path| path.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).copied()))
}
/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or
/// incoming side; false when the path, subpath or anchor is not there.
/// Whether anchor `ai` of subpath `si` of path `id` (or of type on a path's path) has a segment on
/// its outgoing (`out`) or incoming side; false when the path, subpath or anchor is not there.
fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result<bool> {
if s.script_running() {
return Err(EngineError::Busy);
}
let d = &s.doc()?.doc;
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
Ok(d.node(id).and_then(Node::anchor_path).is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, out))))
}
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
@@ -2639,6 +2654,27 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?;
let (idx, expanded) = s.edit("Add Anchor Point", |d, sel| {
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
let idx = super::draw2::with_anchor_path(d, id, |path| {
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
if seg >= sp.segment_count() {
return Err(EngineError::Other("no such segment".into()));
}
Ok(sp.insert_anchor(seg, t))
})?;
// Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor`
// leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only.
if select_anchor || !sel.contains(id) {
sel.clear();
}
sel.anchors.remove(&id);
sel.segments.remove(&id);
if sel.key_anchor.is_some_and(|(k, _)| k == id) {
sel.key_anchor = None;
}
sel.add(id);
return Ok((idx, false));
}
let sp = d.node(id).and_then(Node::path_data).ok_or(EngineError::NoNode(id))?.subpaths.get(si);
if seg >= sp.ok_or_else(|| EngineError::Other("no such subpath".into()))?.segment_count() {
return Err(EngineError::Other("no such segment".into()));
+1
View File
@@ -895,6 +895,7 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[
(&["Object"], "Perspective"),
(&["Object"], "Live Paint"),
(&["Object"], "Image Trace"),
(&["Object"], "Concept to Vector…"),
(&["Object"], "Text Wrap"),
(&["Object"], "Clipping Mask"),
(&["Object"], "Compound Path"),
@@ -762,7 +762,8 @@ pub(super) const ALLOWED: &[&str] = &[
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
/// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and
/// report where it is on disk, or edit text once per match with no limit on the matches in one call.
/// report where it is on disk, edit text once per match with no limit on the matches in one call,
/// or hand an image to a Concept to Vector provider and its results.
pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
@@ -770,6 +771,11 @@ pub(super) const DENIED: &[&str] = &[
"addon.type.fontSheet",
"addon.type.numbers",
"color.contrast",
"conceptVector.cancel",
"conceptVector.generate",
"conceptVector.insert",
"conceptVector.providers",
"conceptVector.results",
"effect.refreshDeferred",
"graphicStyle.setOptions",
"object.blend.createSpine",
+269
View File
@@ -0,0 +1,269 @@
//! Concept to Vector providers: what makes vector variations of a selected image.
//!
//! A provider ([`Provider`]) takes one image's encoded pixels and up to [`MAX_STYLES`] of its own
//! style ids ([`Request`]), and returns one [`Variation`] per style, in the order asked, as paths
//! in the image's pixel space with explicit paints. It sees nothing else of the session or the
//! document. The session keeps the providers in a [`Registry`] and calls one only by its id: an
//! unknown or incapable provider is an error, never a substitute.
//!
//! The host checks every result again ([`check_result`]) before it keeps it, whatever provider
//! made it: the number and order of the variations, finite coordinates and widths within bounds,
//! and the totals [`MAX_ANCHORS`] and [`MAX_PATHS`] across all styles.
//!
//! The one built-in provider ([`offline::ID`]) makes its styles with Image Trace, on this
//! computer: it takes no prompt and makes vector art only.
pub mod offline;
#[cfg(test)]
mod tests;
use std::sync::Arc;
use vectorcraft_geom::{PathData, Point};
/// The most styles one request may ask for.
pub const MAX_STYLES: usize = 8;
/// The most anchor points all the variations of one request may hold together.
pub const MAX_ANCHORS: usize = 1_000_000;
/// The most paths all the variations of one request may hold together, each subpath of a compound
/// path counted as one.
pub const MAX_PATHS: usize = 250_000;
/// The most warnings a variation may carry, and the most characters in each.
pub const MAX_WARNINGS: usize = 16;
const MAX_WARNING_CHARS: usize = 500;
/// One of a provider's styles: its stable id and its English name.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct Style {
pub id: &'static str,
pub label: &'static str,
}
/// What a provider takes and makes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Capabilities {
/// It takes an image as its input.
pub image_input: bool,
/// It makes editable vector paths.
pub vector_output: bool,
/// It takes a text prompt.
pub prompt: bool,
/// It makes raster images.
pub raster_output: bool,
/// It runs on this computer without a network.
pub offline: bool,
/// Its styles, in the order it lists them.
pub styles: Vec<Style>,
}
/// The kind of result a request asks for. `conceptVector.generate` asks only for
/// [`Output::Vector`]: a [`Variation`] holds vector paths.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Output {
Vector,
Raster,
}
/// One request: the encoded pixels of an image, and how to make its variations.
#[derive(Clone, Debug)]
pub struct Request {
/// The image's encoded bytes (PNG, JPEG, WebP or GIF), as the document holds them.
pub image: Arc<Vec<u8>>,
/// The image's size in pixels: the space the variations' paths are in.
pub width: u32,
pub height: u32,
/// The prompt, trimmed; `None` when there is none.
pub prompt: Option<String>,
/// The provider's style ids, 1 to [`MAX_STYLES`] of them, each once.
pub styles: Vec<String>,
/// How much of the image's detail to keep, 0 (least) to 100 (most).
pub detail: u8,
pub output: Output,
}
/// One path of a variation, in the image's pixel space (`(0, 0)` top left, `(width, height)` bottom
/// right).
#[derive(Clone, Debug, PartialEq)]
pub struct VectorPath {
pub path: PathData,
/// The fill color (sRGB), if it is filled.
pub fill: Option<[u8; 3]>,
/// The stroke color (sRGB) and width in pixels, if it is stroked.
pub stroke: Option<([u8; 3], f64)>,
/// Stroked: the stroke's ends are square (cut straight half the width past the path's end);
/// otherwise round.
pub square_caps: bool,
}
/// The variation a provider made for one style.
#[derive(Clone, Debug, PartialEq)]
pub struct Variation {
/// The style id it was made for.
pub style: String,
/// Its paths, bottom-most first.
pub paths: Vec<VectorPath>,
/// Notes for the person who asked (a scaled-down image, nothing traced).
pub warnings: Vec<String>,
}
impl Variation {
/// Its anchor points, every path counted.
pub fn anchors(&self) -> usize {
self.paths.iter().map(|p| p.path.anchor_count()).sum()
}
}
/// Why a provider made nothing.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
pub enum ProviderError {
/// The image or the request cannot be used.
#[error("{0}")]
InvalidInput(String),
/// The provider does not do what the request asks.
#[error("{0}")]
Unsupported(String),
/// The provider cannot run now.
#[error("{0}")]
Unavailable(String),
/// The caller stopped it.
#[error("cancelled; nothing was changed")]
Canceled,
/// The results would pass a limit.
#[error("the results would have more than {0} anchor points: lower Detail or choose fewer styles")]
ResourceLimit(usize),
/// The provider's results do not match the request, or are out of bounds.
#[error("the provider's results do not match the request or are malformed")]
InvalidResult,
/// The provider stopped on a fault of its own.
#[error("the provider stopped with an internal error: {0}")]
Internal(String),
}
/// How far a provider has got: `steps(done, total)`; it stops with [`ProviderError::Canceled`]
/// once this answers `false`.
pub type Steps<'a> = &'a (dyn Fn(u64, u64) -> bool + Sync);
/// Something that makes vector variations of an image.
pub trait Provider: Send + Sync {
/// Its stable id, such as `offline.traceStyles`.
fn id(&self) -> &'static str;
/// Its English name.
fn name(&self) -> &'static str;
fn capabilities(&self) -> Capabilities;
/// One variation for each of `request.styles`, in that order. A style's variation depends only
/// on the image, the prompt, the detail and that style, not on the other styles asked for: a
/// caller with no thread to wait on asks for one style at a time when [`Provider::parts`] gives
/// `None` (`ConceptRun::run_part`, which the web build uses).
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError>;
/// What [`Provider::generate`] makes, made a part at a time ([`Parts`]), for a caller with no
/// thread to wait on; `None` (the default) when it makes no parts smaller than one style.
fn parts(&self, _request: &Request) -> Option<Box<dyn Parts>> {
None
}
}
/// A request's variations made a part at a time: each call of [`Parts::step`] does a part and
/// returns, so that the caller can run other work, or stop, between parts.
pub trait Parts: Send {
/// Does the next part → the variations once the last part is done, `None` before it.
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError>;
/// The styles made so far.
fn styles_done(&self) -> usize;
}
/// The providers a session can call, by id.
#[derive(Clone)]
pub struct Registry {
providers: Vec<Registered>,
}
/// A provider in a [`Registry`], with the id, name and capabilities it gave when it was
/// registered.
#[derive(Clone)]
pub struct Registered {
pub id: &'static str,
pub name: &'static str,
pub capabilities: Capabilities,
pub provider: Arc<dyn Provider>,
}
impl Default for Registry {
/// The built-in provider only.
fn default() -> Self {
let p = offline::TraceStyles;
Self { providers: vec![Registered { id: p.id(), name: p.name(), capabilities: p.capabilities(), provider: Arc::new(p) }] }
}
}
impl Registry {
/// A registry with no provider.
pub fn empty() -> Self {
Self { providers: vec![] }
}
/// Add `provider`, reading its id, name and capabilities once; an error when one with its id
/// is registered already, or when the provider panics while giving them.
pub fn register(&mut self, provider: Arc<dyn Provider>) -> Result<(), String> {
let (id, name, capabilities) = crate::guard::catch_panic(|| (provider.id(), provider.name(), provider.capabilities()))
.map_err(|e| ProviderError::Internal(e).to_string())?;
if self.get(id).is_some() {
return Err(format!("a provider with the id `{id}` is registered already"));
}
self.providers.push(Registered { id, name, capabilities, provider });
Ok(())
}
/// The provider `id` (exactly so spelled).
pub fn get(&self, id: &str) -> Option<&Registered> {
self.providers.iter().find(|p| p.id == id)
}
/// The providers in the order they were registered.
pub fn iter(&self) -> impl Iterator<Item = &Registered> {
self.providers.iter()
}
}
/// Whether `p` is a finite point within `limit` of the image's pixel space.
fn within(p: Point, limit: f64, size: (f64, f64)) -> bool {
p.x.is_finite() && p.y.is_finite() && p.x >= -limit && p.y >= -limit && p.x <= size.0 + limit && p.y <= size.1 + limit
}
/// Checks the variations a provider returned for `request`: one per style in the order asked, at
/// most [`MAX_PATHS`] paths (each subpath of a compound path counted as one) and [`MAX_ANCHORS`]
/// anchors together, each path with a fill or a stroke and with subpaths that each have an anchor,
/// every anchor and handle finite and within one image side of the image, every
/// stroke width finite, over 0 and at most the image's larger side, and at most [`MAX_WARNINGS`]
/// warnings of at most 500 characters on each variation.
pub fn check_result(request: &Request, variations: &[Variation]) -> Result<(), ProviderError> {
if variations.len() != request.styles.len() || variations.iter().zip(&request.styles).any(|(v, s)| v.style != *s) {
return Err(ProviderError::InvalidResult);
}
let size = (f64::from(request.width.max(1)), f64::from(request.height.max(1)));
let side = size.0.max(size.1);
let (mut paths, mut anchors) = (0usize, 0usize);
for v in variations {
// Each subpath of a compound path becomes an object of its own when it is inserted.
paths = v.paths.iter().fold(paths, |n, p| n.saturating_add(p.path.subpaths.len().max(1)));
anchors += v.anchors();
if anchors > MAX_ANCHORS {
return Err(ProviderError::ResourceLimit(MAX_ANCHORS));
}
if paths > MAX_PATHS || v.warnings.len() > MAX_WARNINGS || v.warnings.iter().any(|w| w.chars().count() > MAX_WARNING_CHARS) {
return Err(ProviderError::InvalidResult);
}
for p in &v.paths {
let width_ok = p.stroke.is_none_or(|(_, w)| w.is_finite() && w > 0.0 && w <= side);
let painted = p.fill.is_some() || p.stroke.is_some();
let points_ok = p.path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].into_iter().all(|q| within(q, side, size)));
let no_empty_subpath = !p.path.subpaths.is_empty() && p.path.subpaths.iter().all(|sp| !sp.anchors.is_empty());
if !width_ok || !painted || !no_empty_subpath || !points_ok {
return Err(ProviderError::InvalidResult);
}
}
}
Ok(())
}
+440
View File
@@ -0,0 +1,440 @@
//! The built-in provider: Concept to Vector styles made with Image Trace on this computer.
//!
//! Each style is a fixed set of Image Trace settings of VectorCraft's own, and Detail (0 to 100)
//! moves its Paths, Noise and color count within that style's range. The image is decoded once and
//! traced once per style; an image over [`MAX_PIXELS`] is scaled down first, aspect kept, and
//! each variation says so. The paths are mapped back to the image's own pixel size.
use std::sync::Arc;
use vectorcraft_geom::kurbo::common::solve_cubic;
use vectorcraft_geom::{Affine, Anchor, CubicBez, ParamCurve, PathData, Point, SubPath};
use vectorcraft_trace as tr;
use super::{Capabilities, MAX_ANCHORS, MAX_PATHS, Output, Parts, ProviderError, Request, Steps, Style, Variation, VectorPath};
/// The built-in provider's id.
pub const ID: &str = "offline.traceStyles";
/// The most pixels the built-in provider traces an image at (16 megapixels).
pub const MAX_PIXELS: u64 = 16 << 20;
/// The built-in provider's styles, in the order it lists them.
pub const STYLES: [Style; 5] = [
Style { id: "outline", label: "Outline" },
Style { id: "inkLines", label: "Ink Lines" },
Style { id: "flatColor", label: "Flat Color" },
Style { id: "detailedColor", label: "Detailed Color" },
Style { id: "grayTones", label: "Gray Tones" },
];
/// Concept to Vector styles made with Image Trace ([`ID`]).
pub struct TraceStyles;
/// `lo` at Detail 0 to `hi` at Detail 100.
fn between(lo: f64, hi: f64, t: f64) -> f64 {
lo + (hi - lo) * t
}
/// The trace settings of style `id` at Detail `detail` (0 to 100); `None` for an id that isn't one
/// of [`STYLES`].
pub fn style_params(id: &str, detail: u8) -> Option<tr::TraceParams> {
let t = f64::from(detail.min(100)) / 100.0;
let noise = |lo: f64, hi: f64| between(hi, lo, t).round().max(1.0) as u32;
let count = |lo: f64, hi: f64| between(lo, hi, t).round() as u32;
let base = tr::TraceParams { shapes: false, gradients: false, auto_grouping: false, ..tr::TraceParams::default() };
Some(match id {
// Black stroked lines only: thin lines as center lines, wider areas as outlines.
"outline" => {
tr::TraceParams { fills: false, strokes: true, ignore_white: true, paths: between(50.0, 90.0, t), noise: noise(4.0, 40.0), ..base }
}
// Black filled ink on no background, the straight runs straightened.
"inkLines" => tr::TraceParams {
ignore_white: true,
snap_curves_to_lines: true,
paths: between(50.0, 95.0, t),
corners: 80.0,
noise: noise(4.0, 30.0),
..base
},
// A few flat colors, abutting.
"flatColor" => tr::TraceParams {
mode: tr::Mode::Color,
colors: count(3.0, 8.0),
paths: between(40.0, 80.0, t),
corners: 60.0,
noise: noise(8.0, 40.0),
snap_curves_to_lines: true,
..base
},
// Many colors, stacked so no hairline gaps show.
"detailedColor" => tr::TraceParams {
mode: tr::Mode::Color,
colors: count(12.0, 32.0),
paths: between(70.0, 95.0, t),
corners: 40.0,
noise: noise(2.0, 12.0),
method: tr::Method::Overlapping,
..base
},
// Grays, stacked.
"grayTones" => tr::TraceParams {
mode: tr::Mode::Grayscale,
colors: count(4.0, 12.0),
paths: between(55.0, 90.0, t),
corners: 50.0,
noise: noise(4.0, 20.0),
method: tr::Method::Overlapping,
..base
},
_ => return None,
})
}
/// `img` box-filtered down to at most [`MAX_PIXELS`], aspect kept; `img` itself when it fits.
fn fit(img: tr::Raster) -> tr::Raster {
fit_within(img, MAX_PIXELS)
}
/// `img` box-filtered down to at most `max` pixels (at least 1), aspect kept as far as a side of
/// at least one pixel allows; `img` itself when it fits.
pub(super) fn fit_within(img: tr::Raster, max: u64) -> tr::Raster {
let (w, h) = (u64::from(img.width), u64::from(img.height));
let max = max.max(1);
if w * h <= max || w == 0 || h == 0 {
return img;
}
let k = (max as f64 / (w * h) as f64).sqrt();
// A side that rounds down to one pixel leaves the other side the whole budget, no more.
let nh = ((h as f64 * k).floor() as u64).clamp(1, h.min(max));
let nw = ((w as f64 * k).floor() as u64).clamp(1, w.min(max / nh)) as u32;
let nh = nh as u32;
let mut rgba = Vec::with_capacity(nw as usize * nh as usize * 4);
for y in 0..nh {
let (y0, y1) = (u64::from(y) * h / u64::from(nh), (u64::from(y + 1) * h / u64::from(nh)).max(u64::from(y) * h / u64::from(nh) + 1));
for x in 0..nw {
let (x0, x1) = (u64::from(x) * w / u64::from(nw), (u64::from(x + 1) * w / u64::from(nw)).max(u64::from(x) * w / u64::from(nw) + 1));
// Each pixel's color is weighted by its alpha. A box with nothing opaque in it is clear black.
let mut sum = [0u64; 4];
for sy in y0..y1.min(h) {
for sx in x0..x1.min(w) {
let [r, g, b, a] = img.pixel(sx as u32, sy as u32).map(u64::from);
sum = [sum[0] + r * a, sum[1] + g * a, sum[2] + b * a, sum[3] + a];
}
}
let n = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1);
let alpha = sum[3];
let color = |s: u64| s.checked_div(alpha).map_or(0, |c| c.min(255) as u8);
rgba.extend([color(sum[0]), color(sum[1]), color(sum[2]), (alpha / n) as u8]);
}
}
tr::Raster { width: nw, height: nh, rgba }
}
impl super::Provider for TraceStyles {
fn id(&self) -> &'static str {
ID
}
fn name(&self) -> &'static str {
"Offline Image Trace Styles"
}
fn capabilities(&self) -> Capabilities {
Capabilities { image_input: true, vector_output: true, prompt: false, raster_output: false, offline: true, styles: STYLES.to_vec() }
}
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError> {
let params = checked(request)?;
let total = params.len() as u64;
if !steps(0, total) {
return Err(ProviderError::Canceled);
}
let image = Decoded::new(request)?;
let mut left = MAX_ANCHORS;
let mut out = Vec::with_capacity(params.len());
for (i, (style, p)) in request.styles.iter().zip(&params).enumerate() {
let go_on = |_: u64, _: u64| steps(i as u64, total);
let res = tr::trace_watched(&image.raster, p, left, &go_on).map_err(trace_error)?;
left = left.saturating_sub(res.anchor_count());
out.push(image.variation(style, p, res));
}
if !steps(total, total) {
return Err(ProviderError::Canceled);
}
Ok(with_seams(out))
}
/// The image decoded in the first part; then for each style, its color layers found in one
/// part and each layer traced in a part of its own ([`tr::TraceSteps`]), or all of them in
/// one part where the style stacks them (Overlapping with Fills).
fn parts(&self, request: &Request) -> Option<Box<dyn Parts>> {
Some(Box::new(TraceParts { request: request.clone(), image: None, trace: None, left: MAX_ANCHORS, out: vec![], ended: false }))
}
}
/// The trace settings of each of `request`'s styles; an error for a prompt, an output other than
/// vector art, or a style that isn't one of [`STYLES`]. The host refuses these first; a direct
/// caller gets the same answer.
fn checked(request: &Request) -> Result<Vec<tr::TraceParams>, ProviderError> {
let pid = ID;
if request.prompt.is_some() || request.output != Output::Vector {
return Err(ProviderError::Unsupported(format!("`{pid}` takes no prompt and makes vector art only")));
}
request
.styles
.iter()
.map(|s| style_params(s, request.detail))
.collect::<Option<_>>()
.ok_or_else(|| ProviderError::InvalidInput(format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)")))
}
fn trace_error(e: tr::TraceError) -> ProviderError {
match e {
tr::TraceError::Cancelled => ProviderError::Canceled,
tr::TraceError::TooComplex { .. } => ProviderError::ResourceLimit(MAX_ANCHORS),
e => ProviderError::InvalidInput(e.to_string()),
}
}
/// A request's image decoded for tracing, with what maps its traced paths back.
struct Decoded {
raster: Arc<tr::Raster>,
/// The decoded raster's pixels → the image's own pixel space.
back: Affine,
unit: f64,
warnings: Vec<String>,
}
impl Decoded {
/// `request`'s image decoded, scaled down to at most [`MAX_PIXELS`].
fn new(request: &Request) -> Result<Self, ProviderError> {
let raster = fit(tr::Raster::decode_to_fit(&request.image).map_err(|e| ProviderError::InvalidInput(e.to_string()))?);
let mut warnings = vec![];
let (iw, ih) = (request.width.max(1), request.height.max(1));
if u64::from(raster.width) * u64::from(raster.height) < u64::from(iw) * u64::from(ih) {
warnings.push(format!("The image was traced at {} × {} pixels, scaled down from {iw} × {ih}.", raster.width, raster.height));
}
let back = Affine::scale_non_uniform(f64::from(iw) / f64::from(raster.width.max(1)), f64::from(ih) / f64::from(raster.height.max(1)));
let unit = back.determinant().abs().sqrt();
Ok(Self { raster: Arc::new(raster), back, unit, warnings })
}
/// The variation of `style` that the trace `res` of this image, made with `params`, makes, and
/// the seam fills of an Abutting trace with fills ([`tr::seam_fills`]) trimmed inside the
/// image ([`within_image`]) and outlined in raster pixels before mapping them back, for
/// [`with_seams`] to lay under its paths.
fn variation(&self, style: &str, params: &tr::TraceParams, res: tr::TraceResult) -> Made {
let size = (self.raster.width, self.raster.height);
let seams = tr::seam_fills(&res.paths, params, size).map_or_else(Vec::new, |s| {
s.strokes
.into_iter()
.map(|tp| {
let mut tp = within_image(tp, size);
if let Some(width) = tp.stroke.take() {
tp.path = vectorcraft_pathops::outline_stroke(
&tp.path,
width,
vectorcraft_pathops::Cap::Butt,
vectorcraft_pathops::Join::Round,
4.0,
);
}
tp
})
.filter(|tp| !tp.path.subpaths.is_empty())
.map(|tp| self.vector_path(tp))
.collect()
});
let paths = res.paths.into_iter().map(|tp| self.vector_path(tp)).collect();
Made { variation: Variation { style: style.to_string(), paths, warnings: self.warnings.clone() }, seams }
}
/// Traced path `tp` in the image's own pixels.
fn vector_path(&self, tp: tr::TracedPath) -> VectorPath {
let path = tp.path.transformed(self.back);
match tp.stroke {
Some(w) => VectorPath { path, fill: None, stroke: Some((tp.color, w * self.unit)), square_caps: tp.square_caps },
None => VectorPath { path, fill: Some(tp.color), stroke: None, square_caps: false },
}
}
}
/// A variation made, and the outlined seam fills to lay under its paths.
pub(super) struct Made {
pub(super) variation: Variation,
pub(super) seams: Vec<VectorPath>,
}
/// [`with_seams_within`] [`MAX_ANCHORS`] and [`MAX_PATHS`].
fn with_seams(made: Vec<Made>) -> Vec<Variation> {
with_seams_within(made, MAX_ANCHORS, MAX_PATHS)
}
/// The variations `made`, each with its seam fills under its paths, in order, while they fit in
/// the `max_anchors` anchors and `max_paths` paths (each subpath counted as one) left once every
/// variation is counted: the traced paths of every style come first, and a style whose seam fills
/// do not fit goes without them.
pub(super) fn with_seams_within(made: Vec<Made>, max_anchors: usize, max_paths: usize) -> Vec<Variation> {
let subpaths = |paths: &[VectorPath]| paths.iter().map(|p| p.path.subpaths.len().max(1)).sum::<usize>();
let mut anchors = made.iter().map(|m| m.variation.anchors()).sum::<usize>();
let mut paths = made.iter().map(|m| subpaths(&m.variation.paths)).sum::<usize>();
made.into_iter()
.map(|Made { mut variation, seams }| {
let (more_anchors, more_paths) = (seams.iter().map(|p| p.path.anchor_count()).sum::<usize>(), subpaths(&seams));
if !seams.is_empty() && anchors.saturating_add(more_anchors) <= max_anchors && paths.saturating_add(more_paths) <= max_paths {
anchors += more_anchors;
paths += more_paths;
variation.paths.splice(0..0, seams);
}
variation
})
.collect()
}
/// Seam stroke `tp` of a `size` raster trimmed to half its width inside the raster's border,
/// so that its outline with butt caps and round joins stays inside the image. The pieces left form
/// open runs; a closed subpath left whole stays closed.
fn within_image(mut tp: tr::TracedPath, size: (u32, u32)) -> tr::TracedPath {
let half = tp.stroke.unwrap_or_default() / 2.0;
let (w, h) = (f64::from(size.0), f64::from(size.1));
let mut runs: Vec<SubPath> = vec![];
if !half.is_finite() || half < 0.0 || half * 2.0 > w || half * 2.0 > h {
tp.path = PathData::new(runs);
return tp;
}
let inside = |p: Point| p.x >= half && p.y >= half && p.x <= w - half && p.y <= h - half;
let clamp = |p: Point| Point::new(p.x.clamp(half, w - half), p.y.clamp(half, h - half));
for sp in &tp.path.subpaths {
let count = sp.segment_count();
let mut pieces = vec![];
for k in 0..count {
let c = sp.segment(k);
let mut cuts = vec![0.0, 1.0];
if ![c.p0, c.p1, c.p2, c.p3].into_iter().all(inside) {
for (p0, p1, p2, p3, side) in [
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, half),
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, w - half),
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, half),
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, h - half),
] {
// Intersections with the sides' supporting lines also cover corner crossings.
cuts.extend(
solve_cubic(p0 - side, 3.0 * (p1 - p0), 3.0 * (p0 - 2.0 * p1 + p2), p3 - p0 + 3.0 * (p1 - p2))
.into_iter()
.filter(|&t| t > 0.0 && t < 1.0),
);
}
cuts.sort_by(f64::total_cmp);
cuts.dedup();
}
for pair in cuts.windows(2) {
let (t0, t1) = (pair[0], pair[1]);
pieces.push((k, t0, t1, inside(c.eval(t0 + (t1 - t0) / 2.0))));
}
}
if pieces.iter().all(|&(_, _, _, kept)| kept) {
if count > 0 {
runs.push(sp.clone());
}
continue;
}
// Start after a piece left out, so that a run across a closed subpath's first anchor
// stays one run.
let start = if sp.closed { pieces.iter().position(|&(_, _, _, kept)| !kept).map_or(0, |k| k + 1) } else { 0 };
let mut run: Vec<Anchor> = vec![];
for j in 0..pieces.len() {
let (k, t0, t1, kept) = pieces[(start + j) % pieces.len()];
if kept {
let (Some(&a), Some(&b)) = (sp.anchors.get(k), sp.anchors.get((k + 1) % sp.anchors.len())) else { continue };
let c = sp.segment(k);
let mut c = if t0 == 0.0 && t1 == 1.0 { c } else { c.subsegment(t0..t1) };
// Remove roundoff at the cut endpoints without constraining the curve's handles.
c.p0 = clamp(c.p0);
c.p3 = clamp(c.p3);
if sp.segment_is_line(k) {
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
}
if let Some(last) = run.last_mut() {
last.h_out = c.p1;
} else {
let a = if t0 == 0.0 { a } else { Anchor::corner(c.p0) };
run.push(Anchor { p: c.p0, h_in: c.p0, h_out: c.p1, ..a });
}
let b = if t1 == 1.0 { b } else { Anchor::corner(c.p3) };
run.push(Anchor { p: c.p3, h_in: c.p2, h_out: c.p3, ..b });
} else if !run.is_empty() {
runs.push(open_run(std::mem::take(&mut run)));
}
}
if !run.is_empty() {
runs.push(open_run(run));
}
}
tp.path = PathData::new(runs);
tp
}
/// An open run of anchors: the last one has no handle out.
fn open_run(mut run: Vec<Anchor>) -> SubPath {
if let Some(last) = run.last_mut() {
last.h_out = last.p;
}
SubPath::new(run, false)
}
/// [`TraceStyles`]' variations made a part at a time.
struct TraceParts {
request: Request,
image: Option<Decoded>,
/// The trace of the style after those in `out`, once started.
trace: Option<tr::TraceSteps>,
/// The anchor points the styles not made yet may have.
left: usize,
out: Vec<Made>,
/// The variations or an error have been given.
ended: bool,
}
impl Parts for TraceParts {
/// After the variations or an error, each call gives `None`.
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
if self.ended {
return Ok(None);
}
let part = self.next_part();
self.ended = !matches!(part, Ok(None));
part
}
fn styles_done(&self) -> usize {
self.out.len()
}
}
impl TraceParts {
fn next_part(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
let Some(image) = &self.image else {
checked(&self.request)?;
self.image = Some(Decoded::new(&self.request)?);
return Ok(None);
};
let Some(style) = self.request.styles.get(self.out.len()) else { return Ok(Some(with_seams(std::mem::take(&mut self.out)))) };
let trace = match &mut self.trace {
Some(t) => t,
None => {
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
self.trace.insert(tr::TraceSteps::new(Arc::clone(&image.raster), params, self.left))
}
};
let Some(res) = trace.step().map_err(trace_error)? else { return Ok(None) };
self.trace = None;
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
self.left = self.left.saturating_sub(res.anchor_count());
self.out.push(image.variation(style, &params, res));
if self.out.len() < self.request.styles.len() {
return Ok(None);
}
Ok(Some(with_seams(std::mem::take(&mut self.out))))
}
}
File diff suppressed because it is too large. Load diff
+4
View File
@@ -8,6 +8,7 @@
#![doc(test(attr(forbid(unsafe_code))))]
pub mod cmd;
pub mod concept_vector;
pub mod file_access;
pub mod guard;
pub mod inspect;
@@ -359,6 +360,9 @@ pub struct Session {
/// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or
/// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]).
pub(crate) trace_hand_off: Option<cmd::Traced>,
/// The Concept to Vector providers and the jobs made with them ([`cmd::conceptvector`]); not
/// saved.
pub(crate) concept: cmd::conceptvector::ConceptState,
/// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or
/// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]).
pub(crate) retype_hand_off: Option<cmd::RetypeFound>,
+12
View File
@@ -501,6 +501,9 @@ struct World {
pending_paint: Option<crate::Paint>,
choices: Choices,
journal: Journal,
/// The Concept to Vector jobs, and the number of the first job made after the run started.
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
concept_from: u64,
/// The preferences when the run started.
start_prefs: crate::Prefs,
/// The Caps Lock state when the run started.
@@ -631,6 +634,8 @@ impl World {
pending_paint: s.pending_paint.clone(),
choices: Choices::of(s),
journal: Journal::default(),
concept_jobs: s.concept_jobs_snapshot(),
concept_from: s.next_concept_job(),
start_prefs: s.prefs.clone(),
start_caps_lock: s.caps_lock,
}
@@ -655,6 +660,7 @@ impl World {
swap(&mut self.pending_paint, &mut s.pending_paint);
self.choices.swap(s);
swap(&mut self.journal, &mut s.journal);
s.swap_concept_jobs(&mut self.concept_jobs);
}
}
@@ -696,6 +702,7 @@ pub(crate) struct Savepoint {
pending_paint: Option<crate::Paint>,
choices: Choices,
journal: usize,
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
/// The plug-in events queued before the command ([`Session::plugin_events_mark`]).
plugin_events: u64,
}
@@ -732,6 +739,7 @@ impl Savepoint {
pending_paint: s.pending_paint.clone(),
choices: Choices::of(s),
journal: s.journal.len(),
concept_jobs: s.concept_jobs_snapshot(),
plugin_events: s.plugin_events_mark(),
}
}
@@ -787,6 +795,7 @@ impl Savepoint {
s.pending_paint = self.pending_paint;
self.choices.put(s);
s.journal.truncate(self.journal);
s.restore_concept_jobs(self.concept_jobs);
// The documents the command opened are closed again: plug-ins are not told of them.
s.forget_plugin_opens_since(self.plugin_events);
s.sync_front_profiles();
@@ -2842,6 +2851,9 @@ impl Session {
for st in start.iter().filter(|b| !job.start_uids.contains(&b.uid)) {
self.docs.push(st.clone());
}
// So do the Concept to Vector jobs the app made while the run went on.
let others = std::mem::take(&mut job.world.concept_jobs);
self.merge_concept_jobs(others, job.world.concept_from);
// A document the script closed is gone now, with its recovery copy.
for b in start.iter().filter(|b| job.start_uids.contains(&b.uid) && !self.docs.iter().any(|d| d.uid == b.uid)) {
cmd::recovery::forget_closed(self, b);
+5
View File
@@ -150,6 +150,7 @@ impl Session {
place_queue_loads: 0,
image_hand_off: None,
trace_hand_off: None,
concept: Default::default(),
retype_hand_off: None,
place_cursor_requests: false,
package_hand_off: None,
@@ -568,6 +569,10 @@ impl Session {
// Closed (saved or discarded): nothing left to recover.
let uid = self.docs[index].uid;
cmd::recovery::forget(self, uid);
// In a batch, the jobs are dropped when the batch ends without an error.
if self.batch_stash.is_none() {
self.forget_concept_jobs(uid);
}
let old = self.docs.remove(index);
if let Some(stash) = &mut self.batch_stash {
stash.push(old);
+28 -1
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
use crate::*;
@@ -211,6 +211,33 @@ fn exclude_makes_compound() {
assert!((area_of(&s, r[0]) - 15000.0).abs() < 1.0);
}
#[test]
fn divide_over_work_budget_preserves_art_and_selection() {
let mut s = session();
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let line = s.execute("shape.line", &json!({"x1": -10, "y1": -10, "x2": 110, "y2": 110})).unwrap();
let cutter = NodeId(line["id"].as_u64().unwrap());
// The existing pathops work-budget fixture uses 1,500 overlapping lines.
// Put them in one open path so the setup only makes two document objects.
let line = SubPath::polyline(&[Point::new(-10.0, -10.0), Point::new(110.0, 110.0)], false);
s.edit("complex cutter", |d, _| {
let NodeKind::Path { path, .. } = &mut d.node_mut(cutter).unwrap().kind else { panic!("expected a path") };
*path = PathData::new(vec![line; 1_500]);
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [square.0, cutter.0]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let undo = s.doc().unwrap().history.undo.len();
let error = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
assert!(error.contains("too many segments or pieces"), "{error}");
let state = s.doc().unwrap();
assert!(std::sync::Arc::ptr_eq(&state.doc, &before), "the original document must be restored");
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
}
#[test]
fn divide_produces_group_of_faces() {
let mut s = session();
+135
View File
@@ -519,3 +519,138 @@ fn type_on_a_path_made_with_the_type_tool_has_brackets_at_once() {
assert!(ink(&s, id).y0 > 299.0, "{tool}: below the path");
}
}
/// Press and release `tool` at `p`.
fn click(s: &mut Session, tool: &str, p: Point) {
let v = ViewInfo::default();
s.select_tool(tool, v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap();
}
assert!(!s.in_interaction());
}
/// Type along "M100 300 L300 300 L500 300" turned a quarter turn, so a document-space edit isn't
/// the path's own, and selected; with its path in document space.
fn turned_path_type(s: &mut Session) -> NodeId {
let id = path_type(s, "M100 300 L300 300 L500 300", [100.0, 310.0], "Reshaped type");
s.execute("object.transform", &json!({"ids": [id.0], "matrix": [0, 1, -1, 0, 600, 0]})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
id
}
fn type_path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
text(s, id).type_path().unwrap()
}
fn close(a: Point, b: Point) -> bool {
near(a.x, b.x) && near(a.y, b.y)
}
/// #10862: the Anchor Point tool drags handles out of an anchor of selected type on a path's path,
/// in document space through the type's transform, as one undo step, and the type reflows.
#[test]
fn anchor_point_tool_pulls_handles_out_of_type_on_a_path() {
let mut s = session();
let id = turned_path_type(&mut s);
let middle = type_path(&s, id).subpaths[0].anchors[1].p;
let (glyphs, n) = (origins(&s, id), undo_len(&s));
let to = middle + vectorcraft_geom::Vec2::new(40.0, 0.0);
drag(&mut s, "anchorPoint", middle, to, Mods::default());
let a = type_path(&s, id).subpaths[0].anchors[1];
assert!(close(a.p, middle) && close(a.h_out, to) && close(a.h_in, middle - (to - middle)), "{a:?}");
assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth);
assert_ne!(origins(&s, id), glyphs, "the type reflows along the curved path");
assert_eq!(undo_len(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!type_path(&s, id).subpaths[0].anchors[1].has_out());
}
/// #10862: the rest of the Anchor Point tool's gestures on type on a path's path: a click makes a
/// smooth anchor a corner, a handle drag moves that handle alone, Shift at the press moves the
/// anchor, and a segment drag bends the segment.
#[test]
fn anchor_point_tool_reshapes_type_on_a_path() {
let mut s = session();
let id = turned_path_type(&mut s);
let [first, middle, last] = [0, 1, 2].map(|i| type_path(&s, id).subpaths[0].anchors[i].p);
let up = vectorcraft_geom::Vec2::new(40.0, 0.0);
drag(&mut s, "anchorPoint", middle, middle + up, Mods::default());
// A handle end, dragged, moves alone and makes the anchor a corner.
let handle = middle + vectorcraft_geom::Vec2::new(40.0, 30.0);
drag(&mut s, "anchorPoint", middle + up, handle, Mods::default());
let a = type_path(&s, id).subpaths[0].anchors[1];
assert!(close(a.h_out, handle) && close(a.h_in, middle - up) && a.kind == vectorcraft_geom::AnchorKind::Corner, "{a:?}");
// A click on the anchor takes its handles back.
click(&mut s, "anchorPoint", middle);
let a = type_path(&s, id).subpaths[0].anchors[1];
assert!(!a.has_in() && !a.has_out(), "{a:?}");
// Shift at the press moves the anchor.
let shift = Mods { shift: true, ..Mods::default() };
drag(&mut s, "anchorPoint", middle, middle + up, shift);
assert!(close(type_path(&s, id).subpaths[0].anchors[1].p, middle + up));
// A drag on the first segment bends it; its anchors stay.
let on_segment = first.midpoint(middle + up);
drag(&mut s, "anchorPoint", on_segment, on_segment + vectorcraft_geom::Vec2::new(0.0, 30.0), Mods::default());
let sp = &type_path(&s, id).subpaths[0];
assert!(close(sp.anchors[0].p, first) && close(sp.anchors[2].p, last));
assert!(sp.anchors[0].has_out() && sp.anchors[1].has_in(), "the segment curves: {sp:?}");
}
/// #10862: the Add and Delete Anchor Point tools add an anchor to type on a path's path and delete
/// one, and Pen + Alt pulls handles out of one; Delete leaves the path two anchors at least, and
/// Scissors does not cut the type.
#[test]
fn add_delete_and_pen_alt_edit_type_on_a_path() {
let mut s = session();
let id = turned_path_type(&mut s);
let [first, middle] = [0, 1].map(|i| type_path(&s, id).subpaths[0].anchors[i].p);
let quarter = first.midpoint(middle);
click(&mut s, "addAnchor", quarter);
let sp = type_path(&s, id).subpaths[0].clone();
assert_eq!(sp.anchors.len(), 4);
assert!(close(sp.anchors[1].p, quarter), "{sp:?}");
let alt = Mods { alt: true, ..Mods::default() };
let to = quarter + vectorcraft_geom::Vec2::new(0.0, 25.0);
drag(&mut s, "pen", quarter, to, alt);
let a = type_path(&s, id).subpaths[0].anchors[1];
assert!(close(a.p, quarter) && close(a.h_out, to) && a.kind == vectorcraft_geom::AnchorKind::Smooth, "{a:?}");
// The Pen's Auto Add/Delete adds an anchor on a segment and deletes it again.
let last = type_path(&s, id).subpaths[0].anchors[3].p;
let three_quarters = middle.midpoint(last);
click(&mut s, "pen", three_quarters);
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 5);
click(&mut s, "pen", three_quarters);
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 4);
click(&mut s, "deleteAnchor", quarter);
click(&mut s, "deleteAnchor", middle);
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 2);
let n = undo_len(&s);
let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": 0}));
assert!(r.is_err(), "type on a path keeps two anchors: {r:?}");
assert_eq!((type_path(&s, id).subpaths[0].anchors.len(), undo_len(&s)), (2, n));
let end = type_path(&s, id).subpaths[0].anchors[1].p;
click(&mut s, "scissors", first.midpoint(end));
assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. }));
assert_eq!(undo_len(&s), n, "Scissors leaves the type whole");
}
/// #10862: `path.insertAnchor` on type on a path, unselected or with `selectAnchor`, leaves the type
/// selected whole with no direct-selected anchors, so `path.moveAnchors` (the arrow keys) moves
/// the type instead of failing on an anchor that is not a path's.
#[test]
fn an_anchor_added_to_type_on_a_path_leaves_it_selected_whole() {
let mut s = session();
let id = turned_path_type(&mut s);
for select_anchor in [false, true] {
if !select_anchor {
s.execute("select.set", &json!({"ids": []})).unwrap();
}
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5, "selectAnchor": select_anchor})).unwrap();
let sel = &s.doc().unwrap().selection;
assert!(sel.contains(id) && sel.partial(id).is_none() && !sel.anchors.contains_key(&id), "selectAnchor {select_anchor}");
let before = type_path(&s, id).subpaths[0].anchors[0].p;
s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 0})).unwrap();
assert!(close(type_path(&s, id).subpaths[0].anchors[0].p, before + vectorcraft_geom::Vec2::new(10.0, 0.0)));
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
std::fs::canonicalize(&base).unwrap()
crate::cmd::findfiles::plain(std::fs::canonicalize(&base).unwrap())
}
fn write(path: &Path, bytes: &[u8]) {
+1 -1
View File
@@ -57,7 +57,7 @@ impl AsRef<Path> for Folder {
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path.
fn folder(name: &str) -> Folder {
let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}"));
let base = std::fs::canonicalize(&*guard).unwrap();
let base = crate::cmd::findfiles::plain(std::fs::canonicalize(&*guard).unwrap());
std::fs::create_dir_all(base.join("main")).unwrap();
Folder { _guard: guard, path: base }
}
+185 -36
View File
@@ -279,11 +279,35 @@ enum FrameKind {
/// Point type: the matrix carries the layout (its anchor at the origin of its lines) onto the
/// canvas.
Point([f64; 6]),
/// Area type flowed inside a path: its cubic segments on the canvas, four points each, and the
/// Area Type Options the frame keeps.
Area(Vec<[f64; 8]>, AreaFrame),
/// Type on a path, from `start` to `end` (segment index and the place in that segment).
OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64, options: PathFrame },
/// Area type flowed inside a path: its cubic segments on the canvas, four points each, the Area
/// Type Options the frame keeps, and the frame's matrix (the segments are already on the
/// canvas; the matrix turns and scales the lines inside them).
Area(Vec<[f64; 8]>, AreaFrame, [f64; 6]),
/// Type on a path, from `start` to `end` (segment index and the place in that segment), its
/// segments on the canvas, and the frame's matrix.
OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64, options: PathFrame, matrix: [f64; 6] },
}
/// The matrix of a frame that keeps none: its frame and layout are already on the canvas.
const NO_MATRIX: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
/// Segment `s` (four points) carried onto the canvas by the frame matrix `m`.
fn on_canvas(m: &[f64; 6], s: &[f64; 8]) -> [f64; 8] {
let [a, b, c, d, e, f] = *m;
let mut out = *s;
for [x, y] in out.as_chunks_mut::<2>().0 {
(*x, *y) = (a * *x + c * *y + e, b * *x + d * *y + f);
}
out
}
/// The scale of the frame matrix `m` and its turn (the matrix without its scale or its move), or
/// `None` for a matrix that mirrors, has no size or isn't finite.
fn turn_of(m: &[f64; 6]) -> Option<(f64, Affine)> {
let [a, b, c, d, ..] = *m;
let det = a * d - b * c;
let scale = det.abs().sqrt();
(scale.is_finite() && scale > 1e-6 && det > 0.0).then(|| (scale, Affine::new([a / scale, b / scale, c / scale, d / scale, 0.0, 0.0])))
}
/// The Type on a Path Options a frame of type on a path keeps at key 11. Each stays at its default
@@ -732,19 +756,21 @@ impl Texts {
fn frame(&self, i: usize) -> Option<FrameKind> {
let f = self.frames.get(i)?.get("0")?;
let carries = f.get("2")?;
// Key 2, the frame's matrix: it carries the frame's segments and its layout onto the canvas.
// Type that is neither turned nor scaled has none (Illustrator 24 leaves it out): its frame
// and layout are already where they go on the canvas.
let matrix: [f64; 6] = match carries.get("2") {
None => NO_MATRIX,
Some(m) => m.nums()?.try_into().ok()?,
};
let segments = || -> Option<Vec<[f64; 8]>> {
let n = f.get("1")?.get("0")?.nums()?;
let (chunks, rest) = n.as_chunks::<8>();
(rest.is_empty() && !chunks.is_empty() && chunks.len() <= MAX_SEGMENTS).then(|| chunks.to_vec())
(rest.is_empty() && !chunks.is_empty() && chunks.len() <= MAX_SEGMENTS).then(|| chunks.iter().map(|s| on_canvas(&matrix, s)).collect())
};
match carries.get("0").and_then(Val::num).unwrap_or(0.0) as i64 {
// Point type that is neither turned nor scaled has no matrix (Illustrator 24 leaves it out):
// its layout is already where it goes on the canvas.
0 => Some(FrameKind::Point(match carries.get("2") {
None => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
Some(m) => m.nums()?.try_into().ok()?,
})),
1 => Some(FrameKind::Area(segments()?, AreaFrame::read(carries))),
0 => Some(FrameKind::Point(matrix)),
1 => Some(FrameKind::Area(segments()?, AreaFrame::read(carries), matrix)),
2 => {
let range = carries.get("6").and_then(Val::nums).unwrap_or_default();
let segments = segments()?;
@@ -760,7 +786,7 @@ impl Texts {
let start = finite(range.first()).unwrap_or(0.0).clamp(0.0, n);
(start, finite(range.get(1)).unwrap_or(n).clamp(start, n))
};
Some(FrameKind::OnPath { segments, start, end, options: PathFrame::read(carries) })
Some(FrameKind::OnPath { segments, start, end, options: PathFrame::read(carries), matrix })
}
_ => None,
}
@@ -1219,11 +1245,11 @@ impl Story {
frame == 0 && matches!(self.frames.first(), Some(FrameKind::Point(_))) && self.is_blank()
}
/// The point frame's matrix (the first frame's, when it is one), else the identity.
/// The first frame's matrix, which carries its layout onto the canvas, else the identity.
fn matrix(&self) -> [f64; 6] {
match self.frames.first() {
Some(FrameKind::Point(m)) => *m,
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
Some(FrameKind::Point(m) | FrameKind::Area(_, _, m) | FrameKind::OnPath { matrix: m, .. }) => *m,
None => NO_MATRIX,
}
}
@@ -1256,7 +1282,7 @@ impl Story {
let size = self.runs.iter().map(|(_, s)| s.size).fold(0.0, f64::max) * art_scale(to_doc);
let bounds = |segments: &[[f64; 8]]| path_of(segments, template, to_doc).bounds();
let r = match self.frames.first()? {
FrameKind::Area(s, _) => bounds(s)?,
FrameKind::Area(s, ..) => bounds(s)?,
FrameKind::OnPath { segments, .. } => bounds(segments)?.inflate(size * 1.5, size * 1.5),
FrameKind::Point(m) => {
let longest = self.text.split(['\r', '\x03']).map(|l| l.chars().count()).max().unwrap_or(0) as f64;
@@ -1312,23 +1338,34 @@ impl Story {
let threaded = frame > 0;
let (scale, xf, kind) = match kind {
FrameKind::Point(m) => {
let [a, b, c, d, ..] = *m;
let scale = (a * d - b * c).abs().sqrt();
if !(scale.is_finite() && scale > 1e-6 && a * d - b * c > 0.0) || threaded {
return None;
}
let (scale, turn) = turn_of(m).filter(|_| !threaded)?;
let (x, y) = self.place(template);
let at = to_doc * Point::new(x, y);
(scale, Affine::new([a / scale, b / scale, c / scale, d / scale, at.x, at.y]), TextKind::Point)
(scale, Affine::translate(at.to_vec2()) * turn, TextKind::Point)
}
FrameKind::Area(s, _) => (1.0, Affine::IDENTITY, TextKind::Area { frame: path_of(s, template, to_doc) }),
FrameKind::OnPath { segments, start, end, options } => {
// Turned area type keeps its turn: its lines run along the turned frame, which is kept
// in the text's own space (the frame on the canvas turned back).
FrameKind::Area(s, _, m) => {
let (scale, turn) = turn_of(m)?;
(scale, turn, TextKind::Area { frame: path_of(s, template, to_doc).transformed(turn.inverse()) })
}
// The glyphs follow the path's tangent and grow by one scale: a frame matrix that also
// stretches or slants them isn't made from the text document (the page draws that type).
FrameKind::OnPath { segments, start, end, options, matrix } => {
let (scale, _) = turn_of(matrix).filter(|(_, turn)| {
let [a, b, c, d, ..] = turn.as_coeffs();
(a - d).abs() < 1e-6 && (b + c).abs() < 1e-6
})?;
let n = segments.len() as f64;
// A closed path keeps its end bracket wherever it is (the same place as the start: a
// full turn, see `TextKind::path_span`); an open one's end at its end is none, unless
// a flip makes it the place the type starts.
let end = (closed(segments) || options.flip || *end < n - 0.02).then(|| length_fraction(segments, *end));
(1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end })
(
scale,
Affine::IDENTITY,
TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end },
)
}
};
// A `\x03` ends a line inside its paragraph: a forced line break (U+2028), which the
@@ -1389,7 +1426,7 @@ impl Story {
}
// Each frame of a thread keeps its own options.
match self.frames.get(frame) {
Some(FrameKind::Area(_, options)) => options.apply(&mut t.area, scale),
Some(FrameKind::Area(_, options, _)) => options.apply(&mut t.area, scale),
Some(FrameKind::OnPath { options, .. }) => {
t.path_effect = options.effect;
t.path_align = options.align;
@@ -1450,7 +1487,7 @@ impl Story {
pub(super) fn place_first_line(&self, node: &mut Node, frame: usize, template: (f64, f64), to_doc: Affine) -> bool {
// Closer than this (points of the document) and the line is where the file has it.
const SAME: f64 = 0.5;
if matches!(self.frames.get(frame), Some(FrameKind::Area(_, AreaFrame { first_baseline: Some(_), .. }))) {
if matches!(self.frames.get(frame), Some(FrameKind::Area(_, AreaFrame { first_baseline: Some(_), .. }, _))) {
return false;
}
let NodeKind::Text(t) = &mut node.kind else { return false };
@@ -1458,7 +1495,8 @@ impl Story {
return false;
}
let Some((_, (x, y))) = self.line_starts(template).into_iter().next() else { return false };
let at = to_doc * Point::new(x, y);
// In the text's own space, where its lines are laid out (turned area type's is turned).
let at = t.xf.inverse() * (to_doc * Point::new(x, y));
let db = vectorcraft_text::FontDb::global();
// A frame too short for the line lays nothing out: as the line needs it (see `fit_first_line`).
let mut probe = TextObject::clone(t);
@@ -2229,7 +2267,7 @@ mod tests {
for frame in [
FrameKind::Point([0.0, 1.0, -1.0, 0.0, 30.0, 40.0]),
FrameKind::Point([2.0, 0.0, 0.0, 2.0, -7.0, 3.0]),
FrameKind::Area(area_segments(), AreaFrame::default()),
FrameKind::Area(area_segments(), AreaFrame::default(), NO_MATRIX),
] {
let mut st = story("type", &[0.0], &Para::default());
st.frames = vec![frame.clone()];
@@ -2987,12 +3025,12 @@ mod tests {
let mut s = story("one\rtwo\rthree\r", &[0.0, 15.6, 31.2], &Para::default());
// A point-type frame (the helper's) isn't fitted.
assert!(!s.fit_last_lines(&mut t));
s.frames = vec![FrameKind::Area(vec![], AreaFrame::default())];
s.frames = vec![FrameKind::Area(vec![], AreaFrame::default(), NO_MATRIX)];
assert!(s.fit_last_lines(&mut t));
assert_eq!(vectorcraft_text::layout(db, &t).lines.len(), 3);
// A story threaded through two frames: its lines are the first frame's alone.
let mut t = area(third.baseline - 20.0 + third.descent / 2.0);
s.frames.push(FrameKind::Area(vec![], AreaFrame::default()));
s.frames.push(FrameKind::Area(vec![], AreaFrame::default(), NO_MATRIX));
assert!(!s.fit_last_lines(&mut t));
}
@@ -3017,7 +3055,7 @@ mod tests {
(placed, l.lines.first().map(|l| l.baseline), t.area.first_baseline)
};
let mut s = story("Heading\r", &[], &Para::default());
s.frames = vec![FrameKind::Area(frame, AreaFrame::default())];
s.frames = vec![FrameKind::Area(frame, AreaFrame::default(), NO_MATRIX)];
// Where this lays the line out on its own: the file agrees, and nothing changes.
s.lines = vec![(10.0, 20.0)];
let (_, Some(own), _) = first(&s) else { panic!("a line") };
@@ -3030,6 +3068,32 @@ mod tests {
assert!(at.is_some_and(|y| (y - (own - 3.0)).abs() < 1e-6), "{at:?} for {}", own - 3.0);
}
#[test]
fn turned_area_type_s_first_line_is_compared_in_its_own_space() {
// GUARDS: the file's first line was compared with the layout where it is on the page, not
// in the turned type's own space: turned area type whose line is where the file has it got
// a fixed first baseline it doesn't keep.
let (template, to_doc) = ((CANVAS_CENTRE, -CANVAS_CENTRE), Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]));
let first = |s: &Story| {
let mut node = s.node(NodeId(0), 0, template, to_doc).unwrap();
let placed = s.place_first_line(&mut node, 0, template, to_doc);
let NodeKind::Text(t) = node.kind else { panic!("area type") };
let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
(placed, l.lines.first().map(|l| l.baseline), t.area.first_baseline)
};
let mut s = story("Heading\r", &[], &Para::default());
// A quarter turn round the canvas's origin: the frame's own space is the text document's.
s.frames = vec![area_frame("/2 [ 0 1 -1 0 0 0 ]")];
s.lines = vec![(10.0, 20.0)];
let (_, Some(own), _) = first(&s) else { panic!("a line") };
s.lines = vec![(10.0, own)];
assert_eq!(first(&s), (false, Some(own), vectorcraft_doc::FirstBaseline::Ascent));
s.lines = vec![(10.0, own - 3.0)];
let (placed, at, fb) = first(&s);
assert!(placed && fb == vectorcraft_doc::FirstBaseline::Fixed, "{fb:?}");
assert!(at.is_some_and(|y| (y - (own - 3.0)).abs() < 1e-6), "{at:?} for {}", own - 3.0);
}
/// A text document's area frame, the rectangle 10, 20 to 210, 120 of the canvas, whose frame
/// data has `options` besides its kind, written by hand.
fn area_frame(options: &str) -> FrameKind {
@@ -3065,6 +3129,91 @@ mod tests {
t.area
}
/// The text object a story in the area frame [`area_frame`] makes with `options` comes in as,
/// or `None`.
fn area_type(options: &str) -> Option<TextObject> {
let mut s = story("Some area type\r", &[], &Para::default());
s.frames = vec![area_frame(options)];
let to_doc = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]);
match s.node(NodeId(0), 0, (CANVAS_CENTRE, -CANVAS_CENTRE), to_doc)?.kind {
NodeKind::Text(t) => Some(*t),
_ => None,
}
}
/// Width and height of the area frame of `t`, in its own space.
fn own_frame_size(t: &TextObject) -> (f64, f64) {
let vectorcraft_doc::TextKind::Area { frame } = &t.kind else { panic!("area type") };
let r = frame.bounds().unwrap();
(r.width(), r.height())
}
#[test]
fn turned_area_type_comes_in_turned_with_its_lines_along_its_frame() {
// GUARDS: area type's frame matrix was left out: a frame turned a quarter came in unturned,
// its lines across the page where the file runs them down it.
let plain = area_type("").unwrap();
let turned = area_type("/2 [ 0 1 -1 0 300 0 ]").unwrap();
let (w, h) = own_frame_size(&plain);
assert!(w > h, "{w} by {h}");
// On the page the frame stands on its end ...
let page = turned.bounds().unwrap();
assert!((page.width() - h).abs() < 1e-6 && (page.height() - w).abs() < 1e-6, "{page:?}");
// ... and in the text's own space, where its lines run, it is as wide as the unturned one.
let (tw, th) = own_frame_size(&turned);
assert!((tw - w).abs() < 1e-6 && (th - h).abs() < 1e-6, "{tw} by {th}");
let along = turned.xf * Point::new(1.0, 0.0) - turned.xf * Point::ZERO;
assert!(along.x.abs() < 1e-9 && (along.y.abs() - 1.0).abs() < 1e-9, "{along:?}");
// A turn alone leaves the type's size as it is.
assert_eq!(turned.runs[0].style.size, plain.runs[0].style.size);
}
#[test]
fn a_scaled_area_frame_scales_its_type_and_a_mirrored_one_isnt_made() {
// GUARDS: area type's frame matrix was left out: a frame scaled up came in at its unscaled
// size, and a mirrored one unmirrored.
let plain = area_type("").unwrap();
let double = area_type("/2 [ 2 0 0 2 0 0 ]").unwrap();
assert_eq!(double.runs[0].style.size, plain.runs[0].style.size * 2.0);
let ((w, h), (dw, dh)) = (own_frame_size(&plain), own_frame_size(&double));
assert!((dw - 2.0 * w).abs() < 1e-6 && (dh - 2.0 * h).abs() < 1e-6, "{dw} by {dh}");
// Mirrored type isn't made from the text document, as point type isn't.
assert!(area_type("/2 [ -1 0 0 1 0 0 ]").is_none());
}
#[test]
fn type_on_a_turned_path_runs_along_the_path_where_the_canvas_has_it() {
// GUARDS: type on a path's frame matrix was left out: the path of a frame turned a quarter
// came in unturned.
let open = [[0.0, 0.0, 30.0, 0.0, 70.0, 0.0, 100.0, 0.0], [100.0, 0.0, 130.0, 0.0, 170.0, 0.0, 200.0, 0.0]];
let path = |options: &str| {
let (t, _) = on_path("type", on_path_frame_with(&open, [0.0, 2.0], options).unwrap());
let vectorcraft_doc::TextKind::OnPath { path, .. } = &t.kind else { panic!("type on a path") };
path.bounds().unwrap()
};
let plain = path("");
assert!(plain.width() > 100.0 && plain.height() < 1e-6, "{plain:?}");
let turned = path("/2 [ 0 1 -1 0 0 0 ]");
assert!(turned.width() < 1e-6 && (turned.height() - plain.width()).abs() < 1e-6, "{turned:?}");
}
#[test]
fn type_on_a_stretched_path_is_left_to_the_page() {
// GUARDS: a frame matrix that stretched the path four times and the type not at all came
// in with glyphs twice as wide and twice as tall.
let open = [[0.0, 0.0, 30.0, 0.0, 70.0, 0.0, 100.0, 0.0], [100.0, 0.0, 130.0, 0.0, 170.0, 0.0, 200.0, 0.0]];
let made = |options: &str| {
let mut st = story("type", &[0.0], &Para::default());
st.frames = vec![on_path_frame_with(&open, [0.0, 2.0], options).unwrap()];
st.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY)
};
assert!(made("/2 [ 4 0 0 1 0 0 ]").is_none());
assert!(made("/2 [ 1 0.5 0 1 0 0 ]").is_none());
// A uniform scale and a turn are still made.
assert!(made("/2 [ 2 0 0 2 0 0 ]").is_some());
assert!(made("/2 [ 0 2 -2 0 0 0 ]").is_some());
}
#[test]
fn area_frame_options_are_read() {
// GUARDS: area type came in with one row, one column and the 18 pt gutter whatever its frame kept.
@@ -3152,7 +3301,7 @@ mod tests {
#[test]
fn area_frame_without_options_comes_in_as_before() {
assert_eq!(area_of(vec![area_frame("")], 0, 1.0), vectorcraft_doc::AreaOptions::default());
assert_eq!(area_frame(""), FrameKind::Area(area_segments(), AreaFrame::default()));
assert_eq!(area_frame(""), FrameKind::Area(area_segments(), AreaFrame::default(), NO_MATRIX));
}
/// The segments [`area_frame`] writes.
@@ -3199,7 +3348,7 @@ mod tests {
(placed, l.baselines().first().map(|b| b.0.x), t.area.first_baseline)
};
let mut s = story("§§\r", &[], &Para::default());
s.frames = vec![FrameKind::Area(frame, AreaFrame::default())];
s.frames = vec![FrameKind::Area(frame, AreaFrame::default(), NO_MATRIX)];
s.vertical = true;
s.anchor = (210.0, 20.0);
s.lines = vec![(0.0, 0.0)];
+24 -1
View File
@@ -38,7 +38,9 @@ fn frame_text_from_art(info: &SlotInfo, node: &mut Node, region: &mut Option<Rec
let size = text.runs.iter().map(|r| r.style.size).fold(0.0, f64::max);
match &mut text.kind {
TextKind::Area { frame } => {
*frame = path.clone();
// The object's path is on the page; turned area type keeps its frame in its own
// (turned) space.
*frame = path.transformed(text.xf.inverse());
*region = path.bounds();
}
TextKind::OnPath { path: on, .. } => {
@@ -738,4 +740,25 @@ mod tests {
assert_eq!(has_made_words(&present, &content, &spelled, &mut few), Some(true));
assert!(one_word_everywhere - few.0 < one_word_everywhere / 2, "{} searches", one_word_everywhere - few.0);
}
/// The object's own path frames turned area type where the path is on the page: the frame is
/// kept in the type's turned space.
#[test]
fn an_object_s_path_frames_turned_area_type_where_the_path_is() {
// GUARDS: the path replaced the frame as it is on the page, and the type's turn then turned
// it a second time.
let mut node = text(1, "Turned");
let NodeKind::Text(t) = &mut node.kind else { panic!("type") };
t.xf = Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]);
t.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)) };
let on_page = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 20.0, 150.0, 220.0));
let info = SlotInfo { story: Some(0), frame: 0, shown: true, art_path: Some(on_page.clone()), look: None, group: None };
let mut region = None;
frame_text_from_art(&info, &mut node, &mut region);
let NodeKind::Text(t) = &node.kind else { panic!("type") };
let (drawn, want) = (t.bounds().unwrap(), on_page.bounds().unwrap());
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
assert!(near(drawn.x0, want.x0) && near(drawn.y0, want.y0) && near(drawn.x1, want.x1) && near(drawn.y1, want.y1), "{drawn:?} {want:?}");
assert_eq!(region, Some(want));
}
}
+19 -1
View File
@@ -720,7 +720,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.taskBar.actions",
"Bar Actions",
"",
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"conceptToVector\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
),
(
"window.taskBar.resetActions",
@@ -1038,6 +1038,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
),
(
"ui.conceptVector",
"Concept to Vector…",
"",
"{} open the Concept to Vector panel for the selected image or unexpanded Image Trace object; an error when the selection is not one such object, unlocked and shown (engine: conceptVector.generate / conceptVector.insert)",
),
(
"ui.conceptVector.generate",
"Generate Concept to Vector Styles",
"",
"{} make the styles ticked in the Concept to Vector panel of the selected image or unexpanded Image Trace object, with the panel's Detail (the panel's Generate; engine: conceptVector.generate), and show them in the panel; off the UI thread in the app unless VECTORCRAFT_SYNC_OPEN is set, one part a frame on the web; a run going is canceled first, and the new one starts once its thread has ended → {running: true} while they are made, else {running: false, job}",
),
(
"ui.conceptVector.cancel",
"Cancel Concept to Vector",
"",
"{} stop the styles the Concept to Vector panel is making off the UI thread (the panel's Cancel; on the web, before the next part): nothing is kept or shown → {canceled: 0 or 1}",
),
(
"ui.recolorUndo",
"Undo Changes",
+29 -2
View File
@@ -4,7 +4,8 @@
//! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit
//! and dashes from the pen). Opaque solid strokes with round caps and round joins drawn one after
//! another, each starting where the last one ended, with the same pen and clip, join into one
//! path. Other strokes stay apart, each with its own caps and its own dashes.
//! path. Other strokes stay apart, each with its own caps and its own dashes. A path that is
//! only filled comes in with every figure closed.
//! - A path filled with a pattern or hatched brush is filled with the average color of the
//! brush's tile.
//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or
@@ -309,11 +310,14 @@ impl Mapper {
st
}
/// A path node painted with `fill` and `stroke`; None when neither shows.
/// A path node painted with `fill` and `stroke`; None when neither shows. A path that is only
/// filled has every figure closed, as a fill closes it: a figure a file fills without closing
/// it (FILLPATH without CLOSEFIGURE) comes in as a closed path.
fn path_node(&self, bp: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f32, &LineStyle)>, even_odd: bool) -> Option<Node> {
if bp.elements().is_empty() {
return None;
}
let bp = if stroke.is_none() { closed_figures(&bp) } else { bp };
let mut items = vec![];
if let Some(c) = fill.filter(|c| c[3] > 0) {
let mut f = FillLayer::new(color(c));
@@ -793,6 +797,29 @@ impl Mapper {
}
}
/// `bp` with every figure that has a segment and no close closed.
fn closed_figures(bp: &BezPath) -> BezPath {
let mut out = BezPath::new();
let mut open = false;
for el in bp.elements() {
match el {
PathEl::MoveTo(_) => {
if open {
out.close_path();
}
open = false;
}
PathEl::ClosePath => open = false,
PathEl::LineTo(_) | PathEl::QuadTo(..) | PathEl::CurveTo(..) => open = true,
}
out.push(*el);
}
if open {
out.close_path();
}
out
}
/// Where a line `lead + span` long (along the baseline) starts from the reference point, as
/// `align` puts it, and `lead` on from there: where its first character starts.
fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 {
+48
View File
@@ -1560,3 +1560,51 @@ fn emf_without_a_frame_is_read_at_its_device_resolution() {
let p = paths(&back.document);
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 5.0 * mm, 20.0 * mm, 7.5 * mm), 0.01), "{:?}", p[0].geometric_bounds());
}
/// Whether each subpath of each path in `bytes` is closed, in order.
fn closed_subpaths(bytes: &[u8]) -> Vec<Vec<bool>> {
paths(&import(bytes).unwrap().document)
.iter()
.map(|n| match &n.kind {
NodeKind::Path { path, .. } => path.subpaths.iter().map(|s| s.closed).collect(),
_ => panic!("a path"),
})
.collect()
}
#[test]
fn filled_ellipses_and_filled_path_figures_come_in_closed() {
// A green brush in slot 1, selected; a null pen.
let brush = vec![(39, le(&[1, 0, 0x00_ff_00, 0])), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32]))];
// EMR_ELLIPSE.
let ellipse = [brush.clone(), vec![(42, le(&[1000, 1000, 2000, 1500]))]].concat();
assert_eq!(closed_subpaths(&hand_emf(5000, 3000, &ellipse)), vec![vec![true]]);
// EmfPlusFillEllipse with an inline green color, in a dual file.
let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]);
let fill = [le(&[0xFF00_FF00u32 as i32]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat();
let comment = emf_plus(&[(0x4001, 1, header), (0x400E, 0x8000, fill), (0x4002, 0, vec![])]);
assert_eq!(closed_subpaths(&hand_emf(5000, 3000, &[(70, comment)])), vec![vec![true]]);
// BEGINPATH, two figures of MOVETOEX and POLYBEZIERTO16 (half an ellipse each) without
// CLOSEFIGURE, ENDPATH, then `paint`.
let bracket = |paint: u32, pen: bool| {
let mut r = brush.clone();
if pen {
r.push((37, le(&[0x8000_0007u32 as i32])));
}
r.push((59, vec![]));
for x in [1000, 3000] {
let half: [i16; 12] = [x + 1000, 1500, x + 200, 1500, x, 1400, x, 1250, x, 1100, x + 200, 1000];
r.push((27, le(&[i32::from(x) + 1000, 1250])));
let mut body = le(&[0, 0, 0, 0, 6]);
body.extend(half.iter().flat_map(|v| v.to_le_bytes()));
r.push((88, body));
}
r.push((60, vec![]));
r.push((paint, le(&[0, 0, 0, 0])));
closed_subpaths(&hand_emf(5000, 3000, &r))
};
// FILLPATH: a fill closes every open figure.
assert_eq!(bracket(62, false), vec![vec![true, true]]);
// STROKEPATH: a stroke leaves them open.
assert_eq!(bracket(64, true), vec![vec![false, false]]);
}
+30 -8
View File
@@ -83,6 +83,7 @@ impl<'p> Builder<'p> {
cmyk_keys: HashSet::new(),
intent_cmyk: None,
separation_paints: HashMap::new(),
fill_overprint: (false, 0),
opaque: HashSet::new(),
warnings: vec![],
fonts: HashMap::new(),
@@ -155,6 +156,7 @@ impl<'p> Builder<'p> {
self.stack = vec![Frame::new(FrameKind::Root)];
self.root_groups.clear();
self.blend = BlendMode::Normal;
self.fill_overprint = (false, 0);
self.glyphs = None;
self.type3_run = None;
self.text = None;
@@ -182,6 +184,21 @@ impl<'p> Builder<'p> {
self.scan.overprints && self.scan.paints.get(self.paint_at - 1).copied().unwrap_or(false)
}
/// Whether the image the interpreter draws now, colorized by `paint`, overprints: its fill
/// overprint, as the interpreter reported it for this image. Off in a nested reading, as for
/// paths. A process color (one without a swatch) overprinting in mode 0 is reported as paths
/// are ([`OVERPRINT_ZERO_MODE`]).
pub(super) fn image_overprint(&mut self, paint: &Paint) -> bool {
let (on, mode) = self.fill_overprint;
if !on || self.nested > 0 {
return false;
}
if mode == 0 && matches!(paint, Paint::Solid { swatch: None, .. }) {
self.warn(OVERPRINT_ZERO_MODE);
}
true
}
/// What the interpreter draws now, as the page's walk counts it: the path whose turn comes
/// next, or the `text` before it. `None` in a nested reading, which the walk doesn't follow.
pub(super) fn walked(&self, text: bool) -> Option<Walked> {
@@ -207,9 +224,10 @@ impl<'p> Builder<'p> {
pub(super) fn end_page(&mut self) -> Vec<(Option<usize>, Vec<Arc<Node>>)> {
let mut children = self.close_frames();
// The interpreter drew another number of paths than the file was read to paint: which
// of them overprint can't be trusted.
// of them overprint can't be trusted. An image's overprint comes from the interpreter
// itself, so it stays.
if self.scan.overprints && self.paint_at != self.scan.paints.len() {
children.iter_mut().for_each(vectorcraft_doc::overprint::clear_overprints);
children.iter_mut().for_each(vectorcraft_doc::overprint::clear_paint_overprints);
self.warn(OVERPRINT_UNREAD);
}
let groups = std::mem::take(&mut self.root_groups);
@@ -1114,7 +1132,8 @@ impl<'p> Builder<'p> {
}
/// An image of key `key` (its blob made by `make` the first time), placed by `xf`, with opacity
/// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image).
/// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image), which
/// overprints when the interpreter says the image does ([`Self::image_overprint`]).
pub(super) fn add_image_masked(
&mut self,
key: u128,
@@ -1123,6 +1142,7 @@ impl<'p> Builder<'p> {
mask: Option<OpacityMask>,
colorize: Option<Paint>,
) {
let overprint = colorize.as_ref().is_some_and(|p| self.image_overprint(p));
let (k, w, h) = if let Some(v) = self.image_keys.get(&key).cloned() {
v
} else {
@@ -1143,6 +1163,7 @@ impl<'p> Builder<'p> {
);
n.extras_mut().mask = mask.map(Box::new);
n.extras_mut().colorize = colorize.map(Box::new);
n.extras_mut().colorize_overprint = overprint;
self.push_node(n);
}
@@ -1616,14 +1637,15 @@ fn visual_glyph_text(text: String) -> String {
order.iter().filter_map(|&i| chars.get(i)).collect()
}
/// Whether a visible fill or stroke among `children` overprints, characters' too, directly or
/// through children that don't isolate. In an isolated group an overprinting object is drawn on
/// the group's empty backdrop, so it covers the inks of the art below the group that it does not
/// paint; without isolation it leaves them.
/// Whether a visible fill or stroke among `children` overprints, characters' and colorized
/// images' too, directly or through children that don't isolate. In an isolated group an
/// overprinting object is drawn on the group's empty backdrop, so it covers the inks of the art
/// below the group that it does not paint; without isolation it leaves them.
fn children_overprint(children: &[Arc<Node>]) -> bool {
children.iter().any(|c| {
c.visible
&& (c.appearance.items.iter().any(|i| i.visible() && i.overprint())
&& (c.colorize_overprints()
|| c.appearance.items.iter().any(|i| i.visible() && i.overprint())
|| matches!(&c.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|| (!c.isolate && c.children().is_some_and(|ch| children_overprint(ch))))
})
+4
View File
@@ -31,6 +31,10 @@ impl<'a> Device<'a> for Builder<'_> {
}
}
fn set_overprint(&mut self, fill: bool, _stroke: bool, mode: u8) {
self.fill_overprint = (fill, mode);
}
fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &craft::pdf::interpret::Paint<'a>, draw_mode: &PathDrawMode) {
self.flush_glyphs();
self.flush_type3();
+3
View File
@@ -144,6 +144,9 @@ pub(super) struct Builder<'p> {
/// Images in a Separation space, by key: the paint of their ink, or `None` when they open in
/// RGB (an ink that can't be told, tints that can't be read).
pub(super) separation_paints: HashMap<u128, Option<Paint>>,
/// The fill overprint (`/op`) and overprint mode (`/OPM`) the interpreter reported last. It
/// reports them before each image it draws, and an image paints with the fill's overprint.
pub(super) fill_overprint: (bool, u8),
/// Mask keys of CMYK images whose mask turned out to hide nothing.
pub(super) opaque: HashSet<u128>,
pub(super) warnings: Vec<String>,
+115
View File
@@ -134,3 +134,118 @@ fn hidden_optional_content_and_pattern_cells_dont_shift_the_count() {
assert!(about_overprint(&r).is_empty(), "layers {layers}: {:?}", r.warnings);
}
}
/// A 2 × 1 image in the spot ink `Spot1` (a Separation space): it opens colorized by the ink.
const SPOT_IMAGE: &str = "<< /Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace [/Separation /Spot1 /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>] /BitsPerComponent 8 /Filter /ASCIIHexDecode /Length 5 >>\nstream\nFF00>\nendstream";
/// An 8 × 1 image mask: it opens colorized by the color that paints it.
const MASK: &str = "<< /Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode /Length 3 >>\nstream\nC3>\nendstream";
/// A page drawing `image` as `/Im1` with `content`, then the `extra` objects after it.
fn open_image(content: &str, image: &str, extra: &[&str]) -> ImportReport {
let mut objects = vec![image];
objects.extend_from_slice(extra);
open(content, &format!("{SPOT} /XObject << /Im1 {} 0 R /X0 {} 0 R >>", first_extra(1), first_extra(1) + 1), &objects)
}
/// Each colorized image in paint order: whether its color overprints.
fn image_overprints(d: &Document) -> Vec<bool> {
let mut out = vec![];
d.walk(|n: &Node| {
if matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.is_some() {
out.push(n.colorize_overprints());
}
});
out
}
/// One placement of `/Im1`, `i` steps down the page.
fn draw(i: u32) -> String {
format!("q 80 0 0 10 10 {} cm /Im1 Do Q", 10 + 20 * i)
}
#[test]
fn a_spot_image_overprints_as_its_fill_does() {
// `/op` is the fill's; `/OP` alone is both; a stroke's `/OP` beside `/op false` is not the image's.
let content = format!("/On gs {} /Off gs {} /Stroke gs {} /Both gs {}", draw(0), draw(1), draw(2), draw(3));
let r = open_image(&content, SPOT_IMAGE, &[]);
assert_eq!(image_overprints(&r.document), [true, false, false, true], "{:?}", r.warnings);
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
// Written with its overprint and read again, each keeps it.
let back = import_with_report(&export(&r.document, &PdfOptions::uncompressed()).unwrap(), &ImportOptions::default()).unwrap();
assert_eq!(image_overprints(&back.document), [true, false, false, true], "{:?}", back.warnings);
}
#[test]
fn an_image_mask_overprints_as_its_fill_does() {
let r = open_image(&format!("/CS0 cs 1 scn /On gs {} /Off gs {}", draw(0), draw(1)), MASK, &[]);
assert_eq!(image_overprints(&r.document), [true, false], "{:?}", r.warnings);
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
// Overprint mode 0 changes nothing for a spot color; a process color's zero tints would knock out.
let r = open_image(&format!("/Zero gs /CS0 cs 1 scn {}", draw(0)), MASK, &[]);
assert_eq!(image_overprints(&r.document), [true]);
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
let r = open_image(&format!("/Zero gs 0 0 0 1 k {}", draw(0)), MASK, &[]);
assert_eq!(image_overprints(&r.document), [true]);
assert_eq!(about_overprint(&r).len(), 1, "{:?}", r.warnings);
assert!(about_overprint(&r)[0].contains("/OPM 0"));
}
#[test]
fn an_image_in_a_form_overprints_as_the_form_sets_it() {
// The page's state, then the form's own.
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 400 400]", &format!("{} /Off gs {}", draw(0), draw(1)));
let r = open_image("/On gs /X0 Do", SPOT_IMAGE, &[&form]);
assert_eq!(image_overprints(&r.document), [true, false], "{:?}", r.warnings);
}
#[test]
fn an_isolated_form_holding_only_an_overprinting_image_stays_isolated() {
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 400 400] /Group << /S /Transparency /I true >>", &draw(0));
let r = open_image("/On gs /X0 Do", SPOT_IMAGE, &[&form]);
let mut groups = vec![];
r.document.walk(|n: &Node| {
if matches!(n.kind, NodeKind::Group { .. }) {
groups.push(n.isolate);
}
});
assert_eq!(image_overprints(&r.document), [true]);
assert!(groups.contains(&true), "{groups:?}");
}
#[test]
fn an_image_in_a_pattern_cell_knocks_out_as_the_cells_paths_do() {
let (x, cell) = (first_extra(1), first_extra(1) + 1);
let cell_stream = stream(
&format!(
"/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << {ON} /XObject << /Im1 {x} 0 R >> >>"
),
"/On gs 0 0 1 rg 0 0 5 5 re f q 10 0 0 10 0 0 cm /Im1 Do Q",
);
let r = open("/On gs /Pattern cs /P0 scn 0 0 100 100 re f", &format!("/Pattern << /P0 {cell} 0 R >>"), &[SPOT_IMAGE, &cell_stream]);
let mut art = vec![];
for p in r.document.patterns.iter() {
for a in &p.art {
a.walk(&mut |n: &Node| {
if matches!(n.kind, NodeKind::Image(_)) {
art.push(n.colorize_overprints());
}
});
}
}
assert_eq!(art, [false], "{:?}", r.warnings);
}
#[test]
fn an_image_keeps_its_overprint_on_a_page_whose_paths_cant_be_counted() {
// The paths' overprint is dropped (see above); the image's comes from the interpreter.
let content = format!("0 0 1 rg /Sh0 sh /On gs 10 10 50 50 re f {}", draw(4));
let page = PdfPage {
resources: format!("{ON} /Shading << /Sh0 << /ShadingType 99 >> >> /XObject << /Im1 {} 0 R >>", first_extra(1)),
..PdfPage::new(400.0, 400.0, &content)
};
let r = import_with_report(&pdf_with(&[page], &[SPOT_IMAGE], None), &ImportOptions::default()).unwrap();
assert_eq!(overprints(&r.document), [(Some(false), None)]);
assert_eq!(image_overprints(&r.document), [true]);
assert_eq!(about_overprint(&r).len(), 1, "{:?}", r.warnings);
}
+17
View File
@@ -834,6 +834,23 @@ fn type_path_handles(cx: &ToolContext) -> Vec<Overlay> {
out
}
/// The anchors and direction handles of selected, editable type on a path's path, for the tools
/// that edit them besides Direct Selection (the Anchor Point, Add and Delete Anchor Point tools and
/// the Pen, #10862): the canvas draws only a path's own.
pub(crate) fn type_path_overlays(cx: &ToolContext) -> Vec<Overlay> {
let editable = cx.doc.editable();
let mut out = vec![];
for &id in &cx.selection.objects {
let Some(path) = cx.doc.node(id).filter(|n| is_path_type(n) && editable(id)).and_then(editable_path) else { continue };
let color = cx.doc.layer_color(id);
out.extend(path.anchors().map(|(_, _, a)| Overlay::Anchor { p: a.p, color, filled: false, size: 5.0 }));
}
if !out.is_empty() {
out.extend(type_path_handles(cx));
}
out
}
/// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and
/// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path,
/// subpath, anchor, is_out).
+52 -7
View File
@@ -377,7 +377,18 @@ pub(crate) fn walk_pickable<'a>(cx: &ToolContext<'a>, mut f: impl FnMut(&'a vect
/// Editable path nodes, selected ones first, then the rest top-most first ([`walk_pickable`]).
pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec<NodeId> {
let mut v: Vec<NodeId> = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(|n| n.path_data().is_some())).collect();
candidates(cx, false)
}
/// [`candidate_paths`], with selected type on a path outside perspective among the selected ones:
/// the objects whose anchors the Add, Delete and Anchor Point tools edit (#10862).
pub(crate) fn anchor_owners(cx: &ToolContext) -> Vec<NodeId> {
candidates(cx, true)
}
fn candidates(cx: &ToolContext, path_type: bool) -> Vec<NodeId> {
let picks = |n: &vectorcraft_doc::Node| n.path_data().is_some() || (path_type && crate::select::is_path_type(n));
let mut v: Vec<NodeId> = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(picks)).collect();
let mut rest = vec![];
walk_pickable(cx, |n| {
if let NodeKind::Path { guide: false, .. } = &n.kind {
@@ -407,9 +418,28 @@ pub(crate) fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator<Item = No
.filter(move |&id| editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })))
}
/// [`editable_paths`] with selected type on a path outside perspective: the objects the Pen's Auto
/// Add/Delete adds anchors to and deletes them from (#10862).
pub(crate) fn editable_anchor_owners<'a>(cx: &'a ToolContext) -> impl Iterator<Item = NodeId> + 'a {
let editable = cx.doc.editable();
cx.selection.objects.iter().copied().filter(move |&id| {
editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. }) || crate::select::is_path_type(n))
})
}
/// The paths whose anchors show with the Pen: the selected ones, and those inside selected groups
/// and compound paths (not guides, nor locked or hidden ones). Pen + Alt converts their anchors.
/// and compound paths (not guides, nor locked or hidden ones).
pub(crate) fn shown_paths(cx: &ToolContext) -> Vec<NodeId> {
shown(cx, false)
}
/// [`shown_paths`] with selected type on a path outside perspective, as the Anchor Point tool the
/// Pen lends takes it ([`anchor_owners`]): the objects whose anchors Pen + Alt converts (#10862).
pub(crate) fn shown_anchor_owners(cx: &ToolContext) -> Vec<NodeId> {
shown(cx, true)
}
fn shown(cx: &ToolContext, path_type: bool) -> Vec<NodeId> {
fn inside(n: &vectorcraft_doc::Node, v: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Path { guide: false, .. } => v.push(n.id),
@@ -424,7 +454,11 @@ pub(crate) fn shown_paths(cx: &ToolContext) -> Vec<NodeId> {
}
let mut v = vec![];
for n in cx.selection.objects.iter().filter_map(|id| cx.doc.node(*id)) {
inside(n, &mut v);
if path_type && crate::select::is_path_type(n) {
v.push(n.id);
} else {
inside(n, &mut v);
}
}
let editable = cx.doc.editable();
v.retain(|id| editable(*id));
@@ -436,11 +470,17 @@ pub(crate) fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId
anchor_in(cx, candidate_paths(cx), p, tol)
}
/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor).
/// [`hit_anchor`] on the [`anchor_owners`], selected type on a path's path included.
pub(crate) fn hit_owner_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> {
anchor_in(cx, anchor_owners(cx), p, tol)
}
/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor). Type on
/// a path among `ids` offers its path's anchors ([`vectorcraft_doc::Node::anchor_path`]).
pub(crate) fn anchor_in(cx: &ToolContext, ids: impl IntoIterator<Item = NodeId>, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> {
let mut best: Option<((NodeId, usize, usize), f64)> = None;
for id in ids {
let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue };
let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue };
for (si, ai, a) in pd.anchors() {
let d = a.p.distance(p);
if d <= tol && best.is_none_or(|b| d < b.1 - 1e-9) {
@@ -459,11 +499,16 @@ pub(crate) fn hit_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeI
segment_in(cx, candidate_paths(cx), p, tol)
}
/// [`hit_segment`] on the [`anchor_owners`], selected type on a path's path included.
pub(crate) fn hit_owner_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> {
segment_in(cx, anchor_owners(cx), p, tol)
}
/// Nearest point within `tol` on a segment of the first of `ids` that passes there: (path,
/// subpath, segment, t).
/// subpath, segment, t). Type on a path among `ids` offers its path's segments.
pub(crate) fn segment_in(cx: &ToolContext, ids: impl IntoIterator<Item = NodeId>, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> {
for id in ids {
let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue };
let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue };
if let Some((si, seg, t, _, d)) = pd.nearest(p)
&& d <= tol
{
+21 -16
View File
@@ -14,12 +14,14 @@
//! follow the same conversions (#2544).
//! Scissors: hover and click snap as the Pen does; click a path to split it there (Alt = add,
//! as the Add Anchor Point tool does).
//! Add, Delete and Anchor Point edit the path of selected type on a path outside perspective as
//! they edit a path's (#10862); Delete leaves it two anchors at least, and Scissors does not cut it.
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_geom::{ParamCurve, Point};
use super::{FEEDBACK, hit_anchor, hit_segment, insert_anchor, remove_anchor};
use super::{FEEDBACK, hit_anchor, hit_owner_anchor, hit_owner_segment, hit_segment, insert_anchor, remove_anchor};
use crate::direct::hit_handle;
use crate::guides::{DrawSnap, HandleSnap};
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -276,14 +278,14 @@ impl AnchorTool {
}
fn anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option<Point> {
cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
}
/// Where anchor `ai` is in the document a preview edits: the document as the interaction
/// began, since each preview runs on that, otherwise the document `cx` shows.
fn began_anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option<Point> {
let d = cx.interaction_doc.unwrap_or(cx.doc);
d.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
d.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
}
/// Where a blend's spine point `ai` is in the spine a spine edit changes: the spine pinned
@@ -342,9 +344,9 @@ impl AnchorTool {
let (point, tol) = (cx.point_tol(), cx.pick_tol());
let mut target = if let Some((id, si, ai, out)) = hit_handle(cx, p, point) {
State::Handle { id, si, ai, out, start: p, began: false }
} else if let Some((id, si, ai)) = hit_anchor(cx, p, point) {
} else if let Some((id, si, ai)) = hit_owner_anchor(cx, p, point) {
State::Convert { id, si, ai, start: p, began: false }
} else if let Some((id, si, seg, t)) = hit_segment(cx, p, tol) {
} else if let Some((id, si, seg, t)) = hit_owner_segment(cx, p, tol) {
State::Reshape { id, si, seg, t, start: p, began: false, spine: false }
} else {
State::Idle
@@ -402,12 +404,10 @@ impl AnchorTool {
/// instead of converting it. Any other press is kept.
fn moving(cx: &ToolContext, st: State) -> State {
match st {
State::Convert { id, si, ai, start, .. } => {
match cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) {
Some(from) => State::Move { id, si, ai, from, start, began: false },
None => st,
}
}
State::Convert { id, si, ai, start, .. } => match Self::anchor_pos(cx, id, si, ai) {
Some(from) => State::Move { id, si, ai, from, start, began: false },
None => st,
},
State::SpineConvert { id, ai, start, .. } => {
match crate::direct::spines(cx)
.into_iter()
@@ -471,11 +471,11 @@ impl AnchorTool {
}
fn add(cx: &ToolContext, p: Point) -> Vec<Action> {
hit_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect()
hit_owner_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect()
}
fn delete(cx: &ToolContext, p: Point) -> Vec<Action> {
hit_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect()
hit_owner_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect()
}
}
@@ -708,8 +708,8 @@ impl Tool for AnchorTool {
let has_handles = cx
.doc
.node(id)
.and_then(|n| n.path_data())
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai))
.and_then(|n| n.anchor_path())
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied())
.is_some_and(|a| a.has_in() || a.has_out());
if has_handles {
vec![Action::Exec("path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": "corner"}))]
@@ -743,7 +743,8 @@ impl Tool for AnchorTool {
)]
}
State::Handle { id, si, ai, out, began: false, .. } => {
let Some(a) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) else {
let Some(a) = cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied())
else {
return vec![];
};
vec![Action::Exec(
@@ -780,6 +781,10 @@ impl Tool for AnchorTool {
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = if self.id == "anchorPoint" { Self::spine_overlays(cx) } else { vec![] };
if self.id != "scissors" {
// These tools edit selected type on a path's path, whose anchors the canvas leaves out.
out.extend(crate::direct::type_path_overlays(cx));
}
if matches!(self.state, State::Handle { .. }) {
out.extend(self.guides.iter().cloned());
}
+56
View File
@@ -672,6 +672,62 @@ fn anchor_tools_leave_out_shaper_sources_and_art_outside_isolation() {
assert_eq!(picked(Some(rect), "deleteAnchor", 100.0, 100.0), Some(rect));
}
/// #10862: selected type on a path's path takes the Anchor Point, Add and Delete Anchor Point tools
/// as a path does; Scissors leaves it alone, and type that is not selected is not picked.
#[test]
fn anchor_tools_edit_selected_type_on_a_path() {
let (d, text) = doc_with_path_type();
let p = paint();
let mut s = Selection::default();
s.add(text);
let names = |a: &[Action]| -> Vec<(String, u64)> {
a.iter()
.filter_map(|x| match x {
Action::Preview(c, v) | Action::Exec(c, v) => Some((c.clone(), v["id"].as_u64()?)),
_ => None,
})
.collect()
};
let gesture = |sel: &Selection, tool: &str, from: (f64, f64), to: (f64, f64)| {
let cx = cx(&d, sel, &p);
let mut t = AnchorTool::new(tool);
let mut out = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, from.0, from.1));
if from != to {
out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1)));
}
out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1)));
names(&out)
};
let convert = gesture(&s, "anchorPoint", (400.0, 300.0), (420.0, 260.0));
assert!(convert.contains(&("path.convertAnchor".into(), text.0)), "{convert:?}");
assert_eq!(gesture(&s, "addAnchor", (250.0, 300.0), (250.0, 300.0)), vec![("path.insertAnchor".to_string(), text.0)]);
assert_eq!(gesture(&s, "deleteAnchor", (400.0, 300.0), (400.0, 300.0)), vec![("path.removeAnchor".to_string(), text.0)]);
assert!(gesture(&s, "scissors", (250.0, 300.0), (250.0, 300.0)).is_empty(), "Scissors does not cut type");
let none = Selection::default();
assert!(gesture(&none, "anchorPoint", (400.0, 300.0), (420.0, 260.0)).is_empty(), "type that is not selected");
}
/// #10862: the anchors of selected type on a path's path show with the tools that edit them (the
/// canvas draws only a path's own), not with Scissors, and not when the type is not selected.
#[test]
fn anchor_tools_show_the_anchors_of_selected_type_on_a_path() {
let (d, text) = doc_with_path_type();
let p = paint();
let mut s = Selection::default();
s.add(text);
let anchors =
|o: Vec<Overlay>| -> Vec<Point> { o.into_iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(p) } else { None }).collect() };
let ends = [Point::new(100.0, 300.0), Point::new(400.0, 300.0)];
let selected = cx(&d, &s, &p);
for tool in ["anchorPoint", "addAnchor", "deleteAnchor"] {
assert_eq!(anchors(AnchorTool::new(tool).overlays(&selected)), ends, "{tool}");
}
assert_eq!(anchors(crate::pen::PenTool::default().overlays(&selected)), ends, "pen");
assert!(anchors(AnchorTool::new("scissors").overlays(&selected)).is_empty());
let none = Selection::default();
assert!(anchors(AnchorTool::new("anchorPoint").overlays(&cx(&d, &none, &p))).is_empty());
}
#[test]
fn anchor_point_drag_pulls_handles_click_converts() {
let (d, id) = doc_with_rect();
+1 -1
View File
@@ -171,7 +171,7 @@ mod tests {
(TYPE, &["editing"]),
(&["puppetWarp"], &["pins", "selected"]),
// With nothing queued, `current` (0) is no file's index either.
(&["place"], &["count", "current", "sourceIndex", "name", "width", "height", "names"]),
(&["place"], &["count", "total", "current", "sourceIndex", "name", "width", "height", "names"]),
];
let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k));
// Tools that `create` makes and the catalog doesn't list.
+14 -12
View File
@@ -36,7 +36,7 @@ use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{Anchor, BezPath, Point, Vec2};
use crate::direct::hit_handle;
use crate::draw2::{AnchorTool, editable_paths, shown_paths};
use crate::draw2::{AnchorTool, editable_anchor_owners, shown_anchor_owners, shown_paths};
use crate::guides::{DrawSnap, Leave};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -225,21 +225,21 @@ fn pick_endpoint(first: Option<Point>, last: Point, p: Point, tol: f64, tie: End
(None, None) => None,
}
}
/// Alt held over a handle end, an anchor or a segment of a selected path: the Anchor Point tool's
/// gesture, within its tolerance.
/// Alt held over a handle end, an anchor or a segment of a selected path, or of selected type on a
/// path's path: the Anchor Point tool's gesture, within its tolerance.
fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool {
let point = cx.point_tol();
m.alt
&& (hit_handle(cx, p, point).is_some()
|| crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some()
|| crate::draw2::segment_in(cx, crate::draw2::shown_paths(cx), p, cx.pick_tol()).is_some())
|| crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some()
|| crate::draw2::segment_in(cx, shown_anchor_owners(cx), p, cx.pick_tol()).is_some())
}
/// The cursor where [`alt_converts`]: Alt lends the Anchor Point tool, so its caret over a handle
/// end or an anchor, the Reshape Segment cursor over a segment.
fn alt_cursor(cx: &ToolContext, p: Point) -> Cursor {
let point = cx.point_tol();
if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some() {
if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some() {
Cursor::AnchorPoint
} else {
Cursor::ReshapeSegment
@@ -526,7 +526,8 @@ impl Tool for PenTool {
if let Some(t) = &self.convert {
return t.overlays(cx);
}
let mut o = vec![];
// Pen + Alt and Auto Add/Delete edit selected type on a path's path, so its anchors show.
let mut o = crate::direct::type_path_overlays(cx);
// The rubber band preference hides only the preview segment; Measurement Labels decides the readout.
if self.drag.is_none()
&& self.handle.is_none()
@@ -752,15 +753,16 @@ pub(crate) fn continue_from(cx: &ToolContext, id: NodeId, si: usize, at_first: b
out
}
/// Auto Add/Delete: what a click at `p` does to a selected path. On one of its anchors it deletes
/// it; else, where one of its segments passes within `tol`, it adds an anchor. None when the
/// preference turns it off, Shift is held, or no selected path is there.
/// Auto Add/Delete: what a click at `p` does to a selected path, or to selected type on a path's
/// path. On one of its anchors it deletes it; else, where one of its segments passes within `tol`,
/// it adds an anchor. None when the preference turns it off, Shift is held, or no selected path is
/// there.
fn auto_add_delete(cx: &ToolContext, p: Point, m: Mods, tol: f64) -> Option<Action> {
if !cx.auto_add_delete || m.shift {
return None;
}
let anchor = crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).map(crate::draw2::remove_anchor);
anchor.or_else(|| crate::draw2::segment_in(cx, editable_paths(cx), p, tol).map(crate::draw2::insert_anchor))
let anchor = crate::draw2::anchor_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::remove_anchor);
anchor.or_else(|| crate::draw2::segment_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::insert_anchor))
}
/// A click on a selected blend's spine: delete the point under `p` when no key object sits on it
+32 -1
View File
@@ -32,6 +32,8 @@ struct Entry {
#[derive(Default)]
pub struct PlaceTool {
entries: Vec<Entry>,
/// How many files the last load held, before any was placed or discarded.
total: usize,
current: usize,
/// The tool to return to when the last file is placed or discarded.
prev: Option<String>,
@@ -67,6 +69,7 @@ impl PlaceTool {
}
if self.entries.is_empty() {
self.current = 0;
self.total = 0;
return vec![Action::SwitchTool(self.prev.clone().unwrap_or_else(|| "selection".into()))];
}
self.current %= self.entries.len();
@@ -153,11 +156,13 @@ impl Tool for PlaceTool {
Cursor::Crosshair
}
/// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data).
/// `{count, total, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data);
/// `total` is how many files the load held.
fn options(&self) -> Value {
let e = self.entry();
json!({
"count": self.entries.len(),
"total": self.total,
"current": self.current,
"sourceIndex": e.map(|e| e.source_index),
"name": e.map(|e| &e.name),
@@ -187,6 +192,7 @@ impl Tool for PlaceTool {
})
})
.collect();
self.total = entries.len();
self.entries = entries;
self.current = 0;
self.drag = None;
@@ -233,6 +239,7 @@ impl Tool for PlaceTool {
/// Switching tools discards what the cursor holds.
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.entries.clear();
self.total = 0;
self.drag = None;
vec![]
}
@@ -399,6 +406,30 @@ mod tests {
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]);
}
#[test]
fn the_total_is_the_size_of_the_load_until_the_cursor_empties() {
let (d, _) = doc_with_rect();
let (s, p) = (Default::default(), paint());
let c = cx(&d, &s, &p);
let counts = |t: &PlaceTool| (t.options()["count"].clone(), t.options()["total"].clone());
let mut t = loaded(3);
assert_eq!(counts(&t), (json!(3), json!(3)));
t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0));
t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0));
assert_eq!(counts(&t), (json!(2), json!(3)), "a placed file leaves the total");
t.key(&c, ToolKey::Escape, Mods::default());
assert_eq!(counts(&t), (json!(1), json!(3)), "a discarded file leaves the total");
// A new load replaces the total, and an empty cursor has none.
let mut t = loaded(3);
t.set_option("queue", &json!({"entries": [{"params": {"path": "g.png"}, "name": "g.png", "width": 4.0, "height": 2.0}]}));
assert_eq!(counts(&t), (json!(1), json!(1)));
t.key(&c, ToolKey::Escape, Mods::default());
assert_eq!(counts(&t), (json!(0), json!(0)));
let mut t = loaded(2);
t.deactivate(&c);
assert_eq!(counts(&t), (json!(0), json!(0)));
}
#[test]
fn source_indices_survive_removal_in_cursor_requests() {
let (d, _) = doc_with_rect();
+1 -1
View File
@@ -88,7 +88,7 @@ use layers::parallel_map_at_most;
#[cfg(test)]
pub(crate) use layers::shift_probe;
pub use params::{Method, Mode, PRESET_NAMES, Palette, TraceParams, enhanced_preset, preset, presets};
pub use pipeline::{TraceResult, TracedPath, trace, trace_watched, trace_within};
pub use pipeline::{TraceResult, TraceSteps, TracedPath, trace, trace_watched, trace_within};
#[cfg(test)]
use pipeline::{clear_background, label_extents};
#[cfg(test)]
+259 -75
View File
@@ -1,3 +1,4 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use super::layers::{Layers, parallel_map_at_most};
@@ -177,21 +178,255 @@ pub fn trace_watched(
max_anchors: usize,
steps: &(dyn Fn(u64, u64) -> bool + Sync),
) -> Result<TraceResult, TraceError> {
let (w, h) = (img.width as usize, img.height as usize);
if w == 0 || h == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) {
if !traceable(img) {
return Ok(TraceResult::default());
}
let mut out = trace_paths(img, params, max_anchors, steps)?;
let out = trace_paths(img, params, max_anchors, steps)?;
Ok(grouped(out, img, params))
}
/// Whether `img` has pixels, as many as its size says.
fn traceable(img: &Raster) -> bool {
let (w, h) = (img.width as usize, img.height as usize);
w > 0 && h > 0 && w.checked_mul(h).and_then(|n| n.checked_mul(4)) == Some(img.rgba.len())
}
/// `out` with Auto Grouping's parents (see [`TraceResult::parents`]) when `params` asks for them.
fn grouped(mut out: TraceResult, img: &Raster, params: &TraceParams) -> TraceResult {
if params.auto_grouping {
// Abutting areas cannot overlap; stacked layers, Logo's shapes and stroked lines can.
let stacked = params.method == Method::Overlapping || params.mode == Mode::Logo || params.strokes;
out.parents = group::parents(&out.paths, img.width as usize, img.height as usize, stacked);
}
Ok(out)
out
}
fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<TraceResult, TraceError> {
let (w, h) = (img.width as usize, img.height as usize);
/// How far a trace has got: see [`trace_watched`].
type Steps<'s> = &'s (dyn Fn(u64, u64) -> bool + Sync);
fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: Steps) -> Result<TraceResult, TraceError> {
let p = match prepare(Source::Borrowed(img), params, max_anchors, steps)? {
Begun::Done(out) => return Ok(out),
Begun::Layers(p) => p,
};
if p.stacks() {
let paths = p.job(0).stacked(&p.layers, p.largest(), steps)?;
return Ok((*p).finish_stacked(paths));
}
let traced = {
let job = p.job(0);
// A layer takes about ten bytes a pixel of its box while it is traced (its mask, the labels
// of its components, the stack that fills them, its edges): as many layers at a time as fit
// in half a gigabyte, so that a large image is not traced at the cost of gigabytes.
let at_a_time = ((512 << 20) / (p.largest() * 10)).max(1);
let total = p.layers.len() as u64;
if !steps(0, total) {
return Err(TraceError::Cancelled);
}
// Once stopped, the layers not started yet are skipped.
let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false));
let traced = parallel_map_at_most(at_a_time, &p.layers, |&(r, ci)| {
if stopped.load(Ordering::Relaxed) {
return None;
}
let paths = job.layer(r, ci);
if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) {
stopped.store(true, Ordering::Relaxed);
}
paths
});
if stopped.load(Ordering::Relaxed) {
return Err(TraceError::Cancelled);
}
traced
};
(*p).finish(traced)
}
/// The image a trace works from: borrowed for the length of one call, or shared, for a trace
/// made a part at a time ([`TraceSteps`]).
enum Source<'a> {
Borrowed(&'a Raster),
Shared(Arc<Raster>),
}
impl std::ops::Deref for Source<'_> {
type Target = Raster;
fn deref(&self) -> &Raster {
match self {
Source::Borrowed(img) => img,
Source::Shared(img) => img,
}
}
}
/// A trace with its color layers found and ordered, none of them traced yet.
struct Prepared<'a> {
src: Source<'a>,
/// A copy with a JPEG's block edges (see `deblock`) or a photo's noise (see `smooth`) smoothed
/// away, traced in its place.
smoothed: Option<Raster>,
params: TraceParams,
q: Quantized,
/// Ignore Color, background only: `q.labels` with the background [`TRANSPARENT`].
cleared: Option<Vec<u16>>,
rank: Vec<usize>,
left_out: Vec<bool>,
boxes: Vec<Option<PixelBox>>,
gradients: Vec<Option<TracedGradient>>,
bw_tones: [f64; 2],
/// The layers to trace, bottom first: `(rank, palette entry)`.
layers: Vec<(usize, usize)>,
keep_unmatched: Vec<String>,
keep_ignored: bool,
max_anchors: usize,
}
/// What preparing a trace gives: the whole result (Logo mode), or its layers to trace.
enum Begun<'a> {
Done(TraceResult),
Layers(Box<Prepared<'a>>),
}
impl Prepared<'_> {
/// What tracing one of the layers needs, with `anchors` anchor points made so far.
fn job(&self, anchors: usize) -> Layers<'_> {
Layers {
q: &self.q,
traced: self.cleared.as_deref().unwrap_or(&self.q.labels),
rank: &self.rank,
params: &self.params,
img: self.smoothed.as_ref().unwrap_or(&*self.src),
left_out: self.left_out.clone(),
boxes: self.boxes.clone(),
gradients: &self.gradients,
bw_tones: self.bw_tones,
style: self.params.outline_style(),
w: self.src.width as usize,
h: self.src.height as usize,
anchors: AtomicUsize::new(anchors),
max_anchors: self.max_anchors,
}
}
/// Whether the layers are traced together: Overlapping with Fills fills each shape whole and
/// traces what it encloses again above it (see `Layers::stacked`). Lines (Create Strokes) and
/// outlines (no Fills) are traced a layer at a time.
fn stacks(&self) -> bool {
self.params.method == Method::Overlapping && self.params.fills && !self.params.strokes
}
/// The pixel count of the largest layer's box (at least 1).
fn largest(&self) -> usize {
self.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1)
}
/// The result of `paths`, the layers traced together ([`Prepared::stacks`]).
fn finish_stacked(self, paths: Vec<TracedPath>) -> TraceResult {
let mut out = TraceResult { paths, keep_unmatched: self.keep_unmatched, keep_ignored: self.keep_ignored, ..TraceResult::default() };
// The colors used, bottom layer first.
for &(_, ci) in &self.layers {
if let Some(&color) = self.q.palette.get(ci)
&& !out.palette.contains(&color)
&& out.paths.iter().any(|p| p.color == color)
{
out.palette.push(color);
}
}
out
}
/// The result of `traced`, the paths of each of [`Prepared::layers`] in order (`None` for a
/// layer that passed the anchor maximum).
fn finish(self, traced: Vec<Option<Vec<TracedPath>>>) -> Result<TraceResult, TraceError> {
let mut out = TraceResult { keep_unmatched: self.keep_unmatched, keep_ignored: self.keep_ignored, ..TraceResult::default() };
for (paths, &(_, ci)) in traced.into_iter().zip(&self.layers) {
let paths = paths.ok_or(TraceError::TooComplex { max: self.max_anchors })?;
// A layer with no paths adds no color to the palette.
if paths.is_empty() {
continue;
}
out.paths.extend(paths);
let color = self.q.palette[ci];
if !out.palette.contains(&color) {
out.palette.push(color);
}
}
Ok(out)
}
}
/// A trace made a part at a time, for a caller with no thread to trace on that must let other
/// work run between the parts (the web build). The first [`TraceSteps::step`] finds the color
/// layers and each later one traces one layer, bottom first, one at a time (Overlapping with
/// Fills, without Create Strokes, traces all of them in the second step, as its layers are traced
/// together); the result is the one [`trace_within`] gives.
pub struct TraceSteps {
img: Arc<Raster>,
params: TraceParams,
max_anchors: usize,
state: StepState,
}
enum StepState {
Start,
/// The layers found, the paths of those traced so far, and their anchor points.
Layers(Box<Prepared<'static>>, Vec<Option<Vec<TracedPath>>>, usize),
Finished,
}
impl TraceSteps {
/// A trace of `img` with `params` that gives up with [`TraceError::TooComplex`] once the paths
/// have more than `max_anchors` anchor points; nothing is done until [`TraceSteps::step`].
pub fn new(img: Arc<Raster>, params: TraceParams, max_anchors: usize) -> Self {
Self { img, params, max_anchors, state: StepState::Start }
}
/// Does the next part → the result once the last part is done, `None` before it. After the
/// result or an error, each call gives `None`.
pub fn step(&mut self) -> Result<Option<TraceResult>, TraceError> {
let (prepared, mut traced, anchors) = match std::mem::replace(&mut self.state, StepState::Finished) {
StepState::Finished => return Ok(None),
StepState::Start => {
if !traceable(&self.img) {
return Ok(Some(TraceResult::default()));
}
match prepare(Source::Shared(Arc::clone(&self.img)), &self.params, self.max_anchors, &|_, _| true)? {
Begun::Done(out) => return Ok(Some(grouped(out, &self.img, &self.params))),
Begun::Layers(p) if p.layers.is_empty() => return (*p).finish(vec![]).map(|out| Some(grouped(out, &self.img, &self.params))),
Begun::Layers(p) => {
let traced = Vec::with_capacity(p.layers.len());
self.state = StepState::Layers(p, traced, 0);
return Ok(None);
}
}
}
StepState::Layers(p, traced, anchors) => (p, traced, anchors),
};
if prepared.stacks() {
let paths = prepared.job(0).stacked(&prepared.layers, prepared.largest(), &|_, _| true)?;
return Ok(Some(grouped((*prepared).finish_stacked(paths), &self.img, &self.params)));
}
// With every layer traced already the result is finished below.
let mut anchors = anchors;
if let Some(&(r, ci)) = prepared.layers.get(traced.len()) {
let job = prepared.job(anchors);
let paths = job.layer(r, ci);
anchors = job.anchors.load(Ordering::Relaxed);
traced.push(Some(paths.ok_or(TraceError::TooComplex { max: self.max_anchors })?));
}
if traced.len() < prepared.layers.len() {
self.state = StepState::Layers(prepared, traced, anchors);
return Ok(None);
}
(*prepared).finish(traced).map(|out| Some(grouped(out, &self.img, &self.params)))
}
}
/// Finds the color layers of `src` traced with `params` and the order they stack in, telling
/// `steps(0, 0)` after each stage; Logo mode traces the whole image at once.
fn prepare<'a>(src: Source<'a>, params: &TraceParams, max_anchors: usize, steps: Steps) -> Result<Begun<'a>, TraceError> {
let (w, h) = (src.width as usize, src.height as usize);
// The colors Keep Colors traces (checked in every mode).
let listed = params
.keep_colors
@@ -202,7 +437,7 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
let go_on = || if steps(0, 0) { Ok(()) } else { Err(TraceError::Cancelled) };
if params.mode == Mode::Logo {
go_on()?;
return logo::trace_logo(img, params, max_anchors);
return logo::trace_logo(&src, params, max_anchors).map(Begun::Done);
}
// The colour Ignore Color leaves out, if not white.
let ignore = match &params.ignore_color {
@@ -218,12 +453,12 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
// A photo is traced from a copy with its noise smoothed away (see `smooth`); the deblocked copy is
// dropped once it is smoothed.
let photo = |img: &Raster| params.mode != Mode::BlackAndWhite && quantize::continuous_tone(img);
let prepared = match deblock::deblocked(img, strength) {
let smoothed = match deblock::deblocked(&src, strength) {
Some(deblocked) if photo(&deblocked) => Some(smooth::smoothed(&deblocked)),
Some(deblocked) => Some(deblocked),
None => photo(img).then(|| smooth::smoothed(img)),
None => photo(&src).then(|| smooth::smoothed(&src)),
};
let img = prepared.as_ref().unwrap_or(img);
let img = smoothed.as_ref().unwrap_or(&*src);
go_on()?;
// Gradients are found first and kept out of the palette: no colour is spent on bands of them.
// Grayscale finds them in the image's grays (as its flat colours are), so their stops are gray.
@@ -337,75 +572,24 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
.collect();
// Every layer is left out although a listed color matches one: Ignore Color left those out.
let keep_ignored = !listed.is_empty() && layers.is_empty() && order.iter().any(|&ci| is_kept(q.palette[ci], &listed));
let job = Layers {
q: &q,
traced: cleared.as_deref().unwrap_or(&q.labels),
rank: &rank,
let tones = bw_tones(img, &q);
let params = params.clone();
Ok(Begun::Layers(Box::new(Prepared {
src,
smoothed,
params,
img,
q,
cleared,
rank,
left_out,
boxes,
gradients: &gradients,
bw_tones: bw_tones(img, &q),
style: params.outline_style(),
w,
h,
anchors: AtomicUsize::new(0),
gradients,
bw_tones: tones,
layers,
keep_unmatched,
keep_ignored,
max_anchors,
};
let mut out = TraceResult { keep_unmatched, keep_ignored, ..TraceResult::default() };
// A layer takes about ten bytes a pixel of its box while it is traced (its mask, the labels
// of its components, the stack that fills them, its edges): as many layers at a time as fit
// in half a gigabyte, so that a large image is not traced at the cost of gigabytes.
let largest = job.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1);
let at_a_time = ((512 << 20) / (largest * 10)).max(1);
// Overlapping with Fills: each shape is filled whole, and what it encloses is traced again above it (see
// `Layers::stacked`). Lines (Create Strokes) and outlines (no Fills) are stacked as they always were.
if params.method == Method::Overlapping && params.fills && !params.strokes {
out.paths = job.stacked(&layers, largest, steps)?;
// The colors used, bottom layer first.
for &(_, ci) in &layers {
if let Some(&color) = q.palette.get(ci)
&& !out.palette.contains(&color)
&& out.paths.iter().any(|p| p.color == color)
{
out.palette.push(color);
}
}
return Ok(out);
}
let total = layers.len() as u64;
if !steps(0, total) {
return Err(TraceError::Cancelled);
}
// Once stopped, the layers not started yet are skipped.
let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false));
let traced = parallel_map_at_most(at_a_time, &layers, |&(r, ci)| {
if stopped.load(Ordering::Relaxed) {
return None;
}
let paths = job.layer(r, ci);
if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) {
stopped.store(true, Ordering::Relaxed);
}
paths
});
if stopped.load(Ordering::Relaxed) {
return Err(TraceError::Cancelled);
}
for (paths, &(_, ci)) in traced.into_iter().zip(&layers) {
let paths = paths.ok_or(TraceError::TooComplex { max: max_anchors })?;
// A layer with no paths adds no color to the palette.
if paths.is_empty() {
continue;
}
out.paths.extend(paths);
let color = q.palette[ci];
if !out.palette.contains(&color) {
out.palette.push(color);
}
}
Ok(out)
})))
}
/// The luminance of white and of black in a Black and White quantisation: what its lightest
+46
View File
@@ -1086,6 +1086,52 @@ fn a_watched_trace_counts_its_layers_and_stops_when_told() {
assert!(matches!(trace_watched(&img, &p, usize::MAX, &|done, _| done == 0), Err(TraceError::Cancelled)));
}
/// A trace made a part at a time finds its layers in the first part and traces one layer a part
/// after it (all of them in the second part for Overlapping with Fills, which stacks them), and
/// gives what one call gives, Auto Grouping, Logo mode and the anchor budget included.
#[test]
fn a_trace_made_a_part_at_a_time_matches_one_made_at_once() {
fn parts(img: &Raster, p: &TraceParams, max: usize) -> (usize, Result<TraceResult, TraceError>) {
let mut s = TraceSteps::new(std::sync::Arc::new(img.clone()), p.clone(), max);
let mut n = 0;
loop {
n += 1;
assert!(n < 1000, "the parts never end");
match s.step() {
Ok(None) => {}
Ok(Some(r)) => return (n, Ok(r)),
Err(e) => return (n, Err(e)),
}
}
}
let img = stripes(120, 8);
let overlapping =
TraceParams { mode: Mode::Color, colors: 16, noise: 1, method: Method::Overlapping, auto_grouping: true, ..TraceParams::default() };
// Overlapping with Fills traces its layers together: one part finds them, the next traces them.
for (p, layered) in [
(TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() }, true),
(TraceParams { strokes: true, ..overlapping.clone() }, true),
(overlapping, false),
] {
let at_once = trace_within(&img, &p, usize::MAX).unwrap();
let (n, made) = parts(&img, &p, usize::MAX);
assert_eq!(made.unwrap(), at_once, "{p:?}");
assert!(at_once.palette.len() > 1, "{} colors", at_once.palette.len());
assert!(if layered { n > 2 } else { n == 2 }, "{n} parts for {} colors, {p:?}", at_once.palette.len());
}
let logo = TraceParams { mode: Mode::Logo, ..TraceParams::default() };
let round = disc(64, 32.0, 32.0, 20.0);
let (n, made) = parts(&round, &logo, usize::MAX);
assert_eq!((n, made.unwrap()), (1, trace_within(&round, &logo, usize::MAX).unwrap()), "Logo mode is one part");
let p = TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() };
let anchors = trace(&img, &p).anchor_count();
assert!(matches!(parts(&img, &p, anchors / 2).1, Err(TraceError::TooComplex { max }) if max == anchors / 2));
assert_eq!(parts(&img, &p, anchors).1.unwrap(), trace(&img, &p));
let mut done = TraceSteps::new(std::sync::Arc::new(Raster::from_fn(0, 0, |_, _| WHITE)), p, usize::MAX);
assert_eq!(done.step().unwrap(), Some(TraceResult::default()), "an empty image");
assert_eq!(done.step().unwrap(), None, "nothing after the result");
}
/// Layers traced in parallel come out in the same order every time: bottom (largest) first.
#[test]
fn parallel_layers_keep_their_order() {
+9 -1
View File
@@ -149,7 +149,15 @@ pub(crate) fn open_with(
previewing: bool,
) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, spec.command, fields, build);
// Each add-on dialog previews on the canvas, so the scrim leaves the canvas undimmed (#10706).
let canvas = crate::dialogs::host::preview_canvas(app);
let dialog = HostedParamDialog::new(&ctx, spec.command, fields, move |fields| {
let dialog = build(fields);
match canvas {
Some(canvas) => dialog.canvas(canvas),
None => dialog,
}
});
let dialog = if previewing { dialog } else { dialog.preview_off() };
let host = app.dialogs().ok_or("no window")?;
close_open(app);
@@ -134,7 +134,7 @@ mod tests {
let undo = panel.app().session.active().unwrap().history.undo.len();
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(typed);
panel.type_text(&crate::tests::regional_text(typed));
panel.frame();
let proposed = panel.app().session.tool_options_of(tool);
assert_ne!(proposed[key], before[key], "{label} changes while typing");
@@ -16,7 +16,7 @@ use vectorcraft_tools::addons::tangent_circle;
use crate::VectorcraftApp;
use crate::canvas::rulers::general_lengths;
use crate::dialogs::host::{HeldOptions, open_held_with};
use crate::dialogs::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas};
use crate::dialogs::preview::LivePreview;
/// The dialog's kind.
@@ -64,9 +64,10 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) {
let lengths = general_lengths(app);
let fields = DialogFields::from_pairs([("radius", FieldValue::Number(radius))]);
// The field has no bounds: a radius typed outside the tool's range is kept as typed and shows [`RADIUS_RANGE`].
let canvas = preview_canvas(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
let rows = vec![Param::number("radius", tl!("Radius:"), radius, 1.0, 2).length(lengths)];
ParamDialog::new(KIND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true)
ParamDialog::new(KIND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews_on(true, canvas)
});
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(mut open) = app.addon_dialogs.tangent_radius.take() {
+1 -1
View File
@@ -663,7 +663,7 @@ mod cancel_tests {
panel.frame();
panel.click_role("TL", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("4.125");
panel.type_text(&crate::tests::regional_text("4.125"));
panel.frame();
let proposed = panel.app().session.tool_options();
assert_ne!(proposed["cornerRadii"], before["cornerRadii"]);
+3
View File
@@ -251,6 +251,7 @@ impl VectorcraftApp {
plugin_runs: Default::default(),
placing: Default::default(),
trace_runs: Default::default(),
concept_runs: Default::default(),
retype_runs: Default::default(),
recovery: Default::default(),
closing: None,
@@ -419,6 +420,7 @@ impl VectorcraftApp {
opening::poll(self);
plugin_runs::poll(self);
trace_runs::poll(self);
crate::panels::concept_vector::poll(self);
placing::poll(self);
retype_runs::poll(self);
// The handlers' time counts toward the frame-time sample, as the delivery after the UI
@@ -662,6 +664,7 @@ impl VectorcraftApp {
|| !self.placing.pending.is_empty()
|| !self.trace_runs.running.is_empty()
|| self.retype_runs.running.is_some()
|| self.concept_runs.busy()
{
// Keep the status bar's progress moving and pick the result up when it arrives.
ctx.request_repaint_after(std::time::Duration::from_millis(100));
+2 -1
View File
@@ -11,7 +11,8 @@ pub(crate) fn navigation(p: &Prefs) -> NavigationOptions {
let mut options = NavigationOptions::default();
options.wheel = if p.zoom_with_mouse_wheel { WheelScheme::Zoom } else { WheelScheme::Scroll };
options.animated_zoom = crate::canvas::animated_zoom(p);
options.scrubby_zoom = crate::canvas::animated_zoom(p);
options.eased_wheel_zoom = p.zoom_with_mouse_wheel && options.animated_zoom;
options.scrubby_zoom = options.animated_zoom;
options.trackpad_rotate = p.trackpad_rotate_view;
options.touch_gestures = p.touch_gestures;
options.overscroll = true;
+2 -2
View File
@@ -25,8 +25,8 @@ const TIP: PartKey = PartKey::new("tip");
const CHIP: f32 = 5.0;
const CHIP_RIM: f32 = 6.0;
const CHIP_RING: f32 = 8.0;
/// Where the Selection tool's rule badge sits from the pointer, in points.
const BADGE_OFFSET: Vec2 = Vec2::new(14.0, 14.0);
/// Where the Selection tool's rule badge and the loaded place cursor's file sit from the pointer, in points.
pub(super) const BADGE_OFFSET: Vec2 = Vec2::new(14.0, 14.0);
/// Shows `overlays` (the session's list, read after the tool host ran) over `extra` (the thread and gap overlays),
/// on the canvas of `space`. The extras lie under the tool's own marks.
+1 -1
View File
@@ -257,6 +257,6 @@ fn ruler_labels_carry_the_sign_and_the_steps_decimals() {
(1.0, 0.0625, "1"),
(1.1875, 0.0625, "1.1875"),
] {
assert_eq!(x.tick_label(&units, value, step), want, "the tick at {value} of a {step} step");
assert_eq!(x.tick_label(&units, value, step), crate::tests::regional_text(want), "the tick at {value} of a {step} step");
}
}
+4 -1
View File
@@ -280,6 +280,7 @@ fn offer(app: &VectorcraftApp, images_memo: &mut Memo, smooth_memo: &mut Memo) -
items.push((tl!("Image Trace"), "image", TASK_BAR_IMAGE_TRACE, none()));
items.push((tl!("Crop Image"), "dc-pf-crop", "ui.cropImage", none()));
items.push((tl!("Remove Background"), "eraser", crate::addons::image::REMOVE_BACKGROUND, none()));
items.push((tl!("Concept to Vector"), "sparkles", crate::panels::concept_vector::OPEN, none()));
}
// Direct-selected anchors take the place of a path's Offset Path and Simplify. For them the bar
// offers Remove, Connect, Cut and Convert to corner or smooth, as the reference app does
@@ -309,6 +310,7 @@ fn offer(app: &VectorcraftApp, images_memo: &mut Memo, smooth_memo: &mut Memo) -
}
} else if is_trace {
items.push((tl!("Expand"), "maximize-2", "imageTrace.expand", none()));
items.push((tl!("Concept to Vector"), "sparkles", crate::panels::concept_vector::OPEN, none()));
} else if is_clip_group {
items.push((tl!("Edit Clipping Path"), "dc-direct", "object.clippingMask.editMask", none()));
items.push((tl!("Release Clipping Mask"), "ungroup", "object.clippingMask.release", none()));
@@ -661,10 +663,11 @@ impl Chip {
/// (`window.taskBar.actions {action, visible?}`): each action's id, the command its button runs and
/// the `tool` that command names, if any. An action that is off stays out of the bar, and More
/// Options does not list it either; turning one off changes only the bar. Every action starts on.
pub(crate) const TASK_BAR_ACTIONS: [(&str, &str, Option<&str>); 37] = [
pub(crate) const TASK_BAR_ACTIONS: [(&str, &str, Option<&str>); 38] = [
("imageTrace", TASK_BAR_IMAGE_TRACE, None),
("cropImage", "ui.cropImage", None),
("removeBackground", crate::addons::image::REMOVE_BACKGROUND, None),
("conceptToVector", crate::panels::concept_vector::OPEN, None),
("removeAnchorPoints", "path.removeAnchors", None),
("join", "path.join", None),
("cutPath", "path.cutAtAnchors", None),
+21
View File
@@ -5435,6 +5435,27 @@ fn the_task_bar_removes_a_selected_images_background() {
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0[3]), (0, 255), "the white background is cleared, the red dot kept");
}
/// For one selected image the Contextual Task Bar offers Concept to Vector, which opens its panel;
/// a rectangle gets no such item.
#[test]
fn the_task_bar_opens_concept_to_vector_for_a_selected_image() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let raw = (0..20 * 20).flat_map(|i| if i % 20 < 10 { [0, 0, 0, 255] } else { [255; 4] }).collect();
let img = craft_image_codecs::Image::from_raw(20, 20, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
let data = vectorcraft_format::base64_encode(&png);
app.run("file.place", json!({"name": "half.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap();
app.select_tool("selection");
let actions = task_bar_actions(&mut app);
assert!(actions.contains(&"Concept to Vector"), "{actions:?}");
click(&mut app, "Concept to Vector");
assert!(crate::panel_docking::showing(&app.ui, crate::panels::concept_vector::ID), "{}", app.ui.status);
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
let actions = task_bar_actions(&mut app);
assert!(!actions.is_empty() && !actions.contains(&"Concept to Vector"), "{actions:?}");
}
/// A selected group's Contextual Task Bar offers Ungroup and Isolate. While an opacity mask is
/// edited, when Enter Isolation Mode is off, a group in the mask art gets Ungroup without Isolate.
#[test]
+14 -1
View File
@@ -866,7 +866,8 @@ fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> Too
response
}
/// The session's overlays, then the text threads and Live Paint gaps under them, shown over the picture.
/// The session's overlays, then the text threads and Live Paint gaps under them, shown over the picture, and the
/// loaded place cursor's file over them.
fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_info: ViewInfo) {
let Some(space) = pass.space else { return };
let revolve = crate::dialogs::three_d::gizmo_shown(app);
@@ -892,6 +893,18 @@ fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_in
}
}
super::overlays::show(app, ui, &space, &list, &extra);
// The loaded place cursor shows its current file and the files left beside the pointer, while the canvas has the
// pointer and no view tool is held. A press that began on the canvas keeps `hover_doc` while it is dragged off it,
// so the pointer must also be over the canvas.
if app.session.tool_id() == "place"
&& app.ui.screen_mode < 3
&& app.hover_doc.is_some()
&& !view_tool_held(app)
&& let Some(at) = ui.input(|i| i.pointer.hover_pos())
&& space.view.rect.contains(at)
{
crate::place::cursor_overlay(app, ui, at, space.view.rect, super::overlays::BADGE_OFFSET);
}
}
/// Whether the canvas has a tool gesture in progress. Only the current window's body is live: panes and the other
+1 -1
View File
@@ -289,7 +289,7 @@ fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected:
let target = crate::panels::transparency_target(app);
group(ui, rank::OPACITY, |ui| {
Field::new(label).side(SideLabel::new().link().scrub(true)).show(ui, |ui, _| {
let number = NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0)))
let number = NumberField::new(label, Bind::given(Some(crate::panels::shown_percent(opacity))))
.range(0.0..=100.0)
.unit("%")
.scrub_by_label()
+24
View File
@@ -3194,6 +3194,30 @@ fn the_control_bar_opacity_drops_an_unfinished_value_when_the_selection_changes(
assert_eq!((opacity(&bar, &a), opacity(&bar, &b)), (0.5, 0.01), "the typing gives the other object 1%, not 20+1");
}
/// The arrow keys step the Control bar's Opacity by one percent at every press: 51% reads back from its f32 as
/// 50.999999%, and the next Up still goes to 52%, as 99% going Down goes to 98%.
#[test]
fn the_control_bar_opacity_steps_at_every_arrow_press() {
use egui::{Key, Modifiers};
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 20, "y": 50, "width": 40, "height": 40})).unwrap()["id"].clone();
let node = vectorcraft_doc::NodeId(id.as_u64().unwrap());
let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar);
bar.room(egui::vec2(2400.0, 300.0)).frame();
for (start, key, steps) in [(50, Key::ArrowUp, [51.0, 52.0, 53.0]), (100, Key::ArrowDown, [99.0, 98.0, 97.0])] {
bar.app().run("transparency.set", json!({"ids": [id], "opacity": start})).unwrap();
bar.frame();
bar.click_role("Opacity:", Role::SPIN_BUTTON);
for percent in steps {
bar.key(key, Modifiers::NONE);
let opacity = bar.app().session.active().unwrap().doc.node(node).unwrap().opacity;
assert_eq!(opacity, (percent / 100.0) as f32, "{key:?} from {start}% reaches {percent}%");
}
}
}
/// File › Revert drops an unfinished Opacity expression in the Control bar, though the reverted document has the same
/// object, with the same opacity, selected again before the next frame.
#[test]
@@ -825,7 +825,7 @@ mod tests {
assert_eq!(pending.size_choice, Some(ArtboardSizeChoice::Orientation(true)));
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(typed);
panel.type_text(&crate::tests::regional_text(typed));
assert_eq!(actual_value(&panel), pending, "typing must not discard the pending orientation or reference-point policy");
panel.key(Key::Escape, Modifiers::NONE);
assert!(!is_open(&panel.app()), "Escape discards the modal for {label}");
@@ -875,7 +875,7 @@ mod tests {
panel.frame();
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(typed);
panel.type_text(&crate::tests::regional_text(typed));
if blur {
panel.key(Key::Tab, Modifiers::NONE);
}
+6 -4
View File
@@ -19,7 +19,7 @@ use craft::ui::runtime::env::LengthUnits;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, Selection};
use super::host::{HeldOptions, open_held_with};
use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas};
use super::preview::LivePreview; // PLAN: assumed path of wg.A20's `LivePreview`
use crate::VectorcraftApp;
use crate::canvas::general_lengths;
@@ -119,7 +119,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let document = app.session.active().map(|st| (st.uid, st.reverts));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(on_blend, lengths).values(Bind::bound(fields)));
let canvas = preview_canvas(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(on_blend, lengths, canvas).values(Bind::bound(fields)));
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(move |app| {
if app.object_dialogs.blend.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled))
&& let Some(open) = app.object_dialogs.blend.take()
@@ -138,7 +139,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
}
/// The dialog over its rows; Steps shows (disabled for Smooth Color) with the two modes that have a count of steps.
fn dialog<'a>(on_blend: bool, lengths: LengthUnits) -> ParamDialog<'a> {
/// It previews a blend on `canvas`.
fn dialog<'a>(on_blend: bool, lengths: LengthUnits, canvas: Option<egui::Id>) -> ParamDialog<'a> {
let spacing = SPACING.iter().map(|(value, label)| ((*value).to_owned(), tl!(label).into())).collect();
let params = vec![
Param::new("spacing", tl!("Spacing:"), ParamKind::choice(spacing, None)),
@@ -148,7 +150,7 @@ fn dialog<'a>(on_blend: bool, lengths: LengthUnits) -> ParamDialog<'a> {
Param::number("distance", tl!("Distance"), 10.0, 1.0, 3).length(lengths).bounds(Some(0.001), None).visible_when("spacing", "distance"),
Param::custom("orientation", tl!("Orientation:"), orientation_row),
];
ParamDialog::new(KIND, tl!("Blend Options"), params).previews(on_blend)
ParamDialog::new(KIND, tl!("Blend Options"), params).previews_on(on_blend, canvas)
}
/// The orientation the fields hold: `page` unless it is `path`.
@@ -47,7 +47,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
fields.set("name", g.name.as_str());
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
let rows = vec![Param::new("name", field_label(tl!("Name:")), ParamKind::text(""))];
let dialog = hosted(&ctx, KIND, tl!("Color Group Options"), fields, rows, false);
let dialog = hosted(&ctx, KIND, tl!("Color Group Options"), fields, rows, false, None);
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
// A different document, a revert, or a different group closes the draft without renaming.
if !same_group(app, &identity) {
@@ -54,7 +54,7 @@ pub fn open(app: &mut VectorcraftApp) {
})
.response
});
let dialog = hosted(&ctx, KIND, tl!("Color Guide Options"), fields, vec![steps, variations], false);
let dialog = hosted(&ctx, KIND, tl!("Color Guide Options"), fields, vec![steps, variations], false, None);
let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
app.ui.color_guide = options(app.ui.color_guide, &answer.fields);
Ok(())
+3 -2
View File
@@ -10,7 +10,7 @@ use craft::ui::runtime::env::{Label, LengthUnits, UnitKind};
use serde_json::{Map, Value};
use super::form;
use super::host::{HeldOptions, open_held_with};
use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas};
use super::preview::LivePreview;
use crate::VectorcraftApp;
@@ -119,11 +119,12 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par
let setting = Setting::of(app);
let fields = form::fields_of(&command_params(command, &params, setting), &params);
let token = Arc::new(());
let canvas = preview_canvas(app);
let dialog = {
let (key, heading, opening) = (command.to_string(), heading_label(label), params.clone());
HostedParamDialog::command(&ctx, command, fields, move |fields| {
ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting))
.previews(previews)
.previews_on(previews, canvas)
.values(craft::ui::contract::Bind::bound(fields))
})
// The Preview box starts off, as production's dialogs did (#5360).
+5 -2
View File
@@ -36,7 +36,7 @@ use serde_json::{Map, Value, json};
use vectorcraft_doc::{EnvelopeKind, NodeKind};
use super::form::{fields_of, json_of};
use super::host::{HeldOptions, open_held_with};
use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas};
use super::preview::LivePreview;
use super::warp_effect::{percent_param, row_label, static_style, style_entries, style_param};
use crate::VectorcraftApp;
@@ -195,9 +195,12 @@ fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map<String,
}
}
let fields = fields_of(&params(kind, &DialogFields::new()), &values);
let canvas = preview_canvas(app);
let dialog = HostedParamDialog::command(&ctx, kind, fields, move |fields| {
let reset = fields.bool("reset").unwrap_or(false);
ParamDialog::command(kind, heading(kind, reset), params(kind, fields)).previews(kind != OPTIONS || envelope).values(Bind::bound(fields))
ParamDialog::command(kind, heading(kind, reset), params(kind, fields))
.previews_on(kind != OPTIONS || envelope, canvas)
.values(Bind::bound(fields))
});
let generation = OPENED.fetch_add(1, Ordering::Relaxed);
let cancel = Box::new(move |app: &mut VectorcraftApp| {
+6 -2
View File
@@ -26,7 +26,7 @@ use vectorcraft_geom::Point;
use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params};
use super::form;
use super::host::{HeldOptions, open_held_with};
use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas};
use super::preview::LivePreview;
use super::tool_options;
use crate::VectorcraftApp;
@@ -129,8 +129,12 @@ pub fn open(app: &mut VectorcraftApp, at: Option<Point>) -> Value {
}
});
let held = HeldOptions { parent: None, cancel: Some(cancel) };
let canvas = preview_canvas(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)).values(Bind::bound(fields)).previews(previews).reset_to(defaults.clone())
ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths))
.values(Bind::bound(fields))
.previews_on(previews, canvas)
.reset_to(defaults.clone())
});
let document = app.session.active().map(|st| (st.uid, st.reverts));
match open_held_with(app, dialog, ok, held) {
+23
View File
@@ -2,6 +2,7 @@
//! module and every held dialog.
use craft::ui::dialog::{DialogId, DialogResult, HoldsOk};
use craft::ui::patterns::form_dialogs::ParamDialog;
use craft::ui::runtime::env::WindowKey;
use craft::ui::shell::WindowDialogs;
use serde_json::Value;
@@ -140,6 +141,28 @@ pub(crate) fn open_held_with<D: HoldsOk>(
Some(id)
}
/// The canvas of the window that shows the active document, for a dialog that previews on it.
pub(crate) fn preview_canvas(app: &VectorcraftApp) -> Option<egui::Id> {
crate::doc_windows::current(app).map(crate::canvas::canvas_id)
}
/// A parameter dialog's Preview box over a document canvas.
pub(crate) trait PreviewsOn {
/// Shows the Preview box when `on`, and then registers `canvas` (from [`preview_canvas`]): the modal layer's
/// scrim leaves that canvas undimmed, so the preview shows its true colors, and the wheel still moves the view.
fn previews_on(self, on: bool, canvas: Option<egui::Id>) -> Self;
}
impl PreviewsOn for ParamDialog<'_> {
fn previews_on(self, on: bool, canvas: Option<egui::Id>) -> Self {
let dialog = self.previews(on);
match canvas.filter(|_| on) {
Some(canvas) => dialog.canvas(canvas),
None => dialog,
}
}
}
/// The dialog on top of the stack.
pub(crate) fn top_dialog(app: &VectorcraftApp) -> Option<DialogId> {
// `open_dialogs` lists in opening order, the top one last.
+6 -4
View File
@@ -24,6 +24,7 @@ use craft::ui::runtime::env::UnitKind;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{JustificationOptions, SingleWordJustify};
use super::host::{PreviewsOn as _, preview_canvas};
use super::preview::LivePreview;
use super::warichu::set_shared;
use crate::VectorcraftApp;
@@ -92,8 +93,8 @@ fn problem(fields: &DialogFields) -> Option<&'static str> {
}
/// The dialog over its values: three titled groups of Minimum, Desired and Maximum, Auto Leading and
/// Single Word Justification. Preview starts off ([`HostedParamDialog::preview_off`]).
fn form(fields: &mut DialogFields) -> ParamDialog<'_> {
/// Single Word Justification. Preview starts off ([`HostedParamDialog::preview_off`]) and shows on `canvas`.
fn form(fields: &mut DialogFields, canvas: Option<egui::Id>) -> ParamDialog<'_> {
let titles = [tl!("Word Spacing"), tl!("Letter Spacing"), tl!("Glyph Scaling")];
let columns = [tl!("Minimum"), tl!("Desired"), tl!("Maximum")];
let mut rows = Vec::new();
@@ -108,7 +109,7 @@ fn form(fields: &mut DialogFields) -> ParamDialog<'_> {
let options = single_word_choices().into_iter().map(|(id, label)| (id.to_owned(), label.into())).collect();
rows.push(Param::new("singleWord", tl!("Single Word Justification:"), ParamKind::choice(options, Some("fullJustify".to_owned()))));
let reason = problem(fields);
let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews(true).values(Bind::bound(fields));
let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews_on(true, canvas).values(Bind::bound(fields));
match reason {
Some(why) => dialog.ok_enabled(false).ok_reason(why.into()),
None => dialog,
@@ -145,7 +146,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
set_shared(&mut fields, "autoLeading", crate::panels::paragraph::shared_justification_f64(app, |j| j.auto_leading));
set_shared(&mut fields, "singleWord", crate::panels::paragraph::shared_single_word_justify(app).map(single_word_name));
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), form).preview_off();
let canvas = preview_canvas(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), move |fields| form(fields, canvas)).preview_off();
let id = super::host::open_held(app, dialog, |app, result| {
let Some(open) = app.justification.take() else { return Ok(()) };
if !open.in_opening_document(app) {
@@ -36,7 +36,7 @@ pub fn open(app: &mut VectorcraftApp, swatches: Vec<String>) -> Result<Value, St
Param::new("toGlobal", tl!("Convert Process to Global").to_owned(), ParamKind::bool(true)).enabled_when("from", "artwork"),
Param::new("includeTints", tl!("Include Swatches for Tints").to_owned(), ParamKind::bool(false)).enabled_when("from", "artwork"),
];
let dialog = hosted(&ctx, KIND, tl!("New Color Group"), fields, rows, false);
let dialog = hosted(&ctx, KIND, tl!("New Color Group"), fields, rows, false, None);
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let Some(source) = app.session.active().filter(|active| active.uid == document) else {
return Err(tl!("Create this color group in the document that opened the dialog.").to_owned());
+1 -1
View File
@@ -49,7 +49,7 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s
other => (vec![name_row()], Some(crate::panels::swatch_paint_params(other))),
};
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
let dialog = hosted(&ctx, KIND, tl!("New Swatch"), fields, rows, false);
let dialog = hosted(&ctx, KIND, tl!("New Swatch"), fields, rows, false, None);
let group = group.unwrap_or_default().to_owned();
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let active =
+5 -3
View File
@@ -26,7 +26,7 @@ use vectorcraft_geom::PathData;
use super::form;
// PLAN: assumed `LivePreview` is exported by `dialogs::form` (wg.A20, widgets-w11).
use super::host::{HeldOptions, open_held, open_held_with};
use super::host::{HeldOptions, PreviewsOn as _, open_held, open_held_with, preview_canvas};
use super::preview::LivePreview;
use crate::VectorcraftApp;
@@ -445,13 +445,14 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem
let lengths = crate::canvas::general_lengths(app);
let opening = op.opening();
let key = op.key();
let canvas = preview_canvas(app);
let dialog = HostedParamDialog::new(&ctx, key, fields, move |f| {
let mut d = ParamDialog::new(key, op.title(), rows(op, &opening, lengths)).values(Bind::bound(f));
if let Some(k) = remember.clone() {
d = d.remember(k);
}
if op.previews() {
d = d.previews(true);
d = d.previews_on(true, canvas);
}
if op == PathOp::Simplify { d.below(counts_row) } else { d }
});
@@ -531,8 +532,9 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) {
let reverts = state.reverts;
let (width, height) = state.doc.bounds_of(&state.selection.objects, false).map_or((0.0, 0.0), |b| (b.width(), b.height()));
let lengths = crate::canvas::general_lengths(app);
let canvas = preview_canvas(app);
let dialog = HostedParamDialog::new(&ctx, SPLIT_COMMAND, split_fields(width, height), move |f| {
ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews(true)
ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews_on(true, canvas)
});
let ok = |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| {
let Some(mut record) = app.object_dialogs.split.take() else { return Err(tl!("The Split Into Grid dialog is closed.").to_owned()) };
+6 -5
View File
@@ -30,7 +30,7 @@ use vectorcraft_color::cms::{self, Intent, ProfileKind, ProofTarget};
use vectorcraft_engine::cmd::colormgmt::proof_file::{self, EXT};
use vectorcraft_render::proof;
use super::host::{HeldOptions, open_held_with};
use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas};
use crate::VectorcraftApp;
use crate::file_asks::{Owner, ask, ask_while};
use crate::menus::Node;
@@ -88,7 +88,8 @@ pub fn open(app: &mut VectorcraftApp) {
("simulatePaper", FieldValue::Bool(s.simulate_paper)),
("simulateBlack", FieldValue::Bool(s.simulate_black)),
]);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, build);
let canvas = preview_canvas(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| build(fields, canvas));
let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() };
match open_held_with(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields), options) {
Some(id) => app.ui.proof_setup = Some(Open { id, opening: Arc::new(()), before, shown: None, sent: None }),
@@ -114,13 +115,13 @@ fn rgb_device(device: &str) -> bool {
device.starts_with("rgb:")
}
/// The dialog over the host's values, made again every pass.
fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
/// The dialog over the host's values, made again every pass, previewing on `canvas`.
fn build(fields: &mut DialogFields, canvas: Option<egui::Id>) -> ParamDialog<'_> {
let footer = vec![
(SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other).stays_open(true)),
(LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other).stays_open(true)),
];
ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews(true).extra_buttons(footer)
ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews_on(true, canvas).extra_buttons(footer)
}
/// The rows for the values `fields` hold now.
+1 -1
View File
@@ -39,7 +39,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
fields.set("limitTo", limit.clone());
fields.set(OPENING, FieldValue::Json(json!({"uid": document, "reverts": reverts, "colors": colors})));
let rows = vec![Param::new("limitTo", field_label(tl!("Limit to Library:")), ParamKind::choice(options, Some(limit)))];
let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false);
let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false, None);
// Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays.
let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let Some(FieldValue::Json(opening)) = answer.fields.get(OPENING) else { return Err("the Recolor with Preset target is missing".into()) };
+1 -1
View File
@@ -31,7 +31,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
fields.set("values", id(use_lab));
let options = CHOICES.iter().map(|(lab, text, help)| (id(*lab).to_owned(), tl!(text).to_owned().into(), tl!(help).to_owned().into())).collect();
let rows = vec![Param::new("values", field_label(tl!("Lab Spot Colors:")), ParamKind::radio_with_details(options, Some(id(true).to_owned())))];
let dialog = hosted(&ctx, KIND, tl!("Spot Colors"), fields, rows, false);
let dialog = hosted(&ctx, KIND, tl!("Spot Colors"), fields, rows, false, None);
let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let use_lab = answer.fields.text("values") == Some(id(true));
app.run("swatch.spotOptions", json!({ "useLab": use_lab })).map(|_| ())
+6 -4
View File
@@ -31,7 +31,7 @@ use serde_json::{Value, json};
use vectorcraft_color::cms::Model;
use vectorcraft_color::{Color, GradientPaint, Paint};
use super::host::{HeldOptions, open_held_with};
use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas};
use crate::VectorcraftApp;
use crate::panels::color::{color_of_values, gamut, model_values};
@@ -179,7 +179,8 @@ pub(super) fn name_row() -> Param {
Param::new("name", field_label(tl!("Swatch Name:")), ParamKind::text(""))
}
/// A hosted dialog for the command `key`, whose rows are `rows`: the one way the colour dialogs build theirs.
/// A hosted dialog for the command `key`, whose rows are `rows`: the one way the colour dialogs build theirs. One
/// that `previews` does so on `canvas`.
pub(super) fn hosted(
ctx: &egui::Context,
key: &'static str,
@@ -187,10 +188,11 @@ pub(super) fn hosted(
fields: DialogFields,
rows: Vec<Param>,
previews: bool,
canvas: Option<egui::Id>,
) -> HostedParamDialog {
let title = title.to_owned();
HostedParamDialog::new(ctx, key, fields, move |values| {
ParamDialog::new(key, title.clone(), rows.clone()).values(Bind::bound(values)).previews(previews)
ParamDialog::new(key, title.clone(), rows.clone()).values(Bind::bound(values)).previews_on(previews, canvas)
})
}
@@ -294,7 +296,7 @@ fn launch(app: &mut VectorcraftApp, swatch: &str, fields: DialogFields, rows: Ve
let active = app.session.active().ok_or("no drawing")?;
let document = (active.uid, active.reverts);
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true);
let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true, preview_canvas(app));
if owns_preview(app) {
let _ = app.session.cancel_interaction();
}
+21 -4
View File
@@ -381,16 +381,22 @@ fn two_pages(editing_data: bool, password: Option<&str>) -> Vec<u8> {
/// Two 100 pt pages and, on the first, editing data with two artboards to match and a layer of its
/// own, which draws the square the first page draws.
fn two_pages_with_a_layer_in_the_editing_data(layer: &str) -> Vec<u8> {
fn two_pages_with_a_layer_in_the_editing_data(layer: &str, with_trim_box: bool) -> Vec<u8> {
let point = |x: i32, y: i32, n: u8| format!("%_{x} {y} /RealPointRelToROrigin\n%_ (PositionPoint{n}) ,\n");
let board = |top: i32| format!("%_/Dictionary :\n{}{}%_; ,\n", point(0, top, 1), point(100, top - 100, 2));
let boards = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n", board(100), board(-50));
let art = format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 10.0, 30.0, 30.0));
let data = ai::editing_data(100.0, 100.0, &format!("{boards}{}", ai::layer(layer, &art)));
let mut first = PdfPage::new(100.0, 100.0, "0 0 0 1 k 10 10 20 20 re f");
let page = |content| {
let edge = if with_trim_box { 120.0 } else { 100.0 };
let mut page = PdfPage::new(edge, edge, content);
page.trim = with_trim_box.then_some([10.0, 10.0, 110.0, 110.0]);
page
};
let mut first = page("0 0 0 1 k 10 10 20 20 re f");
first.entries = format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(2));
let stream = format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len());
pdf_with(&[first, PdfPage::new(100.0, 100.0, "")], &[&stream], None)
pdf_with(&[first, page("")], &[&stream], None)
}
/// #6135: the editing data of a `.ai` holds every artboard, so opening one asks nothing, opens
@@ -398,7 +404,7 @@ fn two_pages_with_a_layer_in_the_editing_data(layer: &str) -> Vec<u8> {
#[test]
fn opening_an_ai_with_editing_data_reads_it_without_asking() {
let mut app = app();
let bytes = two_pages_with_a_layer_in_the_editing_data("Only in the editing data");
let bytes = two_pages_with_a_layer_in_the_editing_data("Only in the editing data", false);
io::open_bytes(&mut app, "two.ai", &bytes, Some("/tmp/two.ai".into())).unwrap();
assert!(!is_open(&app), "no Import PDF dialog");
assert_eq!(app.session.documents().len(), 2);
@@ -435,6 +441,17 @@ fn opening_a_pdf_with_editing_data_keeps_its_trim_boxes_unless_a_box_is_picked()
confirm(&mut app).unwrap();
assert_eq!(artboard_widths(&app), [100.0, 200.0], "an explicit crop box");
let bytes = two_pages_with_a_layer_in_the_editing_data("An editable layer", true);
let mut app = self::app();
assert!(import_pdf::offer(&mut app, "readable.pdf", &bytes, None, None));
confirm(&mut app).unwrap();
assert_eq!(artboard_widths(&app), [100.0, 100.0], "the trim boxes match the artboards in the editing data");
let mut app = self::app();
assert!(import_pdf::offer(&mut app, "readable.pdf", &bytes, None, None));
set(&mut app, "cropTo", json!("crop"));
confirm(&mut app).unwrap();
assert_eq!(artboard_widths(&app), [120.0, 120.0], "the crop boxes override the artboards in the editing data");
let mut app = self::app();
assert!(import_pdf::offer(&mut app, "locked.pdf", &trimmed(Some("pw")), None, None));
set(&mut app, "password", json!("pw"));
+2 -2
View File
@@ -131,7 +131,7 @@ mod tests {
for (label, text) in [("Value", typed), ("Variation:", variation)] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(text);
panel.type_text(&crate::tests::regional_text(text));
panel.key(Key::Escape, Modifiers::NONE);
assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::<HostedParamDialog>()));
assert_eq!(panel.app().session.tool_options_of(tool), original, "the canceled {label} leaves the tool unchanged");
@@ -143,7 +143,7 @@ mod tests {
for (label, text) in [("Value", typed), ("Variation:", variation)] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(text);
panel.type_text(&crate::tests::regional_text(text));
panel.key(Key::Tab, Modifiers::NONE);
}
panel.click_role("Mode", Role::COMBO_BOX);
+2
View File
@@ -266,6 +266,8 @@ pub struct VectorcraftApp {
pub placing: placing::Placing,
/// Image Traces running off the UI thread ([`trace_runs`]).
pub trace_runs: trace_runs::TraceRuns,
/// The Concept to Vector panel's settings and its run off the UI thread ([`panels::concept_vector`]).
pub concept_runs: panels::concept_vector::ConceptRuns,
/// Retype's search of the installed fonts, off the UI thread ([`retype_runs`]).
pub retype_runs: retype_runs::RetypeRuns,
/// Data Recovery's timer and startup question ([`recovery`]).
+3
View File
@@ -132,6 +132,9 @@ pub fn context_items(app: &VectorcraftApp) -> Vec<Node> {
vec![c("Auto Spell Check", "edit.autoSpellCheck"), c("Check Spelling…", crate::dialogs::check_spelling::COMMAND)],
));
}
// One image or unexpanded Image Trace object; left out otherwise, as the menu leaves out
// every command that can't run.
v.push(c("Concept to Vector…", crate::panels::concept_vector::OPEN));
v.extend([c("Make Guides", "view.guides.make"), Sep, sub("Transform", transform_items())]);
if intertwine.is_none() {
v.push(sub("Arrange", arrange_items()));
+3
View File
@@ -838,6 +838,9 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
"tool.setOption" => app.session.set_tool_option_cmd(p),
"effect.dialog" => crate::dialogs::open_effect_dialog(app, p),
"ui.recolorDialog" => crate::dialogs::recolor::open(app, p),
crate::panels::concept_vector::OPEN => crate::panels::concept_vector::open(app),
crate::panels::concept_vector::GENERATE => crate::panels::concept_vector::generate_run(app),
crate::panels::concept_vector::CANCEL => Ok(crate::panels::concept_vector::cancel_run(app)),
"ui.cropImage" if !selected_image(app, |_| true) => Err("select an image".into()),
"ui.cropImage" => app.try_select_tool(vectorcraft_tools::cropimage::ID).map(|()| json!({"tool": app.session.tool_id()})),
"ui.paramDialog" => param_dialog(app, p),
+3
View File
@@ -385,6 +385,9 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
id if saved_view_slot(id).is_some() => saved_view(app, id).is_some(),
"effect.dialog" | "ui.recolorDialog" | "ui.effectGalleryDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
"ui.cropImage" => selected_image(app, |_| true),
crate::panels::concept_vector::OPEN => crate::panels::concept_vector::eligible(app).is_ok(),
crate::panels::concept_vector::GENERATE => crate::panels::concept_vector::eligible(app).is_ok(),
crate::panels::concept_vector::CANCEL => app.concept_runs.busy(),
"effect.applyLast" | "effect.last" => app.last_effect.is_some() && app.session.active().is_some_and(|d| !d.selection.is_empty()),
"pathfinder.repeat" => app.last_pathfinder.as_ref().is_some_and(|op| {
let min = crate::panels::pathfinder::minimum_operands(op);
+3
View File
@@ -398,6 +398,8 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
c("Expand", "imageTrace.expand"),
],
),
// Opens the Concept to Vector panel for the selected image or Image Trace object.
c("Concept to Vector…", crate::panels::concept_vector::OPEN),
sub(
"Text Wrap",
vec![
@@ -772,6 +774,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
panel("Color Guide", "colorGuide"),
panel("Color Themes", "colorThemes"),
panel("Color Wheel", crate::panels::color_wheel::ID),
panel("Concept to Vector", crate::panels::concept_vector::ID),
panel("CSS Properties", crate::panels::css_properties::ID),
panel("Document Info", "docInfo"),
panel("Flattener Preview", crate::panels::flattener_preview::ID),
+19 -1
View File
@@ -721,7 +721,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.taskBar.actions",
"Bar Actions",
"",
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"conceptToVector\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
),
(
"window.taskBar.resetActions",
@@ -1039,6 +1039,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
),
(
"ui.conceptVector",
"Concept to Vector…",
"",
"{} open the Concept to Vector panel for the selected image or unexpanded Image Trace object; an error when the selection is not one such object, unlocked and shown (engine: conceptVector.generate / conceptVector.insert)",
),
(
"ui.conceptVector.generate",
"Generate Concept to Vector Styles",
"",
"{} make the styles ticked in the Concept to Vector panel of the selected image or unexpanded Image Trace object, with the panel's Detail (the panel's Generate; engine: conceptVector.generate), and show them in the panel; off the UI thread in the app unless VECTORCRAFT_SYNC_OPEN is set, one part a frame on the web; a run going is canceled first, and the new one starts once its thread has ended → {running: true} while they are made, else {running: false, job}",
),
(
"ui.conceptVector.cancel",
"Cancel Concept to Vector",
"",
"{} stop the styles the Concept to Vector panel is making off the UI thread (the panel's Cancel; on the web, before the next part): nothing is kept or shown → {canceled: 0 or 1}",
),
(
"ui.recolorUndo",
"Undo Changes",
+1
View File
@@ -116,6 +116,7 @@ pub fn long_operation_busy(app: &VectorcraftApp) -> bool {
|| !app.placing.pending.is_empty()
|| !app.trace_runs.running.is_empty()
|| crate::retype_runs::any_running(app)
|| app.concept_runs.busy()
}
/// Does opening happen off the UI thread here? Not on wasm (no threads), in unit tests (they look
+6
View File
@@ -1076,6 +1076,12 @@ fn run(app: &mut VectorcraftApp, actions: Vec<Action<String>>, reveal: Option<St
if layout_of(&app.ui).opens_in_flyout(&panel) {
app.ui.open_panel = Some(panel);
} else {
// An open flyout is a popup layer of the main window, and palette windows stay hidden while one shows: a
// floating window revealed with a flyout open (a built-in workspace opens its panel's flyout) would open
// hidden, so the flyout closes.
if floating_window(layout_of(&app.ui), &panel).is_some() {
app.ui.open_panel = None;
}
app.dock_rt.raise = Some(panel);
}
}
@@ -601,6 +601,21 @@ fn a_panel_floated_in_any_built_in_workspace_opens_a_shown_window() {
}
}
/// Palette windows hide while the main window shows a popup, which an open flyout is: a built-in workspace opens its
/// panel's flyout, and a panel floated then closes it, so its window shows.
#[test]
fn floating_a_panel_closes_the_open_flyout_that_would_hide_its_window() {
let mut h = Harness::new();
h.app.run("window.workspace", json!({"name": "Essentials Classic"})).unwrap();
h.frames(3);
assert_eq!(h.app.ui.open_panel.as_deref(), Some("color"), "Essentials Classic opens its Color flyout");
h.app.run("window.panel.float", json!({"panel": "tools", "x": 200, "y": 200})).unwrap();
h.frames(6);
assert_eq!(h.app.ui.open_panel, None, "the flyout closed");
let viewport = h.viewport("tools");
assert!(h.host.borrow().windows[&viewport].visible, "the tools window shows");
}
/// A panel opened from the Window menu floats in an OS window that keeps showing while the art on
/// the canvas is selected and moved, and the Selection tool's move ends where it is released.
#[test]
+11
View File
@@ -16,6 +16,7 @@ pub mod color;
pub mod color_guide;
pub mod color_themes;
pub mod color_wheel;
pub mod concept_vector;
pub mod css_properties;
pub mod discover;
pub mod doc_info;
@@ -603,6 +604,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
variables::ID => variables::show(app, ui),
"colorThemes" => color_themes::show(app, ui),
color_wheel::ID => color_wheel::show(app, ui),
concept_vector::ID => concept_vector::show(app, ui),
links::ID => links::show(app, ui),
preflight::ID => preflight::show(app, ui),
asset_export::ID => asset_export::show(app, ui),
@@ -1262,6 +1264,15 @@ pub(crate) fn whole_steps(range: std::ops::RangeInclusive<f64>) -> ChannelRule {
rule
}
/// An opacity stored as an f32 fraction (0 to 1), as the percent an Opacity field shows: the whole percent when it
/// stores as the same f32, so that an arrow key steps on from it, and the exact percent otherwise. 51 % stores as
/// 0.51f32, which reads back as 50.999999 %; an Up press from there would step to 51 % again.
pub(crate) fn shown_percent(fraction: f32) -> f64 {
let percent = f64::from(fraction) * 100.0;
let whole = percent.round();
if (whole / 100.0) as f32 == fraction { whole } else { percent }
}
/// A section of a panel or dialog under its heading in label text: the reference app's section headings are regular
/// weight, not bold.
pub(crate) fn section<'a>(title: impl Into<Label>) -> Section<'a> {
@@ -227,7 +227,7 @@ fn a_plug_in_effect_s_editor_follows_its_manifest() {
}
assert!(!panel.shows("spacing") && !panel.shows("width"), "the labels replace the names");
let spacing = panel.value_role("Spacing", craft::ui::contract::Role::SPIN_BUTTON);
assert!(spacing.as_deref().is_some_and(|v| v.contains("1.5") && v.contains("mm")), "{spacing:?}");
assert!(spacing.as_deref().is_some_and(|v| v.contains(&crate::tests::regional_text("1.5")) && v.contains("mm")), "{spacing:?}");
assert!(panel.value("Angles").is_some_and(|v| v.contains("45, 135")), "{:?}", panel.value("Angles"));
// Without the outline, its width isn't shown.
panel.app().run("effect.setParams", json!({"item": null, "index": 0, "params": {"outline": false}})).unwrap();
+6 -3
View File
@@ -463,6 +463,7 @@ fn an_open_color_or_gradient_pop_out_runs_one_pass_a_frame() {
#[test]
fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let mut app = app();
app.run("paint.setFill", json!({"color": "#224466"})).unwrap();
@@ -470,8 +471,8 @@ fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() {
app.run("paint.toggleActive", json!({"fill": true})).unwrap();
let mut panel = Panel::new(app, show);
let (fill, stroke) = paints_hex(&panel.app());
let fill_well = panel.rect("Fill");
let stroke_well = panel.rect("Stroke");
let fill_well = panel.rect_role_with_value(Role::RADIO_BUTTON, &fill);
let stroke_well = panel.rect_role_with_value(Role::RADIO_BUTTON, &stroke);
let stroke_hit = egui::pos2(stroke_well.center().x, (fill_well.bottom() + stroke_well.bottom()) / 2.0);
assert!(stroke_well.contains(stroke_hit) && !fill_well.contains(stroke_hit), "click the exposed part of Stroke");
panel.click_at(stroke_hit);
@@ -487,7 +488,9 @@ fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() {
panel.click("None");
assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), String::new()));
panel.click("Fill");
let fill_hit = egui::pos2(fill_well.center().x, (fill_well.top() + stroke_well.top()) / 2.0);
assert!(fill_well.contains(fill_hit) && !stroke_well.contains(fill_hit), "click the exposed part of Fill");
panel.click_at(fill_hit);
assert!(panel.app().session.fill_active);
panel.click("Black");
assert_eq!(paints_hex(&panel.app()), ("#000000".into(), String::new()));
+1 -1
View File
@@ -1901,7 +1901,7 @@ fn opacity_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, tgt:
// The row reads dim and takes no edit with nothing it can set.
Stack::new().enabled(live).show(ui, |ui, _| {
let rule = super::whole_steps(0.0..=100.0);
let row = ChannelRow::new(tl!("Opacity").to_string(), Bind::given(f64::from(o) * 100.0), rule)
let row = ChannelRow::new(tl!("Opacity").to_string(), Bind::given(super::shown_percent(o)), rule)
.unit(ChannelUnit::Percent)
.track(track.clone())
.checker(true);
+735
View File
@@ -0,0 +1,735 @@
//! Concept to Vector panel (Window › Concept to Vector, Object › Concept to Vector…): vector
//! variations of the selected image or unexpanded Image Trace object, one for each ticked style,
//! compared side by side and inserted to the right of the image.
//!
//! The panel calls the built-in provider ([`offline::ID`]), whose styles are made with Image Trace
//! on this computer: its prompt field is disabled and it makes vector art only. Generate prepares
//! the request at once (`conceptVector.generate`'s checks) and runs the provider on a thread of its
//! own ([`ConceptRuns`]); a new Generate cancels the one running and starts once that run's
//! thread has ended, so one thread makes styles at a time. Results from another provider
//! are named as that provider names its styles. The results stay in this session
//! until Insert Selected puts the ticked ones in the document as one undo step
//! (`conceptVector.insert`). The web build has no thread for it, so it makes one part a frame
//! (the built-in provider: the image decoded, a style's color layers found, or one color layer
//! traced, or all of them for a style that stacks its layers), and Cancel takes effect before the
//! next part. Unit tests that set neither
//! `off_the_ui_thread` nor `by_frames` run the command at once.
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use craft::behavior::Mixed;
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::{Divider, Picture, PictureSize, Progress, Shade, Text};
use craft::ui::form::{Field, SliderField, SliderFieldLayout};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{ThumbAspect, ThumbSize};
use craft::ui::text::TextField;
use egui::{Color32, Pos2, Rect, Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_doc::cancel::CancelToken;
use vectorcraft_engine::cmd::conceptvector::{ConceptRun, PartRun, provider_error};
use vectorcraft_engine::concept_vector::{MAX_STYLES, ProviderError, Variation, offline};
use crate::VectorcraftApp;
pub const ID: &str = "conceptVector";
/// The UI command that opens the panel for the selected image.
pub const OPEN: &str = "ui.conceptVector";
/// The UI command of the panel's Generate: it makes the ticked styles of the selection.
pub const GENERATE: &str = "ui.conceptVector.generate";
/// The UI command of the panel's Cancel: it stops the styles being made.
pub const CANCEL: &str = "ui.conceptVector.cancel";
/// What the status bar says while styles are made.
const LABEL: &str = "Making the Concept to Vector styles";
/// The most points a preview draws; the points past them are left out of it.
const PREVIEW_POINTS: usize = 40_000;
/// A preview's height in points.
const PREVIEW_H: f32 = 110.0;
/// Pixels per point of a preview's painted image.
const PREVIEW_SCALE: f32 = 2.0;
/// The thinnest a preview draws a stroke, in points, so that thin lines still show.
const MIN_STROKE: f32 = 0.5;
/// The color a preview paints its paths over: the paper of the image's box, which the variations'
/// own colors are drawn on.
const PAPER: Color32 = Color32::WHITE;
/// What a run's thread hands back.
type Done = (ConceptRun, Result<Vec<Variation>, ProviderError>);
/// How a Generate runs.
enum Work {
/// On a thread of its own, which hands back its results.
Thread(Receiver<Done>),
/// On the UI thread, one part a frame ([`ConceptRun::run_part`]), where no thread can run it.
Frames(Box<ConceptRun>, PartRun),
/// Waiting for the thread of a canceled run to end before it starts on a thread of its own, so
/// that one thread makes styles at a time.
Queued(Box<ConceptRun>),
}
/// A Generate running.
struct Running {
token: CancelToken,
/// Styles made and in all.
steps: Arc<[AtomicU64; 2]>,
work: Work,
}
/// One variation as the panel draws it: its fills and strokes painted into `image` in the order of
/// its paths.
struct Preview {
style: String,
label: String,
aspect: f32,
image: egui::ColorImage,
/// The key the panel's picture stores `image` under: one for each job and style.
key: u64,
warnings: Vec<String>,
/// Part of the variation is left out of `image` ([`PREVIEW_POINTS`]).
cut: bool,
}
/// The job the panel shows.
struct Shown {
job: u64,
/// The document the job was made in ([`vectorcraft_engine::DocState::uid`]): the results show
/// only while it is the active one.
doc: u64,
previews: Vec<Preview>,
/// The styles ticked for Insert Selected.
picked: Vec<String>,
}
/// The panel's settings and its run.
pub struct ConceptRuns {
styles: Vec<String>,
detail: u8,
running: Option<Running>,
/// The thread of a canceled run, until it ends.
stopping: Option<Receiver<Done>>,
shown: Option<Shown>,
/// The provider Generate calls: the built-in one, or another in unit tests.
pub(crate) provider: &'static str,
/// Set by unit tests whose app makes styles off the UI thread.
pub(crate) off_the_ui_thread: bool,
/// Set by unit tests whose app makes styles one a frame, as the web build does.
pub(crate) by_frames: bool,
}
impl Default for ConceptRuns {
fn default() -> Self {
Self {
styles: offline::STYLES.iter().map(|s| s.id.to_string()).collect(),
detail: 50,
running: None,
stopping: None,
shown: None,
provider: offline::ID,
off_the_ui_thread: false,
by_frames: false,
}
}
}
impl ConceptRuns {
/// Is a Generate running?
pub fn busy(&self) -> bool {
self.running.is_some()
}
/// The job the panel shows.
pub fn job(&self) -> Option<u64> {
self.shown.as_ref().map(|s| s.job)
}
}
/// The params of `conceptVector.generate` for the panel's settings.
fn params(app: &VectorcraftApp) -> Value {
json!({ "provider": app.concept_runs.provider, "styles": app.concept_runs.styles, "detail": app.concept_runs.detail })
}
/// Whether the panel can make styles of the selection; else why not.
pub fn eligible(app: &VectorcraftApp) -> Result<(), String> {
let p = json!({ "provider": offline::ID, "styles": [offline::STYLES[0].id] });
ConceptRun::prepare(&app.session, &p).map(|_| ()).map_err(|e| match e {
vectorcraft_engine::EngineError::BadParams { msg, .. } => msg,
e => e.to_string(),
})
}
/// `ui.conceptVector`: opens the panel for the selection; an error when it has nothing to use.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
eligible(app)?;
app.run("window.panel.activate", json!({ "panel": ID }))
}
/// Makes the ticked styles of the selection: off the UI thread where it can; on the web, one part
/// a frame; else (unit tests, `VECTORCRAFT_SYNC_OPEN`) at once.
pub fn generate(app: &mut VectorcraftApp) -> Result<(), String> {
let p = params(app);
let frames = cfg!(target_arch = "wasm32") || app.concept_runs.by_frames;
if !(frames || app.concept_runs.off_the_ui_thread || crate::opening::available()) {
let v = app.run("conceptVector.generate", p)?;
show_job(app, &v);
return Ok(());
}
let run = ConceptRun::prepare(&app.session, &p).map_err(|e| e.to_string())?;
cancel(app);
let token = CancelToken::new();
let steps = Arc::new([AtomicU64::new(0), AtomicU64::new(run.style_count() as u64)]);
let work = if frames {
Work::Frames(Box::new(run), PartRun::default())
} else if worker_ended(&mut app.concept_runs) {
spawn(run, &token, &steps)?
} else {
Work::Queued(Box::new(run))
};
app.concept_runs.running = Some(Running { token, steps, work });
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
app.status(format!("{}…", crate::i18n::msg(LABEL)));
Ok(())
}
/// Starts `run` on a thread of its own, which stops once `token` is canceled and counts the styles
/// made in `steps`.
fn spawn(run: ConceptRun, token: &CancelToken, steps: &Arc<[AtomicU64; 2]>) -> Result<Work, String> {
let (tx, done) = channel();
let stop = token.clone();
let counts = Arc::clone(steps);
std::thread::Builder::new()
.name("vectorcraft-concept".into())
.spawn(move || {
let [done_now, total_now] = &*counts;
let report = |done: u64, total: u64| {
done_now.store(done, Ordering::Relaxed);
total_now.store(total, Ordering::Relaxed);
!stop.is_cancelled()
};
let made = run.run(&report);
// The app may have quit, or the run was canceled: nothing to hand it to.
let _ = tx.send((run, made));
})
.map_err(|e| e.to_string())?;
Ok(Work::Thread(done))
}
/// Whether no canceled run's thread is still going: it has handed back its results, which are
/// dropped, or ended.
fn worker_ended(runs: &mut ConceptRuns) -> bool {
let ended = runs.stopping.as_ref().is_none_or(|rx| !matches!(rx.try_recv(), Err(TryRecvError::Empty)));
if ended {
runs.stopping = None;
}
ended
}
/// Cancel: the run stops at its next check (on the web, before its next part), and its results
/// are dropped. A run on a thread is kept track of until its thread ends, and the next Generate
/// waits for that.
pub fn cancel(app: &mut VectorcraftApp) {
if let Some(r) = app.concept_runs.running.take() {
r.token.cancel();
if let Work::Thread(rx) = r.work {
app.concept_runs.stopping = Some(rx);
}
if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) {
app.ui.status.clear();
}
}
}
/// `ui.conceptVector.generate`, the panel's Generate: makes the ticked styles of the selection
/// with the panel's Detail → `{running: true}` while they are made off the UI thread (or one part
/// a frame on the web), else `{running: false, job}` with the job shown.
pub fn generate_run(app: &mut VectorcraftApp) -> Result<Value, String> {
generate(app)?;
Ok(if app.concept_runs.busy() { json!({ "running": true }) } else { json!({ "running": false, "job": app.concept_runs.job() }) })
}
/// `ui.conceptVector.cancel`, the panel's Cancel: stops the styles being made, and says so in the
/// status bar → `{canceled: 0 or 1}`.
pub fn cancel_run(app: &mut VectorcraftApp) -> Value {
if !app.concept_runs.busy() {
return json!({ "canceled": 0 });
}
cancel(app);
app.status(vectorcraft_engine::EngineError::Cancelled.to_string());
json!({ "canceled": 1 })
}
/// Each frame: makes the next part of a run made one part a frame, and keeps a finished run's
/// results as a job and shows it. Not while a dialog or an interaction is open, as
/// [`crate::trace_runs::poll`].
pub fn poll(app: &mut VectorcraftApp) {
if app.asking_dialog_open() || app.session.in_interaction() {
return;
}
// A run waiting for a canceled run's thread starts once that thread has ended.
if matches!(app.concept_runs.running.as_ref().map(|r| &r.work), Some(Work::Queued(_))) {
if !worker_ended(&mut app.concept_runs) {
return;
}
let Some(Running { token, steps, work: Work::Queued(run) }) = app.concept_runs.running.take() else { return };
match spawn(*run, &token, &steps) {
Ok(work) => app.concept_runs.running = Some(Running { token, steps, work }),
Err(e) => app.status(e),
}
return;
}
let Some(r) = app.concept_runs.running.as_mut() else { return };
let ended = match &mut r.work {
Work::Thread(_) | Work::Queued(_) => None,
Work::Frames(run, made) => {
let stop = r.token.clone();
match run.run_part(made, &|_, _| !stop.is_cancelled()) {
Ok(false) => {
r.steps[0].store(made.styles_done() as u64, Ordering::Relaxed);
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
return;
}
Ok(true) => Some(Ok(())),
Err(e) => Some(Err(e)),
}
}
};
let received = match (&ended, &r.work) {
(None, Work::Thread(rx)) => match rx.try_recv() {
Ok(done) => Some(done),
Err(TryRecvError::Empty) => return,
Err(TryRecvError::Disconnected) => None,
},
_ => None,
};
let Some(r) = app.concept_runs.running.take() else { return };
let done = match (ended, r.work) {
(Some(end), Work::Frames(run, made)) => Some((*run, end.map(|()| made.made()))),
_ => received,
};
finish(app, &r.token, done);
}
/// Keeps a run's results `done` as a job and shows it; else why there are none, in the status bar.
/// Nothing when `token` was canceled.
fn finish(app: &mut VectorcraftApp, token: &CancelToken, done: Option<Done>) {
if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) {
app.ui.status.clear();
}
if token.is_cancelled() {
return;
}
match done {
// Nothing is kept or shown when the run's document has closed.
Some((run, Ok(made))) => {
if let Some(v) = run.finish(&mut app.session, made) {
show_job(app, &v);
}
}
Some((_, Err(e))) => app.status(provider_error(e).to_string()),
None => app.status("Concept to Vector stopped: its thread ended without results (please report this bug)"),
}
}
/// Shows the variations of `job` (a job as `conceptVector.generate` returns it), every one ticked,
/// each named as the job names its style: by the name its provider gives the style.
fn show_job(app: &mut VectorcraftApp, job: &Value) {
let Some(id) = job["job"].as_u64() else { return };
let Some(doc) = app.session.concept_job_doc(id) else { return };
let Some((variations, (w, h))) = app.session.concept_variations(id) else { return };
let listed = job["variations"].as_array().map(Vec::as_slice).unwrap_or_default();
let label_of = |style: &str| listed.iter().find(|v| v["style"] == style).and_then(|v| v["label"].as_str());
let previews: Vec<Preview> = variations
.iter()
.map(|v| {
let label = label_of(&v.style).map_or_else(|| v.style.clone(), str::to_string);
Preview { key: preview_key(id, &v.style), ..preview(v, label, (w, h)) }
})
.collect();
let picked = previews.iter().map(|p| p.style.clone()).collect();
app.concept_runs.shown = Some(Shown { job: id, doc, previews, picked });
}
/// The key a preview of `style` in job `job` is stored under as a picture.
fn preview_key(job: u64, style: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
("concept-vector", job, style).hash(&mut h);
h.finish()
}
/// A preview's width in points, `height` high, for an image `aspect` wide per unit high.
fn preview_width(aspect: f32, height: f32) -> f32 {
(height * aspect).clamp(height * 0.4, height * 2.5)
}
/// The box an image `aspect` wide per unit high takes inside `inner`: as large as fits, centered,
/// so a preview whose width [`preview_width`] clamps keeps the image's proportions.
fn art_rect(inner: Rect, aspect: f32) -> Rect {
let size = vec2(inner.width().min(inner.height() * aspect), inner.height().min(inner.width() / aspect));
Rect::from_center_size(inner.center(), size)
}
/// The size in pixels of the fills of a preview of an image `aspect` wide per unit high: its
/// [`art_rect`] inside the 4 pt margin, at [`PREVIEW_SCALE`].
fn image_size(aspect: f32) -> [usize; 2] {
let inner = Rect::from_min_size(Pos2::ZERO, vec2(preview_width(aspect, PREVIEW_H), PREVIEW_H)).shrink(4.0);
let art = art_rect(inner, aspect);
let px = |pt: f32| (pt * PREVIEW_SCALE).round().max(1.0) as usize;
[px(art.width()), px(art.height())]
}
/// Paints `rings` (polylines in 0..1 of the image's box, each closed, nonzero winding) in `color`
/// over `img`, antialiased with four samples a pixel high.
fn fill_rings(img: &mut egui::ColorImage, rings: &[Vec<Pos2>], color: Color32) {
const SUB: usize = 4;
let [w, h] = img.size;
let (sx, sy) = (w as f32, h as f32);
let mut edges: Vec<(f32, f32, f32, f32)> = vec![];
for ring in rings {
for (a, b) in ring.iter().zip(ring.iter().skip(1).chain(ring.first())) {
edges.push((a.x * sx, a.y * sy, b.x * sx, b.y * sy));
}
}
let top = edges.iter().map(|e| e.1.min(e.3)).fold(f32::INFINITY, f32::min);
let bottom = edges.iter().map(|e| e.1.max(e.3)).fold(f32::NEG_INFINITY, f32::max);
let left = edges.iter().map(|e| e.0.min(e.2)).fold(f32::INFINITY, f32::min);
let right = edges.iter().map(|e| e.0.max(e.2)).fold(f32::NEG_INFINITY, f32::max);
if !(top.is_finite() && bottom.is_finite() && left.is_finite() && right.is_finite()) {
return;
}
let (y0, y1) = (top.floor().clamp(0.0, sy) as usize, bottom.ceil().clamp(0.0, sy) as usize);
// Only the columns the rings reach: `cover[i]` is column `c0 + i`.
let (c0, c1) = (left.floor().clamp(0.0, sx) as usize, right.ceil().clamp(0.0, sx) as usize);
let mut cover = vec![0f32; c1.saturating_sub(c0)];
let mut xs: Vec<(f32, i32)> = vec![];
// Each sample row looks only at the edges that reach it: the edges in order of their tops are
// taken in as the rows reach them, and dropped once the rows pass their bottoms.
edges.sort_by(|a, b| a.1.min(a.3).total_cmp(&b.1.min(b.3)));
let (mut next, mut active) = (0, Vec::<(f32, f32, f32, f32)>::new());
for row in y0..y1 {
cover.fill(0.0);
for k in 0..SUB {
let y = row as f32 + (k as f32 + 0.5) / SUB as f32;
while let Some(&e) = edges.get(next).filter(|e| e.1.min(e.3) <= y) {
active.push(e);
next += 1;
}
active.retain(|e| e.1.max(e.3) > y);
xs.clear();
for &(x0, ya, x1, yb) in &active {
if (ya <= y) != (yb <= y) {
xs.push((x0 + (y - ya) / (yb - ya) * (x1 - x0), if yb > ya { 1 } else { -1 }));
}
}
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut wind = 0;
for pair in xs.windows(2) {
wind += pair[0].1;
let (a, b) = (pair[0].0.max(0.0), pair[1].0.min(sx));
if wind == 0 || b <= a {
continue;
}
let (start, end) = ((a.floor() as usize).saturating_sub(c0), (b.ceil() as usize).min(c1).saturating_sub(c0));
for (i, c) in cover.iter_mut().enumerate().take(end).skip(start) {
let px = (c0 + i) as f32;
*c += (b.min(px + 1.0) - a.max(px)).max(0.0) / SUB as f32;
}
}
}
for (i, c) in cover.iter().enumerate().filter(|(_, c)| **c > 0.0) {
let px = c0 + i;
let a = c.min(1.0);
let mix = |s: u8, t: u8| (f32::from(t) * a + f32::from(s) * (1.0 - a)).round() as u8;
if let Some(d) = img.pixels.get_mut(row * w + px) {
*d = Color32::from_rgb(mix(d.r(), color.r()), mix(d.g(), color.g()), mix(d.b(), color.b()));
}
}
}
}
/// Paints `rings` (polylines in 0..1 of the image's box) stroked `width` pixels wide in `color`
/// over `img`: each segment as a rectangle, with a disc at each point for round joins and caps
/// once the stroke is wide enough for them to show. With `square_caps`, an open line has no disc
/// at its ends, and its end segments reach half the width past them.
fn stroke_rings(img: &mut egui::ColorImage, rings: &[Vec<Pos2>], width: f32, color: Color32, square_caps: bool) {
let (sx, sy) = (img.size[0] as f32, img.size[1] as f32);
let r = width / 2.0;
let unit = |p: Pos2| Pos2::new(p.x / sx, p.y / sy);
for ring in rings {
let pts: Vec<Pos2> = ring.iter().map(|q| Pos2::new(q.x * sx, q.y * sy)).collect();
let last = pts.len().saturating_sub(1);
let square = square_caps && pts.len() > 1 && pts.first() != pts.last();
for (k, a) in pts.iter().enumerate() {
if r > 0.75 && !(square && (k == 0 || k == last)) {
let disc: Vec<Pos2> = (0..8)
.map(|i| {
let t = i as f32 * std::f32::consts::TAU / 8.0;
unit(*a + vec2(t.cos(), t.sin()) * r)
})
.collect();
fill_rings(img, &[disc], color);
}
let Some(b) = pts.get(k + 1) else { continue };
let d = *b - *a;
let len = d.length();
if len > 0.0 {
let n = vec2(-d.y, d.x) * (r / len);
let along = d * (r / len);
let a = if square && k == 0 { *a - along } else { *a };
let b = if square && k + 1 == last { *b + along } else { *b };
fill_rings(img, &[vec![unit(a + n), unit(b + n), unit(b - n), unit(a - n)]], color);
}
}
}
}
/// `path`'s elements, made as they are taken, so that taking the first few of a long path does
/// not convert the rest.
fn elements(path: &vectorcraft_geom::PathData) -> impl Iterator<Item = vectorcraft_geom::PathEl> + '_ {
use vectorcraft_geom::PathEl;
path.subpaths.iter().filter_map(|sp| sp.anchors.first().map(|first| (sp, first.p))).flat_map(|(sp, start)| {
let segments = (0..sp.segment_count()).map(move |i| {
let c = sp.segment(i);
if sp.segment_is_line(i) { PathEl::LineTo(c.p3) } else { PathEl::CurveTo(c.p1, c.p2, c.p3) }
});
std::iter::once(PathEl::MoveTo(start)).chain(segments).chain(sp.closed.then_some(PathEl::ClosePath))
})
}
/// `els` until no point is `left` to take, checked as each element is taken; a closing element
/// still closes its ring.
fn within_budget<'a>(
els: impl Iterator<Item = vectorcraft_geom::PathEl> + 'a,
left: &'a std::cell::Cell<usize>,
) -> impl Iterator<Item = vectorcraft_geom::PathEl> + 'a {
els.take_while(move |el| left.get() > 0 || matches!(el, vectorcraft_geom::PathEl::ClosePath))
}
/// How many elements [`elements`] makes of `path`.
fn element_count(path: &vectorcraft_geom::PathData) -> usize {
path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).map(|sp| 1 + sp.segment_count() + usize::from(sp.closed)).sum()
}
/// Variation `v` of an image `size` pixels big: its paths painted in order, each path's fill and
/// then its stroke, stopping after [`PREVIEW_POINTS`] points in all, and whether that left part of
/// it out ([`Preview::cut`]).
fn preview(v: &Variation, label: String, size: (u32, u32)) -> Preview {
let (w, h) = (f64::from(size.0.max(1)), f64::from(size.1.max(1)));
let aspect = (w / h) as f32;
let mut image = egui::ColorImage::filled(image_size(aspect), PAPER);
let left = std::cell::Cell::new(PREVIEW_POINTS);
let at = |q: vectorcraft_geom::Point| Pos2::new((q.x / w) as f32, (q.y / h) as f32);
let rgb = |[r, g, b]: [u8; 3]| Color32::from_rgb(r, g, b);
let cut = std::cell::Cell::new(false);
for p in &v.paths {
if left.get() == 0 {
cut.set(true);
break;
}
let mut rings: Vec<Vec<Pos2>> = vec![];
let mut ring: Vec<Pos2> = vec![];
let taken = std::cell::Cell::new(0usize);
// Counted after `within_budget`, so the element it stops at is not counted as drawn.
let els = within_budget(elements(&p.path), &left).inspect(|_| taken.set(taken.get() + 1));
// `flatten` takes an element only after the points of the one before, and makes a bounded
// number of each curve, so the elements past the points left are neither made nor flattened.
vectorcraft_geom::flatten(els, (w.max(h) / 400.0).max(0.25), |el| {
let q = match el {
vectorcraft_geom::PathEl::MoveTo(q) => {
if ring.len() > 1 {
rings.push(std::mem::take(&mut ring));
}
ring.clear();
q
}
vectorcraft_geom::PathEl::LineTo(q) => q,
vectorcraft_geom::PathEl::ClosePath => {
if let Some(first) = ring.first().copied() {
ring.push(first);
}
if ring.len() > 1 {
rings.push(std::mem::take(&mut ring));
}
ring.clear();
return;
}
_ => return,
};
if left.get() > 0 {
left.set(left.get() - 1);
ring.push(at(q));
} else {
cut.set(true);
}
});
if taken.get() < element_count(&p.path) {
cut.set(true);
}
if ring.len() > 1 {
rings.push(ring);
}
if let Some(c) = p.fill {
fill_rings(&mut image, &rings, rgb(c));
}
if let Some((c, width)) = p.stroke {
// To scale with the image, and at least MIN_STROKE points.
let px = ((width / w) as f32 * image.size[0] as f32).max(MIN_STROKE * PREVIEW_SCALE);
stroke_rings(&mut image, &rings, px, rgb(c), p.square_caps);
}
}
Preview { style: v.style.clone(), label, aspect, image, key: 0, warnings: v.warnings.clone(), cut: cut.get() }
}
/// Insert Selected: the ticked variations go to the right of the image, as one undo step.
pub fn insert(app: &mut VectorcraftApp) -> Result<Value, String> {
let Some(shown) = &app.concept_runs.shown else { return Err("`job` must be a job number from conceptVector.generate".into()) };
let p = json!({ "job": shown.job, "variations": shown.picked });
app.run("conceptVector.insert", p)
}
/// A style's name as shown: translated as Image Trace's preset of that name where the catalog has
/// one (the Outline style is not the Outline view), as any other string else.
fn style_name(label: &str) -> &str {
crate::i18n::tr_ctx(crate::i18n::current(), "imageTrace", label)
}
/// Draws preview `p` as a large thumbnail at the image's proportions, named for a screen reader by
/// its style.
fn draw_preview(ui: &mut Ui, p: &Preview) {
let image = || p.image.clone();
Picture::new(style_name(&p.label).to_string(), p.key, &image)
.aspect(ThumbAspect::from_ratio(p.aspect))
.extent(PictureSize::Thumb(ThumbSize::Large))
.show(ui);
}
/// The panel: the provider's note, a check box for each style (at most [`MAX_STYLES`] ticked),
/// Detail, the prompt field the built-in provider leaves disabled, then Generate (`ui.conceptVector.generate`)
/// or, while styles are made, their progress and Cancel (`ui.conceptVector.cancel`), and the results.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
Text::new(tl!("Offline Image Trace styles, made on this computer")).shade(Shade::Muted).show(ui);
let ready = eligible(app);
let count = app.concept_runs.styles.len();
Field::new(tl!("Styles")).show(ui, |ui, _| {
Text::new(format!("{count} / {MAX_STYLES}")).show(ui);
});
let mut toggled = None;
for s in &offline::STYLES {
let on = app.concept_runs.styles.iter().any(|id| id == s.id);
let allowed = on || count < MAX_STYLES;
let picked = Checkbox::new(Bind::given(on)).label(style_name(s.label)).id_salt(("concept-style", s.id)).enabled(allowed).show(ui);
if let Some(next) = picked.value().copied().filter(|next| *next != on) {
toggled = Some((s.id, next));
}
}
if let Some((id, on)) = toggled {
let styles = &mut app.concept_runs.styles;
styles.retain(|s| s != id);
if on {
styles.push(id.to_string());
// In the provider's order.
styles.sort_by_key(|s| offline::STYLES.iter().position(|st| st.id == s));
}
}
let detail = f64::from(app.concept_runs.detail);
let edited = Field::new(tl!("Detail"))
.show(ui, |ui, _| {
SliderField::new(tl!("Detail"), Bind::given(detail), 0.0..=100.0).layout(SliderFieldLayout::Inline).step(1.0).show(ui).value().copied()
})
.inner
.flatten();
if let Some(v) = edited.filter(|v| *v != detail) {
app.concept_runs.detail = v.round().clamp(0.0, 100.0) as u8;
}
TextField::new(tl!("Offline styles do not use prompts"), Bind::given(Mixed::Same(String::new())))
.placeholder(tl!("Offline styles do not use prompts"))
.enabled(false)
.show(ui);
if let Some(r) = &app.concept_runs.running {
let (done, total) = (r.steps[0].load(Ordering::Relaxed), r.steps[1].load(Ordering::Relaxed));
let frac = if total > 0 { done.min(total) as f32 / total as f32 } else { 0.0 };
Progress::new(frac).label(tl!("Making the Concept to Vector styles")).show(ui);
if Button::new(tl!("Cancel")).show(ui).clicked()
&& let Err(e) = app.run(CANCEL, json!({}))
{
app.status(e);
}
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
} else {
let can = ready.is_ok() && count > 0;
if Button::new(tl!("Generate")).enabled(can).show(ui).clicked()
&& let Err(e) = app.run(GENERATE, json!({}))
{
app.status(e);
}
}
if let Err(why) = &ready {
Text::new(crate::i18n::msg(why).to_string()).shade(Shade::Muted).show(ui);
}
show_results(app, ui);
}
/// The comparison strip of the job shown, with a tick on each and Insert Selected, while the
/// document it was made in is the active one. Nothing, and the job is no longer shown, once the
/// session has dropped it (its document closed).
fn show_results(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.concept_runs.job().is_some_and(|job| app.session.concept_variations(job).is_none()) {
app.concept_runs.shown = None;
}
let active = app.session.active().map(|d| d.uid);
let Some(Shown { previews, picked, doc, .. }) = &mut app.concept_runs.shown else { return };
if active != Some(*doc) {
return;
}
Divider::horizontal().show(ui);
let mut toggled = None;
Row::new().wrap(true).show(ui, |ui, _| {
for p in previews.iter() {
Stack::new().id_salt(("concept-result", &p.style)).show(ui, |ui, _| {
draw_preview(ui, p);
let on = picked.contains(&p.style);
let out = Checkbox::new(Bind::given(on)).label(style_name(&p.label).to_string()).id_salt(("concept-pick", &p.style)).show(ui);
if let Some(next) = out.value().copied().filter(|next| *next != on) {
toggled = Some((p.style.clone(), next));
}
if p.cut {
Text::new(tl!("The preview leaves out part of this style")).shade(Shade::Muted).show(ui);
}
for w in &p.warnings {
Text::new(w.clone()).shade(Shade::Muted).show(ui);
}
});
}
});
if let Some((style, on)) = toggled {
picked.retain(|s| *s != style);
if on {
picked.push(style);
}
}
let any = !picked.is_empty();
if Button::new(tl!("Insert Selected")).enabled(any).show(ui).clicked()
&& let Err(e) = insert(app)
{
app.status(e);
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,615 @@
//! The Concept to Vector panel drawn headless: its routes (Window, Object, the context menu,
//! Properties and the Control bar), why it can't run, the style limit, the disabled prompt,
//! Generate at once and off the UI thread, Cancel, and Insert Selected as one undo step.
use std::sync::Arc;
use egui::{Color32, Pos2, Rect, vec2};
use serde_json::json;
use vectorcraft_doc::NodeKind;
use vectorcraft_engine::Session;
use vectorcraft_engine::concept_vector::{Capabilities, Provider, ProviderError, Request, Steps, Style, Variation, VectorPath, offline};
use vectorcraft_geom::{PathData, Point, SubPath};
use super::{
CANCEL, GENERATE, ID, OPEN, PREVIEW_H, PREVIEW_POINTS, Work, art_rect, cancel, elements, finish, generate, insert, poll, preview, preview_width,
show, show_job, within_budget,
};
use crate::tests_labels::painted_text;
use crate::tests_removeanchors::{at, click_control, control_frame, has, properties_frame};
use crate::{VectorcraftApp, menus};
/// Waits for the run on its thread to end and keeps its results, as `poll` does once they are there.
fn wait(app: &mut VectorcraftApp) {
let Some(r) = app.concept_runs.running.take() else { return };
let Work::Thread(rx) = &r.work else { panic!("the run is not on a thread") };
let done = rx.recv().ok();
finish(app, &r.token, done);
}
/// The styles made so far of a run made one part a frame.
fn made_so_far(app: &VectorcraftApp) -> Option<usize> {
match &app.concept_runs.running.as_ref()?.work {
Work::Frames(_, made) => Some(made.styles_done()),
Work::Thread(_) | Work::Queued(_) => None,
}
}
/// A PNG of `w` × `h` pixels: black on the left half, a red square on the right, white elsewhere.
fn png(w: u32, h: u32) -> Vec<u8> {
let img = image::RgbaImage::from_fn(w, h, |x, y| {
image::Rgba(if x < w / 2 {
[0, 0, 0, 255]
} else if (w * 5 / 8..w * 7 / 8).contains(&x) && (h / 4..h * 3 / 4).contains(&y) {
[220, 30, 30, 255]
} else {
[255; 4]
})
});
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
/// An app with a 400 × 300 document and one embedded image of 40 × 30 pixels, selected.
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let data = vectorcraft_format::base64_encode(&png(40, 30));
app.run("file.place", json!({"name": "art.png", "dataBase64": data, "link": false, "at": [60, 60]})).unwrap();
app
}
fn undo_steps(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().history.undo.len()
}
fn root_count(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum()
}
#[test]
fn the_panel_is_registered_with_a_bundled_icon_and_opens_from_window() {
let row = crate::state::ICON_PANELS.iter().find(|(id, ..)| *id == ID).expect("registered");
assert_eq!(row.1, "Concept to Vector");
crate::icons::register();
assert!(craft::ui::primitives::has_icon(&craft::behavior::IconId::new(row.2)), "{}", row.2);
let mut app = app();
let item = menus::menu_entries(&app).into_iter().find(|e| e.path == ["Window"] && e.label == "Concept to Vector").expect("Window item");
let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
menus::invoke(&mut app, &id, p);
assert!(crate::panel_docking::showing(&app.ui, ID));
}
/// Object › Concept to Vector… and the context menu need one image (or Image Trace object) that is
/// shown and unlocked; without one the Object item is disabled, the context menu leaves it out and
/// the command says why.
#[test]
fn object_and_context_menus_open_it_for_one_image_only() {
let mut app = app();
let object = |app: &VectorcraftApp| {
menus::menu_entries(app).into_iter().find(|e| e.path == ["Object"] && e.label == "Concept to Vector…").expect("Object item")
};
let in_context = |app: &VectorcraftApp| menus::context_entries(app).iter().any(|e| e.label == "Concept to Vector…");
assert!(object(&app).enabled && in_context(&app));
let item = object(&app);
let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
menus::invoke(&mut app, &id, p);
assert!(crate::panel_docking::showing(&app.ui, ID), "{}", app.ui.status);
app.run("object.lock", json!({})).unwrap();
app.run("select.none", json!({})).unwrap();
assert!(!object(&app).enabled && !in_context(&app));
let e = app.run(OPEN, json!({})).unwrap_err();
assert!(e.contains("select one image or an unexpanded Image Trace object"), "{e}");
app.run("object.unlockAll", json!({})).unwrap();
app.run("shape.rectangle", json!({"x": 250, "y": 200, "width": 20, "height": 20})).unwrap();
assert!(!object(&app).enabled && !in_context(&app), "a rectangle is not a source");
app.run("select.all", json!({})).unwrap();
assert!(!object(&app).enabled, "two objects are not one source");
}
/// Properties' Quick Actions and the Control bar offer it for a selected image, and the Control
/// bar's button opens the panel.
#[test]
fn properties_and_the_control_bar_offer_it() {
let mut app = app();
assert!(has(&properties_frame(&mut app, 280.0), "Concept to Vector"));
let ctx = crate::testing::ui_context();
let bar = control_frame(&mut app, &ctx, vec![]);
click_control(&mut app, &ctx, at(&bar, "Concept to Vector"));
assert!(crate::panel_docking::showing(&app.ui, ID), "{}", app.ui.status);
}
/// The panel says its styles are offline Image Trace styles, disables the prompt, allows 1 to 8
/// styles, and shows why it can't run with nothing to use.
#[test]
fn the_panel_shows_offline_styles_a_disabled_prompt_and_why_it_cannot_run() {
let mut app = app();
let text = painted_text(&mut app, show);
// The provider's first and last styles stand for the check box of each.
let shown = [
"Offline Image Trace styles, made on this computer",
"Offline styles do not use prompts",
"Outline",
"Gray Tones",
"Detail",
"5 / 8",
"Generate",
];
for s in shown {
assert!(text.contains(s), "{s}: {text}");
}
app.run("select.none", json!({})).unwrap();
let text = painted_text(&mut app, show);
assert!(text.contains("select one image or an unexpanded Image Trace object"), "{text}");
}
/// Generate at once (no thread): a preview for each ticked style, every one ticked, the document
/// unchanged; Insert Selected puts the ticked ones beside the image as one undo step.
#[test]
fn generate_previews_every_style_and_insert_adds_the_ticked_ones_as_one_step() {
let mut app = app();
app.concept_runs.styles = vec!["outline".into(), "flatColor".into(), "grayTones".into()];
let (steps, roots) = (undo_steps(&app), root_count(&app));
generate(&mut app).unwrap();
assert_eq!((undo_steps(&app), root_count(&app)), (steps, roots), "Generate changes nothing");
let shown = app.concept_runs.shown.as_ref().expect("a job is shown");
let styles: Vec<&str> = shown.previews.iter().map(|p| p.style.as_str()).collect();
assert_eq!(styles, ["outline", "flatColor", "grayTones"]);
let painted = |p: &super::Preview| p.image.pixels.iter().any(|c| *c != Color32::WHITE);
assert!(shown.previews.iter().all(painted), "every style paints its preview");
assert_eq!(shown.picked.len(), 3);
let text = painted_text(&mut app, show);
assert!(text.contains("Insert Selected") && text.contains("Flat Color"), "{text}");
app.concept_runs.shown.as_mut().unwrap().picked = vec!["grayTones".into(), "outline".into()];
let v = insert(&mut app).unwrap();
assert_eq!(v["ids"].as_array().unwrap().len(), 2);
assert_eq!((undo_steps(&app), root_count(&app)), (steps + 1, roots + 2), "one step, two groups");
let st = app.session.doc().unwrap();
let names: Vec<Option<&str>> = st.selection.objects.iter().map(|id| st.doc.node(*id).and_then(|n| n.name.as_deref())).collect();
assert_eq!(names, [Some("Outline"), Some("Gray Tones")], "in the provider's order");
assert!(st.selection.objects.iter().all(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Group { .. }))));
app.run("edit.undo", json!({})).unwrap();
assert_eq!(root_count(&app), roots);
}
/// Closing the document drops its jobs, and the panel then stops showing the job's results and
/// Insert Selected.
#[test]
fn results_of_a_closed_document_are_no_longer_shown() {
let mut app = app();
generate(&mut app).unwrap();
let text = painted_text(&mut app, show);
assert!(text.contains("Insert Selected"), "{text}");
assert!(app.session.close_document(0));
let text = painted_text(&mut app, show);
assert!(!text.contains("Insert Selected"), "{text}");
assert!(app.concept_runs.shown.is_none());
}
/// The results show only while the document they were made in is the active one: in another
/// document neither they nor Insert Selected show, and they show again on going back.
#[test]
fn results_show_only_in_the_document_they_were_made_in() {
let mut app = app();
generate(&mut app).unwrap();
assert!(painted_text(&mut app, show).contains("Insert Selected"));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let text = painted_text(&mut app, show);
assert!(!text.contains("Insert Selected"), "{text}");
assert!(app.concept_runs.job().is_some(), "the job is kept");
assert!(app.session.set_active(0));
assert!(painted_text(&mut app, show).contains("Insert Selected"));
}
/// `ui.conceptVector.generate` is the panel's Generate: it shows the ticked styles of the selection
/// as the button does, and while they are made off the UI thread it says so.
#[test]
fn the_generate_command_makes_the_styles_as_the_button_does() {
let mut app = app();
app.concept_runs.styles = vec!["outline".into()];
assert!(menus::enabled(&app, GENERATE));
let v = app.run(GENERATE, json!({})).unwrap();
assert_eq!(v["running"], false);
assert_eq!(v["job"].as_u64(), app.concept_runs.job());
assert!(app.concept_runs.job().is_some());
app.concept_runs.off_the_ui_thread = true;
assert_eq!(app.run(GENERATE, json!({})).unwrap(), json!({"running": true}));
wait(&mut app);
app.run("select.none", json!({})).unwrap();
assert!(!menus::enabled(&app, GENERATE));
}
/// A provider whose every run waits until the test lets it go on, once per run.
struct Gated(std::sync::Mutex<std::sync::mpsc::Receiver<()>>);
impl Provider for Gated {
fn id(&self) -> &'static str {
"test.gated"
}
fn name(&self) -> &'static str {
"Gated"
}
fn capabilities(&self) -> Capabilities {
Capabilities {
image_input: true,
vector_output: true,
prompt: false,
raster_output: false,
offline: true,
styles: vec![Style { id: "g", label: "G" }],
}
}
fn generate(&self, r: &Request, _: Steps) -> Result<Vec<Variation>, ProviderError> {
self.0.lock().map_err(|_| ProviderError::Canceled)?.recv().map_err(|_| ProviderError::Canceled)?;
let sq = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
Ok(r.styles.iter().map(|s| Variation { style: s.clone(), ..one_path(&sq, Some([0; 3]), None) }).collect())
}
}
/// Generate after Cancel waits for the canceled run's thread to end before it starts its own, so
/// one thread makes styles at a time, and its results are the ones shown.
#[test]
fn generate_after_cancel_waits_for_the_canceled_thread() {
let mut app = app();
let (go, gate) = std::sync::mpsc::channel();
app.session.concept_providers_mut().register(Arc::new(Gated(std::sync::Mutex::new(gate)))).unwrap();
app.concept_runs.provider = "test.gated";
app.concept_runs.styles = vec!["g".into()];
app.concept_runs.off_the_ui_thread = true;
generate(&mut app).unwrap();
cancel(&mut app);
generate(&mut app).unwrap();
let queued = |app: &VectorcraftApp| matches!(app.concept_runs.running.as_ref().map(|r| &r.work), Some(Work::Queued(_)));
assert!(queued(&app), "the new run waits");
poll(&mut app);
assert!(queued(&app), "while the canceled thread is still going");
assert!(app.concept_runs.busy());
// The canceled run, then the new one, may go on.
go.send(()).unwrap();
go.send(()).unwrap();
while queued(&app) {
poll(&mut app);
std::thread::yield_now();
}
wait(&mut app);
let job = app.concept_runs.job().expect("the new run's results are shown");
assert!(app.session.concept_variations(job).is_some());
}
/// A preview that leaves part of its variation out says so under it; one that draws all of it
/// does not.
#[test]
fn a_preview_that_leaves_part_out_says_so() {
let square = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
assert!(!preview(&one_path(&square, Some([0; 3]), None), "s".into(), (100, 100)).cut);
let many: Vec<Point> = (0..PREVIEW_POINTS + 10).map(|i| Point::new((i % 100) as f64, (i / 1000) as f64)).collect();
assert!(preview(&one_path(&many, Some([0; 3]), None), "s".into(), (100, 100)).cut, "one long path");
let mut two = one_path(&square, Some([0; 3]), None);
let full: Vec<Point> = (0..PREVIEW_POINTS - 1).map(|i| Point::new((i % 100) as f64, (i / 1000) as f64)).collect();
two.paths.insert(0, one_path(&full, Some([0; 3]), None).paths.remove(0));
assert!(preview(&two, "s".into(), (100, 100)).cut, "a path past the limit");
// An open last path whose final segment is the one point past the limit.
let open: Vec<Point> = (0..=PREVIEW_POINTS).map(|i| Point::new((i % 100) as f64, (i / 1000) as f64)).collect();
let last = Variation {
style: "s".into(),
paths: vec![VectorPath {
path: PathData::single(SubPath::polyline(&open, false)),
fill: None,
stroke: Some(([0; 3], 1.0)),
square_caps: false,
}],
warnings: vec![],
};
assert!(preview(&last, "s".into(), (100, 100)).cut, "an open path's last segment past the limit");
let mut app = app();
let v = app.run("conceptVector.generate", json!({"provider": offline::ID, "styles": ["outline"]})).unwrap();
show_job(&mut app, &v);
app.concept_runs.shown.as_mut().unwrap().previews[0].cut = true;
assert!(painted_text(&mut app, show).contains("The preview leaves out part of this style"));
}
/// At most eight styles: a ninth tick is refused by the command, and none is refused too.
#[test]
fn no_style_or_too_many_are_refused() {
let mut app = app();
app.concept_runs.styles.clear();
let e = generate(&mut app).unwrap_err();
assert!(e.contains("must list 1 to 8 different style ids"), "{e}");
app.concept_runs.styles = (0..9).map(|_| "outline".to_string()).collect();
assert!(generate(&mut app).is_err());
assert!(app.concept_runs.shown.is_none());
}
/// Off the UI thread: Generate returns at once with the run going; its results are kept when it
/// ends. Cancel drops a run, and nothing is shown or changed.
#[test]
fn generate_runs_off_the_ui_thread_and_cancel_drops_it() {
let mut app = app();
app.concept_runs.off_the_ui_thread = true;
let steps = undo_steps(&app);
generate(&mut app).unwrap();
assert!(app.concept_runs.busy());
let text = painted_text(&mut app, show);
assert!(text.contains("Cancel"), "{text}");
wait(&mut app);
assert!(!app.concept_runs.busy());
let job = app.concept_runs.job().expect("results shown");
assert!(app.session.concept_variations(job).is_some());
app.concept_runs.shown = None;
generate(&mut app).unwrap();
cancel(&mut app);
assert!(!app.concept_runs.busy() && app.concept_runs.shown.is_none());
assert_eq!(undo_steps(&app), steps);
}
/// `ui.conceptVector.cancel` is the panel's Cancel: on while styles are being made, it stops them
/// and says so, and nothing is kept or shown.
#[test]
fn the_cancel_command_stops_a_run_as_the_button_does() {
let mut app = app();
app.concept_runs.off_the_ui_thread = true;
assert!(!menus::enabled(&app, CANCEL));
generate(&mut app).unwrap();
assert!(menus::enabled(&app, CANCEL));
assert_eq!(app.run(CANCEL, json!({})).unwrap(), json!({"canceled": 1}));
assert!(!app.concept_runs.busy() && !menus::enabled(&app, CANCEL));
assert_eq!(app.ui.status, vectorcraft_engine::EngineError::Cancelled.to_string());
poll(&mut app);
assert!(app.concept_runs.shown.is_none());
}
fn one_path(points: &[Point], fill: Option<[u8; 3]>, stroke: Option<([u8; 3], f64)>) -> Variation {
Variation {
style: "s".into(),
paths: vec![VectorPath { path: PathData::single(SubPath::polyline(points, true)), fill, stroke, square_caps: false }],
warnings: vec![],
}
}
/// A filled path paints its color inside its outline and leaves the rest white; a stroked one
/// paints its outline and leaves the inside white.
#[test]
fn previews_paint_fills_and_strokes() {
let square = [Point::new(25.0, 25.0), Point::new(75.0, 25.0), Point::new(75.0, 75.0), Point::new(25.0, 75.0)];
let red = [200, 20, 20];
let p = preview(&one_path(&square, Some(red), None), "s".into(), (100, 100));
let [w, h] = p.image.size;
let px = |p: &super::Preview, x: usize, y: usize| p.image.pixels[y * w + x];
assert_eq!(px(&p, w / 2, h / 2), Color32::from_rgb(200, 20, 20));
assert_eq!((px(&p, 2, 2), px(&p, w - 3, h - 3)), (Color32::WHITE, Color32::WHITE));
let p = preview(&one_path(&square, None, Some((red, 4.0))), "s".into(), (100, 100));
assert_eq!((px(&p, w / 2, h / 2), px(&p, 2, 2)), (Color32::WHITE, Color32::WHITE));
assert_eq!(px(&p, w / 2, h / 4), Color32::from_rgb(200, 20, 20), "the top edge");
}
/// The pixels a preview paints across the top edge of a square stroked `width` wide, in an image
/// 200 by 100 pixels.
fn stroke_cover(width: f64) -> usize {
let square = [Point::new(25.0, 25.0), Point::new(75.0, 25.0), Point::new(75.0, 75.0), Point::new(25.0, 75.0)];
let p = preview(&one_path(&square, None, Some(([0, 0, 0], width))), "s".into(), (200, 100));
let [w, h] = p.image.size;
let x = w / 4;
(0..h / 2).filter(|y| p.image.pixels[y * w + x] != Color32::WHITE).count()
}
/// Preview strokes are painted to scale with the image, and at least half a point wide.
#[test]
fn preview_strokes_keep_their_widths() {
// The image's 200 pixels are about 408 preview pixels wide: a 10-pixel stroke is about 20.
let (thin, thick) = (stroke_cover(1.0), stroke_cover(10.0));
assert!((19..=23).contains(&thick), "{thick}");
assert!((1..=4).contains(&thin), "{thin}");
assert!(stroke_cover(0.01) >= 1, "thin lines still show");
}
/// A line with square caps is painted to the corners of its ends, and one with round caps leaves
/// them white.
#[test]
fn preview_strokes_keep_their_caps() {
let line = PathData::single(SubPath::polyline(&[Point::new(25.0, 50.0), Point::new(75.0, 50.0)], false));
let corner = |square_caps: bool| {
let paths = vec![VectorPath { path: line.clone(), fill: None, stroke: Some(([0, 0, 0], 20.0)), square_caps }];
let p = preview(&Variation { style: "s".into(), paths, warnings: vec![] }, "s".into(), (100, 100));
let [w, h] = p.image.size;
// Past the line's right end, near the corner of a square cap: 8 and 8 pixels of the image.
p.image.pixels[(h * 58 / 100) * w + w * 83 / 100]
};
assert_eq!(corner(true), Color32::BLACK, "square caps");
assert_eq!(corner(false), Color32::WHITE, "round caps");
}
/// Paths are painted in their order: a fill above a stroke covers it, and a stroke above a fill
/// shows.
#[test]
fn previews_paint_paths_in_their_order() {
let square = [Point::new(25.0, 25.0), Point::new(75.0, 25.0), Point::new(75.0, 75.0), Point::new(25.0, 75.0)];
let cover = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
let path = |pts: &[Point]| PathData::single(SubPath::polyline(pts, true));
let stroke = VectorPath { path: path(&square), fill: None, stroke: Some(([0, 0, 0], 4.0)), square_caps: false };
let fill = VectorPath { path: path(&cover), fill: Some([200, 20, 20]), stroke: None, square_caps: false };
let on_edge = |paths: Vec<VectorPath>| {
let p = preview(&Variation { style: "s".into(), paths, warnings: vec![] }, "s".into(), (100, 100));
let [w, h] = p.image.size;
p.image.pixels[(h / 4) * w + w / 2]
};
assert_eq!(on_edge(vec![stroke.clone(), fill.clone()]), Color32::from_rgb(200, 20, 20), "the fill covers the stroke below it");
assert_eq!(on_edge(vec![fill, stroke]), Color32::BLACK, "the stroke shows above the fill");
}
/// A path's elements, made as they are taken, are the elements of its converted path.
#[test]
fn preview_elements_match_the_converted_path() {
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((10.0, 0.0));
bp.curve_to((15.0, 0.0), (20.0, 5.0), (20.0, 10.0));
bp.close_path();
bp.move_to((30.0, 30.0));
bp.line_to((40.0, 35.0));
let path = PathData::from_bezpath(&bp);
let made: Vec<_> = elements(&path).collect();
assert_eq!(made, path.to_bezpath().elements().to_vec());
assert_eq!(elements(&path).take(2).count(), 2);
}
/// A curve flattened into more points than are left ends the elements taken: those after it are
/// not flattened, while a closing element still closes the ring.
#[test]
fn preview_elements_stop_once_no_point_is_left() {
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((0.0, 0.0));
for i in 0..100 {
let x = f64::from(i) * 100.0;
bp.curve_to((x + 30.0, 400.0), (x + 70.0, -400.0), (x + 100.0, 0.0));
}
let path = PathData::from_bezpath(&bp);
let left = std::cell::Cell::new(10);
let taken = std::cell::Cell::new(0);
vectorcraft_geom::flatten(within_budget(elements(&path).inspect(|_| taken.set(taken.get() + 1)), &left), 0.25, |el| {
if matches!(el, vectorcraft_geom::PathEl::LineTo(_)) && left.get() > 0 {
left.set(left.get() - 1);
}
});
assert_eq!(left.get(), 0);
assert!(taken.get() <= 3, "{} elements taken", taken.get());
let closing = [vectorcraft_geom::PathEl::LineTo((1.0, 1.0).into()), vectorcraft_geom::PathEl::ClosePath];
assert_eq!(within_budget(closing.into_iter(), &left).count(), 0, "nothing is taken once none is left");
assert_eq!(within_budget(closing[1..].iter().copied(), &left).count(), 1, "but a ring still closes");
}
/// A preview of an image wider or taller than its box allows keeps the image's proportions, with
/// margins, instead of stretching the image to the box.
#[test]
fn a_preview_of_a_wide_or_tall_image_keeps_its_proportions() {
let square = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
for (size, aspect) in [((1000, 100), 10.0f32), ((100, 1000), 0.1)] {
let p = preview(&one_path(&square, Some([9, 9, 9]), None), "s".into(), size);
let [w, h] = p.image.size;
assert!(((w as f32 / h as f32) / aspect - 1.0).abs() < 0.06, "{size:?}: {w} x {h}");
let inner = Rect::from_min_size(Pos2::ZERO, vec2(preview_width(aspect, PREVIEW_H), PREVIEW_H)).shrink(4.0);
let art = art_rect(inner, aspect);
assert!(inner.expand(0.01).contains_rect(art), "{art:?} in {inner:?}");
assert!((art.aspect_ratio() / aspect - 1.0).abs() < 1e-3, "{art:?}");
assert!((art.center() - inner.center()).length() < 1e-3, "{art:?}");
}
}
/// One path with more points than a preview draws is cut off within the path: its points in the
/// top quarter are painted, and those past the limit, in the bottom quarter, are not.
#[test]
fn a_preview_stops_at_its_point_limit_within_one_path() {
let zigzag: Vec<Point> =
(0..PREVIEW_POINTS * 3).map(|i| Point::new((i % 100) as f64, if i < PREVIEW_POINTS { 10.0 } else { 90.0 } + (i % 2) as f64 * 0.5)).collect();
let mut path = one_path(&zigzag, None, Some(([0, 0, 0], 1.0)));
if let Some(sp) = path.paths[0].path.subpaths.first_mut() {
sp.closed = false;
}
let p = preview(&path, "s".into(), (100, 100));
let [w, h] = p.image.size;
let painted = |rows: std::ops::Range<usize>| rows.flat_map(|y| (0..w).map(move |x| y * w + x)).any(|i| p.image.pixels[i] != Color32::WHITE);
assert!(painted(0..h / 4), "the points before the limit");
assert!(!painted(h * 3 / 4..h), "the points past it");
}
/// As on the web (no thread): Generate returns with the run going and nothing made; each frame
/// makes one part (the image decoded, a style's color layers found, one layer traced), the styles
/// are made in order, and the last part's frame shows them all.
#[test]
fn on_the_web_generate_makes_one_part_a_frame() {
let mut app = app();
app.concept_runs.by_frames = true;
app.concept_runs.styles = vec!["outline".into(), "flatColor".into(), "grayTones".into()];
let (steps, roots) = (undo_steps(&app), root_count(&app));
generate(&mut app).unwrap();
assert!(app.concept_runs.busy() && app.concept_runs.shown.is_none());
assert_eq!(made_so_far(&app), Some(0), "made one part a frame, not on a thread");
let text = painted_text(&mut app, show);
assert!(text.contains("Cancel"), "{text}");
let mut seen = vec![];
while let Some(k) = made_so_far(&app) {
assert!(seen.len() < 1000, "the parts never end");
seen.push(k);
assert!(app.concept_runs.shown.is_none());
poll(&mut app);
}
assert!(seen.windows(2).all(|w| w[0] <= w[1]) && seen.contains(&1) && seen.contains(&2), "{seen:?}");
assert!(seen.len() > 3, "more than one part a style: {seen:?}");
assert!(!app.concept_runs.busy());
let shown = app.concept_runs.shown.as_ref().expect("results shown");
let styles: Vec<&str> = shown.previews.iter().map(|p| p.style.as_str()).collect();
assert_eq!(styles, ["outline", "flatColor", "grayTones"]);
assert!(app.session.concept_variations(shown.job).is_some());
assert_eq!((undo_steps(&app), root_count(&app)), (steps, roots), "Generate changes nothing");
}
/// On the web, Cancel takes effect inside a style: after the image's color layers are found and
/// one is traced, the run is dropped, and nothing is shown or changed.
#[test]
fn on_the_web_cancel_stops_a_style_part_way() {
let mut app = app();
app.concept_runs.by_frames = true;
app.concept_runs.styles = vec!["flatColor".into()];
let (steps, roots) = (undo_steps(&app), root_count(&app));
generate(&mut app).unwrap();
// The image decoded, its color layers found, and the first layer traced.
for _ in 0..3 {
poll(&mut app);
assert_eq!(made_so_far(&app), Some(0), "the one style is still being made");
}
cancel(&mut app);
poll(&mut app);
assert!(!app.concept_runs.busy() && app.concept_runs.shown.is_none());
assert_eq!((undo_steps(&app), root_count(&app)), (steps, roots));
}
/// A provider with one style, `sketch`, named "Pencil Sketch": a square for each style asked.
struct Sketches;
impl Provider for Sketches {
fn id(&self) -> &'static str {
"test.sketches"
}
fn name(&self) -> &'static str {
"Sketches"
}
fn capabilities(&self) -> Capabilities {
let styles = vec![Style { id: "sketch", label: "Pencil Sketch" }];
Capabilities { image_input: true, vector_output: true, prompt: false, raster_output: false, offline: true, styles }
}
fn generate(&self, r: &Request, _: Steps) -> Result<Vec<Variation>, ProviderError> {
let sq = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
Ok(r.styles.iter().map(|s| Variation { style: s.clone(), ..one_path(&sq, Some([0; 3]), None) }).collect())
}
}
/// The results of another provider are named as that provider names its styles.
#[test]
fn results_are_named_as_their_provider_names_its_styles() {
let mut app = app();
app.session.concept_providers_mut().register(Arc::new(Sketches)).unwrap();
let v = app.run("conceptVector.generate", json!({"provider": "test.sketches", "styles": ["sketch"]})).unwrap();
show_job(&mut app, &v);
let shown = app.concept_runs.shown.as_ref().expect("a job is shown");
let labels: Vec<&str> = shown.previews.iter().map(|p| p.label.as_str()).collect();
assert_eq!(labels, ["Pencil Sketch"]);
let text = painted_text(&mut app, show);
assert!(text.contains("Pencil Sketch"), "{text}");
}
/// Insert Selected after the image moved: the job no longer applies, and nothing changes.
#[test]
fn insert_after_the_image_moved_changes_nothing() {
let mut app = app();
generate(&mut app).unwrap();
app.run("object.transform", json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap();
let (steps, roots) = (undo_steps(&app), root_count(&app));
let e = insert(&mut app).unwrap_err();
assert!(e.contains("no longer applies"), "{e}");
assert_eq!((undo_steps(&app), root_count(&app)), (steps, roots));
}
+1 -1
View File
@@ -727,7 +727,7 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo
Row::new().wrap(true).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui);
let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0);
let shown = stop.map_or(100.0, |s| super::shown_percent(s.opacity));
let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown)))
.range(0.0..=100.0)
.unit("%")
@@ -361,6 +361,23 @@ fn an_unfinished_stop_value_does_not_reach_another_stop() {
assert_eq!((stops_of(&rig, a)[0].1, stops_of(&rig, b)[0].1), (1.0, 0.01), "the other object's stop takes 1%");
}
/// The arrow keys step a stop's Opacity by one percent at every press: 51% reads back from its f32 as 50.999999%, and
/// the next Up still goes to 52%, as 99% going Down goes to 98%.
#[test]
fn a_stops_opacity_steps_at_every_arrow_press() {
let mut app = app(json!({"gradient": {"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]}}));
app.run("gradient.selectStop", json!({"index": 0})).unwrap();
let mut rig = Rig::new(app);
let opacity = |rig: &Rig| fill(&rig.app()).gradient.stops[0].opacity;
for (start, key, steps) in [("50", Key::ArrowUp, [51.0, 52.0, 53.0]), ("100", Key::ArrowDown, [99.0, 98.0, 97.0])] {
rig.type_into("Opacity", start);
for percent in steps {
rig.fixture.key(key, Modifiers::NONE).settle();
assert_eq!(opacity(&rig), (percent / 100.0) as f32, "{key:?} from {start}% reaches {percent}%");
}
}
}
/// An unfinished value in a freeform point's Opacity or Spread field does not reach the next point selected, and one
/// in Angle does not reach another object's gradient.
#[test]
+3 -1
View File
@@ -312,7 +312,9 @@ mod tests {
app.run("view.setZoom", json!({"zoom": 100})).unwrap();
let mut panel = crate::tests::panel_harness::Panel::new(app, draw);
panel.app().ui.status.clear();
panel.type_into("Zoom", "80..2");
let decimal = craft::i18n::Format::new(&craft::i18n::Region::system(), craft::i18n::Digits::Latin).number_ungrouped(0.2, 1);
let mark = decimal.strip_prefix('0').unwrap().strip_suffix('2').unwrap();
panel.type_into("Zoom", &format!("80{mark}{mark}2"));
{
let app = panel.app();
assert!((app.view().unwrap().zoom - 0.8).abs() < 1e-9, "applies the valid prefix");
+1
View File
@@ -304,6 +304,7 @@ pub(crate) fn quick_actions(app: &mut VectorcraftApp) -> Vec<QuickAction> {
add(super::symbols::changed_instances_selected(app), tl!("Reset"), "symbol.instance.reset");
add(multi_color(app), tl!("Recolor"), "ui.recolorDialog");
add(is_image, tl!("Crop Image"), "ui.cropImage");
add(is_image, tl!("Concept to Vector"), crate::panels::concept_vector::OPEN);
add(is_image, tl!("Mask"), "object.maskImage");
// Remove Background at once with its defaults.
add(is_image, tl!("Remove Background"), crate::addons::image::REMOVE_BACKGROUND);
@@ -132,6 +132,21 @@ fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() {
assert_eq!((fill_opacity(&p.app()) * 100.0).round(), before + 1.0);
}
/// The arrow keys step the row's percent field by one percent at every press: 51% reads back from its f32 as
/// 50.999999%, and the next Up still goes to 52%, as 99% going Down goes to 98%.
#[test]
fn the_percent_field_steps_at_every_arrow_press() {
let mut p = Panel::new(app());
for (start, key, steps) in [(50.0, Key::ArrowUp, [51.0, 52.0, 53.0]), (100.0, Key::ArrowDown, [99.0, 98.0, 97.0])] {
p.run("paint.setFill", json!({"opacity": start}));
for percent in steps {
let t = field(&p);
p.fx.access(AccessActionKind::Focus, &t).key(key, Modifiers::NONE).idle(2);
assert_eq!(fill_opacity(&p.app()), (percent / 100.0) as f32, "{key:?} from {start}% reaches {percent}%");
}
}
}
/// Hiding the row during a drag on its slider keeps the opacity the drag previewed as one undo step
/// and leaves no interaction open.
#[test]
+1
View File
@@ -58,6 +58,7 @@ fn bar(app: &mut VectorcraftApp, ui: &mut Ui) {
pub(crate) fn reads(value: Option<String>, unit: Unit, pt: f64) -> bool {
value.is_some_and(|v| {
let Some(number) = v.strip_suffix(unit.suffix()).map(str::trim_end) else { return false };
let number = vectorcraft_doc::decimal_point(number);
let decimals = number.split_once('.').map_or(0, |(_, d)| d.len());
number.parse::<f64>().is_ok_and(|shown| (shown - unit.from_pt(pt)).abs() <= 0.5 * 10f64.powi(-(decimals as i32)) + 1e-9)
})
+1 -1
View File
@@ -20,7 +20,7 @@ fn pt(v: f64) -> String {
/// A shown angle, in degrees.
fn degrees(p: &Panel, name: &str) -> Option<f64> {
p.value(name)?.trim_end_matches('°').trim_end().parse().ok()
vectorcraft_doc::parse_number(&vectorcraft_doc::decimal_point(p.value(name)?.trim_end_matches('°').trim_end()))
}
/// The state of panel-menu row `id`, as the panel menus' states give it.
+62 -25
View File
@@ -111,6 +111,9 @@ pub struct PlaceState {
/// [`ASKED`]), with the automation roots the cursor was loaded in: its OK, pressed outside any
/// roots, places the file within them. Cleared when the cursor is loaded again.
asked: Option<(u64, std::sync::Arc<vectorcraft_engine::file_access::AutomationRoots>)>,
/// The size the loaded cursor's thumbnail and count took when last shown, which places them on the side of the
/// pointer where they fit ([`cursor_overlay`]).
cursor_size: Vec2,
}
/// The `file.place` param that ties an import options dialog's OK to the click of the place cursor
@@ -838,35 +841,66 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) {
.collect();
}
/// The loaded place cursor at `at` in the overlay layer `ui`: the current file's thumbnail with the
/// number of files loaded. A thumbnail is named by its place in the cursor's list, which
/// [`show_thumbnails`] replaces only together with a new load number.
pub fn cursor_overlay(app: &mut VectorcraftApp, ui: &mut egui::Ui, at: egui::Pos2) {
/// The loaded place cursor beside the pointer at `pointer`, `offset` from it, over `ui` (the canvas
/// `canvas`): the current file's thumbnail and, for a load of more than one file, the files left of
/// the load (`remaining/total`, `1/3` for the last of three). An empty cursor shows nothing. A
/// thumbnail is named by its place in the cursor's list, which [`show_thumbnails`] replaces only
/// together with a new load number.
pub(crate) fn cursor_overlay(app: &mut VectorcraftApp, ui: &mut egui::Ui, pointer: egui::Pos2, canvas: egui::Rect, offset: Vec2) {
let size = app.place.cursor_size;
let shown = show_cursor(app, ui, beside(pointer, offset, size, canvas)).unwrap_or(Vec2::ZERO);
// The first frame of a new size placed it by the old one.
if shown != size {
app.place.cursor_size = shown;
ui.ctx().request_repaint();
}
}
/// Where a box of `size` goes beside the pointer at `pointer` in `canvas`: `offset` below and to its
/// right, on an axis where that passes the canvas's edge `offset` above or to its left instead, and
/// inside the canvas where it fits on neither side.
fn beside(pointer: egui::Pos2, offset: Vec2, size: Vec2, canvas: egui::Rect) -> egui::Pos2 {
let axis = |at: f32, offset: f32, len: f32, min: f32, max: f32| {
let after = at + offset;
let start = if after + len > max { at - offset - len } else { after };
start.min(max - len).max(min)
};
egui::pos2(axis(pointer.x, offset.x, size.x, canvas.min.x, canvas.max.x), axis(pointer.y, offset.y, size.y, canvas.min.y, canvas.max.y))
}
/// [`cursor_overlay`]'s thumbnail and count with their top-left corner at `at`, and the size they
/// took; `None` for an empty cursor.
fn show_cursor(app: &VectorcraftApp, ui: &mut egui::Ui, at: egui::Pos2) -> Option<Vec2> {
let opts = app.session.tool_options();
let count = opts["count"].as_u64().unwrap_or(0);
if count == 0 {
return None;
}
let total = opts["total"].as_u64().unwrap_or(count).max(count);
let name = opts["name"].as_str().unwrap_or_default();
let found = (app.place.queue_load == app.session.place_queue_loads()).then(|| app.place.cursor_thumbnail(&opts)).flatten();
let revision = Revision::new(app.place.queue_load);
let room = egui::Rect::from_min_max(at, ui.max_rect().max.max(at));
ui.scope_builder(egui::UiBuilder::new().max_rect(room), |ui| {
match found {
Some((key, image)) => {
let side = |n: usize| u16::try_from(n.max(1)).unwrap_or(u16::MAX);
let [w, h] = image.size;
Picture::new(name.to_string(), key as u64, &|| image.clone())
.revision(revision)
.aspect(ThumbAspect::new(side(w), side(h)))
.extent(PictureSize::Thumb(ThumbSize::Medium))
.show(ui);
}
None => {
Text::new(name.to_string()).shade(Shade::Muted).show(ui);
}
let room = egui::Rect::from_min_max(at, ui.clip_rect().max.max(at));
// A child `Ui`: the overlay takes no room in the canvas's layout.
let ui = &mut ui.new_child(egui::UiBuilder::new().id_salt("place-cursor").max_rect(room));
match found {
Some((key, image)) => {
let side = |n: usize| u16::try_from(n.max(1)).unwrap_or(u16::MAX);
let [w, h] = image.size;
Picture::new(name.to_string(), key as u64, &|| image.clone())
.revision(revision)
.aspect(ThumbAspect::new(side(w), side(h)))
.extent(PictureSize::Thumb(ThumbSize::Medium))
.show(ui);
}
if count > 1 {
Badge::count(u32::try_from(count).unwrap_or(u32::MAX)).show(ui);
None => {
Text::new(name.to_string()).shade(Shade::Muted).show(ui);
}
});
}
if total > 1 {
Badge::new(format!("{count}/{total}")).show(ui);
}
Some(ui.min_rect().size())
}
// ---------- drops ----------
@@ -1317,9 +1351,12 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool
});
}
Row::new().fit_rank(rank::GROUP).show(ui, |ui, _| crate::panels::image_trace::trace_button(app, ui));
for (label, cmd) in
[(tl!("Mask"), "object.maskImage"), (tl!("Crop Image"), "ui.cropImage"), (tl!("Remove Background"), crate::addons::image::REMOVE_BACKGROUND)]
{
for (label, cmd) in [
(tl!("Mask"), "object.maskImage"),
(tl!("Crop Image"), "ui.cropImage"),
(tl!("Concept to Vector"), crate::panels::concept_vector::OPEN),
(tl!("Remove Background"), crate::addons::image::REMOVE_BACKGROUND),
] {
Row::new().fit_rank(rank::GROUP).show(ui, |ui, _| {
if clicked(&Button::new(label.to_string()).show(ui)) {
crate::menus::invoke(app, cmd, json!({}));
+2
View File
@@ -534,6 +534,7 @@ const GROUPS: &[(&str, &str)] = &[
("ui.colorGuideOptions", "Window › Color Guide"),
("ui.colorPicker", "Color"),
("ui.colorRgbPercent", "Window › Color"),
("ui.conceptVector.", "Window › Concept to Vector"),
("ui.corners", "Window › Transform"),
("ui.dialogReset", "Dialogs"),
("ui.dxfOptionsDialog", "File"),
@@ -3081,6 +3082,7 @@ mod tests {
assert_eq!(group("ui.recolorDialog").as_deref(), Some("Edit › Edit Colors"));
assert_eq!(group("ui.rename").as_deref(), Some("Window › Layers"));
assert_eq!(group("ui.justification").as_deref(), Some("Window › Paragraph"));
assert_eq!(group("ui.conceptVector.cancel").as_deref(), Some("Window › Concept to Vector"));
assert_eq!(group("addon.pathtools.cornerRemove").as_deref(), Some("Object › Plug-ins › Path Precision Tools"));
}
}
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more