Web app: open a design a few features a frame, with progress and Cancel (#10275)

* Engine: open a design a feature at a time (#10198)

OpenSteps splits doc.open of a design into steps for a caller that must
keep working meanwhile (the web app, which has one thread): start reads
the file, each step evaluates the next feature by moving a copy's history
marker one feature on (so every result before it is reused), and finish
puts the design in the session's place with doc.open's reply. The next
feature's imported STEP text is offered first, so a caller can read it
in parts. Session::opened and opened_at are split into small helpers so
both paths build the session the same way; doc.open is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Web app: open a design a few features a frame, with progress and Cancel (#10198)

On the web, a design to open is now a staged file load like a STEP file
(#1376): its features are evaluated for about 30 ms a frame through
OpenSteps, a feature's imported STEP file is read a solid per frame first
and held so the feature finds it read, the progress card counts the
design's features, Cancel works between steps, and the meshes are made
a few per frame afterwards. The desktop app keeps its worker thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kaltenbrunnermarkus
2026-11-01 00:16:01 +00:00
committed by GitHub
parent 68105938e2
commit b7a6967ef2
5 changed files with 453 additions and 16 deletions
+90 -2
View File
@@ -9,6 +9,9 @@ mod easyprint;
#[path = "file_import.rs"]
pub(crate) mod import;
#[path = "file_open_steps.rs"]
pub(crate) mod open_steps;
#[cfg(not(target_arch = "wasm32"))]
#[path = "file_send.rs"]
mod send;
@@ -339,11 +342,29 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
let read_only = bool_(p, "read_only").unwrap_or(false);
// Stamped before it is read: a write while it is being read is a change too.
let disk = solidcraft_io::design_lock::stamp(path);
let (doc, saved) = read_design(s, path)?;
opened_design(s, Session::opened_at(doc, saved.as_ref(), Some(path)), path, read_only, disk)
}
/// Read the design file at `path` for `doc.open`, under its file's name if it has none of its own.
fn read_design(s: &mut Session, path: &str) -> Result<(Document, Option<solidcraft_doc::SavedModel>)> {
let (mut doc, saved) = solidcraft_io::read_design_file(path, s.open_preview.take()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
if let Some(stem) = default_name_for(&doc.name, path) {
doc.name = stem;
}
s.replace_design(Session::opened_at(doc, saved.as_ref(), Some(path)));
Ok((doc, saved))
}
/// `doc.open` of a design: `opened`, the design read from `path` and evaluated, takes `s`'s
/// place, and the reply says what it is.
fn opened_design(
s: &mut Session,
opened: Session,
path: &str,
read_only: bool,
disk: Option<solidcraft_io::design_lock::FileStamp>,
) -> Result<Value> {
s.replace_design(opened);
s.disk = disk;
s.read_only = read_only;
let errors = s.model.results.iter().filter(|r| r.error.is_some()).count();
@@ -475,7 +496,12 @@ impl Session {
/// them. Absolute in-memory targets survive Save As, undo, redo and recovery unchanged.
pub fn opened_at(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>, path: Option<&str>) -> Self {
super::component_link::resolve_design_links(&mut doc, path);
let mut session = Self::opened(doc, saved);
Self::opened(doc, saved).located(path)
}
/// This session, just opened, as the design in the file at `path`.
pub(crate) fn located(self, path: Option<&str>) -> Self {
let mut session = self;
session.path = path.map(str::to_owned);
// A design saved before body names were pinned (#6403) is pinned now, as its first
// command would pin it: that command pinned them as part of itself, so undoing it went
@@ -1855,6 +1881,68 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
/// #10198: a design opened a feature at a time ([`OpenSteps`]) is the design `doc.open`
/// opens: the same features, results, bodies and history marker, with its file and name. Its
/// import is offered before the step that evaluates it, and other files are left to `doc.open`.
#[test]
fn a_design_opened_a_feature_at_a_time_is_the_one_doc_open_opens() {
use super::open_steps::OpenSteps;
let dir = std::env::temp_dir().join(format!("solidcraft-open-steps-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("steps.sc").to_string_lossy().to_string();
let step = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/step-conformance/cylinder_seam.step");
let mut s = Session::default();
s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap();
s.execute("file.insert_step", &json!({"path": step})).unwrap();
s.execute("component.activate", &json!({"component": "root"})).unwrap();
s.execute("solid.box", &json!({"length":5,"width":5,"height":5,"corner":[40,0,0]})).unwrap();
s.execute("solid.box", &json!({"length":5,"width":5,"height":5,"corner":[60,0,0]})).unwrap();
let features = s.doc.features.len();
s.execute("timeline.rollback", &json!({"position": features - 1})).unwrap();
s.execute("file.save", &json!({"path": path, "cache": false})).unwrap();
let mut whole = Session::default();
let opened = whole.execute("doc.open", &json!({"path": path, "read_only": true})).unwrap();
let mut steps = OpenSteps::start(&json!({"path": path, "read_only": true})).unwrap().expect("a design is opened in steps");
assert_eq!(steps.path(), path);
assert_eq!(steps.progress(), (0, features - 1), "the saved marker is where evaluation stops");
let mut imports = 0;
let mut n = 0;
while !steps.done() {
if let Some(text) = steps.next_import() {
assert!(text.contains("ISO-10303-21"));
imports += 1;
}
steps.step();
n += 1;
assert_eq!(steps.progress().0, n);
}
assert_eq!((imports, n), (1, features - 1));
assert!(!steps.step(), "nothing is left to evaluate");
let mut stepped = Session::default();
let reply = steps.finish(&mut stepped).unwrap();
assert_eq!(reply, opened);
assert_eq!(stepped.doc, whole.doc);
assert_eq!(stepped.doc.marker, Some(features - 1));
assert_eq!((stepped.path.as_deref(), stepped.read_only), (Some(path.as_str()), true));
let summary = |s: &Session| -> Vec<(u64, bool, bool)> { s.model.results.iter().map(|r| (r.id, r.skipped, r.error.is_some())).collect() };
assert_eq!(summary(&stepped), summary(&whole));
let bodies =
|s: &Session| -> Vec<(String, usize)> { s.world_state().bodies.iter().map(|b| (b.name.clone(), b.mesh().triangles.len())).collect() };
assert_eq!(bodies(&stepped), bodies(&whole));
assert_eq!(stepped.world_state().bodies.len(), 3, "the box, the cylinder and the box before the marker");
assert!(stepped.model.is_current(&stepped.doc));
// Other files, and STEP-only options, are opened by `doc.open`.
for p in [json!({"path": step}), json!({"path": "part.stl"}), json!({"path": path, "up": "y"}), json!({})] {
assert!(OpenSteps::start(&p).unwrap().is_none(), "{p}");
}
assert!(OpenSteps::start(&json!({"path": dir.join("missing.sc").to_string_lossy()})).is_err());
std::fs::remove_dir_all(dir).unwrap();
}
/// Every option the format registry offers is a parameter its owning command documents,
/// so the registry and the commands can't drift apart.
#[test]
+125
View File
@@ -0,0 +1,125 @@
//! Opening a design a feature at a time, for a caller that must keep doing other work while a
//! large design is read: the web app has one thread, which has to keep drawing frames (and offer
//! Cancel) meanwhile (#10198). [`OpenSteps::start`] reads the file, [`OpenSteps::step`] evaluates
//! the next feature of its timeline, and [`OpenSteps::finish`] puts the design in the session's
//! place as `doc.open` does. The result is the same design, evaluated the same way: each step
//! moves a copy's history marker one feature on, so the evaluation reuses every result before it.
use std::sync::Arc;
use serde_json::Value;
use solidcraft_doc::{Document, FeatureKind, Model, Visibility};
use super::{opened_design, read_design};
use crate::params::bool_;
use crate::{Result, Session};
/// A design file being opened ([`OpenSteps::start`]).
pub struct OpenSteps {
path: String,
read_only: bool,
disk: Option<solidcraft_io::design_lock::FileStamp>,
/// The design as the session will hold it, its history marker moved to `next` meanwhile.
doc: Arc<Document>,
/// The history marker the design was saved with.
marker: Option<usize>,
visibility: Visibility,
model: Model,
/// Features evaluated so far, and where evaluation stops (the saved marker, or the end).
next: usize,
stop: usize,
/// The model came from the file and needs no evaluation.
adopted: bool,
}
impl OpenSteps {
/// Read the design file `doc.open` would open with parameters `p`, without evaluating it.
/// `None` when `p` names a file `doc.open` reads in another way (a CAD, mesh or drawing file,
/// or a point cloud), or asks for something only those take: run `doc.open` for it.
pub fn start(p: &Value) -> Result<Option<OpenSteps>> {
let Some(path) = p.get("path").and_then(Value::as_str) else { return Ok(None) };
let other = solidcraft_io::is_step_path(path)
|| solidcraft_io::is_mesh_path(path)
|| solidcraft_io::is_point_cloud_path(path)
|| super::super::drawing_import_command(path).is_some()
|| ["names", "up"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null()));
if other || path.trim().is_empty() || path.len() >= 4096 {
return Ok(None);
}
let read_only = bool_(p, "read_only").unwrap_or(false);
// Stamped before it is read, as `doc.open` does.
let disk = solidcraft_io::design_lock::stamp(path);
let (mut doc, saved) = read_design(&mut Session::default(), path)?;
super::super::component_link::resolve_design_links(&mut doc, Some(path));
// What `Session::opened` does before it evaluates.
solidcraft_io::vfs::install_checks();
let visibility = std::mem::take(&mut doc.visibility);
let doc = Arc::new(doc);
let marker = doc.marker;
let stop = marker.unwrap_or(usize::MAX).min(doc.features.len());
let adopted = Session::saved_model(&doc, saved.as_ref());
let steps = OpenSteps {
path: path.to_string(),
read_only,
disk,
doc,
marker,
visibility,
next: if adopted.is_some() { stop } else { 0 },
stop,
adopted: adopted.is_some(),
model: adopted.unwrap_or_default(),
};
Ok(Some(steps))
}
/// The file being opened.
pub fn path(&self) -> &str {
&self.path
}
/// Features evaluated so far, and how many there are to evaluate.
pub fn progress(&self) -> (usize, usize) {
(self.next, self.stop)
}
/// Whether every feature has been evaluated ([`Self::finish`] is next).
pub fn done(&self) -> bool {
self.next >= self.stop
}
/// The STEP text the next feature imports, when it is an import that is not suppressed: a
/// caller can read it in parts first (`kernel::StepReading`), and while it holds that
/// reading's result the step finds the file read.
pub fn next_import(&self) -> Option<Arc<str>> {
let f = self.doc.features.get(self.next).filter(|_| !self.done())?;
match &f.kind {
FeatureKind::Import { step, .. } if !f.suppressed => Some(step.clone()),
_ => None,
}
}
/// Evaluate the next feature. False once there is none left.
pub fn step(&mut self) -> bool {
if self.done() {
return false;
}
self.next += 1;
Arc::make_mut(&mut self.doc).marker = Some(self.next);
self.model.evaluate(&self.doc);
!self.done()
}
/// Put the design in `s`'s place as `doc.open` does, and answer as it does. Features not
/// yet evaluated are evaluated now.
pub fn finish(mut self, s: &mut Session) -> Result<Value> {
Arc::make_mut(&mut self.doc).marker = self.marker;
if !self.adopted {
// Every result is current: this takes them all and keeps the placement proof
// `Session::opened` keeps.
self.model.evaluate_shared(&self.doc);
}
let opened = Session::with_model(self.doc, self.visibility, self.model).located(Some(&self.path));
opened_design(s, opened, &self.path, self.read_only, self.disk)
}
}
+1
View File
@@ -42,6 +42,7 @@ pub(crate) use face::{FaceRefForm, face_ref_form};
pub(crate) use features::profiles as feature_profiles;
pub(crate) use features::{EdgeRefForm, PLANE_FORMS, axis_dir_form, axis_line_object, edge_ref_form, explicit_plane, plane_name_problem, sketch_key};
pub use features::{auto_operation, extrude_reach, shown_scope};
pub use file::open_steps::OpenSteps;
pub use join_pieces::{Addition, addition};
pub use sketch::dimension_roles;
pub(crate) use sketch::face::face_pick_form;