diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 586deb604c..138d75ed61 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -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()); diff --git a/crates/engine/src/cmd/conceptvector.rs b/crates/engine/src/cmd/conceptvector.rs new file mode 100644 index 0000000000..469c0c1080 --- /dev/null +++ b/crates/engine/src/cmd/conceptvector.rs @@ -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>), + 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>, + provider: String, + outcome: Outcome, +} + +/// The session's providers and jobs. +pub(crate) struct ConceptState { + pub(crate) registry: cv::Registry, + jobs: VecDeque, + 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 { + 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 { + self.concept.jobs.clone() + } + + /// Puts back the jobs that [`Self::concept_jobs_snapshot`] took. + pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque) { + 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) { + 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, 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 = 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>)> { + 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, + /// 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 { + 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 = 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::>().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, 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 { + 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) -> Option { + 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>>, + /// The styles the provider's parts had made when last asked, inside the panic guard. + done: usize, + made: Vec, +} + +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 { + 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 { + 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 = 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 { + 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 { + 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 { + let list: Vec = 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 { + 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 { + 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 { + 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 { + 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::>().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 = 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 = 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, Vec) = 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 = 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 { + 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 = 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, Option)> = 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 = 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::>() })) +} + +#[cfg(test)] +thread_local! { + /// How many times [`place_row`] has looked at an object on this thread. + pub(crate) static LOOKS: std::cell::Cell = 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, start: f64, obstacles: &[Rect]) -> Option { + // 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> = row(start) + .iter() + .map(|b| { + let mut lane: Vec = 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::() { + 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 { + 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 + ), + ] +} diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 821c74acb0..a7e19bc0cb 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -14,7 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // 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 { } 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 { 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 { (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); } }; diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index fb9d2df26b..0bc243be41 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -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"), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 0cc69aced4..fa90cccf8e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -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", diff --git a/crates/engine/src/concept_vector.rs b/crates/engine/src/concept_vector.rs new file mode 100644 index 0000000000..da5ae76304 --- /dev/null +++ b/crates/engine/src/concept_vector.rs @@ -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