Merge commit '0aea8fed95071c341445ba587a4ce5d0d76753d0' into fix/ui-svg-filter-inline-cap

This commit is contained in:
dotCooCoo committed 2026-11-26 19:00:44 -08:00
commit 913b69d97f
39 files changed
+1225 -155

No files matched your search

+34 -13
View File
@@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec<u8> {
pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "view.proofSetup.save";
let (path, named) = file_path(s, p, C)?;
let mut setup = proof::view().setup;
setup_params(p, &mut setup, C)?;
check_device(&setup.target).map_err(|e| bad(C, e))?;
// A file `view.proofSetup.load` would refuse is not written (a device with a very long name).
let bytes = encode(&setup);
if bytes.len() > MAX_FILE {
return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes")));
}
let (setup, bytes) = encode_options(p, &path)?;
if named
&& let Some(dir) = std::path::Path::new(&path).parent()
&& !dir.is_dir()
@@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Object(r))
}
/// Serialize the Customize dialog's draft without committing it or writing a path.
pub fn draft_bytes(p: &Value) -> Result<Vec<u8>> {
encode_options(p, "Proof Setup").map(|(_, bytes)| bytes)
}
fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec<u8>)> {
const C: &str = "view.proofSetup.save";
let mut setup = proof::view().setup;
setup_params(p, &mut setup, C)?;
check_device(&setup.target).map_err(|e| bad(C, e))?;
let bytes = encode(&setup);
if bytes.len() > MAX_FILE {
return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes")));
}
Ok((setup, bytes))
}
/// The file `p` names for `cmd` and the usable proof setup in it.
fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> {
let (path, _) = file_path(s, p, cmd)?;
// One byte past the limit shows a file over it, which is not read further.
let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?;
if bytes.len() > MAX_FILE {
return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes")));
}
let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let setup = checked_setup(&bytes, &path, cmd)?;
Ok((path, setup))
}
/// Read a picked proof setup's validated settings without applying them to the view.
pub fn draft_fields(bytes: &[u8], name: &str) -> Result<Value> {
let setup = checked_setup(bytes, name, "view.proofSetup.read")?;
Ok(Value::Object(setup_json(&setup)))
}
fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result<ProofSetup> {
if bytes.len() > MAX_FILE {
return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes")));
}
let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
Ok(setup)
}
pub(super) fn read(s: &mut Session, p: &Value) -> Result<Value> {
let (path, setup) = read_setup(s, p, "view.proofSetup.read")?;
let mut r = setup_json(&setup);
+38
View File
@@ -167,6 +167,8 @@ pub struct FrameStats {
/// group or an effect's raster. A part of the frame rendered on its own can draw that art with
/// other pixels than the whole frame does.
pub view_sized: usize,
bounded_view_sized: usize,
view_sized_bounds: Option<Rect>,
/// How many threads composed the frame from its two ink planes, in a CMYK document that shows
/// transparency; 0 for other frames.
pub ink_threads: usize,
@@ -183,10 +185,35 @@ pub struct FrameStats {
pub micros: u64,
}
impl FrameStats {
/// A conservative enclosure in the frame's output pixels, when every view-sized operation has
/// a known bound. `None` leaves the choice to render the whole frame.
pub fn view_sized_bounds(&self) -> Option<Rect> {
self.view_sized_bounds.filter(|_| self.bounded_view_sized == self.view_sized)
}
}
impl super::Renderer {
/// Records an operation bounded by its own output clip. A nested effect can affect more than
/// its own clip once an ancestor filters or composites it, so only bound direct RGB output.
pub(crate) fn note_view_sized_clip(&mut self, f: &Frame, clip: Rect) {
self.stats.view_sized += 1;
if self.nested == 0 && self.offscreen_live == 0 && f.view == f.output && f.doc.color_mode == vectorcraft_doc::ColorMode::Rgb {
let bound = f.output.transform_rect_bbox(clip).inflate(1.0, 1.0);
if bound.is_finite() {
self.stats.bounded_view_sized += 1;
self.stats.view_sized_bounds = vectorcraft_geom::union_opt(self.stats.view_sized_bounds, Some(bound));
}
}
}
}
#[derive(Clone, Copy)]
pub(crate) struct Frame<'a> {
/// Drawing into a multithreaded context: vello filter layers must be rendered offscreen.
pub(crate) mt: bool,
/// Set the flag if the incomplete paint would need a full render.
pub(crate) patch: Option<&'a std::cell::Cell<bool>>,
pub(crate) doc: &'a Document,
/// `doc`'s symbol art boxes, which culling measures symbol instances by ([`SymbolBoxes::quick`]).
pub(crate) symbols: &'a SymbolBoxes<'a>,
@@ -208,6 +235,17 @@ pub(crate) struct Frame<'a> {
}
impl Frame<'_> {
pub(crate) fn reject_patch(&self) -> bool {
self.patch.is_some_and(|hit| {
hit.set(true);
true
})
}
pub(crate) fn patch_rejected(&self) -> bool {
self.patch.is_some_and(std::cell::Cell::get)
}
/// Text space → device pixels when type is snapped to the pixel grid (Type anti-aliasing).
pub(crate) fn text_snap(&self, t: &TextObject) -> Option<Affine> {
(self.opts.anti_alias == AntiAlias::Type).then(|| self.view * t.xf)
+18 -2
View File
@@ -11,6 +11,12 @@ use super::{
RasterFx, Rect, RenderContext, Renderer, Shape, blend_mode, effects, fill_rule, paint, peniko,
};
/// The content to filter. An inner glow's output has an enclosing clip, while a shadow can spread beyond its content.
pub(super) enum FilterReach {
Clipped(Rect),
Spreads(Rect),
}
/// A hash of the names of `doc`'s swatches and patterns, of the paints and spot flags of its global
/// swatches, and of the Spot Colors option those colors depend on.
pub(crate) fn paint_names(doc: &Document) -> u64 {
@@ -596,15 +602,25 @@ impl Renderer {
&mut self,
ctx: &mut RenderContext,
f: &Frame,
reach: Rect,
reach: FilterReach,
blur: f64,
composite: Option<(vectorcraft_doc::color::BlendMode, f32)>,
draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame, Option<(vectorcraft_doc::color::BlendMode, f32)>),
) {
// A filter layer's coarser grid starts where its context does: at the corner of a context
// drawn single-threaded, and at the frame's edge for a region cropped to the frame.
let (reach, clipped) = match reach {
FilterReach::Clipped(rect) => (rect, true),
FilterReach::Spreads(rect) => (rect, false),
};
let screen = Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
self.stats.view_sized += usize::from(!f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen);
if !f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen {
if clipped {
self.note_view_sized_clip(f, reach);
} else {
self.stats.view_sized += 1;
}
}
if !f.mt {
return self.inside_layer(|r| draw(r, ctx, f, composite));
}
+9 -4
View File
@@ -1,5 +1,6 @@
use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage};
use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry};
use super::pixels::FilterReach;
use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted};
use super::raster::{
DRAG_PIXEL_BUDGET, MAX_RASTERIZE, PIXEL_BUDGET, ViewCrop, content_changing, doc_raster_ppi, image_size, linear_key, pan_margin, pcolor,
@@ -261,7 +262,7 @@ impl Renderer {
let reach = reach + Vec2::new(dx, dy);
#[cfg(test)]
note_silhouette();
self.with_filters(ctx, f, reach, blur, Some((mode, opacity)), |r, c, fr, comp| {
self.with_filters(ctx, f, FilterReach::Spreads(reach), blur, Some((mode, opacity)), |r, c, fr, comp| {
c.set_transform(fr.view);
c.push_layer(None, comp.map(|m| blend_mode(m.0)), comp.map(|m| m.1), None, Some(filter));
let ink = darkness.map_or(fr.ink, |d| fr.ink.darkened(d));
@@ -473,7 +474,7 @@ impl Renderer {
let opacity = self.opacity_of(a);
if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_doc::color::BlendMode::Normal || a.isolate) {
let blends = self.blends_through(a);
let bounds = if blends { self.bounds_of(f.symbols, a) } else { None };
let bounds = if blends { self.frame_bounds_of(f, a) } else { None };
let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() };
self.group(ctx, f, comp, &mut |r, c, fr| r.draw_object_fx_art(c, fr, a, cache));
} else {
@@ -819,6 +820,9 @@ impl Renderer {
rfx: &[RasterFx],
paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame),
) {
if !rfx.is_empty() && f.reject_patch() {
return;
}
// Only the last MAX_RASTERIZE Rasterize effects are drawn.
let count = rfx.iter().filter(|fx| matches!(fx, RasterFx::Rasterize(_))).count();
let capped: Vec<RasterFx>;
@@ -998,7 +1002,7 @@ impl Renderer {
let RasterFx::InnerGlow { mode, opacity, blur, color, center } = fx else { continue };
let filter = shadow_filter(0.0, 0.0, *blur, pcolor(f.ink, color));
if pixels {
self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |r, c, fr, comp| {
self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |r, c, fr, comp| {
if let Some((m, o)) = comp {
c.set_transform(Affine::IDENTITY);
c.push_layer(None, Some(blend_mode(m)), Some(o), None, None);
@@ -1032,7 +1036,7 @@ impl Renderer {
});
continue;
}
self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |_, c, fr, comp| {
self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |_, c, fr, comp| {
// The blend layer goes outside the clip: a clip layer is isolated, so a blend
// inside it would mix with nothing instead of the content below.
if let Some((m, o)) = comp {
@@ -1131,6 +1135,7 @@ mod tests {
let opts = RenderOptions::default();
let frame = Frame {
mt: false,
patch: None,
doc: &doc,
symbols: &symbols,
view: Affine::IDENTITY,
+72
View File
@@ -1530,6 +1530,78 @@ fn moved_objects_draw_their_effect_rasters_while_interacting() {
/// 1600 × 1000 view near its corner needs more than the drag's budget. The
/// frame after the drag, of the same document, is what a fresh renderer draws, as is a frame
/// rendered while interacting without a drag (a dialog's preview).
#[test]
fn a_plain_patch_stops_at_a_raster_effect() {
let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("texture.texturizer", json!({}))]);
let plain = Node::path(
doc.alloc_id(),
shapes::rectangle(Rect::new(94.0, 3.0, 96.0, 6.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap();
let (width, height) = (2000, 1600);
let view = Affine::scale(20.0);
let still = RenderOptions::default();
let mut renderer = Renderer::new();
renderer.threads = 0;
renderer.render(&doc, width, height, view, &still);
let total_drawn = renderer.stats.drawn;
let mut scratch = Renderer::new();
scratch.threads = 0;
let patch_view = Affine::translate((-1850.0, -50.0)) * view;
assert!(scratch.render_plain_patch(&doc, 100, 100, patch_view, &still).is_some(), "the distant patch does not draw the effect");
assert!(scratch.render_plain_patch(&doc, width, height, view, &still).is_none(), "a patch that draws the effect needs the full render");
assert!(scratch.stats.drawn < total_drawn, "the rejected patch does not draw the artwork after the effect");
}
#[test]
fn a_plain_patch_does_not_build_unrelated_3d_art_to_cull_it() {
let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("threeD.extrude", json!({"depth": 10}))]);
let plain = Node::path(
doc.alloc_id(),
shapes::rectangle(Rect::new(290.0, 10.0, 300.0, 20.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap();
let opts = RenderOptions::default();
let mut whole = Renderer::new();
whole.threads = 0;
whole.render(&doc, 350, 150, Affine::IDENTITY, &opts);
assert!(whole.stats.three_d_built > 0, "the fixture generates 3D art");
let mut scratch = Renderer::new();
scratch.threads = 0;
let patch = Affine::translate((-280.0, 0.0));
let result = scratch.render_plain_patch(&doc, 40, 30, patch, &opts);
assert_eq!(scratch.stats.three_d_built, 0, "fall back before rebuilding 3D art");
assert!(result.is_none());
let layer = doc.layers[0].id;
let art = doc.layers[0].children().unwrap()[0].clone();
doc.remove(art.id).unwrap();
let mut group = Node::group(doc.alloc_id(), vec![art.clone()]);
group.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.innerGlow".into(), params: json!({"blur": 4}), visible: true });
assert!(super::has_object_fx(&group), "this group uses the alternate bounds path");
let group = doc.insert(Some(layer), 0, group).unwrap();
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "alternate group bounds also need the 3D child");
doc.remove(group).unwrap();
let mut template = Node::layer(doc.alloc_id(), "Template", vectorcraft_doc::LayerColor::Preset(0));
if let vectorcraft_doc::NodeKind::Layer { template: flag, children, .. } = &mut template.kind {
*flag = true;
children.push(art.clone());
}
let template = doc.insert(Some(layer), 0, template).unwrap();
let hidden = RenderOptions { hide_templates: true, ..opts.clone() };
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &hidden).is_none(), "layer bounds conservatively include hidden templates");
assert_eq!(scratch.stats.three_d_built, 0);
doc.remove(template).unwrap();
doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Solid".into(), art });
let instance = Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Solid".into(), xf: Affine::IDENTITY });
doc.insert(Some(layer), 0, instance).unwrap();
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "a symbol's definition also needs 3D bounds");
}
#[test]
fn a_drag_renders_raster_effects_within_the_drag_budget() {
let effects = vec![("stylize.dropShadow", json!({"x": 4, "y": 3, "blur": 7, "opacity": 80})), ("texture.texturizer", json!({}))];
+7 -1
View File
@@ -114,6 +114,9 @@ impl Renderer {
}
fn group_offscreen(&mut self, ctx: &mut RenderContext, f: &Frame, c: Composite, r: Region, draw: &mut Content) {
if f.reject_patch() {
return;
}
let Composite { clip, blend, opacity, mask, isolated, .. } = c;
// A group that blends with its backdrop is drawn twice (over the backdrop, and alone for
// its coverage), and so is everything in it, so such groups nested in each other cost 2ⁿ.
@@ -309,7 +312,10 @@ impl Renderer {
/// `c` over the backdrop and its shape are drawn offscreen over `c`'s bounds, and `c` is drawn
/// as in the other knockout passes (groups in it can't copy their backdrop).
pub(crate) fn knockout_over(&mut self, ctx: &mut RenderContext, f: &Frame, c: &Arc<Node>, backdrop: &Arc<Pixmap>) {
let bounds = self.bounds_of(f.symbols, c);
let bounds = self.frame_bounds_of(f, c);
if f.patch_rejected() {
return;
}
let Some(r) = region(ctx, f, bounds) else { return };
let view = Affine::translate((-(r.x as f64), -(r.y as f64))) * f.view;
let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, r.w as f64, r.h as f64));
+5 -1
View File
@@ -583,7 +583,7 @@ impl Renderer {
let enclosing = std::mem::replace(&mut self.knockout, knockout);
if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) {
let blends = self.blends_through(a);
let bounds = if blends { self.bounds_of(f.symbols, a) } else { None };
let bounds = if blends { self.frame_bounds_of(f, a) } else { None };
let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() };
self.group(ctx, f, comp, &mut |r, c, fr| r.draw_live_body(c, fr, a, true));
} else {
@@ -636,6 +636,10 @@ impl Renderer {
if !m.is_valid() {
return;
}
// A cropped mesh may lose a covered neighbor that supplied a color at its fringe.
if f.reject_patch() {
return;
}
if f.opts.outline {
let bp = m.lines().to_bezpath();
self.hairline(ctx, f, &bp, [0, 0, 0, 255]);
+1
View File
@@ -198,6 +198,7 @@ fn rasterize(
let v = view * def.instance_xf(o);
let frame = Frame {
mt: false,
patch: None,
doc,
symbols: &symbols,
view: v,
+66 -11
View File
@@ -113,9 +113,32 @@ impl Renderer {
/// set in one of the document's composite fonts draws in the document's definition, also when
/// no session has registered it (a document that is not in front, or read from a file).
pub fn render(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered {
self.render_document(doc, width, height, view, opts, None)
}
/// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen
/// group compositing require the full render.
pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option<Rendered> {
if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample {
return None;
}
let hit = std::cell::Cell::new(false);
let image = self.render_document(doc, width, height, view, opts, Some(&hit));
(!hit.get()).then_some(image)
}
fn render_document(
&mut self,
doc: &Document,
width: u32,
height: u32,
view: Affine,
opts: &RenderOptions,
patch: Option<&std::cell::Cell<bool>>,
) -> Rendered {
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
self.render_as(doc, width, height, view, opts, false, 1)
self.render_as(doc, width, height, view, opts, false, 1, patch)
}
/// [`Self::render`], or with `inks` the ink amounts in the working CMYK space instead of
@@ -123,14 +146,24 @@ impl Renderer {
/// pixel of the output in pixels of this render: the supersampling factor while an export
/// draws its art at several times its size, else 1 ([`Frame::output`]).
#[allow(clippy::too_many_arguments)]
fn render_as(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions, inks: bool, cell: u32) -> Rendered {
fn render_as(
&mut self,
doc: &Document,
width: u32,
height: u32,
view: Affine,
opts: &RenderOptions,
inks: bool,
cell: u32,
patch: Option<&std::cell::Cell<bool>>,
) -> Rendered {
let start = now();
if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() {
let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE));
if let Some(k) = supersample_factor(w, h) {
let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() };
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k);
let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
self.hairline = hairline;
let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize);
self.stats.micros = now().saturating_sub(start);
@@ -164,7 +197,7 @@ impl Renderer {
let symbols = doc.symbol_boxes().quick();
let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view;
let plates = proof::plate_lut(opts, doc);
let frame = Frame { mt: threads > 0, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() };
let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() };
self.begin_frame();
// View Opacity Mask: the mask's coverage in greyscale instead of the artwork.
if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) {
@@ -199,7 +232,7 @@ impl Renderer {
self.draw_frame(&frame, w, h)
};
self.end_frame();
if !inks {
if !inks && !pixels.is_empty() {
proof::post(&mut pixels, opts);
}
self.stats.symbol_art = symbols.art_measured();
@@ -218,9 +251,8 @@ impl Renderer {
self.placed_frame = None;
}
/// End a frame: drop cache entries not used for a few frames (every render, thumbnails too,
/// so the nodes they hold go with them).
fn end_frame(&mut self) {
/// Drop stale bounds and paths, including old versions of edited nodes.
fn sweep_node_geometry(&mut self) {
let g = self.stamp;
// Swept however few the entries: each keeps its node alive, and an object dragged or
// edited makes a new node (with its layer) in every frame. Kept until there were 1,024 of
@@ -230,6 +262,23 @@ impl Renderer {
// A kept path stays while its object is in `geom`, which keeps the objects still drawn.
let geom = &self.geom;
self.kept.retain(|_, e| g - e.stamp <= 3 || geom.get(&(Arc::as_ptr(&e.node) as usize)).is_some_and(|k| Arc::ptr_eq(&k.node, &e.node)));
}
/// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update.
/// Age the measurement caches and keep the previous draw's effect rasters available.
pub fn finish_measurement_only(&mut self) {
self.stamp += 1;
self.sweep_node_geometry();
let g = self.stamp;
self.blends.retain(|_, e| g - e.2 <= 3);
self.let_go_of_measured();
}
/// End a frame: drop cache entries not used for a few frames (every render, thumbnails too,
/// so the nodes they hold go with them).
fn end_frame(&mut self) {
let g = self.stamp;
self.sweep_node_geometry();
if self.strokes.len() > 1024 {
self.strokes.retain(|_, e| g - e.stamp <= 3);
let strokes = &self.strokes;
@@ -309,11 +358,17 @@ impl Renderer {
} else {
self.draw_page(&mut ctx, f);
}
let pm = self.finish(&mut ctx, self.raster);
let pm = if f.patch_rejected() {
self.picture = None;
None
} else {
Some(self.finish(&mut ctx, self.raster))
};
self.contexts.push((threads, ctx));
if self.contexts.len() > 2 {
self.contexts.remove(0);
}
let Some(pm) = pm else { return Vec::new() };
let mut pixels = pm.data_as_u8_slice().to_vec();
if let Some(bg) = opts.background {
over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg)));
@@ -370,7 +425,7 @@ impl Renderer {
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
self.render_as(doc, w, h, view, opts, true, 1).pixels
self.render_as(doc, w, h, view, opts, true, 1, None).pixels
}
/// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels.
@@ -427,7 +482,7 @@ impl Renderer {
ctx.set_aliasing_threshold(opts.anti_alias.threshold());
let symbols = doc.symbol_boxes().quick();
let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view;
let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None };
let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None };
let raster = std::mem::replace(&mut self.raster, raster_settings(opts));
self.begin_frame();
(self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None);
+64 -8
View File
@@ -7,10 +7,33 @@ use super::{
use crate::kept_paths::{self, KeptPath};
use crate::node_checks::{holds_measured_three_d, measures_three_d};
fn needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool {
measures_three_d(node)
|| matches!(&node.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.symbol(symbol).is_some_and(
|s| holds_measured_three_d(&s.art) || holds_instance(&s.art) && symbols.has_effects(symbol)
))
}
fn subtree_needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool {
needs_three_d_bounds(symbols, node)
|| node.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child)))
}
impl Renderer {
/// Cached cull bounds of a node (containers union their cached children), symbol instances
/// measured by their art box from `symbols`.
pub(crate) fn bounds_of(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<Rect> {
self.bounds_with_patch(symbols, a, None)
}
pub(crate) fn frame_bounds_of(&mut self, f: &Frame, a: &Arc<Node>) -> Option<Rect> {
self.bounds_with_patch(f.symbols, a, f.patch.map(|_| f))
}
fn bounds_with_patch(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, patch: Option<&Frame<'_>>) -> Option<Rect> {
if patch.is_some_and(Frame::patch_rejected) {
return None;
}
let key = Arc::as_ptr(a) as usize;
if let Some(e) = self.geom.get_mut(&key)
&& Arc::ptr_eq(&e.node, a)
@@ -18,6 +41,11 @@ impl Renderer {
e.stamp = self.stamp;
return e.bounds;
}
// The full renderer can reuse its 3D art. A cold scratch renderer may otherwise
// build it while calculating cull bounds, including bounds of symbol definitions.
if patch.is_some_and(|f| needs_three_d_bounds(symbols, a) && f.reject_patch()) {
return None;
}
let b = match &a.kind {
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(a) => {
let mut acc: Option<Rect> = None;
@@ -25,7 +53,10 @@ impl Renderer {
let source = a.extras().trace.is_some().then(|| children.first()).flatten();
for c in children {
if c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)) {
acc = vectorcraft_geom::union_opt(acc, self.bounds_of(symbols, c));
acc = vectorcraft_geom::union_opt(acc, self.bounds_with_patch(symbols, c, patch));
if patch.is_some_and(Frame::patch_rejected) {
return None;
}
}
}
acc
@@ -48,6 +79,14 @@ impl Renderer {
let pad = brush_fx::pad(symbols, a);
b.map(|b| fx::with_own_raster_reach(symbols, a, b).inflate(pad, pad))
}
// The fallback measures the whole subtree without going through the cached
// child traversal above. Reject cold measurement before entering it.
_ if patch.is_some_and(|f| {
a.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child))) && f.reject_patch()
}) =>
{
return None;
}
_ => self.kept_bounds(symbols, a).unwrap_or_else(|| brush_fx::cull_bounds(symbols, a)),
};
self.geom.insert(key, GeomEntry { node: a.clone(), bounds: b, path: None, stamp: self.stamp });
@@ -227,7 +266,11 @@ impl Renderer {
if crate::node_checks::left_out(f.opts, f.doc, a) {
return true;
}
match self.bounds_of(f.symbols, a) {
let bounds = self.frame_bounds_of(f, a);
if f.patch_rejected() {
return true;
}
match bounds {
Some(b) => {
let pad = f.px * 2.0;
// Level of detail: leaves smaller than a quarter pixel are invisible.
@@ -241,7 +284,7 @@ impl Renderer {
}
pub(crate) fn draw_arc(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>) {
if self.skipped(f, a) {
if f.patch_rejected() || self.skipped(f, a) {
return;
}
// An image masked by one white shape painted straight into the shape, as an image in a
@@ -272,7 +315,10 @@ impl Renderer {
let Some(m) = a.extras().mask.as_deref().filter(|m| !m.disabled && !f.opts.outline && !self.is_shape(a)) else { return false };
// A masked object is a non-isolated group of its own, drawn over its own pixels: the
// mask is rendered over those only.
let bounds = self.bounds_of(f.symbols, a);
let bounds = self.frame_bounds_of(f, a);
if f.patch_rejected() {
return true;
}
let Some((r, sub)) = group::area(ctx, f, bounds) else { return true };
let Some(mask) = self.mask_values(&sub, m, r.w, r.h) else { return true };
let blends = a.blend != vectorcraft_color::BlendMode::Normal || (!a.isolate && self.blends_through(a));
@@ -296,6 +342,9 @@ impl Renderer {
/// The coverage of opacity mask `m` per output pixel (row-major): its art rendered offscreen,
/// as luminance ([`mask_value`]).
pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Option<Vec<u8>> {
if f.reject_patch() {
return None;
}
let mut mctx = f.offscreen_context(w, h);
// Mask art is a picture of its own: it takes no part in a knockout group around the object,
// and its luminance is that of its screen colours.
@@ -393,7 +442,7 @@ impl Renderer {
return;
}
// A cancelled export stops drawing; whoever asked for the picture drops it (see `cancel`).
if vectorcraft_doc::cancel::is_cancelled() {
if f.patch_rejected() || f.patch.is_some() && measures_three_d(n) && f.reject_patch() || vectorcraft_doc::cancel::is_cancelled() {
return;
}
if force {
@@ -679,7 +728,7 @@ impl Renderer {
let inverse = im.xf.inverse();
let (mut x0, mut x1, mut y0, mut y1) = (0.0_f64, w, 0.0_f64, h);
for c in shapes {
if let Some(b) = self.bounds_of(f.symbols, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) {
if let Some(b) = self.frame_bounds_of(f, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) {
for q in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] {
let p = inverse * kurbo::Point::new(q.0, q.1);
if p.x.is_finite() && p.y.is_finite() {
@@ -742,7 +791,11 @@ impl Renderer {
if crate::node_checks::left_out(f.opts, f.doc, c) {
return;
}
match self.bounds_of(f.symbols, c) {
let bounds = self.frame_bounds_of(f, c);
if f.patch_rejected() {
return;
}
match bounds {
Some(b) => {
let pad = f.px * 2.0;
if !rects_overlap(b.inflate(pad, pad), f.visible) {
@@ -781,7 +834,7 @@ impl Renderer {
self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n)));
}
} else {
for c in children {
for c in children.iter().take_while(|_| !f.patch_rejected()) {
self.draw_arc(ctx, f, c);
}
}
@@ -804,6 +857,9 @@ impl Renderer {
/// over the elements below it (the art below the group when the group is non-isolated and
/// drawn over a copy of it, see [`Self::group`] and [`Self::knockout_over`]).
pub(crate) fn draw_knockout(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc<Node>]) {
if f.reject_patch() {
return;
}
let backdrop = self.backdrop.take();
for c in Node::knockout_elements(children) {
if self.skipped(f, c) {
+4
View File
@@ -327,6 +327,10 @@ impl Renderer {
/// characters'. It also returns false for type whose offscreen drawing would be more than
/// [`MAX_RASTER_SIDE`] pixels a side or more than [`fx::PIXEL_BUDGET`] pixels in all.
fn draw_type_edges(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, t: &TextObject, g: &Arc<TextGeom>, geom_kept: bool) -> bool {
// A smaller frame can fit the offscreen type that a full frame draws as Sharp.
if f.reject_patch() {
return true;
}
if proof::overprints(f.opts) && t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke) {
return false;
}
+24
View File
@@ -10,6 +10,30 @@ use crate::blobs::blob_key;
use crate::tests_fontchange::fonts_steady;
use crate::*;
#[test]
fn geometry_from_measurement_only_frames_releases_old_node_versions() {
let mut doc = Document::new(100.0, 100.0);
let layer = doc.layers[0].id;
let id = doc.alloc_id();
let path = Node::path(
id,
vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)),
vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
doc.insert(Some(layer), 0, path).unwrap();
let oldest = Arc::downgrade(&doc.layers[0].children().unwrap()[0]);
let mut renderer = Renderer::new();
let opts = RenderOptions::default();
for _ in 0..12 {
let mut next = doc.clone();
next.node_mut(id).unwrap().transform(Affine::translate((1.0, 0.0)), false);
assert!(matches!(renderer.changed(&doc, &next, &opts), Changed::Area(_)));
renderer.finish_measurement_only();
doc = next;
}
assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw");
}
/// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by
/// the tests running alongside).
fn png(w: u32, h: u32, seed: u8) -> Vec<u8> {
+11
View File
@@ -43,6 +43,17 @@ fn partial(a: &[u8]) -> usize {
a.iter().filter(|v| **v > 0 && **v < 255).count()
}
#[test]
fn a_plain_patch_defers_frame_sensitive_type_edges() {
let mut renderer = Renderer::new();
renderer.threads = 0;
let opts = RenderOptions::default();
let sharp = page(TypeAntiAlias::Sharp, None);
let crisp = page(TypeAntiAlias::Crisp, None);
assert!(renderer.render_plain_patch(&sharp, W, H, Affine::IDENTITY, &opts).is_some());
assert!(renderer.render_plain_patch(&crisp, W, H, Affine::IDENTITY, &opts).is_none());
}
/// The first pixels of `drawn` (type drawn with `m`) that are not the share `edge_coverage` gives
/// the same pixel of `sharp` (the type drawn with Sharp), within a step of rounding: (pixel,
/// Sharp, drawn).
+4
View File
@@ -276,6 +276,10 @@ fn a_frame_counts_the_art_it_draws_by_its_size() {
let mut r = Renderer::new();
r.render(&mesh(100.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default());
assert_eq!(r.stats.view_sized, 0, "a mesh within the mesh buffer");
assert!(
r.render_plain_patch(&mesh(100.0), 60, 60, Affine::translate((-50.0, -50.0)), &RenderOptions::default()).is_none(),
"a patch through a mesh must fall back even when the full mesh fits"
);
r.render(&mesh(3000.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default());
assert!(r.stats.view_sized > 0, "a mesh past the mesh buffer");
}
+2
View File
@@ -121,6 +121,8 @@ impl VectorcraftApp {
moved: false,
from_worker: false,
whole_frames: false,
view_sized_bounds: None,
web_patch_renderer: None,
reused: None,
waits_for_still: cfg!(target_arch = "wasm32"),
still: None,
+8 -3
View File
@@ -26,10 +26,15 @@ pub struct CanvasCache {
/// ([`canvas::show`]).
pub from_worker: bool,
/// The frame shown drew art in a way that depends on its size, or a part of it drawn again on
/// this thread would not have matched the frame around it: until the next whole frame is shown,
/// edits of the frame shown render whole, on the worker when the frame is heavy
/// ([`canvas::show`]).
/// this thread would not have matched the frame around it. Edits that reach the affected area
/// render whole, on the worker when the frame is heavy ([`canvas::show`]).
pub whole_frames: bool,
/// The shown web frame can still be patched outside this enclosure in its own raster pixels.
/// Present only when all frame-size-dependent output has a known bound.
pub view_sized_bounds: Option<vectorcraft_geom::Rect>,
/// Draws for a patch against a web frame with bounded view-sensitive art.
/// The renderer of the whole frame keeps its raster and derived-art caches across these patches.
pub web_patch_renderer: Option<Box<vectorcraft_render::Renderer>>,
/// The frame shown holds pixels the worker copied from its last frame, and when it was shown
/// (seconds, egui's input time): it renders whole once it has been shown for
/// [`canvas::STILL_SECS`] with the view unmoved.
+2 -9
View File
@@ -353,7 +353,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy}))
}
Payload::Style(_) => Ok(()),
Payload::Panel(PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => {
Payload::Panel(drag @ PanelDrag::Paint { params, paint, .. }) if !params.is_null() => {
if let Some(color) = paint.color()
&& crate::panels::proxy_cmd(app, false) == "paint.setFill"
&& let Some((id, points)) = selected_mesh_drop(app, at, zoom)
@@ -362,14 +362,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
return run(app, "object.mesh.setPointColor", params);
}
let Some(hit) = hit() else { return Ok(()) };
let mut params = if let Some(rows) = rows.as_ref().filter(|rows| rows.unlinked_process_color)
&& app.session.active().is_some_and(|st| st.uid != rows.document)
&& let Some(color) = paint.color()
{
json!({"color": crate::panels::color_json(&color), "keepModel": true})
} else {
params.clone()
};
let Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| st.uid)) else { return Ok(()) };
params["ids"] = json!([owner(app, &hit)?]);
params["focus"] = json!(false);
let cmd = crate::panels::proxy_cmd(app, false);
+52 -11
View File
@@ -57,9 +57,10 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo
/// is at most 8 ms, and except when that frame drew raster effects from rasters made before their
/// objects moved ([`crate::CanvasCache::moved`]) or holds pixels copied from the worker's last frame
/// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects,
/// and this thread's doesn't. No frame that drew art in a way that depends on its size, or that a
/// part drawn again here since it was shown would have differed from, is drawn again in part
/// ([`crate::CanvasCache::whole_frames`]). A frame that drew nothing from moved rasters or at a
/// and this thread's doesn't. A web frame with known view-sensitive output bounds can still be
/// patched outside them, accounting for the patch's rounding. Otherwise view-sensitive art or
/// an earlier rejected patch requires a whole render ([`crate::CanvasCache::whole_frames`]).
/// A frame that drew nothing from moved rasters or at a
/// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction
/// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change.
/// Leaving an interaction still replaces the whole frame. What changed is measured by this thread's renderer: it keeps what
@@ -101,17 +102,32 @@ pub(super) fn changed_pixels(
vectorcraft_render::Changed::Nothing => Some(None),
vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) {
None => Some(None),
Some([x0, y0, x1, y1]) if !app.canvas.whole_frames => {
Some([x0, y0, x1, y1]) => {
let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h));
let patch = Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1));
if app.canvas.whole_frames && app.canvas.view_sized_bounds.is_none_or(|bounds| !bounds.intersect(patch).is_zero_area()) {
return None;
}
// A full draw can use 3D art measured here. Do not rebuild it in the scratch renderer.
if app.canvas.view_sized_bounds.is_some() && app.canvas.renderer.measured_bytes() > 0 {
return None;
}
let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h));
(share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1]))
}
Some(_) => None,
},
vectorcraft_render::Changed::Everything => None,
}
}
fn web_patch_renderer(slot: &mut Option<Box<vectorcraft_render::Renderer>>) -> &mut vectorcraft_render::Renderer {
slot.get_or_insert_with(|| {
let mut renderer = vectorcraft_render::Renderer::new();
renderer.threads = 0;
Box::new(renderer)
})
}
/// `a..b` of `0..n`, grown to whole eighths of `n` and moved back into `0..n`: the parts of a
/// frame rendered again come in few sizes, which keep the contexts the renderer keeps.
fn in_steps(a: u32, b: u32, n: u32) -> (u32, u32) {
@@ -608,6 +624,8 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate:
app.canvas.moved = done.moved > 0;
app.canvas.from_worker = true;
app.canvas.whole_frames = done.view_sized;
app.canvas.view_sized_bounds = None;
app.canvas.web_patch_renderer = None;
}
/// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas.
@@ -707,15 +725,27 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
let t0 = monotonic_ms();
if region.is_none() {
// Nothing in view to draw again: what was made to measure the edit isn't drawn.
app.canvas.renderer.let_go_of_measured();
app.canvas.renderer.finish_measurement_only();
}
let display = app.display_profile.transform(app.session.prefs.monitor_profile_display);
if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) {
let renderer = &mut app.canvas.renderer;
let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view;
let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts));
let plain_patch = app.canvas.view_sized_bounds.is_some();
let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer };
let part = effects.view(|| {
if plain_patch {
renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts)
} else {
Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts))
}
});
let Some(mut part) = part else {
app.canvas.view_sized_bounds = None;
return false;
};
if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 {
app.canvas.whole_frames = true;
app.canvas.view_sized_bounds = None;
return false;
}
let width = part.width;
@@ -723,7 +753,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
let color = color_image(&part);
let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
tex.set_partial([x0 as usize, y0 as usize], color, options);
app.canvas.moved |= app.canvas.renderer.stats.moved > 0;
app.canvas.moved |= renderer.stats.moved > 0;
if plain_patch {
app.canvas.renderer.finish_measurement_only();
}
}
app.canvas.key = Some((*key).clone());
app.canvas.shown = Some(((*doc).clone(), opts.clone()));
@@ -779,6 +812,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
// thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a
// part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]).
let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc);
if !same_doc {
app.canvas.web_patch_renderer = None;
}
let settling = app.canvas.moved && !key.interacting;
let staying = key.interacting && app.canvas.from_worker;
// A document's first frame (opened, or its tab chosen) renders on the worker too: how long it
@@ -802,7 +838,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
(Some(worker), true, false) => {
// The worker draws the frame: what this thread's renderer made to measure the edit
// isn't drawn here.
app.canvas.renderer.let_go_of_measured();
app.canvas.renderer.finish_measurement_only();
let queued = worker.submit(crate::render_worker::Job {
key: key.clone(),
doc: doc.clone(),
@@ -835,7 +871,12 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
app.perf.render_ms = monotonic_ms() - t0;
app.canvas.last_ms = app.perf.render_ms;
app.canvas.moved = app.canvas.renderer.stats.moved > 0;
app.canvas.whole_frames = app.canvas.renderer.stats.view_sized > 0 || app.canvas.renderer.stats.previewed > 0;
let stats = app.canvas.renderer.stats;
app.canvas.whole_frames = stats.view_sized > 0 || stats.previewed > 0;
app.canvas.view_sized_bounds = if app.canvas.waits_for_still && stats.previewed == 0 { stats.view_sized_bounds() } else { None };
if app.canvas.view_sized_bounds.is_none() {
app.canvas.web_patch_renderer = None;
}
app.canvas.from_worker = false;
app.canvas.reused = None;
}
+72
View File
@@ -1030,6 +1030,78 @@ fn an_edit_over_art_drawn_for_the_frames_size() {
}
}
#[test]
fn web_partial_redraws_skip_unchanged_view_sensitive_art() {
keeping_color_settings(|| {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
app.ui.task_bar = false;
app.ui.view.rulers = false;
app.canvas.worker_started = true;
app.canvas.waits_for_still = true;
app.canvas.renderer.threads = 0;
let glow = app.run("shape.rectangle", json!({"x": 55, "y": 70, "width": 55, "height": 55})).unwrap()["id"].clone();
app.run("effect.apply", json!({"ids": [glow], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap();
let large = app.run("shape.rectangle", json!({"x": -980, "y": -700, "width": 965, "height": 1010})).unwrap()["id"].clone();
app.run("effect.apply", json!({"ids": [large], "effect": "texture.texturizer", "params": {}})).unwrap();
let far = app.run("shape.rectangle", json!({"x": 300, "y": 200, "width": 12, "height": 12})).unwrap()["id"].clone();
let near = app.run("shape.rectangle", json!({"x": 60, "y": 80, "width": 12, "height": 12})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap();
app.run("select.none", json!({})).unwrap();
let ctx = crate::testing::ui_context();
shapes(&mut app, &ctx);
if let Some(vm) = app.view_mut() {
(vm.zoom, vm.center) = (1.2, Point::new(200.0, 150.0));
}
// Start from a full raster at the chosen view rather than waiting for the reprojected view to settle.
app.canvas.key = None;
let read = |app: &mut VectorcraftApp| {
let (_, mut delta) = frame_output(app, &ctx);
let tex = app.canvas.texture.as_ref().unwrap().id();
delta.set.remove(&tex).and_then(|mut uploads| uploads.pop()).expect("the edit uploads canvas pixels")
};
let first = read(&mut app);
assert!(first.pos.is_none());
assert!(app.canvas.renderer.stats.view_sized > 0, "single-threaded filter layers depend on the frame size");
let egui::ImageData::Color(first) = first.image;
let mut composed = (*first).clone();
for color in ["#ff0000", "#00ff00"] {
app.run("paint.setFill", json!({"ids": [far], "color": color})).unwrap();
let delta = read(&mut app);
let [x, y] = delta.pos.expect("an edit away from the glow uploads only a patch");
let egui::ImageData::Color(patch) = delta.image;
for row in 0..patch.height() {
let start = (y + row) * composed.width() + x;
composed.pixels[start..start + patch.width()].copy_from_slice(&patch.pixels[row * patch.width()..(row + 1) * patch.width()]);
}
}
let key = app.canvas.key.as_ref().unwrap();
let view = app.canvas_view().unwrap();
let (w, h, view) = frame_view(key.pixel, (key.w, key.h), &view, key.ppp);
let (doc, still) = app.canvas.shown.as_ref().unwrap();
let drag = vectorcraft_render::RenderOptions { interacting: true, dragging: true, ..still.clone() };
let mut cold = vectorcraft_render::Renderer::new();
cold.threads = 0;
cold.render(doc, w, h, view, &drag);
assert!(cold.stats.previewed > 0, "a cold renderer draws the large effect at drag resolution");
app.canvas.renderer.render(doc, w, h, view, &drag);
assert_eq!(app.canvas.renderer.stats.previewed, 0, "distant canvas patches left the full-resolution effect available for the drag");
// The old glow's bounds survive successive partial renders, even though neither draws it.
app.run("paint.setFill", json!({"ids": [near], "color": "#0202ee"})).unwrap();
let overlap = read(&mut app);
assert!(overlap.pos.is_none(), "editing inside the old glow's bounds renders the whole frame");
app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap();
let restored = read(&mut app);
assert!(restored.pos.is_none());
let egui::ImageData::Color(restored) = restored.image;
assert_eq!(restored.size, composed.size);
assert!(restored.pixels == composed.pixels, "partial updates equal a full redraw: {}", differing(&composed.pixels, Some(&restored.pixels)));
app.run("effect.apply", json!({"ids": [far], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap();
assert!(read(&mut app).pos.is_none(), "the new glow in the part also requires a whole frame");
});
}
/// A canvas more device pixels across than the largest texture side the display supports renders
/// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel
/// Preview's region of document pixels stays within it too.
+17 -3
View File
@@ -21,7 +21,7 @@ super::confirm::wrapped_dialog!(BrushDeleteQuestion, StandardPrompt, KIND);
/// What the question is about: the document it was asked in, the `brush.delete` params and whether a
/// stroke uses one of the brushes.
struct BrushDeleteAsk {
doc: Option<u64>,
doc: Option<(u64, u64)>,
params: Value,
used: bool,
}
@@ -33,7 +33,7 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) {
return;
};
let (message, yes, no) = words(used);
let doc = app.session.active().map(|d| d.uid);
let doc = app.session.active().map(|d| (d.uid, d.reverts));
let prompt =
StandardPrompt::custom(message).button(PromptChoice::Proceed, yes).button(PromptChoice::Cancel, no).tag(BrushDeleteAsk { doc, params, used });
dialogs.with(|host| host.open(BrushDeleteQuestion(prompt)));
@@ -89,7 +89,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// Yes on brushes that a stroke has started to use since the question opened asks again with Remove
/// Strokes and Cancel. When another document has become the active one, nothing is deleted.
fn confirm(app: &mut VectorcraftApp, question: BrushDeleteAsk) {
if question.doc != app.session.active().map(|doc| doc.uid) {
if !confirmation_is_current(app, question.doc) {
return;
}
if !question.used {
@@ -111,5 +111,19 @@ pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, bool)> {
Some((words(used).0.to_string(), used))
}
/// Whether the opening Brush confirmation still owns the active drawing's contents.
pub(super) fn confirmation_is_current(app: &mut VectorcraftApp, opening: Option<(u64, u64)>) -> bool {
let current = app.session.active().map(|st| (st.uid, st.reverts));
if opening == current {
return true;
}
if let (Some((document, _)), Some((active, _))) = (opening, current)
&& document == active
{
app.status(tl!("The document was reverted. Reopen this dialog to continue."));
}
false
}
#[cfg(test)]
pub(super) mod tests;
@@ -10,6 +10,15 @@ pub(in crate::dialogs) fn app() -> VectorcraftApp {
crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()))
}
/// Writes a native file for the test to revert to.
pub(in crate::dialogs) fn save_for_revert(app: &mut VectorcraftApp, tag: &str) -> std::path::PathBuf {
let file = std::env::temp_dir().join(format!("vectorcraft-brush-{tag}-{}.vectorcraft", std::process::id()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap();
file
}
/// Answers the open question `D` the way its button does (`Some(choice)`: the button of that choice,
/// `None`: Cancel's close), then runs the module's `pump`.
pub(in crate::dialogs) fn answer<D: StackDialog>(app: &mut VectorcraftApp, choice: Option<&str>, pump: fn(&mut VectorcraftApp, &egui::Context)) {
@@ -84,3 +93,36 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() {
assert!(stroke.width > 0.0);
}
}
#[test]
fn stale_delete_approval_keeps_the_saved_brush_after_revert() {
let mut app = app();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let slim = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 8})).unwrap()["id"].as_u64().unwrap();
let tall = app.run("shape.rectangle", json!({"x": 10, "y": 30, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [slim]})).unwrap();
let file = save_for_revert(&mut app, "delete-revert");
let brush_height = |app: &mut VectorcraftApp| {
let brush = app.run("brush.get", json!({"name": "Bar"})).expect("the saved brush still exists");
let art: vectorcraft_doc::Node = serde_json::from_value(brush["art"].clone()).unwrap();
art.geometric_bounds().unwrap().height()
};
let saved = brush_height(&mut app);
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap();
assert!((brush_height(&mut app) - saved).abs() > 1e-6);
ask(&mut app, json!({"names": ["Bar"]}), false);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(file);
let st = app.session.active().unwrap();
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
assert!((brush_height(&mut app) - saved).abs() < 1e-6);
let undo = app.session.active().unwrap().history.undo.len();
answer::<BrushDeleteQuestion>(&mut app, Some("proceed"), pump);
assert!((brush_height(&mut app) - saved).abs() < 1e-6);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
}
@@ -22,7 +22,7 @@ super::confirm::wrapped_dialog!(ReplaceArtQuestion, StandardPrompt, KIND);
/// What the question is about: the document it was asked in, the brush and the art.
struct ReplaceArtAsk {
doc: Option<u64>,
doc: Option<(u64, u64)>,
name: String,
ids: Vec<u64>,
}
@@ -59,7 +59,7 @@ pub fn ask(app: &mut VectorcraftApp, name: &str, ids: &[u64]) {
app.status("no window");
return;
};
let doc = app.session.active().map(|d| d.uid);
let doc = app.session.active().map(|d| (d.uid, d.reverts));
let prompt = StandardPrompt::custom(tl!(
"Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?"
))
@@ -86,7 +86,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// Runs `brush.replaceArt`. When another document has become the active one, no brush changes.
fn confirm(app: &mut VectorcraftApp, question: ReplaceArtAsk, apply: bool) {
if question.doc != app.session.active().map(|doc| doc.uid) {
if !super::brush_delete::confirmation_is_current(app, question.doc) {
return;
}
let params = json!({"name": question.name, "ids": question.ids, "applyToStrokes": apply});
@@ -1,7 +1,7 @@
use serde_json::json;
use vectorcraft_doc::NodeId;
use super::super::brush_delete::tests::{answer, app};
use super::super::brush_delete::tests::{answer, app, save_for_revert};
use super::*;
fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> u64 {
@@ -95,3 +95,30 @@ fn a_button_changes_no_brush_after_another_document_became_active() {
app.run("document.activate", json!({"index": 0})).unwrap();
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6);
}
#[test]
fn stale_replace_approval_keeps_the_saved_brush_art_after_revert() {
let mut app = app();
let (_, tall) = used_brush(&mut app);
let thick = rect(&mut app, 10.0, 65.0, 40.0, 30.0);
let file = save_for_revert(&mut app, "replace-revert");
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap();
assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6);
replace(&mut app, "Bar", &[thick]);
assert!(asks(&app));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(file);
let st = app.session.active().unwrap();
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
assert!(st.doc.node(NodeId(thick)).is_some(), "the restored drawing shares the same local source ID");
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6);
let undo = app.session.active().unwrap().history.undo.len();
answer::<ReplaceArtQuestion>(&mut app, Some("proceed"), pump);
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6, "the stale answer leaves the restored brush intact");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
}
+22 -10
View File
@@ -26,6 +26,7 @@
use std::cell::RefCell;
use std::ops::RangeInclusive;
use std::path::Path;
use std::sync::Arc;
use craft::behavior::{ColumnKey, ColumnWidth, Selection, SelectionChange, keyed};
@@ -135,6 +136,8 @@ enum PartEdit {
/// The Composite Fonts dialog on the dialog host. OK files the fonts for [`pump`], which runs
/// [`COMMAND`] and answers whether the dialog may close.
pub struct CompositeFontsDialog {
/// The document whose fonts the draft edits.
document: u64,
fonts: Vec<CompositeFont>,
/// The index of the font picked.
selected: usize,
@@ -167,9 +170,9 @@ pub struct CompositeFontsDialog {
/// Open Composite Fonts on the active document's composite fonts, the first one picked, with the
/// custom character sets and the sample hidden and nothing typed.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec();
let document = app.session.active().ok_or("no document open")?;
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
let dialog = CompositeFontsDialog::new(fonts, crate::font_menu::hold(app));
let dialog = CompositeFontsDialog::new(document.uid, document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app));
dialogs.with(|host| host.open(dialog));
Ok(Value::Null)
}
@@ -241,10 +244,11 @@ fn part_mut(f: &mut CompositeFont, at: usize) -> Option<&mut CompositePart> {
impl CompositeFontsDialog {
/// The dialog over `fonts`, the first picked.
fn new(fonts: Vec<CompositeFont>, hold: PickerHold) -> Self {
fn new(document: u64, fonts: Vec<CompositeFont>, hold: PickerHold) -> Self {
let mut sample = Map::new();
sample::defaults(&mut sample);
CompositeFontsDialog {
document,
fonts,
selected: 0,
set: 0,
@@ -852,15 +856,18 @@ impl StackDialog for CompositeFontsDialog {
/// file dialog a Load…, Replace… or Save… asked for.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let Some((held, request)) = with_dialog(app, |d| {
let held = d.held.take();
let held = d.held.take().map(|fonts| (d.document, fonts));
let request = d.file.take().map(|request| (request, Arc::clone(&d.file_owner)));
(held, request)
}) else {
return;
};
if let Some(fonts) = held {
// A name two fonts share or a value out of range keeps the dialog open with the reason.
let answer = app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from);
if let Some((document, fonts)) = held {
let answer = if app.session.active().is_some_and(|active| active.uid == document) {
app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from)
} else {
Err(Label::from(tl!("Composite Fonts can only change the document where it was opened.").to_owned()))
};
with_dialog(app, |d| d.held.answer(answer));
}
if let Some((request, owner)) = request {
@@ -892,14 +899,19 @@ fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()>
/// Reads the fonts of the file picked and gives them to the dialog (Load… or Replace…).
fn load_file(app: &mut VectorcraftApp, request: &PresetFileRequest, replace: bool, picked: &Picked) -> Result<Value, String> {
// PLAN: assumed fl.A23 `file_asks::open_params(&Picked) -> Option<Map<String, Value>>`; `None` is a cancelled pick.
let Some(mut params) = open_params(picked) else { return Ok(Value::Null) };
let browser_name = params.remove("name");
let name = picked
.first_path()
.as_deref()
.or_else(|| browser_name.as_ref().and_then(Value::as_str).map(Path::new))
.and_then(Path::file_name)
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
params.insert("apply".into(), json!(false));
let read = app.run(IMPORT, Value::Object(params))?;
let fonts: Vec<CompositeFont> = serde_json::from_value(read["fonts"].clone()).map_err(|e| e.to_string())?;
with_dialog(app, |d| d.load(fonts, replace));
let name = picked.first_path().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default();
// Only the file's name goes into the status line.
if let Some(event) = request.loaded(name, Vec::new()) {
report(app, event);
}
@@ -97,6 +97,36 @@ fn delayed_load_and_replace_leave_the_reopened_composite_fonts_draft_alone() {
}
}
#[test]
fn load_and_replace_accept_a_browser_picked_file() {
let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["Draft", "From Web"]), (PresetCommands::Replace, &["From Web"])];
for (command, expected) in choices {
let mut app = app();
let picker = scripted(&mut app);
let ctx = ctx(&app);
open(&mut app).unwrap();
let bytes = dialog(&mut app, |d| {
d.new_font("From Web".into());
file_bytes(&d.fonts).unwrap()
});
cancel(&mut app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Draft".into()));
let dialogs = app.dialogs().unwrap();
ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear();
let step = steps(&app);
request(&mut app, command, None);
picker.answer_contents(&[("picked.vccomposite", &bytes)]);
poll(&mut app, &ctx);
let draft_names = dialog(&mut app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::<Vec<_>>());
assert_eq!(draft_names, expected, "{}", app.ui.status);
assert!(app.ui.status.contains("picked.vccomposite"), "{}", app.ui.status);
assert!(names(&app).is_empty(), "picking a file edits only the draft");
assert_eq!(steps(&app), step);
}
}
fn steps(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
@@ -169,6 +199,41 @@ fn composite_fonts_change_on_ok_as_one_undo_step() {
assert!(names(&app).is_empty());
}
#[test]
fn a_held_composite_fonts_ok_keeps_the_draft_with_its_opening_document() {
let mut app = app();
app.run("file.new", json!({"width": 440, "height": 440})).unwrap();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Destination only".into()));
ok(&mut app).unwrap();
let destination = (names(&app), steps(&app));
app.run("document.activate", json!({"index": 0})).unwrap();
let source = (names(&app), steps(&app));
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("From the source".into()));
let ctx = ctx(&app);
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| {
assert!(!host.confirm_by_id(&ctx, id));
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
});
app.run("document.activate", json!({"index": 1})).unwrap();
pump(&mut app, &ctx);
assert_eq!((names(&app), steps(&app)), destination, "the other document keeps its fonts and undo history");
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
assert!(is_open(&app));
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!((names(&app), steps(&app)), source);
ok(&mut app).unwrap();
assert_eq!(names(&app), ["From the source"]);
assert_eq!(steps(&app), source.1 + 1);
assert!(!is_open(&app));
}
/// New is based on the font picked and takes the next free name; a name two fonts share, or one
/// left empty, keeps the dialog open and changes nothing.
#[test]
@@ -9,6 +9,8 @@
//!
//! Field: `selected` (a preset's name).
use std::sync::Arc;
use craft::behavior::{DisplayOrder, ItemSource, Selection};
use craft::host::PickRequest;
use craft::ui::buttons::Button;
@@ -117,13 +119,22 @@ pub(super) struct PresetsDialog {
names: Vec<String>,
/// The button pressed in the last pass, for [`pump`] to run outside the host's lock.
action: Option<Action>,
/// Identifies the manager that opened an Import picker.
import_owner: Arc<()>,
open: bool,
}
impl PresetsDialog {
fn new(selected: &str, presets: Vec<GridDefinition>) -> Self {
let mut dialog =
PresetsDialog { id: dialog_id(KIND), selected: selected.to_owned(), presets: Vec::new(), names: Vec::new(), action: None, open: true };
let mut dialog = PresetsDialog {
id: dialog_id(KIND),
selected: selected.to_owned(),
presets: Vec::new(),
names: Vec::new(),
action: None,
import_owner: Arc::new(()),
open: true,
};
dialog.set_presets(presets);
dialog
}
@@ -296,13 +307,18 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul
select(app, &next);
}
Action::Import => {
let Some(owner) = with_dialog(app, |manager| Arc::clone(&manager.import_owner)) else { return Ok(()) };
let request = PickRequest::open(KIND).filter("Perspective grid presets", PRESET_EXTS);
file_asks::ask(app, request, Owner::Free, |app, picked| {
file_asks::ask(app, request, Owner::Free, move |app, picked| {
let mut params = file_asks::open_params(&picked).ok_or("cancelled")?;
params.remove("name");
let r = app.run("perspective.presets.import", Value::Object(params))?;
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
select(app, first);
with_dialog(app, |manager| {
if Arc::ptr_eq(&manager.import_owner, &owner) {
manager.selected = first.to_owned();
}
});
}
Ok(r)
});
+85 -19
View File
@@ -4,8 +4,8 @@
//! Preview shows the proof on the canvas while the dialog is open; OK sets the proof setup and
//! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. Save…
//! writes the dialog's settings to a proof setup file (`view.proofSetup.save`) and Load… reads one
//! into the dialog (`view.proofSetup.read`). Both are desktop only. Their pickers start in the
//! Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below
//! into the dialog (`view.proofSetup.read`). The browser reads picked bytes and downloads a copy
//! when saving. Desktop pickers start in the Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below
//! Customize… ([`saved_items`]): Save… makes the folder when it may be written, and Load…'s picker
//! starts in its own default folder until the folder exists.
//!
@@ -116,15 +116,10 @@ fn rgb_device(device: &str) -> bool {
/// The dialog over the host's values, made again every pass.
fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
// The web has no folder to keep setups in.
let footer = if cfg!(target_arch = "wasm32") {
Vec::new()
} else {
vec![
(SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)),
(LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)),
]
};
let footer = vec![
(SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)),
(LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)),
];
ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews(true).extra_buttons(footer)
}
@@ -297,6 +292,29 @@ fn act(app: &mut VectorcraftApp, id: DialogId, fields: &DialogFields, action: &s
/// Save…: the dialog's settings go to the picked file, and the menu lists the saved setups again.
fn save(app: &mut VectorcraftApp, fields: &DialogFields) {
let mut request =
PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT);
let mut p = params(fields);
if let Some(o) = p.as_object_mut() {
o.remove("proof");
}
if app.host.files().browser_saves() {
match proof_file::draft_bytes(&p) {
Ok(bytes) => {
crate::file_asks::save(app, request, bytes, Owner::Free, |app, picked| {
match picked {
Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())),
Picked::Downloaded(name) => app.status(format!("Saved {name}")),
Picked::Failed(error) => return Err(error),
_ => {}
}
Ok(Value::Null)
});
}
Err(e) => app.status(e.to_string()),
}
return;
}
// The picker opens in the folder, made for it when it may be written. [`list_saved`] removes
// it again when the picker closes without a file in it.
let dir = app.session.proof_setup_dir().map(Path::to_path_buf);
@@ -307,15 +325,9 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) {
if made.is_some() {
saved().made = made;
}
let mut request =
PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT);
if let Some(dir) = dir {
request = request.directory(dir);
}
let mut p = params(fields);
if let Some(o) = p.as_object_mut() {
o.remove("proof");
}
ask(app, request, Owner::Free, move |app, picked| {
let Picked::Saved { path, .. } = picked else { return Ok(Value::Null) };
let path = path.to_string_lossy().into_owned();
@@ -343,8 +355,16 @@ fn load(app: &mut VectorcraftApp, id: DialogId) {
&& app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
};
ask_while(app, request, Owner::Free, is_live, move |app, picked| {
let Some(path) = picked.first_path() else { return Ok(Value::Null) };
let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?;
let r = match picked {
Picked::Contents(files) => {
let Some((name, bytes)) = files.into_iter().next() else { return Ok(Value::Null) };
proof_file::draft_fields(&bytes, &name).map_err(|e| e.to_string())?
}
other => {
let Some(path) = other.first_path() else { return Ok(Value::Null) };
app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?
}
};
let fields = [
("device", "target"),
("intent", "intent"),
@@ -817,6 +837,52 @@ mod tests {
assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation));
}
#[test]
fn a_browser_pick_loads_a_proof_setup_into_the_draft() {
let _view = DefaultProofView::new();
let (mut app, ctx) = app();
let files = scripted(&mut app, ScriptedFiles::held().in_browser());
app.run("ui.proofSetupDialog", json!({})).unwrap();
set(&mut app, &ctx, "preview", json!(false));
let before = proof::view();
let mut source = before.setup.clone();
source.intent = Intent::Saturation;
press(&mut app, &ctx, LOAD_BUTTON);
files.answer(Picked::Contents(vec![("browser.vcproof".into(), proof_file::encode(&source))]));
crate::file_asks::poll(&mut app);
assert_eq!(values(&app)["intent"], "saturation");
assert_eq!(proof::view(), before);
press(&mut app, &ctx, LOAD_BUTTON);
files.answer(Picked::Contents(vec![("oversized.vcproof".into(), vec![b' '; proof_file::MAX_FILE + 1])]));
crate::file_asks::poll(&mut app);
assert!(app.ui.status.contains("larger than"));
assert_eq!(values(&app)["intent"], "saturation");
assert_eq!(proof::view(), before);
}
#[test]
fn saving_a_browser_proof_setup_gives_the_file_service_the_draft_bytes() {
let _view = DefaultProofView::new();
let (mut app, ctx) = app();
let files = scripted(&mut app, ScriptedFiles::held().in_browser());
app.run("ui.proofSetupDialog", json!({})).unwrap();
for (k, v) in [("intent", json!("saturation")), ("preview", json!(false))] {
set(&mut app, &ctx, k, v);
}
let before = proof::view();
let dir = vectorcraft_testkit::TempDir::new("proof-setup-browser-save");
let path = dir.join("draft.vcproof");
press(&mut app, &ctx, SAVE);
files.answer(Picked::Saved { path: path.clone(), file_type: None });
crate::file_asks::poll(&mut app);
let bytes = files.file(&path).expect("the browser file service receives the draft bytes");
assert_eq!(proof_file::parse(&bytes).unwrap().intent, Intent::Saturation);
assert_eq!(proof::view(), before);
assert_eq!(values(&app)["intent"], "saturation");
assert!(!path.exists(), "the browser save does not write through the native path");
}
#[test]
fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() {
let _view = DefaultProofView::new();
+71 -7
View File
@@ -6,7 +6,7 @@
//! dialog opened on are held by its OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use serde_json::{Value, json};
use super::host::open_held;
@@ -15,12 +15,13 @@ use crate::VectorcraftApp;
/// The command Rename answers for; the key of its dialog.
pub(crate) const CMD: &str = "artboard.rename";
const TARGET: &str = "__target";
/// `artboard.rename` for the selected artboards: opens the dialog on the one artboard's name, or on an empty name
/// for several.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?;
let document = st.uid;
let selected: Vec<_> =
crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect();
let name = match selected.as_slice() {
@@ -30,21 +31,34 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let artboards: Vec<_> = selected.iter().map(|board| board.id).collect();
let mut fields = DialogFields::new();
fields.set("name", name);
// The held answer carries the target of the draft being confirmed, including after reopening.
fields.set(TARGET, FieldValue::Json(json!({"document": st.uid, "reverts": st.reverts, "artboards": artboards})));
let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| {
let rows = vec![Param::new("name", tl!("Name:"), ParamKind::text(""))];
ParamDialog::command(CMD, tl!("Rename"), rows).values(Bind::bound(fields))
});
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| {
let ok = |app: &mut VectorcraftApp, result: &ParamResult| {
let name = result.fields.text("name").unwrap_or_default();
// An empty name keeps the names as they are, as the Artboards panel's name field does.
if name.trim().is_empty() {
return Ok(());
}
let st =
app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?;
let indices = artboards
let Some(FieldValue::Json(target)) = result.fields.get(TARGET) else {
return Err(tl!("The artboards being renamed could not be found.").to_owned());
};
let st = app
.session
.active()
.filter(|st| Some(st.uid) == target["document"].as_u64())
.ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?;
if Some(st.reverts) != target["reverts"].as_u64() {
return Err(tl!("The document was reverted. Reopen the dialog to rename artboards.").to_owned());
}
let indices = target["artboards"]
.as_array()
.ok_or_else(|| tl!("The artboards being renamed could not be found.").to_owned())?
.iter()
.map(|id| st.doc.artboards.iter().position(|board| board.id == *id))
.map(|id| st.doc.artboards.iter().position(|board| Some(u64::from(board.id)) == id.as_u64()))
.collect::<Option<Vec<_>>>()
.ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?;
if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) {
@@ -61,6 +75,14 @@ mod tests {
use super::*;
use vectorcraft_engine::Session;
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
@@ -143,6 +165,48 @@ mod tests {
assert!(!app.any_dialog_open());
}
#[test]
fn rename_cannot_use_a_draft_opened_before_file_revert() {
let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-rename-artboards-revert-{}.vectorcraft", std::process::id())));
let services = crate::Services {
read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))),
write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))),
..Default::default()
};
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
app.select_tool("artboard");
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
let active = app.session.active().unwrap();
let (document, reverts, artboard) = (active.uid, active.reverts, active.doc.artboards[0].id);
app.run(CMD, json!({"indices": [0], "name": "Temporary"})).unwrap();
open(&mut app).unwrap();
let (id, fields) = open_rename(&app);
assert_eq!(fields["name"], "Temporary");
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| {
host.set_json_field(&ctx, id, "name", json!("Stale")).unwrap();
assert!(!host.confirm_by_id(&ctx, id));
});
app.run("file.revert", json!({"confirmed": true})).unwrap();
let active = app.session.active().unwrap();
assert_eq!((active.uid, active.reverts, active.doc.artboards[0].id), (document, reverts + 1, artboard));
let undo = active.history.undo.len();
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"], "an older draft cannot rename the reloaded board");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))));
app.session.set_tool_option("selected", &json!([0, 2]));
open(&mut app).unwrap();
rename(&mut app, "Page");
assert_eq!(names(&app), ["Page-1", "Artboard 2", "Page-2"]);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() {
let mut app = app();
+101 -10
View File
@@ -138,6 +138,7 @@ impl ItemSource<usize> for Shown<'_> {}
pub(crate) struct SavedNamesDialog {
id: DialogId,
document: u64,
reverts: u64,
names: SavedNames,
draft: NamesDraft,
/// The picked row, by its index in the draft; one at most.
@@ -148,10 +149,10 @@ pub(crate) struct SavedNamesDialog {
impl SavedNamesDialog {
/// The dialog over `list`, with the first name picked.
fn new(document: u64, names: SavedNames, list: Vec<String>) -> Self {
fn new(document: u64, reverts: u64, names: SavedNames, list: Vec<String>) -> Self {
let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) };
let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect();
SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() }
SavedNamesDialog { id: id_of(names.kind), document, reverts, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() }
}
/// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for
@@ -327,9 +328,10 @@ impl StackDialog for SavedNamesDialog {
/// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them).
pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec<String>) -> Result<(), String> {
list.truncate(names.max);
let document = app.session.active().ok_or("no document open")?.uid;
let active = app.session.active().ok_or("no document open")?;
let (document, reverts) = (active.uid, active.reverts);
let dialogs = app.dialogs().ok_or("no window")?;
dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list)));
dialogs.with(|host| host.open(SavedNamesDialog::new(document, reverts, names, list)));
Ok(())
}
@@ -343,15 +345,15 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
.filter_map(|open| {
let dialog = host.get_mut_by_id::<SavedNamesDialog>(open.id)?;
let edits = dialog.held.take()?;
Some((open.id, dialog.document, dialog.names.command, edits))
Some((open.id, dialog.document, dialog.reverts, dialog.names.command, edits))
})
.collect()
});
for (id, document, command, edits) in filed {
let outcome = if app.session.active().is_some_and(|active| active.uid == document) {
app.run(command, json!({ "edits": edits }))
} else {
Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned())
for (id, document, reverts, command, edits) in filed {
let outcome = match app.session.active().filter(|active| active.uid == document) {
Some(active) if active.reverts != reverts => Err(tl!("The document was reverted. Reopen the dialog to edit saved names.").to_owned()),
Some(_) => app.run(command, json!({ "edits": edits })),
None => Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()),
};
if let Err(reason) = &outcome {
app.status(reason.clone());
@@ -368,6 +370,95 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
mod tests {
use super::*;
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn saved_selection_draft_does_not_edit_a_reverted_drawing() {
exercise_reverted_draft(false);
}
#[test]
fn saved_views_draft_does_not_edit_a_reverted_drawing() {
exercise_reverted_draft(true);
}
fn exercise_reverted_draft(is_view: bool) {
let path = SavedFile(std::env::temp_dir().join(format!("vc-saved-names-revert-{}-{is_view}.vectorcraft", std::process::id())));
let services = crate::Services {
read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))),
write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))),
..Default::default()
};
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services));
let add_shape = |app: &mut VectorcraftApp, x| {
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap();
};
let names = |app: &mut VectorcraftApp| {
if is_view {
let views = &app.session.active().unwrap().doc.views;
json!(views.iter().map(|view| &view.name).collect::<Vec<_>>())
} else {
app.run("select.savedList", json!({})).unwrap()
}
};
let open = |app: &mut VectorcraftApp| {
if is_view {
crate::dialogs::edit_views::open(app).unwrap();
crate::dialogs::edit_views::KIND
} else {
crate::dialogs::edit_selection::open(app).unwrap();
crate::dialogs::edit_selection::KIND
}
};
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
add_shape(&mut app, 10);
for name in ["Shared", "Spare"] {
app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap();
}
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
add_shape(&mut app, 40);
let old = app.session.active().unwrap();
let (document, reverts) = (old.uid, old.reverts);
let kind = open(&mut app);
let id = id_of(kind);
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| {
host.set_json_field(&ctx, id, "name0", json!("Stale")).unwrap();
host.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap();
assert!(!host.confirm_by_id(&ctx, id));
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
});
app.run("file.revert", json!({"confirmed": true})).unwrap();
let active = app.session.active().unwrap();
assert_eq!((active.uid, active.reverts), (document, reverts + 1), "Revert preserves the tab's UID");
assert_eq!(names(&mut app), json!(["Shared", "Spare"]));
let undo = app.session.active().unwrap().history.undo.len();
pump(&mut app, &ctx);
assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "{kind} cannot apply its old draft to the reloaded drawing");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
assert!(dialogs.with(|host| host.cancel_by_id(&ctx, id)));
assert_eq!(open(&mut app), kind);
dialogs.with(|host| {
host.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap();
host.confirm_by_id(&ctx, id);
});
pump(&mut app, &ctx);
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Accepted)));
assert_eq!(names(&mut app), json!(["Revised", "Spare"]));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn saved_names_edits_stay_with_their_document() {
for is_view in [false, true] {
+43 -18
View File
@@ -14,7 +14,7 @@ use std::sync::LazyLock;
use craft::behavior::{ColumnWidth, IconId};
use craft::egui::{Response, Ui};
use craft::host::{PickRequest, Picked};
use craft::host::PickRequest;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::overlay::Trigger;
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
@@ -178,26 +178,16 @@ pub(crate) fn save_preset_row(ui: &mut Ui, fields: &mut Map<String, Value>) -> O
}
/// Import Preset…: the presets of a picked file are added to the saved ones; `then` gets the names
/// added, or the error (`cancelled` when no file was picked). On the web the picked file arrives
/// with its bytes and imports through `io::open_bytes`, which reports no names.
/// added, or the error (`cancelled` when no file was picked). Browser picks use the file's contents.
pub(crate) fn import_presets(app: &mut VectorcraftApp, then: impl FnOnce(&mut VectorcraftApp, Result<Vec<String>, String>) + 'static) {
let request = PickRequest::open("export-presets").filter("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS);
// `then` reports its own result, so the continuation never fails (a failure would reach the status line twice).
let _ = file_asks::ask(app, request, Owner::Free, move |app, picked| {
let result: Result<Vec<String>, String> = match picked {
Picked::Contents(files) => match files.first() {
Some((name, bytes)) => io::open_bytes(app, name, bytes, None).map(|_| Vec::new()),
None => Err("cancelled".into()),
},
other => match other.first_path() {
Some(path) => {
let path = path.to_string_lossy().into_owned();
io::import_presets(app, "document.exportPresets.import", io::EXPORT_PRESETS, json!({ "path": path }))
.map(|r| r["imported"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect())
}
None => Err("cancelled".into()),
},
};
let result = file_asks::open_params(&picked).ok_or_else(|| "cancelled".to_owned()).and_then(|mut params| {
params.remove("name");
io::import_presets(app, "document.exportPresets.import", io::EXPORT_PRESETS, Value::Object(params))
.map(|r| r["imported"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect())
});
then(app, result);
Ok(Value::Null)
});
@@ -488,7 +478,6 @@ pub(crate) fn rows(ui: &mut Ui, fields: &mut Map<String, Value>, mut menu: Optio
}
shown.output
}
/// The format Format Settings opens on for format rows `rows`: the first row's format when it has
/// settings of its own, else PNG. Row spellings (`jpeg`, `tif`) give the canonical id.
pub(crate) fn settings_format(rows: &[Value]) -> &'static str {
@@ -561,3 +550,39 @@ pub(crate) fn settings(ui: &mut Ui, fields: &mut Map<String, Value>, presets: &[
}
shown.output
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_browser_preset_picker_routes_by_content_without_opening_drawings() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.services.download = Some(Box::new(|_, _| Ok(())));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("document.exportPresets.save", json!({"name": "Fleet", "settings": {"formats": [{"format": "png"}]}})).unwrap();
let export = app.run("document.exportPresets.export", json!({"names": ["Fleet"]})).unwrap();
let bytes = export["data"].as_str().unwrap().as_bytes();
app.run("document.exportPresets.delete", json!({"name": "Fleet"})).unwrap();
let document = app.session.active().unwrap().uid;
let picker = crate::tests::picks::scripted(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
let picked = |app: &mut VectorcraftApp, name: &str, bytes: &[u8]| {
let answer = Rc::new(Cell::new(None));
let report = Rc::clone(&answer);
import_presets(app, move |_, result| report.set(Some(result)));
picker.answer_contents(&[(name, bytes)]);
crate::tests::picks::poll(app, &ctx);
answer.take().unwrap()
};
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="30" height="20"><rect width="10" height="10"/></svg>"#;
let error = picked(&mut app, "drawing.svg", svg);
assert_eq!(app.session.documents().len(), 1, "Import Preset must not open a drawing");
assert!(error.unwrap_err().contains("not an export presets file"));
assert_eq!(picked(&mut app, "different-extension.svg", bytes), Ok(vec!["Fleet".to_string()]));
assert_eq!(app.ui.status, "Imported export presets: Fleet");
assert_eq!(app.session.active().unwrap().uid, document);
}
}
+12 -2
View File
@@ -29,6 +29,7 @@
//! are not the dialog's default. `selectDlg` opens the host's folder picker in its own folder.
use std::path::Path;
use std::sync::Arc;
use craft::host::{PickRequest, Picked};
use craft::theme::variant::Tone;
@@ -276,6 +277,7 @@ impl StackDialog for ScriptNotice {
/// The dialog of a script's file dialog call: what the run asked for, read from the run's own
/// request when the dialog opens, so no field of the dialog changes what the person reads.
pub(crate) struct ScriptFiles {
opening: Arc<()>,
kind: PickerKind,
prompt: String,
can_always: bool,
@@ -290,6 +292,7 @@ pub(crate) struct ScriptFiles {
impl ScriptFiles {
fn new(p: ScriptPicker) -> Self {
Self {
opening: Arc::new(()),
kind: p.kind,
prompt: p.prompt,
can_always: p.can_always,
@@ -719,8 +722,11 @@ pub(crate) fn settle_files(app: &mut VectorcraftApp, result: DialogResult<FilesA
}
/// Asks for the files of the kind the running script asked for, starting at the script's file or
/// folder, with the script's file types; the answer goes to the open file dialog.
/// folder, with the script's file types; the answer goes to the dialog that opened the picker.
fn choose(app: &mut VectorcraftApp) {
let Some(opening) = with_host(app, |host, _| host.get::<ScriptFiles>().map(|dialog| Arc::clone(&dialog.opening))).flatten() else {
return;
};
let Some(p) = app.session.script_picker() else { return };
let several = p.multiple && p.kind == PickerKind::Open;
let mut request = match p.kind {
@@ -750,7 +756,11 @@ fn choose(app: &mut VectorcraftApp) {
file_asks::ask(app, request, Owner::Free, move |app, picked| {
let chosen = picked.paths().iter().map(|path| path.to_string_lossy().into_owned()).collect();
let automated = app.file_asks.automated();
with_host(app, |host, _| host.get_mut::<ScriptFiles>().map(|dialog| dialog.add(chosen, several, automated)));
with_host(app, |host, _| {
if let Some(dialog) = host.get_mut::<ScriptFiles>().filter(|dialog| Arc::ptr_eq(&dialog.opening, &opening)) {
dialog.add(chosen, several, automated);
}
});
Ok(Value::Null)
});
}
@@ -311,6 +311,33 @@ fn the_presets_manager_imports_browser_contents_and_desktop_paths() {
assert_eq!(field(&app, "selected"), json!("Desktop"));
}
#[test]
fn a_late_perspective_import_leaves_the_reopened_managers_selection_alone() {
use super::perspective_presets::{self, Action, KIND};
use vectorcraft_engine::cmd::perspgrid::PRESET_FORMAT;
let mut app = app();
let picker = crate::tests_picks::scripted(&mut app);
let ctx = window(&app);
let preset = |name: &str| json!({"format": PRESET_FORMAT, "presets": [{"name": name}]}).to_string();
app.run("ui.perspectivePresetsDialog", json!({})).unwrap();
perspective_presets::run(&mut app, Action::Import, "[1P-Normal View]").unwrap();
assert_eq!(picker.requests().len(), 1);
assert!(host(&app, |h| h.cancel_by_id(&ctx, dialog_id(KIND))));
let selected = "[2P-Normal View]";
app.run("ui.perspectivePresetsDialog", json!({"selected": selected})).unwrap();
picker.answer_contents(&[("First.vcperspective", preset("First").as_bytes())]);
crate::tests_picks::poll(&mut app, &ctx);
assert!(app.session.perspective_preset("First").is_some(), "the file still imports into saved presets");
assert_eq!(field(&app, "selected"), json!(selected), "the reopened manager keeps its choice");
perspective_presets::run(&mut app, Action::Import, selected).unwrap();
picker.answer_contents(&[("Second.vcperspective", preset("Second").as_bytes())]);
crate::tests_picks::poll(&mut app, &ctx);
assert!(app.session.perspective_preset("Second").is_some());
assert_eq!(field(&app, "selected"), json!("Second"), "the current manager selects its own import");
}
#[test]
fn perspective_preset_menus_list_the_views_of_each_type() {
let app = app();
+10 -9
View File
@@ -354,8 +354,8 @@ impl Target {
struct Form {
/// The path whose stroke carries the points.
path: u64,
/// The uid of the document the dialog opened in.
doc: Option<u64>,
/// The document's UID and revert count when the dialog opened.
doc: Option<(u64, u64)>,
/// Adjust Adjoining Width Points.
adjust: bool,
target: Target,
@@ -684,8 +684,9 @@ impl StackDialog for WidthPointDialog {
/// Adjoining adjustment defaults to false. Either half of a discontinuous point opens both.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let id = p.get("id").and_then(Value::as_u64).ok_or("give the path `id`")?;
let doc = &app.session.active().ok_or("no document")?.doc;
let id = vectorcraft_tools::distort::stroke_owner(doc, NodeId(id)).0;
let active = app.session.active().ok_or("no document")?;
let document = (active.uid, active.reverts);
let id = vectorcraft_tools::distort::stroke_owner(&active.doc, NodeId(id)).0;
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
let mut index = match p.get("index").filter(|v| !v.is_null()) {
Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("no such width point")?),
@@ -695,7 +696,6 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
return Err("give only one of `index`, `indices` and `t`".into());
}
let adjust = p.get("adjustAdjoining").and_then(Value::as_bool).unwrap_or(false);
let uid = app.session.active().map(|st| st.uid);
let mut several = None;
if let Some(indices) = p.get("indices").filter(|v| !v.is_null()) {
match target(app, id, indices)? {
@@ -711,7 +711,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
}
None => one_point(app, id, index, p)?,
};
let dialog = WidthPointDialog::new(Form { path: id, doc: uid, adjust, target }, stroke_lengths(app));
let dialog = WidthPointDialog::new(Form { path: id, doc: Some(document), adjust, target }, stroke_lengths(app));
app.dialogs().ok_or("no window")?.with(|host| host.open(dialog));
Ok(Value::Null)
}
@@ -749,10 +749,11 @@ fn one_point(app: &VectorcraftApp, id: u64, index: Option<usize>, p: &Value) ->
Ok(Target::One { index, t, at, sides: Sides::of(l, r), out, single: Single::None })
}
/// Whether the document the dialog opened in (`doc`) is still the active one.
fn same_document(app: &VectorcraftApp, doc: Option<u64>) -> Result<(), String> {
/// Whether the document the dialog opened in is active and has not been reloaded by Revert.
fn same_document(app: &VectorcraftApp, doc: Option<(u64, u64)>) -> Result<(), String> {
match (doc, app.session.active()) {
(Some(uid), Some(st)) if st.uid == uid => Ok(()),
(Some((uid, reverts)), Some(st)) if (st.uid, st.reverts) == (uid, reverts) => Ok(()),
(Some((uid, _)), Some(st)) if st.uid == uid => Err(tl!("The document was reverted. Reopen Width Point Edit.").to_owned()),
_ => Err("no such width point".into()),
}
}
@@ -851,6 +851,57 @@ fn second_document(app: &mut VectorcraftApp, id: u64) {
app.run("stroke.widthProfile.set", json!({"ids": [other], "points": points})).unwrap();
}
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn exercise_reverted_point(prospective: bool) {
let (mut app, id) = if prospective { creation_app() } else { app() };
app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-width-point-revert-{}-{prospective}.vectorcraft", std::process::id())));
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
let saved = points(&app, id);
let state = app.session.active().unwrap();
let (document, reverts) = (state.uid, state.reverts);
app.run("shape.rectangle", json!({"x": 30, "y": 30, "width": 10, "height": 10})).unwrap();
let target = if prospective { json!({"id": id, "t": 0.4}) } else { json!({"id": id, "index": 1}) };
app.run("ui.widthPointEdit", target.clone()).unwrap();
set(&app, "side1", json!(7));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.reverts), (document, reverts + 1));
assert_eq!(points(&app, id), saved, "the reloaded path still looks like the original target");
let undo = state.history.undo.len();
let accepted = ok(&mut app);
assert_eq!(points(&app, id), saved, "the old Width Point draft leaves the reloaded path alone");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(accepted.is_err() && is_open(&app));
cancel(&app);
app.run("ui.widthPointEdit", target).unwrap();
set(&app, "side1", json!(7));
ok(&mut app).unwrap();
assert_ne!(points(&app, id), saved);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn existing_width_point_draft_cannot_edit_a_reverted_path() {
exercise_reverted_point(false);
}
#[test]
fn prospective_width_point_draft_cannot_edit_a_reverted_path() {
exercise_reverted_point(true);
}
#[test]
fn ok_and_delete_act_only_in_the_document_the_dialog_opened_in() {
for opened in [json!({"indices": [1, 3]}), json!({"index": 2})] {
+20 -4
View File
@@ -646,13 +646,25 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va
}
/// File → New from Template…: a template (or any readable file) as a new untitled document. Without
/// a path the open dialog starts in the Templates folder. On the web the browser's file picker
/// opens it (`.vctemplate`, `.ait` and template files open untitled there too).
/// a path the open dialog starts in the Templates folder. The browser supplies the picked file's
/// name and bytes for the same template loader.
pub fn new_from_template(app: &mut VectorcraftApp, path: Option<String>) -> Result<Value, String> {
let Some(path) = path else {
let filters = std::iter::once(("Templates", TEMPLATE_EXTS)).chain(fileio::builtin_open_filters());
let request = open_request("template", fileio::templates_dialog_folder(&app.session.prefs), filters);
return ask_open(app, request, Owner::Free, new_from_path);
return Ok(file_asks::ask(app, request, Owner::Free, |app, picked| match picked {
Picked::Contents(files) => {
let (name, bytes) = files.into_iter().next().ok_or("cancelled")?;
if let Err(error) = open_template(app, &name, &bytes, None) {
report_open_error(app, &name, &error);
}
Ok(Value::Null)
}
picked => {
let path = picked.first_path().ok_or("cancelled")?;
new_from_path(app, path.to_string_lossy().into_owned())
}
}));
};
new_from_path(app, path)
}
@@ -660,7 +672,11 @@ pub fn new_from_template(app: &mut VectorcraftApp, path: Option<String>) -> Resu
/// [`new_from_template`] for the file at `path`.
fn new_from_path(app: &mut VectorcraftApp, path: String) -> Result<Value, String> {
let bytes = read(app, &path)?;
let r = fileio::open_template(&mut app.session, &path, &bytes, Some(&path)).map_err(|e| e.to_string())?;
open_template(app, &path, &bytes, Some(&path))
}
fn open_template(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<&str>) -> Result<Value, String> {
let r = fileio::open_template(&mut app.session, name, bytes, path).map_err(|e| e.to_string())?;
opened(app, &r);
Ok(r)
}
+17
View File
@@ -1,5 +1,6 @@
//! What panels drag onto art and onto each other.
use serde_json::{Value, json};
use vectorcraft_color::Paint;
/// What panels drag onto art and onto each other. One payload type, so the canvas has one drop
@@ -70,4 +71,20 @@ impl PanelDrag {
_ => None,
}
}
/// A named process swatch follows the source drawing's swatch. In another drawing its
/// captured process color applies without using a same-name swatch there.
pub(crate) fn paint_drop_params(&self, destination: Option<u64>) -> Option<Value> {
let Self::Paint { paint, params, rows, .. } = self else { return None };
if params.is_null() {
return None;
}
if let Some(rows) = rows.as_ref().filter(|rows| rows.unlinked_process_color)
&& destination.is_some_and(|uid| uid != rows.document)
&& let Some(color) = paint.color()
{
return Some(json!({"color": crate::panels::color_json(&color), "keepModel": true}));
}
Some(params.clone())
}
}
+29 -2
View File
@@ -790,9 +790,9 @@ fn takes_drop(mixed: (bool, bool), well: Well, drag: &PanelDrag) -> bool {
/// Paints the fill (the primary well) or the stroke with the paint `drag` carries.
fn drop_paint(app: &mut VectorcraftApp, well: Well, drag: &PanelDrag) {
if let PanelDrag::Paint { params, .. } = drag {
if let Some(params) = drag.paint_drop_params(app.session.active().map(|st| st.uid)) {
let cmd = if well == Well::Primary { "paint.setFill" } else { "paint.setStroke" };
app.run(cmd, params.clone()).ok();
app.run(cmd, params).ok();
}
}
@@ -1085,6 +1085,33 @@ mod tests {
assert_eq!(current_paints(&app).0.color().map(|c| c.to_hex()), Some("#00ff00".into()));
}
#[test]
fn proxy_drops_keep_the_dragged_process_color_after_switching_documents() {
use crate::panel_drag::SwatchRows;
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let name = "Shared Swatch";
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
let source = app.session.active().unwrap();
let paint = source.doc.swatch(name).unwrap().paint.clone();
let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true };
let drag = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None };
app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap();
drop_paint(&mut app, Well::Primary, &drag);
assert_eq!(current_paints(&app).0, app.session.active().unwrap().doc.swatch(name).unwrap().paint);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap();
let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
drop_paint(&mut app, Well::Primary, &drag);
drop_paint(&mut app, Well::Secondary, &drag);
assert_eq!(current_paints(&app), (paint.clone(), paint));
assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination);
}
#[test]
fn paint_params_roundtrip_shapes() {
assert_eq!(paint_params(&Paint::None), json!({"none": true}));
+45
View File
@@ -170,6 +170,51 @@ fn new_from_template_takes_bytes_from_agents() {
assert_eq!(app.session.active().unwrap().path, None);
}
#[test]
fn new_from_template_opens_browser_bytes_and_desktop_paths_as_untitled_copies() {
let folder = dir("new-from-template-pick");
let name = "Source Drawing.svg";
let bytes = br#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="60"><rect width="20" height="10"/></svg>"#;
let path = folder.join(name);
std::fs::write(&path, bytes).unwrap();
for browser in [false, true] {
let mut app = app();
if browser {
app.services.download = Some(Box::new(|_, _| Ok(())));
}
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
rect(&mut app);
let source = app.session.active().unwrap();
let source_uid = source.uid;
let source_undo = source.history.undo.len();
let picker = scripted(&mut app);
picks::asks(&mut app, "file.newFromTemplate");
assert_eq!(picker.requests()[0].purpose, "template");
if browser {
picker.answer_contents(&[(name, bytes)]);
} else {
picker.answer(&[path.to_str().unwrap()]);
}
poll(&mut app);
let opened = app.session.active().unwrap();
assert!(opened.title().starts_with("Untitled-"), "browser={browser}: the template copy was named {:?}", opened.title());
assert_eq!((app.session.documents().len(), app.views.len()), (2, 2));
assert_eq!((opened.path.as_deref(), opened.history.undo.len()), (None, 0));
assert_eq!(opened.doc.layers[0].children().unwrap().len(), 1);
let source = &app.session.documents()[0];
assert_eq!((source.uid, source.history.undo.len()), (source_uid, source_undo));
if browser {
picks::asks(&mut app, "file.newFromTemplate");
picker.answer_contents(&[(name, b"not a drawing")]);
poll(&mut app);
assert_eq!(app.session.documents().len(), 2, "an invalid template opens no document");
assert!(app.ui.status.contains("Couldn't open Source Drawing.svg"), "{}", app.ui.status);
}
}
let _ = std::fs::remove_dir_all(folder);
}
#[test]
fn show_in_folder_needs_a_saved_document_and_a_file_manager() {
let shown = Rc::new(RefCell::new(vec![]));
+24
View File
@@ -70,6 +70,30 @@ fn allow_once(app: &mut VectorcraftApp) {
script_run::settle_files(app, DialogResult::Ok(FilesAnswer { answer: "once", paths, left_out: false, automated: false }));
}
#[test]
fn a_script_file_reply_does_not_populate_a_reopened_dialog() {
let mut app = app();
let picker = scripted(&mut app);
app.session.prefs.show_external_script_warning = false;
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "File.openDialog('Choose');"})).unwrap().unwrap();
script_runs::poll(&mut app);
script_run::with_host(&app, |host, _| host.get_mut::<ScriptFiles>().unwrap().choose = true).unwrap();
pump(&mut app);
assert_eq!(picker.requests().len(), 1);
script_run::forget::<ScriptFiles>(&app);
script_run::open_picker(&app, app.session.script_picker().unwrap());
let old_path = std::env::temp_dir().join("original-script-picker.txt");
picker.answer(&[&old_path.to_string_lossy()]);
let ctx = app.ui_ctx.clone().unwrap();
crate::tests::picks::poll(&mut app, &ctx);
assert!(picked(&app).is_empty(), "the old file chooser must not populate the new open dialog");
set(&app, PICKER_KIND, "answer", json!("deny")).unwrap();
assert!(confirm(&mut app, PICKER_KIND));
finish(&mut app);
}
#[test]
fn the_warning_comes_before_the_run_and_cancel_runs_nothing() {
let mut app = app();