diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 39b39fc294..78927ef970 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -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> { + 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), diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 7c13b8f755..eb882f5e77 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -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) { - 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) { + clear(a, false); +} + +fn clear(a: &mut Arc, 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) { } } // 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); } } diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5b213f3b08..c4d3cd6bb4 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -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 { 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/draw2.rs b/crates/engine/src/cmd/draw2.rs index 71d41bde68..4311fdf290 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -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; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 32aa11172c..75d07fcaf5 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -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 { 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 { 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 { } 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() } diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 4ea2e723a3..46d862ae27 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "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 { "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 { "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 ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index f69ac40822..999953eb52 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -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(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result) -> Result { + 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)), 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/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index bd21723558..d434dcf6ec 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -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 // 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 } 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()) diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 005cc4a557..2dd408acdc 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -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 diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 6e63170f88..3c6343ebea 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -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); } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 536a533321..d16c871c48 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "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 { "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 { "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 { 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 { 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 { 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> { 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 { 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 { @@ -2639,6 +2654,27 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result { 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())); 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