mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge pull request #7051 from dotCooCoo/feat/concept-to-vector-providers
Concept to Vector: offline Image Trace styles behind a provider boundary
This commit is contained in:
36 files changed
+5104
-87
No files matched your search
@@ -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());
|
||||
|
||||
@@ -0,0 +1,830 @@
|
||||
//! Concept to Vector (`conceptVector.*`): vector variations of one selected image, made by a
|
||||
//! provider ([`crate::concept_vector`]), compared, and inserted beside the image.
|
||||
//!
|
||||
//! `conceptVector.generate` asks the named provider for one variation per style and keeps them as a
|
||||
//! job of this session; it changes nothing in the document. `conceptVector.insert` puts the chosen
|
||||
//! variations to the right of the image as one undo step. A job is kept until it is canceled, its
|
||||
//! document closes, or [`KEEP_JOBS`] newer ones replace it; it is never saved.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::buildcmds::TRACE_NAME;
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::shape_node;
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_id, cmd, has_doc, text_param};
|
||||
use crate::concept_vector::{self as cv, MAX_STYLES, Output, Provider, ProviderError, Request, Variation};
|
||||
|
||||
/// The most jobs a session keeps; a new one drops the oldest.
|
||||
pub const KEEP_JOBS: usize = 4;
|
||||
|
||||
/// The gap, in points, between the image and the first inserted variation, and between variations.
|
||||
pub const GAP: f64 = 24.0;
|
||||
|
||||
/// A job's variations, or that it was canceled.
|
||||
#[derive(Clone)]
|
||||
enum Outcome {
|
||||
Done(Arc<Vec<Variation>>),
|
||||
Canceled,
|
||||
}
|
||||
|
||||
/// What `conceptVector.generate` made, and what it was made of.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Job {
|
||||
id: u64,
|
||||
/// The document ([`crate::DocState::uid`]) and the object (an image or an Image Trace object).
|
||||
doc: u64,
|
||||
source: NodeId,
|
||||
image: ImageObject,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
provider: String,
|
||||
outcome: Outcome,
|
||||
}
|
||||
|
||||
/// The session's providers and jobs.
|
||||
pub(crate) struct ConceptState {
|
||||
pub(crate) registry: cv::Registry,
|
||||
jobs: VecDeque<Job>,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Default for ConceptState {
|
||||
fn default() -> Self {
|
||||
Self { registry: cv::Registry::default(), jobs: VecDeque::new(), next: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The Concept to Vector providers this session calls by id.
|
||||
pub fn concept_providers(&self) -> &cv::Registry {
|
||||
&self.concept.registry
|
||||
}
|
||||
|
||||
/// The providers, to register another ([`cv::Registry::register`]).
|
||||
pub fn concept_providers_mut(&mut self) -> &mut cv::Registry {
|
||||
&mut self.concept.registry
|
||||
}
|
||||
|
||||
/// Job `job`'s variations and the size in pixels of the image they were made of; `None` for a
|
||||
/// job this session does not keep, or one that was canceled.
|
||||
pub fn concept_variations(&self, job: u64) -> Option<(&[Variation], (u32, u32))> {
|
||||
let j = self.concept.jobs.iter().find(|j| j.id == job)?;
|
||||
match &j.outcome {
|
||||
Outcome::Done(v) => Some((v.as_slice(), (j.image.width, j.image.height))),
|
||||
Outcome::Canceled => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The document ([`crate::DocState::uid`]) job `job` was made in; `None` for a job this session
|
||||
/// does not keep.
|
||||
pub fn concept_job_doc(&self, job: u64) -> Option<u64> {
|
||||
self.concept.jobs.iter().find(|j| j.id == job).map(|j| j.doc)
|
||||
}
|
||||
|
||||
/// The jobs, for a batch to put back when a step fails. Job numbers are not reused.
|
||||
pub(crate) fn concept_jobs_snapshot(&self) -> VecDeque<Job> {
|
||||
self.concept.jobs.clone()
|
||||
}
|
||||
|
||||
/// Puts back the jobs that [`Self::concept_jobs_snapshot`] took.
|
||||
pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque<Job>) {
|
||||
self.concept.jobs = jobs;
|
||||
}
|
||||
|
||||
/// Exchanges the jobs with `jobs`: a script works on a copy of them, which becomes the
|
||||
/// session's only when the script ends without an error.
|
||||
pub(crate) fn swap_concept_jobs(&mut self, jobs: &mut VecDeque<Job>) {
|
||||
std::mem::swap(&mut self.concept.jobs, jobs);
|
||||
}
|
||||
|
||||
/// The number the next job gets.
|
||||
pub(crate) fn next_concept_job(&self) -> u64 {
|
||||
self.concept.next
|
||||
}
|
||||
|
||||
/// Takes in what the app did to the jobs while a script ran, `others` being the jobs as the app
|
||||
/// left them: a job canceled there is canceled here too, and the jobs numbered `from` or higher
|
||||
/// that this session does not keep (those the app made) are added. Then keeps the
|
||||
/// [`KEEP_JOBS`] newest of open documents.
|
||||
pub(crate) fn merge_concept_jobs(&mut self, others: VecDeque<Job>, from: u64) {
|
||||
for j in others {
|
||||
match self.concept.jobs.iter_mut().find(|k| k.id == j.id) {
|
||||
Some(k) if matches!(j.outcome, Outcome::Canceled) => k.outcome = Outcome::Canceled,
|
||||
Some(_) => {}
|
||||
None if j.id >= from => self.concept.jobs.push_back(j),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
self.concept.jobs.make_contiguous().sort_by_key(|j| j.id);
|
||||
self.prune_concept_jobs();
|
||||
while self.concept.jobs.len() > KEEP_JOBS {
|
||||
self.concept.jobs.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the jobs of document `doc` (its `uid`), when it closes.
|
||||
pub(crate) fn forget_concept_jobs(&mut self, doc: u64) {
|
||||
self.concept.jobs.retain(|j| j.doc != doc);
|
||||
}
|
||||
|
||||
/// Drops the jobs whose document is closed.
|
||||
/// In a batch, nothing is dropped until the batch ends without an error.
|
||||
pub(crate) fn prune_concept_jobs(&mut self) {
|
||||
if self.batch_stash.is_some() {
|
||||
return;
|
||||
}
|
||||
let open: Vec<u64> = self.documents().iter().map(|d| d.uid).collect();
|
||||
self.concept.jobs.retain(|j| open.contains(&j.doc));
|
||||
}
|
||||
}
|
||||
|
||||
/// The image `n` shows: its own, or the source image of an Image Trace object that wasn't expanded.
|
||||
fn shown_image(n: &Node) -> Option<&ImageObject> {
|
||||
match &shown_image_node(n)?.kind {
|
||||
NodeKind::Image(i) => Some(i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The image object [`shown_image`] reads: `n` itself, or the first member of its Image Trace object.
|
||||
fn shown_image_node(n: &Node) -> Option<&Node> {
|
||||
match &n.kind {
|
||||
NodeKind::Image(_) => Some(n),
|
||||
NodeKind::Group { clip: false, .. } if n.name.as_deref() == Some(TRACE_NAME) => {
|
||||
n.children()?.first().map(|i| &**i).filter(|i| matches!(i.kind, NodeKind::Image(_)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a group whose members are made or placed from data it holds (a graph, an Objects on
|
||||
/// Path, Shaper, dimension, flare or Live Paint group, a compound shape, a plug-in's generated
|
||||
/// art), so that a member added to it would be placed again, replaced or combined with the others?
|
||||
fn generated(n: &Node) -> bool {
|
||||
let e = n.extras();
|
||||
e.generated.is_some()
|
||||
|| e.graph.is_some()
|
||||
|| e.objects_on_path.is_some()
|
||||
|| e.shaper.is_some()
|
||||
|| e.dimension.is_some()
|
||||
|| e.flare.is_some()
|
||||
|| e.compound_shape
|
||||
|| vectorcraft_tools::builder::is_live_paint(n)
|
||||
}
|
||||
|
||||
const NO_SOURCE: &str = "select one image or an unexpanded Image Trace object";
|
||||
|
||||
const LOCKED: &str = "the image is locked or hidden";
|
||||
|
||||
/// The object `id` names, else the one selected: an image or an unexpanded Image Trace object,
|
||||
/// shown and unlocked with every layer and group around it, and not on a locked artboard → it, its
|
||||
/// image and the image's bytes.
|
||||
fn source(s: &Session, c: &str, p: &Value) -> Result<(NodeId, ImageObject, Arc<Vec<u8>>)> {
|
||||
let id = match p.get("id").filter(|v| !v.is_null()) {
|
||||
Some(v) => checked_id(s, v, c)?,
|
||||
None => match selected_roots(s)?.as_slice() {
|
||||
[one] => *one,
|
||||
_ => return Err(bad(c, NO_SOURCE)),
|
||||
},
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let image = shown_image(n).ok_or_else(|| bad(c, NO_SOURCE))?;
|
||||
if !d.is_editable(id) {
|
||||
return Err(bad(c, LOCKED));
|
||||
}
|
||||
let blob = d.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?;
|
||||
Ok((id, image.clone(), Arc::clone(&blob.bytes)))
|
||||
}
|
||||
|
||||
/// A generation prepared from the session, which runs without it ([`ConceptRun::run`]), on any
|
||||
/// thread, and is kept as a job with [`ConceptRun::finish`].
|
||||
pub struct ConceptRun {
|
||||
provider: Arc<dyn Provider>,
|
||||
/// The provider's id, as it was registered.
|
||||
provider_id: &'static str,
|
||||
request: Request,
|
||||
doc: u64,
|
||||
source: NodeId,
|
||||
image: ImageObject,
|
||||
}
|
||||
|
||||
impl ConceptRun {
|
||||
/// What `conceptVector.generate` with params `p` makes in the active document, checked as the
|
||||
/// command checks it.
|
||||
pub fn prepare(s: &Session, p: &Value) -> Result<ConceptRun> {
|
||||
const C: &str = "conceptVector.generate";
|
||||
let name = text_param(p, "provider", C)?.ok_or_else(|| bad(C, "missing `provider` (see conceptVector.providers)"))?;
|
||||
let found =
|
||||
s.concept.registry.get(name).ok_or_else(|| bad(C, format!("no Concept to Vector provider `{name}` (see conceptVector.providers)")))?;
|
||||
let (caps, pid, provider) = (&found.capabilities, found.id, Arc::clone(&found.provider));
|
||||
let styles_error = || bad(C, format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)"));
|
||||
// The count is checked before any id is copied or scanned for repeats.
|
||||
let styles: Vec<String> = match p.get("styles") {
|
||||
Some(Value::Array(a)) if (1..=MAX_STYLES).contains(&a.len()) => {
|
||||
a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<_>>().ok_or_else(styles_error)?
|
||||
}
|
||||
_ => return Err(styles_error()),
|
||||
};
|
||||
let known = |id: &String| caps.styles.iter().any(|st| st.id == id);
|
||||
let unique = styles.iter().enumerate().all(|(i, id)| !styles.get(..i).unwrap_or_default().contains(id));
|
||||
if !unique || !styles.iter().all(known) {
|
||||
return Err(styles_error());
|
||||
}
|
||||
let prompt = text_param(p, "prompt", C)?.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);
|
||||
// Results are vector paths, inserted as vector art, whatever else a provider makes.
|
||||
let output = match text_param(p, "output", C)? {
|
||||
None | Some("vector") => Output::Vector,
|
||||
Some(_) => return Err(bad(C, "`output` must be \"vector\"")),
|
||||
};
|
||||
if !caps.image_input {
|
||||
return Err(bad(C, format!("`{pid}` does not take an image")));
|
||||
}
|
||||
if !caps.vector_output {
|
||||
return Err(bad(C, format!("`{pid}` does not make vector art")));
|
||||
}
|
||||
if prompt.is_some() && !caps.prompt {
|
||||
return Err(bad(C, format!("`{pid}` takes no prompt")));
|
||||
}
|
||||
let detail = match p.get("detail") {
|
||||
None => 50,
|
||||
Some(v) => v.as_u64().filter(|d| *d <= 100).ok_or_else(|| bad(C, "`detail` must be a whole number from 0 to 100"))? as u8,
|
||||
};
|
||||
let (source, image, bytes) = source(s, C, p)?;
|
||||
let request = Request { image: bytes, width: image.width, height: image.height, prompt, styles, detail, output };
|
||||
Ok(ConceptRun { provider, provider_id: pid, request, doc: s.doc()?.uid, source, image })
|
||||
}
|
||||
|
||||
/// The document it was prepared in ([`crate::DocState::uid`]).
|
||||
pub fn doc(&self) -> u64 {
|
||||
self.doc
|
||||
}
|
||||
|
||||
/// The image or Image Trace object it makes variations of.
|
||||
pub fn source(&self) -> NodeId {
|
||||
self.source
|
||||
}
|
||||
|
||||
/// Asks the provider for the variations and checks them ([`cv::check_result`]), telling `steps`
|
||||
/// how far it has got; it touches no document. A panic in the provider is an error.
|
||||
pub fn run(&self, steps: cv::Steps) -> std::result::Result<Vec<Variation>, ProviderError> {
|
||||
let made = crate::guard::catch_panic(|| self.provider.generate(&self.request, steps)).map_err(ProviderError::Internal)??;
|
||||
cv::check_result(&self.request, &made)?;
|
||||
Ok(made)
|
||||
}
|
||||
|
||||
/// How many styles it makes.
|
||||
pub fn style_count(&self) -> usize {
|
||||
self.request.styles.len()
|
||||
}
|
||||
|
||||
/// Does the next part of the run kept in `run`, for a caller with no thread for
|
||||
/// [`ConceptRun::run`] (the web build), which can run other work, or stop, between the parts
|
||||
/// → whether every style is made ([`PartRun::made`]). A provider that makes parts
|
||||
/// ([`cv::Provider::parts`]) does one of its own; the others make one style alone, and the
|
||||
/// styles made so far are checked together ([`cv::check_result`]) after each one, so the
|
||||
/// totals stop the run as soon as they are passed. A panic in the provider is an error.
|
||||
pub fn run_part(&self, run: &mut PartRun, steps: cv::Steps) -> std::result::Result<bool, ProviderError> {
|
||||
let guard = ProviderError::Internal;
|
||||
if run.parts.is_none() {
|
||||
run.parts = Some(crate::guard::catch_panic(|| self.provider.parts(&self.request)).map_err(guard)?);
|
||||
}
|
||||
if let Some(Some(parts)) = &mut run.parts {
|
||||
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
|
||||
if !steps(run.done as u64, self.style_count() as u64) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
let Some(made) = crate::guard::catch_panic(|| parts.step()).map_err(guard)?? else {
|
||||
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
|
||||
return Ok(false);
|
||||
};
|
||||
cv::check_result(&self.request, &made)?;
|
||||
run.made = made;
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(style) = self.request.styles.get(run.made.len()) else { return Ok(true) };
|
||||
let one = Request { styles: vec![style.clone()], ..self.request.clone() };
|
||||
let next = crate::guard::catch_panic(|| self.provider.generate(&one, steps)).map_err(guard)??;
|
||||
cv::check_result(&one, &next)?;
|
||||
// A style that takes the totals past their limits is dropped, so `run` keeps only the
|
||||
// styles that passed.
|
||||
let kept = run.made.len();
|
||||
run.made.extend(next);
|
||||
let so_far = Request { styles: self.request.styles.get(..run.made.len()).unwrap_or_default().to_vec(), ..one };
|
||||
if let Err(e) = cv::check_result(&so_far, &run.made) {
|
||||
run.made.truncate(kept);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(run.made.len() == self.request.styles.len())
|
||||
}
|
||||
|
||||
/// Keeps `variations` as a new job of `s` → the job, as `conceptVector.results` gives it;
|
||||
/// `None`, keeping nothing, when the document it was prepared in has closed.
|
||||
pub fn finish(self, s: &mut Session, variations: Vec<Variation>) -> Option<Value> {
|
||||
s.prune_concept_jobs();
|
||||
if !s.documents().iter().any(|d| d.uid == self.doc) {
|
||||
return None;
|
||||
}
|
||||
let id = s.concept.next;
|
||||
s.concept.next += 1;
|
||||
let job = Job {
|
||||
id,
|
||||
doc: self.doc,
|
||||
source: self.source,
|
||||
image: self.image,
|
||||
bytes: self.request.image,
|
||||
provider: self.provider_id.to_string(),
|
||||
outcome: Outcome::Done(Arc::new(variations)),
|
||||
};
|
||||
let out = job_json(&s.concept.registry, &job);
|
||||
s.concept.jobs.push_back(job);
|
||||
while s.concept.jobs.len() > KEEP_JOBS {
|
||||
s.concept.jobs.pop_front();
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a run made a part at a time ([`ConceptRun::run_part`]) has got.
|
||||
#[derive(Default)]
|
||||
pub struct PartRun {
|
||||
/// The provider's parts, once asked for (`None` inside: it makes one style at a time).
|
||||
parts: Option<Option<Box<dyn cv::Parts>>>,
|
||||
/// The styles the provider's parts had made when last asked, inside the panic guard.
|
||||
done: usize,
|
||||
made: Vec<Variation>,
|
||||
}
|
||||
|
||||
impl PartRun {
|
||||
/// The styles made so far.
|
||||
pub fn styles_done(&self) -> usize {
|
||||
if self.made.is_empty() { self.done } else { self.made.len() }
|
||||
}
|
||||
|
||||
/// The variations made: all of them once [`ConceptRun::run_part`] has said so.
|
||||
pub fn made(self) -> Vec<Variation> {
|
||||
self.made
|
||||
}
|
||||
}
|
||||
|
||||
/// `e` as the engine's error.
|
||||
pub fn provider_error(e: ProviderError) -> EngineError {
|
||||
match e {
|
||||
ProviderError::Canceled => EngineError::Cancelled,
|
||||
e => EngineError::Other(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The English name of style `style` of provider `provider`, else the id.
|
||||
fn style_label(registry: &cv::Registry, provider: &str, style: &str) -> String {
|
||||
let caps = registry.get(provider).map(|p| &p.capabilities);
|
||||
caps.and_then(|c| c.styles.iter().find(|s| s.id == style).map(|s| s.label.to_string())).unwrap_or_else(|| style.to_string())
|
||||
}
|
||||
|
||||
/// Where `style` comes in the styles `provider` lists; after them when it lists no such style.
|
||||
fn style_rank(registry: &cv::Registry, provider: &str, style: &str) -> usize {
|
||||
let caps = registry.get(provider).map(|p| &p.capabilities);
|
||||
caps.and_then(|c| c.styles.iter().position(|s| s.id == style)).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// Where `image`'s pixels lie in the document.
|
||||
fn image_rect(image: &ImageObject) -> Option<Rect> {
|
||||
let r = Rect::new(0.0, 0.0, f64::from(image.width.max(1)), f64::from(image.height.max(1)));
|
||||
let pts = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| image.xf * kurbo::Point::new(x, y));
|
||||
let mut out = Rect::from_points(pts[0], pts[0]);
|
||||
for q in &pts[1..] {
|
||||
out = out.union_pt(*q);
|
||||
}
|
||||
[out.x0, out.y0, out.x1, out.y1].iter().all(|v| v.is_finite()).then_some(out)
|
||||
}
|
||||
|
||||
fn job_json(registry: &cv::Registry, j: &Job) -> Value {
|
||||
let (state, variations) = match &j.outcome {
|
||||
Outcome::Done(v) => ("done", v.as_slice()),
|
||||
Outcome::Canceled => ("canceled", &[][..]),
|
||||
};
|
||||
let variations: Vec<Value> = variations
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let bounds = v.paths.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b));
|
||||
json!({
|
||||
"style": v.style,
|
||||
"label": style_label(registry, &j.provider, &v.style),
|
||||
"paths": v.paths.len(),
|
||||
"anchors": v.anchors(),
|
||||
"bounds": bounds.map(|b| [b.x0, b.y0, b.x1, b.y1]),
|
||||
"warnings": v.warnings,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({ "job": j.id, "provider": j.provider, "source": j.source.0, "state": state, "variations": variations })
|
||||
}
|
||||
|
||||
/// The `job` param of command `c`.
|
||||
fn job_param(c: &str, p: &Value) -> Result<u64> {
|
||||
p.get("job").and_then(Value::as_u64).ok_or_else(|| bad(c, "`job` must be a job number from conceptVector.generate"))
|
||||
}
|
||||
|
||||
/// The error of command `c` for a job the session does not keep.
|
||||
fn no_job(c: &str, job: u64) -> EngineError {
|
||||
bad(c, format!("no Concept to Vector job {job}: it was never made, or was dropped (see conceptVector.results)"))
|
||||
}
|
||||
|
||||
/// The index of job `job` among those `s` keeps.
|
||||
fn job_index(s: &mut Session, c: &str, job: u64) -> Result<usize> {
|
||||
s.prune_concept_jobs();
|
||||
s.concept.jobs.iter().position(|j| j.id == job).ok_or_else(|| no_job(c, job))
|
||||
}
|
||||
|
||||
fn providers(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let list: Vec<Value> = s
|
||||
.concept
|
||||
.registry
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let c = &p.capabilities;
|
||||
json!({
|
||||
"id": p.id,
|
||||
"name": p.name,
|
||||
"available": true,
|
||||
"offline": c.offline,
|
||||
"imageInput": c.image_input,
|
||||
"vectorOutput": c.vector_output,
|
||||
"prompt": c.prompt,
|
||||
"rasterOutput": c.raster_output,
|
||||
"maxStyles": MAX_STYLES,
|
||||
"styles": c.styles,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let selected = s.concept.registry.iter().next().map(|p| p.id);
|
||||
Ok(json!({ "providers": list, "selected": selected }))
|
||||
}
|
||||
|
||||
fn generate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let run = ConceptRun::prepare(s, p)?;
|
||||
// A script's run stops when the script is asked to stop, and keeps no job.
|
||||
let stop = s.script_in_run.then(|| s.script_interrupt());
|
||||
let stopped = || stop.as_ref().is_some_and(|i| i.is_set());
|
||||
let made = run.run(&|_, _| !stopped()).map_err(provider_error)?;
|
||||
if stopped() {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
run.finish(s, made).ok_or(EngineError::NoDocument)
|
||||
}
|
||||
|
||||
fn results(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.results";
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
|
||||
Ok(job_json(&s.concept.registry, j))
|
||||
}
|
||||
|
||||
/// The error of an insert or cancel played from recorded steps: a job lives only in this session,
|
||||
/// and a job number from another one may name other results.
|
||||
const REPLAYED: &str = "Concept to Vector jobs are not saved, so a recorded insert or cancel does not play again: generate again";
|
||||
|
||||
fn cancel(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.cancel";
|
||||
if s.replaying() {
|
||||
return Err(bad(C, REPLAYED));
|
||||
}
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
if let Some(j) = s.concept.jobs.get_mut(at) {
|
||||
j.outcome = Outcome::Canceled;
|
||||
}
|
||||
Ok(json!({ "job": job, "state": "canceled" }))
|
||||
}
|
||||
|
||||
/// The appearance of variation path `p`, its widths scaled by `unit` (points per pixel).
|
||||
fn appearance_of(p: &cv::VectorPath, unit: f64) -> Appearance {
|
||||
let solid = |c: [u8; 3]| Paint::solid(Color::rgb8(c[0], c[1], c[2]));
|
||||
let mut items = vec![];
|
||||
if let Some(c) = p.fill {
|
||||
items.push(AppearanceItem::Fill(FillLayer::new(solid(c))));
|
||||
}
|
||||
if let Some((c, w)) = p.stroke {
|
||||
let cap = if p.square_caps { LineCap::Square } else { LineCap::Round };
|
||||
items.push(AppearanceItem::Stroke(StrokeLayer { cap, join: LineJoin::Round, ..StrokeLayer::new(solid(c), w * unit) }));
|
||||
}
|
||||
Appearance { items, ..Default::default() }
|
||||
}
|
||||
|
||||
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.insert";
|
||||
if s.replaying() {
|
||||
return Err(bad(C, REPLAYED));
|
||||
}
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
let list_error = || bad(C, format!("`variations` must list different style ids of job {job}"));
|
||||
let listed = match p.get("variations") {
|
||||
Some(Value::Array(a)) if !a.is_empty() => a,
|
||||
_ => return Err(list_error()),
|
||||
};
|
||||
let stale = || bad(C, format!("job {job} no longer applies: its document, image or image placement changed, so generate again"));
|
||||
let (doc, source, image, bytes, picked, label_of) = {
|
||||
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
|
||||
let Outcome::Done(all) = &j.outcome else { return Err(bad(C, format!("job {job} has no results to insert: it was canceled"))) };
|
||||
// The count is checked before the ids are read or scanned for repeats.
|
||||
if listed.len() > all.len() {
|
||||
return Err(list_error());
|
||||
}
|
||||
let chosen: Vec<&str> = listed.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(list_error)?;
|
||||
let unique = chosen.iter().enumerate().all(|(i, id)| !chosen.get(..i).unwrap_or_default().contains(id));
|
||||
let mut picked: Vec<Variation> = all.iter().filter(|v| chosen.contains(&v.style.as_str())).cloned().collect();
|
||||
if !unique || picked.len() != chosen.len() {
|
||||
return Err(list_error());
|
||||
}
|
||||
// In the provider's order, whatever order they were listed or generated in.
|
||||
picked.sort_by_key(|v| style_rank(&s.concept.registry, &j.provider, &v.style));
|
||||
let labels: Vec<String> = picked.iter().map(|v| style_label(&s.concept.registry, &j.provider, &v.style)).collect();
|
||||
(j.doc, j.source, j.image.clone(), Arc::clone(&j.bytes), picked, labels)
|
||||
};
|
||||
// The same document, the same object showing the same pixels where they were.
|
||||
let st = s.doc()?;
|
||||
let now = st.doc.node(source).and_then(shown_image);
|
||||
let same_pixels = || st.doc.images.get(&image.key).is_some_and(|b| Arc::ptr_eq(&b.bytes, &bytes) || *b.bytes == *bytes);
|
||||
let current = st.uid == doc && now.is_some_and(|i| i.key == image.key && i.xf == image.xf && i.width == image.width && i.height == image.height);
|
||||
if !current || !same_pixels() {
|
||||
return Err(stale());
|
||||
}
|
||||
if !st.doc.is_editable(source) {
|
||||
return Err(bad(C, LOCKED));
|
||||
}
|
||||
// The results go above the outermost group around the image that clips or masks it, so that
|
||||
// it hides none of them, and above the outermost envelope, blend, repeat or other live object,
|
||||
// the outermost group whose members it makes or places ([`generated`]), and the outermost
|
||||
// group with effects or fills and strokes of its own, so that its content and the place its
|
||||
// effects measure from stay as they are. A layer that clips or masks its art, or has effects,
|
||||
// fills or strokes of its own, leaves them nowhere to go. An effect that moves or reshapes
|
||||
// the image, its own or a group's around it, shows it away from its placement, which the
|
||||
// results are placed by.
|
||||
let ancestry = st.doc.ancestry(source).ok_or_else(stale)?;
|
||||
let moves = |id: &NodeId| st.doc.node(*id).is_some_and(|n| !n.is_layer() && vectorcraft_render::effects::has_geometry(&n.appearance.effects));
|
||||
if ancestry.iter().any(moves) {
|
||||
return Err(bad(C, "the image or a group around it has effects that move or reshape it, so the results would not go beside it"));
|
||||
}
|
||||
// A distorted image ([`Node::image_quad`]) is drawn at its corners, not by its transform.
|
||||
if st.doc.node(source).and_then(shown_image_node).is_some_and(Node::is_distorted_image) {
|
||||
return Err(bad(C, "the image is distorted, so the results would not go beside it"));
|
||||
}
|
||||
let mut anchor = source;
|
||||
for &id in ancestry.iter().rev().skip(1) {
|
||||
let n = st.doc.node(id).ok_or_else(stale)?;
|
||||
let masked = n.extras().mask.as_ref().is_some_and(|m| !m.disabled);
|
||||
if matches!(n.kind, NodeKind::Layer { clip: true, .. }) {
|
||||
return Err(bad(C, "the image is on a layer with a clipping mask, which would hide the results"));
|
||||
}
|
||||
if n.is_layer() && masked {
|
||||
return Err(bad(C, "the image is on a layer with an opacity mask, which would hide the results"));
|
||||
}
|
||||
let styled = !n.appearance.items.is_empty() || !n.appearance.effects.is_empty();
|
||||
if n.is_layer() && !n.appearance.effects.is_empty() {
|
||||
return Err(bad(C, "the image is on a layer with effects of its own, which would apply to the results"));
|
||||
}
|
||||
// A layer's fills and strokes paint over its members, the results included.
|
||||
if n.is_layer() && !n.appearance.items.is_empty() {
|
||||
return Err(bad(C, "the image is on a layer with fills or strokes of its own, which would apply to the results"));
|
||||
}
|
||||
let live = !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || generated(n);
|
||||
if !n.is_layer() && (masked || live || styled || matches!(n.kind, NodeKind::Group { clip: true, .. })) {
|
||||
anchor = id;
|
||||
}
|
||||
}
|
||||
let src = image_rect(&image).ok_or_else(stale)?;
|
||||
// A variation with no paths adds nothing: it is left out, and with none left nothing changes.
|
||||
let (picked, label_of): (Vec<Variation>, Vec<String>) = picked.into_iter().zip(label_of).filter(|(v, _)| !v.paths.is_empty()).unzip();
|
||||
if picked.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let unit = image.xf.determinant().abs().sqrt();
|
||||
// Each chosen variation's box over the image: the image's box and the variation's painted
|
||||
// bounds, which may reach past it. A square cap's corner lies half the width along the path
|
||||
// and half across it from the end, so up to √2 times half the width past it on an axis.
|
||||
let boxes: Vec<Rect> = picked
|
||||
.iter()
|
||||
.map(|v| {
|
||||
v.paths
|
||||
.iter()
|
||||
.filter_map(|vp| {
|
||||
let reach = if vp.square_caps { std::f64::consts::SQRT_2 } else { 1.0 };
|
||||
let half = vp.stroke.map_or(0.0, |(_, w)| w * unit / 2.0 * reach);
|
||||
vp.path.transformed(image.xf).bounds().map(|b| b.inflate(half, half))
|
||||
})
|
||||
.fold(src, |a, b| a.union(b))
|
||||
})
|
||||
.collect();
|
||||
// How far each variation's box is moved past the first's: each box starts GAP to the right of
|
||||
// the one before it (`width + GAP` further right for boxes the image's size).
|
||||
let mut offsets = Vec::with_capacity(boxes.len());
|
||||
let mut next = 0.0;
|
||||
for (k, b) in boxes.iter().enumerate() {
|
||||
if let Some(prev) = k.checked_sub(1).and_then(|j| boxes.get(j)) {
|
||||
next += prev.x1 - b.x0 + GAP;
|
||||
}
|
||||
offsets.push(next);
|
||||
}
|
||||
// The first box's left edge, which may lie left of the image's where its variation paints there.
|
||||
let first = boxes.first().map_or(src.x0, |b| b.x0);
|
||||
// The boxes with the first one's left edge moved to `x0`, the others after it.
|
||||
let row = |x0: f64| -> Vec<Rect> {
|
||||
boxes
|
||||
.iter()
|
||||
.zip(&offsets)
|
||||
.map(|(b, off)| {
|
||||
let dx = x0 + off - first;
|
||||
Rect::new(b.x0 + dx, b.y0, b.x1 + dx, b.y1)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The painted bounds of every visible object (the source's too: an Image Trace object's traced
|
||||
// art and effects can reach past the image), and the image's own box. A layer or group that
|
||||
// paints nothing of its own is measured by its members (an opacity mask only hides them); one
|
||||
// that clips, by its members after the clipping path, cut to what it paints.
|
||||
let mut obstacles: Vec<Rect> = vec![src];
|
||||
// One lookup of the symbols for the whole walk, so each symbol's art is measured once.
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let mut stack: Vec<(&Arc<Node>, Option<Rect>)> = st.doc.layers.iter().map(|l| (l, None)).collect();
|
||||
while let Some((node, within)) = stack.pop() {
|
||||
if !node.visible {
|
||||
continue;
|
||||
}
|
||||
let cut = |b: Rect| match within {
|
||||
Some(w) => Some(b.intersect(w)).filter(|i| i.width() > 0.0 && i.height() > 0.0),
|
||||
None => Some(b),
|
||||
};
|
||||
let painted = || vectorcraft_render::painted_bounds_with(&symbols, node).and_then(cut);
|
||||
if node.id == source {
|
||||
obstacles.extend(painted());
|
||||
continue;
|
||||
}
|
||||
let clips = matches!(node.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
let by_members = (node.is_layer() || matches!(node.kind, NodeKind::Group { .. }))
|
||||
&& node.appearance.items.is_empty()
|
||||
&& node.appearance.effects.is_empty();
|
||||
if by_members {
|
||||
// A clipping path paints its fills and strokes when they are set (`Node::clip_paint`),
|
||||
// its strokes outside the clip too, whether or not it is shown.
|
||||
if clips && let Some(path) = node.children().into_iter().flatten().next() {
|
||||
let paint = path.clip_paint();
|
||||
for part in [paint.fill, paint.stroke].into_iter().flatten() {
|
||||
if let Some(b) = vectorcraft_render::painted_bounds_with(&symbols, &part).and_then(cut) {
|
||||
obstacles.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
let within = if clips {
|
||||
// Nothing of a clipping group shows outside what it paints.
|
||||
let Some(shown) = painted() else { continue };
|
||||
Some(shown)
|
||||
} else {
|
||||
within
|
||||
};
|
||||
stack.extend(node.children().into_iter().flatten().skip(usize::from(clips)).map(|c| (c, within)));
|
||||
} else if let Some(b) = painted() {
|
||||
obstacles.push(b);
|
||||
}
|
||||
}
|
||||
let placed = place_row(&row, src.x1 + GAP, &obstacles);
|
||||
let room = || bad(C, "there is no room for the results to the right of the image");
|
||||
let Some(x0) = placed.filter(|x0| x0.is_finite()) else {
|
||||
return Err(room());
|
||||
};
|
||||
let right = row(x0).iter().map(|r| r.x1).fold(f64::NEG_INFINITY, f64::max);
|
||||
if right > crate::MAX_COORD {
|
||||
return Err(room());
|
||||
}
|
||||
let ids = s.edit("Concept to Vector", |d, sel| {
|
||||
let mut groups = vec![];
|
||||
for ((v, label), off) in picked.into_iter().zip(label_of).zip(&offsets) {
|
||||
let dx = x0 + off - first;
|
||||
let xf = Affine::translate((dx, 0.0)) * image.xf;
|
||||
let mut members = Vec::with_capacity(v.paths.len());
|
||||
for vp in &v.paths {
|
||||
let path = vp.path.transformed(xf);
|
||||
if path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().any(|c| c.abs() > crate::MAX_COORD)) {
|
||||
return Err(room());
|
||||
}
|
||||
let mut node = shape_node(d, path, None);
|
||||
node.appearance = appearance_of(vp, unit).into();
|
||||
members.push(Arc::new(node));
|
||||
}
|
||||
let mut g = Node::group(d.alloc_id(), members);
|
||||
g.name = Some(label);
|
||||
groups.push(g);
|
||||
}
|
||||
let ids: Vec<NodeId> = groups.iter().map(|g| g.id).collect();
|
||||
d.insert_beside(vec![(anchor, groups)], false)?;
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`place_row`] has looked at an object on this thread.
|
||||
pub(crate) static LOOKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Where the left edge of the row's first box goes, from `start` rightward, so that no box meets
|
||||
/// one of `obstacles`: a box in the way moves GAP past the rightmost object it meets. `row(x0)`
|
||||
/// gives the boxes with the first one's left edge at `x0`. `None` when the moves run out.
|
||||
pub(crate) fn place_row(row: &dyn Fn(f64) -> Vec<Rect>, start: f64, obstacles: &[Rect]) -> Option<f64> {
|
||||
// Each box's objects: those level with it, by their left edges. The row only moves right, so
|
||||
// each object joins its box's list once, when the box's right edge passes its left edge, and
|
||||
// stays: of those joined, only the rightmost right edge matters, and the box meets that object
|
||||
// exactly when the edge is right of the box's left edge.
|
||||
let lanes: Vec<Vec<Rect>> = row(start)
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let mut lane: Vec<Rect> = obstacles.iter().filter(|o| o.y0 < b.y1 && b.y0 < o.y1).copied().collect();
|
||||
lane.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||
lane
|
||||
})
|
||||
.collect();
|
||||
let mut joined = vec![0usize; lanes.len()];
|
||||
let mut reach = vec![f64::NEG_INFINITY; lanes.len()];
|
||||
let mut x0 = start;
|
||||
// Each move takes a box past every object joined to it, so another move of that box needs a
|
||||
// new object to join.
|
||||
for _ in 0..=lanes.iter().map(Vec::len).sum::<usize>() {
|
||||
let mut shift = None;
|
||||
for ((r, lane), (j, far)) in row(x0).iter().zip(&lanes).zip(joined.iter_mut().zip(reach.iter_mut())) {
|
||||
while let Some(o) = lane.get(*j).filter(|o| o.x0 < r.x1) {
|
||||
#[cfg(test)]
|
||||
LOOKS.with(|n| n.set(n.get() + 1));
|
||||
*far = far.max(o.x1);
|
||||
*j += 1;
|
||||
}
|
||||
// The first box in the way, moved past the rightmost object it meets.
|
||||
if shift.is_none() && *far > r.x0 {
|
||||
shift = Some(*far + GAP - r.x0);
|
||||
}
|
||||
}
|
||||
match shift {
|
||||
None => return Some(x0),
|
||||
Some(by) => x0 += by,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "conceptVector.providers",
|
||||
"Concept to Vector Providers",
|
||||
[],
|
||||
None,
|
||||
"{} → {providers: [{id, name, available, offline, imageInput, vectorOutput, prompt, rasterOutput, maxStyles: 8, styles: [{id, label}]}], selected: the id the panel uses} the providers conceptVector.generate can call by id; the built-in offline.traceStyles makes its styles with Image Trace on this computer (outline, inkLines, flatColor, detailedColor, grayTones), takes no prompt and makes vector art only",
|
||||
always,
|
||||
providers
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.generate",
|
||||
"Generate Concept to Vector Styles",
|
||||
[],
|
||||
None,
|
||||
"{id?: image or unexpanded Image Trace object (default: the one selected object), provider: id (conceptVector.providers; no other provider is used in its place), styles: [style id…] (1 to 8 different ids of that provider), detail?: 0-100 (50: how much of the image's detail each style keeps), prompt?: text (an error for a provider without prompts unless empty), output?: \"vector\" (the only output; any other value is an error)} one variation of the image for each style, kept by this session as a job and not put in the document; a provider that takes no image, makes no vector art or takes no prompt when one is given is refused with that reason; an object that is locked or hidden, itself or by a layer or group around it, or on a locked artboard, is refused → {job, provider, source: id, state: \"done\", variations: [{style, label, paths, anchors, bounds: [x0,y0,x1,y1] in the image's pixels, warnings: [text…]}]}",
|
||||
has_doc,
|
||||
generate
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.results",
|
||||
"Concept to Vector Results",
|
||||
[],
|
||||
None,
|
||||
"{job} a job conceptVector.generate made, as it returned it, or with state \"canceled\" and no variations; the session keeps the 4 newest jobs, until their document closes → {job, provider, source, state, variations}",
|
||||
has_doc,
|
||||
results
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.cancel",
|
||||
"Cancel Concept to Vector Job",
|
||||
[],
|
||||
None,
|
||||
"{job} drop a job's variations, so that it can't be inserted; canceling it again does the same; an error when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved → {job, state: \"canceled\"}",
|
||||
has_doc,
|
||||
cancel
|
||||
),
|
||||
cmd!(
|
||||
"conceptVector.insert",
|
||||
"Insert Concept to Vector Styles",
|
||||
[],
|
||||
None,
|
||||
"{job, variations: [style id…] (different styles of the job)} put a group of each chosen variation, named after its style and in the provider's order, in a row to the right of the job's image, each the image's size with 24 pt between them, moved further right past other visible art in their way, where a variation reaches past its box too (the next one then starts 24 pt past what it paints); the groups go above the outermost clip group or opacity-masked group around the image, and above the outermost envelope, blend, repeat or other live object, the outermost group whose members it makes or places (a graph, an Objects on Path, Shaper, dimension, flare or Live Paint group, a compound shape) and the outermost group with effects or fills and strokes of its own around it; the image and other art stay as they are; one undo step; a variation with no paths is left out, and when every chosen one has none nothing changes (no undo step, ids []); an error when the job's document is not the active one, the object, its image or its placement changed, the object is now locked or hidden, or it is on a layer with a clipping mask, an opacity mask, or effects, fills or strokes of its own, or it or a group around it has effects that move or reshape it, or its image is distorted (Perspective Distort or Free Distort), and when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved →{ids: the groups, selected}",
|
||||
has_doc,
|
||||
insert
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -14,7 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The active artboard the app passes, for the steps that act on it.
|
||||
let artboard = p.get("artboard").and_then(Value::as_u64);
|
||||
// What an error rolls back besides the documents: session-level state a step may change
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group).
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group, the
|
||||
// Concept to Vector jobs).
|
||||
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
|
||||
// would otherwise run inside it and take its baseline as theirs (#1697).
|
||||
if s.active().is_some() && !s.previewing {
|
||||
@@ -24,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
let (clipboard_copied, copies) = (s.clipboard_copied, s.copies);
|
||||
let concept_jobs = s.concept_jobs_snapshot();
|
||||
// The documents as they are now, whole: what a failed step brings back. Their art, history,
|
||||
// file, format and saved state share their data with the open ones until a step changes them.
|
||||
let start = s.docs.clone();
|
||||
@@ -42,6 +44,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(results) => {
|
||||
s.notify_text_tool("batch.end");
|
||||
s.batch_steps = Some(grouped);
|
||||
s.prune_concept_jobs();
|
||||
results
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -59,6 +62,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
|
||||
(s.clipboard_copied, s.copies) = (clipboard_copied, copies);
|
||||
s.pending_paint = None;
|
||||
s.restore_concept_jobs(concept_jobs);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -895,6 +895,7 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[
|
||||
(&["Object"], "Perspective"),
|
||||
(&["Object"], "Live Paint"),
|
||||
(&["Object"], "Image Trace"),
|
||||
(&["Object"], "Concept to Vector…"),
|
||||
(&["Object"], "Text Wrap"),
|
||||
(&["Object"], "Clipping Mask"),
|
||||
(&["Object"], "Compound Path"),
|
||||
|
||||
@@ -762,7 +762,8 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and
|
||||
/// report where it is on disk, or edit text once per match with no limit on the matches in one call.
|
||||
/// report where it is on disk, edit text once per match with no limit on the matches in one call,
|
||||
/// or hand an image to a Concept to Vector provider and its results.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
@@ -770,6 +771,11 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"addon.type.fontSheet",
|
||||
"addon.type.numbers",
|
||||
"color.contrast",
|
||||
"conceptVector.cancel",
|
||||
"conceptVector.generate",
|
||||
"conceptVector.insert",
|
||||
"conceptVector.providers",
|
||||
"conceptVector.results",
|
||||
"effect.refreshDeferred",
|
||||
"graphicStyle.setOptions",
|
||||
"object.blend.createSpine",
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
//! Concept to Vector providers: what makes vector variations of a selected image.
|
||||
//!
|
||||
//! A provider ([`Provider`]) takes one image's encoded pixels and up to [`MAX_STYLES`] of its own
|
||||
//! style ids ([`Request`]), and returns one [`Variation`] per style, in the order asked, as paths
|
||||
//! in the image's pixel space with explicit paints. It sees nothing else of the session or the
|
||||
//! document. The session keeps the providers in a [`Registry`] and calls one only by its id: an
|
||||
//! unknown or incapable provider is an error, never a substitute.
|
||||
//!
|
||||
//! The host checks every result again ([`check_result`]) before it keeps it, whatever provider
|
||||
//! made it: the number and order of the variations, finite coordinates and widths within bounds,
|
||||
//! and the totals [`MAX_ANCHORS`] and [`MAX_PATHS`] across all styles.
|
||||
//!
|
||||
//! The one built-in provider ([`offline::ID`]) makes its styles with Image Trace, on this
|
||||
//! computer: it takes no prompt and makes vector art only.
|
||||
|
||||
pub mod offline;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
|
||||
/// The most styles one request may ask for.
|
||||
pub const MAX_STYLES: usize = 8;
|
||||
|
||||
/// The most anchor points all the variations of one request may hold together.
|
||||
pub const MAX_ANCHORS: usize = 1_000_000;
|
||||
|
||||
/// The most paths all the variations of one request may hold together, each subpath of a compound
|
||||
/// path counted as one.
|
||||
pub const MAX_PATHS: usize = 250_000;
|
||||
|
||||
/// The most warnings a variation may carry, and the most characters in each.
|
||||
pub const MAX_WARNINGS: usize = 16;
|
||||
const MAX_WARNING_CHARS: usize = 500;
|
||||
|
||||
/// One of a provider's styles: its stable id and its English name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
pub struct Style {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
}
|
||||
|
||||
/// What a provider takes and makes.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Capabilities {
|
||||
/// It takes an image as its input.
|
||||
pub image_input: bool,
|
||||
/// It makes editable vector paths.
|
||||
pub vector_output: bool,
|
||||
/// It takes a text prompt.
|
||||
pub prompt: bool,
|
||||
/// It makes raster images.
|
||||
pub raster_output: bool,
|
||||
/// It runs on this computer without a network.
|
||||
pub offline: bool,
|
||||
/// Its styles, in the order it lists them.
|
||||
pub styles: Vec<Style>,
|
||||
}
|
||||
|
||||
/// The kind of result a request asks for. `conceptVector.generate` asks only for
|
||||
/// [`Output::Vector`]: a [`Variation`] holds vector paths.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Output {
|
||||
Vector,
|
||||
Raster,
|
||||
}
|
||||
|
||||
/// One request: the encoded pixels of an image, and how to make its variations.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Request {
|
||||
/// The image's encoded bytes (PNG, JPEG, WebP or GIF), as the document holds them.
|
||||
pub image: Arc<Vec<u8>>,
|
||||
/// The image's size in pixels: the space the variations' paths are in.
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// The prompt, trimmed; `None` when there is none.
|
||||
pub prompt: Option<String>,
|
||||
/// The provider's style ids, 1 to [`MAX_STYLES`] of them, each once.
|
||||
pub styles: Vec<String>,
|
||||
/// How much of the image's detail to keep, 0 (least) to 100 (most).
|
||||
pub detail: u8,
|
||||
pub output: Output,
|
||||
}
|
||||
|
||||
/// One path of a variation, in the image's pixel space (`(0, 0)` top left, `(width, height)` bottom
|
||||
/// right).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VectorPath {
|
||||
pub path: PathData,
|
||||
/// The fill color (sRGB), if it is filled.
|
||||
pub fill: Option<[u8; 3]>,
|
||||
/// The stroke color (sRGB) and width in pixels, if it is stroked.
|
||||
pub stroke: Option<([u8; 3], f64)>,
|
||||
/// Stroked: the stroke's ends are square (cut straight half the width past the path's end);
|
||||
/// otherwise round.
|
||||
pub square_caps: bool,
|
||||
}
|
||||
|
||||
/// The variation a provider made for one style.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Variation {
|
||||
/// The style id it was made for.
|
||||
pub style: String,
|
||||
/// Its paths, bottom-most first.
|
||||
pub paths: Vec<VectorPath>,
|
||||
/// Notes for the person who asked (a scaled-down image, nothing traced).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Variation {
|
||||
/// Its anchor points, every path counted.
|
||||
pub fn anchors(&self) -> usize {
|
||||
self.paths.iter().map(|p| p.path.anchor_count()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a provider made nothing.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
pub enum ProviderError {
|
||||
/// The image or the request cannot be used.
|
||||
#[error("{0}")]
|
||||
InvalidInput(String),
|
||||
/// The provider does not do what the request asks.
|
||||
#[error("{0}")]
|
||||
Unsupported(String),
|
||||
/// The provider cannot run now.
|
||||
#[error("{0}")]
|
||||
Unavailable(String),
|
||||
/// The caller stopped it.
|
||||
#[error("cancelled; nothing was changed")]
|
||||
Canceled,
|
||||
/// The results would pass a limit.
|
||||
#[error("the results would have more than {0} anchor points: lower Detail or choose fewer styles")]
|
||||
ResourceLimit(usize),
|
||||
/// The provider's results do not match the request, or are out of bounds.
|
||||
#[error("the provider's results do not match the request or are malformed")]
|
||||
InvalidResult,
|
||||
/// The provider stopped on a fault of its own.
|
||||
#[error("the provider stopped with an internal error: {0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
/// How far a provider has got: `steps(done, total)`; it stops with [`ProviderError::Canceled`]
|
||||
/// once this answers `false`.
|
||||
pub type Steps<'a> = &'a (dyn Fn(u64, u64) -> bool + Sync);
|
||||
|
||||
/// Something that makes vector variations of an image.
|
||||
pub trait Provider: Send + Sync {
|
||||
/// Its stable id, such as `offline.traceStyles`.
|
||||
fn id(&self) -> &'static str;
|
||||
/// Its English name.
|
||||
fn name(&self) -> &'static str;
|
||||
fn capabilities(&self) -> Capabilities;
|
||||
/// One variation for each of `request.styles`, in that order. A style's variation depends only
|
||||
/// on the image, the prompt, the detail and that style, not on the other styles asked for: a
|
||||
/// caller with no thread to wait on asks for one style at a time when [`Provider::parts`] gives
|
||||
/// `None` (`ConceptRun::run_part`, which the web build uses).
|
||||
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError>;
|
||||
/// What [`Provider::generate`] makes, made a part at a time ([`Parts`]), for a caller with no
|
||||
/// thread to wait on; `None` (the default) when it makes no parts smaller than one style.
|
||||
fn parts(&self, _request: &Request) -> Option<Box<dyn Parts>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A request's variations made a part at a time: each call of [`Parts::step`] does a part and
|
||||
/// returns, so that the caller can run other work, or stop, between parts.
|
||||
pub trait Parts: Send {
|
||||
/// Does the next part → the variations once the last part is done, `None` before it.
|
||||
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError>;
|
||||
/// The styles made so far.
|
||||
fn styles_done(&self) -> usize;
|
||||
}
|
||||
|
||||
/// The providers a session can call, by id.
|
||||
#[derive(Clone)]
|
||||
pub struct Registry {
|
||||
providers: Vec<Registered>,
|
||||
}
|
||||
|
||||
/// A provider in a [`Registry`], with the id, name and capabilities it gave when it was
|
||||
/// registered.
|
||||
#[derive(Clone)]
|
||||
pub struct Registered {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
pub capabilities: Capabilities,
|
||||
pub provider: Arc<dyn Provider>,
|
||||
}
|
||||
|
||||
impl Default for Registry {
|
||||
/// The built-in provider only.
|
||||
fn default() -> Self {
|
||||
let p = offline::TraceStyles;
|
||||
Self { providers: vec![Registered { id: p.id(), name: p.name(), capabilities: p.capabilities(), provider: Arc::new(p) }] }
|
||||
}
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// A registry with no provider.
|
||||
pub fn empty() -> Self {
|
||||
Self { providers: vec![] }
|
||||
}
|
||||
|
||||
/// Add `provider`, reading its id, name and capabilities once; an error when one with its id
|
||||
/// is registered already, or when the provider panics while giving them.
|
||||
pub fn register(&mut self, provider: Arc<dyn Provider>) -> Result<(), String> {
|
||||
let (id, name, capabilities) = crate::guard::catch_panic(|| (provider.id(), provider.name(), provider.capabilities()))
|
||||
.map_err(|e| ProviderError::Internal(e).to_string())?;
|
||||
if self.get(id).is_some() {
|
||||
return Err(format!("a provider with the id `{id}` is registered already"));
|
||||
}
|
||||
self.providers.push(Registered { id, name, capabilities, provider });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The provider `id` (exactly so spelled).
|
||||
pub fn get(&self, id: &str) -> Option<&Registered> {
|
||||
self.providers.iter().find(|p| p.id == id)
|
||||
}
|
||||
|
||||
/// The providers in the order they were registered.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Registered> {
|
||||
self.providers.iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `p` is a finite point within `limit` of the image's pixel space.
|
||||
fn within(p: Point, limit: f64, size: (f64, f64)) -> bool {
|
||||
p.x.is_finite() && p.y.is_finite() && p.x >= -limit && p.y >= -limit && p.x <= size.0 + limit && p.y <= size.1 + limit
|
||||
}
|
||||
|
||||
/// Checks the variations a provider returned for `request`: one per style in the order asked, at
|
||||
/// most [`MAX_PATHS`] paths (each subpath of a compound path counted as one) and [`MAX_ANCHORS`]
|
||||
/// anchors together, each path with a fill or a stroke and with subpaths that each have an anchor,
|
||||
/// every anchor and handle finite and within one image side of the image, every
|
||||
/// stroke width finite, over 0 and at most the image's larger side, and at most [`MAX_WARNINGS`]
|
||||
/// warnings of at most 500 characters on each variation.
|
||||
pub fn check_result(request: &Request, variations: &[Variation]) -> Result<(), ProviderError> {
|
||||
if variations.len() != request.styles.len() || variations.iter().zip(&request.styles).any(|(v, s)| v.style != *s) {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
let size = (f64::from(request.width.max(1)), f64::from(request.height.max(1)));
|
||||
let side = size.0.max(size.1);
|
||||
let (mut paths, mut anchors) = (0usize, 0usize);
|
||||
for v in variations {
|
||||
// Each subpath of a compound path becomes an object of its own when it is inserted.
|
||||
paths = v.paths.iter().fold(paths, |n, p| n.saturating_add(p.path.subpaths.len().max(1)));
|
||||
anchors += v.anchors();
|
||||
if anchors > MAX_ANCHORS {
|
||||
return Err(ProviderError::ResourceLimit(MAX_ANCHORS));
|
||||
}
|
||||
if paths > MAX_PATHS || v.warnings.len() > MAX_WARNINGS || v.warnings.iter().any(|w| w.chars().count() > MAX_WARNING_CHARS) {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
for p in &v.paths {
|
||||
let width_ok = p.stroke.is_none_or(|(_, w)| w.is_finite() && w > 0.0 && w <= side);
|
||||
let painted = p.fill.is_some() || p.stroke.is_some();
|
||||
let points_ok = p.path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].into_iter().all(|q| within(q, side, size)));
|
||||
let no_empty_subpath = !p.path.subpaths.is_empty() && p.path.subpaths.iter().all(|sp| !sp.anchors.is_empty());
|
||||
if !width_ok || !painted || !no_empty_subpath || !points_ok {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
//! The built-in provider: Concept to Vector styles made with Image Trace on this computer.
|
||||
//!
|
||||
//! Each style is a fixed set of Image Trace settings of VectorCraft's own, and Detail (0 to 100)
|
||||
//! moves its Paths, Noise and color count within that style's range. The image is decoded once and
|
||||
//! traced once per style; an image over [`MAX_PIXELS`] is scaled down first, aspect kept, and
|
||||
//! each variation says so. The paths are mapped back to the image's own pixel size.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::kurbo::common::solve_cubic;
|
||||
use vectorcraft_geom::{Affine, Anchor, CubicBez, ParamCurve, PathData, Point, SubPath};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
use super::{Capabilities, MAX_ANCHORS, MAX_PATHS, Output, Parts, ProviderError, Request, Steps, Style, Variation, VectorPath};
|
||||
|
||||
/// The built-in provider's id.
|
||||
pub const ID: &str = "offline.traceStyles";
|
||||
|
||||
/// The most pixels the built-in provider traces an image at (16 megapixels).
|
||||
pub const MAX_PIXELS: u64 = 16 << 20;
|
||||
|
||||
/// The built-in provider's styles, in the order it lists them.
|
||||
pub const STYLES: [Style; 5] = [
|
||||
Style { id: "outline", label: "Outline" },
|
||||
Style { id: "inkLines", label: "Ink Lines" },
|
||||
Style { id: "flatColor", label: "Flat Color" },
|
||||
Style { id: "detailedColor", label: "Detailed Color" },
|
||||
Style { id: "grayTones", label: "Gray Tones" },
|
||||
];
|
||||
|
||||
/// Concept to Vector styles made with Image Trace ([`ID`]).
|
||||
pub struct TraceStyles;
|
||||
|
||||
/// `lo` at Detail 0 to `hi` at Detail 100.
|
||||
fn between(lo: f64, hi: f64, t: f64) -> f64 {
|
||||
lo + (hi - lo) * t
|
||||
}
|
||||
|
||||
/// The trace settings of style `id` at Detail `detail` (0 to 100); `None` for an id that isn't one
|
||||
/// of [`STYLES`].
|
||||
pub fn style_params(id: &str, detail: u8) -> Option<tr::TraceParams> {
|
||||
let t = f64::from(detail.min(100)) / 100.0;
|
||||
let noise = |lo: f64, hi: f64| between(hi, lo, t).round().max(1.0) as u32;
|
||||
let count = |lo: f64, hi: f64| between(lo, hi, t).round() as u32;
|
||||
let base = tr::TraceParams { shapes: false, gradients: false, auto_grouping: false, ..tr::TraceParams::default() };
|
||||
Some(match id {
|
||||
// Black stroked lines only: thin lines as center lines, wider areas as outlines.
|
||||
"outline" => {
|
||||
tr::TraceParams { fills: false, strokes: true, ignore_white: true, paths: between(50.0, 90.0, t), noise: noise(4.0, 40.0), ..base }
|
||||
}
|
||||
// Black filled ink on no background, the straight runs straightened.
|
||||
"inkLines" => tr::TraceParams {
|
||||
ignore_white: true,
|
||||
snap_curves_to_lines: true,
|
||||
paths: between(50.0, 95.0, t),
|
||||
corners: 80.0,
|
||||
noise: noise(4.0, 30.0),
|
||||
..base
|
||||
},
|
||||
// A few flat colors, abutting.
|
||||
"flatColor" => tr::TraceParams {
|
||||
mode: tr::Mode::Color,
|
||||
colors: count(3.0, 8.0),
|
||||
paths: between(40.0, 80.0, t),
|
||||
corners: 60.0,
|
||||
noise: noise(8.0, 40.0),
|
||||
snap_curves_to_lines: true,
|
||||
..base
|
||||
},
|
||||
// Many colors, stacked so no hairline gaps show.
|
||||
"detailedColor" => tr::TraceParams {
|
||||
mode: tr::Mode::Color,
|
||||
colors: count(12.0, 32.0),
|
||||
paths: between(70.0, 95.0, t),
|
||||
corners: 40.0,
|
||||
noise: noise(2.0, 12.0),
|
||||
method: tr::Method::Overlapping,
|
||||
..base
|
||||
},
|
||||
// Grays, stacked.
|
||||
"grayTones" => tr::TraceParams {
|
||||
mode: tr::Mode::Grayscale,
|
||||
colors: count(4.0, 12.0),
|
||||
paths: between(55.0, 90.0, t),
|
||||
corners: 50.0,
|
||||
noise: noise(4.0, 20.0),
|
||||
method: tr::Method::Overlapping,
|
||||
..base
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `img` box-filtered down to at most [`MAX_PIXELS`], aspect kept; `img` itself when it fits.
|
||||
fn fit(img: tr::Raster) -> tr::Raster {
|
||||
fit_within(img, MAX_PIXELS)
|
||||
}
|
||||
|
||||
/// `img` box-filtered down to at most `max` pixels (at least 1), aspect kept as far as a side of
|
||||
/// at least one pixel allows; `img` itself when it fits.
|
||||
pub(super) fn fit_within(img: tr::Raster, max: u64) -> tr::Raster {
|
||||
let (w, h) = (u64::from(img.width), u64::from(img.height));
|
||||
let max = max.max(1);
|
||||
if w * h <= max || w == 0 || h == 0 {
|
||||
return img;
|
||||
}
|
||||
let k = (max as f64 / (w * h) as f64).sqrt();
|
||||
// A side that rounds down to one pixel leaves the other side the whole budget, no more.
|
||||
let nh = ((h as f64 * k).floor() as u64).clamp(1, h.min(max));
|
||||
let nw = ((w as f64 * k).floor() as u64).clamp(1, w.min(max / nh)) as u32;
|
||||
let nh = nh as u32;
|
||||
let mut rgba = Vec::with_capacity(nw as usize * nh as usize * 4);
|
||||
for y in 0..nh {
|
||||
let (y0, y1) = (u64::from(y) * h / u64::from(nh), (u64::from(y + 1) * h / u64::from(nh)).max(u64::from(y) * h / u64::from(nh) + 1));
|
||||
for x in 0..nw {
|
||||
let (x0, x1) = (u64::from(x) * w / u64::from(nw), (u64::from(x + 1) * w / u64::from(nw)).max(u64::from(x) * w / u64::from(nw) + 1));
|
||||
// Each pixel's color is weighted by its alpha. A box with nothing opaque in it is clear black.
|
||||
let mut sum = [0u64; 4];
|
||||
for sy in y0..y1.min(h) {
|
||||
for sx in x0..x1.min(w) {
|
||||
let [r, g, b, a] = img.pixel(sx as u32, sy as u32).map(u64::from);
|
||||
sum = [sum[0] + r * a, sum[1] + g * a, sum[2] + b * a, sum[3] + a];
|
||||
}
|
||||
}
|
||||
let n = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1);
|
||||
let alpha = sum[3];
|
||||
let color = |s: u64| s.checked_div(alpha).map_or(0, |c| c.min(255) as u8);
|
||||
rgba.extend([color(sum[0]), color(sum[1]), color(sum[2]), (alpha / n) as u8]);
|
||||
}
|
||||
}
|
||||
tr::Raster { width: nw, height: nh, rgba }
|
||||
}
|
||||
|
||||
impl super::Provider for TraceStyles {
|
||||
fn id(&self) -> &'static str {
|
||||
ID
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"Offline Image Trace Styles"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities { image_input: true, vector_output: true, prompt: false, raster_output: false, offline: true, styles: STYLES.to_vec() }
|
||||
}
|
||||
|
||||
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError> {
|
||||
let params = checked(request)?;
|
||||
let total = params.len() as u64;
|
||||
if !steps(0, total) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
let image = Decoded::new(request)?;
|
||||
let mut left = MAX_ANCHORS;
|
||||
let mut out = Vec::with_capacity(params.len());
|
||||
for (i, (style, p)) in request.styles.iter().zip(¶ms).enumerate() {
|
||||
let go_on = |_: u64, _: u64| steps(i as u64, total);
|
||||
let res = tr::trace_watched(&image.raster, p, left, &go_on).map_err(trace_error)?;
|
||||
left = left.saturating_sub(res.anchor_count());
|
||||
out.push(image.variation(style, p, res));
|
||||
}
|
||||
if !steps(total, total) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
Ok(with_seams(out))
|
||||
}
|
||||
|
||||
/// The image decoded in the first part; then for each style, its color layers found in one
|
||||
/// part and each layer traced in a part of its own ([`tr::TraceSteps`]), or all of them in
|
||||
/// one part where the style stacks them (Overlapping with Fills).
|
||||
fn parts(&self, request: &Request) -> Option<Box<dyn Parts>> {
|
||||
Some(Box::new(TraceParts { request: request.clone(), image: None, trace: None, left: MAX_ANCHORS, out: vec![], ended: false }))
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace settings of each of `request`'s styles; an error for a prompt, an output other than
|
||||
/// vector art, or a style that isn't one of [`STYLES`]. The host refuses these first; a direct
|
||||
/// caller gets the same answer.
|
||||
fn checked(request: &Request) -> Result<Vec<tr::TraceParams>, ProviderError> {
|
||||
let pid = ID;
|
||||
if request.prompt.is_some() || request.output != Output::Vector {
|
||||
return Err(ProviderError::Unsupported(format!("`{pid}` takes no prompt and makes vector art only")));
|
||||
}
|
||||
request
|
||||
.styles
|
||||
.iter()
|
||||
.map(|s| style_params(s, request.detail))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(|| ProviderError::InvalidInput(format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)")))
|
||||
}
|
||||
|
||||
fn trace_error(e: tr::TraceError) -> ProviderError {
|
||||
match e {
|
||||
tr::TraceError::Cancelled => ProviderError::Canceled,
|
||||
tr::TraceError::TooComplex { .. } => ProviderError::ResourceLimit(MAX_ANCHORS),
|
||||
e => ProviderError::InvalidInput(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A request's image decoded for tracing, with what maps its traced paths back.
|
||||
struct Decoded {
|
||||
raster: Arc<tr::Raster>,
|
||||
/// The decoded raster's pixels → the image's own pixel space.
|
||||
back: Affine,
|
||||
unit: f64,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Decoded {
|
||||
/// `request`'s image decoded, scaled down to at most [`MAX_PIXELS`].
|
||||
fn new(request: &Request) -> Result<Self, ProviderError> {
|
||||
let raster = fit(tr::Raster::decode_to_fit(&request.image).map_err(|e| ProviderError::InvalidInput(e.to_string()))?);
|
||||
let mut warnings = vec![];
|
||||
let (iw, ih) = (request.width.max(1), request.height.max(1));
|
||||
if u64::from(raster.width) * u64::from(raster.height) < u64::from(iw) * u64::from(ih) {
|
||||
warnings.push(format!("The image was traced at {} × {} pixels, scaled down from {iw} × {ih}.", raster.width, raster.height));
|
||||
}
|
||||
let back = Affine::scale_non_uniform(f64::from(iw) / f64::from(raster.width.max(1)), f64::from(ih) / f64::from(raster.height.max(1)));
|
||||
let unit = back.determinant().abs().sqrt();
|
||||
Ok(Self { raster: Arc::new(raster), back, unit, warnings })
|
||||
}
|
||||
|
||||
/// The variation of `style` that the trace `res` of this image, made with `params`, makes, and
|
||||
/// the seam fills of an Abutting trace with fills ([`tr::seam_fills`]) trimmed inside the
|
||||
/// image ([`within_image`]) and outlined in raster pixels before mapping them back, for
|
||||
/// [`with_seams`] to lay under its paths.
|
||||
fn variation(&self, style: &str, params: &tr::TraceParams, res: tr::TraceResult) -> Made {
|
||||
let size = (self.raster.width, self.raster.height);
|
||||
let seams = tr::seam_fills(&res.paths, params, size).map_or_else(Vec::new, |s| {
|
||||
s.strokes
|
||||
.into_iter()
|
||||
.map(|tp| {
|
||||
let mut tp = within_image(tp, size);
|
||||
if let Some(width) = tp.stroke.take() {
|
||||
tp.path = vectorcraft_pathops::outline_stroke(
|
||||
&tp.path,
|
||||
width,
|
||||
vectorcraft_pathops::Cap::Butt,
|
||||
vectorcraft_pathops::Join::Round,
|
||||
4.0,
|
||||
);
|
||||
}
|
||||
tp
|
||||
})
|
||||
.filter(|tp| !tp.path.subpaths.is_empty())
|
||||
.map(|tp| self.vector_path(tp))
|
||||
.collect()
|
||||
});
|
||||
let paths = res.paths.into_iter().map(|tp| self.vector_path(tp)).collect();
|
||||
Made { variation: Variation { style: style.to_string(), paths, warnings: self.warnings.clone() }, seams }
|
||||
}
|
||||
|
||||
/// Traced path `tp` in the image's own pixels.
|
||||
fn vector_path(&self, tp: tr::TracedPath) -> VectorPath {
|
||||
let path = tp.path.transformed(self.back);
|
||||
match tp.stroke {
|
||||
Some(w) => VectorPath { path, fill: None, stroke: Some((tp.color, w * self.unit)), square_caps: tp.square_caps },
|
||||
None => VectorPath { path, fill: Some(tp.color), stroke: None, square_caps: false },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A variation made, and the outlined seam fills to lay under its paths.
|
||||
pub(super) struct Made {
|
||||
pub(super) variation: Variation,
|
||||
pub(super) seams: Vec<VectorPath>,
|
||||
}
|
||||
|
||||
/// [`with_seams_within`] [`MAX_ANCHORS`] and [`MAX_PATHS`].
|
||||
fn with_seams(made: Vec<Made>) -> Vec<Variation> {
|
||||
with_seams_within(made, MAX_ANCHORS, MAX_PATHS)
|
||||
}
|
||||
|
||||
/// The variations `made`, each with its seam fills under its paths, in order, while they fit in
|
||||
/// the `max_anchors` anchors and `max_paths` paths (each subpath counted as one) left once every
|
||||
/// variation is counted: the traced paths of every style come first, and a style whose seam fills
|
||||
/// do not fit goes without them.
|
||||
pub(super) fn with_seams_within(made: Vec<Made>, max_anchors: usize, max_paths: usize) -> Vec<Variation> {
|
||||
let subpaths = |paths: &[VectorPath]| paths.iter().map(|p| p.path.subpaths.len().max(1)).sum::<usize>();
|
||||
let mut anchors = made.iter().map(|m| m.variation.anchors()).sum::<usize>();
|
||||
let mut paths = made.iter().map(|m| subpaths(&m.variation.paths)).sum::<usize>();
|
||||
made.into_iter()
|
||||
.map(|Made { mut variation, seams }| {
|
||||
let (more_anchors, more_paths) = (seams.iter().map(|p| p.path.anchor_count()).sum::<usize>(), subpaths(&seams));
|
||||
if !seams.is_empty() && anchors.saturating_add(more_anchors) <= max_anchors && paths.saturating_add(more_paths) <= max_paths {
|
||||
anchors += more_anchors;
|
||||
paths += more_paths;
|
||||
variation.paths.splice(0..0, seams);
|
||||
}
|
||||
variation
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Seam stroke `tp` of a `size` raster trimmed to half its width inside the raster's border,
|
||||
/// so that its outline with butt caps and round joins stays inside the image. The pieces left form
|
||||
/// open runs; a closed subpath left whole stays closed.
|
||||
fn within_image(mut tp: tr::TracedPath, size: (u32, u32)) -> tr::TracedPath {
|
||||
let half = tp.stroke.unwrap_or_default() / 2.0;
|
||||
let (w, h) = (f64::from(size.0), f64::from(size.1));
|
||||
let mut runs: Vec<SubPath> = vec![];
|
||||
if !half.is_finite() || half < 0.0 || half * 2.0 > w || half * 2.0 > h {
|
||||
tp.path = PathData::new(runs);
|
||||
return tp;
|
||||
}
|
||||
let inside = |p: Point| p.x >= half && p.y >= half && p.x <= w - half && p.y <= h - half;
|
||||
let clamp = |p: Point| Point::new(p.x.clamp(half, w - half), p.y.clamp(half, h - half));
|
||||
for sp in &tp.path.subpaths {
|
||||
let count = sp.segment_count();
|
||||
let mut pieces = vec![];
|
||||
for k in 0..count {
|
||||
let c = sp.segment(k);
|
||||
let mut cuts = vec![0.0, 1.0];
|
||||
if ![c.p0, c.p1, c.p2, c.p3].into_iter().all(inside) {
|
||||
for (p0, p1, p2, p3, side) in [
|
||||
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, half),
|
||||
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, w - half),
|
||||
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, half),
|
||||
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, h - half),
|
||||
] {
|
||||
// Intersections with the sides' supporting lines also cover corner crossings.
|
||||
cuts.extend(
|
||||
solve_cubic(p0 - side, 3.0 * (p1 - p0), 3.0 * (p0 - 2.0 * p1 + p2), p3 - p0 + 3.0 * (p1 - p2))
|
||||
.into_iter()
|
||||
.filter(|&t| t > 0.0 && t < 1.0),
|
||||
);
|
||||
}
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
cuts.dedup();
|
||||
}
|
||||
for pair in cuts.windows(2) {
|
||||
let (t0, t1) = (pair[0], pair[1]);
|
||||
pieces.push((k, t0, t1, inside(c.eval(t0 + (t1 - t0) / 2.0))));
|
||||
}
|
||||
}
|
||||
if pieces.iter().all(|&(_, _, _, kept)| kept) {
|
||||
if count > 0 {
|
||||
runs.push(sp.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Start after a piece left out, so that a run across a closed subpath's first anchor
|
||||
// stays one run.
|
||||
let start = if sp.closed { pieces.iter().position(|&(_, _, _, kept)| !kept).map_or(0, |k| k + 1) } else { 0 };
|
||||
let mut run: Vec<Anchor> = vec![];
|
||||
for j in 0..pieces.len() {
|
||||
let (k, t0, t1, kept) = pieces[(start + j) % pieces.len()];
|
||||
if kept {
|
||||
let (Some(&a), Some(&b)) = (sp.anchors.get(k), sp.anchors.get((k + 1) % sp.anchors.len())) else { continue };
|
||||
let c = sp.segment(k);
|
||||
let mut c = if t0 == 0.0 && t1 == 1.0 { c } else { c.subsegment(t0..t1) };
|
||||
// Remove roundoff at the cut endpoints without constraining the curve's handles.
|
||||
c.p0 = clamp(c.p0);
|
||||
c.p3 = clamp(c.p3);
|
||||
if sp.segment_is_line(k) {
|
||||
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
|
||||
}
|
||||
if let Some(last) = run.last_mut() {
|
||||
last.h_out = c.p1;
|
||||
} else {
|
||||
let a = if t0 == 0.0 { a } else { Anchor::corner(c.p0) };
|
||||
run.push(Anchor { p: c.p0, h_in: c.p0, h_out: c.p1, ..a });
|
||||
}
|
||||
let b = if t1 == 1.0 { b } else { Anchor::corner(c.p3) };
|
||||
run.push(Anchor { p: c.p3, h_in: c.p2, h_out: c.p3, ..b });
|
||||
} else if !run.is_empty() {
|
||||
runs.push(open_run(std::mem::take(&mut run)));
|
||||
}
|
||||
}
|
||||
if !run.is_empty() {
|
||||
runs.push(open_run(run));
|
||||
}
|
||||
}
|
||||
tp.path = PathData::new(runs);
|
||||
tp
|
||||
}
|
||||
|
||||
/// An open run of anchors: the last one has no handle out.
|
||||
fn open_run(mut run: Vec<Anchor>) -> SubPath {
|
||||
if let Some(last) = run.last_mut() {
|
||||
last.h_out = last.p;
|
||||
}
|
||||
SubPath::new(run, false)
|
||||
}
|
||||
|
||||
/// [`TraceStyles`]' variations made a part at a time.
|
||||
struct TraceParts {
|
||||
request: Request,
|
||||
image: Option<Decoded>,
|
||||
/// The trace of the style after those in `out`, once started.
|
||||
trace: Option<tr::TraceSteps>,
|
||||
/// The anchor points the styles not made yet may have.
|
||||
left: usize,
|
||||
out: Vec<Made>,
|
||||
/// The variations or an error have been given.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
impl Parts for TraceParts {
|
||||
/// After the variations or an error, each call gives `None`.
|
||||
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
|
||||
if self.ended {
|
||||
return Ok(None);
|
||||
}
|
||||
let part = self.next_part();
|
||||
self.ended = !matches!(part, Ok(None));
|
||||
part
|
||||
}
|
||||
|
||||
fn styles_done(&self) -> usize {
|
||||
self.out.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl TraceParts {
|
||||
fn next_part(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
|
||||
let Some(image) = &self.image else {
|
||||
checked(&self.request)?;
|
||||
self.image = Some(Decoded::new(&self.request)?);
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(style) = self.request.styles.get(self.out.len()) else { return Ok(Some(with_seams(std::mem::take(&mut self.out)))) };
|
||||
let trace = match &mut self.trace {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
|
||||
self.trace.insert(tr::TraceSteps::new(Arc::clone(&image.raster), params, self.left))
|
||||
}
|
||||
};
|
||||
let Some(res) = trace.step().map_err(trace_error)? else { return Ok(None) };
|
||||
self.trace = None;
|
||||
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
|
||||
self.left = self.left.saturating_sub(res.anchor_count());
|
||||
self.out.push(image.variation(style, ¶ms, res));
|
||||
if self.out.len() < self.request.styles.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(with_seams(std::mem::take(&mut self.out))))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,7 @@
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod cmd;
|
||||
pub mod concept_vector;
|
||||
pub mod file_access;
|
||||
pub mod guard;
|
||||
pub mod inspect;
|
||||
@@ -359,6 +360,9 @@ pub struct Session {
|
||||
/// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or
|
||||
/// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]).
|
||||
pub(crate) trace_hand_off: Option<cmd::Traced>,
|
||||
/// The Concept to Vector providers and the jobs made with them ([`cmd::conceptvector`]); not
|
||||
/// saved.
|
||||
pub(crate) concept: cmd::conceptvector::ConceptState,
|
||||
/// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or
|
||||
/// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]).
|
||||
pub(crate) retype_hand_off: Option<cmd::RetypeFound>,
|
||||
|
||||
@@ -501,6 +501,9 @@ struct World {
|
||||
pending_paint: Option<crate::Paint>,
|
||||
choices: Choices,
|
||||
journal: Journal,
|
||||
/// The Concept to Vector jobs, and the number of the first job made after the run started.
|
||||
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
|
||||
concept_from: u64,
|
||||
/// The preferences when the run started.
|
||||
start_prefs: crate::Prefs,
|
||||
/// The Caps Lock state when the run started.
|
||||
@@ -631,6 +634,8 @@ impl World {
|
||||
pending_paint: s.pending_paint.clone(),
|
||||
choices: Choices::of(s),
|
||||
journal: Journal::default(),
|
||||
concept_jobs: s.concept_jobs_snapshot(),
|
||||
concept_from: s.next_concept_job(),
|
||||
start_prefs: s.prefs.clone(),
|
||||
start_caps_lock: s.caps_lock,
|
||||
}
|
||||
@@ -655,6 +660,7 @@ impl World {
|
||||
swap(&mut self.pending_paint, &mut s.pending_paint);
|
||||
self.choices.swap(s);
|
||||
swap(&mut self.journal, &mut s.journal);
|
||||
s.swap_concept_jobs(&mut self.concept_jobs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -696,6 +702,7 @@ pub(crate) struct Savepoint {
|
||||
pending_paint: Option<crate::Paint>,
|
||||
choices: Choices,
|
||||
journal: usize,
|
||||
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
|
||||
/// The plug-in events queued before the command ([`Session::plugin_events_mark`]).
|
||||
plugin_events: u64,
|
||||
}
|
||||
@@ -732,6 +739,7 @@ impl Savepoint {
|
||||
pending_paint: s.pending_paint.clone(),
|
||||
choices: Choices::of(s),
|
||||
journal: s.journal.len(),
|
||||
concept_jobs: s.concept_jobs_snapshot(),
|
||||
plugin_events: s.plugin_events_mark(),
|
||||
}
|
||||
}
|
||||
@@ -787,6 +795,7 @@ impl Savepoint {
|
||||
s.pending_paint = self.pending_paint;
|
||||
self.choices.put(s);
|
||||
s.journal.truncate(self.journal);
|
||||
s.restore_concept_jobs(self.concept_jobs);
|
||||
// The documents the command opened are closed again: plug-ins are not told of them.
|
||||
s.forget_plugin_opens_since(self.plugin_events);
|
||||
s.sync_front_profiles();
|
||||
@@ -2842,6 +2851,9 @@ impl Session {
|
||||
for st in start.iter().filter(|b| !job.start_uids.contains(&b.uid)) {
|
||||
self.docs.push(st.clone());
|
||||
}
|
||||
// So do the Concept to Vector jobs the app made while the run went on.
|
||||
let others = std::mem::take(&mut job.world.concept_jobs);
|
||||
self.merge_concept_jobs(others, job.world.concept_from);
|
||||
// A document the script closed is gone now, with its recovery copy.
|
||||
for b in start.iter().filter(|b| job.start_uids.contains(&b.uid) && !self.docs.iter().any(|d| d.uid == b.uid)) {
|
||||
cmd::recovery::forget_closed(self, b);
|
||||
|
||||
@@ -150,6 +150,7 @@ impl Session {
|
||||
place_queue_loads: 0,
|
||||
image_hand_off: None,
|
||||
trace_hand_off: None,
|
||||
concept: Default::default(),
|
||||
retype_hand_off: None,
|
||||
place_cursor_requests: false,
|
||||
package_hand_off: None,
|
||||
@@ -568,6 +569,10 @@ impl Session {
|
||||
// Closed (saved or discarded): nothing left to recover.
|
||||
let uid = self.docs[index].uid;
|
||||
cmd::recovery::forget(self, uid);
|
||||
// In a batch, the jobs are dropped when the batch ends without an error.
|
||||
if self.batch_stash.is_none() {
|
||||
self.forget_concept_jobs(uid);
|
||||
}
|
||||
let old = self.docs.remove(index);
|
||||
if let Some(stash) = &mut self.batch_stash {
|
||||
stash.push(old);
|
||||
|
||||
@@ -720,7 +720,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.taskBar.actions",
|
||||
"Bar Actions",
|
||||
"",
|
||||
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
|
||||
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"conceptToVector\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
|
||||
),
|
||||
(
|
||||
"window.taskBar.resetActions",
|
||||
@@ -1038,6 +1038,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector",
|
||||
"Concept to Vector…",
|
||||
"",
|
||||
"{} open the Concept to Vector panel for the selected image or unexpanded Image Trace object; an error when the selection is not one such object, unlocked and shown (engine: conceptVector.generate / conceptVector.insert)",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector.generate",
|
||||
"Generate Concept to Vector Styles",
|
||||
"",
|
||||
"{} make the styles ticked in the Concept to Vector panel of the selected image or unexpanded Image Trace object, with the panel's Detail (the panel's Generate; engine: conceptVector.generate), and show them in the panel; off the UI thread in the app unless VECTORCRAFT_SYNC_OPEN is set, one part a frame on the web; a run going is canceled first, and the new one starts once its thread has ended → {running: true} while they are made, else {running: false, job}",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector.cancel",
|
||||
"Cancel Concept to Vector",
|
||||
"",
|
||||
"{} stop the styles the Concept to Vector panel is making off the UI thread (the panel's Cancel; on the web, before the next part): nothing is kept or shown → {canceled: 0 or 1}",
|
||||
),
|
||||
(
|
||||
"ui.recolorUndo",
|
||||
"Undo Changes",
|
||||
|
||||
@@ -88,7 +88,7 @@ use layers::parallel_map_at_most;
|
||||
#[cfg(test)]
|
||||
pub(crate) use layers::shift_probe;
|
||||
pub use params::{Method, Mode, PRESET_NAMES, Palette, TraceParams, enhanced_preset, preset, presets};
|
||||
pub use pipeline::{TraceResult, TracedPath, trace, trace_watched, trace_within};
|
||||
pub use pipeline::{TraceResult, TraceSteps, TracedPath, trace, trace_watched, trace_within};
|
||||
#[cfg(test)]
|
||||
use pipeline::{clear_background, label_extents};
|
||||
#[cfg(test)]
|
||||
|
||||
+259
-75
@@ -1,3 +1,4 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use super::layers::{Layers, parallel_map_at_most};
|
||||
@@ -177,21 +178,255 @@ pub fn trace_watched(
|
||||
max_anchors: usize,
|
||||
steps: &(dyn Fn(u64, u64) -> bool + Sync),
|
||||
) -> Result<TraceResult, TraceError> {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
if w == 0 || h == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) {
|
||||
if !traceable(img) {
|
||||
return Ok(TraceResult::default());
|
||||
}
|
||||
let mut out = trace_paths(img, params, max_anchors, steps)?;
|
||||
let out = trace_paths(img, params, max_anchors, steps)?;
|
||||
Ok(grouped(out, img, params))
|
||||
}
|
||||
|
||||
/// Whether `img` has pixels, as many as its size says.
|
||||
fn traceable(img: &Raster) -> bool {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
w > 0 && h > 0 && w.checked_mul(h).and_then(|n| n.checked_mul(4)) == Some(img.rgba.len())
|
||||
}
|
||||
|
||||
/// `out` with Auto Grouping's parents (see [`TraceResult::parents`]) when `params` asks for them.
|
||||
fn grouped(mut out: TraceResult, img: &Raster, params: &TraceParams) -> TraceResult {
|
||||
if params.auto_grouping {
|
||||
// Abutting areas cannot overlap; stacked layers, Logo's shapes and stroked lines can.
|
||||
let stacked = params.method == Method::Overlapping || params.mode == Mode::Logo || params.strokes;
|
||||
out.parents = group::parents(&out.paths, img.width as usize, img.height as usize, stacked);
|
||||
}
|
||||
Ok(out)
|
||||
out
|
||||
}
|
||||
|
||||
fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<TraceResult, TraceError> {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
/// How far a trace has got: see [`trace_watched`].
|
||||
type Steps<'s> = &'s (dyn Fn(u64, u64) -> bool + Sync);
|
||||
|
||||
fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: Steps) -> Result<TraceResult, TraceError> {
|
||||
let p = match prepare(Source::Borrowed(img), params, max_anchors, steps)? {
|
||||
Begun::Done(out) => return Ok(out),
|
||||
Begun::Layers(p) => p,
|
||||
};
|
||||
if p.stacks() {
|
||||
let paths = p.job(0).stacked(&p.layers, p.largest(), steps)?;
|
||||
return Ok((*p).finish_stacked(paths));
|
||||
}
|
||||
let traced = {
|
||||
let job = p.job(0);
|
||||
// A layer takes about ten bytes a pixel of its box while it is traced (its mask, the labels
|
||||
// of its components, the stack that fills them, its edges): as many layers at a time as fit
|
||||
// in half a gigabyte, so that a large image is not traced at the cost of gigabytes.
|
||||
let at_a_time = ((512 << 20) / (p.largest() * 10)).max(1);
|
||||
let total = p.layers.len() as u64;
|
||||
if !steps(0, total) {
|
||||
return Err(TraceError::Cancelled);
|
||||
}
|
||||
// Once stopped, the layers not started yet are skipped.
|
||||
let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false));
|
||||
let traced = parallel_map_at_most(at_a_time, &p.layers, |&(r, ci)| {
|
||||
if stopped.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let paths = job.layer(r, ci);
|
||||
if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) {
|
||||
stopped.store(true, Ordering::Relaxed);
|
||||
}
|
||||
paths
|
||||
});
|
||||
if stopped.load(Ordering::Relaxed) {
|
||||
return Err(TraceError::Cancelled);
|
||||
}
|
||||
traced
|
||||
};
|
||||
(*p).finish(traced)
|
||||
}
|
||||
|
||||
/// The image a trace works from: borrowed for the length of one call, or shared, for a trace
|
||||
/// made a part at a time ([`TraceSteps`]).
|
||||
enum Source<'a> {
|
||||
Borrowed(&'a Raster),
|
||||
Shared(Arc<Raster>),
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Source<'_> {
|
||||
type Target = Raster;
|
||||
fn deref(&self) -> &Raster {
|
||||
match self {
|
||||
Source::Borrowed(img) => img,
|
||||
Source::Shared(img) => img,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trace with its color layers found and ordered, none of them traced yet.
|
||||
struct Prepared<'a> {
|
||||
src: Source<'a>,
|
||||
/// A copy with a JPEG's block edges (see `deblock`) or a photo's noise (see `smooth`) smoothed
|
||||
/// away, traced in its place.
|
||||
smoothed: Option<Raster>,
|
||||
params: TraceParams,
|
||||
q: Quantized,
|
||||
/// Ignore Color, background only: `q.labels` with the background [`TRANSPARENT`].
|
||||
cleared: Option<Vec<u16>>,
|
||||
rank: Vec<usize>,
|
||||
left_out: Vec<bool>,
|
||||
boxes: Vec<Option<PixelBox>>,
|
||||
gradients: Vec<Option<TracedGradient>>,
|
||||
bw_tones: [f64; 2],
|
||||
/// The layers to trace, bottom first: `(rank, palette entry)`.
|
||||
layers: Vec<(usize, usize)>,
|
||||
keep_unmatched: Vec<String>,
|
||||
keep_ignored: bool,
|
||||
max_anchors: usize,
|
||||
}
|
||||
|
||||
/// What preparing a trace gives: the whole result (Logo mode), or its layers to trace.
|
||||
enum Begun<'a> {
|
||||
Done(TraceResult),
|
||||
Layers(Box<Prepared<'a>>),
|
||||
}
|
||||
|
||||
impl Prepared<'_> {
|
||||
/// What tracing one of the layers needs, with `anchors` anchor points made so far.
|
||||
fn job(&self, anchors: usize) -> Layers<'_> {
|
||||
Layers {
|
||||
q: &self.q,
|
||||
traced: self.cleared.as_deref().unwrap_or(&self.q.labels),
|
||||
rank: &self.rank,
|
||||
params: &self.params,
|
||||
img: self.smoothed.as_ref().unwrap_or(&*self.src),
|
||||
left_out: self.left_out.clone(),
|
||||
boxes: self.boxes.clone(),
|
||||
gradients: &self.gradients,
|
||||
bw_tones: self.bw_tones,
|
||||
style: self.params.outline_style(),
|
||||
w: self.src.width as usize,
|
||||
h: self.src.height as usize,
|
||||
anchors: AtomicUsize::new(anchors),
|
||||
max_anchors: self.max_anchors,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the layers are traced together: Overlapping with Fills fills each shape whole and
|
||||
/// traces what it encloses again above it (see `Layers::stacked`). Lines (Create Strokes) and
|
||||
/// outlines (no Fills) are traced a layer at a time.
|
||||
fn stacks(&self) -> bool {
|
||||
self.params.method == Method::Overlapping && self.params.fills && !self.params.strokes
|
||||
}
|
||||
|
||||
/// The pixel count of the largest layer's box (at least 1).
|
||||
fn largest(&self) -> usize {
|
||||
self.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1)
|
||||
}
|
||||
|
||||
/// The result of `paths`, the layers traced together ([`Prepared::stacks`]).
|
||||
fn finish_stacked(self, paths: Vec<TracedPath>) -> TraceResult {
|
||||
let mut out = TraceResult { paths, keep_unmatched: self.keep_unmatched, keep_ignored: self.keep_ignored, ..TraceResult::default() };
|
||||
// The colors used, bottom layer first.
|
||||
for &(_, ci) in &self.layers {
|
||||
if let Some(&color) = self.q.palette.get(ci)
|
||||
&& !out.palette.contains(&color)
|
||||
&& out.paths.iter().any(|p| p.color == color)
|
||||
{
|
||||
out.palette.push(color);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The result of `traced`, the paths of each of [`Prepared::layers`] in order (`None` for a
|
||||
/// layer that passed the anchor maximum).
|
||||
fn finish(self, traced: Vec<Option<Vec<TracedPath>>>) -> Result<TraceResult, TraceError> {
|
||||
let mut out = TraceResult { keep_unmatched: self.keep_unmatched, keep_ignored: self.keep_ignored, ..TraceResult::default() };
|
||||
for (paths, &(_, ci)) in traced.into_iter().zip(&self.layers) {
|
||||
let paths = paths.ok_or(TraceError::TooComplex { max: self.max_anchors })?;
|
||||
// A layer with no paths adds no color to the palette.
|
||||
if paths.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.paths.extend(paths);
|
||||
let color = self.q.palette[ci];
|
||||
if !out.palette.contains(&color) {
|
||||
out.palette.push(color);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// A trace made a part at a time, for a caller with no thread to trace on that must let other
|
||||
/// work run between the parts (the web build). The first [`TraceSteps::step`] finds the color
|
||||
/// layers and each later one traces one layer, bottom first, one at a time (Overlapping with
|
||||
/// Fills, without Create Strokes, traces all of them in the second step, as its layers are traced
|
||||
/// together); the result is the one [`trace_within`] gives.
|
||||
pub struct TraceSteps {
|
||||
img: Arc<Raster>,
|
||||
params: TraceParams,
|
||||
max_anchors: usize,
|
||||
state: StepState,
|
||||
}
|
||||
|
||||
enum StepState {
|
||||
Start,
|
||||
/// The layers found, the paths of those traced so far, and their anchor points.
|
||||
Layers(Box<Prepared<'static>>, Vec<Option<Vec<TracedPath>>>, usize),
|
||||
Finished,
|
||||
}
|
||||
|
||||
impl TraceSteps {
|
||||
/// A trace of `img` with `params` that gives up with [`TraceError::TooComplex`] once the paths
|
||||
/// have more than `max_anchors` anchor points; nothing is done until [`TraceSteps::step`].
|
||||
pub fn new(img: Arc<Raster>, params: TraceParams, max_anchors: usize) -> Self {
|
||||
Self { img, params, max_anchors, state: StepState::Start }
|
||||
}
|
||||
|
||||
/// Does the next part → the result once the last part is done, `None` before it. After the
|
||||
/// result or an error, each call gives `None`.
|
||||
pub fn step(&mut self) -> Result<Option<TraceResult>, TraceError> {
|
||||
let (prepared, mut traced, anchors) = match std::mem::replace(&mut self.state, StepState::Finished) {
|
||||
StepState::Finished => return Ok(None),
|
||||
StepState::Start => {
|
||||
if !traceable(&self.img) {
|
||||
return Ok(Some(TraceResult::default()));
|
||||
}
|
||||
match prepare(Source::Shared(Arc::clone(&self.img)), &self.params, self.max_anchors, &|_, _| true)? {
|
||||
Begun::Done(out) => return Ok(Some(grouped(out, &self.img, &self.params))),
|
||||
Begun::Layers(p) if p.layers.is_empty() => return (*p).finish(vec![]).map(|out| Some(grouped(out, &self.img, &self.params))),
|
||||
Begun::Layers(p) => {
|
||||
let traced = Vec::with_capacity(p.layers.len());
|
||||
self.state = StepState::Layers(p, traced, 0);
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
StepState::Layers(p, traced, anchors) => (p, traced, anchors),
|
||||
};
|
||||
if prepared.stacks() {
|
||||
let paths = prepared.job(0).stacked(&prepared.layers, prepared.largest(), &|_, _| true)?;
|
||||
return Ok(Some(grouped((*prepared).finish_stacked(paths), &self.img, &self.params)));
|
||||
}
|
||||
// With every layer traced already the result is finished below.
|
||||
let mut anchors = anchors;
|
||||
if let Some(&(r, ci)) = prepared.layers.get(traced.len()) {
|
||||
let job = prepared.job(anchors);
|
||||
let paths = job.layer(r, ci);
|
||||
anchors = job.anchors.load(Ordering::Relaxed);
|
||||
traced.push(Some(paths.ok_or(TraceError::TooComplex { max: self.max_anchors })?));
|
||||
}
|
||||
if traced.len() < prepared.layers.len() {
|
||||
self.state = StepState::Layers(prepared, traced, anchors);
|
||||
return Ok(None);
|
||||
}
|
||||
(*prepared).finish(traced).map(|out| Some(grouped(out, &self.img, &self.params)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the color layers of `src` traced with `params` and the order they stack in, telling
|
||||
/// `steps(0, 0)` after each stage; Logo mode traces the whole image at once.
|
||||
fn prepare<'a>(src: Source<'a>, params: &TraceParams, max_anchors: usize, steps: Steps) -> Result<Begun<'a>, TraceError> {
|
||||
let (w, h) = (src.width as usize, src.height as usize);
|
||||
// The colors Keep Colors traces (checked in every mode).
|
||||
let listed = params
|
||||
.keep_colors
|
||||
@@ -202,7 +437,7 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
|
||||
let go_on = || if steps(0, 0) { Ok(()) } else { Err(TraceError::Cancelled) };
|
||||
if params.mode == Mode::Logo {
|
||||
go_on()?;
|
||||
return logo::trace_logo(img, params, max_anchors);
|
||||
return logo::trace_logo(&src, params, max_anchors).map(Begun::Done);
|
||||
}
|
||||
// The colour Ignore Color leaves out, if not white.
|
||||
let ignore = match ¶ms.ignore_color {
|
||||
@@ -218,12 +453,12 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
|
||||
// A photo is traced from a copy with its noise smoothed away (see `smooth`); the deblocked copy is
|
||||
// dropped once it is smoothed.
|
||||
let photo = |img: &Raster| params.mode != Mode::BlackAndWhite && quantize::continuous_tone(img);
|
||||
let prepared = match deblock::deblocked(img, strength) {
|
||||
let smoothed = match deblock::deblocked(&src, strength) {
|
||||
Some(deblocked) if photo(&deblocked) => Some(smooth::smoothed(&deblocked)),
|
||||
Some(deblocked) => Some(deblocked),
|
||||
None => photo(img).then(|| smooth::smoothed(img)),
|
||||
None => photo(&src).then(|| smooth::smoothed(&src)),
|
||||
};
|
||||
let img = prepared.as_ref().unwrap_or(img);
|
||||
let img = smoothed.as_ref().unwrap_or(&*src);
|
||||
go_on()?;
|
||||
// Gradients are found first and kept out of the palette: no colour is spent on bands of them.
|
||||
// Grayscale finds them in the image's grays (as its flat colours are), so their stops are gray.
|
||||
@@ -337,75 +572,24 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
|
||||
.collect();
|
||||
// Every layer is left out although a listed color matches one: Ignore Color left those out.
|
||||
let keep_ignored = !listed.is_empty() && layers.is_empty() && order.iter().any(|&ci| is_kept(q.palette[ci], &listed));
|
||||
let job = Layers {
|
||||
q: &q,
|
||||
traced: cleared.as_deref().unwrap_or(&q.labels),
|
||||
rank: &rank,
|
||||
let tones = bw_tones(img, &q);
|
||||
let params = params.clone();
|
||||
Ok(Begun::Layers(Box::new(Prepared {
|
||||
src,
|
||||
smoothed,
|
||||
params,
|
||||
img,
|
||||
q,
|
||||
cleared,
|
||||
rank,
|
||||
left_out,
|
||||
boxes,
|
||||
gradients: &gradients,
|
||||
bw_tones: bw_tones(img, &q),
|
||||
style: params.outline_style(),
|
||||
w,
|
||||
h,
|
||||
anchors: AtomicUsize::new(0),
|
||||
gradients,
|
||||
bw_tones: tones,
|
||||
layers,
|
||||
keep_unmatched,
|
||||
keep_ignored,
|
||||
max_anchors,
|
||||
};
|
||||
let mut out = TraceResult { keep_unmatched, keep_ignored, ..TraceResult::default() };
|
||||
// A layer takes about ten bytes a pixel of its box while it is traced (its mask, the labels
|
||||
// of its components, the stack that fills them, its edges): as many layers at a time as fit
|
||||
// in half a gigabyte, so that a large image is not traced at the cost of gigabytes.
|
||||
let largest = job.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1);
|
||||
let at_a_time = ((512 << 20) / (largest * 10)).max(1);
|
||||
// Overlapping with Fills: each shape is filled whole, and what it encloses is traced again above it (see
|
||||
// `Layers::stacked`). Lines (Create Strokes) and outlines (no Fills) are stacked as they always were.
|
||||
if params.method == Method::Overlapping && params.fills && !params.strokes {
|
||||
out.paths = job.stacked(&layers, largest, steps)?;
|
||||
// The colors used, bottom layer first.
|
||||
for &(_, ci) in &layers {
|
||||
if let Some(&color) = q.palette.get(ci)
|
||||
&& !out.palette.contains(&color)
|
||||
&& out.paths.iter().any(|p| p.color == color)
|
||||
{
|
||||
out.palette.push(color);
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let total = layers.len() as u64;
|
||||
if !steps(0, total) {
|
||||
return Err(TraceError::Cancelled);
|
||||
}
|
||||
// Once stopped, the layers not started yet are skipped.
|
||||
let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false));
|
||||
let traced = parallel_map_at_most(at_a_time, &layers, |&(r, ci)| {
|
||||
if stopped.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let paths = job.layer(r, ci);
|
||||
if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) {
|
||||
stopped.store(true, Ordering::Relaxed);
|
||||
}
|
||||
paths
|
||||
});
|
||||
if stopped.load(Ordering::Relaxed) {
|
||||
return Err(TraceError::Cancelled);
|
||||
}
|
||||
for (paths, &(_, ci)) in traced.into_iter().zip(&layers) {
|
||||
let paths = paths.ok_or(TraceError::TooComplex { max: max_anchors })?;
|
||||
// A layer with no paths adds no color to the palette.
|
||||
if paths.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.paths.extend(paths);
|
||||
let color = q.palette[ci];
|
||||
if !out.palette.contains(&color) {
|
||||
out.palette.push(color);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
})))
|
||||
}
|
||||
|
||||
/// The luminance of white and of black in a Black and White quantisation: what its lightest
|
||||
|
||||
@@ -1086,6 +1086,52 @@ fn a_watched_trace_counts_its_layers_and_stops_when_told() {
|
||||
assert!(matches!(trace_watched(&img, &p, usize::MAX, &|done, _| done == 0), Err(TraceError::Cancelled)));
|
||||
}
|
||||
|
||||
/// A trace made a part at a time finds its layers in the first part and traces one layer a part
|
||||
/// after it (all of them in the second part for Overlapping with Fills, which stacks them), and
|
||||
/// gives what one call gives, Auto Grouping, Logo mode and the anchor budget included.
|
||||
#[test]
|
||||
fn a_trace_made_a_part_at_a_time_matches_one_made_at_once() {
|
||||
fn parts(img: &Raster, p: &TraceParams, max: usize) -> (usize, Result<TraceResult, TraceError>) {
|
||||
let mut s = TraceSteps::new(std::sync::Arc::new(img.clone()), p.clone(), max);
|
||||
let mut n = 0;
|
||||
loop {
|
||||
n += 1;
|
||||
assert!(n < 1000, "the parts never end");
|
||||
match s.step() {
|
||||
Ok(None) => {}
|
||||
Ok(Some(r)) => return (n, Ok(r)),
|
||||
Err(e) => return (n, Err(e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
let img = stripes(120, 8);
|
||||
let overlapping =
|
||||
TraceParams { mode: Mode::Color, colors: 16, noise: 1, method: Method::Overlapping, auto_grouping: true, ..TraceParams::default() };
|
||||
// Overlapping with Fills traces its layers together: one part finds them, the next traces them.
|
||||
for (p, layered) in [
|
||||
(TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() }, true),
|
||||
(TraceParams { strokes: true, ..overlapping.clone() }, true),
|
||||
(overlapping, false),
|
||||
] {
|
||||
let at_once = trace_within(&img, &p, usize::MAX).unwrap();
|
||||
let (n, made) = parts(&img, &p, usize::MAX);
|
||||
assert_eq!(made.unwrap(), at_once, "{p:?}");
|
||||
assert!(at_once.palette.len() > 1, "{} colors", at_once.palette.len());
|
||||
assert!(if layered { n > 2 } else { n == 2 }, "{n} parts for {} colors, {p:?}", at_once.palette.len());
|
||||
}
|
||||
let logo = TraceParams { mode: Mode::Logo, ..TraceParams::default() };
|
||||
let round = disc(64, 32.0, 32.0, 20.0);
|
||||
let (n, made) = parts(&round, &logo, usize::MAX);
|
||||
assert_eq!((n, made.unwrap()), (1, trace_within(&round, &logo, usize::MAX).unwrap()), "Logo mode is one part");
|
||||
let p = TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() };
|
||||
let anchors = trace(&img, &p).anchor_count();
|
||||
assert!(matches!(parts(&img, &p, anchors / 2).1, Err(TraceError::TooComplex { max }) if max == anchors / 2));
|
||||
assert_eq!(parts(&img, &p, anchors).1.unwrap(), trace(&img, &p));
|
||||
let mut done = TraceSteps::new(std::sync::Arc::new(Raster::from_fn(0, 0, |_, _| WHITE)), p, usize::MAX);
|
||||
assert_eq!(done.step().unwrap(), Some(TraceResult::default()), "an empty image");
|
||||
assert_eq!(done.step().unwrap(), None, "nothing after the result");
|
||||
}
|
||||
|
||||
/// Layers traced in parallel come out in the same order every time: bottom (largest) first.
|
||||
#[test]
|
||||
fn parallel_layers_keep_their_order() {
|
||||
|
||||
@@ -251,6 +251,7 @@ impl VectorcraftApp {
|
||||
plugin_runs: Default::default(),
|
||||
placing: Default::default(),
|
||||
trace_runs: Default::default(),
|
||||
concept_runs: Default::default(),
|
||||
retype_runs: Default::default(),
|
||||
recovery: Default::default(),
|
||||
closing: None,
|
||||
@@ -419,6 +420,7 @@ impl VectorcraftApp {
|
||||
opening::poll(self);
|
||||
plugin_runs::poll(self);
|
||||
trace_runs::poll(self);
|
||||
crate::panels::concept_vector::poll(self);
|
||||
placing::poll(self);
|
||||
retype_runs::poll(self);
|
||||
// The handlers' time counts toward the frame-time sample, as the delivery after the UI
|
||||
@@ -662,6 +664,7 @@ impl VectorcraftApp {
|
||||
|| !self.placing.pending.is_empty()
|
||||
|| !self.trace_runs.running.is_empty()
|
||||
|| self.retype_runs.running.is_some()
|
||||
|| self.concept_runs.busy()
|
||||
{
|
||||
// Keep the status bar's progress moving and pick the result up when it arrives.
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
|
||||
@@ -280,6 +280,7 @@ fn offer(app: &VectorcraftApp, images_memo: &mut Memo, smooth_memo: &mut Memo) -
|
||||
items.push((tl!("Image Trace"), "image", TASK_BAR_IMAGE_TRACE, none()));
|
||||
items.push((tl!("Crop Image"), "dc-pf-crop", "ui.cropImage", none()));
|
||||
items.push((tl!("Remove Background"), "eraser", crate::addons::image::REMOVE_BACKGROUND, none()));
|
||||
items.push((tl!("Concept to Vector"), "sparkles", crate::panels::concept_vector::OPEN, none()));
|
||||
}
|
||||
// Direct-selected anchors take the place of a path's Offset Path and Simplify. For them the bar
|
||||
// offers Remove, Connect, Cut and Convert to corner or smooth, as the reference app does
|
||||
@@ -309,6 +310,7 @@ fn offer(app: &VectorcraftApp, images_memo: &mut Memo, smooth_memo: &mut Memo) -
|
||||
}
|
||||
} else if is_trace {
|
||||
items.push((tl!("Expand"), "maximize-2", "imageTrace.expand", none()));
|
||||
items.push((tl!("Concept to Vector"), "sparkles", crate::panels::concept_vector::OPEN, none()));
|
||||
} else if is_clip_group {
|
||||
items.push((tl!("Edit Clipping Path"), "dc-direct", "object.clippingMask.editMask", none()));
|
||||
items.push((tl!("Release Clipping Mask"), "ungroup", "object.clippingMask.release", none()));
|
||||
@@ -661,10 +663,11 @@ impl Chip {
|
||||
/// (`window.taskBar.actions {action, visible?}`): each action's id, the command its button runs and
|
||||
/// the `tool` that command names, if any. An action that is off stays out of the bar, and More
|
||||
/// Options does not list it either; turning one off changes only the bar. Every action starts on.
|
||||
pub(crate) const TASK_BAR_ACTIONS: [(&str, &str, Option<&str>); 37] = [
|
||||
pub(crate) const TASK_BAR_ACTIONS: [(&str, &str, Option<&str>); 38] = [
|
||||
("imageTrace", TASK_BAR_IMAGE_TRACE, None),
|
||||
("cropImage", "ui.cropImage", None),
|
||||
("removeBackground", crate::addons::image::REMOVE_BACKGROUND, None),
|
||||
("conceptToVector", crate::panels::concept_vector::OPEN, None),
|
||||
("removeAnchorPoints", "path.removeAnchors", None),
|
||||
("join", "path.join", None),
|
||||
("cutPath", "path.cutAtAnchors", None),
|
||||
|
||||
@@ -5435,6 +5435,27 @@ fn the_task_bar_removes_a_selected_images_background() {
|
||||
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0[3]), (0, 255), "the white background is cleared, the red dot kept");
|
||||
}
|
||||
|
||||
/// For one selected image the Contextual Task Bar offers Concept to Vector, which opens its panel;
|
||||
/// a rectangle gets no such item.
|
||||
#[test]
|
||||
fn the_task_bar_opens_concept_to_vector_for_a_selected_image() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let raw = (0..20 * 20).flat_map(|i| if i % 20 < 10 { [0, 0, 0, 255] } else { [255; 4] }).collect();
|
||||
let img = craft_image_codecs::Image::from_raw(20, 20, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).unwrap();
|
||||
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&png);
|
||||
app.run("file.place", json!({"name": "half.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap();
|
||||
app.select_tool("selection");
|
||||
let actions = task_bar_actions(&mut app);
|
||||
assert!(actions.contains(&"Concept to Vector"), "{actions:?}");
|
||||
click(&mut app, "Concept to Vector");
|
||||
assert!(crate::panel_docking::showing(&app.ui, crate::panels::concept_vector::ID), "{}", app.ui.status);
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
let actions = task_bar_actions(&mut app);
|
||||
assert!(!actions.is_empty() && !actions.contains(&"Concept to Vector"), "{actions:?}");
|
||||
}
|
||||
|
||||
/// A selected group's Contextual Task Bar offers Ungroup and Isolate. While an opacity mask is
|
||||
/// edited, when Enter Isolation Mode is off, a group in the mask art gets Ungroup without Isolate.
|
||||
#[test]
|
||||
|
||||
@@ -266,6 +266,8 @@ pub struct VectorcraftApp {
|
||||
pub placing: placing::Placing,
|
||||
/// Image Traces running off the UI thread ([`trace_runs`]).
|
||||
pub trace_runs: trace_runs::TraceRuns,
|
||||
/// The Concept to Vector panel's settings and its run off the UI thread ([`panels::concept_vector`]).
|
||||
pub concept_runs: panels::concept_vector::ConceptRuns,
|
||||
/// Retype's search of the installed fonts, off the UI thread ([`retype_runs`]).
|
||||
pub retype_runs: retype_runs::RetypeRuns,
|
||||
/// Data Recovery's timer and startup question ([`recovery`]).
|
||||
|
||||
@@ -132,6 +132,9 @@ pub fn context_items(app: &VectorcraftApp) -> Vec<Node> {
|
||||
vec![c("Auto Spell Check", "edit.autoSpellCheck"), c("Check Spelling…", crate::dialogs::check_spelling::COMMAND)],
|
||||
));
|
||||
}
|
||||
// One image or unexpanded Image Trace object; left out otherwise, as the menu leaves out
|
||||
// every command that can't run.
|
||||
v.push(c("Concept to Vector…", crate::panels::concept_vector::OPEN));
|
||||
v.extend([c("Make Guides", "view.guides.make"), Sep, sub("Transform", transform_items())]);
|
||||
if intertwine.is_none() {
|
||||
v.push(sub("Arrange", arrange_items()));
|
||||
|
||||
@@ -838,6 +838,9 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
|
||||
"tool.setOption" => app.session.set_tool_option_cmd(p),
|
||||
"effect.dialog" => crate::dialogs::open_effect_dialog(app, p),
|
||||
"ui.recolorDialog" => crate::dialogs::recolor::open(app, p),
|
||||
crate::panels::concept_vector::OPEN => crate::panels::concept_vector::open(app),
|
||||
crate::panels::concept_vector::GENERATE => crate::panels::concept_vector::generate_run(app),
|
||||
crate::panels::concept_vector::CANCEL => Ok(crate::panels::concept_vector::cancel_run(app)),
|
||||
"ui.cropImage" if !selected_image(app, |_| true) => Err("select an image".into()),
|
||||
"ui.cropImage" => app.try_select_tool(vectorcraft_tools::cropimage::ID).map(|()| json!({"tool": app.session.tool_id()})),
|
||||
"ui.paramDialog" => param_dialog(app, p),
|
||||
|
||||
@@ -385,6 +385,9 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
|
||||
id if saved_view_slot(id).is_some() => saved_view(app, id).is_some(),
|
||||
"effect.dialog" | "ui.recolorDialog" | "ui.effectGalleryDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
|
||||
"ui.cropImage" => selected_image(app, |_| true),
|
||||
crate::panels::concept_vector::OPEN => crate::panels::concept_vector::eligible(app).is_ok(),
|
||||
crate::panels::concept_vector::GENERATE => crate::panels::concept_vector::eligible(app).is_ok(),
|
||||
crate::panels::concept_vector::CANCEL => app.concept_runs.busy(),
|
||||
"effect.applyLast" | "effect.last" => app.last_effect.is_some() && app.session.active().is_some_and(|d| !d.selection.is_empty()),
|
||||
"pathfinder.repeat" => app.last_pathfinder.as_ref().is_some_and(|op| {
|
||||
let min = crate::panels::pathfinder::minimum_operands(op);
|
||||
|
||||
@@ -398,6 +398,8 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
|
||||
c("Expand", "imageTrace.expand"),
|
||||
],
|
||||
),
|
||||
// Opens the Concept to Vector panel for the selected image or Image Trace object.
|
||||
c("Concept to Vector…", crate::panels::concept_vector::OPEN),
|
||||
sub(
|
||||
"Text Wrap",
|
||||
vec![
|
||||
@@ -772,6 +774,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
|
||||
panel("Color Guide", "colorGuide"),
|
||||
panel("Color Themes", "colorThemes"),
|
||||
panel("Color Wheel", crate::panels::color_wheel::ID),
|
||||
panel("Concept to Vector", crate::panels::concept_vector::ID),
|
||||
panel("CSS Properties", crate::panels::css_properties::ID),
|
||||
panel("Document Info", "docInfo"),
|
||||
panel("Flattener Preview", crate::panels::flattener_preview::ID),
|
||||
|
||||
@@ -721,7 +721,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.taskBar.actions",
|
||||
"Bar Actions",
|
||||
"",
|
||||
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
|
||||
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"conceptToVector\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
|
||||
),
|
||||
(
|
||||
"window.taskBar.resetActions",
|
||||
@@ -1039,6 +1039,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector",
|
||||
"Concept to Vector…",
|
||||
"",
|
||||
"{} open the Concept to Vector panel for the selected image or unexpanded Image Trace object; an error when the selection is not one such object, unlocked and shown (engine: conceptVector.generate / conceptVector.insert)",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector.generate",
|
||||
"Generate Concept to Vector Styles",
|
||||
"",
|
||||
"{} make the styles ticked in the Concept to Vector panel of the selected image or unexpanded Image Trace object, with the panel's Detail (the panel's Generate; engine: conceptVector.generate), and show them in the panel; off the UI thread in the app unless VECTORCRAFT_SYNC_OPEN is set, one part a frame on the web; a run going is canceled first, and the new one starts once its thread has ended → {running: true} while they are made, else {running: false, job}",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector.cancel",
|
||||
"Cancel Concept to Vector",
|
||||
"",
|
||||
"{} stop the styles the Concept to Vector panel is making off the UI thread (the panel's Cancel; on the web, before the next part): nothing is kept or shown → {canceled: 0 or 1}",
|
||||
),
|
||||
(
|
||||
"ui.recolorUndo",
|
||||
"Undo Changes",
|
||||
|
||||
@@ -116,6 +116,7 @@ pub fn long_operation_busy(app: &VectorcraftApp) -> bool {
|
||||
|| !app.placing.pending.is_empty()
|
||||
|| !app.trace_runs.running.is_empty()
|
||||
|| crate::retype_runs::any_running(app)
|
||||
|| app.concept_runs.busy()
|
||||
}
|
||||
|
||||
/// Does opening happen off the UI thread here? Not on wasm (no threads), in unit tests (they look
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod color;
|
||||
pub mod color_guide;
|
||||
pub mod color_themes;
|
||||
pub mod color_wheel;
|
||||
pub mod concept_vector;
|
||||
pub mod css_properties;
|
||||
pub mod discover;
|
||||
pub mod doc_info;
|
||||
@@ -603,6 +604,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
|
||||
variables::ID => variables::show(app, ui),
|
||||
"colorThemes" => color_themes::show(app, ui),
|
||||
color_wheel::ID => color_wheel::show(app, ui),
|
||||
concept_vector::ID => concept_vector::show(app, ui),
|
||||
links::ID => links::show(app, ui),
|
||||
preflight::ID => preflight::show(app, ui),
|
||||
asset_export::ID => asset_export::show(app, ui),
|
||||
|
||||
@@ -0,0 +1,735 @@
|
||||
//! Concept to Vector panel (Window › Concept to Vector, Object › Concept to Vector…): vector
|
||||
//! variations of the selected image or unexpanded Image Trace object, one for each ticked style,
|
||||
//! compared side by side and inserted to the right of the image.
|
||||
//!
|
||||
//! The panel calls the built-in provider ([`offline::ID`]), whose styles are made with Image Trace
|
||||
//! on this computer: its prompt field is disabled and it makes vector art only. Generate prepares
|
||||
//! the request at once (`conceptVector.generate`'s checks) and runs the provider on a thread of its
|
||||
//! own ([`ConceptRuns`]); a new Generate cancels the one running and starts once that run's
|
||||
//! thread has ended, so one thread makes styles at a time. Results from another provider
|
||||
//! are named as that provider names its styles. The results stay in this session
|
||||
//! until Insert Selected puts the ticked ones in the document as one undo step
|
||||
//! (`conceptVector.insert`). The web build has no thread for it, so it makes one part a frame
|
||||
//! (the built-in provider: the image decoded, a style's color layers found, or one color layer
|
||||
//! traced, or all of them for a style that stacks its layers), and Cancel takes effect before the
|
||||
//! next part. Unit tests that set neither
|
||||
//! `off_the_ui_thread` nor `by_frames` run the command at once.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc::{Receiver, TryRecvError, channel};
|
||||
|
||||
use craft::behavior::Mixed;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::display::{Divider, Picture, PictureSize, Progress, Shade, Text};
|
||||
use craft::ui::form::{Field, SliderField, SliderFieldLayout};
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::text::TextField;
|
||||
use egui::{Color32, Pos2, Rect, Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::cancel::CancelToken;
|
||||
use vectorcraft_engine::cmd::conceptvector::{ConceptRun, PartRun, provider_error};
|
||||
use vectorcraft_engine::concept_vector::{MAX_STYLES, ProviderError, Variation, offline};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
pub const ID: &str = "conceptVector";
|
||||
|
||||
/// The UI command that opens the panel for the selected image.
|
||||
pub const OPEN: &str = "ui.conceptVector";
|
||||
|
||||
/// The UI command of the panel's Generate: it makes the ticked styles of the selection.
|
||||
pub const GENERATE: &str = "ui.conceptVector.generate";
|
||||
|
||||
/// The UI command of the panel's Cancel: it stops the styles being made.
|
||||
pub const CANCEL: &str = "ui.conceptVector.cancel";
|
||||
|
||||
/// What the status bar says while styles are made.
|
||||
const LABEL: &str = "Making the Concept to Vector styles";
|
||||
|
||||
/// The most points a preview draws; the points past them are left out of it.
|
||||
const PREVIEW_POINTS: usize = 40_000;
|
||||
|
||||
/// A preview's height in points.
|
||||
const PREVIEW_H: f32 = 110.0;
|
||||
|
||||
/// Pixels per point of a preview's painted image.
|
||||
const PREVIEW_SCALE: f32 = 2.0;
|
||||
|
||||
/// The thinnest a preview draws a stroke, in points, so that thin lines still show.
|
||||
const MIN_STROKE: f32 = 0.5;
|
||||
|
||||
/// The color a preview paints its paths over: the paper of the image's box, which the variations'
|
||||
/// own colors are drawn on.
|
||||
const PAPER: Color32 = Color32::WHITE;
|
||||
|
||||
/// What a run's thread hands back.
|
||||
type Done = (ConceptRun, Result<Vec<Variation>, ProviderError>);
|
||||
|
||||
/// How a Generate runs.
|
||||
enum Work {
|
||||
/// On a thread of its own, which hands back its results.
|
||||
Thread(Receiver<Done>),
|
||||
/// On the UI thread, one part a frame ([`ConceptRun::run_part`]), where no thread can run it.
|
||||
Frames(Box<ConceptRun>, PartRun),
|
||||
/// Waiting for the thread of a canceled run to end before it starts on a thread of its own, so
|
||||
/// that one thread makes styles at a time.
|
||||
Queued(Box<ConceptRun>),
|
||||
}
|
||||
|
||||
/// A Generate running.
|
||||
struct Running {
|
||||
token: CancelToken,
|
||||
/// Styles made and in all.
|
||||
steps: Arc<[AtomicU64; 2]>,
|
||||
work: Work,
|
||||
}
|
||||
|
||||
/// One variation as the panel draws it: its fills and strokes painted into `image` in the order of
|
||||
/// its paths.
|
||||
struct Preview {
|
||||
style: String,
|
||||
label: String,
|
||||
aspect: f32,
|
||||
image: egui::ColorImage,
|
||||
/// The key the panel's picture stores `image` under: one for each job and style.
|
||||
key: u64,
|
||||
warnings: Vec<String>,
|
||||
/// Part of the variation is left out of `image` ([`PREVIEW_POINTS`]).
|
||||
cut: bool,
|
||||
}
|
||||
|
||||
/// The job the panel shows.
|
||||
struct Shown {
|
||||
job: u64,
|
||||
/// The document the job was made in ([`vectorcraft_engine::DocState::uid`]): the results show
|
||||
/// only while it is the active one.
|
||||
doc: u64,
|
||||
previews: Vec<Preview>,
|
||||
/// The styles ticked for Insert Selected.
|
||||
picked: Vec<String>,
|
||||
}
|
||||
|
||||
/// The panel's settings and its run.
|
||||
pub struct ConceptRuns {
|
||||
styles: Vec<String>,
|
||||
detail: u8,
|
||||
running: Option<Running>,
|
||||
/// The thread of a canceled run, until it ends.
|
||||
stopping: Option<Receiver<Done>>,
|
||||
shown: Option<Shown>,
|
||||
/// The provider Generate calls: the built-in one, or another in unit tests.
|
||||
pub(crate) provider: &'static str,
|
||||
/// Set by unit tests whose app makes styles off the UI thread.
|
||||
pub(crate) off_the_ui_thread: bool,
|
||||
/// Set by unit tests whose app makes styles one a frame, as the web build does.
|
||||
pub(crate) by_frames: bool,
|
||||
}
|
||||
|
||||
impl Default for ConceptRuns {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
styles: offline::STYLES.iter().map(|s| s.id.to_string()).collect(),
|
||||
detail: 50,
|
||||
running: None,
|
||||
stopping: None,
|
||||
shown: None,
|
||||
provider: offline::ID,
|
||||
off_the_ui_thread: false,
|
||||
by_frames: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConceptRuns {
|
||||
/// Is a Generate running?
|
||||
pub fn busy(&self) -> bool {
|
||||
self.running.is_some()
|
||||
}
|
||||
|
||||
/// The job the panel shows.
|
||||
pub fn job(&self) -> Option<u64> {
|
||||
self.shown.as_ref().map(|s| s.job)
|
||||
}
|
||||
}
|
||||
|
||||
/// The params of `conceptVector.generate` for the panel's settings.
|
||||
fn params(app: &VectorcraftApp) -> Value {
|
||||
json!({ "provider": app.concept_runs.provider, "styles": app.concept_runs.styles, "detail": app.concept_runs.detail })
|
||||
}
|
||||
|
||||
/// Whether the panel can make styles of the selection; else why not.
|
||||
pub fn eligible(app: &VectorcraftApp) -> Result<(), String> {
|
||||
let p = json!({ "provider": offline::ID, "styles": [offline::STYLES[0].id] });
|
||||
ConceptRun::prepare(&app.session, &p).map(|_| ()).map_err(|e| match e {
|
||||
vectorcraft_engine::EngineError::BadParams { msg, .. } => msg,
|
||||
e => e.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `ui.conceptVector`: opens the panel for the selection; an error when it has nothing to use.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
eligible(app)?;
|
||||
app.run("window.panel.activate", json!({ "panel": ID }))
|
||||
}
|
||||
|
||||
/// Makes the ticked styles of the selection: off the UI thread where it can; on the web, one part
|
||||
/// a frame; else (unit tests, `VECTORCRAFT_SYNC_OPEN`) at once.
|
||||
pub fn generate(app: &mut VectorcraftApp) -> Result<(), String> {
|
||||
let p = params(app);
|
||||
let frames = cfg!(target_arch = "wasm32") || app.concept_runs.by_frames;
|
||||
if !(frames || app.concept_runs.off_the_ui_thread || crate::opening::available()) {
|
||||
let v = app.run("conceptVector.generate", p)?;
|
||||
show_job(app, &v);
|
||||
return Ok(());
|
||||
}
|
||||
let run = ConceptRun::prepare(&app.session, &p).map_err(|e| e.to_string())?;
|
||||
cancel(app);
|
||||
let token = CancelToken::new();
|
||||
let steps = Arc::new([AtomicU64::new(0), AtomicU64::new(run.style_count() as u64)]);
|
||||
let work = if frames {
|
||||
Work::Frames(Box::new(run), PartRun::default())
|
||||
} else if worker_ended(&mut app.concept_runs) {
|
||||
spawn(run, &token, &steps)?
|
||||
} else {
|
||||
Work::Queued(Box::new(run))
|
||||
};
|
||||
app.concept_runs.running = Some(Running { token, steps, work });
|
||||
if let Some(ctx) = &app.ui_ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
app.status(format!("{}…", crate::i18n::msg(LABEL)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts `run` on a thread of its own, which stops once `token` is canceled and counts the styles
|
||||
/// made in `steps`.
|
||||
fn spawn(run: ConceptRun, token: &CancelToken, steps: &Arc<[AtomicU64; 2]>) -> Result<Work, String> {
|
||||
let (tx, done) = channel();
|
||||
let stop = token.clone();
|
||||
let counts = Arc::clone(steps);
|
||||
std::thread::Builder::new()
|
||||
.name("vectorcraft-concept".into())
|
||||
.spawn(move || {
|
||||
let [done_now, total_now] = &*counts;
|
||||
let report = |done: u64, total: u64| {
|
||||
done_now.store(done, Ordering::Relaxed);
|
||||
total_now.store(total, Ordering::Relaxed);
|
||||
!stop.is_cancelled()
|
||||
};
|
||||
let made = run.run(&report);
|
||||
// The app may have quit, or the run was canceled: nothing to hand it to.
|
||||
let _ = tx.send((run, made));
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Work::Thread(done))
|
||||
}
|
||||
|
||||
/// Whether no canceled run's thread is still going: it has handed back its results, which are
|
||||
/// dropped, or ended.
|
||||
fn worker_ended(runs: &mut ConceptRuns) -> bool {
|
||||
let ended = runs.stopping.as_ref().is_none_or(|rx| !matches!(rx.try_recv(), Err(TryRecvError::Empty)));
|
||||
if ended {
|
||||
runs.stopping = None;
|
||||
}
|
||||
ended
|
||||
}
|
||||
|
||||
/// Cancel: the run stops at its next check (on the web, before its next part), and its results
|
||||
/// are dropped. A run on a thread is kept track of until its thread ends, and the next Generate
|
||||
/// waits for that.
|
||||
pub fn cancel(app: &mut VectorcraftApp) {
|
||||
if let Some(r) = app.concept_runs.running.take() {
|
||||
r.token.cancel();
|
||||
if let Work::Thread(rx) = r.work {
|
||||
app.concept_runs.stopping = Some(rx);
|
||||
}
|
||||
if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) {
|
||||
app.ui.status.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.conceptVector.generate`, the panel's Generate: makes the ticked styles of the selection
|
||||
/// with the panel's Detail → `{running: true}` while they are made off the UI thread (or one part
|
||||
/// a frame on the web), else `{running: false, job}` with the job shown.
|
||||
pub fn generate_run(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
generate(app)?;
|
||||
Ok(if app.concept_runs.busy() { json!({ "running": true }) } else { json!({ "running": false, "job": app.concept_runs.job() }) })
|
||||
}
|
||||
|
||||
/// `ui.conceptVector.cancel`, the panel's Cancel: stops the styles being made, and says so in the
|
||||
/// status bar → `{canceled: 0 or 1}`.
|
||||
pub fn cancel_run(app: &mut VectorcraftApp) -> Value {
|
||||
if !app.concept_runs.busy() {
|
||||
return json!({ "canceled": 0 });
|
||||
}
|
||||
cancel(app);
|
||||
app.status(vectorcraft_engine::EngineError::Cancelled.to_string());
|
||||
json!({ "canceled": 1 })
|
||||
}
|
||||
|
||||
/// Each frame: makes the next part of a run made one part a frame, and keeps a finished run's
|
||||
/// results as a job and shows it. Not while a dialog or an interaction is open, as
|
||||
/// [`crate::trace_runs::poll`].
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
if app.asking_dialog_open() || app.session.in_interaction() {
|
||||
return;
|
||||
}
|
||||
// A run waiting for a canceled run's thread starts once that thread has ended.
|
||||
if matches!(app.concept_runs.running.as_ref().map(|r| &r.work), Some(Work::Queued(_))) {
|
||||
if !worker_ended(&mut app.concept_runs) {
|
||||
return;
|
||||
}
|
||||
let Some(Running { token, steps, work: Work::Queued(run) }) = app.concept_runs.running.take() else { return };
|
||||
match spawn(*run, &token, &steps) {
|
||||
Ok(work) => app.concept_runs.running = Some(Running { token, steps, work }),
|
||||
Err(e) => app.status(e),
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(r) = app.concept_runs.running.as_mut() else { return };
|
||||
let ended = match &mut r.work {
|
||||
Work::Thread(_) | Work::Queued(_) => None,
|
||||
Work::Frames(run, made) => {
|
||||
let stop = r.token.clone();
|
||||
match run.run_part(made, &|_, _| !stop.is_cancelled()) {
|
||||
Ok(false) => {
|
||||
r.steps[0].store(made.styles_done() as u64, Ordering::Relaxed);
|
||||
if let Some(ctx) = &app.ui_ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
return;
|
||||
}
|
||||
Ok(true) => Some(Ok(())),
|
||||
Err(e) => Some(Err(e)),
|
||||
}
|
||||
}
|
||||
};
|
||||
let received = match (&ended, &r.work) {
|
||||
(None, Work::Thread(rx)) => match rx.try_recv() {
|
||||
Ok(done) => Some(done),
|
||||
Err(TryRecvError::Empty) => return,
|
||||
Err(TryRecvError::Disconnected) => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let Some(r) = app.concept_runs.running.take() else { return };
|
||||
let done = match (ended, r.work) {
|
||||
(Some(end), Work::Frames(run, made)) => Some((*run, end.map(|()| made.made()))),
|
||||
_ => received,
|
||||
};
|
||||
finish(app, &r.token, done);
|
||||
}
|
||||
|
||||
/// Keeps a run's results `done` as a job and shows it; else why there are none, in the status bar.
|
||||
/// Nothing when `token` was canceled.
|
||||
fn finish(app: &mut VectorcraftApp, token: &CancelToken, done: Option<Done>) {
|
||||
if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) {
|
||||
app.ui.status.clear();
|
||||
}
|
||||
if token.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
match done {
|
||||
// Nothing is kept or shown when the run's document has closed.
|
||||
Some((run, Ok(made))) => {
|
||||
if let Some(v) = run.finish(&mut app.session, made) {
|
||||
show_job(app, &v);
|
||||
}
|
||||
}
|
||||
Some((_, Err(e))) => app.status(provider_error(e).to_string()),
|
||||
None => app.status("Concept to Vector stopped: its thread ended without results (please report this bug)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the variations of `job` (a job as `conceptVector.generate` returns it), every one ticked,
|
||||
/// each named as the job names its style: by the name its provider gives the style.
|
||||
fn show_job(app: &mut VectorcraftApp, job: &Value) {
|
||||
let Some(id) = job["job"].as_u64() else { return };
|
||||
let Some(doc) = app.session.concept_job_doc(id) else { return };
|
||||
let Some((variations, (w, h))) = app.session.concept_variations(id) else { return };
|
||||
let listed = job["variations"].as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
let label_of = |style: &str| listed.iter().find(|v| v["style"] == style).and_then(|v| v["label"].as_str());
|
||||
let previews: Vec<Preview> = variations
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let label = label_of(&v.style).map_or_else(|| v.style.clone(), str::to_string);
|
||||
Preview { key: preview_key(id, &v.style), ..preview(v, label, (w, h)) }
|
||||
})
|
||||
.collect();
|
||||
let picked = previews.iter().map(|p| p.style.clone()).collect();
|
||||
app.concept_runs.shown = Some(Shown { job: id, doc, previews, picked });
|
||||
}
|
||||
|
||||
/// The key a preview of `style` in job `job` is stored under as a picture.
|
||||
fn preview_key(job: u64, style: &str) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
("concept-vector", job, style).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// A preview's width in points, `height` high, for an image `aspect` wide per unit high.
|
||||
fn preview_width(aspect: f32, height: f32) -> f32 {
|
||||
(height * aspect).clamp(height * 0.4, height * 2.5)
|
||||
}
|
||||
|
||||
/// The box an image `aspect` wide per unit high takes inside `inner`: as large as fits, centered,
|
||||
/// so a preview whose width [`preview_width`] clamps keeps the image's proportions.
|
||||
fn art_rect(inner: Rect, aspect: f32) -> Rect {
|
||||
let size = vec2(inner.width().min(inner.height() * aspect), inner.height().min(inner.width() / aspect));
|
||||
Rect::from_center_size(inner.center(), size)
|
||||
}
|
||||
|
||||
/// The size in pixels of the fills of a preview of an image `aspect` wide per unit high: its
|
||||
/// [`art_rect`] inside the 4 pt margin, at [`PREVIEW_SCALE`].
|
||||
fn image_size(aspect: f32) -> [usize; 2] {
|
||||
let inner = Rect::from_min_size(Pos2::ZERO, vec2(preview_width(aspect, PREVIEW_H), PREVIEW_H)).shrink(4.0);
|
||||
let art = art_rect(inner, aspect);
|
||||
let px = |pt: f32| (pt * PREVIEW_SCALE).round().max(1.0) as usize;
|
||||
[px(art.width()), px(art.height())]
|
||||
}
|
||||
|
||||
/// Paints `rings` (polylines in 0..1 of the image's box, each closed, nonzero winding) in `color`
|
||||
/// over `img`, antialiased with four samples a pixel high.
|
||||
fn fill_rings(img: &mut egui::ColorImage, rings: &[Vec<Pos2>], color: Color32) {
|
||||
const SUB: usize = 4;
|
||||
let [w, h] = img.size;
|
||||
let (sx, sy) = (w as f32, h as f32);
|
||||
let mut edges: Vec<(f32, f32, f32, f32)> = vec![];
|
||||
for ring in rings {
|
||||
for (a, b) in ring.iter().zip(ring.iter().skip(1).chain(ring.first())) {
|
||||
edges.push((a.x * sx, a.y * sy, b.x * sx, b.y * sy));
|
||||
}
|
||||
}
|
||||
let top = edges.iter().map(|e| e.1.min(e.3)).fold(f32::INFINITY, f32::min);
|
||||
let bottom = edges.iter().map(|e| e.1.max(e.3)).fold(f32::NEG_INFINITY, f32::max);
|
||||
let left = edges.iter().map(|e| e.0.min(e.2)).fold(f32::INFINITY, f32::min);
|
||||
let right = edges.iter().map(|e| e.0.max(e.2)).fold(f32::NEG_INFINITY, f32::max);
|
||||
if !(top.is_finite() && bottom.is_finite() && left.is_finite() && right.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let (y0, y1) = (top.floor().clamp(0.0, sy) as usize, bottom.ceil().clamp(0.0, sy) as usize);
|
||||
// Only the columns the rings reach: `cover[i]` is column `c0 + i`.
|
||||
let (c0, c1) = (left.floor().clamp(0.0, sx) as usize, right.ceil().clamp(0.0, sx) as usize);
|
||||
let mut cover = vec![0f32; c1.saturating_sub(c0)];
|
||||
let mut xs: Vec<(f32, i32)> = vec![];
|
||||
// Each sample row looks only at the edges that reach it: the edges in order of their tops are
|
||||
// taken in as the rows reach them, and dropped once the rows pass their bottoms.
|
||||
edges.sort_by(|a, b| a.1.min(a.3).total_cmp(&b.1.min(b.3)));
|
||||
let (mut next, mut active) = (0, Vec::<(f32, f32, f32, f32)>::new());
|
||||
for row in y0..y1 {
|
||||
cover.fill(0.0);
|
||||
for k in 0..SUB {
|
||||
let y = row as f32 + (k as f32 + 0.5) / SUB as f32;
|
||||
while let Some(&e) = edges.get(next).filter(|e| e.1.min(e.3) <= y) {
|
||||
active.push(e);
|
||||
next += 1;
|
||||
}
|
||||
active.retain(|e| e.1.max(e.3) > y);
|
||||
xs.clear();
|
||||
for &(x0, ya, x1, yb) in &active {
|
||||
if (ya <= y) != (yb <= y) {
|
||||
xs.push((x0 + (y - ya) / (yb - ya) * (x1 - x0), if yb > ya { 1 } else { -1 }));
|
||||
}
|
||||
}
|
||||
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut wind = 0;
|
||||
for pair in xs.windows(2) {
|
||||
wind += pair[0].1;
|
||||
let (a, b) = (pair[0].0.max(0.0), pair[1].0.min(sx));
|
||||
if wind == 0 || b <= a {
|
||||
continue;
|
||||
}
|
||||
let (start, end) = ((a.floor() as usize).saturating_sub(c0), (b.ceil() as usize).min(c1).saturating_sub(c0));
|
||||
for (i, c) in cover.iter_mut().enumerate().take(end).skip(start) {
|
||||
let px = (c0 + i) as f32;
|
||||
*c += (b.min(px + 1.0) - a.max(px)).max(0.0) / SUB as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, c) in cover.iter().enumerate().filter(|(_, c)| **c > 0.0) {
|
||||
let px = c0 + i;
|
||||
let a = c.min(1.0);
|
||||
let mix = |s: u8, t: u8| (f32::from(t) * a + f32::from(s) * (1.0 - a)).round() as u8;
|
||||
if let Some(d) = img.pixels.get_mut(row * w + px) {
|
||||
*d = Color32::from_rgb(mix(d.r(), color.r()), mix(d.g(), color.g()), mix(d.b(), color.b()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints `rings` (polylines in 0..1 of the image's box) stroked `width` pixels wide in `color`
|
||||
/// over `img`: each segment as a rectangle, with a disc at each point for round joins and caps
|
||||
/// once the stroke is wide enough for them to show. With `square_caps`, an open line has no disc
|
||||
/// at its ends, and its end segments reach half the width past them.
|
||||
fn stroke_rings(img: &mut egui::ColorImage, rings: &[Vec<Pos2>], width: f32, color: Color32, square_caps: bool) {
|
||||
let (sx, sy) = (img.size[0] as f32, img.size[1] as f32);
|
||||
let r = width / 2.0;
|
||||
let unit = |p: Pos2| Pos2::new(p.x / sx, p.y / sy);
|
||||
for ring in rings {
|
||||
let pts: Vec<Pos2> = ring.iter().map(|q| Pos2::new(q.x * sx, q.y * sy)).collect();
|
||||
let last = pts.len().saturating_sub(1);
|
||||
let square = square_caps && pts.len() > 1 && pts.first() != pts.last();
|
||||
for (k, a) in pts.iter().enumerate() {
|
||||
if r > 0.75 && !(square && (k == 0 || k == last)) {
|
||||
let disc: Vec<Pos2> = (0..8)
|
||||
.map(|i| {
|
||||
let t = i as f32 * std::f32::consts::TAU / 8.0;
|
||||
unit(*a + vec2(t.cos(), t.sin()) * r)
|
||||
})
|
||||
.collect();
|
||||
fill_rings(img, &[disc], color);
|
||||
}
|
||||
let Some(b) = pts.get(k + 1) else { continue };
|
||||
let d = *b - *a;
|
||||
let len = d.length();
|
||||
if len > 0.0 {
|
||||
let n = vec2(-d.y, d.x) * (r / len);
|
||||
let along = d * (r / len);
|
||||
let a = if square && k == 0 { *a - along } else { *a };
|
||||
let b = if square && k + 1 == last { *b + along } else { *b };
|
||||
fill_rings(img, &[vec![unit(a + n), unit(b + n), unit(b - n), unit(a - n)]], color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `path`'s elements, made as they are taken, so that taking the first few of a long path does
|
||||
/// not convert the rest.
|
||||
fn elements(path: &vectorcraft_geom::PathData) -> impl Iterator<Item = vectorcraft_geom::PathEl> + '_ {
|
||||
use vectorcraft_geom::PathEl;
|
||||
path.subpaths.iter().filter_map(|sp| sp.anchors.first().map(|first| (sp, first.p))).flat_map(|(sp, start)| {
|
||||
let segments = (0..sp.segment_count()).map(move |i| {
|
||||
let c = sp.segment(i);
|
||||
if sp.segment_is_line(i) { PathEl::LineTo(c.p3) } else { PathEl::CurveTo(c.p1, c.p2, c.p3) }
|
||||
});
|
||||
std::iter::once(PathEl::MoveTo(start)).chain(segments).chain(sp.closed.then_some(PathEl::ClosePath))
|
||||
})
|
||||
}
|
||||
|
||||
/// `els` until no point is `left` to take, checked as each element is taken; a closing element
|
||||
/// still closes its ring.
|
||||
fn within_budget<'a>(
|
||||
els: impl Iterator<Item = vectorcraft_geom::PathEl> + 'a,
|
||||
left: &'a std::cell::Cell<usize>,
|
||||
) -> impl Iterator<Item = vectorcraft_geom::PathEl> + 'a {
|
||||
els.take_while(move |el| left.get() > 0 || matches!(el, vectorcraft_geom::PathEl::ClosePath))
|
||||
}
|
||||
|
||||
/// How many elements [`elements`] makes of `path`.
|
||||
fn element_count(path: &vectorcraft_geom::PathData) -> usize {
|
||||
path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).map(|sp| 1 + sp.segment_count() + usize::from(sp.closed)).sum()
|
||||
}
|
||||
|
||||
/// Variation `v` of an image `size` pixels big: its paths painted in order, each path's fill and
|
||||
/// then its stroke, stopping after [`PREVIEW_POINTS`] points in all, and whether that left part of
|
||||
/// it out ([`Preview::cut`]).
|
||||
fn preview(v: &Variation, label: String, size: (u32, u32)) -> Preview {
|
||||
let (w, h) = (f64::from(size.0.max(1)), f64::from(size.1.max(1)));
|
||||
let aspect = (w / h) as f32;
|
||||
let mut image = egui::ColorImage::filled(image_size(aspect), PAPER);
|
||||
let left = std::cell::Cell::new(PREVIEW_POINTS);
|
||||
let at = |q: vectorcraft_geom::Point| Pos2::new((q.x / w) as f32, (q.y / h) as f32);
|
||||
let rgb = |[r, g, b]: [u8; 3]| Color32::from_rgb(r, g, b);
|
||||
let cut = std::cell::Cell::new(false);
|
||||
for p in &v.paths {
|
||||
if left.get() == 0 {
|
||||
cut.set(true);
|
||||
break;
|
||||
}
|
||||
let mut rings: Vec<Vec<Pos2>> = vec![];
|
||||
let mut ring: Vec<Pos2> = vec![];
|
||||
let taken = std::cell::Cell::new(0usize);
|
||||
// Counted after `within_budget`, so the element it stops at is not counted as drawn.
|
||||
let els = within_budget(elements(&p.path), &left).inspect(|_| taken.set(taken.get() + 1));
|
||||
// `flatten` takes an element only after the points of the one before, and makes a bounded
|
||||
// number of each curve, so the elements past the points left are neither made nor flattened.
|
||||
vectorcraft_geom::flatten(els, (w.max(h) / 400.0).max(0.25), |el| {
|
||||
let q = match el {
|
||||
vectorcraft_geom::PathEl::MoveTo(q) => {
|
||||
if ring.len() > 1 {
|
||||
rings.push(std::mem::take(&mut ring));
|
||||
}
|
||||
ring.clear();
|
||||
q
|
||||
}
|
||||
vectorcraft_geom::PathEl::LineTo(q) => q,
|
||||
vectorcraft_geom::PathEl::ClosePath => {
|
||||
if let Some(first) = ring.first().copied() {
|
||||
ring.push(first);
|
||||
}
|
||||
if ring.len() > 1 {
|
||||
rings.push(std::mem::take(&mut ring));
|
||||
}
|
||||
ring.clear();
|
||||
return;
|
||||
}
|
||||
_ => return,
|
||||
};
|
||||
if left.get() > 0 {
|
||||
left.set(left.get() - 1);
|
||||
ring.push(at(q));
|
||||
} else {
|
||||
cut.set(true);
|
||||
}
|
||||
});
|
||||
if taken.get() < element_count(&p.path) {
|
||||
cut.set(true);
|
||||
}
|
||||
if ring.len() > 1 {
|
||||
rings.push(ring);
|
||||
}
|
||||
if let Some(c) = p.fill {
|
||||
fill_rings(&mut image, &rings, rgb(c));
|
||||
}
|
||||
if let Some((c, width)) = p.stroke {
|
||||
// To scale with the image, and at least MIN_STROKE points.
|
||||
let px = ((width / w) as f32 * image.size[0] as f32).max(MIN_STROKE * PREVIEW_SCALE);
|
||||
stroke_rings(&mut image, &rings, px, rgb(c), p.square_caps);
|
||||
}
|
||||
}
|
||||
Preview { style: v.style.clone(), label, aspect, image, key: 0, warnings: v.warnings.clone(), cut: cut.get() }
|
||||
}
|
||||
|
||||
/// Insert Selected: the ticked variations go to the right of the image, as one undo step.
|
||||
pub fn insert(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let Some(shown) = &app.concept_runs.shown else { return Err("`job` must be a job number from conceptVector.generate".into()) };
|
||||
let p = json!({ "job": shown.job, "variations": shown.picked });
|
||||
app.run("conceptVector.insert", p)
|
||||
}
|
||||
|
||||
/// A style's name as shown: translated as Image Trace's preset of that name where the catalog has
|
||||
/// one (the Outline style is not the Outline view), as any other string else.
|
||||
fn style_name(label: &str) -> &str {
|
||||
crate::i18n::tr_ctx(crate::i18n::current(), "imageTrace", label)
|
||||
}
|
||||
|
||||
/// Draws preview `p` as a large thumbnail at the image's proportions, named for a screen reader by
|
||||
/// its style.
|
||||
fn draw_preview(ui: &mut Ui, p: &Preview) {
|
||||
let image = || p.image.clone();
|
||||
Picture::new(style_name(&p.label).to_string(), p.key, &image)
|
||||
.aspect(ThumbAspect::from_ratio(p.aspect))
|
||||
.extent(PictureSize::Thumb(ThumbSize::Large))
|
||||
.show(ui);
|
||||
}
|
||||
|
||||
/// The panel: the provider's note, a check box for each style (at most [`MAX_STYLES`] ticked),
|
||||
/// Detail, the prompt field the built-in provider leaves disabled, then Generate (`ui.conceptVector.generate`)
|
||||
/// or, while styles are made, their progress and Cancel (`ui.conceptVector.cancel`), and the results.
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
Text::new(tl!("Offline Image Trace styles, made on this computer")).shade(Shade::Muted).show(ui);
|
||||
let ready = eligible(app);
|
||||
let count = app.concept_runs.styles.len();
|
||||
Field::new(tl!("Styles")).show(ui, |ui, _| {
|
||||
Text::new(format!("{count} / {MAX_STYLES}")).show(ui);
|
||||
});
|
||||
let mut toggled = None;
|
||||
for s in &offline::STYLES {
|
||||
let on = app.concept_runs.styles.iter().any(|id| id == s.id);
|
||||
let allowed = on || count < MAX_STYLES;
|
||||
let picked = Checkbox::new(Bind::given(on)).label(style_name(s.label)).id_salt(("concept-style", s.id)).enabled(allowed).show(ui);
|
||||
if let Some(next) = picked.value().copied().filter(|next| *next != on) {
|
||||
toggled = Some((s.id, next));
|
||||
}
|
||||
}
|
||||
if let Some((id, on)) = toggled {
|
||||
let styles = &mut app.concept_runs.styles;
|
||||
styles.retain(|s| s != id);
|
||||
if on {
|
||||
styles.push(id.to_string());
|
||||
// In the provider's order.
|
||||
styles.sort_by_key(|s| offline::STYLES.iter().position(|st| st.id == s));
|
||||
}
|
||||
}
|
||||
let detail = f64::from(app.concept_runs.detail);
|
||||
let edited = Field::new(tl!("Detail"))
|
||||
.show(ui, |ui, _| {
|
||||
SliderField::new(tl!("Detail"), Bind::given(detail), 0.0..=100.0).layout(SliderFieldLayout::Inline).step(1.0).show(ui).value().copied()
|
||||
})
|
||||
.inner
|
||||
.flatten();
|
||||
if let Some(v) = edited.filter(|v| *v != detail) {
|
||||
app.concept_runs.detail = v.round().clamp(0.0, 100.0) as u8;
|
||||
}
|
||||
TextField::new(tl!("Offline styles do not use prompts"), Bind::given(Mixed::Same(String::new())))
|
||||
.placeholder(tl!("Offline styles do not use prompts"))
|
||||
.enabled(false)
|
||||
.show(ui);
|
||||
if let Some(r) = &app.concept_runs.running {
|
||||
let (done, total) = (r.steps[0].load(Ordering::Relaxed), r.steps[1].load(Ordering::Relaxed));
|
||||
let frac = if total > 0 { done.min(total) as f32 / total as f32 } else { 0.0 };
|
||||
Progress::new(frac).label(tl!("Making the Concept to Vector styles")).show(ui);
|
||||
if Button::new(tl!("Cancel")).show(ui).clicked()
|
||||
&& let Err(e) = app.run(CANCEL, json!({}))
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
|
||||
} else {
|
||||
let can = ready.is_ok() && count > 0;
|
||||
if Button::new(tl!("Generate")).enabled(can).show(ui).clicked()
|
||||
&& let Err(e) = app.run(GENERATE, json!({}))
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
if let Err(why) = &ready {
|
||||
Text::new(crate::i18n::msg(why).to_string()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
show_results(app, ui);
|
||||
}
|
||||
|
||||
/// The comparison strip of the job shown, with a tick on each and Insert Selected, while the
|
||||
/// document it was made in is the active one. Nothing, and the job is no longer shown, once the
|
||||
/// session has dropped it (its document closed).
|
||||
fn show_results(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if app.concept_runs.job().is_some_and(|job| app.session.concept_variations(job).is_none()) {
|
||||
app.concept_runs.shown = None;
|
||||
}
|
||||
let active = app.session.active().map(|d| d.uid);
|
||||
let Some(Shown { previews, picked, doc, .. }) = &mut app.concept_runs.shown else { return };
|
||||
if active != Some(*doc) {
|
||||
return;
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
let mut toggled = None;
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
for p in previews.iter() {
|
||||
Stack::new().id_salt(("concept-result", &p.style)).show(ui, |ui, _| {
|
||||
draw_preview(ui, p);
|
||||
let on = picked.contains(&p.style);
|
||||
let out = Checkbox::new(Bind::given(on)).label(style_name(&p.label).to_string()).id_salt(("concept-pick", &p.style)).show(ui);
|
||||
if let Some(next) = out.value().copied().filter(|next| *next != on) {
|
||||
toggled = Some((p.style.clone(), next));
|
||||
}
|
||||
if p.cut {
|
||||
Text::new(tl!("The preview leaves out part of this style")).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
for w in &p.warnings {
|
||||
Text::new(w.clone()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some((style, on)) = toggled {
|
||||
picked.retain(|s| *s != style);
|
||||
if on {
|
||||
picked.push(style);
|
||||
}
|
||||
}
|
||||
let any = !picked.is_empty();
|
||||
if Button::new(tl!("Insert Selected")).enabled(any).show(ui).clicked()
|
||||
&& let Err(e) = insert(app)
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,615 @@
|
||||
//! The Concept to Vector panel drawn headless: its routes (Window, Object, the context menu,
|
||||
//! Properties and the Control bar), why it can't run, the style limit, the disabled prompt,
|
||||
//! Generate at once and off the UI thread, Cancel, and Insert Selected as one undo step.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Color32, Pos2, Rect, vec2};
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::concept_vector::{Capabilities, Provider, ProviderError, Request, Steps, Style, Variation, VectorPath, offline};
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
|
||||
use super::{
|
||||
CANCEL, GENERATE, ID, OPEN, PREVIEW_H, PREVIEW_POINTS, Work, art_rect, cancel, elements, finish, generate, insert, poll, preview, preview_width,
|
||||
show, show_job, within_budget,
|
||||
};
|
||||
use crate::tests_labels::painted_text;
|
||||
use crate::tests_removeanchors::{at, click_control, control_frame, has, properties_frame};
|
||||
use crate::{VectorcraftApp, menus};
|
||||
|
||||
/// Waits for the run on its thread to end and keeps its results, as `poll` does once they are there.
|
||||
fn wait(app: &mut VectorcraftApp) {
|
||||
let Some(r) = app.concept_runs.running.take() else { return };
|
||||
let Work::Thread(rx) = &r.work else { panic!("the run is not on a thread") };
|
||||
let done = rx.recv().ok();
|
||||
finish(app, &r.token, done);
|
||||
}
|
||||
|
||||
/// The styles made so far of a run made one part a frame.
|
||||
fn made_so_far(app: &VectorcraftApp) -> Option<usize> {
|
||||
match &app.concept_runs.running.as_ref()?.work {
|
||||
Work::Frames(_, made) => Some(made.styles_done()),
|
||||
Work::Thread(_) | Work::Queued(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A PNG of `w` × `h` pixels: black on the left half, a red square on the right, white elsewhere.
|
||||
fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_fn(w, h, |x, y| {
|
||||
image::Rgba(if x < w / 2 {
|
||||
[0, 0, 0, 255]
|
||||
} else if (w * 5 / 8..w * 7 / 8).contains(&x) && (h / 4..h * 3 / 4).contains(&y) {
|
||||
[220, 30, 30, 255]
|
||||
} else {
|
||||
[255; 4]
|
||||
})
|
||||
});
|
||||
let mut out = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// An app with a 400 × 300 document and one embedded image of 40 × 30 pixels, selected.
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&png(40, 30));
|
||||
app.run("file.place", json!({"name": "art.png", "dataBase64": data, "link": false, "at": [60, 60]})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn undo_steps(app: &VectorcraftApp) -> usize {
|
||||
app.session.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn root_count(app: &VectorcraftApp) -> usize {
|
||||
app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_panel_is_registered_with_a_bundled_icon_and_opens_from_window() {
|
||||
let row = crate::state::ICON_PANELS.iter().find(|(id, ..)| *id == ID).expect("registered");
|
||||
assert_eq!(row.1, "Concept to Vector");
|
||||
crate::icons::register();
|
||||
assert!(craft::ui::primitives::has_icon(&craft::behavior::IconId::new(row.2)), "{}", row.2);
|
||||
let mut app = app();
|
||||
let item = menus::menu_entries(&app).into_iter().find(|e| e.path == ["Window"] && e.label == "Concept to Vector").expect("Window item");
|
||||
let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
|
||||
menus::invoke(&mut app, &id, p);
|
||||
assert!(crate::panel_docking::showing(&app.ui, ID));
|
||||
}
|
||||
|
||||
/// Object › Concept to Vector… and the context menu need one image (or Image Trace object) that is
|
||||
/// shown and unlocked; without one the Object item is disabled, the context menu leaves it out and
|
||||
/// the command says why.
|
||||
#[test]
|
||||
fn object_and_context_menus_open_it_for_one_image_only() {
|
||||
let mut app = app();
|
||||
let object = |app: &VectorcraftApp| {
|
||||
menus::menu_entries(app).into_iter().find(|e| e.path == ["Object"] && e.label == "Concept to Vector…").expect("Object item")
|
||||
};
|
||||
let in_context = |app: &VectorcraftApp| menus::context_entries(app).iter().any(|e| e.label == "Concept to Vector…");
|
||||
assert!(object(&app).enabled && in_context(&app));
|
||||
let item = object(&app);
|
||||
let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
|
||||
menus::invoke(&mut app, &id, p);
|
||||
assert!(crate::panel_docking::showing(&app.ui, ID), "{}", app.ui.status);
|
||||
|
||||
app.run("object.lock", json!({})).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert!(!object(&app).enabled && !in_context(&app));
|
||||
let e = app.run(OPEN, json!({})).unwrap_err();
|
||||
assert!(e.contains("select one image or an unexpanded Image Trace object"), "{e}");
|
||||
|
||||
app.run("object.unlockAll", json!({})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 250, "y": 200, "width": 20, "height": 20})).unwrap();
|
||||
assert!(!object(&app).enabled && !in_context(&app), "a rectangle is not a source");
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
assert!(!object(&app).enabled, "two objects are not one source");
|
||||
}
|
||||
|
||||
/// Properties' Quick Actions and the Control bar offer it for a selected image, and the Control
|
||||
/// bar's button opens the panel.
|
||||
#[test]
|
||||
fn properties_and_the_control_bar_offer_it() {
|
||||
let mut app = app();
|
||||
assert!(has(&properties_frame(&mut app, 280.0), "Concept to Vector"));
|
||||
let ctx = crate::testing::ui_context();
|
||||
let bar = control_frame(&mut app, &ctx, vec![]);
|
||||
click_control(&mut app, &ctx, at(&bar, "Concept to Vector"));
|
||||
assert!(crate::panel_docking::showing(&app.ui, ID), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
/// The panel says its styles are offline Image Trace styles, disables the prompt, allows 1 to 8
|
||||
/// styles, and shows why it can't run with nothing to use.
|
||||
#[test]
|
||||
fn the_panel_shows_offline_styles_a_disabled_prompt_and_why_it_cannot_run() {
|
||||
let mut app = app();
|
||||
let text = painted_text(&mut app, show);
|
||||
// The provider's first and last styles stand for the check box of each.
|
||||
let shown = [
|
||||
"Offline Image Trace styles, made on this computer",
|
||||
"Offline styles do not use prompts",
|
||||
"Outline",
|
||||
"Gray Tones",
|
||||
"Detail",
|
||||
"5 / 8",
|
||||
"Generate",
|
||||
];
|
||||
for s in shown {
|
||||
assert!(text.contains(s), "{s}: {text}");
|
||||
}
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(text.contains("select one image or an unexpanded Image Trace object"), "{text}");
|
||||
}
|
||||
|
||||
/// Generate at once (no thread): a preview for each ticked style, every one ticked, the document
|
||||
/// unchanged; Insert Selected puts the ticked ones beside the image as one undo step.
|
||||
#[test]
|
||||
fn generate_previews_every_style_and_insert_adds_the_ticked_ones_as_one_step() {
|
||||
let mut app = app();
|
||||
app.concept_runs.styles = vec!["outline".into(), "flatColor".into(), "grayTones".into()];
|
||||
let (steps, roots) = (undo_steps(&app), root_count(&app));
|
||||
generate(&mut app).unwrap();
|
||||
assert_eq!((undo_steps(&app), root_count(&app)), (steps, roots), "Generate changes nothing");
|
||||
let shown = app.concept_runs.shown.as_ref().expect("a job is shown");
|
||||
let styles: Vec<&str> = shown.previews.iter().map(|p| p.style.as_str()).collect();
|
||||
assert_eq!(styles, ["outline", "flatColor", "grayTones"]);
|
||||
let painted = |p: &super::Preview| p.image.pixels.iter().any(|c| *c != Color32::WHITE);
|
||||
assert!(shown.previews.iter().all(painted), "every style paints its preview");
|
||||
assert_eq!(shown.picked.len(), 3);
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(text.contains("Insert Selected") && text.contains("Flat Color"), "{text}");
|
||||
|
||||
app.concept_runs.shown.as_mut().unwrap().picked = vec!["grayTones".into(), "outline".into()];
|
||||
let v = insert(&mut app).unwrap();
|
||||
assert_eq!(v["ids"].as_array().unwrap().len(), 2);
|
||||
assert_eq!((undo_steps(&app), root_count(&app)), (steps + 1, roots + 2), "one step, two groups");
|
||||
let st = app.session.doc().unwrap();
|
||||
let names: Vec<Option<&str>> = st.selection.objects.iter().map(|id| st.doc.node(*id).and_then(|n| n.name.as_deref())).collect();
|
||||
assert_eq!(names, [Some("Outline"), Some("Gray Tones")], "in the provider's order");
|
||||
assert!(st.selection.objects.iter().all(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Group { .. }))));
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(root_count(&app), roots);
|
||||
}
|
||||
|
||||
/// Closing the document drops its jobs, and the panel then stops showing the job's results and
|
||||
/// Insert Selected.
|
||||
#[test]
|
||||
fn results_of_a_closed_document_are_no_longer_shown() {
|
||||
let mut app = app();
|
||||
generate(&mut app).unwrap();
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(text.contains("Insert Selected"), "{text}");
|
||||
assert!(app.session.close_document(0));
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(!text.contains("Insert Selected"), "{text}");
|
||||
assert!(app.concept_runs.shown.is_none());
|
||||
}
|
||||
|
||||
/// The results show only while the document they were made in is the active one: in another
|
||||
/// document neither they nor Insert Selected show, and they show again on going back.
|
||||
#[test]
|
||||
fn results_show_only_in_the_document_they_were_made_in() {
|
||||
let mut app = app();
|
||||
generate(&mut app).unwrap();
|
||||
assert!(painted_text(&mut app, show).contains("Insert Selected"));
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(!text.contains("Insert Selected"), "{text}");
|
||||
assert!(app.concept_runs.job().is_some(), "the job is kept");
|
||||
assert!(app.session.set_active(0));
|
||||
assert!(painted_text(&mut app, show).contains("Insert Selected"));
|
||||
}
|
||||
|
||||
/// `ui.conceptVector.generate` is the panel's Generate: it shows the ticked styles of the selection
|
||||
/// as the button does, and while they are made off the UI thread it says so.
|
||||
#[test]
|
||||
fn the_generate_command_makes_the_styles_as_the_button_does() {
|
||||
let mut app = app();
|
||||
app.concept_runs.styles = vec!["outline".into()];
|
||||
assert!(menus::enabled(&app, GENERATE));
|
||||
let v = app.run(GENERATE, json!({})).unwrap();
|
||||
assert_eq!(v["running"], false);
|
||||
assert_eq!(v["job"].as_u64(), app.concept_runs.job());
|
||||
assert!(app.concept_runs.job().is_some());
|
||||
app.concept_runs.off_the_ui_thread = true;
|
||||
assert_eq!(app.run(GENERATE, json!({})).unwrap(), json!({"running": true}));
|
||||
wait(&mut app);
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert!(!menus::enabled(&app, GENERATE));
|
||||
}
|
||||
|
||||
/// A provider whose every run waits until the test lets it go on, once per run.
|
||||
struct Gated(std::sync::Mutex<std::sync::mpsc::Receiver<()>>);
|
||||
|
||||
impl Provider for Gated {
|
||||
fn id(&self) -> &'static str {
|
||||
"test.gated"
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"Gated"
|
||||
}
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities {
|
||||
image_input: true,
|
||||
vector_output: true,
|
||||
prompt: false,
|
||||
raster_output: false,
|
||||
offline: true,
|
||||
styles: vec![Style { id: "g", label: "G" }],
|
||||
}
|
||||
}
|
||||
fn generate(&self, r: &Request, _: Steps) -> Result<Vec<Variation>, ProviderError> {
|
||||
self.0.lock().map_err(|_| ProviderError::Canceled)?.recv().map_err(|_| ProviderError::Canceled)?;
|
||||
let sq = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
Ok(r.styles.iter().map(|s| Variation { style: s.clone(), ..one_path(&sq, Some([0; 3]), None) }).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate after Cancel waits for the canceled run's thread to end before it starts its own, so
|
||||
/// one thread makes styles at a time, and its results are the ones shown.
|
||||
#[test]
|
||||
fn generate_after_cancel_waits_for_the_canceled_thread() {
|
||||
let mut app = app();
|
||||
let (go, gate) = std::sync::mpsc::channel();
|
||||
app.session.concept_providers_mut().register(Arc::new(Gated(std::sync::Mutex::new(gate)))).unwrap();
|
||||
app.concept_runs.provider = "test.gated";
|
||||
app.concept_runs.styles = vec!["g".into()];
|
||||
app.concept_runs.off_the_ui_thread = true;
|
||||
generate(&mut app).unwrap();
|
||||
cancel(&mut app);
|
||||
generate(&mut app).unwrap();
|
||||
let queued = |app: &VectorcraftApp| matches!(app.concept_runs.running.as_ref().map(|r| &r.work), Some(Work::Queued(_)));
|
||||
assert!(queued(&app), "the new run waits");
|
||||
poll(&mut app);
|
||||
assert!(queued(&app), "while the canceled thread is still going");
|
||||
assert!(app.concept_runs.busy());
|
||||
// The canceled run, then the new one, may go on.
|
||||
go.send(()).unwrap();
|
||||
go.send(()).unwrap();
|
||||
while queued(&app) {
|
||||
poll(&mut app);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
wait(&mut app);
|
||||
let job = app.concept_runs.job().expect("the new run's results are shown");
|
||||
assert!(app.session.concept_variations(job).is_some());
|
||||
}
|
||||
|
||||
/// A preview that leaves part of its variation out says so under it; one that draws all of it
|
||||
/// does not.
|
||||
#[test]
|
||||
fn a_preview_that_leaves_part_out_says_so() {
|
||||
let square = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
assert!(!preview(&one_path(&square, Some([0; 3]), None), "s".into(), (100, 100)).cut);
|
||||
let many: Vec<Point> = (0..PREVIEW_POINTS + 10).map(|i| Point::new((i % 100) as f64, (i / 1000) as f64)).collect();
|
||||
assert!(preview(&one_path(&many, Some([0; 3]), None), "s".into(), (100, 100)).cut, "one long path");
|
||||
let mut two = one_path(&square, Some([0; 3]), None);
|
||||
let full: Vec<Point> = (0..PREVIEW_POINTS - 1).map(|i| Point::new((i % 100) as f64, (i / 1000) as f64)).collect();
|
||||
two.paths.insert(0, one_path(&full, Some([0; 3]), None).paths.remove(0));
|
||||
assert!(preview(&two, "s".into(), (100, 100)).cut, "a path past the limit");
|
||||
// An open last path whose final segment is the one point past the limit.
|
||||
let open: Vec<Point> = (0..=PREVIEW_POINTS).map(|i| Point::new((i % 100) as f64, (i / 1000) as f64)).collect();
|
||||
let last = Variation {
|
||||
style: "s".into(),
|
||||
paths: vec![VectorPath {
|
||||
path: PathData::single(SubPath::polyline(&open, false)),
|
||||
fill: None,
|
||||
stroke: Some(([0; 3], 1.0)),
|
||||
square_caps: false,
|
||||
}],
|
||||
warnings: vec![],
|
||||
};
|
||||
assert!(preview(&last, "s".into(), (100, 100)).cut, "an open path's last segment past the limit");
|
||||
|
||||
let mut app = app();
|
||||
let v = app.run("conceptVector.generate", json!({"provider": offline::ID, "styles": ["outline"]})).unwrap();
|
||||
show_job(&mut app, &v);
|
||||
app.concept_runs.shown.as_mut().unwrap().previews[0].cut = true;
|
||||
assert!(painted_text(&mut app, show).contains("The preview leaves out part of this style"));
|
||||
}
|
||||
|
||||
/// At most eight styles: a ninth tick is refused by the command, and none is refused too.
|
||||
#[test]
|
||||
fn no_style_or_too_many_are_refused() {
|
||||
let mut app = app();
|
||||
app.concept_runs.styles.clear();
|
||||
let e = generate(&mut app).unwrap_err();
|
||||
assert!(e.contains("must list 1 to 8 different style ids"), "{e}");
|
||||
app.concept_runs.styles = (0..9).map(|_| "outline".to_string()).collect();
|
||||
assert!(generate(&mut app).is_err());
|
||||
assert!(app.concept_runs.shown.is_none());
|
||||
}
|
||||
|
||||
/// Off the UI thread: Generate returns at once with the run going; its results are kept when it
|
||||
/// ends. Cancel drops a run, and nothing is shown or changed.
|
||||
#[test]
|
||||
fn generate_runs_off_the_ui_thread_and_cancel_drops_it() {
|
||||
let mut app = app();
|
||||
app.concept_runs.off_the_ui_thread = true;
|
||||
let steps = undo_steps(&app);
|
||||
generate(&mut app).unwrap();
|
||||
assert!(app.concept_runs.busy());
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(text.contains("Cancel"), "{text}");
|
||||
wait(&mut app);
|
||||
assert!(!app.concept_runs.busy());
|
||||
let job = app.concept_runs.job().expect("results shown");
|
||||
assert!(app.session.concept_variations(job).is_some());
|
||||
|
||||
app.concept_runs.shown = None;
|
||||
generate(&mut app).unwrap();
|
||||
cancel(&mut app);
|
||||
assert!(!app.concept_runs.busy() && app.concept_runs.shown.is_none());
|
||||
assert_eq!(undo_steps(&app), steps);
|
||||
}
|
||||
|
||||
/// `ui.conceptVector.cancel` is the panel's Cancel: on while styles are being made, it stops them
|
||||
/// and says so, and nothing is kept or shown.
|
||||
#[test]
|
||||
fn the_cancel_command_stops_a_run_as_the_button_does() {
|
||||
let mut app = app();
|
||||
app.concept_runs.off_the_ui_thread = true;
|
||||
assert!(!menus::enabled(&app, CANCEL));
|
||||
generate(&mut app).unwrap();
|
||||
assert!(menus::enabled(&app, CANCEL));
|
||||
assert_eq!(app.run(CANCEL, json!({})).unwrap(), json!({"canceled": 1}));
|
||||
assert!(!app.concept_runs.busy() && !menus::enabled(&app, CANCEL));
|
||||
assert_eq!(app.ui.status, vectorcraft_engine::EngineError::Cancelled.to_string());
|
||||
poll(&mut app);
|
||||
assert!(app.concept_runs.shown.is_none());
|
||||
}
|
||||
|
||||
fn one_path(points: &[Point], fill: Option<[u8; 3]>, stroke: Option<([u8; 3], f64)>) -> Variation {
|
||||
Variation {
|
||||
style: "s".into(),
|
||||
paths: vec![VectorPath { path: PathData::single(SubPath::polyline(points, true)), fill, stroke, square_caps: false }],
|
||||
warnings: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled path paints its color inside its outline and leaves the rest white; a stroked one
|
||||
/// paints its outline and leaves the inside white.
|
||||
#[test]
|
||||
fn previews_paint_fills_and_strokes() {
|
||||
let square = [Point::new(25.0, 25.0), Point::new(75.0, 25.0), Point::new(75.0, 75.0), Point::new(25.0, 75.0)];
|
||||
let red = [200, 20, 20];
|
||||
let p = preview(&one_path(&square, Some(red), None), "s".into(), (100, 100));
|
||||
let [w, h] = p.image.size;
|
||||
let px = |p: &super::Preview, x: usize, y: usize| p.image.pixels[y * w + x];
|
||||
assert_eq!(px(&p, w / 2, h / 2), Color32::from_rgb(200, 20, 20));
|
||||
assert_eq!((px(&p, 2, 2), px(&p, w - 3, h - 3)), (Color32::WHITE, Color32::WHITE));
|
||||
let p = preview(&one_path(&square, None, Some((red, 4.0))), "s".into(), (100, 100));
|
||||
assert_eq!((px(&p, w / 2, h / 2), px(&p, 2, 2)), (Color32::WHITE, Color32::WHITE));
|
||||
assert_eq!(px(&p, w / 2, h / 4), Color32::from_rgb(200, 20, 20), "the top edge");
|
||||
}
|
||||
|
||||
/// The pixels a preview paints across the top edge of a square stroked `width` wide, in an image
|
||||
/// 200 by 100 pixels.
|
||||
fn stroke_cover(width: f64) -> usize {
|
||||
let square = [Point::new(25.0, 25.0), Point::new(75.0, 25.0), Point::new(75.0, 75.0), Point::new(25.0, 75.0)];
|
||||
let p = preview(&one_path(&square, None, Some(([0, 0, 0], width))), "s".into(), (200, 100));
|
||||
let [w, h] = p.image.size;
|
||||
let x = w / 4;
|
||||
(0..h / 2).filter(|y| p.image.pixels[y * w + x] != Color32::WHITE).count()
|
||||
}
|
||||
|
||||
/// Preview strokes are painted to scale with the image, and at least half a point wide.
|
||||
#[test]
|
||||
fn preview_strokes_keep_their_widths() {
|
||||
// The image's 200 pixels are about 408 preview pixels wide: a 10-pixel stroke is about 20.
|
||||
let (thin, thick) = (stroke_cover(1.0), stroke_cover(10.0));
|
||||
assert!((19..=23).contains(&thick), "{thick}");
|
||||
assert!((1..=4).contains(&thin), "{thin}");
|
||||
assert!(stroke_cover(0.01) >= 1, "thin lines still show");
|
||||
}
|
||||
|
||||
/// A line with square caps is painted to the corners of its ends, and one with round caps leaves
|
||||
/// them white.
|
||||
#[test]
|
||||
fn preview_strokes_keep_their_caps() {
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(25.0, 50.0), Point::new(75.0, 50.0)], false));
|
||||
let corner = |square_caps: bool| {
|
||||
let paths = vec![VectorPath { path: line.clone(), fill: None, stroke: Some(([0, 0, 0], 20.0)), square_caps }];
|
||||
let p = preview(&Variation { style: "s".into(), paths, warnings: vec![] }, "s".into(), (100, 100));
|
||||
let [w, h] = p.image.size;
|
||||
// Past the line's right end, near the corner of a square cap: 8 and 8 pixels of the image.
|
||||
p.image.pixels[(h * 58 / 100) * w + w * 83 / 100]
|
||||
};
|
||||
assert_eq!(corner(true), Color32::BLACK, "square caps");
|
||||
assert_eq!(corner(false), Color32::WHITE, "round caps");
|
||||
}
|
||||
|
||||
/// Paths are painted in their order: a fill above a stroke covers it, and a stroke above a fill
|
||||
/// shows.
|
||||
#[test]
|
||||
fn previews_paint_paths_in_their_order() {
|
||||
let square = [Point::new(25.0, 25.0), Point::new(75.0, 25.0), Point::new(75.0, 75.0), Point::new(25.0, 75.0)];
|
||||
let cover = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
|
||||
let path = |pts: &[Point]| PathData::single(SubPath::polyline(pts, true));
|
||||
let stroke = VectorPath { path: path(&square), fill: None, stroke: Some(([0, 0, 0], 4.0)), square_caps: false };
|
||||
let fill = VectorPath { path: path(&cover), fill: Some([200, 20, 20]), stroke: None, square_caps: false };
|
||||
let on_edge = |paths: Vec<VectorPath>| {
|
||||
let p = preview(&Variation { style: "s".into(), paths, warnings: vec![] }, "s".into(), (100, 100));
|
||||
let [w, h] = p.image.size;
|
||||
p.image.pixels[(h / 4) * w + w / 2]
|
||||
};
|
||||
assert_eq!(on_edge(vec![stroke.clone(), fill.clone()]), Color32::from_rgb(200, 20, 20), "the fill covers the stroke below it");
|
||||
assert_eq!(on_edge(vec![fill, stroke]), Color32::BLACK, "the stroke shows above the fill");
|
||||
}
|
||||
|
||||
/// A path's elements, made as they are taken, are the elements of its converted path.
|
||||
#[test]
|
||||
fn preview_elements_match_the_converted_path() {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((10.0, 0.0));
|
||||
bp.curve_to((15.0, 0.0), (20.0, 5.0), (20.0, 10.0));
|
||||
bp.close_path();
|
||||
bp.move_to((30.0, 30.0));
|
||||
bp.line_to((40.0, 35.0));
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
let made: Vec<_> = elements(&path).collect();
|
||||
assert_eq!(made, path.to_bezpath().elements().to_vec());
|
||||
assert_eq!(elements(&path).take(2).count(), 2);
|
||||
}
|
||||
|
||||
/// A curve flattened into more points than are left ends the elements taken: those after it are
|
||||
/// not flattened, while a closing element still closes the ring.
|
||||
#[test]
|
||||
fn preview_elements_stop_once_no_point_is_left() {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
for i in 0..100 {
|
||||
let x = f64::from(i) * 100.0;
|
||||
bp.curve_to((x + 30.0, 400.0), (x + 70.0, -400.0), (x + 100.0, 0.0));
|
||||
}
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
let left = std::cell::Cell::new(10);
|
||||
let taken = std::cell::Cell::new(0);
|
||||
vectorcraft_geom::flatten(within_budget(elements(&path).inspect(|_| taken.set(taken.get() + 1)), &left), 0.25, |el| {
|
||||
if matches!(el, vectorcraft_geom::PathEl::LineTo(_)) && left.get() > 0 {
|
||||
left.set(left.get() - 1);
|
||||
}
|
||||
});
|
||||
assert_eq!(left.get(), 0);
|
||||
assert!(taken.get() <= 3, "{} elements taken", taken.get());
|
||||
let closing = [vectorcraft_geom::PathEl::LineTo((1.0, 1.0).into()), vectorcraft_geom::PathEl::ClosePath];
|
||||
assert_eq!(within_budget(closing.into_iter(), &left).count(), 0, "nothing is taken once none is left");
|
||||
assert_eq!(within_budget(closing[1..].iter().copied(), &left).count(), 1, "but a ring still closes");
|
||||
}
|
||||
|
||||
/// A preview of an image wider or taller than its box allows keeps the image's proportions, with
|
||||
/// margins, instead of stretching the image to the box.
|
||||
#[test]
|
||||
fn a_preview_of_a_wide_or_tall_image_keeps_its_proportions() {
|
||||
let square = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
|
||||
for (size, aspect) in [((1000, 100), 10.0f32), ((100, 1000), 0.1)] {
|
||||
let p = preview(&one_path(&square, Some([9, 9, 9]), None), "s".into(), size);
|
||||
let [w, h] = p.image.size;
|
||||
assert!(((w as f32 / h as f32) / aspect - 1.0).abs() < 0.06, "{size:?}: {w} x {h}");
|
||||
let inner = Rect::from_min_size(Pos2::ZERO, vec2(preview_width(aspect, PREVIEW_H), PREVIEW_H)).shrink(4.0);
|
||||
let art = art_rect(inner, aspect);
|
||||
assert!(inner.expand(0.01).contains_rect(art), "{art:?} in {inner:?}");
|
||||
assert!((art.aspect_ratio() / aspect - 1.0).abs() < 1e-3, "{art:?}");
|
||||
assert!((art.center() - inner.center()).length() < 1e-3, "{art:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// One path with more points than a preview draws is cut off within the path: its points in the
|
||||
/// top quarter are painted, and those past the limit, in the bottom quarter, are not.
|
||||
#[test]
|
||||
fn a_preview_stops_at_its_point_limit_within_one_path() {
|
||||
let zigzag: Vec<Point> =
|
||||
(0..PREVIEW_POINTS * 3).map(|i| Point::new((i % 100) as f64, if i < PREVIEW_POINTS { 10.0 } else { 90.0 } + (i % 2) as f64 * 0.5)).collect();
|
||||
let mut path = one_path(&zigzag, None, Some(([0, 0, 0], 1.0)));
|
||||
if let Some(sp) = path.paths[0].path.subpaths.first_mut() {
|
||||
sp.closed = false;
|
||||
}
|
||||
let p = preview(&path, "s".into(), (100, 100));
|
||||
let [w, h] = p.image.size;
|
||||
let painted = |rows: std::ops::Range<usize>| rows.flat_map(|y| (0..w).map(move |x| y * w + x)).any(|i| p.image.pixels[i] != Color32::WHITE);
|
||||
assert!(painted(0..h / 4), "the points before the limit");
|
||||
assert!(!painted(h * 3 / 4..h), "the points past it");
|
||||
}
|
||||
|
||||
/// As on the web (no thread): Generate returns with the run going and nothing made; each frame
|
||||
/// makes one part (the image decoded, a style's color layers found, one layer traced), the styles
|
||||
/// are made in order, and the last part's frame shows them all.
|
||||
#[test]
|
||||
fn on_the_web_generate_makes_one_part_a_frame() {
|
||||
let mut app = app();
|
||||
app.concept_runs.by_frames = true;
|
||||
app.concept_runs.styles = vec!["outline".into(), "flatColor".into(), "grayTones".into()];
|
||||
let (steps, roots) = (undo_steps(&app), root_count(&app));
|
||||
generate(&mut app).unwrap();
|
||||
assert!(app.concept_runs.busy() && app.concept_runs.shown.is_none());
|
||||
assert_eq!(made_so_far(&app), Some(0), "made one part a frame, not on a thread");
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(text.contains("Cancel"), "{text}");
|
||||
let mut seen = vec![];
|
||||
while let Some(k) = made_so_far(&app) {
|
||||
assert!(seen.len() < 1000, "the parts never end");
|
||||
seen.push(k);
|
||||
assert!(app.concept_runs.shown.is_none());
|
||||
poll(&mut app);
|
||||
}
|
||||
assert!(seen.windows(2).all(|w| w[0] <= w[1]) && seen.contains(&1) && seen.contains(&2), "{seen:?}");
|
||||
assert!(seen.len() > 3, "more than one part a style: {seen:?}");
|
||||
assert!(!app.concept_runs.busy());
|
||||
let shown = app.concept_runs.shown.as_ref().expect("results shown");
|
||||
let styles: Vec<&str> = shown.previews.iter().map(|p| p.style.as_str()).collect();
|
||||
assert_eq!(styles, ["outline", "flatColor", "grayTones"]);
|
||||
assert!(app.session.concept_variations(shown.job).is_some());
|
||||
assert_eq!((undo_steps(&app), root_count(&app)), (steps, roots), "Generate changes nothing");
|
||||
}
|
||||
|
||||
/// On the web, Cancel takes effect inside a style: after the image's color layers are found and
|
||||
/// one is traced, the run is dropped, and nothing is shown or changed.
|
||||
#[test]
|
||||
fn on_the_web_cancel_stops_a_style_part_way() {
|
||||
let mut app = app();
|
||||
app.concept_runs.by_frames = true;
|
||||
app.concept_runs.styles = vec!["flatColor".into()];
|
||||
let (steps, roots) = (undo_steps(&app), root_count(&app));
|
||||
generate(&mut app).unwrap();
|
||||
// The image decoded, its color layers found, and the first layer traced.
|
||||
for _ in 0..3 {
|
||||
poll(&mut app);
|
||||
assert_eq!(made_so_far(&app), Some(0), "the one style is still being made");
|
||||
}
|
||||
cancel(&mut app);
|
||||
poll(&mut app);
|
||||
assert!(!app.concept_runs.busy() && app.concept_runs.shown.is_none());
|
||||
assert_eq!((undo_steps(&app), root_count(&app)), (steps, roots));
|
||||
}
|
||||
|
||||
/// A provider with one style, `sketch`, named "Pencil Sketch": a square for each style asked.
|
||||
struct Sketches;
|
||||
|
||||
impl Provider for Sketches {
|
||||
fn id(&self) -> &'static str {
|
||||
"test.sketches"
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"Sketches"
|
||||
}
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
let styles = vec![Style { id: "sketch", label: "Pencil Sketch" }];
|
||||
Capabilities { image_input: true, vector_output: true, prompt: false, raster_output: false, offline: true, styles }
|
||||
}
|
||||
fn generate(&self, r: &Request, _: Steps) -> Result<Vec<Variation>, ProviderError> {
|
||||
let sq = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
Ok(r.styles.iter().map(|s| Variation { style: s.clone(), ..one_path(&sq, Some([0; 3]), None) }).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// The results of another provider are named as that provider names its styles.
|
||||
#[test]
|
||||
fn results_are_named_as_their_provider_names_its_styles() {
|
||||
let mut app = app();
|
||||
app.session.concept_providers_mut().register(Arc::new(Sketches)).unwrap();
|
||||
let v = app.run("conceptVector.generate", json!({"provider": "test.sketches", "styles": ["sketch"]})).unwrap();
|
||||
show_job(&mut app, &v);
|
||||
let shown = app.concept_runs.shown.as_ref().expect("a job is shown");
|
||||
let labels: Vec<&str> = shown.previews.iter().map(|p| p.label.as_str()).collect();
|
||||
assert_eq!(labels, ["Pencil Sketch"]);
|
||||
let text = painted_text(&mut app, show);
|
||||
assert!(text.contains("Pencil Sketch"), "{text}");
|
||||
}
|
||||
|
||||
/// Insert Selected after the image moved: the job no longer applies, and nothing changes.
|
||||
#[test]
|
||||
fn insert_after_the_image_moved_changes_nothing() {
|
||||
let mut app = app();
|
||||
generate(&mut app).unwrap();
|
||||
app.run("object.transform", json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap();
|
||||
let (steps, roots) = (undo_steps(&app), root_count(&app));
|
||||
let e = insert(&mut app).unwrap_err();
|
||||
assert!(e.contains("no longer applies"), "{e}");
|
||||
assert_eq!((undo_steps(&app), root_count(&app)), (steps, roots));
|
||||
}
|
||||
@@ -304,6 +304,7 @@ pub(crate) fn quick_actions(app: &mut VectorcraftApp) -> Vec<QuickAction> {
|
||||
add(super::symbols::changed_instances_selected(app), tl!("Reset"), "symbol.instance.reset");
|
||||
add(multi_color(app), tl!("Recolor"), "ui.recolorDialog");
|
||||
add(is_image, tl!("Crop Image"), "ui.cropImage");
|
||||
add(is_image, tl!("Concept to Vector"), crate::panels::concept_vector::OPEN);
|
||||
add(is_image, tl!("Mask"), "object.maskImage");
|
||||
// Remove Background at once with its defaults.
|
||||
add(is_image, tl!("Remove Background"), crate::addons::image::REMOVE_BACKGROUND);
|
||||
|
||||
@@ -1351,9 +1351,12 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool
|
||||
});
|
||||
}
|
||||
Row::new().fit_rank(rank::GROUP).show(ui, |ui, _| crate::panels::image_trace::trace_button(app, ui));
|
||||
for (label, cmd) in
|
||||
[(tl!("Mask"), "object.maskImage"), (tl!("Crop Image"), "ui.cropImage"), (tl!("Remove Background"), crate::addons::image::REMOVE_BACKGROUND)]
|
||||
{
|
||||
for (label, cmd) in [
|
||||
(tl!("Mask"), "object.maskImage"),
|
||||
(tl!("Crop Image"), "ui.cropImage"),
|
||||
(tl!("Concept to Vector"), crate::panels::concept_vector::OPEN),
|
||||
(tl!("Remove Background"), crate::addons::image::REMOVE_BACKGROUND),
|
||||
] {
|
||||
Row::new().fit_rank(rank::GROUP).show(ui, |ui, _| {
|
||||
if clicked(&Button::new(label.to_string()).show(ui)) {
|
||||
crate::menus::invoke(app, cmd, json!({}));
|
||||
|
||||
@@ -534,6 +534,7 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("ui.colorGuideOptions", "Window › Color Guide"),
|
||||
("ui.colorPicker", "Color"),
|
||||
("ui.colorRgbPercent", "Window › Color"),
|
||||
("ui.conceptVector.", "Window › Concept to Vector"),
|
||||
("ui.corners", "Window › Transform"),
|
||||
("ui.dialogReset", "Dialogs"),
|
||||
("ui.dxfOptionsDialog", "File"),
|
||||
@@ -3081,6 +3082,7 @@ mod tests {
|
||||
assert_eq!(group("ui.recolorDialog").as_deref(), Some("Edit › Edit Colors"));
|
||||
assert_eq!(group("ui.rename").as_deref(), Some("Window › Layers"));
|
||||
assert_eq!(group("ui.justification").as_deref(), Some("Window › Paragraph"));
|
||||
assert_eq!(group("ui.conceptVector.cancel").as_deref(), Some("Window › Concept to Vector"));
|
||||
assert_eq!(group("addon.pathtools.cornerRemove").as_deref(), Some("Object › Plug-ins › Path Precision Tools"));
|
||||
}
|
||||
}
|
||||
@@ -330,6 +330,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[
|
||||
("navigator", "Navigator", "map"),
|
||||
("separations", "Separations Preview", "printer"),
|
||||
("imageTrace", "Image Trace", "image"),
|
||||
(crate::panels::concept_vector::ID, "Concept to Vector", "sparkles"),
|
||||
("magicWand", "Magic Wand", "wand-sparkles"),
|
||||
(crate::panels::flattener_preview::ID, "Flattener Preview", "eye"),
|
||||
("attributes", "Attributes", "settings"),
|
||||
|
||||
+6
-2
@@ -1014,9 +1014,13 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
|
||||
## G18 Generative AI features
|
||||
|
||||
- **Done:** Concept to Vector in part: Window › Concept to Vector makes 1 to 5 styles of one selected image
|
||||
side by side and inserts the ticked ones beside it as one undo step (`conceptVector.*`). Providers plug in
|
||||
by id (`crates/engine/src/concept_vector.rs`), and a request to any provider makes up to 8 variations; the
|
||||
only provider is built in and makes five offline Image Trace styles.
|
||||
- **Missing:** Text to Vector Graphic, Generative Recolor, Generative Shape Fill (#766), Generative Expand,
|
||||
Concept to Vector, Prompt to Edit, Rewrite Text. Adobe's run on its cloud models; ours would be a pluggable
|
||||
provider.
|
||||
Concept to Vector's prompt-led generation and raster output, Prompt to Edit, Rewrite Text. In the reference
|
||||
app these run on cloud models; ours would be a pluggable provider.
|
||||
- **Needs:** an owner decision on models and providers.
|
||||
- **Estimate:** 30–60 h after that decision.
|
||||
|
||||
|
||||
+51
-1
@@ -7013,6 +7013,55 @@ already walks Image Trace. Short agent entry points:
|
||||
nothing, and a built-in preset's name, `Custom` or another saved preset's name keeps the editor open. Delete selects
|
||||
the saved preset below the deleted one, else the one above it, else Default. Import… asks whether to replace saved presets whose names the file holds (Cancel
|
||||
keeps them), and Export… writes every saved preset.
|
||||
- Concept to Vector: `conceptVector.providers` lists the providers that `conceptVector.generate` can call by id, with
|
||||
their styles. The built-in `offline.traceStyles` makes the styles `outline`, `inkLines`, `flatColor`, `detailedColor`
|
||||
and `grayTones` with Image Trace on this computer; it takes no prompt and makes vector art only. A provider is used
|
||||
only when it is named: an unknown one is an error, and so is one that takes no image, makes no vector art, or does
|
||||
not support a non-empty `prompt`, each with that reason; no other provider is used in its place. Results are vector
|
||||
art, so `output` other than `"vector"` is an error for every provider. `flatColor` traces abutting fills and lays
|
||||
seam fills under them, as Image Trace's Abutting method with Fills does, when they fit within the limits below.
|
||||
`conceptVector.generate {id?, provider, styles: [style id…], detail?: 0-100, prompt?, output?: "vector"}` makes one
|
||||
variation of the image (or unexpanded Image Trace object) for each of 1 to 8 different styles and keeps them as a job of
|
||||
the session; it does not change the document and is not journaled. A source that is locked or hidden, itself or by a
|
||||
layer or group around it, or that is on a locked artboard, is refused. Results are
|
||||
checked whatever provider made them: one variation per style in the order asked, every point finite and near the
|
||||
image, every subpath with an anchor point, at most 250,000 paths (each subpath of a compound path counted as one)
|
||||
and 1,000,000 anchor points in all. The reply lists each variation's `style`, `label`,
|
||||
`paths`, `anchors`, `bounds` in the image's pixels and `warnings` (for example that a large image was traced scaled
|
||||
down to 16 megapixels). `conceptVector.results {job}` returns the job again, and `conceptVector.cancel {job}` drops
|
||||
its variations. The session keeps the 4 newest jobs until their document closes. A `conceptVector.generate` in a
|
||||
script stops when the script is asked to stop, and keeps no job. A script that ends with an error,
|
||||
like a batch, leaves the jobs as they were: the jobs it made are dropped, and a job it canceled, or whose document it
|
||||
closed, is kept.
|
||||
`conceptVector.insert {job, variations: [style id…]}` puts a group of each chosen variation, named after its style and
|
||||
in the provider's order, to the right of the image, each the image's size with 24 pt between them, moved further
|
||||
right past other visible art, also where a variation reaches past its image-sized box (the next one then starts 24
|
||||
pt past what it paints); it is one undo step and selects the groups. A variation with no paths is left out, and when
|
||||
every chosen one has none, nothing changes (no undo step, `ids` empty). The groups go above the outermost clip group or
|
||||
opacity-masked group around the image, so that it does not hide them, 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, whose content stays as it is. It is an error when the job was canceled or dropped, when its document
|
||||
is not the active one, when the object, its pixels or its placement changed, when the object is now locked or hidden,
|
||||
or when it is on a layer with a clipping mask, an opacity mask, or effects, fills or strokes of its own, or when the
|
||||
object or a group around it has effects that move or reshape it (Transform, a warp), which show the image away from
|
||||
its placement, or when its image is distorted (Perspective Distort or Free Distort) and drawn at its corners instead
|
||||
of by its transform. Jobs are not saved, so an insert or a cancel played from recorded steps (an action, a journal played
|
||||
again, or a step of a batch played again) is an error too. Example, where insert takes the `job`
|
||||
that generate returned (job numbers count up through the session, so 1 only for its first job):
|
||||
|
||||
```json
|
||||
{"command": "conceptVector.generate", "params": {"provider": "offline.traceStyles", "styles": ["outline", "flatColor"], "detail": 60}}
|
||||
{"command": "conceptVector.insert", "params": {"job": 1, "variations": ["flatColor"]}}
|
||||
```
|
||||
|
||||
In the app, `ui.conceptVector` opens the Concept to Vector panel, which runs the same commands; Generate shows a progress bar
|
||||
and Cancel. On the desktop it runs off the UI thread unless `VECTORCRAFT_SYNC_OPEN` is set, in which case it runs at
|
||||
once on the UI thread; the web build runs it on the UI thread one part a frame, and
|
||||
Cancel takes effect before the next part. `ui.conceptVector.generate` does what Generate does and returns
|
||||
`{running: true}` while the styles are made, else `{running: false, job}`; `ui.conceptVector.cancel` does what Cancel
|
||||
does. A Generate after a Cancel starts once the canceled run's thread has ended. The panel shows a job's results only
|
||||
while the document it was made in is the active one, and a preview that leaves part of its variation out says so.
|
||||
- Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`,
|
||||
`livePaint.info {group?|id?}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?,
|
||||
color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill rows that draw of
|
||||
@@ -11832,7 +11881,8 @@ be one of …", and a `visible` that is not true or false fails with "`visible`
|
||||
every group as it is. The groups and their contents are VectorCraft's own.
|
||||
`window.taskBar.actions {action, visible?}` (desktop app) turns one of the Contextual Task Bar's actions or chips on
|
||||
(`visible: true`), off (`false`) or toggles it (omitted or null), and returns `{action, visible}`. The actions are `imageTrace`,
|
||||
`cropImage`, `removeBackground`, `removeAnchorPoints`, `join` (Connect and Join), `cutPath`, `convertToCorner`,
|
||||
`cropImage`, `removeBackground`, `conceptToVector` (Concept to Vector), `removeAnchorPoints`,
|
||||
`join` (Connect and Join), `cutPath`, `convertToCorner`,
|
||||
`convertToSmooth`, `group`, `makeClippingMask`, `unite`, `expand`, `editClippingPath`, `releaseClippingMask`,
|
||||
`ungroup`, `isolate`, `editPath`, `releaseCompoundPath`, `createOutlines`, `convertToPointType`, `convertToAreaType`,
|
||||
`typeOnPathOptions`, `centerOnTop`, `centerOnBottom`, `dynamicText`, `offsetPath`, `simplify`, `smooth`, `duplicate`,
|
||||
|
||||
@@ -2055,6 +2055,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Image Trace, JPEG blocks:** Color, Grayscale and Black and White traces smooth the edges of a JPEG's 8 × 8 blocks before tracing, so a dark ground whose tone changes slowly is no longer traced as staircases along the block edges. The block grid is found in the image itself: the mean step between neighboring pixels must peak at one position in eight, across and down. A cropped JPEG and a JPEG saved in another format are smoothed too. A picture of flat 8 × 8 cells is left as it is, and art made of 8 × 8 cells with slight texture inside each cell is smoothed as a JPEG copy would be. A small step at a block edge, with no edge in the eight pixels around it, is spread over those eight pixels, and larger steps are kept, as the deblocking filters of ITU-T H.263 Annex J and MPEG-4 Part 2 Annex F.3.1 do. Black and White smooths only the smallest steps, and traces of more than 16 colors move every row of a stretch of eight by the same amount (VectorCraft's own rule and values). On a 4000 × 3000 photo saved as JPEG, the straight outline segments that lie on the block grid fall from 52% and 51% (across and down) to 24% and 29% at 16 Colors, and from 54% and 51% to 43% and 42% at High Fidelity Photo; staircase runs fall from 83 to 67 (16 Colors), 11 to 1 (6 Colors), 30 to 13 (Black and White Logo) and 428 to 403 (High Fidelity Photo). A 600 px photo saved as a quality-40 JPEG has 4 staircase runs instead of 2 at 16 Colors. Images without a block grid trace as before. Tests: `tests::a_jpegs_blocks_are_not_traced_as_steps`, `deblock::tests`. Scores and hours unchanged.
|
||||
- **Image Trace, Document Library color groups:** with Document Swatches, the panel's Colors menu and `"colorGroup"` trace with one color group's colors instead of every swatch, as the public panel documentation describes Document Library; code-drawn tests in `crates/engine` and the panel.
|
||||
- **Image Trace, Document Library colors:** with Document Swatches, traced fills and strokes use the displayed colors of process, global, spot and tint swatches without links, so editing a swatch leaves the trace unchanged; swatch-library colors are also unlinked; code-drawn tests in `crates/engine`.
|
||||
- **Concept to Vector, offline styles (in part):** Window › Concept to Vector and Object › Concept to Vector… (also the context menu and the contextual task bar for one image or unexpanded Image Trace object; the Control bar and Properties for one image) make 1 to 5 styles of the selected image side by side (a request to any provider makes up to 8 variations, one per selected style) and insert the ticked ones to the right of it as one undo step (beside any group that makes or places its members, such as a graph, Objects on Path or Live Paint group, and never on a layer with effects, fills or strokes of its own; the previews show only while their document is the active one), as the help page describes for comparing styles ([Generate vector artwork from images](https://helpx.adobe.com/illustrator/desktop/use-generative-ai/generate-vector-artwork-from-images.html)). The only provider is built in: five VectorCraft styles (Outline, Ink Lines, Flat Color, Detailed Color, Gray Tones) made with Image Trace on this computer, with Detail from 0 to 100; it takes no prompt and makes no raster output, so prompt-led generation is still missing. Other providers plug in by id through `crates/engine/src/concept_vector.rs`, and every result is checked before it is kept. `ui.conceptVector.generate` and `ui.conceptVector.cancel` do what the panel's Generate and Cancel do. Tests: `concept_vector::tests` in `crates/engine` and `panels::concept_vector::tests` in `crates/ui-egui`. Scores and hours unchanged.
|
||||
- **Image Trace, flattened slivers:** in a Color, Grayscale or Black and White trace with Fills, a traced region whose outline straightens onto one line (a single pixel, or a one-pixel row along an edge, its pieces shared with the regions beside it) is left out instead of becoming a selectable path with no area, which paints nothing. Snap Curves To Lines straightens more outlines, so it leaves out more of these. Without Fills, the region's 1 px stroke draws it, and it is kept. Code-drawn tests in `crates/trace`.
|
||||
- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` clip group under its paths, with strokes along the edges two filled paths share, in the lower path's color, 1.5 image pixels wide (VectorCraft's own width) and clipped to the image's box within the traced paths' box; on an image stretched more one way than another, each stroke's outline in image pixels is a filled path instead. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` and `image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge` in `crates/engine`.
|
||||
- **Image Trace, Auto Color rare colours:** the Automatic palette keeps colours too rare for its area count when they are distinct (Oklab) and drawn as coherent regions, at most six, protected from mixed-colour merging and Noise; code-drawn stem, highlight, low-contrast and scattered-noise tests (see [quality notes](image-trace-quality.md#auto-color-keeps-rare-colours)).
|
||||
|
||||
@@ -508,6 +508,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
|
||||
| Image Trace panel: Ignore Color has a canvas eyedropper beside its color picker | done | #8068. Samples original pixels of the selected placed image or the retained source of a live trace without changing the displayed canvas View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. An outside or transparent miss leaves the pick armed; a valid sample or Escape restores the previous tool, and changing the target or explicitly choosing a tool cancels. Paint defaults and selection are retained. `tests/image_trace_ignore_sampler.rs`; no algorithm parity claim. Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; runtime pending). | unknown |
|
||||
| Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | unknown |
|
||||
| Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (<https://web.archive.org/web/20250831090623/https://helpx.adobe.com/illustrator/using/image-trace.html>). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | unknown |
|
||||
| Concept to Vector panel: Window › Concept to Vector and Object › Concept to Vector… (also the context menu and the Contextual Task Bar) open it for one image or unexpanded Image Trace object, and the Control bar and Properties' Quick Actions for one image; it makes 1 to 5 styles side by side (a request to any provider makes up to 8 variations, one per selected style) and Insert Selected puts the ticked ones to the right of the image as one undo step | partial | The help page describes choosing up to 8 styles of the selected image to compare side by side (<https://helpx.adobe.com/illustrator/desktop/use-generative-ai/generate-vector-artwork-from-images.html>). The built-in provider makes five offline Image Trace styles with Detail 0 to 100; its prompt field is disabled and it makes no raster output. On the web build a run is made one part a frame, so Cancel takes effect inside a style. Decoding the image, finding a style's color layers and tracing one layer are each one part; the Detailed Color and Gray Tones styles trace all their color layers in one part. Cancel waits for the part in progress to end. `conceptVector.providers`, `conceptVector.generate`, `conceptVector.results`, `conceptVector.cancel`, `conceptVector.insert`, `ui.conceptVector.cancel` (the panel's Cancel); `panels/concept_vector.rs` headless tests | unknown |
|
||||
| Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls; Window > Toolbars > Compact Tools adds optional denser spacing for the main Tools panel while retaining the existing default (#7234) | unknown |
|
||||
| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON | unknown |
|
||||
| Actions panel: ≡ › Replace Actions… puts the set of a saved file in place of every set in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.actionSet.replace`; `panels/actions.rs` tests. The file is read as Load Actions… reads it; the item asks no question first | unknown |
|
||||
|
||||
Reference in new issue
Block a user