Drawings: a view draws again only when what it shows changes (#4892 U1) (#12423)

A view's entry keeps what it was drawn from: each body of the world state by
its occurrences, name, reference mark and geometry key. A view drawn from a
world state that showed the same takes the new one and draws nothing, so a
sketch, or an edit taken back, projects no view.

A drawing closed keeps its views' lines in the sheet scene's provider, and
opened again starts from them: with nothing changed it draws no view, and with
the model changed its last lines show, out of date, until drawn. Dimensions are
read again. Only in memory, never saved; a deleted drawing's lines go with it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
CamWightandClaude Opus 5.5 authored and GitHub committed 2026-11-05 18:53:53 -05:00
1 parent 41dcdd1273
commit b4242e9844
3 files changed
+245 -17

No files matched your search

+91 -10
View File
@@ -17,10 +17,12 @@
//! brings one of them up to date, a short piece of work for the UI's tick: a view's projection with
//! its dimensions in the same swap, so new lines never show under old dimensions, or, once the views
//! are, the dimensions of one view that changed. A view moved across its sheet is moved, never
//! projected again, and an edited dimension is read again alone. The provider
//! evaluates no model either. Its cache is the
//! projected again, and an edited dimension is read again alone. A view drawn from a world state that
//! showed the same bodies, where and as they are now (`SourceKey`), is up to date: an appearance,
//! or an edit taken back, draws nothing. The provider evaluates no model either. Its cache is the
//! session's view state, beside the drawing: never saved, never an undo step, and dropped when its
//! drawing closes.
//! drawing closes, all but its views' lines (`drawing_scene_kept.rs`), which the drawing opened
//! again starts from.
//!
//! [`hit`] says which of a scene's objects is under a point of the sheet, the one rule for picking
//! there: the sheet page's hover and `drawing.scene.hit`.
@@ -54,6 +56,10 @@ use crate::drawing_view::{CHORD_MM, LineRequest, MIN_MODEL_CHORD_MM, Shown, Show
use crate::params::bad;
use crate::{EngineError, Result, Session};
#[path = "drawing_scene_kept.rs"]
mod kept;
use kept::{KeptLines, KeptView};
/// The command the sheet scene answers for, in its errors.
pub const CMD: &str = "drawing.scene";
@@ -605,20 +611,48 @@ pub struct Cache {
/// Numbers each view drawn and each read of dimensions, so a scene is assembled again only when
/// one of its views or dimensions was.
serial: u64,
/// The views' lines of each drawing closed, for when it opens again. They outlive the rest.
kept: KeptLines,
/// Views drawn, for tests: a move draws none.
#[cfg(test)]
projections: usize,
}
/// What a view's lines show: each body of the world state by the occurrences that place it, its
/// definition's body name, whether it is a reference, and its geometry where it stands. A world state
/// with the same draws the same lines, so an appearance, or an edit taken back, draws nothing. It
/// keys the whole set, not a view's own bodies: which bodies share a mesh, so the lines' last bits,
/// hangs on all of them ([`crate::mesh_lines`]).
#[derive(Debug, PartialEq)]
pub(crate) struct SourceKey(Vec<(Vec<u64>, String, bool, u64)>);
impl SourceKey {
/// None when there is nothing to show, or a body's geometry has no key: a view drawn from it
/// always draws again.
fn of(shown: &std::result::Result<ShownSet, Unmeasured>) -> Option<Arc<SourceKey>> {
let set = shown.as_ref().ok()?;
let body = |one: &Shown| Some((one.path.clone(), one.body.clone(), one.reference, set.body(one)?.geometry_key()?));
set.bodies.iter().map(body).collect::<Option<Vec<_>>>().map(|bodies| Arc::new(SourceKey(bodies)))
}
}
/// A view's last drawing, and what it was drawn from: the world state (held, so its address can't
/// be reused while it is compared) and the view as it drew.
/// be reused while it is compared), what that showed, and the view as it drew.
struct Entry {
state: Arc<ModelState>,
shows: Option<Arc<SourceKey>>,
view: ResolvedView,
drawn: Drawn,
serial: u64,
}
impl Entry {
/// Drawn from another world state than `state` that showed `now`.
fn shows_the_same(&self, state: &Arc<ModelState>, now: &SourceKey) -> bool {
!Arc::ptr_eq(&self.state, state) && self.shows.as_deref() == Some(now)
}
}
/// A dimension's last drawing, and what it was drawn from: its record, the world state, its view's
/// drawing (by serial, which holds its frame) and the drawing's units.
struct DimensionEntry {
@@ -655,6 +689,17 @@ struct Assembled {
}
impl Cache {
/// Drawing `drawing`'s lines kept when it closed, as its views' entries: from a world state that
/// has gone, so each is out of date until [`keep_what_shows_the_same`] finds it shows the same.
fn take_kept(&mut self, drawing: u64) {
let gone: Arc<ModelState> = Arc::default();
for (id, kept) in self.kept.take(drawing) {
self.serial += 1;
let entry = Entry { state: gone.clone(), shows: kept.shows, view: kept.view, drawn: kept.drawn, serial: self.serial };
self.views.insert(id, entry);
}
}
/// Whether view `id`, drawing as `view` now, was last drawn so, from `state`.
fn fresh(&self, id: u64, state: &Arc<ModelState>, view: &ResolvedView) -> bool {
self.views.get(&id).is_some_and(|e| Arc::ptr_eq(&e.state, state) && e.view == *view)
@@ -756,8 +801,13 @@ pub fn extract(s: &mut Session, sheet: u64) -> Result<SheetView> {
}
let record = sheet_of(&d, sheet)?;
let on = views_on(&d, sheet)?;
if cache.drawing != Some(d.id) {
cache.take_kept(d.id);
}
cache.drawing = Some(d.id);
cache.sheet = Some(sheet);
keep_what_shows_the_same(s, &on, &state);
let cache = &mut s.drawing_scenes;
let stale = on.iter().filter(|(id, view, _)| !cache.fresh(*id, &state, view)).map(|(id, ..)| *id).collect();
let stale_dimensions = cache.stale_dimensions(&d, &on, &state, &units).iter().map(|record| record.id).collect();
let inputs = cache.inputs(&d, record, &on);
@@ -791,6 +841,7 @@ pub fn step(s: &mut Session) -> bool {
let Ok(on) = views_on(&d, sheet) else { return false };
let Ok(state) = s.world_state() else { return false };
let units = s.doc.drawing_units(&d).to_string();
keep_what_shows_the_same(s, &on, &state);
let waiting: Vec<(u64, ResolvedView)> =
on.iter().filter(|(id, view, _)| !s.drawing_scenes.fresh(*id, &state, view)).map(|(id, view, _)| (*id, view.clone())).collect();
let Some((id, view)) = waiting.first().cloned() else { return step_dimensions(s, &d, &on, &state, units) };
@@ -799,6 +850,7 @@ pub fn step(s: &mut Session) -> bool {
_ => crate::drawing_view::shown(s),
};
let drawn = draw(s, &shown, id, &view);
let shows = SourceKey::of(&shown);
// The view's dimensions through its new frame, in the same swap as its lines.
let frame = drawn.frame;
let these = dimensions_on(&d, std::iter::once(id));
@@ -807,7 +859,7 @@ pub fn step(s: &mut Session) -> bool {
cache.shown = Some((state.clone(), shown));
cache.serial += 1;
let serial = cache.serial;
cache.views.insert(id, Entry { state: state.clone(), view, drawn, serial });
cache.views.insert(id, Entry { state: state.clone(), shows, view, drawn, serial });
cache.keep_dimensions(these, lines, &state, serial, &units);
#[cfg(test)]
{
@@ -831,12 +883,41 @@ fn step_dimensions(s: &mut Session, d: &Drawing, on: &[(u64, ResolvedView, Vec2)
!others.is_empty()
}
/// Drops the cache once its drawing isn't the one open: closing a drawing (or opening another) ends
/// its scenes, and the world states they hold. [`Session::execute`] calls it after every command.
pub(crate) fn forget_closed(s: &mut Session) {
if s.drawing_scenes.drawing.is_some_and(|d| s.open_drawing != Some(d)) {
s.drawing_scenes = Cache::default();
/// Each view of `on` drawn from another world state that showed what `state` shows takes `state`:
/// drawn as it draws now, it is then up to date ([`Cache::fresh`]) and draws nothing. `state`'s shown
/// set is worked out once, only when a view is behind it, and kept for [`step`] to draw from.
fn keep_what_shows_the_same(s: &mut Session, on: &[(u64, ResolvedView, Vec2)], state: &Arc<ModelState>) {
let entry = |id: &u64| s.drawing_scenes.views.get(id);
if !on.iter().any(|(id, ..)| entry(id).is_some_and(|e| e.shows.is_some() && !Arc::ptr_eq(&e.state, state))) {
return;
}
let shown = match s.drawing_scenes.shown.take() {
Some((was, shown)) if Arc::ptr_eq(&was, state) => shown,
_ => crate::drawing_view::shown(s),
};
let now = SourceKey::of(&shown);
let cache = &mut s.drawing_scenes;
cache.shown = Some((state.clone(), shown));
let Some(now) = now else { return };
for (id, ..) in on {
if let Some(entry) = cache.views.get_mut(id).filter(|e| e.shows_the_same(state, &now)) {
entry.state = state.clone();
}
}
}
/// Drops the cache once its drawing isn't the one open: closing a drawing (or opening another) ends
/// its scenes, and the world states they hold. Its views' lines are kept, for when it opens again,
/// and forgotten with the drawing. [`Session::execute`] calls it after every command.
pub(crate) fn forget_closed(s: &mut Session) {
let cache = &mut s.drawing_scenes;
if let Some(drawing) = cache.drawing.filter(|d| s.open_drawing != Some(*d)) {
let mut kept = std::mem::take(&mut cache.kept);
let views = std::mem::take(&mut cache.views).into_iter().map(|(id, e)| (id, KeptView { view: e.view, drawn: e.drawn, shows: e.shows }));
kept.keep(drawing, views.collect());
*cache = Cache { kept, ..Cache::default() };
}
cache.kept.retain(|drawing| s.doc.drawings.iter().any(|d| d.id == drawing));
}
#[cfg(test)]
+45
View File
@@ -0,0 +1,45 @@
//! What the sheet scene's provider keeps of a drawing once it closes: each view's last lines, how the
//! view drew them and what they showed, so the drawing opened again starts from them. No world state
//! is held, so a closed drawing keeps no model. Only in memory, never saved.
use std::collections::BTreeMap;
use std::sync::Arc;
use solidcraft_doc::drawing::view::ResolvedView;
use super::{Drawn, SourceKey};
/// Each closed drawing's views' last lines, by drawing and view.
#[derive(Default)]
pub(super) struct KeptLines(BTreeMap<u64, BTreeMap<u64, KeptView>>);
/// A view's last lines: drawn as `view` drew, from a world state that showed `shows`.
pub(super) struct KeptView {
pub(super) view: ResolvedView,
pub(super) drawn: Drawn,
pub(super) shows: Option<Arc<SourceKey>>,
}
impl KeptLines {
/// Keeps `views` as drawing `drawing`'s. It has none kept already: they were taken back when it
/// opened.
pub(super) fn keep(&mut self, drawing: u64, views: BTreeMap<u64, KeptView>) {
self.0.insert(drawing, views);
}
/// Drawing `drawing`'s, taken out.
pub(super) fn take(&mut self, drawing: u64) -> BTreeMap<u64, KeptView> {
self.0.remove(&drawing).unwrap_or_default()
}
/// Forgets each drawing `exists` says is gone.
pub(super) fn retain(&mut self, exists: impl Fn(u64) -> bool) {
self.0.retain(|drawing, _| exists(*drawing));
}
/// Drawing `drawing`'s, by view.
#[cfg(test)]
pub(super) fn of(&self, drawing: u64) -> impl Iterator<Item = (&u64, &KeptView)> {
self.0.get(&drawing).into_iter().flatten()
}
}
+109 -7
View File
@@ -467,22 +467,124 @@ fn after_a_model_change_the_last_scene_shows_until_its_views_are_drawn_again() {
assert_eq!((last.stale.len(), s.drawing_scenes.projections, bytes(&last.scene)), (0, projections + 2, bytes(&now)));
}
/// Closing the drawing drops its scenes and the world states they hold; opened again, every view
/// is out of date.
/// Closing the drawing drops its scenes and the world states they hold, and keeps each view's lines.
/// Opened again with nothing changed, its views show those lines, up to date, and none is drawn:
/// only its dimensions are read again.
#[test]
fn closing_the_drawing_drops_its_scenes() {
let (mut s, sheet, _) = front_and_top();
fn closing_the_drawing_keeps_its_lines_for_when_it_opens_again() {
let (mut s, sheet, [front, _]) = front_and_top();
top_edge(&mut s, front);
let drawing = ids::encode(s.open_drawing.unwrap());
let before = settled(&mut s, sheet);
assert_eq!(s.drawing_scenes.views.len(), 2);
run(&mut s, "drawing.close", json!({}));
let cache = &s.drawing_scenes;
assert!(cache.views.is_empty() && cache.last.is_none() && cache.shown.is_none() && cache.drawing.is_none());
assert!(cache.views.is_empty() && cache.dimensions.is_empty() && cache.last.is_none() && cache.shown.is_none() && cache.drawing.is_none());
assert!(!step(&mut s));
run(&mut s, "drawing.open", json!({"drawing": drawing}));
let reopened = extract(&mut s, sheet).unwrap();
// A new scene, so a new number: the page can't take it for the one it showed before.
assert!(reopened.stale.len() == 2 && reopened.generation > before.generation);
assert!(reopened.stale.is_empty() && reopened.generation > before.generation, "{:?}", reopened.stale);
assert_eq!(reopened.stale_dimensions.len(), 1);
let after = settled(&mut s, sheet);
assert_eq!((bytes(&after.scene), s.drawing_scenes.projections), (bytes(&before.scene), 0));
}
/// A change that leaves every body where it was and as it was draws no view: a sketch (a new feature,
/// so a new world state, that adds no body), and a model edit taken back before its views were drawn
/// again.
#[test]
fn a_change_that_shows_the_same_draws_no_view() {
let (mut s, sheet, _) = front_and_top();
let drawing = json!({"drawing": ids::encode(s.open_drawing.unwrap())});
let before = settled(&mut s, sheet);
let state = s.world_state().unwrap();
let checkpoint = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].clone();
run(&mut s, "drawing.close", json!({}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Note"}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "drawing.open", drawing.clone());
assert!(!Arc::ptr_eq(&state, &s.world_state().unwrap()), "a new world state");
assert!(extract(&mut s, sheet).unwrap().stale.is_empty());
run(&mut s, "drawing.close", json!({}));
let block = s.doc.features[0].id;
run(&mut s, "timeline.edit", json!({"feature": block.to_string(), "set": {"height": 40}}));
run(&mut s, "drawing.open", drawing);
assert_eq!(extract(&mut s, sheet).unwrap().stale.len(), 2, "40 tall shows otherwise");
run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": checkpoint}));
// A step straight after the change, with no extract between, finds nothing to draw either.
assert!(!step(&mut s));
let back = extract(&mut s, sheet).unwrap();
assert!(back.stale.is_empty(), "{:?}", back.stale);
assert_eq!((bytes(&back.scene), s.drawing_scenes.projections), (bytes(&before.scene), 0));
}
/// A body renamed while the drawing was closed draws its views again, so a press on a line names it
/// as it is called now.
#[test]
fn a_renamed_body_draws_again() {
let (mut s, sheet, _) = front_and_top();
let drawing = json!({"drawing": ids::encode(s.open_drawing.unwrap())});
settled(&mut s, sheet);
run(&mut s, "drawing.close", json!({}));
run(&mut s, "body.rename", json!({"body": "Block", "name": "Brick"}));
run(&mut s, "drawing.open", drawing);
assert_eq!(extract(&mut s, sheet).unwrap().stale.len(), 2);
settled(&mut s, sheet);
assert_eq!(line_under(&mut s, sheet, [150.0, 155.2], 0.5)["body"], json!("Brick"));
}
/// A part made a reference while the drawing was closed stands where it stood, but draws as a
/// reference part now: its views draw again.
#[test]
fn a_part_made_reference_draws_again() {
let (design, over) = under_and_over();
let (mut s, sheet, _) = front_and_top_of(design);
let drawing = json!({"drawing": ids::encode(s.open_drawing.unwrap())});
settled(&mut s, sheet);
run(&mut s, "drawing.close", json!({}));
run(&mut s, "occurrence.bom_type", json!({"occurrence": over, "bom_type": "reference"}));
run(&mut s, "drawing.open", drawing);
assert_eq!(extract(&mut s, sheet).unwrap().stale.len(), 2);
}
/// Opened again after a model change, with a view's scale changed too, a drawing shows its last
/// lines, out of date, until each view is drawn; then it draws as the built scene does.
#[test]
fn a_drawing_opened_after_a_change_shows_its_last_lines_until_drawn() {
let (mut s, sheet, [front, top]) = front_and_top();
let drawing = json!({"drawing": ids::encode(s.open_drawing.unwrap())});
let before = settled(&mut s, sheet);
run(&mut s, "drawing.close", json!({}));
let block = s.doc.features[0].id;
run(&mut s, "timeline.edit", json!({"feature": block.to_string(), "set": {"height": 40}}));
run(&mut s, "drawing.open", drawing);
run(&mut s, "drawing.view.edit", json!({"view": ids::encode(front), "set": {"scale": "1:4"}}));
let reopened = extract(&mut s, sheet).unwrap();
assert_eq!(reopened.stale.len(), 2);
for id in [front, top] {
assert_eq!(bytes_of(group_of(&reopened.scene, id)), bytes_of(group_of(&before.scene, id)), "{id}");
}
let now = settled(&mut s, sheet);
assert_eq!((bytes(&now.scene), s.drawing_scenes.projections), (bytes(&built(&s, sheet).scene), 2));
}
/// A drawing's kept lines go with it: deleted, nothing of it is kept.
#[test]
fn a_deleted_drawings_lines_are_not_kept() {
let (mut s, sheet, _) = front_and_top();
let drawing = s.open_drawing.unwrap();
settled(&mut s, sheet);
run(&mut s, "drawing.close", json!({}));
assert_eq!(s.drawing_scenes.kept.of(drawing).count(), 2);
run(&mut s, "drawing.delete", json!({"drawing": ids::encode(drawing)}));
assert_eq!(s.drawing_scenes.kept.of(drawing).count(), 0);
}
/// A set with nothing to show has no key, so a view drawn from it always draws again.
#[test]
fn nothing_to_show_has_no_source_key() {
assert_eq!(SourceKey::of(&Err(Unmeasured::NoBodies)), None);
}
/// A view whose lines would take the sheet past a paper scene's records fails and is left out;