Skip to content

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

Canvas: lock a reference image so it cannot be moved or deleted by mistake while sketching (#12310) (#12713)

PaddleStroke4f687454fc47
diff --git a/assets/locales/pending/canvas-lock.json b/assets/locales/pending/canvas-lock.json
new file mode 100644
index 0000000000..9f6ff3a901
--- /dev/null
+++ b/assets/locales/pending/canvas-lock.json
@@ -0,0 +1,10 @@
+{
+ "en": { "browser.canvas_locked": "The canvas is locked. Unlock it first." },
+ "ar": { "browser.canvas_locked": "اللوحة مقفلة. ألغِ قفلها أولاً." },
+ "de": { "browser.canvas_locked": "Die Leinwand ist gesperrt. Entsperren Sie sie zuerst." },
+ "he": { "browser.canvas_locked": "הקנבס נעול. בטל את הנעילה תחילה." },
+ "ja": { "browser.canvas_locked": "キャンバスはロックされています。先にロックを解除してください。" },
+ "ko": { "browser.canvas_locked": "캔버스가 잠겨 있습니다. 먼저 잠금을 해제하세요." },
+ "vi": { "browser.canvas_locked": "Canvas đang bị khóa. Hãy mở khóa trước." },
+ "zh": { "browser.canvas_locked": "画布已锁定。请先解锁。" }
+}
diff --git a/crates/doc/src/canvas.rs b/crates/doc/src/canvas.rs
index dd52be0316..95becebb53 100644
--- a/crates/doc/src/canvas.rs
+++ b/crates/doc/src/canvas.rs
@@ -37,6 +37,10 @@ pub struct Canvas {
pub flip: bool,
#[serde(default = "yes")]
pub visible: bool,
+ /// Locked (#12310): its place, size, angle and flip stay as they are, and it is not deleted,
+ /// until it is unlocked. Its opacity, visibility and name can still change.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub locked: bool,
/// The component it belongs to (its plane is in that component's frame, so it moves with
/// the component's occurrence); 0 = the root.
#[serde(default, skip_serializing_if = "is_root")]
diff --git a/crates/doc/src/format/pending/canvas-lock.rs b/crates/doc/src/format/pending/canvas-lock.rs
new file mode 100644
index 0000000000..a2bf4518e9
--- /dev/null
+++ b/crates/doc/src/format/pending/canvas-lock.rs
@@ -0,0 +1,4 @@
+//! A canvas can be locked (#12310): `locked: true` on the canvas keeps its place, size, angle and
+//! flip, and keeps it from being deleted, until it is unlocked. Older designs need no
+//! transformation: without the field a canvas is unlocked, as before. The last release warns about
+//! the newer format number and opens the design with its canvases unlocked.
diff --git a/crates/engine/src/cmd/delete.rs b/crates/engine/src/cmd/delete.rs
index f000d14a86..f435cd52f4 100644
--- a/crates/engine/src/cmd/delete.rs
+++ b/crates/engine/src/cmd/delete.rs
@@ -211,6 +211,11 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
}
for k in keys(p, "canvases") {
+ // A locked canvas stays (#12310), as a locked body does.
+ if let Some(c) = s.doc.canvases.iter().find(|c| c.id.to_string() == k || c.name == k).filter(|c| c.locked) {
+ skip(super::sketch_canvas::locked_reason(c));
+ continue;
+ }
sub(s, "canvas.delete", json!({ "canvas": k }))?;
done = true;
}
diff --git a/crates/engine/src/cmd/sketch_canvas.rs b/crates/engine/src/cmd/sketch_canvas.rs
index c732700391..4046ba93f9 100644
--- a/crates/engine/src/cmd/sketch_canvas.rs
+++ b/crates/engine/src/cmd/sketch_canvas.rs
@@ -43,7 +43,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("canvas")
.contract(&EDIT_CONTRACT)
.output(output_schema_for::<CanvasEdited>)
- .params("canvas: id or name; center?, width?, angle?: deg, opacity?, flip?, visible?, name?"),
+ .params("canvas: id or name; center?, width?, angle?: deg, opacity?, flip?, visible?, name?, locked? (a locked canvas refuses center, width, angle, flip, Calibrate and Delete)"),
CommandSpec::new("canvas.calibrate", "Calibrate Canvas", crate::checked!("canvas.calibrate", calibrate))
.icon("measure")
.contract(&CALIBRATE_CONTRACT)
@@ -109,6 +109,7 @@ fn make(s: &mut Session, p: &Value, cmd: &str, decal: bool) -> Result<Value> {
opacity,
flip: bool_(p, "flip").unwrap_or(false),
visible: true,
+ locked: false,
component,
});
canvas_reply(cmd, CanvasPlaced { canvas: id, name, pixels, param_warnings: Vec::new() })
@@ -139,6 +140,19 @@ fn find(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
s.doc.canvases.iter().position(|c| c.id.to_string() == key || c.name == key).ok_or_else(|| bad(cmd, format!("no canvas `{key}`")))
}
+/// A locked canvas (#12310) keeps its place and is not deleted: the refusal names it.
+fn refuse_locked(s: &Session, i: usize, cmd: &str) -> Result<()> {
+ match s.doc.canvases.get(i) {
+ Some(c) if c.locked => Err(bad(cmd, locked_reason(c))),
+ _ => Ok(()),
+ }
+}
+
+/// Why a locked canvas is left as it is.
+pub(crate) fn locked_reason(c: &Canvas) -> String {
+ format!("{} is locked; unlock it first", c.name)
+}
+
fn edit_canvas(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "canvas.edit";
let i = find(s, p, cmd)?;
@@ -146,7 +160,15 @@ fn edit_canvas(s: &mut Session, p: &Value) -> Result<Value> {
if width.is_some_and(|w| !(w > 1e-6 && w < 1e7)) {
return Err(bad(cmd, "`width` must be positive"));
}
+ // Unlocking in the same call lets the other changes through.
+ let moves = ["center", "width", "angle", "flip"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
+ if moves && bool_(p, "locked") != Some(false) {
+ refuse_locked(s, i, cmd)?;
+ }
let c = s.doc_mut().canvases.get_mut(i).ok_or_else(|| bad(cmd, "canvas"))?;
+ if let Some(l) = bool_(p, "locked") {
+ c.locked = l;
+ }
if let Some(v) = p.get("center").and_then(vec2) {
c.center = v;
}
@@ -182,6 +204,7 @@ fn calibrate(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "the points must differ"));
}
let k = d / now;
+ refuse_locked(s, i, cmd)?;
let c = s.doc_mut().canvases.get_mut(i).ok_or_else(|| bad(cmd, "canvas"))?;
c.width *= k;
c.center = a + (c.center - a) * k;
@@ -191,6 +214,7 @@ fn calibrate(s: &mut Session, p: &Value) -> Result<Value> {
fn delete_canvas(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "canvas.delete";
let i = find(s, p, cmd)?;
+ refuse_locked(s, i, cmd)?;
let c = s.doc_mut().canvases.remove(i);
canvas_reply(cmd, CanvasDeleted { deleted: c.id, param_warnings: Vec::new() })
}
@@ -223,6 +247,48 @@ mod tests {
assert!(s.execute("canvas.edit", &json!({"canvas": first, "width": 500})).is_err());
}
+ /// A locked canvas (#12310) refuses a move, a resize, a turn, a flip, Calibrate and Delete,
+ /// keeps taking opacity, visibility and a new name, is saved locked, and moves again once
+ /// unlocked. Delete of a selection with it deletes the rest and says why it stayed.
+ #[test]
+ fn a_locked_canvas_keeps_its_place_and_is_not_deleted() {
+ let mut s = Session::default();
+ let id = s.execute("canvas.insert", &json!({"data": png(10, 10), "width": 50})).unwrap()["canvas"].as_u64().unwrap();
+ let other = s.execute("canvas.insert", &json!({"data": png(10, 10)})).unwrap()["canvas"].as_u64().unwrap();
+ s.execute("canvas.edit", &json!({"canvas": id, "locked": true})).unwrap();
+ let locked = s.doc.canvases[0].clone();
+ assert!(locked.locked);
+ for p in [
+ json!({"canvas": id, "center": [5, 5]}),
+ json!({"canvas": id, "width": 80}),
+ json!({"canvas": id, "angle": 30}),
+ json!({"canvas": id, "flip": true}),
+ json!({"canvas": id, "locked": true, "width": 80}),
+ ] {
+ let e = s.execute("canvas.edit", &p).unwrap_err().to_string();
+ assert!(e.contains("Canvas1 is locked"), "{p}: {e}");
+ }
+ assert!(s.execute("canvas.calibrate", &json!({"canvas": id, "a": [0, 0], "b": [10, 0], "distance": 20})).is_err());
+ assert!(s.execute("canvas.delete", &json!({"canvas": id})).is_err());
+ assert_eq!(s.doc.canvases[0], locked, "nothing changed");
+ s.execute("canvas.edit", &json!({"canvas": id, "opacity": 0.9, "visible": false, "name": "Blueprint"})).unwrap();
+ assert!(s.doc.canvases[0].locked && !s.doc.canvases[0].visible && s.doc.canvases[0].name == "Blueprint");
+ // Saved locked; a design without the field opens unlocked.
+ let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
+ assert!(back.canvases[0].locked && !back.canvases[1].locked);
+ assert!(serde_json::to_value(&s.doc.canvases[1]).unwrap().get("locked").is_none(), "an unlocked canvas saves as before");
+ // Delete of both deletes the unlocked one and names the locked one.
+ let r = s.execute("selection.delete", &json!({"canvases": [id, other]})).unwrap();
+ assert_eq!(r["skipped"], json!(["Blueprint is locked; unlock it first"]));
+ assert_eq!(s.doc.canvases.iter().map(|c| c.id).collect::<Vec<_>>(), [id]);
+ assert!(s.execute("selection.delete", &json!({"canvases": [id]})).is_err());
+ // Unlocking in the same call lets the move through.
+ s.execute("canvas.edit", &json!({"canvas": id, "locked": false, "width": 80})).unwrap();
+ assert!(!s.doc.canvases[0].locked && (s.doc.canvases[0].width - 80.0).abs() < 1e-12);
+ s.execute("canvas.delete", &json!({"canvas": id})).unwrap();
+ assert!(s.doc.canvases.is_empty());
+ }
+
#[test]
fn canvas_insert_edit_calibrate_save() {
let mut s = Session::default();
diff --git a/crates/engine/src/schema/canvas.rs b/crates/engine/src/schema/canvas.rs
index ef193c3132..5f6d1acd8c 100644
--- a/crates/engine/src/schema/canvas.rs
+++ b/crates/engine/src/schema/canvas.rs
@@ -147,6 +147,10 @@ pub struct CanvasEditParams {
/// Its new name; blank text keeps the name.
#[serde(default)]
pub name: Option<String>,
+ /// Lock it or unlock it. A locked canvas refuses a new centre, width, angle or flip, Calibrate
+ /// and Delete until it is unlocked; its opacity, visibility and name can still change.
+ #[serde(default)]
+ pub locked: Option<bool>,
}
/// Scale a canvas so that two points on it are a known distance apart: the image is scaled about
diff --git a/crates/engine/src/schema/canvas_tests.rs b/crates/engine/src/schema/canvas_tests.rs
index 0d075bcbe7..6e77a545b1 100644
--- a/crates/engine/src/schema/canvas_tests.rs
+++ b/crates/engine/src/schema/canvas_tests.rs
@@ -28,7 +28,7 @@ fn schemas_and_the_key_check_agree() {
input_schema_for::<CanvasDecalParams>(),
&["angle", "at", "center", "data", "face", "flip", "name", "offset", "opacity", "path", "width"],
);
- assert_keys(input_schema_for::<CanvasEditParams>(), &["angle", "canvas", "center", "flip", "name", "opacity", "visible", "width"]);
+ assert_keys(input_schema_for::<CanvasEditParams>(), &["angle", "canvas", "center", "flip", "locked", "name", "opacity", "visible", "width"]);
assert_keys(input_schema_for::<CanvasCalibrateParams>(), &["a", "b", "canvas", "distance"]);
assert_keys(input_schema_for::<CanvasDeleteParams>(), &["canvas"]);
}
diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs
index 0a1b0d1fcd..bab4a17b7f 100644
--- a/crates/io/src/design.rs
+++ b/crates/io/src/design.rs
@@ -1873,6 +1873,7 @@ mod tests {
opacity: 0.5,
flip: false,
visible: true,
+ locked: false,
component: 0,
});
doc
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs
index 4dd11e8dea..2bffbfb351 100644
--- a/crates/ui-egui/src/browser.rs
+++ b/crates/ui-egui/src/browser.rs
@@ -2380,7 +2380,7 @@ pub const CANVASES: &str = "c0/canvases";
/// The Canvases folder (reference images) with an eye per canvas.
fn canvas_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &mut Actions) {
- let canvases: Vec<(u64, String, bool)> = app.session.doc.canvases.iter().map(|c| (c.id, c.name.clone(), c.visible)).collect();
+ let canvases: Vec<(u64, String, bool, bool)> = app.session.doc.canvases.iter().map(|c| (c.id, c.name.clone(), c.visible, c.locked)).collect();
if canvases.is_empty() {
return;
}
@@ -2403,8 +2403,9 @@ fn canvas_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &mut A
if !open {
return;
}
- for (id, name, visible) in canvases {
+ for (id, name, visible, locked) in canvases {
let selected = app.tree.picked_canvases.contains(&id);
+ let badges: &[&str] = if locked { &["lock"] } else { &[] };
let r = draw_row(
ui,
ui.scope_id().with(("canvas", id)),
@@ -2416,6 +2417,7 @@ fn canvas_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &mut A
name: true,
selected,
dim: !visible || !shown,
+ badges,
..Default::default()
},
);
@@ -2435,7 +2437,9 @@ fn canvas_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &mut A
app.tree.picked_canvases.push(id);
}
}
- if r.double {
+ if r.double && locked {
+ app.set_status(crate::i18n::tr("browser.canvas_locked"), true);
+ } else if r.double {
app.tree.canvas_panel = Some(CanvasPanel::new(app, id, false));
}
if let Some(p) = r.secondary {
@@ -2454,14 +2458,19 @@ pub fn point_cloud_items(app: &SolveApp, id: u64) -> Vec<Item> {
/// The menu of a canvas.
pub fn canvas_items(app: &SolveApp, id: u64) -> Vec<Item> {
- let visible = app.session.doc.canvases.iter().find(|c| c.id == id).is_some_and(|c| c.visible);
+ let canvas = app.session.doc.canvases.iter().find(|c| c.id == id);
+ let visible = canvas.is_some_and(|c| c.visible);
+ // A locked canvas (#12310) is not moved, calibrated or deleted until it is unlocked.
+ let locked = canvas.is_some_and(|c| c.locked);
+ let why = locked.then(|| crate::i18n::tr("browser.canvas_locked").to_string());
vec![
- Item::action("ui.editCanvas", "Edit Canvas", "canvas").with(json!({ "canvas": id })),
- Item::action("ui.calibrateCanvas", "Calibrate", "measure").with(json!({ "canvas": id })),
+ Item::action("ui.editCanvas", "Edit Canvas", "canvas").with(json!({ "canvas": id })).off_because(why.clone()),
+ Item::action("ui.calibrateCanvas", "Calibrate", "measure").with(json!({ "canvas": id })).off_because(why.clone()),
Item::action("canvas.to_sketch", "Canvas to Sketch", "canvas").with(json!({ "canvas": id })),
Item::sep(),
- Item::action("ui.delete", "Delete", "delete").with(json!({ "canvases": [id] })),
+ Item::action("ui.delete", "Delete", "delete").with(json!({ "canvases": [id] })).off_because(why),
Item::action("ui.rename", "Rename", "rename").key("F2").with(json!({ "canvas": id })),
+ Item::action("ui.canvasLocked", if locked { "Unlock" } else { "Lock" }, "ground").with(json!({ "canvas": id, "locked": !locked })),
Item::sep(),
Item::action("ui.canvasVisible", "Show/Hide", "eye").key("V").with(json!({ "canvas": id, "visible": !visible })),
]
diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs
index 14ffcc4fb7..461da7cc05 100644
--- a/crates/ui-egui/src/context_menu.rs
+++ b/crates/ui-egui/src/context_menu.rs
@@ -1801,7 +1801,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {
"ui.isolateOccurrence" => {
let _ = app.run("browser.visibility", json!({"visible": true, "paths": [p["path"]], "isolate": true}));
}
- "ui.canvasVisible" => drop(app.run("canvas.edit", p)),
+ "ui.canvasVisible" | "ui.canvasLocked" => drop(app.run("canvas.edit", p)),
"ui.toolbarPin"
| "ui.toolbarRemove"
| "ui.toolbarReset"
diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs
index edc34dd8a4..12f9553de5 100644
--- a/crates/ui-egui/src/menu_tests.rs
+++ b/crates/ui-egui/src/menu_tests.rs
@@ -840,6 +840,20 @@ fn canvas_menu_hides_renames_calibrates_and_deletes() {
assert!(app.session.doc.canvases.is_empty());
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.doc.canvases.len(), 1);
+ // A locked canvas (#12310) can't be edited, calibrated or deleted, from its menu or the Delete key.
+ act(&mut app, &t, "Lock");
+ assert!(app.session.doc.canvases[0].locked);
+ let items = context_menu::items(&app, &t);
+ for label in ["Edit Canvas", "Calibrate", "Delete"] {
+ let item = find(&items, label);
+ assert!(!item.enabled && item.tip.as_deref() == Some(crate::i18n::tr("browser.canvas_locked")), "{label}: {item:?}");
+ }
+ assert!(find(&items, "Show/Hide").enabled && find(&items, "Rename").enabled);
+ app.tree.picked_canvases = vec![id];
+ crate::delete::delete_selection(&mut app);
+ assert_eq!(app.session.doc.canvases.len(), 1, "the locked canvas stays");
+ act(&mut app, &t, "Unlock");
+ assert!(!app.session.doc.canvases[0].locked);
// A canvas picked in the browser goes with the Delete key.
app.tree.picked_canvases = vec![id];
crate::delete::delete_selection(&mut app);