From b7a6967ef29a0ea2aa1ed74ba575e5a98ad83fd2 Mon Sep 17 00:00:00 2001 From: kaltenbrunnermarkus <153593707+kaltenbrunnermarkus@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:16:01 +0000 Subject: [PATCH] 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 * 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 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/file.rs | 92 ++++++++- crates/engine/src/cmd/file_open_steps.rs | 125 ++++++++++++ crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/lib.rs | 21 ++- crates/ui-egui/src/file_load.rs | 230 ++++++++++++++++++++++- 5 files changed, 453 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/cmd/file_open_steps.rs diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 77bf1b8f7..d3dc965be 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -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 { 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)> { 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, +) -> Result { + 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] diff --git a/crates/engine/src/cmd/file_open_steps.rs b/crates/engine/src/cmd/file_open_steps.rs new file mode 100644 index 000000000..e32665b86 --- /dev/null +++ b/crates/engine/src/cmd/file_open_steps.rs @@ -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, + /// The design as the session will hold it, its history marker moved to `next` meanwhile. + doc: Arc, + /// The history marker the design was saved with. + marker: Option, + 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> { + 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> { + 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 { + 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) + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index cf228ea4a..0064bc9b5 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -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; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 591677e21..4779c6a82 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -47,8 +47,8 @@ use solidcraft_geom::Vec3; pub use cmd::settings::{MAX_PROFILE_NAME, profile_name}; pub use cmd::{ - Addition, CommandInfo, CommandSpec, addition, auto_operation, command_specs, dimension_roles, extrude_reach, find_command, resolve_design_links, - shown_scope, standard_view, + Addition, CommandInfo, CommandSpec, OpenSteps, addition, auto_operation, command_specs, dimension_roles, extrude_reach, find_command, + resolve_design_links, shown_scope, standard_view, }; pub use solidcraft_doc as doc; pub use solidcraft_doc::Visibility; @@ -671,14 +671,23 @@ impl Session { // The session keeps what is hidden (an undo step of its own); the design file carries it. let visibility = std::mem::take(&mut doc.visibility); let doc = Arc::new(doc); - let adopted = saved - .filter(|_| solidcraft_geom::env::var_os("NO_MODEL_CACHE").is_none()) - .and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok()); - let model = adopted.unwrap_or_else(|| { + let model = Self::saved_model(&doc, saved).unwrap_or_else(|| { let mut model = Model::new(); model.evaluate_shared(&doc); model }); + Self::with_model(doc, visibility, model) + } + + /// The model `doc`'s file kept, when it is `doc`'s evaluation and the cache is not turned off. + pub(crate) fn saved_model(doc: &Arc, saved: Option<&solidcraft_doc::SavedModel>) -> Option { + saved + .filter(|_| solidcraft_geom::env::var_os("NO_MODEL_CACHE").is_none()) + .and_then(|saved| Model::adopt(doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok()) + } + + /// A session on `doc` evaluated as `model`, with what it hides. + pub(crate) fn with_model(doc: Arc, visibility: Visibility, model: Model) -> Self { Session { saved: doc.clone(), doc, diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index b5dc74bdb..5de4f4b0a 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -152,12 +152,19 @@ impl Drop for Running { /// drawing (and offer Cancel) while a large file comes in. The file is parsed in one frame, /// then its solids are converted a few at a time, each frame for about [`STAGED_FRAME_MS`]; /// the import is then cached, and the command that inserts or opens the file finds it read. +/// A design is opened the same way, a few features a frame ([`step_opening`]). struct Staged { tx: Sender, session: Option, command: &'static str, params: Value, reading: Option, + /// A design being opened: its features evaluated so far. + opening: Option, + /// The feature of that design whose imported STEP file was read last (by `reading`), and + /// the result, held until the feature has been evaluated, which finds the file read. + read_for: Option, + held: Option>, /// The command's result once it has run; then the bodies' meshes are made, a few a frame, /// so the first frame that draws the design doesn't make them all at once. ran: Option, @@ -175,14 +182,15 @@ const STAGED_THUMBNAIL_TRIANGLES: usize = 1_000_000; const STAGED_FRAME_MS: f64 = 30.0; /// Files read in stages: STEP (not IGES, FreeCAD or Rhino, which are first restated as STEP) to -/// insert or open. +/// insert or open, and designs to open (#10198). #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] fn staged_kind(request: &Request) -> bool { let p = &request.path; - matches!(request.kind, Kind::Insert | Kind::Open) + let step = matches!(request.kind, Kind::Insert | Kind::Open) && solidcraft_engine::io::is_step_path(p) && !solidcraft_engine::io::is_iges_path(p) - && !solidcraft_engine::io::is_native_cad_path(p) + && !solidcraft_engine::io::is_native_cad_path(p); + step || (request.kind == Kind::Open && solidcraft_engine::io::is_design_path(p)) } impl Running { @@ -192,6 +200,19 @@ impl Running { fn cancelled(&self) -> bool { self.progress.is_cancelled() || crate::control::chat_turn_cancelled(self.request.chat_turn.as_deref()) } + /// Features rebuilt and the timeline's length: a design opened in stages counts its own. + fn features(&self) -> (usize, usize) { + self.staged.as_ref().and_then(|s| s.opening.as_ref()).map_or_else(|| self.progress.features(), |o| o.progress()) + } + /// Long work inside a feature for the card. A design opened in stages has some only while + /// it reads a feature's STEP file: the kernel's last count stays behind once the file is + /// read, and would hide "Rebuilding feature N of M" until the next import (#10198). + fn work(&self) -> Option<(&'static str, usize, usize)> { + match &self.staged { + Some(s) if s.opening.is_some() && s.reading.is_none() => None, + _ => self.progress.work(), + } + } } #[derive(Default)] @@ -217,7 +238,7 @@ impl FileLoad { } /// The running load's progress: (features rebuilt, timeline length). pub fn features(&self) -> Option<(usize, usize)> { - self.running.as_ref().map(|r| r.progress.features()) + self.running.as_ref().map(Running::features) } /// No active or queued request; cancelled import workers may still be unwinding. pub fn idle(&self) -> bool { @@ -596,7 +617,20 @@ fn start_staged(app: &mut SolveApp) { preview: None, partial_rx: None, built: None, - staged: Some(Staged { tx, session: Some(session), command, params, reading: None, ran: None, warmed: 0, triangles: 0, shown: false }), + staged: Some(Staged { + tx, + session: Some(session), + command, + params, + reading: None, + opening: None, + read_for: None, + held: None, + ran: None, + warmed: 0, + triangles: 0, + shown: false, + }), request, }); } @@ -613,6 +647,8 @@ fn step_staged(running: &mut Running) { let _ = staged.tx.send(job); staged.session = None; staged.reading = None; + staged.opening = None; + staged.held = None; }; if staged.session.is_none() { return; @@ -644,6 +680,18 @@ fn step_staged(running: &mut Running) { send(staged, Ok(Made { session, result, thumbnail })); return; } + if staged.command == "doc.open" && solidcraft_engine::io::is_design_path(&path) { + match step_opening(staged, &progress, scope, &in_budget) { + None => {} + Some(Ok(result)) => { + // Next frames: the meshes ("Preparing the view"). + running.phase.store(1, Ordering::Relaxed); + staged.ran = Some(result); + } + Some(Err(e)) => send(staged, Err(e)), + } + return; + } let Some(reading) = staged.reading.as_mut() else { // Parse and walk the file. The reading keeps the watch: its steps report progress and // stop on Cancel. @@ -697,6 +745,60 @@ fn step_staged(running: &mut Running) { } } +/// A frame of a design opened in stages (#10198): read the file, then evaluate its features +/// for a frame's worth of time, reading the STEP file a feature imports a piece per frame first, +/// as a staged STEP import does. Once every feature is in, the design takes the scratch +/// session's place as `doc.open` would leave it, and its answer is returned; `None` until then. +fn step_opening( + staged: &mut Staged, + progress: &Arc, + scope: Option, + in_budget: &dyn Fn() -> bool, +) -> Option> { + use solidcraft_engine::doc::progress::watch; + use solidcraft_engine::io::vfs::scoped; + let session = staged.session.as_mut()?; + let Some(opening) = staged.opening.as_mut() else { + let params = staged.params.clone(); + match scoped(scope.clone(), || watch(progress.clone(), || solidcraft_engine::OpenSteps::start(¶ms))) { + Ok(Some(opening)) => staged.opening = Some(opening), + // Options only `doc.open` takes: it opens the file at once. + Ok(None) => { + return Some(scoped(scope, || watch(progress.clone(), || session.execute(staged.command, ¶ms))).map_err(|e| e.to_string())); + } + Err(e) => return Some(Err(e.to_string())), + } + return None; + }; + while in_budget() { + if progress.is_cancelled() { + return Some(Err("file operation cancelled".into())); + } + if let Some(reading) = staged.reading.as_mut() { + if !reading.step() { + // A file that cannot be read fails in its feature, which says why. + staged.held = staged.reading.take().and_then(|r| r.finish_shared().ok()); + } + continue; + } + let next = opening.progress().0; + if staged.read_for != Some(next) + && let Some(text) = opening.next_import() + { + staged.read_for = Some(next); + staged.reading = watch(progress.clone(), || solidcraft_engine::kernel::StepReading::new(&text)).ok(); + continue; + } + let more = scoped(scope.clone(), || watch(progress.clone(), || opening.step())); + staged.held = None; + if !more { + let opening = staged.opening.take()?; + return Some(scoped(scope, || watch(progress.clone(), || opening.finish(session))).map_err(|e| e.to_string())); + } + } + None +} + /// A small picture of the bodies built so far (their display meshes, made here and kept for /// the finished model), or `None` when there is nothing to show yet, too much to draw, or the /// load ended meanwhile (`stop`). @@ -1056,10 +1158,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { _ => std::path::Path::new(&r.request.path).file_name().map(|p| p.to_string_lossy().to_string()).unwrap_or_default(), }; let phase = r.phase.load(Ordering::Relaxed); - let (done, total) = r.progress.features(); + let (done, total) = r.features(); // Long work inside one feature (a large STEP file) has progress of its own. let export = r.request.kind == Kind::ExportDxf; - let work = r.progress.work().filter(|(_, d, t)| export || (phase == 0 && d < t)); + let work = r.work().filter(|(_, d, t)| export || (phase == 0 && d < t)); let screen = ctx.content_rect(); // Leave the title bar to the window. The resize edges are a foreground layer above this. let cover = egui::Rect::from_min_max(egui::pos2(screen.left(), screen.top() + crate::toolbar::APP_BAR_HEIGHT), screen.max); @@ -1579,7 +1681,7 @@ mod tests { let mut app = SolveApp::new(Session::default(), Default::default()); let bodies = |app: &SolveApp| app.session.world_state().bodies.len(); assert!(staged_kind(&Request::new(&path, Kind::Insert)) && staged_kind(&Request::new(&path, Kind::Open))); - assert!(!staged_kind(&Request::new("part.igs", Kind::Insert)) && !staged_kind(&Request::new("part.solidcraft", Kind::Open))); + assert!(!staged_kind(&Request::new("part.igs", Kind::Insert)) && !staged_kind(&Request::new("part.solidcraft", Kind::Insert))); app.file_load.queued.push_back(Request::new(&path, Kind::Insert)); start_staged(&mut app); tick(&mut app, &ctx); @@ -1618,4 +1720,116 @@ mod tests { assert!(Arc::ptr_eq(&before, &app.session.doc)); let _ = std::fs::remove_dir_all(&dir); } + + /// #10198: the web app opens a design a few features a frame, reading the STEP file a feature + /// imports in pieces first, behind the same progress card and Cancel as a STEP file; the + /// design that lands is the one `doc.open` opens. + #[test] + fn a_staged_design_open_lands_over_frames_and_cancels_between_them() { + let dir = std::env::temp_dir().join(format!("solidcraft-staged-open-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("staged.sc").to_string_lossy().into_owned(); + let step = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/step-conformance/cylinder_seam.step"); + let mut part = Session::default(); + part.execute("solid.box", &serde_json::json!({"length": 10, "width": 10, "height": 10})).unwrap(); + part.execute("file.insert_step", &serde_json::json!({"path": step})).unwrap(); + part.execute("component.activate", &serde_json::json!({"component": "root"})).unwrap(); + part.execute("solid.box", &serde_json::json!({"length": 5, "width": 5, "height": 5, "corner": [40, 0, 0]})).unwrap(); + part.execute("file.save", &serde_json::json!({"path": path, "cache": false})).unwrap(); + let mut whole = Session::default(); + whole.execute("doc.open", &serde_json::json!({"path": path})).unwrap(); + let names = |s: &Session| s.world_state().bodies.iter().map(|b| b.name.clone()).collect::>(); + + let ctx = crate::fonts::test_context(); + let mut app = SolveApp::new(Session::default(), Default::default()); + assert!(staged_kind(&Request::new(&path, Kind::Open)) && !staged_kind(&Request::new(&path, Kind::Insert))); + let opening = + |app: &SolveApp| app.file_load.running.as_ref().and_then(|r| r.staged.as_ref()).and_then(|s| s.opening.as_ref()).map(|o| o.progress()); + app.file_load.queued.push_back(Request::new(&path, Kind::Open)); + start_staged(&mut app); + tick(&mut app, &ctx); + assert!(app.file_load.busy() && opening(&app).is_none(), "the first frame only shows the overlay"); + tick(&mut app, &ctx); + let features = whole.doc.features.len(); + assert_eq!(opening(&app), Some((0, features)), "the next frame reads the file, evaluating nothing yet"); + assert_eq!(app.file_load.features(), Some((0, features)), "the card counts the design's features"); + let mut frames = 2; + while app.file_load.running.is_some() && frames < 1000 { + tick(&mut app, &ctx); + frames += 1; + } + assert!(app.status.as_ref().is_some_and(|s| s.0.contains("Open done")), "{:?}", app.status); + assert_eq!(app.session.path.as_deref(), Some(path.as_str())); + assert_eq!(app.session.doc, whole.doc); + assert_eq!(names(&app.session), names(&whole)); + assert_eq!(names(&app.session).len(), 3); + + // Cancelled after the file is read: the design before stays, and nothing waits. + let before = app.session.doc.clone(); + app.file_load.queued.push_back(Request::new(&path, Kind::Open)); + start_staged(&mut app); + tick(&mut app, &ctx); + tick(&mut app, &ctx); + app.file_load.cancel(); + tick(&mut app, &ctx); + assert!(app.file_load.running.is_none() && !app.file_load.busy()); + assert!(Arc::ptr_eq(&before, &app.session.doc)); + // A file that isn't a design fails, and the design stays. + let junk = dir.join("junk.sc").to_string_lossy().into_owned(); + std::fs::write(&junk, "not a design").unwrap(); + app.file_load.queued.push_back(Request::new(&junk, Kind::Open)); + start_staged(&mut app); + for _ in 0..4 { + tick(&mut app, &ctx); + } + assert!(app.file_load.running.is_none()); + assert!(app.status.as_ref().is_some_and(|s| s.2 && s.0.contains("junk.sc")), "{:?}", app.status); + assert!(Arc::ptr_eq(&before, &app.session.doc)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// #10198: while a design opens in stages, the card shows an import's progress only while + /// its STEP file is read, and "Rebuilding feature N of M" again once it is; the kernel's + /// last count of that file must not stay up until the next import. + #[test] + fn a_staged_design_open_shows_an_import_only_while_its_file_is_read() { + let dir = std::env::temp_dir().join(format!("solidcraft-staged-work-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("staged.sc").to_string_lossy().into_owned(); + let step = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/step-conformance/cylinder_seam.step"); + let mut part = Session::default(); + part.execute("file.insert_step", &serde_json::json!({"path": step})).unwrap(); + part.execute("component.activate", &serde_json::json!({"component": "root"})).unwrap(); + part.execute("solid.box", &serde_json::json!({"length": 5, "width": 5, "height": 5, "corner": [40, 0, 0]})).unwrap(); + part.execute("file.save", &serde_json::json!({"path": path, "cache": false})).unwrap(); + + let ctx = crate::fonts::test_context(); + let mut app = SolveApp::new(Session::default(), Default::default()); + app.file_load.queued.push_back(Request::new(&path, Kind::Open)); + start_staged(&mut app); + tick(&mut app, &ctx); + tick(&mut app, &ctx); + // One step of the open at a time, as if every step filled a frame. + let (mut read, mut after_read) = (false, false); + for _ in 0..10_000 { + let Some(r) = app.file_load.running.as_mut() else { break }; + let Some(staged) = r.staged.as_mut() else { break }; + if staged.opening.is_none() { + break; + } + let once = std::cell::Cell::new(true); + if step_opening(staged, &r.progress, None, &|| once.replace(false)).is_some() { + break; + } + let reading = r.staged.as_ref().is_some_and(|s| s.reading.is_some()); + let work = r.work(); + if reading { + read |= work.is_some(); + } else { + after_read |= read; + assert_eq!(work, None, "no import's progress once its file is read"); + } + } + assert!(read && after_read, "the import's progress showed while its file was read, then the open went on"); + } }