mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 11:51:05 +01:00
Merge pull request #8937 from dotCooCoo/perf/docinfo-cached-rows-no-copy
Document Info: frames that fetch nothing reuse the cached rows without copying them
This commit is contained in:
3 files changed
+159
-6
No files matched your search
@@ -159,7 +159,7 @@ pub struct CanvasCache {
|
||||
/// The Navigator's view region, for (document uid, revision, View Artboard Contents Only).
|
||||
pub nav_region: Option<((u64, u64, bool), vectorcraft_geom::Rect)>,
|
||||
/// The Document Info panel's values, for (document uid, revision, selection only, options).
|
||||
pub doc_info: Option<((u64, u64, bool, Value), Value)>,
|
||||
pub doc_info: Option<DocInfoCache>,
|
||||
/// The Variables panel's rows, for the panel's key.
|
||||
pub(crate) variable_rows: Option<(crate::panels::variables::RowsKey, Rc<crate::panels::variables::Rows>)>,
|
||||
/// The Map Art surfaces of the 3D dialog's object.
|
||||
@@ -168,6 +168,10 @@ pub struct CanvasCache {
|
||||
pub(crate) palette: Option<(crate::palette::BuildKey, Arc<crate::palette::Built>)>,
|
||||
}
|
||||
|
||||
/// [`CanvasCache::doc_info`]: (document uid, revision, selection only, the Artboard tool's options)
|
||||
/// and the `document.info` result fetched for them.
|
||||
pub type DocInfoCache = ((u64, u64, bool, Value), Arc<Value>);
|
||||
|
||||
/// [`CanvasCache::map_surfaces`]: the surfaces and what they were computed for.
|
||||
pub type MapSurfacesCache = (MapSurfacesKey, Arc<Vec<vectorcraft_effects::MapSurface>>);
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
//! linked and embedded images, repeat objects), for the whole document or the selection only. The flyout picks one category (or all)
|
||||
//! and saves the text report (`docInfo.save`, the report File → Package writes too).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
@@ -39,8 +41,9 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: String) {
|
||||
}
|
||||
|
||||
/// `document.info` with its categories, fetched again only when the document, the scope or the
|
||||
/// artboards the Artboard tool has selected change.
|
||||
pub(crate) fn info(app: &mut VectorcraftApp) -> Option<Value> {
|
||||
/// artboards the Artboard tool has selected change. A frame that fetches nothing returns the stored
|
||||
/// result without copying it and stores nothing; a failed fetch leaves the stored result as it was.
|
||||
pub(crate) fn info(app: &mut VectorcraftApp) -> Option<Arc<Value>> {
|
||||
let selection_only = app.ui.doc_info.selection_only;
|
||||
let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null };
|
||||
let st = app.session.active()?;
|
||||
@@ -48,10 +51,10 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Option<Value> {
|
||||
if let Some((cached, info)) = &app.canvas.doc_info
|
||||
&& *cached == key
|
||||
{
|
||||
return Some(info.clone());
|
||||
return Some(Arc::clone(info));
|
||||
}
|
||||
let info = app.session.execute("document.info", &json!({ "selectionOnly": selection_only })).ok()?;
|
||||
app.canvas.doc_info = Some((key, info.clone()));
|
||||
let info = Arc::new(app.session.execute("document.info", &json!({ "selectionOnly": selection_only })).ok()?);
|
||||
app.canvas.doc_info = Some((key, Arc::clone(&info)));
|
||||
Some(info)
|
||||
}
|
||||
|
||||
@@ -642,6 +645,151 @@ mod tests {
|
||||
assert_eq!(custom.as_deref(), Some("#ff0000, #00ff00"));
|
||||
}
|
||||
|
||||
/// The by-value cache the panel kept before its result was shared, with the same key.
|
||||
type CopiedCache = Option<((u64, u64, bool, Value), Value)>;
|
||||
|
||||
/// `document.info` read as the panel read it before its result was shared: the stored result
|
||||
/// copied out by value on every call, kept in `cache` so it does not touch the panel's.
|
||||
fn copied_info(app: &mut VectorcraftApp, cache: &mut CopiedCache) -> Option<Value> {
|
||||
let selection_only = app.ui.doc_info.selection_only;
|
||||
let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null };
|
||||
let st = app.session.active()?;
|
||||
let key = (st.uid, st.revision, selection_only, artboard_tool);
|
||||
if let Some((cached, info)) = cache.as_ref()
|
||||
&& *cached == key
|
||||
{
|
||||
return Some(info.clone());
|
||||
}
|
||||
let info = app.session.execute("document.info", &json!({ "selectionOnly": selection_only })).ok()?;
|
||||
*cache = Some((key, info.clone()));
|
||||
Some(info)
|
||||
}
|
||||
|
||||
/// A frame that fetches nothing keeps the stored `document.info` result without a copy and
|
||||
/// shows the same rows; another document (at the same revision), an edit, Selection Only and
|
||||
/// the Artboard tool's options each store a new one, and a category does not. With no
|
||||
/// document nothing is fetched and the stored result stays as it was.
|
||||
#[test]
|
||||
fn frames_that_fetch_nothing_reuse_the_cached_rows() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let mut old: CopiedCache = None;
|
||||
let mut frame = |app: &mut VectorcraftApp| {
|
||||
let text = crate::tests_labels::painted_text(app, show);
|
||||
let Some((key, stored)) = app.canvas.doc_info.clone() else { panic!("nothing stored") };
|
||||
// The rows are the ones the by-value read gives for the same state.
|
||||
let has_doc = app.session.active().is_some();
|
||||
assert_eq!(has_doc.then(|| (*stored).clone()), copied_info(app, &mut old), "the same rows as before");
|
||||
(key, stored, text)
|
||||
};
|
||||
let (_, first, text) = frame(&mut app);
|
||||
assert!(text.contains("Color Mode") && text.contains("Artboard 1"), "{text}");
|
||||
let (_, same, again) = frame(&mut app);
|
||||
assert!(Arc::ptr_eq(&first, &same), "a frame that fetches nothing stores no new result");
|
||||
assert!(Arc::ptr_eq(&info(&mut app).unwrap(), &same), "the stored result is returned without a copy");
|
||||
assert_eq!(text, again);
|
||||
// Another document at the same revision.
|
||||
let revision = |app: &VectorcraftApp| app.session.active().map(|st| st.revision);
|
||||
let at = revision(&app);
|
||||
let before = app.session.active().map(|st| st.uid);
|
||||
app.session.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(revision(&app), at, "both documents are at the same revision");
|
||||
let (key, other, _) = frame(&mut app);
|
||||
assert!(!Arc::ptr_eq(&same, &other), "another document stores a new result");
|
||||
assert_ne!(Some(key.0), before);
|
||||
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
|
||||
let (_, edited, _) = frame(&mut app);
|
||||
assert!(!Arc::ptr_eq(&other, &edited), "an edit stores a new result");
|
||||
assert!(shown_rows(&edited, "objects").contains(&("Paths".into(), "1".into())), "{:?}", shown_rows(&edited, "objects"));
|
||||
run(&mut app, "ui.docInfo.selectionOnly", &json!({})).unwrap().unwrap();
|
||||
let (_, selection, text) = frame(&mut app);
|
||||
assert!(!Arc::ptr_eq(&edited, &selection), "Selection Only stores a new result");
|
||||
assert!(text.contains("(selection)"), "{text}");
|
||||
run(&mut app, "ui.docInfo.selectionOnly", &json!({})).unwrap().unwrap();
|
||||
run(&mut app, "ui.docInfo.category", &json!({"category": "objects"})).unwrap().unwrap();
|
||||
let (_, all, _) = frame(&mut app);
|
||||
let (_, category, _) = frame(&mut app);
|
||||
assert!(Arc::ptr_eq(&all, &category), "a category filters the stored result");
|
||||
run(&mut app, "ui.docInfo.category", &json!({"category": ""})).unwrap().unwrap();
|
||||
app.session.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
|
||||
let (_, two, _) = frame(&mut app);
|
||||
assert!(!Arc::ptr_eq(&category, &two), "a new artboard stores a new result");
|
||||
app.select_tool("artboard");
|
||||
app.session.set_tool_option("selected", &json!([0]));
|
||||
let (_, tool, _) = frame(&mut app);
|
||||
assert!(!Arc::ptr_eq(&two, &tool), "the Artboard tool stores a new result");
|
||||
let artboard_rows = |i: &Value| shown_rows(i, "document").iter().filter(|(l, _)| l == "Artboard").count();
|
||||
assert_eq!(artboard_rows(&tool), 1);
|
||||
app.session.set_tool_option("selected", &json!([0, 1]));
|
||||
let (_, picked, _) = frame(&mut app);
|
||||
assert!(!Arc::ptr_eq(&tool, &picked), "the Artboard tool's options store a new result");
|
||||
assert_eq!(artboard_rows(&picked), 2);
|
||||
let (_, kept, _) = frame(&mut app);
|
||||
assert!(Arc::ptr_eq(&picked, &kept));
|
||||
app.select_tool("selection");
|
||||
let (key, away, _) = frame(&mut app);
|
||||
assert!(!Arc::ptr_eq(&kept, &away), "another tool stores a new result");
|
||||
assert_eq!(key.3, Value::Null);
|
||||
// With no document the panel shows its empty state and keeps the stored result.
|
||||
app.session.execute("file.close", &json!({})).unwrap();
|
||||
app.session.execute("file.close", &json!({})).unwrap();
|
||||
let (_, closed, text) = frame(&mut app);
|
||||
assert!(Arc::ptr_eq(&away, &closed), "nothing is fetched or stored without a document");
|
||||
assert!(text.contains("No document"), "{text}");
|
||||
}
|
||||
|
||||
/// Time a frame's read of Document Info's result for a document with 5,000 objects painted
|
||||
/// with a gradient (a row each): by the by-value read before the result was shared
|
||||
/// ([`copied_info`]) and by [`info`]. Per run each side reads 2,000 times; the two sides
|
||||
/// alternate, and the median time per read of 7 runs is printed, as this thread's CPU time
|
||||
/// where the system reports it (Linux), else wall-clock time.
|
||||
/// Run with `cargo test --release -p vectorcraft-ui-egui --lib doc_info::tests::cached_rows_read_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; performance depends on machine load"]
|
||||
fn cached_rows_read_timing() {
|
||||
const OBJECTS: usize = 5_000;
|
||||
const READS: u32 = 2_000;
|
||||
fn thread_cpu_ns() -> Option<u128> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap();
|
||||
let mut ids = vec![];
|
||||
for i in 0..OBJECTS {
|
||||
let r = json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10});
|
||||
ids.push(app.session.execute("shape.rectangle", &r).unwrap()["id"].clone());
|
||||
}
|
||||
let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
app.session.execute("paint.setFill", &json!({"ids": ids, "gradient": ramp})).unwrap();
|
||||
let mut old: CopiedCache = None;
|
||||
let rows =
|
||||
info(&mut app).unwrap()["sections"].as_array().into_iter().flatten().map(|s| s["rows"].as_array().map_or(0, Vec::len)).sum::<usize>();
|
||||
assert_eq!(copied_info(&mut app, &mut old), info(&mut app).map(|i| (*i).clone()));
|
||||
let time = |app: &mut VectorcraftApp, f: &mut dyn FnMut(&mut VectorcraftApp) -> usize| {
|
||||
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..READS {
|
||||
assert!(f(app) > 0);
|
||||
}
|
||||
let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a);
|
||||
ns as f64 / f64::from(READS) / 1000.0
|
||||
};
|
||||
let sections = |i: &Value| i["sections"].as_array().map_or(0, Vec::len);
|
||||
let (mut copied, mut shared) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
copied.push(time(&mut app, &mut |app| copied_info(app, &mut old).map_or(0, |i| sections(&i))));
|
||||
shared.push(time(&mut app, &mut |app| info(app).map_or(0, |i| sections(&i))));
|
||||
}
|
||||
let median = |v: &mut Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" };
|
||||
eprintln!("{OBJECTS} objects, {rows} rows; {clock} per read, median of 7 runs");
|
||||
eprintln!("copied ({READS} reads a run): {:>10.3} us {copied:.3?}", median(&mut copied));
|
||||
eprintln!("shared ({READS} reads a run): {:>10.3} us {shared:.3?}", median(&mut shared));
|
||||
}
|
||||
|
||||
/// A Repeat object's counts take each language's plural forms, and a grid that draws fewer
|
||||
/// instances than its rows and columns give is followed by the number it draws.
|
||||
#[test]
|
||||
|
||||
@@ -2553,6 +2553,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs).
|
||||
When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs).
|
||||
The Links panel keeps its `links.list` rows and Link Info in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, the Show, Sort or Show DCS Transparency Interactions option changes, or the files are looked at again every 2 seconds, and, while an image is selected, when Link Info opens or closes or the first selected image changes. With 2,001 images a frame's cache step takes 0.2 µs instead of 1.79 ms, and with 10,001 images 0.2 µs instead of 12.2 ms (test build, median of 7 wall-clock runs of 1,000 frames, measured while other builds were running).
|
||||
The Document Info panel keeps its `document.info` result in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, Selection Only is turned on or off, or, while the Artboard tool is the current tool, its options change; choosing a category filters the stored result.
|
||||
In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s.
|
||||
In the web build, an edit while that view moves (a tool drag held near an edge of the canvas, which scrolls the view, or a wheel scroll during a drag) draws only the part of the last frame that the edit changed, at the view that frame was rendered for, and the frame stays drawn moved with the view until the view has been still for 0.2 s (#8688). The part of the canvas a pan uncovers shows the pasteboard and the artboards' paper until then, as for a pan without an edit. Edits that go on after the view stops don't start that 0.2 s again: the whole canvas renders 0.2 s after the view stopped. An edit that changes more than half of the frame, or one while more than the view and the document change, renders the whole canvas at once as before. Tests: `canvas::tests::without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still`, `canvas::tests::without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render`.
|
||||
An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429).
|
||||
|
||||
Reference in new issue
Block a user