Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Point clouds: remember the source file and reload it (#8818) (#8821)

Mario Geiger1589e18f2aec
diff --git a/assets/locales/pending/point-cloud-reload.json b/assets/locales/pending/point-cloud-reload.json
new file mode 100644
index 0000000000..23804cef21
--- /dev/null
+++ b/assets/locales/pending/point-cloud-reload.json
@@ -0,0 +1,47 @@
+{
+ "en": {
+ "cmd.pointcloud_reload": "Reload Point Cloud",
+ "file_load.reloading_cloud": "Reloading point cloud",
+ "ui.point_cloud_reload": "Reload from file"
+ },
+ "fr": {
+ "cmd.pointcloud_reload": "Recharger le nuage de points",
+ "file_load.reloading_cloud": "Rechargement du nuage de points",
+ "ui.point_cloud_reload": "Recharger le fichier"
+ },
+ "de": {
+ "cmd.pointcloud_reload": "Punktwolke neu laden",
+ "file_load.reloading_cloud": "Punktwolke wird neu geladen",
+ "ui.point_cloud_reload": "Aus Datei neu laden"
+ },
+ "ja": {
+ "cmd.pointcloud_reload": "点群を再読み込み",
+ "file_load.reloading_cloud": "点群を再読み込み中",
+ "ui.point_cloud_reload": "ファイルから再読み込み"
+ },
+ "zh": {
+ "cmd.pointcloud_reload": "重新加载点云",
+ "file_load.reloading_cloud": "正在重新加载点云",
+ "ui.point_cloud_reload": "从文件重新加载"
+ },
+ "ko": {
+ "cmd.pointcloud_reload": "포인트 클라우드 다시 불러오기",
+ "file_load.reloading_cloud": "포인트 클라우드 다시 불러오는 중",
+ "ui.point_cloud_reload": "파일에서 다시 불러오기"
+ },
+ "ar": {
+ "cmd.pointcloud_reload": "إعادة تحميل سحابة النقاط",
+ "file_load.reloading_cloud": "جارٍ إعادة تحميل سحابة النقاط",
+ "ui.point_cloud_reload": "إعادة التحميل من الملف"
+ },
+ "he": {
+ "cmd.pointcloud_reload": "טעינה מחדש של ענן נקודות",
+ "file_load.reloading_cloud": "טוען מחדש ענן נקודות",
+ "ui.point_cloud_reload": "טעינה מחדש מהקובץ"
+ },
+ "vi": {
+ "cmd.pointcloud_reload": "Tải lại đám mây điểm",
+ "file_load.reloading_cloud": "Đang tải lại đám mây điểm",
+ "ui.point_cloud_reload": "Tải lại từ tệp"
+ }
+}
diff --git a/crates/doc/src/format/pending/point-cloud-source.rs b/crates/doc/src/format/pending/point-cloud-source.rs
new file mode 100644
index 0000000000..e9e32e4e29
--- /dev/null
+++ b/crates/doc/src/format/pending/point-cloud-source.rs
@@ -0,0 +1,4 @@
+//! A point cloud remembers the file it was read from (#8818): `source`, its path, which
+//! `pointcloud.reload` reads again, and `max_points`, the limit it reads it under. Older designs
+//! need no transformation: their clouds have no source and cannot be reloaded, only inserted again. The last release refuses a design saved
+//! with this (the newer format number) instead of opening its clouds without their source.
diff --git a/crates/doc/src/point_cloud.rs b/crates/doc/src/point_cloud.rs
index a1ad8d959a..01f2661a74 100644
--- a/crates/doc/src/point_cloud.rs
+++ b/crates/doc/src/point_cloud.rs
@@ -80,6 +80,13 @@ pub struct PointCloud {
/// Only the elements within every filter's range are shown.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub filters: Vec<Filter>,
+ /// The file the cloud was read from, to read again (`pointcloud.reload`).
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub source: String,
+ /// The most points the file was read under, which a reload reads it under again; `None`: the
+ /// reader's default.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max_points: Option<u64>,
}
/// Where a property's values come from on one kind of element.
@@ -556,6 +563,8 @@ mod tests {
complex: Complex::default(),
color_property: None,
filters: Vec::new(),
+ source: String::new(),
+ max_points: None,
}
}
diff --git a/crates/doc/src/point_cloud_distribution_tests.rs b/crates/doc/src/point_cloud_distribution_tests.rs
index 522475947c..92b3d6053e 100644
--- a/crates/doc/src/point_cloud_distribution_tests.rs
+++ b/crates/doc/src/point_cloud_distribution_tests.rs
@@ -24,6 +24,8 @@ fn cloud(points: &[[f32; 3]], segments: &[u32], triangles: &[u32], columns: Vec<
complex: Complex { segments: Indices(segments.to_vec().into()), triangles: Indices(triangles.to_vec().into()), columns, names: Vec::new() },
color_property: None,
filters: Vec::new(),
+ source: String::new(),
+ max_points: None,
}
}
diff --git a/crates/engine/src/cmd/point_cloud.rs b/crates/engine/src/cmd/point_cloud.rs
index 9bb560bceb..6810cd8243 100644
--- a/crates/engine/src/cmd/point_cloud.rs
+++ b/crates/engine/src/cmd/point_cloud.rs
@@ -4,13 +4,17 @@
use serde_json::{Value, json};
use solidcraft_doc::Mat;
use solidcraft_doc::point_cloud::{
- ColorBy, Colors, Filter, Keep, MAX_COORD, MAX_FILTERS, MAX_NAMES, MAX_POINTS, POINT_SIZE, PointCloud, Points, UNITS, unit_scale,
+ ColorBy, Colors, Complex, Filter, Keep, MAX_COORD, MAX_FILTERS, MAX_NAMES, MAX_POINTS, POINT_SIZE, PointCloud, Points, UNITS, unit_scale,
};
use super::CommandSpec;
use crate::params::{bad, bool_, str_};
+use crate::schema::point_cloud::{PointCloudReloadParams, PointCloudReloadResult};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
+const RELOAD_CONTRACT: TypedContract<PointCloudReloadParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("pointcloud.insert", "Insert Point Cloud", insert)
.at("SOLID", "INSERT")
@@ -19,12 +23,17 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("pointcloud.edit", "Edit Point Cloud", edit)
.icon("edit")
.params("cloud: id or name; name?; visible?; point_size?: pixels (0.5…16); color_by?: file|single|height or a property's name (the file's colours, the default; one colour; a ramp by height, blue low to red high; or by any property of the file, a ramp over its values or a palette for whole numbers); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); color_range?: [low, high] the ramp runs between (design Z in mm by height), or null for the automatic range (by height all but the lowest and highest 2 % of the points; by a property the values it takes over what the filters keep); height_range?: the same as color_range; units?: mm|cm|m|in|ft (the file's length unit: the points are scaled from the unit they came in as); matrix?: [12 or 16 numbers] (where the cloud sits: a rigid row-major 3x4 or 4x4 matrix, as occurrence.move takes it); tolerance?; filters?: [{property, range: [low, high]} or {property, values: [whole numbers]} for a property with named values], or null (only what every filter keeps is shown) → cloud"),
+ CommandSpec::new("pointcloud.reload", "Reload Point Cloud", crate::checked!("pointcloud.reload", reload))
+ .icon("import")
+ .contract(&RELOAD_CONTRACT)
+ .output(output_schema_for::<PointCloudReloadResult>)
+ .params("cloud: id or name (its file is read again from where it was inserted; name, placement, units, colouring and the filters on properties it still has are kept; read under the limit it was inserted with, so a file that grew is thinned only past that limit) → cloud, points, segments, triangles, warnings"),
CommandSpec::new("pointcloud.delete", "Delete Point Cloud", delete).icon("delete").params("cloud: id or name → deleted"),
CommandSpec::new("pointcloud.list", "Point Clouds", list)
.icon("list")
.noundo()
.doc_only()
- .params("→ clouds: [{cloud, name, file, points, segments, triangles, source_points, units, visible, point_size, color_by (file, single, height or a property's name), color, colored, properties: [{name, integer, span, names}], filters, color_range (the ramp's now, exact over what the filters keep), height_range (the ramp's own range or the automatic one by height), height_auto, bounds: [[x,y,z], [x,y,z]] in the design, matrix}]"),
+ .params("→ clouds: [{cloud, name, file, source (the file's path, read again by pointcloud.reload), points, segments, triangles, source_points, units, visible, point_size, color_by (file, single, height or a property's name), color, colored, properties: [{name, integer, span, names}], filters, color_range (the ramp's now, exact over what the filters keep), height_range (the ramp's own range or the automatic one by height), height_auto, bounds: [[x,y,z], [x,y,z]] in the design, matrix}]"),
];
fn units_of(p: &Value, cmd: &str) -> Result<Option<(&'static str, f64)>> {
@@ -123,13 +132,18 @@ fn check_properties(c: &PointCloud, cmd: &str) -> Result<()> {
return Err(bad(cmd, format!("the point cloud has no property `{n}` (it has {})", names.join(", "))));
}
}
- // A set of values filters a label: a property with named whole numbers.
- if let Some(f) = c.filters.iter().find(|f| matches!(f.keep, Keep::Values { .. }) && c.complex.names(&f.property).is_none()) {
+ if let Some(f) = c.filters.iter().find(|f| picks_from_no_names(&c.complex, f)) {
return Err(bad(cmd, format!("`{}` has no named values: filter it with a range", f.property)));
}
Ok(())
}
+/// A set of values filters a label: a property with named whole numbers. Is this one a set of
+/// values on a property with no names?
+fn picks_from_no_names(complex: &Complex, f: &Filter) -> bool {
+ matches!(f.keep, Keep::Values { .. }) && complex.names(&f.property).is_none()
+}
+
/// `height_range`: absent (`None`), null for the automatic one (`Some(None)`), or [low, high].
fn height_range(p: &Value, cmd: &str) -> Result<Option<Option<[f64; 2]>>> {
let refuse = || bad(cmd, "`height_range` (or `color_range`) must be [low, high], lowest first, or null");
@@ -232,6 +246,8 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
complex: read.complex,
color_property: None,
filters: filters(p, cmd)?.unwrap_or_default(),
+ source: std::path::absolute(path).map(|a| a.to_string_lossy().to_string()).unwrap_or_else(|_| path.to_string()),
+ max_points: Some(max_points as u64),
};
set_colors(&mut cloud, colors.0, colors.1, colors.2);
check_properties(&cloud, cmd)?;
@@ -260,7 +276,7 @@ fn find(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
let key = match p.get("cloud") {
Some(Value::Number(n)) => n.to_string(),
Some(Value::String(x)) => x.clone(),
- _ => return Err(bad(cmd, "`cloud` must be an id or a name")),
+ _ => return Err(bad(cmd, "`cloud` must be an id or name")),
};
s.doc.point_clouds.iter().position(|c| c.id.to_string() == key || c.name == key).ok_or_else(|| bad(cmd, format!("no point cloud `{key}`")))
}
@@ -318,6 +334,56 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"cloud": id}))
}
+/// The most points a reload keeps: the limit the cloud was read under. A read is a function of
+/// the file and that limit, so an unchanged file reads as the very same points, and a file that
+/// grew is thinned only past the limit. The counts cannot say this: a cloud has fewer points than
+/// its file when some could not be read, too, thinned or not.
+fn reload_limit(c: &PointCloud) -> usize {
+ c.max_points.map_or(solidcraft_io::DEFAULT_MAX_POINTS, |n| usize::try_from(n).unwrap_or(MAX_POINTS))
+}
+
+/// Read the cloud's file again where it was read from, keeping its name, placement, units and
+/// how it is shown.
+/// The path comes from the design, which may be someone else's, so it is a design path: one on
+/// another computer is refused from its text until the user allows that server.
+fn reload(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "pointcloud.reload";
+ let i = find(s, p, cmd)?;
+ let mut c = s.doc.point_clouds.get(i).cloned().ok_or_else(|| bad(cmd, "point cloud"))?;
+ if c.source.is_empty() {
+ return Err(bad(cmd, format!("point cloud `{}` does not remember its file", c.name)));
+ }
+ let path = c.source.clone();
+ let scale = unit_scale(&c.units).unwrap_or(1.0);
+ let max_points = reload_limit(&c);
+ let bytes = solidcraft_io::vfs::read_design_path(&path, s.path.as_deref(), solidcraft_io::MAX_POINT_CLOUD_BYTES)
+ .map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ let read = solidcraft_io::read_point_cloud(&bytes, &path, scale, max_points).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ c.origin = read.origin;
+ c.points = Points::new(read.points.into());
+ c.colors = Colors(read.colors.into());
+ c.source_points = read.source_points;
+ c.complex = read.complex;
+ // What the file no longer has is no longer coloured or filtered by.
+ let names: Vec<String> = c.property_names().map(str::to_string).collect();
+ c.filters.retain(|f| names.contains(&f.property) && !picks_from_no_names(&c.complex, f));
+ if c.color_by == ColorBy::Property && !c.color_property.as_ref().is_some_and(|n| names.contains(n)) {
+ (c.color_by, c.color_property) = (ColorBy::File, None);
+ }
+ c.check()?;
+ let out = PointCloudReloadResult {
+ cloud: c.id,
+ points: c.len(),
+ segments: c.complex.segment_count(),
+ triangles: c.complex.triangle_count(),
+ warnings: read.warnings,
+ };
+ let out = serde_json::to_value(out).map_err(|e| EngineError::Other(e.to_string()))?;
+ let slot = s.doc_mut().point_clouds.get_mut(i).ok_or_else(|| bad(cmd, "point cloud"))?;
+ *slot = c;
+ Ok(out)
+}
+
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
let i = find(s, p, "pointcloud.delete")?;
let c = s.doc_mut().point_clouds.remove(i);
@@ -348,6 +414,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
.collect::<Vec<_>>(),
"filters": c.filters,
"color_range": solidcraft_doc::point_cloud_distribution::color_range(c, &solidcraft_doc::point_cloud_distribution::Geometry::of(c), &c.filters),
+ "source": c.source,
"color": c.color,
"colored": !c.colors.is_empty(),
"height_range": c.height_range_now(),
@@ -464,6 +531,174 @@ mod tests {
let _ = std::fs::remove_dir_all(d);
}
+ /// A PLY in text with a `layer` property (or none) on each point.
+ fn layered(path: &std::path::Path, points: usize, layer: bool) {
+ let mut b = format!("ply\nformat ascii 1.0\nelement vertex {points}\nproperty float x\nproperty float y\nproperty float z\n");
+ if layer {
+ b.push_str("property int layer\n");
+ }
+ b.push_str("end_header\n");
+ for i in 0..points {
+ b.push_str(&if layer { format!("{i} 0 0 {i}\n") } else { format!("{i} 0 0\n") });
+ }
+ std::fs::write(path, b).unwrap();
+ }
+
+ #[test]
+ fn a_reload_reads_the_file_again_and_keeps_how_the_cloud_is_shown() {
+ let d = dir("reload");
+ let path = d.join("scan.ply");
+ layered(&path, 3, true);
+ let mut s = Session::default();
+ let id = s.execute("pointcloud.insert", &json!({"path": path, "units": "m"})).unwrap()["cloud"].as_u64().unwrap();
+ s.execute(
+ "pointcloud.edit",
+ &json!({"cloud": id, "name": "Scan", "point_size": 4, "matrix": [1, 0, 0, 100, 0, 1, 0, 0, 0, 0, 1, 0], "color_by": "layer", "filters": [{"property": "layer", "range": [0, 2]}]}),
+ )
+ .unwrap();
+ let listed = s.execute("pointcloud.list", &json!({})).unwrap();
+ assert_eq!(listed["clouds"][0]["source"], json!(std::path::absolute(&path).unwrap()));
+
+ layered(&path, 5, true);
+ let r = s.execute("pointcloud.reload", &json!({"cloud": "Scan"})).unwrap();
+ assert_eq!((r["cloud"].as_u64(), r["points"].as_u64()), (Some(id), Some(5)));
+ let c = &s.doc.point_clouds[0];
+ assert_eq!((c.name.as_str(), c.units.as_str(), c.point_size, c.color_by), ("Scan", "m", 4.0, ColorBy::Property));
+ assert_eq!(c.color_property.as_deref(), Some("layer"));
+ assert_eq!(c.filters.len(), 1);
+ // In metres and moved, as before: the last point is at 4 m, plus 100 mm.
+ assert_eq!(c.world_point(4).map(|p| p.x), Some(4100.0));
+ // One undo step takes it back.
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc.point_clouds[0].len(), 3);
+ s.execute("edit.redo", &json!({})).unwrap();
+ assert_eq!(s.doc.point_clouds[0].len(), 5);
+
+ // What the file no longer has is no longer coloured or filtered by.
+ layered(&path, 2, false);
+ s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap();
+ let c = &s.doc.point_clouds[0];
+ assert_eq!((c.len(), c.color_by, c.color_property.as_deref(), c.filters.len()), (2, ColorBy::File, None, 0));
+
+ // A file that is gone is refused, and the cloud is as it was, with no undo step.
+ std::fs::remove_file(&path).unwrap();
+ let (before, undo) = (s.doc.point_clouds.clone(), s.undo.len());
+ assert!(s.execute("pointcloud.reload", &json!({"cloud": id})).is_err());
+ assert_eq!((&s.doc.point_clouds, s.undo.len()), (&before, undo));
+ let _ = std::fs::remove_dir_all(d);
+ }
+
+ /// A set of values filters a label, so it lasts as long as the file names that property's
+ /// values: left behind, it would make every later `pointcloud.edit` of the cloud refused.
+ #[test]
+ fn a_reload_drops_a_value_filter_when_the_file_stops_naming_the_values() {
+ let d = dir("reload-names");
+ let path = d.join("scan.ply");
+ let write = |comment: &str| {
+ let head = "ply\nformat ascii 1.0\n";
+ let body = "element vertex 2\nproperty float x\nproperty float y\nproperty float z\nproperty int layer\nend_header\n0 0 0 0\n1 0 0 1\n";
+ std::fs::write(&path, format!("{head}{comment}{body}")).unwrap();
+ };
+ write("comment layer: 0 first, 1 second\n");
+ let mut s = Session::default();
+ let id = s.execute("pointcloud.insert", &json!({"path": path})).unwrap()["cloud"].as_u64().unwrap();
+ s.execute("pointcloud.edit", &json!({"cloud": id, "filters": [{"property": "layer", "values": [1]}]})).unwrap();
+
+ // Still named: the filter stays.
+ s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap();
+ assert_eq!(s.doc.point_clouds[0].filters.len(), 1);
+
+ // The same property with no names: the filter goes, and the cloud can still be edited.
+ write("");
+ s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap();
+ assert!(s.doc.point_clouds[0].filters.is_empty());
+ s.execute("pointcloud.edit", &json!({"cloud": id, "point_size": 4})).unwrap();
+ let _ = std::fs::remove_dir_all(d);
+ }
+
+ /// A design may come from anyone, and on Windows only asking about `\\\\host\\share\\x` connects
+ /// to that computer with the user's sign-in: the path is refused from its text, with no file
+ /// call, until the server is allowed.
+ #[test]
+ fn a_reload_reaches_no_network_location_until_its_server_is_allowed() {
+ use solidcraft_io::vfs::{allowing_hosts, file_calls};
+ let d = dir("reload-network");
+ let path = d.join("scan.ply");
+ layered(&path, 3, false);
+ let mut s = Session::default();
+ let id = s.execute("pointcloud.insert", &json!({"path": path})).unwrap()["cloud"].as_u64().unwrap();
+ for (crafted, says) in [(r"\\evil.example\share\scan.ply", "evil.example"), (r"\\.\pipe\scan.ply", "device")] {
+ s.doc_mut().point_clouds[0].source = crafted.into();
+ let (before, undo, calls) = (s.doc.point_clouds.clone(), s.undo.len(), file_calls());
+ let e = s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap_err().to_string();
+ assert!(e.contains(says), "{e}");
+ assert_eq!(file_calls(), calls, "{crafted}: nothing was asked of the disk or the network");
+ assert_eq!((&s.doc.point_clouds, s.undo.len()), (&before, undo));
+ }
+ // Allowed, the read goes ahead (and fails here only because no such server answers).
+ s.doc_mut().point_clouds[0].source = r"\\evil.example\share\scan.ply".into();
+ let calls = file_calls();
+ let allowed = allowing_hosts(&["evil.example".to_string()], || s.execute("pointcloud.reload", &json!({"cloud": id})));
+ assert!(allowed.is_err());
+ assert!(file_calls() > calls, "an allowed server is read");
+ let _ = std::fs::remove_dir_all(d);
+ }
+
+ #[test]
+ fn a_reload_reads_a_grown_file_whole_and_keeps_a_thinned_cloud_thinned() {
+ let d = dir("reload-limit");
+ let (whole, thin) = (d.join("whole.ply"), d.join("thin.ply"));
+ layered(&whole, 4, false);
+ layered(&thin, 100, false);
+ let mut s = Session::default();
+ s.execute("pointcloud.insert", &json!({"path": whole, "name": "Whole"})).unwrap();
+ // One point in ten is the fewest strides that fit in 11: ten points, under the limit.
+ s.execute("pointcloud.insert", &json!({"path": thin, "name": "Thin", "max_points": 11})).unwrap();
+ let thinned = s.doc.point_clouds[1].clone();
+ assert_eq!((thinned.len(), thinned.source_points), (10, 100));
+
+ layered(&whole, 100, false);
+ let r = s.execute("pointcloud.reload", &json!({"cloud": "Whole"})).unwrap();
+ assert_eq!(r["points"].as_u64(), Some(100), "a file that grew is not cut to the count it had");
+
+ // The same file reads as the very same points.
+ s.execute("pointcloud.reload", &json!({"cloud": "Thin"})).unwrap();
+ assert_eq!(s.doc.point_clouds[1].points, thinned.points);
+ // A grown one, thinned under the same limit.
+ layered(&thin, 500, false);
+ let r = s.execute("pointcloud.reload", &json!({"cloud": "Thin"})).unwrap();
+ assert_eq!(r["points"].as_u64(), Some(11));
+ assert_eq!(s.doc.point_clouds[1].source_points, 500);
+ let _ = std::fs::remove_dir_all(d);
+ }
+
+ #[test]
+ fn a_reload_takes_no_unreadable_point_for_thinning() {
+ let d = dir("reload-unreadable");
+ // `count` points in a line, with the one at `far` out of range, so it cannot be read.
+ let line = |count: usize, far: usize| -> Vec<[f32; 3]> { (0..count).map(|i| [if i == far { 1e30 } else { i as f32 }, 0.0, 0.0]).collect() };
+ let whole = ply(&d, "whole.ply", &line(4, 1), false);
+ let thin = ply(&d, "thin.ply", &line(100, 10), false);
+ let mut s = Session::default();
+ s.execute("pointcloud.insert", &json!({"path": whole, "name": "Whole"})).unwrap();
+ s.execute("pointcloud.insert", &json!({"path": thin, "name": "Thin", "max_points": 10})).unwrap();
+ let (kept_whole, kept_thin) = (s.doc.point_clouds[0].clone(), s.doc.point_clouds[1].clone());
+ assert_eq!((kept_whole.len(), kept_whole.source_points), (3, 4));
+ assert_eq!((kept_thin.len(), kept_thin.source_points), (9, 100));
+
+ // The same files read as the very same points.
+ s.execute("pointcloud.reload", &json!({"cloud": "Whole"})).unwrap();
+ s.execute("pointcloud.reload", &json!({"cloud": "Thin"})).unwrap();
+ assert_eq!(s.doc.point_clouds[0].points, kept_whole.points);
+ assert_eq!(s.doc.point_clouds[1].points, kept_thin.points);
+
+ // A file that grew comes in whole, not cut to the count it had.
+ ply(&d, "whole.ply", &line(100, 1), false);
+ let r = s.execute("pointcloud.reload", &json!({"cloud": "Whole"})).unwrap();
+ assert_eq!(r["points"].as_u64(), Some(99));
+ let _ = std::fs::remove_dir_all(d);
+ }
+
#[test]
fn hostile_point_cloud_params_never_panic() {
let d = dir("hostile");
@@ -511,6 +746,18 @@ mod tests {
assert!(s.execute("pointcloud.edit", &p).is_err(), "{p}");
}
assert!(s.execute("pointcloud.delete", &json!({"cloud": "nope"})).is_err());
+ for p in [json!({}), json!({"cloud": 999}), json!({"cloud": [1]})] {
+ assert!(s.execute("pointcloud.reload", &p).is_err(), "{p}");
+ }
+ // A cloud from a design saved before it remembered its file, or naming a file not a scan.
+ let source = s.doc.point_clouds[0].source.clone();
+ for hostile in ["", bad.to_str().unwrap(), d.to_str().unwrap()] {
+ s.doc_mut().point_clouds[0].source = hostile.into();
+ let before = s.doc.point_clouds.clone();
+ assert!(s.execute("pointcloud.reload", &json!({"cloud": id})).is_err(), "{hostile}");
+ assert_eq!(s.doc.point_clouds, before);
+ }
+ s.doc_mut().point_clouds[0].source = source;
// Scaled out of range: refused, and the cloud is as it was.
let far = ply(&d, "far.ply", &[[2e6, 0.0, 0.0], [2e6, 1.0, 0.0]], false);
let far = s.execute("pointcloud.insert", &json!({"path": far})).unwrap()["cloud"].as_u64().unwrap();
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index f6b59100af..4817da3050 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -81,6 +81,7 @@ pub mod parameter_sweep;
pub mod parameters;
pub mod parts;
pub mod plastic;
+pub mod point_cloud;
pub mod print_face;
pub mod render;
pub mod render_bindings;
diff --git a/crates/engine/src/schema/point_cloud.rs b/crates/engine/src/schema/point_cloud.rs
new file mode 100644
index 0000000000..3e763e6948
--- /dev/null
+++ b/crates/engine/src/schema/point_cloud.rs
@@ -0,0 +1,36 @@
+//! Contracts and result types for the commands in `cmd/point_cloud.rs` that have them.
+
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::types::IdOrName;
+
+/// Read a point cloud's file again from where it was inserted. The points, colours, segments,
+/// triangles and properties are replaced; the name, placement, units, point size and colouring
+/// are kept, and so are the filters on properties the file still has. The file is read under the
+/// limit the cloud was inserted with, so a file that grew is thinned only past that limit.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct PointCloudReloadParams {
+ /// The point cloud, by id or name.
+ pub cloud: IdOrName,
+}
+
+/// What `pointcloud.reload` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct PointCloudReloadResult {
+ /// The cloud's id.
+ pub cloud: u64,
+ /// How many points it has now.
+ pub points: usize,
+ /// How many segments it has now.
+ pub segments: usize,
+ /// How many triangles it has now.
+ pub triangles: usize,
+ /// What could not be read from the file, or was thinned out of it.
+ pub warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "point_cloud_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/point_cloud_tests.rs b/crates/engine/src/schema/point_cloud_tests.rs
new file mode 100644
index 0000000000..b61223a258
--- /dev/null
+++ b/crates/engine/src/schema/point_cloud_tests.rs
@@ -0,0 +1,32 @@
+use serde_json::json;
+
+use super::{PointCloudReloadParams, PointCloudReloadResult};
+use crate::Session;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<PointCloudReloadParams>(), &["cloud"]);
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[("pointcloud.reload", json!({"cloud": [1]}))]);
+}
+
+#[test]
+fn the_reply_matches_the_output_schema() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-pointcloud-schema-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("two.xyz");
+ std::fs::write(&path, "0 0 0\n1 0 0\n").unwrap();
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let id = s.execute("pointcloud.insert", &json!({"path": path})).unwrap()["cloud"].clone();
+ let reply = s.execute("pointcloud.reload", &json!({"cloud": id})).unwrap();
+ assert!(reply.get("param_warnings").is_none(), "{reply}");
+ let schema = output_schema_for::<PointCloudReloadResult>();
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, &reply), "{reply} doesn't match {schema}");
+ let _ = std::fs::remove_dir_all(dir);
+}
diff --git a/crates/io/src/vfs.rs b/crates/io/src/vfs.rs
index 1a9ed9d16d..e6af7fb9fa 100644
--- a/crates/io/src/vfs.rs
+++ b/crates/io/src/vfs.rs
@@ -560,14 +560,14 @@ fn design_path_error(path: &str, why: &Remote) -> Error {
let text = match why {
Remote::Network(host) => format!(
"{path}: on the network location \\\\{host}, which designs may not reach until you allow that server \
- (Update Links or Open Linked Design asks; or Preferences › Design › Network locations)"
+ (Update Links, Open Linked Design or Reload from file asks; or Preferences › Design › Network locations)"
),
Remote::Device => format!("{path}: names a device, not a file"),
};
Error::new(ErrorKind::PermissionDenied, text)
}
-/// Check a path a design names (a linked design, a font file) before anything reads it, judged
+/// Check a path a design names (a linked design, a font file, a point cloud's file) before anything reads it, judged
/// from its text first: a network path whose host isn't allowed, or a device path, is refused
/// without a filesystem call. An agent's scope ([`check`]) applies on top.
pub fn check_design_path(path: &str, design: Option<&str>) -> Result<()> {
diff --git a/crates/ui-egui/src/browser/point_clouds.rs b/crates/ui-egui/src/browser/point_clouds.rs
index 8fe9012916..1eaeb10e27 100644
--- a/crates/ui-egui/src/browser/point_clouds.rs
+++ b/crates/ui-egui/src/browser/point_clouds.rs
@@ -44,6 +44,9 @@ pub struct CloudPanel {
#[derive(Clone, Debug)]
pub struct Play {
pub filter: usize,
+ /// The property of that filter: filters are told by place, and a place changes hands when a
+ /// filter before it goes.
+ property: String,
part: Part,
/// When it last moved, and where it is exactly.
at: f64,
@@ -65,14 +68,14 @@ fn colour_key(cloud: u64) -> String {
impl Play {
/// Start playing `part` of `range` within `span`, from the start again when it is at the end.
- fn new(filter: usize, part: Part, [lo, hi]: [f64; 2], span: [f64; 2], at: f64) -> Play {
+ fn new(filter: usize, property: String, part: Part, [lo, hi]: [f64; 2], span: [f64; 2], at: f64) -> Play {
let exact = match part {
Part::High if hi >= span[1] => [lo, lo],
Part::Band if hi >= span[1] => [span[0], span[0] + hi - lo],
Part::Low if lo >= hi => [span[0], hi],
_ => [lo, hi],
};
- Play { filter, part, at, exact, now: exact }
+ Play { filter, property, part, at, exact, now: exact }
}
/// Move on to time `now` at `speed` units a second; whether it reached the end.
fn step(&mut self, now: f64, speed: f64, span: [f64; 2], integer: bool) -> bool {
@@ -263,12 +266,16 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) {
return;
};
let mut edit: Option<Value> = None;
+ let mut reload = false;
let title = crate::i18n::format("browser.edit_point_cloud_title", &[("name", &c.name)]);
let auto = if c.color_by == ColorBy::Height { m.auto_range(&c) } else { None };
let dots = m.dots(&c);
let now = ctx.input(|i| i.time);
// A playing filter moves on; at the end of its span it stops, and is written once.
let mut stop_play = false;
+ // A filter gone from under it (a reload, an agent's edit, an undo) ends the play, unwritten,
+ // or its range would land on the filter that took its place.
+ m.play.take_if(|p| c.filters.get(p.filter).is_none_or(|f| f.property != p.property));
if let Some(p) = m.play.as_mut()
&& let Some(span) = c.filters.get(p.filter).and_then(|f| c.span(&f.property))
{
@@ -502,7 +509,7 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) {
changed = true;
}
let part = range_track::last_part(ui.ctx(), &filter_key(c.id, k));
- m.play = Some(Play::new(k, part, range, span, now));
+ m.play = Some(Play::new(k, f.property.clone(), part, range, span, now));
}
}
}
@@ -533,6 +540,9 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) {
if changed {
edit = Some(json!({ "cloud": c.id, "filters": filters_json(&filters) }));
}
+ if !c.source.is_empty() && ui_kit::button(ui, crate::i18n::tr("ui.point_cloud_reload"), ui_kit::Button::Normal).clicked() {
+ reload = true;
+ }
});
// A filter that stops playing is written where it stopped.
if stop_play && let Some(p) = m.play.take() {
@@ -542,6 +552,9 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) {
edit = Some(json!({ "cloud": c.id, "filters": filters_json(&filters) }));
}
}
+ if reload {
+ crate::network_prompt::reload_cloud(app, c.id, &c.source);
+ }
if let Some(p) = edit
&& app.run("pointcloud.edit", p).is_ok()
{
@@ -612,6 +625,32 @@ mod tests {
path
}
+ /// Filters are told by place: one gone from under a play moves the next into its place, which
+ /// must not take the play's range, on screen or written when the play ends.
+ #[test]
+ fn a_filter_gone_from_under_a_play_ends_the_play() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ let dir = std::env::temp_dir().join(format!("solidcraft-browser-play-gone-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = layered_segments(&dir);
+ let id = h.app.run("pointcloud.insert", json!({"path": path.to_string_lossy()})).unwrap()["cloud"].as_u64().unwrap();
+ let layer = json!({"property": "layer", "range": [0.0, 2.0]});
+ h.app.run("pointcloud.edit", json!({"cloud": id, "filters": [{"property": "t", "range": [2.0, 5.0]}, layer]})).unwrap();
+ let mut card = super::CloudPanel::new(&h.app, id);
+ card.play = Some(super::Play::new(0, "t".into(), super::Part::High, [2.0, 5.0], [0.0, 10.0], 0.0));
+ h.app.tree.cloud_panel = Some(card);
+ h.frames(2);
+ assert!(h.app.tree.cloud_panel.as_ref().unwrap().play.is_some(), "it plays while its filter is there");
+
+ h.app.run("pointcloud.edit", json!({"cloud": id, "filters": [layer]})).unwrap();
+ h.frames(2);
+ let card = h.app.tree.cloud_panel.as_ref().unwrap();
+ assert!(card.play.is_none() && card.playing(id, 0).is_none(), "the layer filter took its place");
+ assert_eq!(h.app.session.doc.point_clouds[0].filters[0].range(), Some([0.0, 2.0]));
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
#[test]
fn a_filter_track_draws_snaps_steps_frames_and_plays() {
let mut h = crate::scenario::Harness::new();
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 348fced840..10e96890da 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -363,7 +363,7 @@ const MAX_BATCH: usize = 10_000;
/// Commands that load a file: through `engine.execute` they go to the app's file loader
/// (`file_load::control`: off the window thread, with progress and Cancel), which a batch would
/// bypass.
-const LOADS_A_FILE: [&str; 4] = ["doc.open", "file.insert_step", "file.insert_mesh", "pointcloud.insert"];
+const LOADS_A_FILE: [&str; 5] = ["doc.open", "file.insert_step", "file.insert_mesh", "pointcloud.insert", "pointcloud.reload"];
/// Edit in Place, Finish Edit and the next or previous tab go to another design's tab: a batch's
/// rollback, or a script's later steps, would land in the wrong design.
@@ -385,7 +385,7 @@ pub(crate) fn batch_refusal(steps: &[Value]) -> Option<String> {
if let Some((i, c)) = steps.iter().enumerate().find_map(|(i, step)| switches_design(step).map(|c| (i, c))) {
return Some(format!("engine.batch unavailable: step {i} ({c}) switches to another design"));
}
- let (i, c) = steps.iter().enumerate().find_map(|(i, step)| command(step).filter(|c| LOADS_A_FILE.contains(c)).map(|c| (i, c)))?;
+ let (i, c) = steps.iter().enumerate().find_map(|(i, step)| LOADS_A_FILE.into_iter().find(|id| is_command(command(step), id)).map(|c| (i, c)))?;
Some(format!("engine.batch unavailable: step {i} ({c}) loads a file"))
}
@@ -643,24 +643,38 @@ fn dispatch_checked(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &V
/// A command that switches to another design, checked at `level` before it runs: it runs at the
/// app's own level, since the session it leaves and the one it brings in each keep theirs.
fn switch_checked(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value, level: ParamCheck) -> Outcome {
- let id = command(p).unwrap_or_default();
- let issues: Vec<String> = solidcraft_engine::schema::issues(id, p.get("params").unwrap_or(&Value::Null)).into_iter().map(|i| i.message).collect();
- if level == ParamCheck::Strict
- && let Some(first) = issues.first()
- {
- return err(solidcraft_engine::params::bad(id, first.as_str()));
- }
+ let warnings = match contract_check_before_run(command(p).unwrap_or_default(), p.get("params").unwrap_or(&Value::Null), level) {
+ Ok(warnings) => warnings,
+ Err(e) => return err(e),
+ };
let mut out = dispatch(app, ctx, method, p);
- if level == ParamCheck::Warn
- && !issues.is_empty()
- && let Outcome::Done(v) = &mut out
- && let Some(o) = v.get_mut("result").and_then(Value::as_object_mut)
- {
- o.insert("param_warnings".into(), json!(issues));
+ if let Outcome::Done(v) = &mut out {
+ add_param_warnings(v, warnings);
}
out
}
+/// A call's parameters against its command's contract, for a command that does not run on a
+/// session at `level` (one that switches design, one the file loader runs): `Err` refuses the
+/// call, `Ok` holds the warnings for its result.
+pub(crate) fn contract_check_before_run(id: &str, params: &Value, level: ParamCheck) -> Result<Vec<String>, String> {
+ let issues: Vec<String> = solidcraft_engine::schema::issues(id, params).into_iter().map(|i| i.message).collect();
+ match (level, issues.first()) {
+ (ParamCheck::Strict, Some(first)) => Err(solidcraft_engine::params::bad(id, first.as_str()).to_string()),
+ (ParamCheck::Warn, _) => Ok(issues),
+ _ => Ok(Vec::new()),
+ }
+}
+
+/// Add what `contract_check_before_run` found to a reply's result.
+pub(crate) fn add_param_warnings(reply: &mut Value, warnings: Vec<String>) {
+ if !warnings.is_empty()
+ && let Some(o) = reply.get_mut("result").and_then(Value::as_object_mut)
+ {
+ o.insert("param_warnings".into(), json!(warnings));
+ }
+}
+
fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> Outcome {
crate::render_workspace::sync_backend(app);
let s = |k: &str| p.get(k).and_then(Value::as_str);
@@ -2787,6 +2801,11 @@ mod tests {
assert_eq!(v["ok"], false, "{v}");
assert_eq!(v["error"], "engine.batch unavailable: step 1 (doc.open) loads a file", "{v}");
assert_eq!(inspect(&mut h)["bodies"].as_array().map(Vec::len), Some(0), "nothing may run before the refusal");
+ let v = batch(&mut h, json!({"commands": [{"command": "pointcloud.reload", "params": {"cloud": 1}}]}));
+ assert_eq!(v["error"], "engine.batch unavailable: step 0 (pointcloud.reload) loads a file", "{v}");
+ // In any spelling the engine takes.
+ let v = batch(&mut h, json!({"commands": [{"command": "POINTCLOUD.RELOAD", "params": {"cloud": 1}}]}));
+ assert_eq!(v["error"], "engine.batch unavailable: step 0 (pointcloud.reload) loads a file", "{v}");
}
#[test]
diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs
index 041e0dd007..00f5fb3332 100644
--- a/crates/ui-egui/src/file_load.rs
+++ b/crates/ui-egui/src/file_load.rs
@@ -42,6 +42,8 @@ pub enum Kind {
/// Read the active design's linked designs again (`component.update_links`, with the
/// request's options: `component` or `components` reads only those links).
UpdateLinks,
+ /// Read a point cloud's file again (`pointcloud.reload`, with the request's `cloud`).
+ ReloadCloud,
}
pub struct Request {
@@ -65,6 +67,9 @@ pub struct Request {
/// Insert the file as a mesh whatever its extension says: a PLY goes to `pointcloud.insert`
/// unless the person chose Insert Mesh for it (then it needs its faces).
pub mesh: bool,
+ /// The level the caller's own `param_check` named and the warnings it found before the run:
+ /// the reply says both (#9184).
+ pub(crate) param_check: Option<(solidcraft_engine::schema::ParamCheck, Vec<String>)>,
}
impl Request {
@@ -79,11 +84,16 @@ impl Request {
design: None,
chat_turn: None,
mesh: false,
+ param_check: None,
}
}
fn insert(&self) -> bool {
self.kind == Kind::Insert
}
+ /// It reads files the active design already names, and changes that design in place.
+ fn reads_again(&self) -> bool {
+ matches!(self.kind, Kind::UpdateLinks | Kind::ReloadCloud)
+ }
/// The command's parameters: the path and the caller's import options.
fn params(&self) -> Value {
let mut params = self.options.clone();
@@ -99,18 +109,26 @@ impl Request {
Kind::Recover { id, dir } => ("doc.recover", json!({"id": id, "dir": dir})),
Kind::ExportDxf => ("file.export_view_dxf", Value::Object(self.options.clone())),
Kind::UpdateLinks => ("component.update_links", Value::Object(self.options.clone())),
+ Kind::ReloadCloud => ("pointcloud.reload", Value::Object(self.options.clone())),
}
}
fn answer(&self, r: Result<Value, String>) {
if let Some(reply) = &self.reply {
- if crate::control::chat_turn_cancelled(self.chat_turn.as_deref()) {
- let _ = reply.send(crate::control::cancelled_chat_response());
- return;
+ let mut response = if crate::control::chat_turn_cancelled(self.chat_turn.as_deref()) {
+ crate::control::cancelled_chat_response()
+ } else {
+ match r {
+ Ok(v) => json!({"ok": true, "result": v}),
+ Err(e) => json!({"ok": false, "error": e}),
+ }
+ };
+ if let Some((level, warnings)) = &self.param_check {
+ crate::control::add_param_warnings(&mut response, warnings.clone());
+ if let Some(o) = response.as_object_mut() {
+ o.insert("param_check".into(), json!(level.name()));
+ }
}
- let _ = reply.send(match r {
- Ok(v) => json!({"ok": true, "result": v}),
- Err(e) => json!({"ok": false, "error": e}),
- });
+ let _ = reply.send(response);
}
}
}
@@ -332,7 +350,7 @@ pub fn begin_request(app: &mut SolveApp, mut request: Request) -> Result<(), Str
}
r
}
- Kind::UpdateLinks => {
+ Kind::UpdateLinks | Kind::ReloadCloud => {
let (command, params) = request.command();
solidcraft_engine::io::vfs::allowing_hosts(&request.allow_hosts, || app.run(command, params))
}
@@ -398,19 +416,44 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio
if cfg!(target_arch = "wasm32") || !matches!(req.method.as_str(), "engine.execute" | "command") {
return Some(req);
}
- let command = req.params.get("command").or(req.params.get("id")).and_then(Value::as_str);
- let kind = match command {
- Some("doc.open") => Kind::Open,
- Some("file.insert_step" | "file.insert_mesh" | "pointcloud.insert") => Kind::Insert,
- Some("file.export_view_dxf") => Kind::ExportDxf,
+ // In any spelling the engine takes: another would run on the window thread.
+ let Some(id) =
+ req.params.get("command").or(req.params.get("id")).and_then(Value::as_str).and_then(solidcraft_engine::find_command).map(|spec| spec.id)
+ else {
+ return Some(req);
+ };
+ let kind = match id {
+ "doc.open" => Kind::Open,
+ "file.insert_step" | "file.insert_mesh" | "pointcloud.insert" => Kind::Insert,
+ "file.export_view_dxf" => Kind::ExportDxf,
+ "pointcloud.reload" => Kind::ReloadCloud,
_ => return Some(req),
};
let params = req.params.get("params");
let path = match params.and_then(|p| p.get("path")).and_then(Value::as_str) {
Some(path) => path,
- None if kind == Kind::ExportDxf => "",
+ None if matches!(kind, Kind::ExportDxf | Kind::ReloadCloud) => "",
None => return Some(req),
};
+ // This never reaches `control::handle`, so the request's own `param_check` is taken here. The
+ // worker's session goes on to be the design's, which keeps its own level: the check comes first.
+ let level = match crate::control::request_param_check(&req.method, &req.params) {
+ Ok(level) => level,
+ Err(e) => {
+ let _ = req.reply.send(json!({"ok": false, "error": e}));
+ return None;
+ }
+ };
+ let param_check = match level
+ .map(|level| crate::control::contract_check_before_run(id, params.unwrap_or(&Value::Null), level).map(|found| (level, found)))
+ .transpose()
+ {
+ Ok(param_check) => param_check,
+ Err(e) => {
+ let _ = req.reply.send(json!({"ok": false, "error": e, "param_check": level.map(|level| level.name())}));
+ return None;
+ }
+ };
let scope = match crate::control::request_scope(app, &req.params) {
Ok(scope) => scope,
Err(e) => {
@@ -421,7 +464,7 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio
// Everything but the path, as given: taking only `up` and `names` dropped an import's
// `matrix` and `name`, so it landed at the origin with nothing said (#4676).
let mut options = params.and_then(Value::as_object).cloned().unwrap_or_default();
- if kind != Kind::ExportDxf {
+ if !matches!(kind, Kind::ExportDxf | Kind::ReloadCloud) {
options.remove("path");
options.retain(|_, v| !v.is_null());
}
@@ -435,6 +478,7 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio
design: None,
chat_turn: req.chat_turn,
mesh: false,
+ param_check,
};
let _ = begin_request(app, request);
None
@@ -495,7 +539,7 @@ fn start(app: &mut SolveApp) {
}
let insert = request.insert();
let before = if insert { crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() };
- let update = request.kind == Kind::UpdateLinks;
+ let update = request.reads_again();
let mut scratch = if insert || update || request.kind == Kind::ExportDxf { app.session.scratch() } else { Session::default() };
// A design opened or recovered here is run through the host's pre-command check too, and
// evaluated under the user's validation mode.
@@ -1075,13 +1119,21 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
request.answer(Ok(made.result));
}
_ if running.cancelled() => request.answer(Err("file operation cancelled".into())),
- Ok(made) if request.kind == Kind::UpdateLinks && running.matches(&app.session) => {
+ Ok(made) if request.reads_again() && running.matches(&app.session) => {
let (id, _) = request.command();
app.session.accept_computed(made.session);
app.big_operation = true;
- crate::linked_source::read_again(app, &request.options, &made.result);
+ if request.kind == Kind::UpdateLinks {
+ crate::linked_source::read_again(app, &request.options, &made.result);
+ }
let r = Ok(made.result);
app.finish_command(id, &r);
+ // The reload is its own undo step: the open card folds only what comes after it.
+ if request.kind == Kind::ReloadCloud
+ && let Some(panel) = app.tree.cloud_panel.as_mut()
+ {
+ panel.depth = app.session.undo.len();
+ }
let language = crate::i18n::Locale::for_language(&app.preferences.language);
app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label(id)))]), false);
// A design it could not read is said as when that was all it was asked.
@@ -1089,6 +1141,12 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
let (name, why) = (f["name"].as_str().unwrap_or_default(), f["error"].as_str().unwrap_or_default());
app.set_status(format!("{name}: {why}"), true);
}
+ // What the file's reading left out is said too.
+ if let Some(w) =
+ r.as_ref().ok().filter(|_| request.kind == Kind::ReloadCloud).and_then(|v| v["warnings"].as_array()).and_then(|w| w.first())
+ {
+ app.set_status(w.as_str().unwrap_or_default().to_string(), false);
+ }
request.answer(r);
}
Ok(_) if reuse_open(app, request) => {}
@@ -1177,7 +1235,7 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
}
Err(e) => {
request.answer(Err(e.clone()));
- if request.kind == Kind::UpdateLinks {
+ if request.reads_again() {
// Said as when the command ran here (the status line, the run's messages).
app.finish_command(request.command().0, &Err(e));
} else if let Kind::Recover { id, dir } = &request.kind {
@@ -1267,6 +1325,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
None => app.session.doc.name.clone(),
},
+ Kind::ReloadCloud => app.session.doc.name.clone(),
_ => 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);
@@ -1311,6 +1370,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
Kind::Recover { .. } => "file_load.recovering",
Kind::ExportDxf => "dxf.exporting",
Kind::UpdateLinks => "file_load.updating_links",
+ Kind::ReloadCloud => "file_load.reloading_cloud",
})
};
let icon = match r.request.kind {
@@ -1319,6 +1379,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
Kind::Recover { .. } => "restore",
Kind::ExportDxf => "export",
Kind::UpdateLinks => "update",
+ Kind::ReloadCloud => "import",
};
let (closed, action) = ui_kit::Window::new(card_id, icon, title)
.cards(((cover.width() - 16.0) / crate::theme::Tokens::get().form_card_width).clamp(0.5, 1.3))
diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rs
index 7e2489602f..3ed4f8ec9d 100644
--- a/crates/ui-egui/src/file_load_ui_tests.rs
+++ b/crates/ui-egui/src/file_load_ui_tests.rs
@@ -255,6 +255,126 @@ fn update_links_names_the_design_it_reads_while_the_window_draws() {
let _ = std::fs::remove_dir_all(&dir);
}
+/// Reload from file reads beside the window, as an insert does: the design waits, Cancel changes
+/// nothing, and a file that is gone is said in the status line.
+#[test]
+fn reloading_a_point_cloud_runs_off_the_window_thread() {
+ let dir = scratch("reload-cloud");
+ let path = dir.join("scan.xyz");
+ std::fs::write(&path, "0 0 0\n1 0 0\n").unwrap();
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ let id = h.app.run("pointcloud.insert", json!({"path": path})).unwrap()["cloud"].as_u64().unwrap();
+ h.app.tree.cloud_panel = Some(crate::browser::CloudPanel::new(&h.app, id));
+ h.frames(4);
+ std::fs::write(&path, "0 0 0\n1 0 0\n2 0 0\n").unwrap();
+ let points = |app: &SolveApp| app.session.doc.point_clouds[0].len();
+ let until_idle = |h: &mut crate::scenario::Harness| {
+ let began = std::time::Instant::now();
+ while !h.app.file_load.idle() {
+ assert!(began.elapsed() < std::time::Duration::from_secs(120), "the reload went on");
+ h.frames(1);
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ }
+ h.frames(3);
+ };
+ let hold = |h: &mut crate::scenario::Harness| {
+ let (started_tx, started_rx) = std::sync::mpsc::channel();
+ let (release_tx, release_rx) = std::sync::mpsc::channel();
+ h.app.file_load.worker_gate = Some((started_tx, release_rx));
+ (started_rx, release_tx)
+ };
+
+ // The card's button: held on its worker, the window draws and the design waits.
+ let design = h.app.session.doc.clone();
+ let (started, release) = hold(&mut h);
+ // Frame by frame: a scenario step would wait for the file operation it starts.
+ let [x, y] = h.widget(crate::i18n::tr("ui.point_cloud_reload")).expect("the card offers a reload");
+ let at = pos2(x as f32, y as f32);
+ let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
+ for event in [Event::PointerMoved(at), button(true), button(false)] {
+ h.frame_with(vec![event]);
+ }
+ let worker = started.recv_timeout(std::time::Duration::from_secs(60)).expect("the worker started");
+ assert_ne!(worker, std::thread::current().id());
+ h.frames(3);
+ assert!(h.widget("Reloading point cloud").is_some(), "the overlay says what runs");
+ assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &design), "the design waits");
+ // Cancel keeps it as it was.
+ h.app.file_load.cancel();
+ drop(release);
+ until_idle(&mut h);
+ assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &design), "a cancelled reload changes nothing");
+
+ // Run through, it brings the new points in, and says it is done, in one undo step.
+ let r = crate::file_load::begin_request(&mut h.app, {
+ let mut request = crate::file_load::Request::new("", crate::file_load::Kind::ReloadCloud);
+ request.options.insert("cloud".into(), json!(id));
+ request
+ });
+ assert!(r.is_ok() && h.app.file_load.busy());
+ until_idle(&mut h);
+ assert_eq!(points(&h.app), 3);
+ assert_eq!(h.app.status.as_ref().map(|s| s.0.as_str()), Some("Reload Point Cloud done"));
+ // The open card folds its edits from here on, so an edit does not take the reload with it.
+ assert_eq!(h.app.tree.cloud_panel.as_ref().map(|p| p.depth), Some(h.app.session.undo.len()));
+ h.app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(points(&h.app), 2);
+
+ // A file that is gone: said, and the design is as it was.
+ std::fs::remove_file(&path).unwrap();
+ let design = h.app.session.doc.clone();
+ let mut request = crate::file_load::Request::new("", crate::file_load::Kind::ReloadCloud);
+ request.options.insert("cloud".into(), json!(id));
+ crate::file_load::begin_request(&mut h.app, request).unwrap();
+ until_idle(&mut h);
+ assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &design));
+ let status = h.app.status.as_ref().map(|s| s.0.clone()).unwrap_or_default();
+ assert!(status.contains("scan.xyz"), "{status}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// A request's own `param_check` (#9184) holds on a command the file loader runs, which never
+/// reaches `control::handle`: a word that is no level is refused, `strict` refuses a broken call
+/// before the file is read, `warn` reads it and says what it found, and every reply says the level.
+/// Any spelling the engine takes goes to the file loader too.
+#[test]
+fn a_file_load_is_checked_at_the_requests_own_level() {
+ let dir = scratch("reload-check");
+ let path = dir.join("scan.xyz");
+ std::fs::write(&path, "0 0 0\n1 0 0\n").unwrap();
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ let id = h.app.run("pointcloud.insert", json!({"path": path})).unwrap()["cloud"].as_u64().unwrap();
+ std::fs::write(&path, "0 0 0\n1 0 0\n2 0 0\n").unwrap();
+ let points = |app: &SolveApp| app.session.doc.point_clouds[0].len();
+ let misspelt = |level: &str| json!({"command": "pointcloud.reload", "params": {"cloud": id, "clowd": 1}, "param_check": level});
+
+ let (v, _) = h.call_queued("engine.execute", misspelt("loud"));
+ assert!(v["ok"] == false && v["error"].as_str().is_some_and(|e| e.contains("`param_check` must be off, warn or strict")), "{v}");
+ let (v, _) = h.call_queued("engine.execute", misspelt("strict"));
+ assert_eq!((&v["ok"], &v["param_check"]), (&json!(false), &json!("strict")), "{v}");
+ assert!(v["error"].as_str().is_some_and(|e| e.contains("clowd")), "{v}");
+ assert_eq!(points(&h.app), 2, "refused unread");
+
+ let (v, _) = h.call_queued("engine.execute", misspelt("warn"));
+ assert_eq!((&v["ok"], &v["param_check"]), (&json!(true), &json!("warn")), "{v}");
+ assert!(v["result"]["param_warnings"][0].as_str().is_some_and(|w| w.contains("clowd")), "{v}");
+ assert_eq!(points(&h.app), 3);
+
+ // Asked nothing, told nothing; the worker's thread shows the file loader took this spelling.
+ std::fs::write(&path, "0 0 0\n1 0 0\n2 0 0\n3 0 0\n").unwrap();
+ let (started_tx, started) = std::sync::mpsc::channel();
+ let (release, release_rx) = std::sync::mpsc::channel();
+ release.send(()).unwrap();
+ h.app.file_load.worker_gate = Some((started_tx, release_rx));
+ let (v, _) = h.call_queued("engine.execute", json!({"command": "POINTCLOUD.RELOAD", "params": {"cloud": id}}));
+ assert_eq!((&v["ok"], v.get("param_check")), (&json!(true), None), "{v}");
+ assert_ne!(started.try_recv().expect("the file loader ran it"), std::thread::current().id());
+ assert_eq!(points(&h.app), 4);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
/// A design may link to a file on another computer (`\\host\share\…`); on Windows reading it, or
/// only asking whether it is there, connects to that computer and may send it the user's sign-in.
/// Update Links and Open Linked Design ask first, naming the server: Cancel reads nothing, Allow
@@ -332,6 +452,58 @@ fn update_links_and_open_linked_design_ask_before_a_network_location() {
let _ = std::fs::remove_dir_all(&dir);
}
+/// Reload from file on a cloud whose file a design names on another computer asks first, naming
+/// the server; Cancel reads nothing, and a local file does not ask.
+#[test]
+fn reloading_a_point_cloud_on_a_network_location_asks_first() {
+ use crate::network_prompt::{Answer, NetworkPrompt, Then, answer, reload_cloud};
+ let dir = scratch("reload-cloud-network");
+ let path = dir.join("scan.xyz");
+ std::fs::write(&path, "0 0 0\n1 0 0\n").unwrap();
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ let id = h.app.run("pointcloud.insert", json!({"path": path})).unwrap()["cloud"].as_u64().unwrap();
+ let local = h.app.session.doc.point_clouds[0].source.clone();
+ let until_idle = |h: &mut crate::scenario::Harness| {
+ let began = std::time::Instant::now();
+ while !h.app.file_load.idle() {
+ assert!(began.elapsed() < std::time::Duration::from_secs(120), "the reload went on");
+ h.frames(1);
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ }
+ h.frames(3);
+ };
+
+ let crafted = r"\\evil.example\share\scan.xyz";
+ h.app.session.doc_mut().point_clouds[0].source = crafted.into();
+ let design = h.app.session.doc.clone();
+ reload_cloud(&mut h.app, id, crafted);
+ assert_eq!(h.app.network_prompt, Some(NetworkPrompt { hosts: vec!["evil.example".into()], then: Then::ReloadCloud(id) }));
+ assert!(h.app.file_load.idle(), "nothing is read while it asks");
+ answer(&mut h.app, Answer::Cancel);
+ h.frames(2);
+ assert!(h.app.network_prompt.is_none() && h.app.file_load.idle());
+ assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &design), "Cancel changes nothing");
+
+ // Allow once holds for that reload alone, and the preferences keep nothing.
+ reload_cloud(&mut h.app, id, crafted);
+ answer(&mut h.app, Answer::Once);
+ assert!(!h.app.file_load.idle(), "the file operation runs");
+ until_idle(&mut h);
+ assert!(h.app.preferences.network_hosts.is_empty());
+ let refused = h.app.session.execute("pointcloud.reload", &json!({"cloud": id})).unwrap_err().to_string();
+ assert!(refused.contains("evil.example") && refused.contains("Reload from file"), "{refused}");
+
+ // A local file does not ask.
+ h.app.session.doc_mut().point_clouds[0].source = local.clone();
+ std::fs::write(&path, "0 0 0\n1 0 0\n2 0 0\n").unwrap();
+ reload_cloud(&mut h.app, id, &local);
+ assert!(h.app.network_prompt.is_none());
+ until_idle(&mut h);
+ assert_eq!(h.app.session.doc.point_clouds[0].len(), 3);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
/// A control-channel (MCP) open is answered when the file is in, with the synchronous
/// command's reply, and the window draws frames while it waits. Commands sent meanwhile wait.
#[test]
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index e50de1b8b5..3ac9441552 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -693,7 +693,7 @@ pub struct SolveApp {
pub lock_prompts: Vec<open_elsewhere::LockPrompt>,
/// A Save waiting for "the file changed on disk" to be answered.
pub disk_prompt: bool,
- /// Update Links or Open Linked Design waiting for a network server to be allowed.
+ /// Update Links, Open Linked Design or Reload from file waiting for a network server to be allowed.
pub network_prompt: Option<network_prompt::NetworkPrompt>,
/// Designs left by crashed apps, offered for recovery.
pub recoverable: Vec<solidcraft_engine::recovery::Entry>,
diff --git a/crates/ui-egui/src/network_prompt.rs b/crates/ui-egui/src/network_prompt.rs
index 5bf818576e..40fbad2e25 100644
--- a/crates/ui-egui/src/network_prompt.rs
+++ b/crates/ui-egui/src/network_prompt.rs
@@ -1,13 +1,15 @@
-//! Files a design names on another computer: a linked design on `\\host\share`. On Windows,
-//! reading such a file, or only asking whether it exists, connects to that computer and may send
-//! it the user's Windows sign-in, so the engine refuses those paths until the server is allowed
-//! (`vfs::design_path_refusal`). Update Links and Open Linked Design ask first, naming the
-//! server: Allow once, Always allow this server (Preferences › Design), or Cancel.
+//! Files a design names on another computer: a linked design or a point cloud's file on
+//! `\\host\share`. On Windows, reading such a file, or only asking whether it exists, connects to
+//! that computer and may send it the user's Windows sign-in, so the engine refuses those paths
+//! until the server is allowed (`vfs::design_path_refusal`). Update Links, Open Linked Design and
+//! Reload from file ask first, naming the server: Allow once, Always allow this server
+//! (Preferences › Design), or Cancel.
//!
//! Only these user actions ask. Commands run programmatically or by an agent never prompt: they
//! get the engine's error, and `component.links` reports such a link's `found` as unknown.
use serde_json::Value;
+use solidcraft_engine::io::vfs::{Remote, design_path_refusal};
use crate::SolveApp;
use crate::ui_kit;
@@ -19,6 +21,9 @@ pub enum Then {
UpdateLinks,
/// Open Linked Design: open this file.
OpenLinked(String),
+ /// Reload from file: read this point cloud's file again (`pointcloud.reload`, off the window
+ /// thread).
+ ReloadCloud(u64),
}
/// A user action waiting for its network servers to be allowed.
@@ -81,6 +86,17 @@ pub(crate) fn open_linked(app: &mut SolveApp, link: &Value) {
app.open_path_async(file);
}
+/// Reload from file on the Edit Point Cloud card: ask first when the cloud's file (`source`) is on
+/// a server not allowed yet. A path that is refused for good says so through the command's error.
+pub(crate) fn reload_cloud(app: &mut SolveApp, cloud: u64, source: &str) {
+ let design = app.session.path.as_deref();
+ if let Some(Remote::Network(host)) = design_path_refusal(source, design) {
+ app.network_prompt = Some(NetworkPrompt { hosts: vec![host], then: Then::ReloadCloud(cloud) });
+ } else {
+ run(app, Vec::new(), Then::ReloadCloud(cloud));
+ }
+}
+
/// Run the action with `hosts` allowed for it alone.
fn run(app: &mut SolveApp, hosts: Vec<String>, then: Then) {
match then {
@@ -91,6 +107,13 @@ fn run(app: &mut SolveApp, hosts: Vec<String>, then: Then) {
}
// Opening a file reads only it, as File › Open does; the design it opens is checked anew.
Then::OpenLinked(file) => app.open_path_async(&file),
+ Then::ReloadCloud(cloud) => {
+ let mut request = crate::file_load::Request::new("", crate::file_load::Kind::ReloadCloud);
+ request.options.insert("cloud".into(), serde_json::json!(cloud));
+ request.allow_hosts = hosts;
+ // An error is said in the status line, as for any file operation.
+ let _ = crate::file_load::begin_request(app, request);
+ }
}
}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 942fc840c9..52393502d8 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -554,8 +554,10 @@ contracts at that level, whatever the app's own (which is `off`), as a headless
`param_warnings` to its result; `strict` refuses it (a batch before its first step), and the
design is left as it was. Every reply to such a request says the level it was checked at as
`param_check`, beside `ok`. A command that switches to another design (`component.edit_in_place`,
-`component.finish_edit`, `view.next_tab`, `view.previous_tab`) has its parameters checked at
-that level before it runs, and then runs at the app's own level, as each design keeps its own.
+`component.finish_edit`, `view.next_tab`, `view.previous_tab`), or one that goes to the file
+loader (`doc.open`, `file.insert_step`, `file.insert_mesh`, `file.export_view_dxf`,
+`pointcloud.insert`, `pointcloud.reload`), has its parameters checked at that level before it
+runs, and then runs at the app's own level, as each design keeps its own.
Any other word is refused; other methods ignore the field. An app older than this ignores the field and its reply has no
`param_check`, so a client that needs the check asks `control.capabilities` first and treats a
reply without `param_check` as unchecked. The bridged MCP server asks once per connection
@@ -567,7 +569,7 @@ reply without `param_check` as unchecked. The bridged MCP server asks once per c
|---|---|---|
| `engine.execute` | `command`: command id, `params`: JSON object | the command's result |
| `engine.script` | `commands`: `[{command, params}, …]` | results, stops at the first error |
-| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`, `coalesce_parameters?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back, `rolled_back`: whether the design is back as it was, `false` only when the checkpoint could not restore it). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown, when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`) or when it goes to another design's tab (`component.edit_in_place`, `component.finish_edit`, which `engine.script` refuses too). Send such steps one by one. A step the batch would certainly refuse at its turn is found before the first step runs (#5853): a step without a command, an unknown command id (with the closest ids) or, with strict parameter checking, a call that breaks its command's contract. The reply is then that step's failure with `completed: 0`, `undone: 0`, `not_run` listing every step and a `note`; nothing has run. With `coalesce_parameters`, each run of consecutive plain parameter edits (`parameters.change` with only a name and an expression, or with `changes`) is set as one `parameters.change {changes}`, so the design rebuilds once for the run. Every step still gets its own result (with `coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits: an edit that would be refused on its own, but not once the run's later edits are in, goes through. A run whose combined edit is refused (a new parameter, a bad expression) runs step by step, so the refused step is named. Answered when done, for up to 3600 s |
+| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`, `coalesce_parameters?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back, `rolled_back`: whether the design is back as it was, `false` only when the checkpoint could not restore it). Refused before anything runs, with an error starting `engine.batch unavailable`, when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`, `pointcloud.insert`, `pointcloud.reload`) or when it goes to another design's tab (`component.edit_in_place`, `component.finish_edit`, which `engine.script` refuses too). Send such steps one by one. A step the batch would certainly refuse at its turn is found before the first step runs (#5853): a step without a command, an unknown command id (with the closest ids) or, with strict parameter checking, a call that breaks its command's contract. The reply is then that step's failure with `completed: 0`, `undone: 0`, `not_run` listing every step and a `note`; nothing has run. With `coalesce_parameters`, each run of consecutive plain parameter edits (`parameters.change` with only a name and an expression, or with `changes`) is set as one `parameters.change {changes}`, so the design rebuilds once for the run. Every step still gets its own result (with `coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits: an edit that would be refused on its own, but not once the run's later edits are in, goes through. A run whose combined edit is refused (a new parameter, a bad expression) runs step by step, so the refused step is named. Answered when done, for up to 3600 s |
| `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut (the user's current first key, or null when cleared), params doc, enabled |
| `document.revision` | — | `{document_id, revision}`: the active design's id and a number that moves whenever the design changes, for programs that follow it ([Following the design](#following-the-design)) |
| `control.subscribe` | — | `{document_id, revision}`, as `document.revision`; the connection is then sent a `design.changed` line whenever they change ([Following the design](#following-the-design)) |
diff --git a/docs/point-clouds.md b/docs/point-clouds.md
index 42768d86c6..9ff04bbabe 100644
--- a/docs/point-clouds.md
+++ b/docs/point-clouds.md
@@ -20,6 +20,22 @@ says what it is; the default is millimetres, as for every other import. Lidar an
usually in metres. The unit can be changed afterwards (Browser › Point Clouds › Edit Point Cloud,
or `pointcloud.edit` with `units`): the points are scaled from the unit they came in as.
+## Reloading
+
+A cloud remembers where its file was (`source`, the absolute path it was inserted from), so a
+file that changed can be read again: **Reload from file** in the Edit Point Cloud card, or
+`pointcloud.reload`. The points, colours, segments, triangles and properties are replaced; the
+name, placement, units, point size and colouring are kept, and so are the filters on properties
+the file still has. A filter on a set of named values goes when the file no longer names them.
+Colouring by a property the file no longer has goes back to the file's colours. The file is read
+under the limit the cloud was inserted with (`max_points`), so the same file reads as the very
+same points and a file that grew comes in whole unless it exceeds that limit, when it is thinned
+as an insert would thin it. The file is read beside the window, with
+progress and Cancel. A cloud opened from a design saved before it remembered its file cannot be
+reloaded. A file on another computer (`\\host\share`) is treated as a linked design's is:
+**Reload from file** asks before it connects to that server, and `pointcloud.reload` is refused
+until the server is allowed in Preferences.
+
## Colours
**Color By** in the Edit Point Cloud card (or `color_by`) says how the points are coloured:
@@ -109,8 +125,9 @@ file as a binary part (12 bytes a point, 3 more with colours).
- `pointcloud.edit` — `cloud` (id or name); `name?`, `visible?`, `point_size?`, `color_by?`,
`color?`, `color_range?`, `filters?`, `units?`, `matrix?` (a rigid placement, as
`occurrence.move` takes it).
+- `pointcloud.reload` — `cloud`; reads its file again (see [Reloading](#reloading)).
- `pointcloud.delete`.
-- `pointcloud.list` — each cloud with its segment and triangle counts, its properties (name, whole-numbered or not, span, named
+- `pointcloud.list` — each cloud with its `source`, its segment and triangle counts, its properties (name, whole-numbered or not, span, named
values), its filters and its ramp's range as drawn (`color_range`).
- `doc.open` opens a point cloud file as a new design holding it; dropping one on the window
adds it to the open design.
diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT
index 197b46cbe2..fd6fb6dcb2 100644
--- a/tests/kernel-cases/EXEMPT
+++ b/tests/kernel-cases/EXEMPT
@@ -146,6 +146,7 @@ pointcloud.delete point clouds: points drawn, never a body
pointcloud.edit point clouds: points drawn, never a body
pointcloud.insert point clouds: points drawn, never a body
pointcloud.list point clouds: points drawn, never a body
+pointcloud.reload point clouds: points drawn, never a body; tested in crates/engine/src/cmd/point_cloud.rs
render.aging.describe rendering: images, cameras, stages
render.backends rendering: images, cameras, stages
render.batch rendering: images, cameras, stages