mirror of
https://github.com/bherbruck/solidcraft.git
synced 2026-11-08 04:52:10 +00:00
Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c18aaf7cc3 | |||
| 1e6b1ec20f | |||
| 4d96c780e1 | |||
| 52afe212a8 | |||
| 0bb09d0b13 | |||
| 11abdba1ba | |||
| 7c9c1699de | |||
| cf9ae4d25e | |||
| 1f29f432ee | |||
| dc679cae34 | |||
| dbbfa437a5 | |||
| ba43d2798f | |||
| 6a1fe74683 |
@@ -842,6 +842,7 @@ Original SolidCraft drawings, Open for owner review; no runtime assignments.
|
||||
| crates/sketch/assets/fonts/liberation-sans/LiberationSans-Regular.ttf | Red Hat, Inc. (Liberation Fonts 2.x; digitized data Google) | https://github.com/liberationfonts (Debian fonts-liberation), unmodified; licence text in crates/sketch/assets/fonts/liberation-sans/OFL.txt; used for sketch Text outlines | SIL OFL 1.1 |
|
||||
| crates/sketch/assets/fonts/liberation-sans/OFL.txt | Red Hat, Inc.; Liberation Fonts contributors | Unmodified accompanying font licence | SIL OFL 1.1 |
|
||||
| assets/locales/pending/drag-to-zoom.json | SolidCraft contributors | Original drag-to-zoom labels and translations | MIT OR Apache-2.0 |
|
||||
| `assets/locales/pending/hole-group-folder.json` | SolidCraft contributors | Original Hole grouping preference labels and translations | MIT OR Apache-2.0 |
|
||||
|
||||
## Code adapted from sibling projects
|
||||
|
||||
|
||||
@@ -2561,6 +2561,8 @@
|
||||
"prefs.design_tools.degrees": "درجات",
|
||||
"prefs.design_tools.double_click_help": "أو لتحرير مكوّن مرتبط في موضعه.",
|
||||
"prefs.design_tools.ghost": "إظهار الموضع القديم للأجزاء المنقولة كشبح",
|
||||
"prefs.design_tools.hole_group": "تجميع الثقوب المصنوعة معًا",
|
||||
"prefs.design_tools.hole_group_help": "الثقوب المصنوعة دفعة واحدة تشترك في مجلد في السجل، مغلق في البداية؛ افتحه لتحرير كل ثقب على حدة.",
|
||||
"prefs.design_tools.hole_moves_help": "اختيار الوجه مجددًا ينقل الثقب بدلًا من إزالته.",
|
||||
"prefs.design_tools.hole_several": "عدة ثقوب على وجه واحد",
|
||||
"prefs.design_tools.hole_several_help": "الاختيار في موضع آخر من الوجه يضيف ثقبًا آخر، واختيار ثقب يزيله.",
|
||||
|
||||
@@ -2348,6 +2348,8 @@
|
||||
"prefs.design_tools.degrees": "Grad",
|
||||
"prefs.design_tools.double_click_help": "Oder zum Bearbeiten einer verknüpften Komponente an Ort und Stelle.",
|
||||
"prefs.design_tools.ghost": "Alte Position verschobener Teile als Geisterbild zeigen",
|
||||
"prefs.design_tools.hole_group": "Gemeinsam erstellte Bohrungen gruppieren",
|
||||
"prefs.design_tools.hole_group_help": "In einem Schritt erstellte Bohrungen teilen sich einen Ordner im Verlauf, zunächst geschlossen; öffnen Sie ihn, um eine Bohrung einzeln zu bearbeiten.",
|
||||
"prefs.design_tools.hole_moves_help": "Erneutes Auswählen der Fläche verschiebt die Bohrung, statt sie zu entfernen.",
|
||||
"prefs.design_tools.hole_several": "Mehrere Bohrungen auf einer Fläche",
|
||||
"prefs.design_tools.hole_several_help": "Eine Auswahl an anderer Stelle der Fläche fügt eine weitere Bohrung hinzu; die Auswahl einer Bohrung entfernt sie.",
|
||||
|
||||
@@ -2561,6 +2561,8 @@
|
||||
"prefs.design_tools.degrees": "Degrees",
|
||||
"prefs.design_tools.double_click_help": "Or to edit a linked one in place.",
|
||||
"prefs.design_tools.ghost": "Show moved parts' old place as a ghost",
|
||||
"prefs.design_tools.hole_group": "Group holes made together",
|
||||
"prefs.design_tools.hole_group_help": "Holes made in one go share a folder in History, closed at first; open it to edit a hole on its own.",
|
||||
"prefs.design_tools.hole_moves_help": "Picking the face again moves the hole instead of removing it.",
|
||||
"prefs.design_tools.hole_several": "Several holes on one face",
|
||||
"prefs.design_tools.hole_several_help": "Picking elsewhere on a face adds another hole; picking a hole removes it.",
|
||||
|
||||
@@ -2561,6 +2561,8 @@
|
||||
"prefs.design_tools.degrees": "מעלות",
|
||||
"prefs.design_tools.double_click_help": "או לעריכת רכיב מקושר במקומו.",
|
||||
"prefs.design_tools.ghost": "הצגת המיקום הקודם של חלקים שהוזזו כרפאים",
|
||||
"prefs.design_tools.hole_group": "קיבוץ חורים שנוצרו יחד",
|
||||
"prefs.design_tools.hole_group_help": "חורים שנוצרו בפעולה אחת חולקים תיקייה בהיסטוריה, סגורה בהתחלה; פתחו אותה כדי לערוך חור בנפרד.",
|
||||
"prefs.design_tools.hole_moves_help": "בחירה חוזרת בפאה מזיזה את החור במקום להסירו.",
|
||||
"prefs.design_tools.hole_several": "כמה חורים בפאה אחת",
|
||||
"prefs.design_tools.hole_several_help": "בחירה במקום אחר בפאה מוסיפה חור נוסף; בחירה בחור מסירה אותו.",
|
||||
|
||||
@@ -2561,6 +2561,8 @@
|
||||
"prefs.design_tools.degrees": "度",
|
||||
"prefs.design_tools.double_click_help": "リンクされたコンポーネントをその場で編集することもできます。",
|
||||
"prefs.design_tools.ghost": "移動したパーツの元の位置をゴースト表示",
|
||||
"prefs.design_tools.hole_group": "一緒に作成した穴をまとめる",
|
||||
"prefs.design_tools.hole_group_help": "一度に作成した穴は履歴で1つのフォルダーにまとめられ、最初は閉じています。開くと穴を個別に編集できます。",
|
||||
"prefs.design_tools.hole_moves_help": "面をもう一度選ぶと穴を削除せずに移動します。",
|
||||
"prefs.design_tools.hole_several": "1つの面に複数の穴",
|
||||
"prefs.design_tools.hole_several_help": "面の別の場所を選ぶと穴を追加し、穴を選ぶとその穴を削除します。",
|
||||
|
||||
@@ -1929,6 +1929,8 @@
|
||||
"prefs.design_tools.degrees": "도",
|
||||
"prefs.design_tools.double_click_help": "연결된 구성요소를 제자리에서 편집할 수도 있습니다.",
|
||||
"prefs.design_tools.ghost": "이동한 부품의 이전 위치를 고스트로 표시",
|
||||
"prefs.design_tools.hole_group": "함께 만든 구멍 그룹화",
|
||||
"prefs.design_tools.hole_group_help": "한 번에 만든 구멍은 기록에서 하나의 폴더를 공유하며, 처음에는 닫혀 있습니다. 폴더를 열어 각 구멍을 개별적으로 편집하세요.",
|
||||
"prefs.design_tools.hole_moves_help": "면을 다시 선택하면 구멍을 제거하지 않고 이동합니다.",
|
||||
"prefs.design_tools.hole_snaps_help": "면의 가운데와 원형 모서리의 중심입니다.",
|
||||
"prefs.design_tools.imported_files": "가져온 파일",
|
||||
|
||||
@@ -2561,6 +2561,8 @@
|
||||
"prefs.design_tools.degrees": "Độ",
|
||||
"prefs.design_tools.double_click_help": "Hoặc để chỉnh sửa thành phần được liên kết tại chỗ.",
|
||||
"prefs.design_tools.ghost": "Hiện vị trí cũ của chi tiết đã di chuyển dưới dạng bóng mờ",
|
||||
"prefs.design_tools.hole_group": "Nhóm các lỗ được tạo cùng lúc",
|
||||
"prefs.design_tools.hole_group_help": "Các lỗ được tạo trong một lần dùng chung một thư mục trong Lịch sử, ban đầu được đóng; mở thư mục để sửa từng lỗ.",
|
||||
"prefs.design_tools.hole_moves_help": "Chọn lại mặt sẽ di chuyển lỗ thay vì xóa lỗ.",
|
||||
"prefs.design_tools.hole_several": "Nhiều lỗ trên một mặt",
|
||||
"prefs.design_tools.hole_several_help": "Chọn chỗ khác trên mặt sẽ thêm một lỗ; chọn một lỗ sẽ xóa lỗ đó.",
|
||||
|
||||
@@ -2561,6 +2561,8 @@
|
||||
"prefs.design_tools.degrees": "度",
|
||||
"prefs.design_tools.double_click_help": "或就地编辑链接的组件。",
|
||||
"prefs.design_tools.ghost": "以虚影显示已移动零件的原位置",
|
||||
"prefs.design_tools.hole_group": "将一起创建的孔分组",
|
||||
"prefs.design_tools.hole_group_help": "一次创建的孔在历史中共用一个文件夹,初始为折叠;展开后可单独编辑每个孔。",
|
||||
"prefs.design_tools.hole_moves_help": "再次选择该面会移动孔而非移除孔。",
|
||||
"prefs.design_tools.hole_several": "一个面上多个孔",
|
||||
"prefs.design_tools.hole_several_help": "在面的其他位置选择会再添加一个孔;选择孔会移除该孔。",
|
||||
|
||||
@@ -1393,13 +1393,18 @@ mod tests {
|
||||
assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64), "{cmd}");
|
||||
assert!(bytes.starts_with(signature), "{cmd}");
|
||||
}
|
||||
// The triangles `file.export` writes (the 80-byte header holds the file's name): a box is
|
||||
// 12 triangles, 84 + 50 bytes each.
|
||||
// The triangles `file.export` writes (the 80-byte header holds the file's name), 84 + 50
|
||||
// bytes each. The mesher lays each planar face out as a regular grid whose sides are at
|
||||
// most a fifth of the body's diagonal (kernel test `a_box_is_a_regular_grid_on_every_face`):
|
||||
// 22.9 / 5 = 4.58 mm, so 5 × 3 × 2 cells along 20 × 10 × 5, two triangles each.
|
||||
s.execute("file.export", &json!({"path": at("box.stl")})).unwrap();
|
||||
assert_eq!(std::fs::read(at("StlBinary.txt")).unwrap()[80..], std::fs::read(at("box.stl")).unwrap()[80..]);
|
||||
assert_eq!(std::fs::metadata(at("box.stl")).unwrap().len(), 84 + 50 * 12);
|
||||
let triangles = 2 * 2 * (5 * 3 + 5 * 2 + 3 * 2);
|
||||
let stl = std::fs::read(at("box.stl")).unwrap();
|
||||
assert_eq!(u32::from_le_bytes([stl[80], stl[81], stl[82], stl[83]]), u32::try_from(triangles).unwrap());
|
||||
assert_eq!(stl.len(), 84 + 50 * triangles);
|
||||
let obj = std::fs::read_to_string(at("Obj.txt")).unwrap();
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("f ")).count(), 12, "{obj}");
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("f ")).count(), triangles, "{obj}");
|
||||
let r = s.execute("file.export_urdf", &json!({"path": at("robot.urdf")})).unwrap();
|
||||
assert_eq!(r["format"], "Urdf");
|
||||
assert!(std::fs::read_to_string(at("robot.urdf")).unwrap().contains("<robot"));
|
||||
|
||||
+315
-140
@@ -12,8 +12,12 @@ use solidcraft_sketch::CurveKind;
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, str_, string_list};
|
||||
use crate::schema::inspect::{
|
||||
BodyFeaturesParams, BodyListParams, FaceCylinder, ModelBodyFeatures, ModelEdge, ModelEdges, ModelFace, ModelFaces, ModelThread, ModelThreads,
|
||||
ModelThreadsParams,
|
||||
BodyFailure, BodyFeaturesParams, BodyFigures, BodyListParams, BodyMeasurement, BodyName, BodyNames, BodyOutcome, BoundingBox, CommandEntry,
|
||||
CommandsParams, CurveShape, DocumentBody, DocumentBodyDetail, DocumentInspectParams, DocumentInspectResult, DocumentParam, DocumentSketch,
|
||||
FaceCylinder, KernelCounts, ListedMaterial, MaterialAssignParams, MaterialAssignResult, MaterialListParams, MaterialListResult, MeasureParams,
|
||||
MeasureResult, MeasureTotal, Measured, MeasuredBodies, MeasuredBody, ModelBodyFeatures, ModelEdge, ModelEdges, ModelFace, ModelFaces,
|
||||
ModelThread, ModelThreads, ModelThreadsParams, SketchConstraint, SketchCurve, SketchInspectParams, SketchInspected, SketchPoint, SketchProfile,
|
||||
SketchWire, TimelineEntry, WireArcInfo,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
@@ -21,6 +25,12 @@ use crate::{EngineError, Result, Session};
|
||||
const BODY_LIST_CONTRACT: TypedContract<BodyListParams> = TypedContract::new();
|
||||
const THREADS_CONTRACT: TypedContract<ModelThreadsParams> = TypedContract::new();
|
||||
const BODY_FEATURES_CONTRACT: TypedContract<BodyFeaturesParams> = TypedContract::new();
|
||||
const MEASURE_CONTRACT: TypedContract<MeasureParams> = TypedContract::new();
|
||||
const DOCUMENT_INSPECT_CONTRACT: TypedContract<DocumentInspectParams> = TypedContract::new();
|
||||
const SKETCH_INSPECT_CONTRACT: TypedContract<SketchInspectParams> = TypedContract::new();
|
||||
const MATERIAL_ASSIGN_CONTRACT: TypedContract<MaterialAssignParams> = TypedContract::new();
|
||||
const MATERIAL_LIST_CONTRACT: TypedContract<MaterialListParams> = TypedContract::new();
|
||||
const COMMANDS_CONTRACT: TypedContract<CommandsParams> = TypedContract::new();
|
||||
|
||||
#[path = "appearance_chain.rs"]
|
||||
mod appearance_chain;
|
||||
@@ -35,19 +45,32 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("inspect.colored_components", "Component Colors", colored_components)
|
||||
.at("SOLID", "INSPECT").icon("colored_components").noundo()
|
||||
.params("enabled?: bool (omitted: toggle); temporary component colours, without changing appearances"),
|
||||
CommandSpec::new("inspect.measure", "Measure", measure)
|
||||
CommandSpec::new("inspect.measure", "Measure", crate::checked!("inspect.measure", measure))
|
||||
.at("SOLID", "INSPECT")
|
||||
.icon("measure")
|
||||
.key("I")
|
||||
.noundo()
|
||||
.contract(&MEASURE_CONTRACT)
|
||||
.output(output_schema_for::<MeasureResult>)
|
||||
.params("bodies?: [names] (default all); names_only?: bool (each world body's name and its definition's, nothing measured) → closed per body; volume_mm3, center_of_mass, density_g_cm3 and mass_g only for closed, consistently oriented bodies; area, bbox and counts for all; total.open_bodies_skipped counts bodies excluded from volume/mass totals; or items: [1-2 selections] (face/edge: type, body, point; index optional) → length/area/volume; diameter, radius, circumference or arc_length/angle_deg of circles, arcs and cylinders; slot sizes; min (distance_mm, from, to), max, center_distance (centre to centre, or from an axis) and angle"),
|
||||
CommandSpec::new("document.inspect", "Inspect Design", inspect).icon("inspect").noundo().params("measure?: bool (include body measurements); sketch_counts?: bool (each sketch also gives its plane and its number of points and constraints)"),
|
||||
CommandSpec::new("document.inspect", "Inspect Design", crate::checked!("document.inspect", inspect))
|
||||
.icon("inspect")
|
||||
.noundo()
|
||||
.contract(&DOCUMENT_INSPECT_CONTRACT)
|
||||
.output(output_schema_for::<DocumentInspectResult>)
|
||||
.params("measure?: bool (include body measurements); sketch_counts?: bool (each sketch also gives its plane and its number of points and constraints)"),
|
||||
CommandSpec::new("document.revision", "Design Revision", revision).icon("inspect").noundo().params(
|
||||
"→ document_id (this open design's id: kept while it stays open, another for each design started or opened), \
|
||||
revision (moves whenever the design, what is hidden or a component's uncaptured position changes, \
|
||||
never on a selection or a view; from one counter for the whole run, so it never repeats). Read-only",
|
||||
),
|
||||
CommandSpec::new("sketch.inspect", "Inspect Sketch", sketch_inspect).at("SKETCH", "INSPECT").icon("inspect").noundo().params("sketch?: id|name (default active)"),
|
||||
CommandSpec::new("sketch.inspect", "Inspect Sketch", crate::checked!("sketch.inspect", sketch_inspect))
|
||||
.at("SKETCH", "INSPECT")
|
||||
.icon("inspect")
|
||||
.noundo()
|
||||
.contract(&SKETCH_INSPECT_CONTRACT)
|
||||
.output(output_schema_for::<SketchInspected>)
|
||||
.params("sketch?: id|name (default active)"),
|
||||
CommandSpec::new("model.edges", "List Edges", crate::checked!("model.edges", model_edges))
|
||||
.icon("inspect")
|
||||
.noundo()
|
||||
@@ -79,9 +102,11 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"body?: name (a placed copy's name means the body it shows; default every body) → bodies: [{body, features: [{id, name}]}], \
|
||||
in timeline order the feature that created each body, every later one that changed it, and those of bodies consumed into it. Read-only",
|
||||
),
|
||||
CommandSpec::new("material.assign", "Physical Material", physical_material)
|
||||
CommandSpec::new("material.assign", "Physical Material", crate::checked!("material.assign", physical_material))
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("material")
|
||||
.contract(&MATERIAL_ASSIGN_CONTRACT)
|
||||
.output(output_schema_for::<MaterialAssignResult>)
|
||||
.params("bodies: [names]; material: name (Steel, Aluminum, ABS Plastic, …, or one made with material.create; `material.list`)"),
|
||||
CommandSpec::new("appearance.assign", "Appearance", crate::checked!("appearance.assign", appearance))
|
||||
.at("SOLID", "MODIFY")
|
||||
@@ -118,11 +143,18 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.contract(&LIST_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<AppearanceListResult>)
|
||||
.params("body?: name (or a placed copy's, `KB (K:2)`: the body it shows) → assigned appearances; with body, its resolved look and its faces' (face index, look)"),
|
||||
CommandSpec::new("material.list", "List Materials", material_list).icon("list")
|
||||
CommandSpec::new("material.list", "List Materials", crate::checked!("material.list", material_list))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&MATERIAL_LIST_CONTRACT)
|
||||
.output(output_schema_for::<MaterialListResult>)
|
||||
.params("→ built-in and design-owned materials (user: true, look, optional physical_card/physical_validation/density_comparison). Read-only; candidate engineering records do not certify sources or supply a solver"),
|
||||
CommandSpec::new("engine.commands", "List Commands", commands).icon("list").noundo(),
|
||||
CommandSpec::new("engine.commands", "List Commands", crate::checked!("engine.commands", commands))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.contract(&COMMANDS_CONTRACT)
|
||||
.output(output_schema_for::<Vec<CommandEntry>>),
|
||||
CommandSpec::new("engine.describe", "Describe Command", crate::checked!("engine.describe", describe))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
@@ -142,7 +174,7 @@ pub(crate) fn encloses_volume(body: &solidcraft_kernel::Body) -> bool {
|
||||
}
|
||||
|
||||
pub fn measure_json(b: &solidcraft_doc::ModelBody) -> Value {
|
||||
measure_sheet_json(b, None)
|
||||
serde_json::to_value(measure_sheet(b, None)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn measure_body(
|
||||
@@ -164,27 +196,53 @@ pub(super) fn measure_body(
|
||||
Ok(measured)
|
||||
}
|
||||
|
||||
fn measure_sheet_json(b: &solidcraft_doc::ModelBody, definitions: Option<&solidcraft_doc::ModelState>) -> Value {
|
||||
fn measure_sheet(b: &solidcraft_doc::ModelBody, definitions: Option<&solidcraft_doc::ModelState>) -> BodyMeasurement {
|
||||
let name = b.name.clone();
|
||||
match measure_body(b, definitions) {
|
||||
Ok(m) => {
|
||||
let closed = encloses_volume(&b.body);
|
||||
json!({
|
||||
"name": b.name,
|
||||
"closed": closed,
|
||||
"volume_mm3": closed.then_some(m.volume),
|
||||
"area_mm2": m.area,
|
||||
"center_of_mass": closed.then_some(m.centroid),
|
||||
"bbox": {"min": m.bbox.min, "max": m.bbox.max},
|
||||
"faces": m.merged.faces,
|
||||
"edges": m.merged.edges,
|
||||
"vertices": m.merged.vertices,
|
||||
"face_types": m.merged.face_types,
|
||||
"kernel": {"faces": m.faces, "edges": m.edges, "vertices": m.vertices, "shells": m.shells},
|
||||
"measured_by": m.measured_by,
|
||||
"notes": m.notes,
|
||||
})
|
||||
let outcome = BodyOutcome::Measured(BodyFigures {
|
||||
closed,
|
||||
volume_mm3: closed.then_some(m.volume),
|
||||
area_mm2: m.area,
|
||||
center_of_mass: closed.then(|| m.centroid.into()),
|
||||
bbox: BoundingBox { min: m.bbox.min.into(), max: m.bbox.max.into() },
|
||||
faces: count(m.merged.faces),
|
||||
edges: count(m.merged.edges),
|
||||
vertices: count(m.merged.vertices),
|
||||
face_types: m.merged.face_types,
|
||||
kernel: KernelCounts { faces: m.faces, edges: m.edges, vertices: m.vertices, shells: m.shells },
|
||||
measured_by: m.measured_by.to_string(),
|
||||
notes: m.notes,
|
||||
});
|
||||
BodyMeasurement { name, outcome }
|
||||
}
|
||||
Err(e) => measure_failed(name, e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn measure_failed(name: String, error: String) -> BodyMeasurement {
|
||||
BodyMeasurement { name, outcome: BodyOutcome::Failed(BodyFailure { error, faces: None, edges: None, vertices: None }) }
|
||||
}
|
||||
|
||||
/// A topology count as the replies give it.
|
||||
fn count(n: usize) -> i64 {
|
||||
i64::try_from(n).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// A reply as JSON: the commands build their replies from the types their output schemas
|
||||
/// describe, so the two can't drift apart.
|
||||
fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
impl BodyMeasurement {
|
||||
/// The volume, when the body has one that is a number.
|
||||
fn volume(&self) -> Option<f64> {
|
||||
match &self.outcome {
|
||||
BodyOutcome::Measured(f) => f.volume_mm3.filter(|v| v.is_finite()),
|
||||
BodyOutcome::Failed(_) => None,
|
||||
}
|
||||
Err(e) => json!({"name": b.name, "error": e.to_string()}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,138 +259,217 @@ fn measure(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "unknown body name"));
|
||||
}
|
||||
if bool_(p, "names_only").unwrap_or(false) {
|
||||
let bodies: Vec<_> = selected.iter().map(|b| json!({"name": b.name, "definition": b.definition_name()})).collect();
|
||||
return Ok(json!({"body_count": bodies.len(), "bodies": bodies}));
|
||||
let bodies: Vec<_> = selected.iter().map(|b| BodyName { name: b.name.clone(), definition: b.definition_name().to_string() }).collect();
|
||||
let measured = Measured::Names(BodyNames { body_count: bodies.len(), bodies });
|
||||
return typed_reply(cmd, MeasureResult { measured, param_warnings: Vec::new() });
|
||||
}
|
||||
// Each body is measured on its own: on all cores, in body order.
|
||||
let mut bodies: Vec<Value> = solidcraft_kernel::map_on_threads(&selected, 16, |b| measure_sheet_json(b, Some(&definitions)))
|
||||
let measurements: Vec<BodyMeasurement> = solidcraft_kernel::map_on_threads(&selected, 16, |b| measure_sheet(b, Some(&definitions)))
|
||||
.into_iter()
|
||||
.zip(&selected)
|
||||
.map(|(m, b)| m.unwrap_or_else(|| json!({"name": b.name, "error": "measuring this body failed"})))
|
||||
.map(|(m, b)| m.unwrap_or_else(|| measure_failed(b.name.clone(), "measuring this body failed".into())))
|
||||
.collect();
|
||||
// Mass from each body's material.
|
||||
for (b, body) in bodies.iter_mut().zip(selected) {
|
||||
let mut bodies: Vec<MeasuredBody> = Vec::with_capacity(measurements.len());
|
||||
for (measurement, body) in measurements.into_iter().zip(selected) {
|
||||
let source = body.definition_name();
|
||||
// Every body's material, measured or not: naming it takes no measuring.
|
||||
b["material"] = json!(s.doc.body_material(source));
|
||||
if let Some(v) = b["volume_mm3"].as_f64() {
|
||||
let mut b = MeasuredBody { measurement, material: s.doc.body_material(source), density_g_cm3: None, mass_g: None, sheet_metal: None };
|
||||
if let Some(v) = b.measurement.volume() {
|
||||
let rho = s.doc.density(source);
|
||||
b["density_g_cm3"] = json!(rho);
|
||||
b["mass_g"] = json!(v * rho / 1000.0);
|
||||
b.density_g_cm3 = Some(rho);
|
||||
b.mass_g = Some(v * rho / 1000.0);
|
||||
}
|
||||
// Only Measure exposes sheet boundary counts; document.inspect keeps kernel counts.
|
||||
if let Some(sheet) = definitions.sheets.iter().find(|sheet| sheet.body == source) {
|
||||
let (df, de, dv) = sheet.round_hole_correction();
|
||||
for (key, delta) in [("faces", df), ("edges", de), ("vertices", dv)] {
|
||||
b[key] = json!(b["kernel"][key].as_i64().unwrap_or(0) + delta);
|
||||
match &mut b.measurement.outcome {
|
||||
BodyOutcome::Measured(f) => {
|
||||
f.faces = count(f.kernel.faces) + df;
|
||||
f.edges = count(f.kernel.edges) + de;
|
||||
f.vertices = count(f.kernel.vertices) + dv;
|
||||
}
|
||||
BodyOutcome::Failed(x) => (x.faces, x.edges, x.vertices) = (Some(df), Some(de), Some(dv)),
|
||||
}
|
||||
b["sheet_metal"] = json!(true);
|
||||
b.sheet_metal = Some(true);
|
||||
}
|
||||
bodies.push(b);
|
||||
}
|
||||
fn figures(b: &MeasuredBody) -> Option<&BodyFigures> {
|
||||
match &b.measurement.outcome {
|
||||
BodyOutcome::Measured(f) => Some(f),
|
||||
BodyOutcome::Failed(_) => None,
|
||||
}
|
||||
}
|
||||
let skipped = bodies.iter().filter(|b| b["closed"] == false).count();
|
||||
let tv: f64 = bodies.iter().filter_map(|b| b["volume_mm3"].as_f64()).sum();
|
||||
let ta: f64 = bodies.iter().filter_map(|b| b["area_mm2"].as_f64()).sum();
|
||||
let tf: u64 = bodies.iter().filter_map(|b| b["faces"].as_u64()).sum();
|
||||
let te: u64 = bodies.iter().filter_map(|b| b["edges"].as_u64()).sum();
|
||||
let tvx: u64 = bodies.iter().filter_map(|b| b["vertices"].as_u64()).sum();
|
||||
let tm: f64 = bodies.iter().filter_map(|b| b["mass_g"].as_f64()).sum();
|
||||
Ok(
|
||||
json!({"body_count": bodies.len(), "bodies": bodies, "total": {"open_bodies_skipped": skipped, "volume_mm3": tv, "area_mm2": ta, "mass_g": tm, "faces": tf, "edges": te, "vertices": tvx}}),
|
||||
let counted = |n: Option<i64>| n.and_then(|n| u64::try_from(n).ok());
|
||||
let faces = |b: &MeasuredBody| match &b.measurement.outcome {
|
||||
BodyOutcome::Measured(f) => (counted(Some(f.faces)), counted(Some(f.edges)), counted(Some(f.vertices))),
|
||||
BodyOutcome::Failed(x) => (counted(x.faces), counted(x.edges), counted(x.vertices)),
|
||||
};
|
||||
let total = MeasureTotal {
|
||||
open_bodies_skipped: bodies.iter().filter(|b| figures(b).is_some_and(|f| !f.closed)).count(),
|
||||
volume_mm3: bodies.iter().filter_map(|b| b.measurement.volume()).sum(),
|
||||
area_mm2: bodies.iter().filter_map(|b| figures(b)).map(|f| f.area_mm2).filter(|a| a.is_finite()).sum(),
|
||||
mass_g: bodies.iter().filter_map(|b| b.mass_g).filter(|m| m.is_finite()).sum(),
|
||||
faces: bodies.iter().filter_map(|b| faces(b).0).sum(),
|
||||
edges: bodies.iter().filter_map(|b| faces(b).1).sum(),
|
||||
vertices: bodies.iter().filter_map(|b| faces(b).2).sum(),
|
||||
};
|
||||
typed_reply(
|
||||
cmd,
|
||||
MeasureResult { measured: Measured::Bodies(MeasuredBodies { body_count: bodies.len(), bodies, total }), param_warnings: Vec::new() },
|
||||
)
|
||||
}
|
||||
|
||||
/// A 2D position as the replies give it.
|
||||
fn at2(p: solidcore_record::Vec2) -> [f64; 2] {
|
||||
[p.x, p.y]
|
||||
}
|
||||
|
||||
/// Sketch `id`, placed where the placed model `world` has it (its component's placement).
|
||||
fn sketch_json(s: &Session, world: &solidcraft_doc::ModelState, id: u64) -> Option<Value> {
|
||||
fn sketch_json(s: &Session, world: &solidcraft_doc::ModelState, id: u64) -> Option<SketchInspected> {
|
||||
let state = s.model.state();
|
||||
let ss = state.sketch(id)?;
|
||||
let plane = world.sketch(id).map(|w| w.plane).unwrap_or(ss.plane);
|
||||
let sk = &ss.sketch;
|
||||
let curves: Vec<Value> = sk
|
||||
let curves: Vec<SketchCurve> = sk
|
||||
.curves
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
let det = ss.report.curve_determined.get(i).copied().unwrap_or(false);
|
||||
let pid = |k: usize| sk.points.get(k).map(|p| p.id.clone()).unwrap_or_default();
|
||||
let mut v = match c.kind {
|
||||
CurveKind::Line { a, b } => json!({"id": c.id, "type": "line", "start": pid(a), "end": pid(b), "start_at": sk.point(a), "end_at": sk.point(b), "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
|
||||
CurveKind::Circle { c: cc, r } => json!({"id": c.id, "type": "circle", "center": pid(cc), "center_at": sk.point(cc), "radius": r, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
|
||||
CurveKind::Arc { c: cc, a, b } => json!({"id": c.id, "type": "arc", "center": pid(cc), "start": pid(a), "end": pid(b), "center_at": sk.point(cc), "start_at": sk.point(a), "end_at": sk.point(b), "radius": sk.radius(i), "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
|
||||
CurveKind::Ellipse { c: cc, m, r } => json!({"id": c.id, "type": "ellipse", "center": pid(cc), "major": pid(m), "center_at": sk.point(cc), "major_at": sk.point(m), "minor_radius": r, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
|
||||
CurveKind::Spline { ref pts, control, degree, periodic, ref nurbs } => {
|
||||
let mut v = json!({"id": c.id, "type": "spline", "points": pts.iter().map(|q| pid(*q)).collect::<Vec<_>>(), "points_at": pts.iter().map(|q| sk.point(*q)).collect::<Vec<_>>(), "control": control, "degree": degree, "periodic": periodic, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det});
|
||||
// A control spline with its own knots (a projected free-form edge) says them.
|
||||
if let (Some(n), Some(o)) = (nurbs, v.as_object_mut()) {
|
||||
o.insert("knots".into(), json!(n.knots));
|
||||
if !n.weights.is_empty() {
|
||||
o.insert("weights".into(), json!(n.weights));
|
||||
}
|
||||
}
|
||||
v
|
||||
let at = |k: usize| sk.point(k).map(at2);
|
||||
let shape = match c.kind {
|
||||
CurveKind::Line { a, b } => CurveShape::Line { start: pid(a), end: pid(b), start_at: at(a), end_at: at(b) },
|
||||
CurveKind::Circle { c: cc, r } => CurveShape::Circle { center: pid(cc), center_at: at(cc), radius: r },
|
||||
CurveKind::Arc { c: cc, a, b } => CurveShape::Arc {
|
||||
center: pid(cc),
|
||||
start: pid(a),
|
||||
end: pid(b),
|
||||
center_at: at(cc),
|
||||
start_at: at(a),
|
||||
end_at: at(b),
|
||||
radius: sk.radius(i),
|
||||
},
|
||||
CurveKind::Ellipse { c: cc, m, r } => {
|
||||
CurveShape::Ellipse { center: pid(cc), major: pid(m), center_at: at(cc), major_at: at(m), minor_radius: r }
|
||||
}
|
||||
CurveKind::Spline { ref pts, control, degree, periodic, ref nurbs } => CurveShape::Spline {
|
||||
points: pts.iter().map(|q| pid(*q)).collect(),
|
||||
points_at: pts.iter().map(|q| at(*q)).collect(),
|
||||
control,
|
||||
degree,
|
||||
periodic,
|
||||
// A control spline with its own knots (a projected free-form edge) says them.
|
||||
knots: nurbs.as_ref().map(|n| n.knots.clone()),
|
||||
weights: nurbs.as_ref().filter(|n| !n.weights.is_empty()).map(|n| n.weights.clone()),
|
||||
},
|
||||
CurveKind::Conic { a, b, apex, rho } => {
|
||||
CurveShape::Conic { start: pid(a), end: pid(b), apex: pid(apex), start_at: at(a), end_at: at(b), apex_at: at(apex), rho }
|
||||
}
|
||||
CurveKind::Conic { a, b, apex, rho } => json!({"id": c.id, "type": "conic", "start": pid(a), "end": pid(b), "apex": pid(apex), "start_at": sk.point(a), "end_at": sk.point(b), "apex_at": sk.point(apex), "rho": rho, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
|
||||
};
|
||||
if let (Some(l), Some(o)) = (&c.link, v.as_object_mut()) {
|
||||
o.insert("link".into(), json!(l));
|
||||
SketchCurve {
|
||||
id: c.id.clone(),
|
||||
shape,
|
||||
construction: c.construction,
|
||||
fixed: sk.curve_locked(i),
|
||||
fully_constrained: det,
|
||||
link: c.link.clone(),
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let locked = sk.locked_points();
|
||||
let points: Vec<Value> = sk
|
||||
let points: Vec<SketchPoint> = sk
|
||||
.points
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| json!({"id": p.id, "at": p.pos, "world": plane.to_world(p.pos), "fixed": locked.get(i).copied().unwrap_or(false), "link": p.link, "fully_constrained": ss.report.point_determined.get(i).copied().unwrap_or(false)}))
|
||||
.map(|(i, p)| SketchPoint {
|
||||
id: p.id.clone(),
|
||||
at: at2(p.pos),
|
||||
world: plane.to_world(p.pos).into(),
|
||||
fixed: locked.get(i).copied().unwrap_or(false),
|
||||
link: p.link.clone(),
|
||||
fully_constrained: ss.report.point_determined.get(i).copied().unwrap_or(false),
|
||||
})
|
||||
.collect();
|
||||
let constraints: Vec<Value> = sk
|
||||
let constraints: Vec<SketchConstraint> = sk
|
||||
.constraints
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut v = serde_json::to_value(&c.kind).unwrap_or_default();
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("id".into(), json!(c.id));
|
||||
o.insert("name".into(), json!(c.kind.name()));
|
||||
if let Some(p) = &c.param {
|
||||
o.insert("param".into(), json!(p));
|
||||
o.insert("expression".into(), json!(s.doc.param(p).map(|x| x.expr.clone())));
|
||||
}
|
||||
let mut kind = match serde_json::to_value(&c.kind) {
|
||||
Ok(Value::Object(kind)) => kind,
|
||||
_ => Default::default(),
|
||||
};
|
||||
// The constraint's own keys win over any of the kind's.
|
||||
for key in ["id", "name", "param", "expression"] {
|
||||
kind.remove(key);
|
||||
}
|
||||
SketchConstraint {
|
||||
id: c.id.clone(),
|
||||
name: c.kind.name().to_string(),
|
||||
param: c.param.clone(),
|
||||
expression: c.param.as_ref().map(|p| s.doc.param(p).map(|x| x.expr.clone())),
|
||||
kind,
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let profiles: Vec<Value> = ss
|
||||
let profiles: Vec<SketchProfile> = ss
|
||||
.profiles
|
||||
.iter()
|
||||
.enumerate()
|
||||
// A loop records one entry per piece it walks, and a conic or spline is walked as many
|
||||
// short pieces: each loop names a curve once, in loop order.
|
||||
.map(|(i, p)| {
|
||||
let holes: Vec<Vec<String>> = p.hole_curves.iter().map(|h| solidcraft_sketch::distinct_curves(h)).collect();
|
||||
json!({"index": i, "area_mm2": p.area, "centroid_sketch": p.centroid, "curves": solidcraft_sketch::distinct_curves(&p.outer_curves), "holes": holes})
|
||||
.map(|(i, p)| SketchProfile {
|
||||
index: i,
|
||||
area_mm2: p.area,
|
||||
centroid_sketch: at2(p.centroid),
|
||||
curves: solidcraft_sketch::distinct_curves(&p.outer_curves),
|
||||
holes: p.hole_curves.iter().map(|h| solidcraft_sketch::distinct_curves(h)).collect(),
|
||||
})
|
||||
.collect();
|
||||
Some(json!({
|
||||
"id": id,
|
||||
"name": ss.name,
|
||||
"plane": ss.plane,
|
||||
"status": ss.report.status,
|
||||
"dof": ss.report.dof,
|
||||
"fully_constrained": ss.report.fully_constrained(),
|
||||
"failing": ss.report.failing,
|
||||
"curves": curves,
|
||||
"points": points,
|
||||
"constraints": constraints,
|
||||
"profiles": profiles,
|
||||
"links": sk.links,
|
||||
"wires": sk.wires.iter().map(|w| json!({"id": w.id, "points": w.pts.len(), "start": w.pts.first(), "end": w.pts.last(), "link": w.link, "arc": w.arc.map(|a| json!({"center": a.center, "radius": a.radius, "start": a.start, "end": a.end, "sweep_deg": solidcraft_sketch::arc_sweep(&a).to_degrees()}))})).collect::<Vec<_>>(),
|
||||
"visible": crate::view::sketch_shown(s, id),
|
||||
}))
|
||||
let wires = sk
|
||||
.wires
|
||||
.iter()
|
||||
.map(|w| SketchWire {
|
||||
id: w.id.clone(),
|
||||
points: w.pts.len(),
|
||||
start: w.pts.first().map(|&p| p.into()),
|
||||
end: w.pts.last().map(|&p| p.into()),
|
||||
link: w.link.clone(),
|
||||
arc: w.arc.map(|a| WireArcInfo {
|
||||
center: a.center.into(),
|
||||
radius: a.radius,
|
||||
start: a.start.into(),
|
||||
end: a.end.into(),
|
||||
sweep_deg: solidcraft_sketch::arc_sweep(&a).to_degrees(),
|
||||
}),
|
||||
})
|
||||
.collect();
|
||||
Some(SketchInspected {
|
||||
id,
|
||||
name: ss.name.clone(),
|
||||
plane: serde_json::to_value(ss.plane).unwrap_or_default(),
|
||||
status: ss.report.status.into(),
|
||||
dof: ss.report.dof,
|
||||
fully_constrained: ss.report.fully_constrained(),
|
||||
failing: ss.report.failing.clone(),
|
||||
curves,
|
||||
points,
|
||||
constraints,
|
||||
profiles,
|
||||
links: serde_json::to_value(&sk.links).unwrap_or_default(),
|
||||
wires,
|
||||
visible: crate::view::sketch_shown(s, id),
|
||||
param_warnings: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn sketch_inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = super::sketch_store::target(s, p, "sketch.inspect")?;
|
||||
sketch_json(s, &*s.world_state()?, id).ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into()))
|
||||
let inspected = sketch_json(s, &*s.world_state()?, id)
|
||||
.ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into()))?;
|
||||
typed_reply("sketch.inspect", inspected)
|
||||
}
|
||||
|
||||
/// Revisions of every design of this run (#6646).
|
||||
@@ -391,24 +528,38 @@ fn revision(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.model.state();
|
||||
let (vals, perr) = s.doc.param_values();
|
||||
let params: Vec<Value> = s
|
||||
let params: Vec<DocumentParam> = s
|
||||
.doc
|
||||
.params
|
||||
.iter()
|
||||
.map(|p| json!({"name": p.name, "expression": p.expr, "unit": p.unit, "value": vals.get(&p.name).map(|v| v.v), "model": p.model, "comment": p.comment, "error": perr.get(&p.name)}))
|
||||
.map(|p| DocumentParam {
|
||||
name: p.name.clone(),
|
||||
expression: p.expr.clone(),
|
||||
unit: p.unit.clone(),
|
||||
value: vals.get(&p.name).map(|v| v.v),
|
||||
model: p.model,
|
||||
comment: p.comment.clone(),
|
||||
error: perr.get(&p.name).cloned(),
|
||||
})
|
||||
.collect();
|
||||
let marker = s.doc.marker.unwrap_or(s.doc.features.len());
|
||||
let timeline: Vec<Value> = s
|
||||
let timeline: Vec<TimelineEntry> = s
|
||||
.doc
|
||||
.features
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, f)| {
|
||||
let r = s.model.result(f.id);
|
||||
json!({
|
||||
"id": f.id, "name": f.name, "type": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": i >= marker,
|
||||
"error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone()), "ms": r.map(|r| r.ms),
|
||||
})
|
||||
TimelineEntry {
|
||||
id: f.id,
|
||||
name: f.name.clone(),
|
||||
kind: f.kind.type_name().to_string(),
|
||||
suppressed: f.suppressed,
|
||||
rolled_back: i >= marker,
|
||||
error: r.and_then(|r| r.error.clone()),
|
||||
warning: r.and_then(|r| r.warning.clone()),
|
||||
ms: r.map(|r| r.ms),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let definitions = s.model.state();
|
||||
@@ -416,46 +567,69 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let with_counts = bool_(p, "sketch_counts").unwrap_or(false);
|
||||
// Each body is measured on its own: on all cores, in body order (as `inspect.measure`).
|
||||
let mut measured =
|
||||
if with_measure { solidcraft_kernel::map_on_threads(&st.bodies, 16, |b| measure_sheet_json(b, Some(&definitions))) } else { Vec::new() }
|
||||
if with_measure { solidcraft_kernel::map_on_threads(&st.bodies, 16, |b| measure_sheet(b, Some(&definitions))) } else { Vec::new() }
|
||||
.into_iter();
|
||||
let bodies: Vec<Value> = st
|
||||
let bodies: Vec<DocumentBody> = st
|
||||
.bodies
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let mut v = match measured.next() {
|
||||
Some(m) => m.unwrap_or_else(|| json!({"name": b.name, "error": "measuring this body failed"})),
|
||||
None => json!({"name": b.name, "feature": b.feature}),
|
||||
};
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("visible".into(), json!(s.body_visible(&b.name)));
|
||||
if s.body_removed_later(&b.name) {
|
||||
// Editing a sketch rolls the timeline back; this body is deleted further on.
|
||||
o.insert("removed_later".into(), json!(true));
|
||||
let detail = match measured.next() {
|
||||
Some(m) => {
|
||||
DocumentBodyDetail::Measured(Box::new(m.unwrap_or_else(|| measure_failed(b.name.clone(), "measuring this body failed".into()))))
|
||||
}
|
||||
}
|
||||
v
|
||||
None => DocumentBodyDetail::Listed { name: b.name.clone(), feature: b.feature },
|
||||
};
|
||||
// Editing a sketch rolls the timeline back; a body deleted further on is `removed_later`.
|
||||
DocumentBody { detail, visible: s.body_visible(&b.name), removed_later: s.body_removed_later(&b.name).then_some(true) }
|
||||
})
|
||||
.collect();
|
||||
let sketches: Vec<Value> = st
|
||||
let sketches: Vec<DocumentSketch> = st
|
||||
.sketches
|
||||
.iter()
|
||||
.map(|ss| {
|
||||
let mut v = json!({"id": ss.feature, "name": ss.name, "dof": ss.report.dof, "status": ss.report.status, "curves": ss.sketch.curves.len(), "profiles": ss.profiles.len(), "visible": crate::view::sketch_shown(s, ss.feature)});
|
||||
let mut v = DocumentSketch {
|
||||
id: ss.feature,
|
||||
name: ss.name.clone(),
|
||||
dof: ss.report.dof,
|
||||
status: ss.report.status.into(),
|
||||
curves: ss.sketch.curves.len(),
|
||||
profiles: ss.profiles.len(),
|
||||
visible: crate::view::sketch_shown(s, ss.feature),
|
||||
plane: None,
|
||||
points: None,
|
||||
constraints: None,
|
||||
};
|
||||
// A summary that stands in for the sketch's contents (the compact MCP inspect_design).
|
||||
if with_counts && let Some(o) = v.as_object_mut() {
|
||||
o.insert("plane".into(), json!(ss.plane));
|
||||
o.insert("points".into(), json!(ss.sketch.points.len()));
|
||||
o.insert("constraints".into(), json!(ss.sketch.constraints.len()));
|
||||
if with_counts {
|
||||
v.plane = Some(serde_json::to_value(ss.plane).unwrap_or_default());
|
||||
v.points = Some(ss.sketch.points.len());
|
||||
v.constraints = Some(ss.sketch.constraints.len());
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"name": s.doc.name, "units": s.doc.units, "metadata": s.doc.metadata, "path": s.path, "dirty": s.is_dirty(), "revision": s.revision,
|
||||
"active_sketch": s.active_sketch, "marker": marker,
|
||||
"params": params, "timeline": timeline, "bodies": bodies, "sketches": sketches,
|
||||
"selection": s.selection, "undo": s.undo.len(), "redo": s.redo.len(), "hidden_origin": s.visibility.hidden_origin,
|
||||
}))
|
||||
typed_reply(
|
||||
"document.inspect",
|
||||
DocumentInspectResult {
|
||||
name: s.doc.name.clone(),
|
||||
units: s.doc.units.clone(),
|
||||
metadata: s.doc.metadata.0.clone(),
|
||||
path: s.path.clone(),
|
||||
dirty: s.is_dirty(),
|
||||
revision: s.revision,
|
||||
active_sketch: s.active_sketch,
|
||||
marker,
|
||||
params,
|
||||
timeline,
|
||||
bodies,
|
||||
sketches,
|
||||
selection: serde_json::to_value(&s.selection).unwrap_or_default(),
|
||||
undo: s.undo.len(),
|
||||
redo: s.redo.len(),
|
||||
hidden_origin: s.visibility.hidden_origin.clone(),
|
||||
param_warnings: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn body_of<'a>(st: &'a solidcraft_doc::ModelState, p: &Value, cmd: &str) -> Result<&'a solidcraft_doc::ModelBody> {
|
||||
@@ -544,7 +718,8 @@ fn describe(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn commands(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(Value::Array(crate::command_specs().iter().map(|c| serde_json::to_value(c.info(s)).unwrap_or_default()).collect()))
|
||||
let list: Vec<CommandEntry> = crate::command_specs().iter().map(|c| c.info(s).into()).collect();
|
||||
typed_reply("engine.commands", list)
|
||||
}
|
||||
|
||||
fn model_threads(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
@@ -568,7 +743,7 @@ fn physical_material(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.doc_mut().materials.insert(b.clone(), canonical.clone());
|
||||
}
|
||||
}
|
||||
Ok(json!({"bodies": bodies, "material": canonical}))
|
||||
typed_reply(cmd, MaterialAssignResult { bodies, material: canonical, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// A colour parameter: `"#rrggbb"` or `[r, g, b]` (0–255).
|
||||
@@ -915,18 +1090,18 @@ fn appearance_list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn material_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let built_in = solidcraft_doc::MATERIALS.iter().map(|(n, d)| json!({"name": n, "density_g_cm3": d}));
|
||||
let built_in = solidcraft_doc::MATERIALS.iter().map(|(n, d)| ListedMaterial::BuiltIn { name: n.to_string(), density_g_cm3: *d });
|
||||
let user = s
|
||||
.doc
|
||||
.user_materials
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let mut out = super::materials::material_json(m)?;
|
||||
out["appearance"] = json!(s.doc.material_look(&m.name).as_ref().map(look_json));
|
||||
Ok(out)
|
||||
let mut out = super::materials::listed_material(m)?;
|
||||
out.appearance = s.doc.material_look(&m.name).as_ref().map(LookReply::from);
|
||||
Ok(ListedMaterial::Design(Box::new(out)))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(json!({"materials": built_in.chain(user).collect::<Vec<_>>()}))
|
||||
typed_reply("material.list", MaterialListResult { materials: built_in.chain(user).collect(), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn colored_components(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -159,9 +159,9 @@ fn material_reply(cmd: &str, m: &UserMaterial) -> Result<MaterialReply> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [`material_reply`] as JSON, for `material.list` (`cmd/inspect.rs`), which isn't converted yet.
|
||||
pub(super) fn material_json(m: &UserMaterial) -> Result<Value> {
|
||||
reply("material.list", material_reply("material.list", m)?)
|
||||
/// [`material_reply`] for `material.list` (`cmd/inspect.rs`).
|
||||
pub(super) fn listed_material(m: &UserMaterial) -> Result<MaterialReply> {
|
||||
material_reply("material.list", m)
|
||||
}
|
||||
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
|
||||
@@ -11,6 +11,7 @@ use solidcraft_geom::{Mesh, UnitVec3};
|
||||
|
||||
use super::measure_shape::{Shape, Slot, add_round, centre};
|
||||
use crate::params::bad;
|
||||
use crate::schema::inspect::{MeasureKind, MeasureResult, Measured, MeasuredItems};
|
||||
use crate::{Result, Sel, Session};
|
||||
|
||||
/// Geometry of a picked item, as points or triangles.
|
||||
@@ -665,16 +666,20 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result<Value> {
|
||||
.ok_or_else(|| bad(cmd, "an item can't be measured (pick vertices, edges, faces, bodies, sketch curves or profiles)"))?,
|
||||
);
|
||||
}
|
||||
let mut out = json!({"items": described.iter().map(|d| d.json.clone()).collect::<Vec<_>>()});
|
||||
let mut out =
|
||||
MeasuredItems { items: described.iter().map(|d| d.json.as_object().cloned().unwrap_or_default()).collect(), ..MeasuredItems::default() };
|
||||
if let [one] = described.as_slice() {
|
||||
for k in ["diameter", "radius", "circumference", "angle_deg", "arc_length", "center", "slot"] {
|
||||
if let Some(v) = one.json.get(k) {
|
||||
out[k] = v.clone();
|
||||
}
|
||||
}
|
||||
let copy = |k: &str| one.json.get(k).cloned();
|
||||
out.diameter = copy("diameter");
|
||||
out.radius = copy("radius");
|
||||
out.circumference = copy("circumference");
|
||||
out.angle_deg = copy("angle_deg");
|
||||
out.arc_length = copy("arc_length");
|
||||
out.center = copy("center");
|
||||
out.slot = copy("slot");
|
||||
if let Some(sl) = &one.slot {
|
||||
out["center_from"] = json!(sl.centres.0);
|
||||
out["center_to"] = json!(sl.centres.1);
|
||||
out.center_from = Some(sl.centres.0.into());
|
||||
out.center_to = Some(sl.centres.1.into());
|
||||
}
|
||||
}
|
||||
if let [a, b] = described.as_slice() {
|
||||
@@ -698,42 +703,45 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result<Value> {
|
||||
max = Some(exact);
|
||||
}
|
||||
if let (Some((p, q)), Some(d)) = (near, min) {
|
||||
out["distance_mm"] = json!(d);
|
||||
out["from"] = json!(p);
|
||||
out["to"] = json!(q);
|
||||
out["delta"] = json!(q - p);
|
||||
out["min"] = json!(d);
|
||||
out.set_closest(d, p, q);
|
||||
}
|
||||
let unbounded = |i: usize| matches!(sels.get(i), Some(Sel::Plane { .. } | Sel::Axis { .. }));
|
||||
if let Some((d, p, q)) = exact_min(&a.shape, &b.shape, near.map(|(p, _)| p), (unbounded(0), unbounded(1)))
|
||||
.filter(|(d, p, q)| d.is_finite() && p.is_finite() && q.is_finite())
|
||||
{
|
||||
out["distance_mm"] = json!(d);
|
||||
out["from"] = json!(p);
|
||||
out["to"] = json!(q);
|
||||
out["delta"] = json!(q - p);
|
||||
out["min"] = json!(d);
|
||||
out.set_closest(d, p, q);
|
||||
}
|
||||
if let (Some((p, q)), Some(d)) = (far, max) {
|
||||
out["max"] = json!(d);
|
||||
out["max_from"] = json!(p);
|
||||
out["max_to"] = json!(q);
|
||||
out["max_delta"] = json!(q - p);
|
||||
out.max = Some(d);
|
||||
out.max_from = Some(p.into());
|
||||
out.max_to = Some(q.into());
|
||||
out.max_delta = Some((q - p).into());
|
||||
}
|
||||
if let Some(c) = c {
|
||||
out["center_distance"] = json!(c.distance);
|
||||
out["center_from"] = json!(c.from);
|
||||
out["center_to"] = json!(c.to);
|
||||
out["center_delta"] = json!(c.to - c.from);
|
||||
out.center_distance = Some(c.distance);
|
||||
out.center_from = Some(c.from.into());
|
||||
out.center_to = Some(c.to.into());
|
||||
out.center_delta = Some((c.to - c.from).into());
|
||||
}
|
||||
out["measure"] = json!(if c.is_some() { "center" } else { "min" });
|
||||
out.measure = Some(if c.is_some() { MeasureKind::Center } else { MeasureKind::Min });
|
||||
if let (Some(da), Some(db)) = (a.dir, b.dir) {
|
||||
let both_faces = matches!(sels.as_slice(), [Sel::Face { .. }, Sel::Face { .. }]);
|
||||
let cos = if both_faces { da.dot(db) } else { corner_cos(a.shape, b.shape).unwrap_or_else(|| da.dot(db).abs()) };
|
||||
out["angle_deg"] = json!(cos.clamp(-1.0, 1.0).acos().to_degrees());
|
||||
out.angle_deg = Some(json!(cos.clamp(-1.0, 1.0).acos().to_degrees()));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
serde_json::to_value(MeasureResult { measured: Measured::Items(Box::new(out)), param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
impl MeasuredItems {
|
||||
/// The closest distance between two items and where it is: `distance_mm` and `min` are one.
|
||||
fn set_closest(&mut self, d: f64, p: Vec3, q: Vec3) {
|
||||
self.distance_mm = Some(d);
|
||||
self.min = Some(d);
|
||||
self.from = Some(p.into());
|
||||
self.to = Some(q.into());
|
||||
self.delta = Some((q - p).into());
|
||||
}
|
||||
}
|
||||
|
||||
/// Farthest pair of points between two pieces of geometry (on their samples and vertices).
|
||||
|
||||
@@ -120,6 +120,7 @@ pub mod sketch_clipboard;
|
||||
mod sketch_constraints;
|
||||
mod sketch_construction;
|
||||
mod sketch_create;
|
||||
pub(crate) use sketch_create::{AT_MUST, MAX_TEXT_EDITS};
|
||||
mod sketch_divide;
|
||||
mod sketch_ends;
|
||||
mod sketch_equation;
|
||||
@@ -128,6 +129,7 @@ mod sketch_import;
|
||||
mod sketch_inspect;
|
||||
mod sketch_modify;
|
||||
mod sketch_project;
|
||||
pub(crate) use sketch_project::{RefForm, ref_form};
|
||||
mod sketch_store;
|
||||
mod surface;
|
||||
mod surface_analysis;
|
||||
|
||||
@@ -10,8 +10,11 @@ use solidcraft_sketch::{Analysis, ConstraintKind, CurveKind, Hold, Sketch, solve
|
||||
use super::{CommandSpec, sketch_store};
|
||||
use crate::params::{bad, bool_, str_};
|
||||
use crate::schema::parameters::{
|
||||
AddedValue, ParamAddParams, ParamAdded, ParamCommentParams, ParamCommented, ParamDeleted, ParamFavoriteParams, ParamFavorited, ParamMoveParams,
|
||||
ParamMoved, ParamNameParams, ParamRenameParams, ParamRenamed,
|
||||
AddedValue, Completion, CompletionKind, DrivenFeature, EvalKind, ExprCompleteParams, ExprCompletions, ExprEvaluateParams, ExprEvaluated,
|
||||
ExprEvaluatedBody, FailedFeature, ParamAddParams, ParamAdded, ParamChangeParams, ParamChanged, ParamChangedBody, ParamChangedOne,
|
||||
ParamCommentParams, ParamCommented, ParamDeleted, ParamExportParams, ParamExportResult, ParamFavoriteParams, ParamFavorited, ParamGraphParams,
|
||||
ParamGraphResult, ParamImportParams, ParamImportResult, ParamListParams, ParamListResult, ParamMoveParams, ParamMoved, ParamNameParams,
|
||||
ParamRename, ParamRenameParams, ParamRenamed, ParamUsersParams, ParamUsersResult, ParameterRow, ParameterUser, SwitchedFeature,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
@@ -22,9 +25,22 @@ const NAME_CONTRACT: TypedContract<ParamNameParams> = TypedContract::new();
|
||||
const COMMENT_CONTRACT: TypedContract<ParamCommentParams> = TypedContract::new();
|
||||
const FAVORITE_CONTRACT: TypedContract<ParamFavoriteParams> = TypedContract::new();
|
||||
const MOVE_CONTRACT: TypedContract<ParamMoveParams> = TypedContract::new();
|
||||
const CHANGE_CONTRACT: TypedContract<ParamChangeParams> = TypedContract::new();
|
||||
const LIST_CONTRACT: TypedContract<ParamListParams> = TypedContract::new();
|
||||
const USERS_CONTRACT: TypedContract<ParamUsersParams> = TypedContract::new();
|
||||
const GRAPH_CONTRACT: TypedContract<ParamGraphParams> = TypedContract::new();
|
||||
const EXPORT_CONTRACT: TypedContract<ParamExportParams> = TypedContract::new();
|
||||
const IMPORT_CONTRACT: TypedContract<ParamImportParams> = TypedContract::new();
|
||||
const EVALUATE_CONTRACT: TypedContract<ExprEvaluateParams> = TypedContract::new();
|
||||
const COMPLETE_CONTRACT: TypedContract<ExprCompleteParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("parameters.change", "Change Parameters", change_param).at("SOLID", "MODIFY").icon("params").params(
|
||||
CommandSpec::new("parameters.change", "Change Parameters", crate::checked!("parameters.change", change_param))
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("params")
|
||||
.contract(&CHANGE_CONTRACT)
|
||||
.output(output_schema_for::<ParamChanged>)
|
||||
.params(
|
||||
"name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\"|text (new parameters default to their value's unit, a length the design's units; \
|
||||
a text parameter's expression is its text, quotes round it optional: sketch texts' words are built from it), comment?, \
|
||||
favorite?: bool, new_name?: rename (references follow; an expression `new = value` renames to `new` and sets value, \
|
||||
@@ -34,7 +50,13 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
(the configuration rules that switch a feature's suppression and read a parameter whose value changed run in their order, as on \
|
||||
activation; driven parameters and restrictions wait for a configuration edit or activation)",
|
||||
),
|
||||
CommandSpec::new("parameters.list", "List Parameters", list).icon("list").noundo().doc_only().params(
|
||||
CommandSpec::new("parameters.list", "List Parameters", crate::checked!("parameters.list", list))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&LIST_CONTRACT)
|
||||
.output(output_schema_for::<ParamListResult>)
|
||||
.params(
|
||||
"favorites?: bool (only favourites), filter?: all|user|sketch|feature|favorites → parameters (name, expression, unit, value (mm/deg in every \
|
||||
reply), display_value (in its own unit), source, feature/input, comment, favorite, uses, used_by, error) and cycles",
|
||||
),
|
||||
@@ -68,30 +90,42 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.contract(&COMMENT_CONTRACT)
|
||||
.output(output_schema_for::<ParamCommented>)
|
||||
.params("name, comment"),
|
||||
CommandSpec::new("parameters.users", "Parameter Users", users)
|
||||
CommandSpec::new("parameters.users", "Parameter Users", crate::checked!("parameters.users", users))
|
||||
.icon("graph")
|
||||
.noundo()
|
||||
.contract(&USERS_CONTRACT)
|
||||
.output(output_schema_for::<ParamUsersResult>)
|
||||
.params("name → users (parameters, feature inputs, dimensions) and the features it drives"),
|
||||
CommandSpec::new("parameters.graph", "Parameter Graph", graph)
|
||||
CommandSpec::new("parameters.graph", "Parameter Graph", crate::checked!("parameters.graph", graph))
|
||||
.icon("graph")
|
||||
.noundo()
|
||||
.contract(&GRAPH_CONTRACT)
|
||||
.output(output_schema_for::<ParamGraphResult>)
|
||||
.params("→ nodes, edges [user, used] (users include Feature:<name>), cycles, errors"),
|
||||
CommandSpec::new("parameters.export", "Export Parameters", export)
|
||||
CommandSpec::new("parameters.export", "Export Parameters", crate::checked!("parameters.export", export))
|
||||
.icon("export")
|
||||
.noundo()
|
||||
.contract(&EXPORT_CONTRACT)
|
||||
.output(output_schema_for::<ParamExportResult>)
|
||||
.params("format?: csv|json (default csv, or from the path), path?: write to a file → text"),
|
||||
CommandSpec::new("parameters.import", "Import Parameters", import)
|
||||
CommandSpec::new("parameters.import", "Import Parameters", crate::checked!("parameters.import", import))
|
||||
.icon("import")
|
||||
.contract(&IMPORT_CONTRACT)
|
||||
.output(output_schema_for::<ParamImportResult>)
|
||||
.params("text: CSV (header with name, expression, unit?, comment?) or JSON [{name, expression, unit?, comment?}] | path; all or nothing"),
|
||||
CommandSpec::new("expr.evaluate", "Evaluate Expression", evaluate)
|
||||
CommandSpec::new("expr.evaluate", "Evaluate Expression", crate::checked!("expr.evaluate", evaluate))
|
||||
.icon("params")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&EVALUATE_CONTRACT)
|
||||
.output(output_schema_for::<ExprEvaluated>)
|
||||
.params("expression, kind?: length|angle|unitless (or unit?: mm|in|deg…; text: the text a text parameter would hold, as `text`) → ok, value (mm/rad), display_value, references, error"),
|
||||
CommandSpec::new("parameters.complete", "Complete Expression", complete)
|
||||
CommandSpec::new("parameters.complete", "Complete Expression", crate::checked!("parameters.complete", complete))
|
||||
.icon("params")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&COMPLETE_CONTRACT)
|
||||
.output(output_schema_for::<ExprCompletions>)
|
||||
.params("prefix?: the text before the cursor → word, suggestions [{text, kind: parameter|function|unit|constant, detail}]"),
|
||||
];
|
||||
|
||||
@@ -108,8 +142,8 @@ fn param_name<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> {
|
||||
}
|
||||
|
||||
/// Features that fail (name and error).
|
||||
fn failing(s: &Session) -> Vec<Value> {
|
||||
s.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| json!({"feature": r.name, "error": e}))).collect()
|
||||
fn failing(s: &Session) -> Vec<FailedFeature> {
|
||||
FailedFeature::of(&s.model.results)
|
||||
}
|
||||
|
||||
pub(super) fn known(s: &Session, name: &str) -> bool {
|
||||
@@ -130,19 +164,20 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(n) = str_(p, "delete") {
|
||||
s.doc_mut().remove_param(n.trim())?;
|
||||
s.settle_value_edit(&solved)?;
|
||||
return Ok(json!({"deleted": n.trim()}));
|
||||
return reply(cmd, ParamChanged { body: ParamChangedBody::Deleted { deleted: n.trim().to_string() }, param_warnings: Vec::new() });
|
||||
}
|
||||
let mut name = param_name(cmd, p)?.to_string();
|
||||
let mut out = json!({});
|
||||
let mut renamed: Option<ParamRename> = None;
|
||||
let mut changed_through: Option<String> = None;
|
||||
if let Some(new) = str_(p, "new_name") {
|
||||
let n = s.doc_mut().rename_param(&name, new)?;
|
||||
out["renamed"] = json!({"from": name, "to": new.trim(), "references_updated": n});
|
||||
renamed = Some(ParamRename { from: name, to: new.trim().to_string(), references_updated: n });
|
||||
name = new.trim().to_string();
|
||||
}
|
||||
let has_expr = p.get("expression").is_some() || p.get("value").is_some();
|
||||
let mut e = if has_expr {
|
||||
Some(expr_arg(p, "expression").or_else(|| expr_arg(p, "value")).ok_or_else(|| bad(cmd, "`expression` must be a number or text"))?)
|
||||
} else if out.get("renamed").is_some() || p.get("favorite").is_some() || p.get("comment").is_some() {
|
||||
} else if renamed.is_some() || p.get("favorite").is_some() || p.get("comment").is_some() {
|
||||
None
|
||||
} else {
|
||||
return Err(bad(cmd, "`expression` must be a number or text"));
|
||||
@@ -151,7 +186,7 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `d7`, a feature input's) is renamed, references following, and takes the expression. A
|
||||
// text parameter's text is only text.
|
||||
if let Some((new, rhs)) = e.as_deref().filter(|_| !is_text(s, &name, str_(p, "unit"))).and_then(expr::definition) {
|
||||
if out.get("renamed").is_some() {
|
||||
if renamed.is_some() {
|
||||
return Err(bad(cmd, format!("`{new} = …` renames `{name}` already: give `new_name` or `name = expression`, not both")));
|
||||
}
|
||||
if rhs.is_empty() {
|
||||
@@ -162,7 +197,7 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `w = 20` shows `w`, and `w = 30` typed over it sets `w`.
|
||||
let refers_to = s.doc.all_param_exprs().into_iter().find(|(n, _, _)| *n == name).map(|(_, e, _)| e);
|
||||
if refers_to.as_deref().map(str::trim) == Some(new.as_str()) && s.doc.param(&new).is_some() {
|
||||
out["changed_through"] = json!(name);
|
||||
changed_through = Some(name);
|
||||
name = new.clone();
|
||||
}
|
||||
if new != name {
|
||||
@@ -170,7 +205,7 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, format!("there is already a parameter `{new}`: type `{new}` to use it, or change it in Parameters")));
|
||||
}
|
||||
let n = s.doc_mut().rename_param(&name, &new)?;
|
||||
out["renamed"] = json!({"from": name, "to": new, "references_updated": n});
|
||||
renamed = Some(ParamRename { from: name, to: new.clone(), references_updated: n });
|
||||
name = new;
|
||||
}
|
||||
e = Some(rhs);
|
||||
@@ -197,20 +232,20 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.settle_value_edit(&solved)?;
|
||||
let (vals, _) = s.doc.param_values();
|
||||
if !switched.is_empty() {
|
||||
out["switched"] = json!(switched);
|
||||
}
|
||||
out["name"] = json!(name);
|
||||
out["expression"] = json!(e);
|
||||
if let Some(t) = s.doc.text_param(&name) {
|
||||
out["text"] = json!(t.text);
|
||||
}
|
||||
out["value"] = json!(vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))));
|
||||
out["display_value"] = json!(s.doc.param_display_value(&vals, &name).map(expr::round_reported));
|
||||
out["recomputed"] = json!(s.model.last_recomputed);
|
||||
out["restored"] = json!(s.model.last_restored);
|
||||
out["errors"] = json!(failing(s));
|
||||
Ok(out)
|
||||
let one = ParamChangedOne {
|
||||
renamed,
|
||||
changed_through,
|
||||
switched,
|
||||
text: s.doc.text_param(&name).map(|t| t.text.clone()),
|
||||
value: vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))),
|
||||
display_value: s.doc.param_display_value(&vals, &name).map(expr::round_reported),
|
||||
recomputed: s.model.last_recomputed,
|
||||
restored: s.model.last_restored,
|
||||
errors: failing(s),
|
||||
name,
|
||||
expression: e,
|
||||
};
|
||||
reply(cmd, ParamChanged { body: ParamChangedBody::One(Box::new(one)), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// The point a length dimension keeps when its value changes: the first it measures from (a
|
||||
@@ -308,19 +343,15 @@ fn change_many(s: &mut Session, changes: &Value, solved: &crate::SketchValues) -
|
||||
}
|
||||
s.settle_value_edit(solved)?;
|
||||
let (vals, _) = s.doc.param_values();
|
||||
let values: serde_json::Map<String, Value> =
|
||||
list.iter().map(|(n, _)| (n.clone(), json!(vals.get(n).map(|v| expr::round_reported(expr::reported_value(*v)))))).collect();
|
||||
let mut out = json!({"changed": values, "recomputed": s.model.last_recomputed, "restored": s.model.last_restored, "errors": failing(s)});
|
||||
if !switched.is_empty() {
|
||||
out["switched"] = json!(switched);
|
||||
}
|
||||
Ok(out)
|
||||
let changed = list.iter().map(|(n, _)| (n.clone(), vals.get(n).map(|v| expr::round_reported(expr::reported_value(*v))))).collect();
|
||||
let body = ParamChangedBody::Many { changed, recomputed: s.model.last_recomputed, restored: s.model.last_restored, errors: failing(s), switched };
|
||||
reply(cmd, ParamChanged { body, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// The configuration rules that switch a feature's suppression and read a parameter this edit
|
||||
/// changed (`Document::apply_suppression_rules`), applied before the design is rebuilt, so that
|
||||
/// one rebuild has them: `[{feature, name, suppressed}]` for each feature they switched.
|
||||
fn switch_by_rules(s: &mut Session, before: &std::collections::BTreeMap<String, expr::Value>) -> Vec<Value> {
|
||||
fn switch_by_rules(s: &mut Session, before: &std::collections::BTreeMap<String, expr::Value>) -> Vec<SwitchedFeature> {
|
||||
if s.doc.configs.rules.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -329,12 +360,13 @@ fn switch_by_rules(s: &mut Session, before: &std::collections::BTreeMap<String,
|
||||
.into_iter()
|
||||
.map(|(id, suppressed)| {
|
||||
let name = s.doc.features.iter().find(|f| f.id == id).map(|f| f.name.clone());
|
||||
json!({"feature": id, "name": name, "suppressed": suppressed})
|
||||
SwitchedFeature { feature: id, name, suppressed }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "parameters.list";
|
||||
let filter = match (bool_(p, "favorites"), str_(p, "filter")) {
|
||||
(Some(true), _) => "favorites".to_string(),
|
||||
(_, Some(f)) => f.to_ascii_lowercase(),
|
||||
@@ -354,7 +386,9 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Favourites first; otherwise the table order (user, sketch, feature).
|
||||
rows.sort_by_key(|r| !r.favorite);
|
||||
let cycles = solidcraft_doc::cycles(&s.doc.all_param_exprs());
|
||||
Ok(json!({"parameters": rows, "count": rows.len(), "cycles": cycles}))
|
||||
let count = rows.len();
|
||||
let parameters = rows.into_iter().map(ParameterRow::from).collect();
|
||||
reply(cmd, ParamListResult { parameters, count, cycles: cycles.into_iter().collect(), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -438,17 +472,24 @@ fn users(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, format!("no parameter `{name}`")));
|
||||
}
|
||||
let users = s.doc.param_users(name);
|
||||
let drives: Vec<Value> =
|
||||
s.doc.features_using_param(name).iter().filter_map(|id| s.doc.feature(*id)).map(|f| json!({"id": f.id, "name": f.name})).collect();
|
||||
Ok(json!({"name": name, "users": users, "drives": drives}))
|
||||
let users = users.into_iter().map(ParameterUser::from).collect();
|
||||
let drives = s
|
||||
.doc
|
||||
.features_using_param(name)
|
||||
.iter()
|
||||
.filter_map(|id| s.doc.feature(*id))
|
||||
.map(|f| DrivenFeature { id: f.id, name: f.name.clone() })
|
||||
.collect();
|
||||
reply(cmd, ParamUsersResult { name: name.to_string(), users, drives, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn graph(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let cmd = "parameters.graph";
|
||||
let (_, errs) = s.doc.param_values();
|
||||
let nodes: Vec<String> = s.doc.param_defs().into_iter().map(|d| d.name).collect();
|
||||
let edges: Vec<[String; 2]> = s.doc.param_graph().into_iter().map(|(a, b)| [a, b]).collect();
|
||||
let cycles = solidcraft_doc::cycles(&s.doc.all_param_exprs());
|
||||
Ok(json!({"nodes": nodes, "edges": edges, "cycles": cycles, "errors": errs}))
|
||||
reply(cmd, ParamGraphResult { nodes, edges, cycles: cycles.into_iter().collect(), errors: errs, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -477,7 +518,7 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(path) = path {
|
||||
solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
}
|
||||
Ok(json!({"format": format, "path": path, "text": text}))
|
||||
reply(cmd, ParamExportResult { format, path: path.map(str::to_string), text, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// Largest parameter table we read from a file.
|
||||
@@ -495,7 +536,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let solved = s.solved_sketches();
|
||||
let names = s.doc_mut().import_params(&text)?;
|
||||
s.settle_value_edit(&solved)?;
|
||||
Ok(json!({"imported": names, "errors": failing(s)}))
|
||||
reply(cmd, ParamImportResult { imported: names, errors: failing(s), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -504,7 +545,8 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let unit = str_(p, "unit");
|
||||
// A text parameter's expression is its text.
|
||||
if unit.is_some_and(solidcraft_doc::text_params::is_text_unit) {
|
||||
return Ok(json!({"ok": true, "kind": "text", "text": solidcraft_doc::text_params::unquote(&e), "references": []}));
|
||||
let body = ExprEvaluatedBody::Text { ok: true, kind: "text".into(), text: solidcraft_doc::text_params::unquote(&e), references: Vec::new() };
|
||||
return reply(cmd, ExprEvaluated { body, param_warnings: Vec::new() });
|
||||
}
|
||||
if let Some(u) = unit
|
||||
&& expr::unit_info(u).is_none()
|
||||
@@ -531,7 +573,7 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
// `name = expression` is worth its expression, and names what it would define (#4071).
|
||||
let defines = expr::definition(&e).map(|(n, _)| n);
|
||||
let mut out = match r {
|
||||
let body = match r {
|
||||
Ok((v, k)) => {
|
||||
let value = match k {
|
||||
Kind::Length => expr::Value::length(v),
|
||||
@@ -543,17 +585,27 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, Kind::Angle) => v.to_degrees(),
|
||||
(None, _) => v,
|
||||
};
|
||||
json!({"ok": true, "value": expr::round_reported(v), "kind": k, "display_value": expr::round_reported(shown), "references": refs})
|
||||
ExprEvaluatedBody::Value {
|
||||
ok: true,
|
||||
value: expr::round_reported(v),
|
||||
kind: EvalKind::from(k),
|
||||
display_value: expr::round_reported(shown),
|
||||
references: refs,
|
||||
defines: defines.map(str::to_string),
|
||||
}
|
||||
}
|
||||
Err(err) => json!({"ok": false, "error": err.to_string().trim_start_matches("expression: ").to_string(), "references": refs}),
|
||||
Err(err) => ExprEvaluatedBody::Failed {
|
||||
ok: false,
|
||||
error: err.to_string().trim_start_matches("expression: ").to_string(),
|
||||
references: refs,
|
||||
defines: defines.map(str::to_string),
|
||||
},
|
||||
};
|
||||
if let Some(name) = defines {
|
||||
out["defines"] = json!(name);
|
||||
}
|
||||
Ok(out)
|
||||
reply(cmd, ExprEvaluated { body, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn complete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "parameters.complete";
|
||||
let text = str_(p, "prefix").unwrap_or("");
|
||||
// The identifier being typed: trailing letters, digits and underscores.
|
||||
let word: String = text.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<Vec<_>>().into_iter().rev().collect();
|
||||
@@ -565,7 +617,7 @@ fn complete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// start.
|
||||
let contains = |n: &str| word.is_empty() || n.to_ascii_lowercase().contains(&lower);
|
||||
let within = |n: &str| contains(n) || solidcraft_doc::name_words_match(n, &word);
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
let mut out: Vec<Completion> = Vec::new();
|
||||
let mut rows: Vec<solidcraft_doc::ParamRow> = s.doc.param_rows().into_iter().filter(|r| within(&r.name)).collect();
|
||||
// Names that start with the word, then names that contain it, then names matched only by
|
||||
// the starts of their words; within each, favourites, then user parameters, then the others.
|
||||
@@ -580,22 +632,22 @@ fn complete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !r.comment.is_empty() {
|
||||
detail.push_str(&format!(" — {}", r.comment));
|
||||
}
|
||||
out.push(json!({"text": r.name, "kind": "parameter", "detail": detail}));
|
||||
out.push(Completion { text: r.name, kind: CompletionKind::Parameter, detail });
|
||||
}
|
||||
for (f, sig) in expr::FUNCTIONS {
|
||||
if starts(f) {
|
||||
out.push(json!({"text": format!("{f}("), "kind": "function", "detail": sig}));
|
||||
out.push(Completion { text: format!("{f}("), kind: CompletionKind::Function, detail: sig.to_string() });
|
||||
}
|
||||
}
|
||||
if starts("pi") {
|
||||
out.push(json!({"text": "pi", "kind": "constant", "detail": "3.14159…"}));
|
||||
out.push(Completion { text: "pi".into(), kind: CompletionKind::Constant, detail: "3.14159…".into() });
|
||||
}
|
||||
for (u, k, _) in expr::UNITS {
|
||||
if !word.is_empty() && starts(u) {
|
||||
out.push(json!({"text": u, "kind": "unit", "detail": k}));
|
||||
out.push(Completion { text: u.to_string(), kind: CompletionKind::Unit, detail: EvalKind::from(*k).word().to_string() });
|
||||
}
|
||||
}
|
||||
Ok(json!({"word": word, "suggestions": out}))
|
||||
reply(cmd, ExprCompletions { word, suggestions: out, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+128
-27
@@ -11,7 +11,7 @@ use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list
|
||||
use crate::schema::sketch::{
|
||||
CancelResult, CoincidentMade, CoincidentParams, CoincidentResult, CollinearParams, ConcentricParams, Constrained, ConstraintResult, EditParams,
|
||||
EditResult, EqualMade, EqualParams, EqualResult, ExitParams, FinishResult, FixOutcome, FixParams, FixResult, HorizontalVerticalParams,
|
||||
MidpointParams, ParallelParams, PerpendicularParams, SymmetryParams, SymmetryResult, TangentParams,
|
||||
MidpointParams, ParallelParams, PerpendicularParams, SymmetryParams, SymmetryResult, TangentMade, TangentParams, TangentResult,
|
||||
};
|
||||
use crate::schema::sketch_shapes::{
|
||||
ArcCenterPointParams, ArcThreePointParams, CircleCenterParams, CircleThreePointParams, CircleTwoPointParams, Created, DrawResult, LineParams,
|
||||
@@ -198,8 +198,8 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("c_tangent")
|
||||
.enabled(in_sketch)
|
||||
.contract(&TANGENT_CONTRACT)
|
||||
.output(output_schema_for::<ConstraintResult>)
|
||||
.params(concat!("a, b: curves or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),
|
||||
.output(output_schema_for::<TangentResult>)
|
||||
.params(concat!("a, b: curves or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created), or the end point of a line or an arc: that end then lies on the other curve (or on the other end point), and its curve is tangent there, in one step (`constraints` lists both)", model_operand_doc!())),
|
||||
CommandSpec::new("sketch.constraint.equal", "Equal", crate::checked!("sketch.constraint.equal", c_equal))
|
||||
.at("SKETCH", "CONSTRAINTS")
|
||||
.icon("c_equal")
|
||||
@@ -1956,6 +1956,12 @@ fn polygon_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn slot(s: &mut Session, p: &Value, cmd: &str, c0: Vec2, c1: Vec2, w: f64) -> Result<Value> {
|
||||
let (out, info) = slot_parts(s, p, cmd, c0, c1, w)?;
|
||||
Ok(result(out, info))
|
||||
}
|
||||
|
||||
/// What [`slot`] adds: the curve and constraint ids, and the sketch's solve.
|
||||
pub(super) fn slot_parts(s: &mut Session, p: &Value, cmd: &str, c0: Vec2, c1: Vec2, w: f64) -> Result<((Vec<String>, Vec<String>), Value)> {
|
||||
let h = w / 2.0;
|
||||
let d = (c1 - c0).normalized().ok_or_else(|| bad(cmd, "the slot ends must differ"))?;
|
||||
let n = d.perp();
|
||||
@@ -1974,7 +1980,7 @@ pub(super) fn slot(s: &mut Session, p: &Value, cmd: &str, c0: Vec2, c1: Vec2, w:
|
||||
cons.push(add_c(sk, ConstraintKind::Equal { a: a0, b: a1 })?);
|
||||
Ok((ids_of(sk, &[l1, a1, l2, a0]), cons))
|
||||
})?;
|
||||
Ok(result(out, info))
|
||||
Ok((out, info))
|
||||
}
|
||||
|
||||
fn slot_c2c(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -2064,8 +2070,7 @@ fn constrain_reply(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Sk
|
||||
reply(cmd, ConstraintResult { made, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// The constraint a command added and, when the sketch already determined it, what determines it
|
||||
/// (see [`constraint_result`], which the other constraint commands build their reply with).
|
||||
/// The constraint a command added and, when the sketch already determined it, what determines it.
|
||||
fn constrained(p: &Value, cmd: &str, id: String, info: Value, by: Option<Vec<String>>) -> Result<Constrained> {
|
||||
let Some(by) = by else { return Ok(Constrained { constraint: id, sketch: info, redundant: None, determined_by: None }) };
|
||||
keep_redundant(p, cmd, &by)?;
|
||||
@@ -2378,21 +2383,6 @@ pub(super) fn keep_redundant(p: &Value, cmd: &str, by: &[String]) -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The result of a constraint command: the constraint, and whether it is redundant (and what
|
||||
/// determines it).
|
||||
pub(super) fn constraint_result(p: &Value, cmd: &str, id: String, info: Value, by: Option<Vec<String>>, extra: Value) -> Result<Value> {
|
||||
let mut out = json!({"constraint": id, "sketch": info});
|
||||
if let Some(by) = by {
|
||||
keep_redundant(p, cmd, &by)?;
|
||||
out["redundant"] = json!(true);
|
||||
out["determined_by"] = json!(by);
|
||||
}
|
||||
if let (Some(o), Value::Object(e)) = (out.as_object_mut(), extra) {
|
||||
o.extend(e);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The residual of the constraint `id` where the sketch is now (see
|
||||
/// [`solidcraft_sketch::constraint_residual`]).
|
||||
pub(super) fn residual_of(sk: &Sketch, id: &str) -> Option<f64> {
|
||||
@@ -2646,12 +2636,123 @@ fn two_curves_or_axes(sk: &mut Sketch, p: &Value, cmd: &str) -> Result<(usize, u
|
||||
}
|
||||
|
||||
fn c_tangent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.tangent", &["a", "b"])?;
|
||||
constrain_reply(s, p, "sketch.constraint.tangent", |sk| {
|
||||
two_curves_or_axes(sk, p, "sketch.constraint.tangent")
|
||||
.and_then(|ab| two_different("sketch.constraint.tangent", ab))
|
||||
.map(|(a, b)| ConstraintKind::Tangent { a, b })
|
||||
})
|
||||
let cmd = "sketch.constraint.tangent";
|
||||
let p = &super::sketch_project::project_operands(s, p, cmd, &["a", "b"])?;
|
||||
let sk = sketch_store::read(&s.doc, sketch_store::target(s, p, cmd)?)?;
|
||||
if tangent_end(sk, p, "a").is_some() || tangent_end(sk, p, "b").is_some() {
|
||||
return tangent_at_end(s, p, cmd);
|
||||
}
|
||||
let made = constrain(s, p, cmd, |sk| {
|
||||
two_curves_or_axes(sk, p, cmd).and_then(|ab| two_different(cmd, ab)).map(|(a, b)| ConstraintKind::Tangent { a, b })
|
||||
})?;
|
||||
reply(cmd, TangentResult { made: TangentMade::Curves(made), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// The point a Tangent operand names when it names no curve and no sketch axis (#12092). `x` and
|
||||
/// `y` name the axes even before their lines exist, as in [`line_or_axis_ref`].
|
||||
fn tangent_end(sk: &Sketch, p: &Value, key: &str) -> Option<usize> {
|
||||
let id = p.get(key)?.as_str()?;
|
||||
if sk.curve_index(id).is_some() || solidcraft_sketch::sketch_axis_geom(id).is_some() {
|
||||
return None;
|
||||
}
|
||||
sk.resolve_point(id)
|
||||
}
|
||||
|
||||
/// The one curve that ends at point `q`, leaving out `other`; `None` when no curve or more than
|
||||
/// one does.
|
||||
fn ended_by(sk: &Sketch, q: usize, other: Option<usize>) -> Option<usize> {
|
||||
let mut owners = sk
|
||||
.curves
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| Some(*i) != other && c.kind.ends().is_some_and(|(start, end)| start == q || end == q))
|
||||
.map(|(i, _)| i);
|
||||
let first = owners.next()?;
|
||||
owners.next().is_none().then_some(first)
|
||||
}
|
||||
|
||||
/// Whether `k` already holds through the sketch's own constraints, so Tangent need not add it
|
||||
/// (#12092): the same constraint (a coincident in either order), or a point on a curve that is one
|
||||
/// of that curve's ends or is joined to one by a coincident.
|
||||
fn already_held(sk: &Sketch, k: &ConstraintKind) -> bool {
|
||||
let joined = |p: usize, q: usize| {
|
||||
p == q
|
||||
|| sk
|
||||
.constraints
|
||||
.iter()
|
||||
.any(|c| !c.driven && matches!(c.kind, ConstraintKind::Coincident { p: x, q: y } if (x, y) == (p, q) || (x, y) == (q, p)))
|
||||
};
|
||||
match *k {
|
||||
ConstraintKind::Coincident { p, q } => joined(p, q),
|
||||
ConstraintKind::PointOnCurve { p, c } => {
|
||||
sk.curves.get(c).and_then(|curve| curve.kind.ends()).is_some_and(|(start, end)| joined(p, start) || joined(p, end))
|
||||
|| sk.constraints.iter().any(|x| !x.driven && x.kind == *k)
|
||||
}
|
||||
_ => sk.constraints.iter().any(|c| !c.driven && c.kind == *k),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tangent with a curve's end point for `a` or `b` (#12092): that end lies on the other curve,
|
||||
/// or on the other end point, and the curve it ends is tangent to the other curve there. Both
|
||||
/// constraints come in one step. A line's end picked with a curve is what moves; otherwise the
|
||||
/// first pick stays and the second moves, as with two curves.
|
||||
fn tangent_at_end(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let not_an_end = |key: &str| {
|
||||
let id = p.get(key).and_then(Value::as_str).unwrap_or_default();
|
||||
bad(cmd, format!("`{id}` is not the end of one curve: pick a curve, or the end point of a line or an arc"))
|
||||
};
|
||||
let (out, info) = edit(s, p, cmd, true, |sk, _| {
|
||||
let rep = solve(&mut sk.clone());
|
||||
let (pa, pb) = (tangent_end(sk, p, "a"), tangent_end(sk, p, "b"));
|
||||
let ca = if pa.is_none() { Some(line_or_axis_ref(sk, p.get("a"), cmd, "a")?) } else { None };
|
||||
let cb = if pb.is_none() { Some(line_or_axis_ref(sk, p.get("b"), cmd, "b")?) } else { None };
|
||||
let a = match (ca, pa) {
|
||||
(Some(c), _) => c,
|
||||
(None, Some(q)) => ended_by(sk, q, cb).ok_or_else(|| not_an_end("a"))?,
|
||||
(None, None) => return Err(not_an_end("a")),
|
||||
};
|
||||
let b = match (cb, pb) {
|
||||
(Some(c), _) => c,
|
||||
(None, Some(q)) => ended_by(sk, q, Some(a)).ok_or_else(|| not_an_end("b"))?,
|
||||
(None, None) => return Err(not_an_end("b")),
|
||||
};
|
||||
let (a, b) = two_different(cmd, (a, b))?;
|
||||
let touch = match (pa, pb) {
|
||||
(Some(q), Some(r)) if q != r => Some(ConstraintKind::Coincident { p: q, q: r }),
|
||||
(Some(q), None) => Some(ConstraintKind::PointOnCurve { p: q, c: b }),
|
||||
(None, Some(r)) => Some(ConstraintKind::PointOnCurve { p: r, c: a }),
|
||||
_ => None,
|
||||
};
|
||||
// A joint: the end already lies on the other curve (it is that curve's end, or joined to it).
|
||||
let joint = touch.as_ref().is_some_and(|k| already_held(sk, k));
|
||||
let mut ids = Vec::new();
|
||||
if let Some(k) = touch.filter(|_| !joint) {
|
||||
ids.push(add_c(sk, k)?);
|
||||
}
|
||||
let tangent = add_c(sk, ConstraintKind::Tangent { a, b })?;
|
||||
ids.push(tangent.clone());
|
||||
// A line's end and a curve, in either order: only that end moves, so the line turns about
|
||||
// its other end and gets longer or shorter to meet the curve (#12092). At a joint that end
|
||||
// can't leave the other curve: the curve it ends stays, and the other curve moves. Otherwise,
|
||||
// as for two curves, the first pick stays and the second moves.
|
||||
let end = match (pa, pb) {
|
||||
(Some(q), None) => Some((q, a, b)),
|
||||
(None, Some(r)) => Some((r, b, a)),
|
||||
_ => None,
|
||||
};
|
||||
let far = end.filter(|_| !joint).and_then(|(q, line, other)| match sk.curves.get(line).map(|c| &c.kind) {
|
||||
Some(k @ CurveKind::Line { .. }) => k.ends().map(|(start, end)| (q, if start == q { end } else { start }, other)),
|
||||
_ => None,
|
||||
});
|
||||
let (stay, moves) = end.filter(|_| joint).map_or((a, b), |(_, own, other)| (own, other));
|
||||
match far {
|
||||
Some((q, f, other)) => apply_in_order(sk, &rep, &[Ent::Curve(other), Ent::Point(f)], Ent::Point(q), cmd, &ids)?,
|
||||
None => apply_in_order(sk, &rep, &[Ent::Curve(stay)], Ent::Curve(moves), cmd, &ids)?,
|
||||
}
|
||||
Ok((tangent, ids))
|
||||
})?;
|
||||
let (constraint, constraints) = out;
|
||||
reply(cmd, TangentResult { made: TangentMade::End { constraint, constraints, sketch: info }, param_warnings: Vec::new() })
|
||||
}
|
||||
fn c_equal(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("curves").is_some() {
|
||||
|
||||
@@ -11,16 +11,30 @@ use super::sketch::edit;
|
||||
use super::sketch_store;
|
||||
use super::{CommandSpec, in_sketch};
|
||||
use crate::params::{bad, req_vec3, vec3};
|
||||
use crate::schema::sketch_3d::{Curves3dResult, Line3dParams, Move3dParams, Move3dResult, Point3dParams, Point3dResult, Spline3dParams};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const LINE3D_CONTRACT: TypedContract<Line3dParams> = TypedContract::new();
|
||||
const SPLINE3D_CONTRACT: TypedContract<Spline3dParams> = TypedContract::new();
|
||||
const POINT3D_CONTRACT: TypedContract<Point3dParams> = TypedContract::new();
|
||||
const MOVE3D_CONTRACT: TypedContract<Move3dParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.line3d", "3D Line", line3d).icon("line").enabled(in_sketch_3d).params(concat!(
|
||||
"points: [[x,y,z]…] world points (2 or more): one 3D line per segment, joined end to end (needs 3D Sketch on)",
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.spline3d", "3D Spline", spline3d)
|
||||
CommandSpec::new("sketch.line3d", "3D Line", crate::checked!("sketch.line3d", line3d))
|
||||
.icon("line")
|
||||
.enabled(in_sketch_3d)
|
||||
.contract(&LINE3D_CONTRACT)
|
||||
.output(output_schema_for::<Curves3dResult>)
|
||||
.params(concat!(
|
||||
"points: [[x,y,z]…] world points (2 or more): one 3D line per segment, joined end to end (needs 3D Sketch on)",
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.spline3d", "3D Spline", crate::checked!("sketch.spline3d", spline3d))
|
||||
.icon("spline")
|
||||
.enabled(in_sketch_3d)
|
||||
.contract(&SPLINE3D_CONTRACT)
|
||||
.output(output_schema_for::<Curves3dResult>)
|
||||
.params(concat!("points: [[x,y,z]…] world fit points (2 or more): a smooth 3D curve through them (needs 3D Sketch on)", created_doc!())),
|
||||
CommandSpec::new("sketch.arc3d", "3D Arc", arc3d)
|
||||
.icon("arc3")
|
||||
@@ -29,16 +43,26 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"start, through, end: [x,y,z] world points: an exact circular arc through them, from start through through to end (needs 3D Sketch on). Stored exactly (centre, radius, angles), so path consumers can treat it as a true arc",
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.point3d", "3D Point", point3d)
|
||||
CommandSpec::new("sketch.point3d", "3D Point", crate::checked!("sketch.point3d", point3d))
|
||||
.icon("point")
|
||||
.enabled(in_sketch_3d)
|
||||
.contract(&POINT3D_CONTRACT)
|
||||
.output(output_schema_for::<Point3dResult>)
|
||||
.params(concat!("point: [x,y,z] world point (needs 3D Sketch on)", created_doc!())),
|
||||
CommandSpec::new("sketch.move3d", "Move 3D Point", move3d)
|
||||
CommandSpec::new("sketch.move3d", "Move 3D Point", crate::checked!("sketch.move3d", move3d))
|
||||
.icon("sketch_move")
|
||||
.enabled(in_sketch)
|
||||
.contract(&MOVE3D_CONTRACT)
|
||||
.output(output_schema_for::<Move3dResult>)
|
||||
.params("wire: drawn 3D curve or point id, index?: fit point (default 0), to: [x,y,z] | by: [dx,dy,dz]; points joined to it move too"),
|
||||
];
|
||||
|
||||
/// A command's reply as JSON: built from the type its output schema describes, so the two can't
|
||||
/// drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn points(cmd: &str, p: &Value, min: usize) -> Result<Vec<Vec3>> {
|
||||
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`points` must list [x,y,z] points"))?;
|
||||
if a.len() < min || a.len() > solidcraft_sketch::MAX_FIT_POINTS {
|
||||
@@ -106,7 +130,7 @@ fn line3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
needs_3d(sk, cmd)?;
|
||||
pts.windows(2).map(|w| sk.add_drawn_wire_in(w, WireSpace::Component).map_err(Into::into)).collect::<Result<Vec<String>>>()
|
||||
})?;
|
||||
Ok(json!({"curves": ids, "sketch": info}))
|
||||
reply(cmd, Curves3dResult { curves: ids, sketch: info, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn spline3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -117,7 +141,7 @@ fn spline3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
needs_3d(sk, cmd)?;
|
||||
Ok(sk.add_drawn_wire_in(&pts, WireSpace::Component)?)
|
||||
})?;
|
||||
Ok(json!({"curves": [id], "sketch": info}))
|
||||
reply(cmd, Curves3dResult { curves: vec![id], sketch: info, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn arc3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -145,7 +169,7 @@ fn point3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
needs_3d(sk, cmd)?;
|
||||
Ok(sk.add_drawn_wire_in(&[at], WireSpace::Component)?)
|
||||
})?;
|
||||
Ok(json!({"point": id, "sketch": info}))
|
||||
reply(cmd, Point3dResult { point: id, sketch: info, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn move3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -183,7 +207,7 @@ fn move3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
Ok(sk.move_drawn_point(&wire, index, to)?)
|
||||
})?;
|
||||
Ok(json!({"moved": n, "sketch": info}))
|
||||
reply(cmd, Move3dResult { moved: n, sketch: info, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -95,6 +95,23 @@ fn a_real_curve_named_like_an_axis_wins() {
|
||||
assert!((start.x + end.x - 10.0).abs() < 1e-7, "mirrored about x = 5: {start:?} {end:?}");
|
||||
}
|
||||
|
||||
/// Tangent also takes a curve's end point (#12092), but `x` and `y` still name the axes before
|
||||
/// their lines exist: a point called `x` does not take the axis's place.
|
||||
#[test]
|
||||
fn a_point_named_like_an_axis_leaves_tangent_on_the_axis() {
|
||||
for (a, b) in [("c", "x"), ("x", "c")] {
|
||||
let mut s = on(json!("XY"));
|
||||
run(&mut s, "sketch.point", json!({"point": [3, 7], "id": "x", "connect": false}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": [10, 4], "radius": 2, "id": "c"}));
|
||||
run(&mut s, "sketch.constraint.tangent", json!({"a": a, "b": b}));
|
||||
let sk = sketch(&s);
|
||||
assert_eq!(axis_lines(&sk).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["x"], "{a}, {b}: the x axis's line");
|
||||
let CurveKind::Circle { c: centre, r } = sk.curves[sk.curve_index("c").unwrap()].kind else { panic!() };
|
||||
assert!((sk.point(centre).unwrap().y.abs() - r).abs() < 1e-7, "{a}, {b}: tangent to x");
|
||||
assert!(pt(&sk, "x").dist(Vec2::new(3.0, 7.0)) < 1e-9, "{a}, {b}: the point called x moved");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangle_centred_on_the_origin_keeps_one_profile() {
|
||||
let mut s = on(json!("XY"));
|
||||
|
||||
@@ -1,54 +1,81 @@
|
||||
//! More sketch constraints (curvature, polygon), constraint glyph anchors and snapping
|
||||
//! inference for interactive tools.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
use solidcore_record::Vec2;
|
||||
use solidcraft_geom::prelude::*;
|
||||
use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch};
|
||||
|
||||
use super::sketch::{add_c, constraint_result, dof_now, edit, listed, redundancy, residual_of};
|
||||
use super::sketch::{add_c, dof_now, edit, keep_redundant, listed, redundancy, residual_of};
|
||||
use super::sketch_store;
|
||||
use super::{CommandSpec, in_sketch};
|
||||
use crate::params::{bad, num, req_vec2, str_, string_list, vec2};
|
||||
use crate::schema::sketch_constraints::{ToggleDiameterParams, ToggleDiameterResult};
|
||||
use crate::schema::sketch_constraints::{
|
||||
AutoConstrainDatumParams, AutoConstrainParams, AutoConstrainResult, ConstrainerParams, ConstrainerResult, ConstraintAdded, CurvatureParams,
|
||||
FinishAutoConstrainParams, Glyph, GlyphsParams, GlyphsResult, PolygonParams, PolygonResult, Snap, SnapParams, SnapResult, ToggleDiameterParams,
|
||||
ToggleDiameterResult, ToggleDrivenParams, ToggleDrivenResult,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const TOGGLE_DIAMETER_CONTRACT: TypedContract<ToggleDiameterParams> = TypedContract::new();
|
||||
const CURVATURE_CONTRACT: TypedContract<CurvatureParams> = TypedContract::new();
|
||||
const POLYGON_CONTRACT: TypedContract<PolygonParams> = TypedContract::new();
|
||||
const AUTO_CONSTRAIN_CONTRACT: TypedContract<AutoConstrainParams> = TypedContract::new();
|
||||
const AUTO_CONSTRAIN_DATUM_CONTRACT: TypedContract<AutoConstrainDatumParams> = TypedContract::new();
|
||||
const FINISH_AUTO_CONSTRAIN_CONTRACT: TypedContract<FinishAutoConstrainParams> = TypedContract::new();
|
||||
const CONSTRAINER_CONTRACT: TypedContract<ConstrainerParams> = TypedContract::new();
|
||||
const TOGGLE_DRIVEN_CONTRACT: TypedContract<ToggleDrivenParams> = TypedContract::new();
|
||||
const GLYPHS_CONTRACT: TypedContract<GlyphsParams> = TypedContract::new();
|
||||
const SNAP_CONTRACT: TypedContract<SnapParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.constraint.curvature", "Curvature", c_smooth)
|
||||
CommandSpec::new("sketch.constraint.curvature", "Curvature", crate::checked!("sketch.constraint.curvature", c_smooth))
|
||||
.at("SKETCH", "CONSTRAINTS")
|
||||
.icon("c_smooth")
|
||||
.enabled(in_sketch)
|
||||
.contract(&CURVATURE_CONTRACT)
|
||||
.output(output_schema_for::<ConstraintAdded>)
|
||||
.params("a, b: two curves sharing an end point (curvature continuous, G2)"),
|
||||
CommandSpec::new("sketch.constraint.polygon", "Polygon", c_polygon)
|
||||
CommandSpec::new("sketch.constraint.polygon", "Polygon", crate::checked!("sketch.constraint.polygon", c_polygon))
|
||||
.at("SKETCH", "CONSTRAINTS")
|
||||
.icon("c_polygon")
|
||||
.enabled(in_sketch)
|
||||
.contract(&POLYGON_CONTRACT)
|
||||
.output(output_schema_for::<PolygonResult>)
|
||||
.params("lines: [line ids] of a closed chain: equal sides with every corner on one circle (a regular polygon)"),
|
||||
CommandSpec::new("sketch.auto_constrain", "AutoConstrain", auto_constrain)
|
||||
CommandSpec::new("sketch.auto_constrain", "AutoConstrain", crate::checked!("sketch.auto_constrain", auto_constrain))
|
||||
.at("SKETCH", "CONSTRAINTS")
|
||||
.icon("auto_constrain")
|
||||
.enabled(in_sketch)
|
||||
.contract(&AUTO_CONSTRAIN_CONTRACT)
|
||||
.output(output_schema_for::<AutoConstrainResult>)
|
||||
.params("tolerance?: mm (default 0.01), angle_tolerance?: deg (default 1), dimensions?: bool (default true): infer constraints, then dimension until fully constrained"),
|
||||
CommandSpec::new("sketch.auto_constrain_from_datum", "AutoConstrain from Datum", auto_constrain_datum)
|
||||
CommandSpec::new("sketch.auto_constrain_from_datum", "AutoConstrain from Datum", crate::checked!("sketch.auto_constrain_from_datum", auto_constrain_datum))
|
||||
.at("SKETCH", "CONSTRAINTS")
|
||||
.icon("auto_constrain")
|
||||
.enabled(in_sketch)
|
||||
.contract(&AUTO_CONSTRAIN_DATUM_CONTRACT)
|
||||
.output(output_schema_for::<AutoConstrainResult>)
|
||||
.params("datum: point ref (default origin); like AutoConstrain with positions measured from the datum"),
|
||||
CommandSpec::new("sketch.finish_auto_constrain", "Finish with AutoConstrain", auto_constrain_finish)
|
||||
CommandSpec::new("sketch.finish_auto_constrain", "Finish with AutoConstrain", crate::checked!("sketch.finish_auto_constrain", auto_constrain_finish))
|
||||
.at("SKETCH", "FINISH SKETCH")
|
||||
.icon("finish")
|
||||
.enabled(in_sketch)
|
||||
.contract(&FINISH_AUTO_CONSTRAIN_CONTRACT)
|
||||
.output(output_schema_for::<AutoConstrainResult>)
|
||||
.params("like AutoConstrain, then Finish Sketch"),
|
||||
CommandSpec::new("sketch.constrainer", "Sketch Constrainer", smart_constrain)
|
||||
CommandSpec::new("sketch.constrainer", "Sketch Constrainer", crate::checked!("sketch.constrainer", smart_constrain))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("constrainer")
|
||||
.enabled(in_sketch)
|
||||
.contract(&CONSTRAINER_CONTRACT)
|
||||
.output(output_schema_for::<ConstrainerResult>)
|
||||
.params("entities: [one or two sketch entity ids]: applies the constraint the geometry nearly has (horizontal/vertical, parallel, perpendicular, collinear, coincident, concentric, equal, tangent)"),
|
||||
CommandSpec::new("sketch.toggle_driven", "Toggle Driven Dimension", toggle_driven).icon("dimension")
|
||||
CommandSpec::new("sketch.toggle_driven", "Toggle Driven Dimension", crate::checked!("sketch.toggle_driven", toggle_driven)).icon("dimension")
|
||||
.enabled(in_sketch)
|
||||
.contract(&TOGGLE_DRIVEN_CONTRACT)
|
||||
.output(output_schema_for::<ToggleDrivenResult>)
|
||||
.params("constraint: dimension id, driven?: bool (default toggles); a driving dimension gets a parameter with its current value"),
|
||||
CommandSpec::new("sketch.toggle_diameter", "Toggle Radius / Diameter", crate::checked!("sketch.toggle_diameter", toggle_diameter))
|
||||
.icon("dimension")
|
||||
@@ -56,13 +83,17 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.contract(&TOGGLE_DIAMETER_CONTRACT)
|
||||
.output(output_schema_for::<ToggleDiameterResult>)
|
||||
.params("constraint: a circle's or an arc's radius or diameter dimension id; diameter?: bool (default: the other one); sketch?: id|name (default: the one being edited). The circle stays the same size: its parameter is halved or doubled (a plain value is rewritten, an expression becomes `(e) / 2` or `2 * (e)`); refused when anything else uses that parameter"),
|
||||
CommandSpec::new("sketch.glyphs", "Constraint Glyphs", glyphs).icon("eye")
|
||||
CommandSpec::new("sketch.glyphs", "Constraint Glyphs", crate::checked!("sketch.glyphs", glyphs)).icon("eye")
|
||||
.enabled(in_sketch)
|
||||
.noundo()
|
||||
.contract(&GLYPHS_CONTRACT)
|
||||
.output(output_schema_for::<GlyphsResult>)
|
||||
.params("sketch?: id|name: every constraint with where to draw its glyph (sketch coordinates)"),
|
||||
CommandSpec::new("sketch.snap", "Snap Inference", snap).icon("snap")
|
||||
CommandSpec::new("sketch.snap", "Snap Inference", crate::checked!("sketch.snap", snap)).icon("snap")
|
||||
.enabled(in_sketch)
|
||||
.noundo()
|
||||
.contract(&SNAP_CONTRACT)
|
||||
.output(output_schema_for::<SnapResult>)
|
||||
.params("at: [x,y], from?: [x,y] (previous click), radius?: mm (snap distance, default 1): what a click there would snap to and infer"),
|
||||
];
|
||||
|
||||
@@ -78,7 +109,26 @@ fn c_smooth(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(id)
|
||||
})?;
|
||||
let by = redundancy(s, p, cmd, before, &info, residual, &id)?;
|
||||
constraint_result(p, cmd, id, info, by, Value::Null)
|
||||
let (redundant, determined_by) = redundant_part(p, cmd, by)?;
|
||||
reply(cmd, ConstraintAdded { constraint: id, sketch: info, redundant, determined_by, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// A command's reply as JSON: they build their replies from the types their output schemas
|
||||
/// describe, so the two can't drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
/// What a new constraint's reply says of redundancy: whether it is, and by which constraints. A
|
||||
/// redundant one is refused when the call asked for `if_redundant: "refuse"`.
|
||||
fn redundant_part(p: &Value, cmd: &str, by: Option<Vec<String>>) -> Result<(bool, Option<Vec<String>>)> {
|
||||
match by {
|
||||
Some(by) => {
|
||||
keep_redundant(p, cmd, &by)?;
|
||||
Ok((true, Some(by)))
|
||||
}
|
||||
None => Ok((false, None)),
|
||||
}
|
||||
}
|
||||
|
||||
fn curve(sk: &Sketch, v: Option<&Value>, cmd: &str) -> Result<usize> {
|
||||
@@ -126,7 +176,7 @@ fn c_polygon(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(cons)
|
||||
})?;
|
||||
Ok(json!({"constraints": out, "sketch": info}))
|
||||
reply(cmd, PolygonResult { constraints: out, sketch: info, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// Most constraints AutoConstrain tries.
|
||||
@@ -273,7 +323,7 @@ fn auto(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
// its freedom whenever they change constraints; no separate initial solve is needed.
|
||||
Ok(run_auto(sk, doc, p, datum, rep.dof))
|
||||
})?;
|
||||
Ok(json!({"added": added, "dof": dof, "sketch": info}))
|
||||
reply(cmd, AutoConstrainResult { added, dof, sketch: info, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn auto_constrain(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -375,7 +425,19 @@ fn smart_constrain(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(id)
|
||||
})?;
|
||||
let by = redundancy(s, p, cmd, before, &info, residual, &id)?;
|
||||
constraint_result(p, cmd, id, info, by, json!({"type": name}))
|
||||
let (redundant, determined_by) = redundant_part(p, cmd, by)?;
|
||||
reply(
|
||||
cmd,
|
||||
ConstrainerResult {
|
||||
constraint: id,
|
||||
sketch: info,
|
||||
redundant,
|
||||
determined_by,
|
||||
kind: name.to_string(),
|
||||
created: None,
|
||||
param_warnings: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn toggle_driven(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -417,7 +479,7 @@ fn toggle_driven(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
s.doc_mut().prune_model_params();
|
||||
Ok(json!({"constraint": cid, "driven": driven, "sketch": info}))
|
||||
reply(cmd, ToggleDrivenResult { constraint: cid, driven, sketch: info, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn toggle_diameter(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -528,26 +590,32 @@ fn glyphs(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.model.state();
|
||||
let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?;
|
||||
let failing = &ss.report.failing;
|
||||
let list: Vec<Value> = ss
|
||||
let glyphs: Vec<Glyph> = ss
|
||||
.sketch
|
||||
.constraints
|
||||
.iter()
|
||||
.map(|c| {
|
||||
json!({
|
||||
"id": c.id,
|
||||
"name": c.kind.name(),
|
||||
"dimension": c.kind.is_dimension(),
|
||||
"driven": c.driven,
|
||||
"value": c.kind.value(),
|
||||
"param": c.param,
|
||||
"at": anchor(&ss.sketch, &c.kind),
|
||||
"failing": failing.contains(&c.id),
|
||||
// Implied by the others (it removes no freedom) but holding: shown dimmed.
|
||||
"redundant": ss.report.redundant.contains(&c.id),
|
||||
})
|
||||
.map(|c| Glyph {
|
||||
id: c.id.clone(),
|
||||
name: c.kind.name().to_string(),
|
||||
dimension: c.kind.is_dimension(),
|
||||
driven: c.driven,
|
||||
value: c.kind.value(),
|
||||
param: c.param.clone(),
|
||||
at: anchor(&ss.sketch, &c.kind).map(|a| [a.x, a.y]),
|
||||
failing: failing.contains(&c.id),
|
||||
// Implied by the others (it removes no freedom) but holding: shown dimmed.
|
||||
redundant: ss.report.redundant.contains(&c.id),
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"sketch": id, "glyphs": list, "dof": ss.report.dof, "fully_constrained": ss.report.fully_constrained(), "conflicts": failing}))
|
||||
let result = GlyphsResult {
|
||||
sketch: id,
|
||||
glyphs,
|
||||
dof: ss.report.dof,
|
||||
fully_constrained: ss.report.fully_constrained(),
|
||||
conflicts: failing.clone(),
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
reply("sketch.glyphs", result)
|
||||
}
|
||||
|
||||
/// Snap inference for a click at `at`: the nearest sketch point (coincident), the midpoint of a
|
||||
@@ -562,12 +630,12 @@ fn snap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.model.state();
|
||||
let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch is not evaluated".into()))?;
|
||||
let sk = &ss.sketch;
|
||||
let mut out: Vec<(f64, Value)> = Vec::new();
|
||||
let mut out: Vec<(f64, Snap)> = Vec::new();
|
||||
// Points (end points, centres, the origin).
|
||||
for q in &sk.points {
|
||||
let d = q.pos.dist(at);
|
||||
if d <= r {
|
||||
out.push((d * 0.5, json!({"type": "coincident", "point": q.id, "at": q.pos})));
|
||||
out.push((d * 0.5, Snap::Coincident { point: q.id.clone(), at: [q.pos.x, q.pos.y] }));
|
||||
}
|
||||
}
|
||||
for (i, c) in sk.curves.iter().enumerate() {
|
||||
@@ -577,13 +645,13 @@ fn snap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let m = (pa + pb) * 0.5;
|
||||
let d = m.dist(at);
|
||||
if d <= r {
|
||||
out.push((d * 0.6, json!({"type": "midpoint", "curve": c.id, "at": m})));
|
||||
out.push((d * 0.6, Snap::Midpoint { curve: c.id.clone(), at: [m.x, m.y] }));
|
||||
}
|
||||
}
|
||||
if let Some(sh) = sk.shape(i) {
|
||||
let q = sh.project(at);
|
||||
if sh.dist(at) <= r && q.dist(at) <= r {
|
||||
out.push((sh.dist(at) + r * 0.5, json!({"type": "on_curve", "curve": c.id, "at": q})));
|
||||
out.push((sh.dist(at) + r * 0.5, Snap::OnCurve { curve: c.id.clone(), at: [q.x, q.y] }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -591,15 +659,15 @@ fn snap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(f) = from {
|
||||
let d = at - f;
|
||||
if d.y.abs() <= r && d.x.abs() > r {
|
||||
out.push((d.y.abs() + r, json!({"type": "horizontal", "at": [at.x, f.y]})));
|
||||
out.push((d.y.abs() + r, Snap::Horizontal { at: [at.x, f.y] }));
|
||||
}
|
||||
if d.x.abs() <= r && d.y.abs() > r {
|
||||
out.push((d.x.abs() + r, json!({"type": "vertical", "at": [f.x, at.y]})));
|
||||
out.push((d.x.abs() + r, Snap::Vertical { at: [f.x, at.y] }));
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let list: Vec<Value> = out.into_iter().take(8).map(|x| x.1).collect();
|
||||
Ok(json!({"snaps": list}))
|
||||
let snaps: Vec<Snap> = out.into_iter().take(8).map(|x| x.1).collect();
|
||||
reply(cmd, SnapResult { snaps, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -13,11 +13,16 @@ macro_rules! text_style_doc {
|
||||
};
|
||||
}
|
||||
|
||||
use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_parg, result, slot};
|
||||
use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_parg, slot_parts};
|
||||
use super::sketch_store;
|
||||
use super::{CommandSpec, in_sketch};
|
||||
use crate::params::{bad, num, req_vec2, str_, string_list};
|
||||
use crate::schema::sketch_create::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult};
|
||||
use crate::schema::sketch_create::{
|
||||
ArcSlotCenterParams, ArcSlotResult, ArcSlotThreePointParams, ArcTangentParams, BlendCurveParams, CenterlineParams, ConicParams,
|
||||
ControlPointSplineParams, DrawResult, EditTextParams, EditTextResult, EllipseParams, FitPointSplineParams, InfiniteLineParams, LineTypeResult,
|
||||
MidpointLineParams, SketchTextParams, SlotCenterPointParams, SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams,
|
||||
SplineReverseResult, TextChange, TextEditsResult, TextExpressions, TextResult, ThreeTangentCircleParams, TwoTangentCircleParams,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
@@ -29,62 +34,108 @@ mod text_move_tests;
|
||||
#[path = "sketch_text_expr_tests.rs"]
|
||||
mod text_expr_tests;
|
||||
|
||||
const MIDPOINT_LINE_CONTRACT: TypedContract<MidpointLineParams> = TypedContract::new();
|
||||
const ARC_TANGENT_CONTRACT: TypedContract<ArcTangentParams> = TypedContract::new();
|
||||
const TWO_TANGENT_CONTRACT: TypedContract<TwoTangentCircleParams> = TypedContract::new();
|
||||
const THREE_TANGENT_CONTRACT: TypedContract<ThreeTangentCircleParams> = TypedContract::new();
|
||||
const SLOT_CENTER_POINT_CONTRACT: TypedContract<SlotCenterPointParams> = TypedContract::new();
|
||||
const ARC_SLOT_THREE_CONTRACT: TypedContract<ArcSlotThreePointParams> = TypedContract::new();
|
||||
const ARC_SLOT_CENTER_CONTRACT: TypedContract<ArcSlotCenterParams> = TypedContract::new();
|
||||
const ELLIPSE_CONTRACT: TypedContract<EllipseParams> = TypedContract::new();
|
||||
const SPLINE_FIT_CONTRACT: TypedContract<FitPointSplineParams> = TypedContract::new();
|
||||
const SPLINE_CONTROL_CONTRACT: TypedContract<ControlPointSplineParams> = TypedContract::new();
|
||||
const CONIC_CONTRACT: TypedContract<ConicParams> = TypedContract::new();
|
||||
const BLEND_CONTRACT: TypedContract<BlendCurveParams> = TypedContract::new();
|
||||
const CENTERLINE_CONTRACT: TypedContract<CenterlineParams> = TypedContract::new();
|
||||
const INFINITE_CONTRACT: TypedContract<InfiniteLineParams> = TypedContract::new();
|
||||
const TEXT_CONTRACT: TypedContract<SketchTextParams> = TypedContract::new();
|
||||
const EDIT_TEXT_CONTRACT: TypedContract<EditTextParams> = TypedContract::new();
|
||||
const SPLINE_REVERSE_CONTRACT: TypedContract<SplineReverseParams> = TypedContract::new();
|
||||
const SPLINE_REMOVE_POINT_CONTRACT: TypedContract<SplineRemovePointParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line)
|
||||
CommandSpec::new("sketch.line.midpoint", "Midpoint Line", crate::checked!("sketch.line.midpoint", midpoint_line))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("line_mid")
|
||||
.enabled(in_sketch)
|
||||
.contract(&MIDPOINT_LINE_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("mid: [x,y], point ref or snap (\"mid:<line>\", \"on:<curve>:x,y\", model vertex/edge); end: [x,y]; construction?", created_doc!())),
|
||||
CommandSpec::new("sketch.arc.tangent", "Tangent Arc", arc_tangent).at("SKETCH", "CREATE").icon("arc_tangent").enabled(in_sketch).params(concat!(
|
||||
CommandSpec::new("sketch.arc.tangent", "Tangent Arc", crate::checked!("sketch.arc.tangent", arc_tangent))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("arc_tangent")
|
||||
.enabled(in_sketch)
|
||||
.contract(&ARC_TANGENT_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!(
|
||||
"start: end point of a line or arc (\"l1.end\"), end: [x,y] or an existing point's id (\"l2.start\": the arc ends on that point); curve?: the curve to be tangent to (default: the one ending at start)",
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.circle.two_tangent", "2-Tangent Circle", circle_tan_tan)
|
||||
CommandSpec::new("sketch.circle.two_tangent", "2-Tangent Circle", crate::checked!("sketch.circle.two_tangent", circle_tan_tan))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("circle_tt")
|
||||
.enabled(in_sketch)
|
||||
.contract(&TWO_TANGENT_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("curves: [two lines/circles/arcs], radius | diameter: expr, near: [x,y] (which of the solutions)", created_doc!())),
|
||||
CommandSpec::new("sketch.circle.three_tangent", "3-Tangent Circle", circle_three_tan)
|
||||
CommandSpec::new("sketch.circle.three_tangent", "3-Tangent Circle", crate::checked!("sketch.circle.three_tangent", circle_three_tan))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("circle_ttt")
|
||||
.enabled(in_sketch)
|
||||
.contract(&THREE_TANGENT_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("curves: [three lines/circles/arcs], near: [x,y] (which of the solutions)", created_doc!())),
|
||||
CommandSpec::new("sketch.slot.center_point", "Center Point Slot", slot_center_point)
|
||||
CommandSpec::new("sketch.slot.center_point", "Center Point Slot", crate::checked!("sketch.slot.center_point", slot_center_point))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("slot_center")
|
||||
.enabled(in_sketch)
|
||||
.contract(&SLOT_CENTER_POINT_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("center: slot centre, end: one arc centre, width", created_doc!())),
|
||||
CommandSpec::new("sketch.slot.arc_three_point", "Three Point Arc Slot", arc_slot_three)
|
||||
CommandSpec::new("sketch.slot.arc_three_point", "Three Point Arc Slot", crate::checked!("sketch.slot.arc_three_point", arc_slot_three))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("arc_slot")
|
||||
.enabled(in_sketch)
|
||||
.contract(&ARC_SLOT_THREE_CONTRACT)
|
||||
.output(output_schema_for::<ArcSlotResult>)
|
||||
.params(concat!("start, through, end: points on the centre arc, width", created_doc!())),
|
||||
CommandSpec::new("sketch.slot.arc_center", "Center Point Arc Slot", arc_slot_center)
|
||||
CommandSpec::new("sketch.slot.arc_center", "Center Point Arc Slot", crate::checked!("sketch.slot.arc_center", arc_slot_center))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("arc_slot_center")
|
||||
.enabled(in_sketch)
|
||||
.contract(&ARC_SLOT_CENTER_CONTRACT)
|
||||
.output(output_schema_for::<ArcSlotResult>)
|
||||
.params(concat!("center, start: centre arc start, end: direction of the centre arc end (counter-clockwise) or sweep: degrees (0 < sweep < 360), width; returns centre_arc", created_doc!())),
|
||||
CommandSpec::new("sketch.ellipse", "Ellipse", ellipse).at("SKETCH", "CREATE").icon("ellipse").enabled(in_sketch).params(concat!(
|
||||
CommandSpec::new("sketch.ellipse", "Ellipse", crate::checked!("sketch.ellipse", ellipse))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("ellipse")
|
||||
.enabled(in_sketch)
|
||||
.contract(&ELLIPSE_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!(
|
||||
"center, major: end of the major axis [x,y], minor: a point the ellipse passes through on the minor side [x,y] | minor_radius. Also adds its major and minor axes as construction lines through the centre (their ends: the major end and the point opposite it, and the two ends of the minor axis on the ellipse), held by midpoint, perpendicular and point-on-curve constraints, so a half-axis is the distance from the centre to an axis end and an axis line's length is a full axis; axes?: bool (default true; false: the ellipse alone, as the Ellipse tool draws it with Draw ellipses with their axes off)",
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.spline.fit_point", "Fit Point Spline", spline_fit)
|
||||
CommandSpec::new("sketch.spline.fit_point", "Fit Point Spline", crate::checked!("sketch.spline.fit_point", spline_fit))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("spline")
|
||||
.enabled(in_sketch)
|
||||
.contract(&SPLINE_FIT_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("points: [[x,y] or point refs…] (2…500): the spline passes through them, periodic?: boolean (default false); periodic cubic fit closes smoothly through at least 3 distinct samples", created_doc!())),
|
||||
CommandSpec::new("sketch.spline.control_point", "Control Point Spline", spline_cv3)
|
||||
CommandSpec::new("sketch.spline.control_point", "Control Point Spline", crate::checked!("sketch.spline.control_point", spline_cv3))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("spline_cv")
|
||||
.enabled(in_sketch)
|
||||
.contract(&SPLINE_CONTROL_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("points: control points (2…500), cubic", created_doc!())),
|
||||
CommandSpec::new("sketch.spline.control_point_5", "Control Point Spline (Degree 5)", spline_cv5)
|
||||
CommandSpec::new("sketch.spline.control_point_5", "Control Point Spline (Degree 5)", crate::checked!("sketch.spline.control_point_5", spline_cv5))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("spline_cv")
|
||||
.enabled(in_sketch)
|
||||
.contract(&SPLINE_CONTROL_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("points: control points (2…500), degree 5", created_doc!())),
|
||||
CommandSpec::new("sketch.spline.insert_point", "Add Spline Point", spline_insert_point)
|
||||
.icon("spline")
|
||||
@@ -102,36 +153,54 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.contract(&SPLINE_REVERSE_CONTRACT)
|
||||
.output(output_schema_for::<SplineReverseResult>)
|
||||
.params("curve: spline id (fit point, control point or closed): its last point becomes its first and the curve runs the other way along the same path; its points and the constraints on them stay. Refused for a projected spline and for one an offset uses or makes. Returns curve"),
|
||||
CommandSpec::new("sketch.conic", "Conic Curve", conic)
|
||||
CommandSpec::new("sketch.conic", "Conic Curve", crate::checked!("sketch.conic", conic))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("conic")
|
||||
.enabled(in_sketch)
|
||||
.contract(&CONIC_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!("start, end, apex: [x,y] or point refs; rho?: 0…1 (default 0.5: parabola)", created_doc!())),
|
||||
CommandSpec::new("sketch.blend_curve", "Blend Curve", blend)
|
||||
CommandSpec::new("sketch.blend_curve", "Blend Curve", crate::checked!("sketch.blend_curve", blend))
|
||||
.at("SKETCH", "MODIFY")
|
||||
.icon("blend")
|
||||
.enabled(in_sketch)
|
||||
.contract(&BLEND_CONTRACT)
|
||||
.output(output_schema_for::<DrawResult>)
|
||||
.params(concat!(
|
||||
"a, b: end points of two curves (\"l1.end\", \"a2.start\"), continuity?: g1|g2|g3|g4 (default g1: a tangent spline; g2…g4 match the reference curves' curvature, curvature rate and 4th derivative as well, as one Bézier of degree 5, 7 or 9)",
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.centerline", "Centerline", centerline)
|
||||
CommandSpec::new("sketch.centerline", "Centerline", crate::checked!("sketch.centerline", centerline))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("centerline")
|
||||
.enabled(in_sketch)
|
||||
.contract(&CENTERLINE_CONTRACT)
|
||||
.output(output_schema_for::<LineTypeResult>)
|
||||
.params("curves: [line ids], value?: bool (default toggles): centerline line type (not in profiles; an axis)"),
|
||||
CommandSpec::new("sketch.infinite", "Infinite Line", infinite_line).icon("infinite")
|
||||
CommandSpec::new("sketch.infinite", "Infinite Line", crate::checked!("sketch.infinite", infinite_line))
|
||||
.icon("infinite")
|
||||
.enabled(in_sketch)
|
||||
.contract(&INFINITE_CONTRACT)
|
||||
.output(output_schema_for::<LineTypeResult>)
|
||||
.params("curves: [line ids], value?: bool (default toggles): infinite line type (#1359): construction geometry drawn across the whole view through the line's two points; off, a normal line"),
|
||||
CommandSpec::new("sketch.text", "Text", text).at("SKETCH", "CREATE").icon("sketch_text").enabled(in_sketch).params(concat!(
|
||||
CommandSpec::new("sketch.text", "Text", crate::checked!("sketch.text", text))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("sketch_text")
|
||||
.enabled(in_sketch)
|
||||
.contract(&TEXT_CONTRACT)
|
||||
.output(output_schema_for::<TextResult>)
|
||||
.params(concat!(
|
||||
"text: string (\\n breaks lines), or text_expression: the words built from text parameters (parameters.add with unit text), number parameters and quoted texts joined by + (\"Label + '-L'\", \"'W' + Width\"; a number parameter shows its value in the design's units, \"85 mm\", an angle in degrees, \"30°\"; number(Width) is the number alone and number(Width, 2) has 2 decimals): the text keeps it, its words follow the parameters (a parameter edit or a configuration row relabels it) and `exprs` returns it as `text`; at: baseline start [x,y], height?: capital height mm (default 5), angle?: deg; at's x and y, height and angle each take a number or an expression over the design's parameters as a string (\"plate_width / 2\", \"label_size\"): the text keeps the expression, follows the parameters, and returns it in `exprs`; an expression naming no parameter is the number it comes to, a bare number in one is in the design's units, \
|
||||
font?: an installed font's family or full name, or a .ttf/.otf file path (~ and %VAR% expand; default: the built-in Liberation Sans), ",
|
||||
text_style_doc!(),
|
||||
created_doc!()
|
||||
)),
|
||||
CommandSpec::new("sketch.edit_text", "Edit Text", edit_text).icon("edit")
|
||||
CommandSpec::new("sketch.edit_text", "Edit Text", crate::checked!("sketch.edit_text", edit_text))
|
||||
.icon("edit")
|
||||
.enabled(in_sketch)
|
||||
.live(edit_text_live)
|
||||
.contract(&EDIT_TEXT_CONTRACT)
|
||||
.output(output_schema_for::<EditTextResult>)
|
||||
.params(concat!(
|
||||
"link: the text's link id (or entity: one of its curves), text? or text_expression? (as in sketch.text; typed words replace the expression), at?, height?, angle?: deg (numbers or expressions as in sketch.text; a number replaces an expression, and so does moving the text), font?: family or file path (empty: the built-in font), ",
|
||||
text_style_doc!(),
|
||||
@@ -141,6 +210,20 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
)),
|
||||
];
|
||||
|
||||
/// A reply made of a typed value, which is also what its output schema describes.
|
||||
fn reply<T: serde::Serialize>(value: T) -> Result<Value> {
|
||||
serde_json::to_value(value).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// What a drawing command returns: the curves and constraints it made, and the sketch's solve.
|
||||
fn drawn_result(out: (Vec<String>, Vec<String>), info: Value) -> DrawResult {
|
||||
DrawResult { curves: out.0, constraints: out.1, sketch: info, created: None, param_warnings: Vec::new() }
|
||||
}
|
||||
|
||||
fn drawn(out: (Vec<String>, Vec<String>), info: Value) -> Result<Value> {
|
||||
reply(drawn_result(out, info))
|
||||
}
|
||||
|
||||
/// The style a command's parameters give, over `old`.
|
||||
fn text_style(p: &Value, cmd: &str, old: TextStyle) -> Result<TextStyle> {
|
||||
let mut style = old;
|
||||
@@ -181,7 +264,7 @@ fn text_style(p: &Value, cmd: &str, old: TextStyle) -> Result<TextStyle> {
|
||||
}
|
||||
|
||||
/// What a text's `at` must be.
|
||||
const AT_MUST: &str = "`at` must be the baseline start [x, y], each a number or an expression";
|
||||
pub(crate) const AT_MUST: &str = "`at` must be the baseline start [x, y], each a number or an expression";
|
||||
|
||||
/// One number of a text, from a command's parameter `key`. A number is that number (mm, or
|
||||
/// degrees for the angle). A string is an expression over the design's parameters: a bare number
|
||||
@@ -278,15 +361,17 @@ fn text_source(doc: &solidcraft_doc::Document, p: &Value, cmd: &str, old: Option
|
||||
}
|
||||
|
||||
/// The expressions behind a text's numbers, for a command's reply (`{"height": "plate_h / 10"}`).
|
||||
fn text_exprs_json(src: &LinkSource) -> Option<Value> {
|
||||
fn text_exprs(src: &LinkSource) -> Option<TextExpressions> {
|
||||
let LinkSource::Text { exprs, .. } = src else { return None };
|
||||
let mut out = serde_json::Map::new();
|
||||
for (key, e) in [("x", &exprs.x), ("y", &exprs.y), ("height", &exprs.height), ("angle", &exprs.angle), ("text", &exprs.text)] {
|
||||
if let Some(e) = e {
|
||||
out.insert(key.into(), json!(e));
|
||||
}
|
||||
}
|
||||
(!out.is_empty()).then_some(Value::Object(out))
|
||||
let out = TextExpressions {
|
||||
x: exprs.x.clone(),
|
||||
y: exprs.y.clone(),
|
||||
height: exprs.height.clone(),
|
||||
angle: exprs.angle.clone(),
|
||||
text: exprs.text.clone(),
|
||||
};
|
||||
let any = [&out.x, &out.y, &out.height, &out.angle, &out.text].iter().any(|e| e.is_some());
|
||||
any.then_some(out)
|
||||
}
|
||||
|
||||
fn text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -296,7 +381,7 @@ fn text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let src = text_source(&s.doc, p, cmd, None)?;
|
||||
let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?;
|
||||
let exprs = text_exprs_json(&src);
|
||||
let exprs = text_exprs(&src);
|
||||
let (l, curves, guide) = sketch_store::update(s, id, |_, _, sk| {
|
||||
// A text needs nothing outside its sketch (a path is one of its curves).
|
||||
let geom = sk.text_source_geometry(&src).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
@@ -308,11 +393,7 @@ fn text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let curves = ids_of(sk, &sk.link_curves(&l));
|
||||
Ok((l, curves, guide))
|
||||
})?;
|
||||
let mut out = json!({"link": l, "curves": curves, "guide": guide});
|
||||
if let Some(exprs) = exprs {
|
||||
out["exprs"] = exprs;
|
||||
}
|
||||
Ok(out)
|
||||
reply(TextResult { change: TextChange { link: l, curves, guide, exprs }, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// A text's path is its guide: the curve it follows becomes construction. Left as it was, it
|
||||
@@ -378,17 +459,18 @@ pub(super) fn move_text(sk: &mut Sketch, link: &str, translate: Vec2, rotation:
|
||||
}
|
||||
|
||||
/// The most texts one `sketch.edit_text {edits}` changes.
|
||||
const MAX_TEXT_EDITS: usize = 1000;
|
||||
pub(crate) const MAX_TEXT_EDITS: usize = 1000;
|
||||
|
||||
fn edit_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.edit_text";
|
||||
let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?;
|
||||
sketch_store::update(s, id, |_, doc, sk| {
|
||||
let edited = sketch_store::update(s, id, |_, doc, sk| {
|
||||
// The numbers its expressions give now (a parameter may have changed since the sketch was
|
||||
// last stored); one that cannot be evaluated is left as it was, to be replaced by this edit.
|
||||
let _ = doc.apply_text_values(&doc.param_values().0, sk);
|
||||
apply_text_edits(sk, doc, p)
|
||||
})
|
||||
})?;
|
||||
reply(edited)
|
||||
}
|
||||
|
||||
/// One frame of an interactive resize or rotation: the sketch is solved and shown, the
|
||||
@@ -399,21 +481,24 @@ fn edit_text_live(s: &mut Session, p: &Value) -> Result<(Value, Option<crate::Li
|
||||
let (out, report) = super::sketch::edit_solved(s, id, false, solidcraft_sketch::Analysis::Full, |sk, doc| {
|
||||
Ok((apply_text_edits(sk, doc, p)?, super::sketch::Left::Unsolved))
|
||||
})?;
|
||||
Ok((out, report.map(|report| crate::LiveEdit { sketch: id, report })))
|
||||
Ok((reply(out)?, report.map(|report| crate::LiveEdit { sketch: id, report })))
|
||||
}
|
||||
|
||||
/// `sketch.edit_text`'s change: one text's (`link` or `entity`), or each of `edits` in turn.
|
||||
/// One command, so the features after the sketch are rebuilt once for all of them.
|
||||
fn apply_text_edits(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<Value> {
|
||||
fn apply_text_edits(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<EditTextResult> {
|
||||
let cmd = "sketch.edit_text";
|
||||
match p.get("edits") {
|
||||
None | Some(Value::Null) => apply_text_edit(sk, doc, p),
|
||||
None | Some(Value::Null) => {
|
||||
let change = apply_text_edit(sk, doc, p)?;
|
||||
Ok(EditTextResult::One(TextResult { change, created: None, param_warnings: Vec::new() }))
|
||||
}
|
||||
Some(Value::Array(edits)) => {
|
||||
if edits.is_empty() || edits.len() > MAX_TEXT_EDITS {
|
||||
return Err(bad(cmd, format!("`edits` must hold 1 to {MAX_TEXT_EDITS} edits")));
|
||||
}
|
||||
let outs = edits.iter().map(|e| apply_text_edit(sk, doc, e)).collect::<Result<Vec<_>>>()?;
|
||||
Ok(json!({"edits": outs}))
|
||||
Ok(EditTextResult::Many(TextEditsResult { edits: outs, created: None, param_warnings: Vec::new() }))
|
||||
}
|
||||
Some(_) => Err(bad(cmd, "`edits` must be a list of edits")),
|
||||
}
|
||||
@@ -421,7 +506,7 @@ fn apply_text_edits(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value)
|
||||
|
||||
/// `sketch.edit_text`'s change to its sketch: the text source's new values and its outlines
|
||||
/// regenerated from them.
|
||||
fn apply_text_edit(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<Value> {
|
||||
fn apply_text_edit(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<TextChange> {
|
||||
let cmd = "sketch.edit_text";
|
||||
let l = match (str_(p, "link"), str_(p, "entity")) {
|
||||
(Some(l), _) => l.to_string(),
|
||||
@@ -438,15 +523,11 @@ fn apply_text_edit(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -
|
||||
return Err(bad(cmd, "the text makes no outline"));
|
||||
}
|
||||
let guide = guide(sk, &src);
|
||||
let exprs = text_exprs_json(&src);
|
||||
let exprs = text_exprs(&src);
|
||||
sk.set_link_source(&l, src.clone());
|
||||
sk.update_link(&l, &geom)?;
|
||||
let curves = ids_of(sk, &sk.link_curves(&l));
|
||||
let mut out = json!({"link": l, "curves": curves, "guide": guide});
|
||||
if let Some(exprs) = exprs {
|
||||
out["exprs"] = exprs;
|
||||
}
|
||||
Ok(out)
|
||||
Ok(TextChange { link: l, curves, guide, exprs })
|
||||
}
|
||||
|
||||
/// The curve ending at point `pi` and the direction leaving it there.
|
||||
@@ -552,7 +633,7 @@ fn blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
solve_new_only(sk, first_new);
|
||||
Ok((ids_of(sk, &[sp]), cons))
|
||||
})?;
|
||||
Ok(result(out, info))
|
||||
drawn(out, info)
|
||||
}
|
||||
|
||||
fn centerline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -577,7 +658,7 @@ fn centerline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(ids.len())
|
||||
})?;
|
||||
Ok(json!({"changed": n, "sketch": info}))
|
||||
reply(LineTypeResult { changed: n, sketch: info, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn infinite_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -601,7 +682,7 @@ fn infinite_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(ids.len())
|
||||
})?;
|
||||
Ok(json!({"changed": n, "sketch": info}))
|
||||
reply(LineTypeResult { changed: n, sketch: info, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -659,7 +740,7 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
];
|
||||
Ok((ids_of(sk, &[e]), cons))
|
||||
})?;
|
||||
Ok(result(out, info))
|
||||
drawn(out, info)
|
||||
}
|
||||
|
||||
fn point_list(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
@@ -704,7 +785,7 @@ fn spline(s: &mut Session, p: &Value, cmd: &str, control: bool, degree: u8) -> R
|
||||
mark_construction(sk, &[c], p);
|
||||
Ok((ids_of(sk, &[c]), Vec::new()))
|
||||
})?;
|
||||
Ok(result(out, info))
|
||||
drawn(out, info)
|
||||
}
|
||||
|
||||
fn spline_fit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -790,7 +871,7 @@ fn conic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mark_construction(sk, &[c], p);
|
||||
Ok((ids_of(sk, &[c]), Vec::new()))
|
||||
})?;
|
||||
Ok(result(out, info))
|
||||
drawn(out, info)
|
||||
}
|
||||
|
||||
fn midpoint_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -812,7 +893,7 @@ fn midpoint_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mark_construction(sk, &[l], p);
|
||||
Ok((ids_of(sk, &[l]), vec![k]))
|
||||
})?;
|
||||
Ok(result(out, info))
|
||||
drawn(out, info)
|
||||
}
|
||||
|
||||
/// Direction leaving curve `ci` at its end point `pi` (continuing the curve past that end).
|
||||
@@ -966,7 +1047,7 @@ fn arc_tangent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let k = add_c(sk, ConstraintKind::Tangent { a: ci, b: a })?;
|
||||
Ok((ids_of(sk, &[a]), vec![k]))
|
||||
})?;
|
||||
Ok(result(out, info))
|
||||
drawn(out, info)
|
||||
}
|
||||
|
||||
/// Initial radius for a circle near `at` touching the curves: the mean distance to them.
|
||||
@@ -1052,7 +1133,7 @@ fn tangent_circle(s: &mut Session, p: &Value, cmd: &str, n: usize, radius: Optio
|
||||
if info["solved"] != json!(true) {
|
||||
return Err(bad(cmd, "no tangent circle there"));
|
||||
}
|
||||
Ok(result(out, info))
|
||||
drawn(out, info)
|
||||
}
|
||||
|
||||
fn circle_tan_tan(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1079,7 +1160,8 @@ fn slot_center_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.slot.center_point";
|
||||
let (c, e) = (req_vec2(cmd, p, "center")?, req_vec2(cmd, p, "end")?);
|
||||
let w = width(p, cmd)?;
|
||||
slot(s, p, cmd, c * 2.0 - e, e, w)
|
||||
let (out, info) = slot_parts(s, p, cmd, c * 2.0 - e, e, w)?;
|
||||
drawn(out, info)
|
||||
}
|
||||
|
||||
/// Arc slot around `o` (centre-line radius `r`) from angle `t0` sweeping `sweep` (> 0).
|
||||
@@ -1117,9 +1199,7 @@ fn arc_slot(s: &mut Session, p: &Value, cmd: &str, o: Vec2, r: f64, t0: f64, swe
|
||||
}
|
||||
Ok((ids_of(sk, &[outer, cap_e, inner, cap_s]), cons))
|
||||
})?;
|
||||
let mut out = result(out, info);
|
||||
out["centre_arc"] = json!(centre_arc);
|
||||
Ok(out)
|
||||
reply(ArcSlotResult { drawn: drawn_result(out, info), centre_arc })
|
||||
}
|
||||
|
||||
fn arc_slot_three(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -6,29 +6,48 @@ use std::collections::HashMap;
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec2;
|
||||
use solidcraft_io::{DxfEntity, DxfLayer, Geom2, MAX_DRAWING_BYTES};
|
||||
use solidcraft_sketch::{CurveKind, LinkKind, LinkSource, Sketch};
|
||||
use solidcraft_sketch::{Analysis, CurveKind, LinkKind, LinkSource, Sketch};
|
||||
|
||||
use super::CommandSpec;
|
||||
use super::sketch::{edit, ids_of};
|
||||
use super::sketch::{Left, edit_solved, ids_of};
|
||||
use super::sketch_store;
|
||||
use crate::params::{bad, num, str_, vec2};
|
||||
use crate::schema::sketch_import::{DrawingInserted, DxfExported, ExportDxfParams, ExportDxfResult, InsertDxfParams, InsertSvgParams, SketchSolve};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const INSERT_DXF_CONTRACT: TypedContract<InsertDxfParams> = TypedContract::new();
|
||||
const INSERT_SVG_CONTRACT: TypedContract<InsertSvgParams> = TypedContract::new();
|
||||
const EXPORT_DXF_CONTRACT: TypedContract<ExportDxfParams> = TypedContract::new();
|
||||
|
||||
/// A command's reply as JSON, built from the type its output schema describes so the two can't
|
||||
/// drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.insert_dxf", "Insert DXF", insert_dxf)
|
||||
CommandSpec::new("sketch.insert_dxf", "Insert DXF", crate::checked!("sketch.insert_dxf", insert_dxf))
|
||||
.at("SKETCH", "INSERT")
|
||||
.icon("sketch_dxf")
|
||||
.contract(&INSERT_DXF_CONTRACT)
|
||||
.output(output_schema_for::<DrawingInserted>)
|
||||
.params(concat!("path | text: ASCII DXF (blocks expanded); at?: [x,y] offset, scale? | width? | height?: mm, the drawing's size before rotation, aspect kept (win over scale); angle?: degrees, about the drawing's origin (or its centre); align?: \"origin\" (default: `at` is where the file's origin goes) | \"center\" (`at` is where the drawing's middle goes and it turns and scales about it); tolerance?: mm within which ends join (default 0.0001); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())),
|
||||
CommandSpec::new("sketch.insert_svg", "Insert SVG", insert_svg)
|
||||
CommandSpec::new("sketch.insert_svg", "Insert SVG", crate::checked!("sketch.insert_svg", insert_svg))
|
||||
.at("SKETCH", "INSERT")
|
||||
.icon("svg")
|
||||
.contract(&INSERT_SVG_CONTRACT)
|
||||
.output(output_schema_for::<DrawingInserted>)
|
||||
.params(concat!("path | text: SVG; at?: [x,y] offset, scale? | width? | height?: mm, the drawing's size before rotation, aspect kept (win over scale); angle?: degrees, about the drawing's origin (or its centre); align?: \"origin\" (default: `at` is where the file's origin goes) | \"center\" (`at` is where the drawing's middle goes and it turns and scales about it); tolerance?: mm within which ends join (default 0.0001); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())),
|
||||
CommandSpec::new("sketch.drawing_bounds", "Drawing Size", drawing_bounds)
|
||||
.icon("svg")
|
||||
.noundo()
|
||||
.params("path | text: SVG or DXF (by `format`: \"svg\" | \"dxf\", default by the file name, else SVG); returns min, max, width and height in the file's own size"),
|
||||
CommandSpec::new("sketch.export_dxf", "Save As DXF", export_dxf).icon("sketch_dxf")
|
||||
CommandSpec::new("sketch.export_dxf", "Save As DXF", crate::checked!("sketch.export_dxf", export_dxf))
|
||||
.icon("sketch_dxf")
|
||||
.noundo()
|
||||
.contract(&EXPORT_DXF_CONTRACT)
|
||||
.output(output_schema_for::<ExportDxfResult>)
|
||||
.params("sketch?: id|name (default active); path?: file to write (else the DXF text is returned); units?: \"design\" | \"in\" | \"inch\" | \"mm\" | \"cm\" | \"m\" | \"ft\" (default mm); layer?: profile layer name (default \"0\"); layers?: \"single\" | \"roles\" (default \"single\": all on `layer`; \"roles\": outer on \"OUTLINE\", holes on \"CUT\"); join?: bool (default false: R12 LINE/ARC; true: closed loops as LWPOLYLINE with arc bulges)"),
|
||||
];
|
||||
|
||||
@@ -251,10 +270,13 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {
|
||||
if geom.len() > solidcraft_sketch::MAX_POINTS {
|
||||
return Err(solidcraft_sketch::SketchError::TooLarge.into());
|
||||
}
|
||||
let ((curves, texts), info) = edit(s, p, cmd, false, |sk, _| {
|
||||
// `sketch::edit`, but keeping the solve as a typed value for the reply.
|
||||
let target = sketch_store::target(s, p, cmd)?;
|
||||
let ((curves, texts), report) = edit_solved(s, target, false, Analysis::Freedom, |sk, _| {
|
||||
let (cs, texts) = add_geometry(sk, &geom, &f, k, tol)?;
|
||||
Ok((ids_of(sk, &cs), texts))
|
||||
Ok(((ids_of(sk, &cs), texts), Left::Unsolved))
|
||||
})?;
|
||||
let info = report.map(|rep| SketchSolve { solved: rep.keeps_orientation(), dof: rep.dof });
|
||||
// Text becomes sketch text.
|
||||
let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch"))?;
|
||||
let mut n_text = 0;
|
||||
@@ -279,7 +301,7 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"sketch": id, "created_sketch": created, "curves": curves.len(), "texts": n_text, "info": info}))
|
||||
reply(cmd, DrawingInserted { sketch: id, created_sketch: created, curves: curves.len(), texts: n_text, info, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn insert_dxf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -522,9 +544,10 @@ fn export_dxf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
if let Some(path) = str_(p, "path").filter(|x| !x.trim().is_empty()) {
|
||||
solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
return Ok(json!({"path": path, "entities": entity_count}));
|
||||
let exported = DxfExported::Written { path: path.to_string(), entities: entity_count };
|
||||
return reply(cmd, ExportDxfResult { exported, param_warnings: Vec::new() });
|
||||
}
|
||||
Ok(json!({"dxf": text, "entities": entity_count}))
|
||||
reply(cmd, ExportDxfResult { exported: DxfExported::Text { dxf: text, entities: entity_count }, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -13,6 +13,12 @@ use solidcraft_sketch::{ConstraintKind, LinkKind, LinkSource, Sketch};
|
||||
use super::sketch_store;
|
||||
use super::{CommandSpec, in_sketch};
|
||||
use crate::params::{bad, bool_, str_, vec3};
|
||||
use crate::schema::sketch_project::{
|
||||
AutoProjectParams, AutoProjectResult, FitCurvesParams, FitSectionResult, Include3dParams, IntersectParams, IntersectionCurveParams,
|
||||
IsoCurveParams, LinkMade, ProjectParams, ProjectResult, ProjectToSurfaceParams, ProjectToSurfaceResult, ProjectedLink, SketchBreakLinkParams,
|
||||
SketchBreakLinkResult, SketchLinkResult, SpunProfileParams,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
macro_rules! refs_doc {
|
||||
@@ -21,105 +27,160 @@ macro_rules! refs_doc {
|
||||
};
|
||||
}
|
||||
|
||||
const PROJECT_CONTRACT: TypedContract<ProjectParams> = TypedContract::new();
|
||||
const INTERSECT_CONTRACT: TypedContract<IntersectParams> = TypedContract::new();
|
||||
const INCLUDE_3D_CONTRACT: TypedContract<Include3dParams> = TypedContract::new();
|
||||
const PROJECT_TO_SURFACE_CONTRACT: TypedContract<ProjectToSurfaceParams> = TypedContract::new();
|
||||
const INTERSECTION_CURVE_CONTRACT: TypedContract<IntersectionCurveParams> = TypedContract::new();
|
||||
const SPUN_PROFILE_CONTRACT: TypedContract<SpunProfileParams> = TypedContract::new();
|
||||
const ISO_CURVE_CONTRACT: TypedContract<IsoCurveParams> = TypedContract::new();
|
||||
const FIT_SECTION_CONTRACT: TypedContract<FitCurvesParams> = TypedContract::new();
|
||||
const BREAK_LINK_CONTRACT: TypedContract<SketchBreakLinkParams> = TypedContract::new();
|
||||
const AUTO_PROJECT_CONTRACT: TypedContract<AutoProjectParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.project", "Project", project_cmd).at("SKETCH", "CREATE").icon("project").key("P").enabled(in_sketch).params(
|
||||
CommandSpec::new("sketch.project", "Project", crate::checked!("sketch.project", project_cmd)).at("SKETCH", "CREATE").icon("project").key("P").enabled(in_sketch).contract(&PROJECT_CONTRACT).output(output_schema_for::<ProjectResult>).params(
|
||||
concat!(refs_doc!(), "; projection_link?: bool (default true)", created_doc!()),
|
||||
),
|
||||
CommandSpec::new("sketch.intersect", "Intersect", intersect_cmd).at("SKETCH", "CREATE").icon("intersect").enabled(in_sketch).params(
|
||||
CommandSpec::new("sketch.intersect", "Intersect", crate::checked!("sketch.intersect", intersect_cmd)).at("SKETCH", "CREATE").icon("intersect").enabled(in_sketch).contract(&INTERSECT_CONTRACT).output(output_schema_for::<ProjectResult>).params(
|
||||
concat!("refs: [{body}, {face: [x,y,z], body?}, {edge: [x,y,z], body?}, {sketch, curve}]: section curves (or points) with the sketch plane; projection_link?: bool (default true)", created_doc!()),
|
||||
),
|
||||
CommandSpec::new("sketch.include_3d", "Include 3D Geometry", include_cmd)
|
||||
CommandSpec::new("sketch.include_3d", "Include 3D Geometry", crate::checked!("sketch.include_3d", include_cmd))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("include")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("refs: like Project (edges, vertices, sketch curves and points); curves out of the sketch plane are flattened onto it", created_doc!())),
|
||||
CommandSpec::new("sketch.project_to_surface", "Project To Surface", project_to_surface)
|
||||
.contract(&INCLUDE_3D_CONTRACT).output(output_schema_for::<ProjectResult>).params(concat!("refs: like Project (edges, vertices, sketch curves and points); curves out of the sketch plane are flattened onto it", created_doc!())),
|
||||
CommandSpec::new("sketch.project_to_surface", "Project To Surface", crate::checked!("sketch.project_to_surface", project_to_surface))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("project_surface")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("curves: [{sketch, curve}…] (curves of other sketches), face: [x,y,z] point on the target face, body?: projected along the active sketch's normal onto the face, as linked 3D curves", created_doc!())),
|
||||
CommandSpec::new("sketch.intersection_curve", "Intersection Curve", intersection_curve)
|
||||
.contract(&PROJECT_TO_SURFACE_CONTRACT).output(output_schema_for::<ProjectToSurfaceResult>).params(concat!("curves: [{sketch, curve}…] (curves of other sketches), face: [x,y,z] point on the target face, body?: projected along the active sketch's normal onto the face, as linked 3D curves", created_doc!())),
|
||||
CommandSpec::new("sketch.intersection_curve", "Intersection Curve", crate::checked!("sketch.intersection_curve", intersection_curve))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("intersection_curve")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("a, b: {body} | {face: [x,y,z], body?} | {sketch, curve} (a curve of another sketch, standing in for its extrusion along that sketch's normal): where they meet, as linked 3D curves", created_doc!())),
|
||||
CommandSpec::new("sketch.spun_profile", "Spun Profile", spun_profile)
|
||||
.contract(&INTERSECTION_CURVE_CONTRACT).output(output_schema_for::<SketchLinkResult>).params(concat!("a, b: {body} | {face: [x,y,z], body?} | {sketch, curve} (a curve of another sketch, standing in for its extrusion along that sketch's normal): where they meet, as linked 3D curves", created_doc!())),
|
||||
CommandSpec::new("sketch.spun_profile", "Spun Profile", crate::checked!("sketch.spun_profile", spun_profile))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("spun")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("body: name, axis: a line of the active sketch (curve id) | X|Y|Z: the body's outline revolved about the axis, in the sketch plane", created_doc!())),
|
||||
CommandSpec::new("sketch.isoparametric_curve", "Isoparametric Curve", iso_curve)
|
||||
.contract(&SPUN_PROFILE_CONTRACT).output(output_schema_for::<SketchLinkResult>).params(concat!("body: name, axis: a line of the active sketch (curve id) | X|Y|Z: the body's outline revolved about the axis, in the sketch plane", created_doc!())),
|
||||
CommandSpec::new("sketch.isoparametric_curve", "Isoparametric Curve", crate::checked!("sketch.isoparametric_curve", iso_curve))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("iso_curve")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("face: [x,y,z] point on the face (the curve passes through it), body?, direction?: u|v|[x,y,z] (default u): linked 3D curve", created_doc!())),
|
||||
CommandSpec::new("sketch.fit_curves_to_section", "Fit Curves to Mesh Section", fit_section)
|
||||
.contract(&ISO_CURVE_CONTRACT).output(output_schema_for::<SketchLinkResult>).params(concat!("face: [x,y,z] point on the face (the curve passes through it), body?, direction?: u|v|[x,y,z] (default u): linked 3D curve", created_doc!())),
|
||||
CommandSpec::new("sketch.fit_curves_to_section", "Fit Curves to Mesh Section", crate::checked!("sketch.fit_curves_to_section", fit_section))
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("fit_section")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!("body: name (a mesh or solid body): its section with the sketch plane, fitted with lines and arcs, as normal (unlinked) geometry", created_doc!())),
|
||||
CommandSpec::new("sketch.break_link", "Break Link", break_link).icon("sketch_break")
|
||||
.contract(&FIT_SECTION_CONTRACT).output(output_schema_for::<FitSectionResult>).params(concat!("body: name (a mesh or solid body): its section with the sketch plane, fitted with lines and arcs, as normal (unlinked) geometry", created_doc!())),
|
||||
CommandSpec::new("sketch.break_link", "Break Link", crate::checked!("sketch.break_link", break_link)).icon("sketch_break")
|
||||
.enabled(in_sketch)
|
||||
.params("link?: link id (j1) | entities?: [curve or point ids]: linked geometry becomes normal sketch geometry"),
|
||||
CommandSpec::new("sketch.auto_project", "Auto-Project Edges on Reference", auto_project).icon("project")
|
||||
.contract(&BREAK_LINK_CONTRACT).output(output_schema_for::<SketchBreakLinkResult>).params("link?: link id (j1) | entities?: [curve or point ids]: linked geometry becomes normal sketch geometry"),
|
||||
CommandSpec::new("sketch.auto_project", "Auto-Project Edges on Reference", crate::checked!("sketch.auto_project", auto_project)).icon("project")
|
||||
.noundo()
|
||||
.params("value?: bool (default toggles): project a face's edges when a sketch is created on it"),
|
||||
.contract(&AUTO_PROJECT_CONTRACT).output(output_schema_for::<AutoProjectResult>).params("value?: bool (default toggles): project a face's edges when a sketch is created on it"),
|
||||
];
|
||||
|
||||
/// Parse one reference.
|
||||
fn source(s: &Session, v: &Value, cmd: &str) -> Result<LinkSource> {
|
||||
/// What a reference says in its JSON, before the design is asked what it names (`source` goes on
|
||||
/// from here, and so does the contract of the commands that take references).
|
||||
pub(crate) enum RefForm<'a> {
|
||||
/// Text: `origin`, an axis letter or a body name, which the design decides.
|
||||
Name(&'a str),
|
||||
/// `{edge: [x,y,z], body?}`.
|
||||
Edge { body: String, at: Vec3 },
|
||||
/// `{face: [x,y,z], body?}`.
|
||||
Face { body: String, at: Vec3 },
|
||||
/// `{vertex: [x,y,z], body?}`.
|
||||
Vertex { body: String, at: Vec3 },
|
||||
/// `{sketch, curve}` or `{sketch, point}`: the sketch as the lookup reads it (an id or a name)
|
||||
/// and the `curve` or `point` given. With neither, the handler refuses it once the sketch is
|
||||
/// found.
|
||||
Sketch { key: String, curve: Option<&'a str>, point: Option<&'a str> },
|
||||
/// `{body: name}`.
|
||||
Body(&'a str),
|
||||
/// `{axis: X|Y|Z|name}`.
|
||||
Axis(&'a str),
|
||||
/// `{plane: XY|XZ|YZ|name}`.
|
||||
Plane(&'a str),
|
||||
/// `{origin: …}`.
|
||||
Origin,
|
||||
}
|
||||
|
||||
/// The form of one reference, or the message (without the command's name) for what no design
|
||||
/// could make sense of. The forms are tried in this order, the first that fits wins: an edge, face
|
||||
/// or vertex whose value is not a point is passed over, not refused.
|
||||
pub(crate) fn ref_form(v: &Value) -> std::result::Result<RefForm<'_>, String> {
|
||||
if let Some(name) = v.as_str() {
|
||||
return match name.to_ascii_lowercase().as_str() {
|
||||
"origin" => Ok(LinkSource::Origin),
|
||||
"x" | "y" | "z" => Ok(LinkSource::Axis { name: name.to_ascii_uppercase() }),
|
||||
_ if s.model.state().body(name).is_some() => Ok(LinkSource::Body { body: name.to_string() }),
|
||||
_ => Err(bad(cmd, format!("unknown reference `{name}`"))),
|
||||
};
|
||||
return Ok(RefForm::Name(name));
|
||||
}
|
||||
let body = || str_(v, "body").unwrap_or("").to_string();
|
||||
if let Some(at) = v.get("edge").and_then(vec3) {
|
||||
return Ok(LinkSource::Edge { body: body(), at });
|
||||
return Ok(RefForm::Edge { body: body(), at });
|
||||
}
|
||||
if let Some(at) = v.get("face").and_then(vec3) {
|
||||
return Ok(LinkSource::Face { body: body(), at });
|
||||
return Ok(RefForm::Face { body: body(), at });
|
||||
}
|
||||
if let Some(at) = v.get("vertex").and_then(vec3) {
|
||||
return Ok(LinkSource::Vertex { body: body(), at });
|
||||
return Ok(RefForm::Vertex { body: body(), at });
|
||||
}
|
||||
if let Some(sk) = v.get("sketch") {
|
||||
let key = match sk {
|
||||
Value::Number(n) => n.to_string(),
|
||||
Value::String(x) => x.clone(),
|
||||
_ => return Err(bad(cmd, "`sketch` must be an id or a name")),
|
||||
_ => return Err("`sketch` must be an id or a name".into()),
|
||||
};
|
||||
let f = s.doc.find_feature(&key).ok_or_else(|| bad(cmd, format!("no sketch `{key}`")))?;
|
||||
if !matches!(f.kind, FeatureKind::Sketch { .. }) {
|
||||
return Err(bad(cmd, format!("`{key}` is not a sketch")));
|
||||
}
|
||||
if Some(f.id) == s.active_sketch {
|
||||
return Err(bad(cmd, "a sketch cannot project its own geometry"));
|
||||
}
|
||||
if let Some(c) = str_(v, "curve") {
|
||||
return Ok(LinkSource::SketchCurve { sketch: f.id, curve: c.to_string() });
|
||||
}
|
||||
if let Some(p) = str_(v, "point") {
|
||||
return Ok(LinkSource::SketchPoint { sketch: f.id, point: p.to_string() });
|
||||
}
|
||||
return Err(bad(cmd, "a sketch reference needs `curve` or `point`"));
|
||||
return Ok(RefForm::Sketch { key, curve: str_(v, "curve"), point: str_(v, "point") });
|
||||
}
|
||||
if let Some(b) = str_(v, "body") {
|
||||
return Ok(LinkSource::Body { body: b.to_string() });
|
||||
return Ok(RefForm::Body(b));
|
||||
}
|
||||
if let Some(a) = str_(v, "axis") {
|
||||
return axis_source(s, a, cmd);
|
||||
return Ok(RefForm::Axis(a));
|
||||
}
|
||||
if let Some(p) = str_(v, "plane") {
|
||||
return Ok(LinkSource::Plane { name: p.to_string() });
|
||||
return Ok(RefForm::Plane(p));
|
||||
}
|
||||
if v.get("origin").is_some() {
|
||||
return Ok(LinkSource::Origin);
|
||||
return Ok(RefForm::Origin);
|
||||
}
|
||||
Err(format!("cannot project {v}"))
|
||||
}
|
||||
|
||||
/// Parse one reference.
|
||||
fn source(s: &Session, v: &Value, cmd: &str) -> Result<LinkSource> {
|
||||
match ref_form(v).map_err(|why| bad(cmd, why))? {
|
||||
RefForm::Name(name) => match name.to_ascii_lowercase().as_str() {
|
||||
"origin" => Ok(LinkSource::Origin),
|
||||
"x" | "y" | "z" => Ok(LinkSource::Axis { name: name.to_ascii_uppercase() }),
|
||||
_ if s.model.state().body(name).is_some() => Ok(LinkSource::Body { body: name.to_string() }),
|
||||
_ => Err(bad(cmd, format!("unknown reference `{name}`"))),
|
||||
},
|
||||
RefForm::Edge { body, at } => Ok(LinkSource::Edge { body, at }),
|
||||
RefForm::Face { body, at } => Ok(LinkSource::Face { body, at }),
|
||||
RefForm::Vertex { body, at } => Ok(LinkSource::Vertex { body, at }),
|
||||
RefForm::Sketch { key, curve, point } => {
|
||||
let f = s.doc.find_feature(&key).ok_or_else(|| bad(cmd, format!("no sketch `{key}`")))?;
|
||||
if !matches!(f.kind, FeatureKind::Sketch { .. }) {
|
||||
return Err(bad(cmd, format!("`{key}` is not a sketch")));
|
||||
}
|
||||
if Some(f.id) == s.active_sketch {
|
||||
return Err(bad(cmd, "a sketch cannot project its own geometry"));
|
||||
}
|
||||
if let Some(c) = curve {
|
||||
return Ok(LinkSource::SketchCurve { sketch: f.id, curve: c.to_string() });
|
||||
}
|
||||
if let Some(p) = point {
|
||||
return Ok(LinkSource::SketchPoint { sketch: f.id, point: p.to_string() });
|
||||
}
|
||||
Err(bad(cmd, "a sketch reference needs `curve` or `point`"))
|
||||
}
|
||||
RefForm::Body(b) => Ok(LinkSource::Body { body: b.to_string() }),
|
||||
RefForm::Axis(a) => axis_source(s, a, cmd),
|
||||
RefForm::Plane(p) => Ok(LinkSource::Plane { name: p.to_string() }),
|
||||
RefForm::Origin => Ok(LinkSource::Origin),
|
||||
}
|
||||
Err(bad(cmd, format!("cannot project {v}")))
|
||||
}
|
||||
|
||||
/// An origin axis (`X`, `Y` or `Z`, in any case), or a construction axis by its name (#9324).
|
||||
@@ -391,10 +452,17 @@ fn add_link_unless_present(
|
||||
Ok(Some(link))
|
||||
}
|
||||
|
||||
fn link_json(sk: &Sketch, link: &str) -> Value {
|
||||
/// A command's reply as JSON: they build their replies from the types their output schemas
|
||||
/// describe, so the two can't drift apart.
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
/// The ids of the curves and of the points that link `link` made.
|
||||
fn link_parts(sk: &Sketch, link: &str) -> (Vec<String>, Vec<String>) {
|
||||
let curves: Vec<String> = sk.link_curves(link).iter().filter_map(|c| sk.curves.get(*c).map(|c| c.id.clone())).collect();
|
||||
let points: Vec<String> = sk.link_points(link).iter().filter_map(|p| sk.points.get(*p).map(|p| p.id.clone())).collect();
|
||||
json!({"link": link, "curves": curves, "points": points})
|
||||
(curves, points)
|
||||
}
|
||||
|
||||
fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind, projection_link: bool) -> Result<Value> {
|
||||
@@ -418,9 +486,10 @@ fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind, projection_l
|
||||
let what = src.describe();
|
||||
match add_link_unless_present(s, doc, id, sk, kind, src, kind == LinkKind::Project) {
|
||||
Ok(Some(l)) => {
|
||||
let mut result = link_json(sk, &l);
|
||||
let (curves, points) = link_parts(sk, &l);
|
||||
let mut result = ProjectedLink { link: Some(l.clone()), curves, points };
|
||||
if !projection_link {
|
||||
result["link"] = Value::Null;
|
||||
result.link = None;
|
||||
sk.break_link(&l)?;
|
||||
}
|
||||
out.push(result);
|
||||
@@ -435,11 +504,7 @@ fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind, projection_l
|
||||
}
|
||||
Ok((out, present))
|
||||
})?;
|
||||
let mut r = json!({"links": out});
|
||||
if !present.is_empty() {
|
||||
r["already_projected"] = json!(present);
|
||||
}
|
||||
Ok(r)
|
||||
reply(cmd, ProjectResult { links: out, already_projected: present, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn project_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -543,16 +608,15 @@ pub(super) fn project_entities(s: &mut Session, p: &Value, cmd: &str) -> Result<
|
||||
}
|
||||
|
||||
/// Add one link from `src` to the active sketch and report it.
|
||||
fn one_link(s: &mut Session, cmd: &str, kind: LinkKind, src: LinkSource) -> Result<Value> {
|
||||
fn one_link(s: &mut Session, cmd: &str, kind: LinkKind, src: LinkSource) -> Result<LinkMade> {
|
||||
let id = sketch_store::active(s).ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?;
|
||||
sketch_store::update(s, id, |s, doc, sk| {
|
||||
refresh(s, doc, id, sk);
|
||||
let what = src.describe();
|
||||
let l = add_link(s, doc, id, sk, kind, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?;
|
||||
let mut out = link_json(sk, &l);
|
||||
let (curves, points) = link_parts(sk, &l);
|
||||
let wires: Vec<String> = sk.link_wires(&l).iter().filter_map(|w| sk.wires.get(*w).map(|w| w.id.clone())).collect();
|
||||
out["wires"] = json!(wires);
|
||||
Ok(out)
|
||||
Ok(LinkMade { link: l, curves, points, wires })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -571,7 +635,7 @@ fn project_to_surface(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
out.push(one_link(s, cmd, LinkKind::Project, LinkSource::OnSurface { sketch, curve, body: body.clone(), at })?);
|
||||
}
|
||||
Ok(json!({"links": out}))
|
||||
reply(cmd, ProjectToSurfaceResult { links: out, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn intersection_curve(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -584,7 +648,8 @@ fn intersection_curve(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let (a, b) = (side("a")?, side("b")?);
|
||||
one_link(s, cmd, LinkKind::Include, LinkSource::Intersection { a: Box::new(a), b: Box::new(b) })
|
||||
let made = one_link(s, cmd, LinkKind::Include, LinkSource::Intersection { a: Box::new(a), b: Box::new(b) })?;
|
||||
reply(cmd, SketchLinkResult { made, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn spun_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -605,7 +670,8 @@ fn spun_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(wa, wb - wa)
|
||||
}
|
||||
};
|
||||
one_link(s, cmd, LinkKind::Project, LinkSource::Spun { body, origin, dir })
|
||||
let made = one_link(s, cmd, LinkKind::Project, LinkSource::Spun { body, origin, dir })?;
|
||||
reply(cmd, SketchLinkResult { made, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn iso_curve(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -620,7 +686,8 @@ fn iso_curve(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
format!("{},{},{}", d.x, d.y, d.z)
|
||||
}
|
||||
};
|
||||
one_link(s, cmd, LinkKind::Include, LinkSource::Iso { body, at, dir })
|
||||
let made = one_link(s, cmd, LinkKind::Include, LinkSource::Iso { body, at, dir })?;
|
||||
reply(cmd, SketchLinkResult { made, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn fit_section(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -636,7 +703,7 @@ fn fit_section(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sk.break_link(&l)?;
|
||||
Ok(curves)
|
||||
})?;
|
||||
Ok(json!({"curves": curves}))
|
||||
reply(cmd, FitSectionResult { curves, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn break_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -670,12 +737,12 @@ fn break_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(links)
|
||||
})?;
|
||||
Ok(json!({"broken": links}))
|
||||
reply(cmd, SketchBreakLinkResult { broken: links, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn auto_project(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.auto_project = bool_(p, "value").unwrap_or(!s.auto_project);
|
||||
Ok(json!({"auto_project": s.auto_project}))
|
||||
reply("sketch.auto_project", AutoProjectResult { auto_project: s.auto_project, created: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// `"x:<a>+<b>:x,y"` from interactive snapping: two distinct curve ids and a hint point.
|
||||
|
||||
@@ -340,6 +340,63 @@ fn tangent_moves_only_the_second_pick() {
|
||||
check_order(line_and_circle(), "sketch.constraint.tangent", "c1", "l1");
|
||||
}
|
||||
|
||||
/// #12092: Tangent with a line's end point and a circle puts that end on the circle and makes the
|
||||
/// line tangent there, in one step. In either pick order only the picked end moves: the line turns
|
||||
/// about its other end and gets longer or shorter, and the circle stays.
|
||||
#[test]
|
||||
fn tangent_at_a_lines_end_puts_the_end_on_the_circle() {
|
||||
// Where the line ends up: its end's distance from the centre, and the line's.
|
||||
let touch = |s: &Session| {
|
||||
let sk = sketch(s);
|
||||
let (a, b) = (pt(s, "l1.start"), pt(s, "l1.end"));
|
||||
let c = sk.point(sk.resolve_point("c1.center").unwrap()).unwrap();
|
||||
let line = (b - a).cross(c - a).abs() / a.dist(b);
|
||||
(b.dist(c), line, sk.radius(sk.curve_index("c1").unwrap()).unwrap())
|
||||
};
|
||||
for (a, b) in [("c1", "l1.end"), ("l1.end", "c1")] {
|
||||
let mut s = line_and_circle();
|
||||
let circle = snap(&s, "c1");
|
||||
let undo = s.undo.len();
|
||||
let r = run(&mut s, "sketch.constraint.tangent", json!({"a": a, "b": b}));
|
||||
assert_eq!(r["constraints"].as_array().map(Vec::len), Some(2), "{a}, {b}: {r}");
|
||||
let (end, line, radius) = touch(&s);
|
||||
assert!((radius - 5.0).abs() < 1e-9, "{a}, {b}: the circle keeps its size: {radius}");
|
||||
assert!((end - 5.0).abs() < 1e-6 && (line - 5.0).abs() < 1e-6, "{a}, {b}: end {end}, line {line} from the centre");
|
||||
assert!(same(&snap(&s, "c1"), &circle), "{a}, {b}: the circle moved");
|
||||
let start = pt(&s, "l1.start");
|
||||
assert!(start.dist(solidcore_record::Vec2::new(5.0, 3.0)) < 1e-9, "{a}, {b}: the line's other end moved to {start:?}");
|
||||
assert_eq!(s.undo.len(), undo + 1, "{a}, {b}: one undo step");
|
||||
}
|
||||
// A point that ends no curve names no curve to be tangent: the refusal says what to pick.
|
||||
let mut s = line_and_circle();
|
||||
let e = s.execute("sketch.constraint.tangent", &json!({"a": "l1", "b": "c1.center"})).unwrap_err().to_string();
|
||||
assert!(e.contains("end"), "{e}");
|
||||
}
|
||||
|
||||
/// A line whose end is already joined to an arc's end (the coincident a click there adds): Tangent
|
||||
/// on that end and the arc, or on the two ends in either order, adds only the tangent, since the
|
||||
/// end already lies on the arc. The joint holds. With the end and the arc the line stays and the
|
||||
/// arc moves; with two ends the first pick stays.
|
||||
#[test]
|
||||
fn tangent_at_a_joint_adds_only_the_tangent() {
|
||||
for (a, b, stays) in [("l1.end", "a1", "l1"), ("a1", "l1.end", "l1"), ("l1.end", "a1.start", "l1"), ("a1.start", "l1.end", "a1")] {
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.line", json!({"points": [[2, 3], [12, 3]]}));
|
||||
run(&mut s, "sketch.arc.center_point", json!({"center": [16, 9], "start": [12, 3], "sweep": 90}));
|
||||
let joints = sketch(&s).constraints.len();
|
||||
let kept = snap(&s, stays);
|
||||
let r = run(&mut s, "sketch.constraint.tangent", json!({"a": a, "b": b}));
|
||||
assert!(same(&snap(&s, stays), &kept), "{a}, {b}: {stays} moved");
|
||||
assert_eq!(r["constraints"].as_array().map(Vec::len), Some(1), "{a}, {b}: {r}");
|
||||
assert_eq!(sketch(&s).constraints.len(), joints + 1, "{a}, {b}: only the tangent is new");
|
||||
let sk = sketch(&s);
|
||||
let arc = sk.curve_index("a1").unwrap();
|
||||
let (p, q, c) = (pt(&s, "l1.start"), pt(&s, "l1.end"), sk.center(arc).unwrap());
|
||||
assert!(q.dist(pt(&s, "a1.start")) < 1e-6, "{a}, {b}: the joint came apart");
|
||||
assert!(((q - p).cross(c - p).abs() / p.dist(q) - sk.radius(arc).unwrap()).abs() < 1e-6, "{a}, {b}: not tangent");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixed_second_pick_makes_the_first_move() {
|
||||
let mut s = line_and_circle();
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
//! Contracts and result types for the commands in `cmd/inspect.rs`.
|
||||
//!
|
||||
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
//! reads it and fails with the handler's message. Whether a body, a sketch or a material exists
|
||||
//! stays the handler's to check. A key the handler refuses when it is left out (`material.assign`'s
|
||||
//! `bodies` and `material`) is optional in the type and required in the schema, so that the
|
||||
//! handler's message, not the check's "is required", is what a caller sees (#12498).
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::check::{located, whole};
|
||||
use super::materials::MaterialReply;
|
||||
use crate::params;
|
||||
|
||||
/// Which command to describe.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -278,6 +292,831 @@ impl From<&solidcraft_doc::ThreadInfo> for ModelThread {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `keys` to the schema's `required` list: for a key the type has optional so that the
|
||||
/// handler, not the check, refuses it when it's left out.
|
||||
fn require_keys(schema: &mut Schema, keys: &[&str]) {
|
||||
let mut required = match schema.get("required") {
|
||||
Some(Value::Array(required)) => required.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
for key in keys {
|
||||
if !required.iter().any(|k| k == key) {
|
||||
required.push((*key).into());
|
||||
}
|
||||
}
|
||||
schema.insert("required".into(), Value::Array(required));
|
||||
}
|
||||
|
||||
fn bodies_and_material_required(schema: &mut Schema) {
|
||||
require_keys(schema, &["bodies", "material"]);
|
||||
}
|
||||
|
||||
/// The message of a handler's parameter error, for a reader the contract shares.
|
||||
fn message(e: crate::EngineError) -> String {
|
||||
match e {
|
||||
crate::EngineError::BadParams { msg, .. } => msg,
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `bodies`: a name or a list of names, read by `params::string_list` itself, with its messages
|
||||
/// (`null` is no names).
|
||||
fn body_names<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<String>>, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
params::string_list("inspect", &json!({ "bodies": v }), "bodies").map(Some).map_err(|e| D::Error::custom(whole(message(e))))
|
||||
}
|
||||
|
||||
fn body_names_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": params::MAX_STRING_LIST}, {"type": "null"}]})
|
||||
}
|
||||
|
||||
/// Read the design: its name, units, properties, parameters, timeline, bodies and sketches, the
|
||||
/// selection and the undo and redo depth. Read-only.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct DocumentInspectParams {
|
||||
/// Measure each body too (volume, area, centre of mass, box, counts, as `inspect.measure`
|
||||
/// does), in place of its feature. Default: false.
|
||||
#[serde(default)]
|
||||
pub measure: Option<bool>,
|
||||
/// Give each sketch also its plane and its number of points and constraints. Default: false.
|
||||
#[serde(default)]
|
||||
pub sketch_counts: Option<bool>,
|
||||
}
|
||||
|
||||
/// What `document.inspect` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DocumentInspectResult {
|
||||
/// The design's name.
|
||||
pub name: String,
|
||||
/// Its length unit.
|
||||
pub units: String,
|
||||
/// Its metadata object as saved, other tools' keys included.
|
||||
pub metadata: Map<String, Value>,
|
||||
/// The file it is saved in; `null` when it has none.
|
||||
pub path: Option<String>,
|
||||
/// Whether it has changes that are not saved.
|
||||
pub dirty: bool,
|
||||
/// How many times the session's design changed.
|
||||
pub revision: u64,
|
||||
/// The sketch being edited, by feature id; `null` when none.
|
||||
pub active_sketch: Option<u64>,
|
||||
/// The timeline marker: features from this index on are rolled back.
|
||||
pub marker: usize,
|
||||
/// The design's parameters.
|
||||
pub params: Vec<DocumentParam>,
|
||||
/// Its features, in timeline order.
|
||||
pub timeline: Vec<TimelineEntry>,
|
||||
/// Its bodies.
|
||||
pub bodies: Vec<DocumentBody>,
|
||||
/// Its sketches.
|
||||
pub sketches: Vec<DocumentSketch>,
|
||||
/// What is selected, each as the selection commands take it.
|
||||
#[schemars(with = "Vec<Map<String, Value>>")]
|
||||
pub selection: Value,
|
||||
/// How many undo steps there are.
|
||||
pub undo: usize,
|
||||
/// How many redo steps there are.
|
||||
pub redo: usize,
|
||||
/// The parts of the origin that are hidden, by name.
|
||||
pub hidden_origin: Vec<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A parameter of the design.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DocumentParam {
|
||||
pub name: String,
|
||||
/// What it is defined as.
|
||||
pub expression: String,
|
||||
/// `mm`, `deg` or empty (no unit).
|
||||
pub unit: String,
|
||||
/// What the expression comes to; `null` when it doesn't evaluate.
|
||||
pub value: Option<f64>,
|
||||
/// Whether a dimension or feature made it, not the user.
|
||||
pub model: bool,
|
||||
pub comment: String,
|
||||
/// Why the expression doesn't evaluate; `null` when it does.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// A feature of the timeline.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct TimelineEntry {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
/// The feature's kind, such as `Extrude`.
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
pub suppressed: bool,
|
||||
/// Whether the timeline marker has rolled it back.
|
||||
pub rolled_back: bool,
|
||||
/// Why it failed; `null` when it did not.
|
||||
pub error: Option<String>,
|
||||
pub warning: Option<String>,
|
||||
/// How long it took to evaluate (ms); `null` when it has no result.
|
||||
pub ms: Option<f64>,
|
||||
}
|
||||
|
||||
/// A body of the design: measured with `measure`, else with the feature that made it.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DocumentBody {
|
||||
#[serde(flatten)]
|
||||
pub detail: DocumentBodyDetail,
|
||||
/// Whether it is shown.
|
||||
pub visible: bool,
|
||||
/// Present, and true, when the timeline is rolled back and the body is deleted further on.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub removed_later: Option<bool>,
|
||||
}
|
||||
|
||||
/// What a body entry says of the body itself.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum DocumentBodyDetail {
|
||||
/// Without `measure`.
|
||||
Listed {
|
||||
name: String,
|
||||
/// The feature that made it, by id.
|
||||
feature: u64,
|
||||
},
|
||||
/// With `measure`.
|
||||
Measured(Box<BodyMeasurement>),
|
||||
}
|
||||
|
||||
/// One body measured: its name and the measurement or why there is none.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyMeasurement {
|
||||
pub name: String,
|
||||
#[serde(flatten)]
|
||||
pub outcome: BodyOutcome,
|
||||
}
|
||||
|
||||
/// A body's measurement.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum BodyOutcome {
|
||||
Measured(BodyFigures),
|
||||
Failed(BodyFailure),
|
||||
}
|
||||
|
||||
/// The measurements of a body.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyFigures {
|
||||
/// Whether it encloses a volume.
|
||||
pub closed: bool,
|
||||
/// Its volume (mm³); `null` unless it is closed.
|
||||
pub volume_mm3: Option<f64>,
|
||||
/// Its surface area (mm²).
|
||||
pub area_mm2: f64,
|
||||
/// Its centre of mass at uniform density; `null` unless it is closed.
|
||||
pub center_of_mass: Option<[f64; 3]>,
|
||||
pub bbox: BoundingBox,
|
||||
/// Faces, with split pieces of one analytic surface counted once (a sheet metal body's in
|
||||
/// `inspect.measure`: with its round holes counted as the design shows them).
|
||||
pub faces: i64,
|
||||
pub edges: i64,
|
||||
pub vertices: i64,
|
||||
/// The merged faces by kind of surface.
|
||||
pub face_types: BTreeMap<String, usize>,
|
||||
/// The kernel's own counts, which split closed curves and surfaces.
|
||||
pub kernel: KernelCounts,
|
||||
/// What volume, area and centre come from: `smlib` (exact) or `mesh` (a mesh body's own
|
||||
/// triangles).
|
||||
pub measured_by: String,
|
||||
/// Anything the measurement says about itself.
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Why a body has no measurement.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyFailure {
|
||||
pub error: String,
|
||||
/// `inspect.measure` only, for a sheet metal body: its hole-corrected count, which has
|
||||
/// nothing to correct.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub faces: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub edges: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub vertices: Option<i64>,
|
||||
}
|
||||
|
||||
/// An axis-aligned box (mm).
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BoundingBox {
|
||||
pub min: [f64; 3],
|
||||
pub max: [f64; 3],
|
||||
}
|
||||
|
||||
/// A body's topology counts as the kernel has them.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct KernelCounts {
|
||||
pub faces: usize,
|
||||
pub edges: usize,
|
||||
pub vertices: usize,
|
||||
pub shells: usize,
|
||||
}
|
||||
|
||||
/// A sketch of the design, in short.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DocumentSketch {
|
||||
/// Its feature id.
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
/// Its remaining degrees of freedom (0: fully constrained).
|
||||
pub dof: usize,
|
||||
pub status: SketchStatus,
|
||||
/// How many curves it has.
|
||||
pub curves: usize,
|
||||
/// How many profiles it closes.
|
||||
pub profiles: usize,
|
||||
/// Whether it is shown.
|
||||
pub visible: bool,
|
||||
/// With `sketch_counts`: where it lies.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<Map<String, Value>>")]
|
||||
pub plane: Option<Value>,
|
||||
/// With `sketch_counts`: how many points it has.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub points: Option<usize>,
|
||||
/// With `sketch_counts`: how many constraints it has.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub constraints: Option<usize>,
|
||||
}
|
||||
|
||||
/// Whether a sketch's constraints solved.
|
||||
#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SketchStatus {
|
||||
Solved,
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl From<solidcraft_sketch::SolveStatus> for SketchStatus {
|
||||
fn from(s: solidcraft_sketch::SolveStatus) -> Self {
|
||||
match s {
|
||||
solidcraft_sketch::SolveStatus::Solved => SketchStatus::Solved,
|
||||
solidcraft_sketch::SolveStatus::Failed => SketchStatus::Failed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How `inspect.measure` selects: bodies, or one or two picked items. With `items`, `bodies` and
|
||||
/// `names_only` are not read, so the check leaves them alone.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct MeasureKeys {
|
||||
/// The bodies to measure, by name. Default: all. Not read with `items`.
|
||||
#[serde(default, deserialize_with = "body_names", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "body_names_schema")]
|
||||
pub bodies: Option<Vec<String>>,
|
||||
/// Give each body's name and its definition's and measure nothing. Default: false. Not read
|
||||
/// with `items`.
|
||||
#[serde(default)]
|
||||
pub names_only: Option<bool>,
|
||||
/// One or two selections to measure, instead of bodies: a face or edge `{type, body, point}`
|
||||
/// (`index` is optional), or a body, vertex, sketch curve or profile as `Sel` has it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "items_schema")]
|
||||
pub items: Option<Vec<Value>>,
|
||||
}
|
||||
|
||||
fn items_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": "array", "items": {"type": "object"}, "minItems": 1, "maxItems": 1000})
|
||||
}
|
||||
|
||||
/// `inspect.measure`'s parameters: [`MeasureKeys`], read as the handler reads them: with `items`
|
||||
/// given (even as `null`) only `items` is read; without it, `bodies` and `names_only`.
|
||||
#[derive(Debug)]
|
||||
pub struct MeasureParams(pub MeasureKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for MeasureParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let value = Value::deserialize(d)?;
|
||||
if let Some(items) = value.get("items") {
|
||||
let list = items.as_array().ok_or_else(|| D::Error::custom(whole("`items` must be a list of selections")))?;
|
||||
if list.is_empty() || list.len() > 1000 {
|
||||
return Err(D::Error::custom(whole("measure one or two items")));
|
||||
}
|
||||
return Ok(MeasureParams(MeasureKeys { bodies: None, names_only: None, items: Some(list.clone()) }));
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(MeasureParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for MeasureParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"MeasureParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
MeasureKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// What `inspect.measure` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct MeasureResult {
|
||||
#[serde(flatten)]
|
||||
pub measured: Measured,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The shapes of `inspect.measure`'s reply.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum Measured {
|
||||
/// With `items`.
|
||||
Items(Box<MeasuredItems>),
|
||||
/// With `names_only`.
|
||||
Names(BodyNames),
|
||||
/// Bodies.
|
||||
Bodies(MeasuredBodies),
|
||||
}
|
||||
|
||||
/// Each world body's name and its definition's.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyNames {
|
||||
pub body_count: usize,
|
||||
pub bodies: Vec<BodyName>,
|
||||
}
|
||||
|
||||
/// A body by its name and its definition's.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct BodyName {
|
||||
pub name: String,
|
||||
pub definition: String,
|
||||
}
|
||||
|
||||
/// The bodies measured, with their totals.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct MeasuredBodies {
|
||||
pub body_count: usize,
|
||||
pub bodies: Vec<MeasuredBody>,
|
||||
pub total: MeasureTotal,
|
||||
}
|
||||
|
||||
/// A body measured, with its material and mass.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct MeasuredBody {
|
||||
#[serde(flatten)]
|
||||
pub measurement: BodyMeasurement,
|
||||
/// Its material's name.
|
||||
pub material: String,
|
||||
/// The material's density; only for a body with a volume.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub density_g_cm3: Option<f64>,
|
||||
/// Its mass (g); only for a body with a volume.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub mass_g: Option<f64>,
|
||||
/// True for a sheet metal body, whose counts are its own, with round holes as the design
|
||||
/// shows them.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sheet_metal: Option<bool>,
|
||||
}
|
||||
|
||||
/// The sum over the bodies measured.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct MeasureTotal {
|
||||
/// How many bodies are left out of the volume and mass because they enclose none.
|
||||
pub open_bodies_skipped: usize,
|
||||
pub volume_mm3: f64,
|
||||
pub area_mm2: f64,
|
||||
pub mass_g: f64,
|
||||
pub faces: u64,
|
||||
pub edges: u64,
|
||||
pub vertices: u64,
|
||||
}
|
||||
|
||||
/// One or two picked items measured: each item, then what its shape gives (for one item) or what
|
||||
/// lies between the two.
|
||||
#[derive(Debug, Default, Serialize, JsonSchema)]
|
||||
pub struct MeasuredItems {
|
||||
/// Each item described: its kind, what it is and its own figures.
|
||||
pub items: Vec<Map<String, Value>>,
|
||||
/// One item that is round: its diameter (mm).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<f64>")]
|
||||
pub diameter: Option<Value>,
|
||||
/// Its radius (mm).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<f64>")]
|
||||
pub radius: Option<Value>,
|
||||
/// A full circle's circumference (mm).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<f64>")]
|
||||
pub circumference: Option<Value>,
|
||||
/// An arc's sweep in degrees; two items: the angle between them.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<f64>")]
|
||||
pub angle_deg: Option<Value>,
|
||||
/// An arc's length (mm).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<f64>")]
|
||||
pub arc_length: Option<Value>,
|
||||
/// One round item's centre.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<[f64; 3]>")]
|
||||
pub center: Option<Value>,
|
||||
/// One slot: its `width`, `center_distance`, `overall_length` and the two `centers`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<Map<String, Value>>")]
|
||||
pub slot: Option<Value>,
|
||||
/// One slot: where its first end is centred; two items: the first item's centre.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub center_from: Option<[f64; 3]>,
|
||||
/// One slot: its second end's centre; two items: the second's.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub center_to: Option<[f64; 3]>,
|
||||
/// Two items: the closest distance between them (mm).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub distance_mm: Option<f64>,
|
||||
/// Two items: where it starts on the first. A coordinate is `null` where it isn't a number: two planes that meet have no
|
||||
/// such point to name (their distance is 0).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<[Option<f64>; 3]>")]
|
||||
pub from: Option<[f64; 3]>,
|
||||
/// Two items: where it ends on the second. A coordinate is `null` where it isn't a number: two planes that meet have no
|
||||
/// such point to name (their distance is 0).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<[Option<f64>; 3]>")]
|
||||
pub to: Option<[f64; 3]>,
|
||||
/// Two items: `to` minus `from`. A coordinate is `null` where it isn't a number: two planes that meet have no
|
||||
/// such point to name (their distance is 0).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<[Option<f64>; 3]>")]
|
||||
pub delta: Option<[f64; 3]>,
|
||||
/// Two items: the closest distance, as `distance_mm`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub min: Option<f64>,
|
||||
/// Two items: the farthest distance (mm).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_from: Option<[f64; 3]>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_to: Option<[f64; 3]>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_delta: Option<[f64; 3]>,
|
||||
/// Two items: the distance between their centres (or from an axis) (mm).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub center_distance: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub center_delta: Option<[f64; 3]>,
|
||||
/// Two items: which distance is the one to read, `center` or `min`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub measure: Option<MeasureKind>,
|
||||
}
|
||||
|
||||
/// Which of two items' distances is the one to read.
|
||||
#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MeasureKind {
|
||||
Center,
|
||||
Min,
|
||||
}
|
||||
|
||||
/// List every command: its id, label, place on the toolbar, icon, shortcut, parameter prose and
|
||||
/// whether it can run now.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CommandsParams {}
|
||||
|
||||
/// One command of `engine.commands`' list.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct CommandEntry {
|
||||
/// The command's id, such as `solid.extrude`.
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
/// The toolbar tab it is on; empty when it is on none.
|
||||
pub tab: String,
|
||||
/// The panel of that tab.
|
||||
pub panel: String,
|
||||
pub icon: String,
|
||||
pub shortcut: Option<String>,
|
||||
/// The parameter documentation, as prose (`engine.describe` has the schemas).
|
||||
pub params: String,
|
||||
/// Whether it can run in the session's state now.
|
||||
pub enabled: bool,
|
||||
/// Why it can't; `null` when it can.
|
||||
pub disabled_reason: Option<String>,
|
||||
/// For a command that is planned and not built yet: what is planned.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub planned: Option<String>,
|
||||
}
|
||||
|
||||
impl From<crate::cmd::CommandInfo> for CommandEntry {
|
||||
fn from(c: crate::cmd::CommandInfo) -> Self {
|
||||
CommandEntry {
|
||||
id: c.id.into(),
|
||||
label: c.label.into(),
|
||||
tab: c.tab.into(),
|
||||
panel: c.panel.into(),
|
||||
icon: c.icon.into(),
|
||||
shortcut: c.shortcut.map(Into::into),
|
||||
params: c.params.into(),
|
||||
enabled: c.enabled,
|
||||
disabled_reason: c.disabled_reason,
|
||||
planned: c.planned.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `material.list` takes no parameters.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct MaterialListParams {}
|
||||
|
||||
/// What `material.list` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct MaterialListResult {
|
||||
/// The built-in materials, then the design's own.
|
||||
pub materials: Vec<ListedMaterial>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A material in the list.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum ListedMaterial {
|
||||
/// A built-in material.
|
||||
BuiltIn {
|
||||
name: String,
|
||||
/// Its density (g/cm³).
|
||||
density_g_cm3: f64,
|
||||
},
|
||||
/// One this design defines, with `user` true, its look and its physical card when it has
|
||||
/// one.
|
||||
Design(Box<MaterialReply>),
|
||||
}
|
||||
|
||||
/// A name as `material.assign` reads `material`: text, with the handler's message for anything
|
||||
/// else, `null` included.
|
||||
fn material_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(Some(s)),
|
||||
_ => Err(D::Error::custom(whole("`material` must be a material name"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Give bodies a physical material (a built-in one, or one made with `material.create`), which
|
||||
/// their mass and density come from. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = bodies_and_material_required)]
|
||||
pub struct MaterialAssignParams {
|
||||
// Optional in the type and required in the schema (`bodies_and_material_required`).
|
||||
/// The bodies, by name: one or a list, at least one, each an existing body.
|
||||
#[serde(default, deserialize_with = "body_names", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "material_bodies_schema")]
|
||||
pub bodies: Option<Vec<String>>,
|
||||
/// The material's name (Steel, Aluminum, ABS Plastic, …, or one made with `material.create`;
|
||||
/// `material.list` lists them). Letter case and spaces at either end don't matter.
|
||||
#[serde(default, deserialize_with = "material_name", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "material_schema")]
|
||||
pub material: Option<String>,
|
||||
}
|
||||
|
||||
fn material_bodies_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": params::MAX_STRING_LIST}]})
|
||||
}
|
||||
|
||||
fn material_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": "string"})
|
||||
}
|
||||
|
||||
/// What `material.assign` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct MaterialAssignResult {
|
||||
/// The bodies that got the material.
|
||||
pub bodies: Vec<String>,
|
||||
/// The material's name as the design has it.
|
||||
pub material: String,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A sketch by its feature id (a number) or its name, as `sketch.inspect` reads `sketch`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SketchTarget {
|
||||
Id(u64),
|
||||
Name(String),
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for SketchTarget {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Number(n) => n.as_u64().map(SketchTarget::Id),
|
||||
Value::String(s) => Some(SketchTarget::Name(s)),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| D::Error::custom(whole("`sketch` must be an id or a name")))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SketchTarget {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SketchTarget".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "A sketch's feature id (a number, never a name) or its name.",
|
||||
"anyOf": [{"type": "integer", "minimum": 0, "maximum": u64::MAX}, {"type": "string"}]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a sketch: its curves, points, constraints, profiles, links and 3D curves, with what is
|
||||
/// determined and what is not. Read-only.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct SketchInspectParams {
|
||||
/// The sketch. Default (also `null`): the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// What `sketch.inspect` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchInspected {
|
||||
/// The sketch's feature id.
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
/// Where it lies, as saved.
|
||||
#[schemars(with = "Map<String, Value>")]
|
||||
pub plane: Value,
|
||||
pub status: SketchStatus,
|
||||
/// Its remaining degrees of freedom (0: fully constrained).
|
||||
pub dof: usize,
|
||||
pub fully_constrained: bool,
|
||||
/// The constraints still violated after a failed solve.
|
||||
pub failing: Vec<String>,
|
||||
pub curves: Vec<SketchCurve>,
|
||||
pub points: Vec<SketchPoint>,
|
||||
pub constraints: Vec<SketchConstraint>,
|
||||
pub profiles: Vec<SketchProfile>,
|
||||
/// Links to geometry outside the sketch (projections, intersections, includes), as saved.
|
||||
#[schemars(with = "Vec<Map<String, Value>>")]
|
||||
pub links: Value,
|
||||
/// Its 3D curves.
|
||||
pub wires: Vec<SketchWire>,
|
||||
/// Whether it is shown.
|
||||
pub visible: bool,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A curve of a sketch: its id, what it is and how it is held.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchCurve {
|
||||
pub id: String,
|
||||
#[serde(flatten)]
|
||||
pub shape: CurveShape,
|
||||
pub construction: bool,
|
||||
/// Whether it is locked (fixed, or linked).
|
||||
pub fixed: bool,
|
||||
/// Whether everything that defines it is determined by constraints.
|
||||
pub fully_constrained: bool,
|
||||
/// For a linked curve: the link that owns it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub link: Option<String>,
|
||||
}
|
||||
|
||||
/// A curve's kind and its points, by id and (`_at`) by position `[x, y]` in the sketch's plane.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum CurveShape {
|
||||
Line {
|
||||
start: String,
|
||||
end: String,
|
||||
start_at: Option<[f64; 2]>,
|
||||
end_at: Option<[f64; 2]>,
|
||||
},
|
||||
Circle {
|
||||
center: String,
|
||||
center_at: Option<[f64; 2]>,
|
||||
radius: f64,
|
||||
},
|
||||
Arc {
|
||||
center: String,
|
||||
start: String,
|
||||
end: String,
|
||||
center_at: Option<[f64; 2]>,
|
||||
start_at: Option<[f64; 2]>,
|
||||
end_at: Option<[f64; 2]>,
|
||||
radius: Option<f64>,
|
||||
},
|
||||
Ellipse {
|
||||
center: String,
|
||||
/// The end of the major axis.
|
||||
major: String,
|
||||
center_at: Option<[f64; 2]>,
|
||||
major_at: Option<[f64; 2]>,
|
||||
minor_radius: f64,
|
||||
},
|
||||
Spline {
|
||||
points: Vec<String>,
|
||||
points_at: Vec<Option<[f64; 2]>>,
|
||||
/// Whether `points` are control points of a B-spline, not fit points.
|
||||
control: bool,
|
||||
degree: u8,
|
||||
periodic: bool,
|
||||
/// A control spline with its own knots (a projected free-form edge).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
knots: Option<Vec<f64>>,
|
||||
/// Its weights, when it has any.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
weights: Option<Vec<f64>>,
|
||||
},
|
||||
Conic {
|
||||
start: String,
|
||||
end: String,
|
||||
apex: String,
|
||||
start_at: Option<[f64; 2]>,
|
||||
end_at: Option<[f64; 2]>,
|
||||
apex_at: Option<[f64; 2]>,
|
||||
rho: f64,
|
||||
},
|
||||
}
|
||||
|
||||
/// A point of a sketch.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchPoint {
|
||||
pub id: String,
|
||||
/// Its position `[x, y]` in the sketch's plane (mm).
|
||||
pub at: [f64; 2],
|
||||
/// Where that is in the design (mm).
|
||||
pub world: [f64; 3],
|
||||
/// Whether it is locked (fixed, or linked).
|
||||
pub fixed: bool,
|
||||
/// For a linked point: the link that owns it; `null` otherwise.
|
||||
pub link: Option<String>,
|
||||
pub fully_constrained: bool,
|
||||
}
|
||||
|
||||
/// A constraint or dimension: its id, its kind's name and the kind's own fields (`type`, then
|
||||
/// the points and curves it ties, a value…), as saved.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchConstraint {
|
||||
pub id: String,
|
||||
/// The kind in short, such as `Horizontal`.
|
||||
pub name: String,
|
||||
/// For a dimension: the parameter that drives it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub param: Option<String>,
|
||||
/// With `param`: the parameter's expression; `null` when the design has no such parameter.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "Option<String>")]
|
||||
pub expression: Option<Option<String>>,
|
||||
#[serde(flatten)]
|
||||
pub kind: Map<String, Value>,
|
||||
}
|
||||
|
||||
/// A region the sketch closes.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchProfile {
|
||||
pub index: usize,
|
||||
pub area_mm2: f64,
|
||||
/// Its centroid `[x, y]` in the sketch's plane.
|
||||
pub centroid_sketch: [f64; 2],
|
||||
/// The curves of its outer loop, each once, in loop order.
|
||||
pub curves: Vec<String>,
|
||||
/// The curves of each hole's loop.
|
||||
pub holes: Vec<Vec<String>>,
|
||||
}
|
||||
|
||||
/// A 3D curve a sketch carries.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchWire {
|
||||
pub id: String,
|
||||
/// How many points its polyline has.
|
||||
pub points: usize,
|
||||
pub start: Option<[f64; 3]>,
|
||||
pub end: Option<[f64; 3]>,
|
||||
/// For a linked curve: the link that owns it; `null` otherwise.
|
||||
pub link: Option<String>,
|
||||
/// For an exact circular arc: its geometry; `null` otherwise.
|
||||
pub arc: Option<WireArcInfo>,
|
||||
}
|
||||
|
||||
/// An exact circular arc of a 3D curve.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct WireArcInfo {
|
||||
pub center: [f64; 3],
|
||||
pub radius: f64,
|
||||
pub start: [f64; 3],
|
||||
pub end: [f64; 3],
|
||||
/// Its sweep (degrees).
|
||||
pub sweep_deg: f64,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "inspect_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{BodyFeaturesParams, BodyListParams, DescribeParams, ModelBodyFeatures, ModelEdges, ModelFaces, ModelThreads, ModelThreadsParams};
|
||||
use super::{
|
||||
BodyFeaturesParams, BodyListParams, CommandEntry, CommandsParams, DescribeParams, DocumentInspectParams, DocumentInspectResult,
|
||||
MaterialAssignParams, MaterialAssignResult, MaterialListParams, MaterialListResult, MeasureParams, MeasureResult, ModelBodyFeatures, ModelEdges,
|
||||
ModelFaces, ModelThreads, ModelThreadsParams, SketchInspectParams, SketchInspected,
|
||||
};
|
||||
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};
|
||||
@@ -90,6 +94,419 @@ fn describe_returns_both_schemas() {
|
||||
assert!(e.as_deref().is_some_and(|e| e.contains("did you mean `solid.extrude`")), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<DocumentInspectParams>(), &["measure", "sketch_counts"]);
|
||||
assert_keys(input_schema_for::<MeasureParams>(), &["bodies", "items", "names_only"]);
|
||||
assert_keys(input_schema_for::<CommandsParams>(), &[]);
|
||||
assert_keys(input_schema_for::<MaterialListParams>(), &[]);
|
||||
assert_keys(input_schema_for::<MaterialAssignParams>(), &["bodies", "material"]);
|
||||
assert_keys(input_schema_for::<SketchInspectParams>(), &["sketch"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors_of_the_inspect_commands() {
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("material.assign", json!({})),
|
||||
("material.assign", json!({"bodies": ["A"]})),
|
||||
("material.assign", json!({"bodies": ["A"], "material": 4})),
|
||||
("material.assign", json!({"bodies": ["A"], "material": null})),
|
||||
("material.assign", json!({"bodies": ["A"], "material": ["Steel"]})),
|
||||
("material.assign", json!({"bodies": 5, "material": "Steel"})),
|
||||
("material.assign", json!({"bodies": [5], "material": "Steel"})),
|
||||
("material.assign", json!({"bodies": [], "material": "Steel"})),
|
||||
("material.assign", json!({"bodies": null, "material": "Steel"})),
|
||||
("material.assign", json!({"material": "Steel"})),
|
||||
("material.assign", json!({"bodies": ["Nope"], "material": "Steel"})),
|
||||
("material.assign", json!({"bodies": ["Nope"], "material": "Unobtainium"})),
|
||||
("inspect.measure", json!({"bodies": 5})),
|
||||
("inspect.measure", json!({"bodies": [5]})),
|
||||
("inspect.measure", json!({"bodies": ["Nope"]})),
|
||||
("inspect.measure", json!({"items": null})),
|
||||
("inspect.measure", json!({"items": "x"})),
|
||||
("inspect.measure", json!({"items": {}})),
|
||||
("inspect.measure", json!({"items": []})),
|
||||
("inspect.measure", json!({"items": "x", "bodies": 5})),
|
||||
("inspect.measure", json!({"items": [1], "bodies": 5, "names_only": "yes"})),
|
||||
("inspect.measure", json!({"items": [{"type": "body", "name": "Nope"}]})),
|
||||
("sketch.inspect", json!({"sketch": true})),
|
||||
("sketch.inspect", json!({"sketch": -1})),
|
||||
("sketch.inspect", json!({"sketch": 1.5})),
|
||||
("sketch.inspect", json!({"sketch": [1]})),
|
||||
("sketch.inspect", json!({"sketch": {}})),
|
||||
("sketch.inspect", json!({"sketch": "Nope"})),
|
||||
("sketch.inspect", json!({"sketch": 99999})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// Each type reads a key as its handler does: with `items` only `items` is read, without it
|
||||
/// `bodies` and `names_only`; `material.assign` leaves a missing or empty `bodies` and a missing
|
||||
/// `material` to the handler's own message; `sketch` is an id, a name or `null`.
|
||||
#[test]
|
||||
fn the_types_read_each_key_as_the_handler_does() {
|
||||
let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
|
||||
let none = Vec::<String>::new();
|
||||
// inspect.measure: the keys read depend on the form.
|
||||
let pick = json!([{"type": "face", "body": "A", "point": [1, 2, 3]}]);
|
||||
assert_eq!(issues("inspect.measure", json!({})), none);
|
||||
assert_eq!(issues("inspect.measure", json!({"bodies": ["A"], "names_only": true})), none);
|
||||
assert_eq!(issues("inspect.measure", json!({"bodies": null, "names_only": null})), none);
|
||||
assert_eq!(issues("inspect.measure", json!({"items": pick})), none);
|
||||
assert_eq!(issues("inspect.measure", json!({"items": pick, "bodies": 5, "names_only": "yes"})), none);
|
||||
assert_eq!(issues("inspect.measure", json!({"bodies": 5})), ["`bodies` must be a list of names; it is 5"]);
|
||||
assert_eq!(issues("inspect.measure", json!({"bodies": ["A", 7]})), ["`bodies` must list names; the entry 2 is 7"]);
|
||||
assert_eq!(issues("inspect.measure", json!({"names_only": "yes"})), ["`names_only` must be true or false"]);
|
||||
assert_eq!(issues("inspect.measure", json!({"items": null})), ["`items` must be a list of selections"]);
|
||||
assert_eq!(issues("inspect.measure", json!({"items": "x", "bodies": 5})), ["`items` must be a list of selections"]);
|
||||
assert_eq!(issues("inspect.measure", json!({"items": []})), ["measure one or two items"]);
|
||||
assert_eq!(issues("inspect.measure", json!({"items": vec![json!({}); 1001]})), ["measure one or two items"]);
|
||||
// material.assign.
|
||||
assert_eq!(issues("material.assign", json!({"bodies": ["A"], "material": "Steel"})), none);
|
||||
assert_eq!(issues("material.assign", json!({"bodies": "A", "material": " steel "})), none);
|
||||
assert_eq!(issues("material.assign", json!({"material": "Steel"})), none);
|
||||
assert_eq!(issues("material.assign", json!({"bodies": [], "material": "Steel"})), none);
|
||||
assert_eq!(issues("material.assign", json!({"bodies": null})), none);
|
||||
assert_eq!(issues("material.assign", json!({"bodies": 5, "material": "Steel"})), ["`bodies` must be a list of names; it is 5"]);
|
||||
assert_eq!(issues("material.assign", json!({"bodies": ["A"], "material": 4})), ["`material` must be a material name"]);
|
||||
assert_eq!(issues("material.assign", json!({"bodies": ["A"], "material": null})), ["`material` must be a material name"]);
|
||||
// sketch.inspect.
|
||||
for ok in [json!({}), json!({"sketch": null}), json!({"sketch": 3}), json!({"sketch": "Base"}), json!({"sketch": "7"})] {
|
||||
assert_eq!(issues("sketch.inspect", ok.clone()), none, "{ok}");
|
||||
}
|
||||
for bad in [json!(true), json!(-1), json!(1.5), json!([1]), json!({"id": 1})] {
|
||||
assert_eq!(issues("sketch.inspect", json!({ "sketch": bad.clone() })), ["`sketch` must be an id or a name"], "{bad}");
|
||||
}
|
||||
// document.inspect's flags are plain booleans, `null` is left out.
|
||||
assert_eq!(issues("document.inspect", json!({"measure": true, "sketch_counts": null})), none);
|
||||
assert_eq!(issues("document.inspect", json!({"measure": "yes"})), ["`measure` must be true or false"]);
|
||||
// Neither list command takes a key.
|
||||
assert_eq!(issues("engine.commands", json!({"x": 1})), ["unknown key `x`"]);
|
||||
assert_eq!(issues("material.list", json!({"x": 1})), ["unknown key `x`"]);
|
||||
}
|
||||
|
||||
/// The schemas say what the handlers need: `material.assign` can't do without `bodies` and
|
||||
/// `material`, though its type leaves them to the handler's message; `inspect.measure` takes
|
||||
/// bodies or items.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
takes(
|
||||
input_schema_for::<MaterialAssignParams>(),
|
||||
&[
|
||||
(json!({"bodies": ["A"], "material": "Steel"}), true),
|
||||
(json!({"bodies": "A", "material": "Steel"}), true),
|
||||
(json!({"material": "Steel"}), false),
|
||||
(json!({"bodies": ["A"]}), false),
|
||||
(json!({"bodies": [], "material": "Steel"}), false),
|
||||
(json!({"bodies": ["A"], "material": 4}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<MeasureParams>(),
|
||||
&[
|
||||
(json!({}), true),
|
||||
(json!({"bodies": ["A"], "names_only": true}), true),
|
||||
(json!({"bodies": "A"}), true),
|
||||
(json!({"bodies": null}), true),
|
||||
(json!({"items": [{"type": "body", "name": "A"}]}), true),
|
||||
(json!({"items": []}), false),
|
||||
(json!({"items": "x"}), false),
|
||||
(json!({"bodies": 5}), false),
|
||||
(json!({"names_only": "yes"}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<SketchInspectParams>(),
|
||||
&[
|
||||
(json!({}), true),
|
||||
(json!({"sketch": 3}), true),
|
||||
(json!({"sketch": "Base"}), true),
|
||||
(json!({"sketch": null}), true),
|
||||
(json!({"sketch": -1}), false),
|
||||
(json!({"sketch": true}), false),
|
||||
],
|
||||
);
|
||||
takes(input_schema_for::<DocumentInspectParams>(), &[(json!({"measure": true, "sketch_counts": false}), true), (json!({"measure": 1}), false)]);
|
||||
takes(input_schema_for::<CommandsParams>(), &[(json!({}), true), (json!({"x": 1}), false)]);
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A reply matches its output schema and, in Warn, carries `param_warnings` only when told to.
|
||||
fn matches<T: schemars::JsonSchema>(id: &str, reply: &Value, warned: bool) {
|
||||
let schema = output_schema_for::<T>();
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
|
||||
assert_eq!(reply.get("param_warnings").is_some(), warned, "{id}: {reply}");
|
||||
}
|
||||
|
||||
/// A design with a box, a cylinder, a sheet metal body, a sketch of every curve kind with a
|
||||
/// dimension, and a sketch that projects a face: returns the first sketch's feature id.
|
||||
fn design(s: &mut Session) -> u64 {
|
||||
run(s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"}));
|
||||
run(s, "solid.cylinder", json!({"radius": 4, "height": 20, "base": [40, 0, 0], "body_name": "Shaft"}));
|
||||
run(s, "material.create", json!({"name": "Alloy", "density_g_cm3": 2.5, "color": "#ff0000"}));
|
||||
run(
|
||||
s,
|
||||
"material.create",
|
||||
json!({"name": "Painted", "density_g_cm3": 1.5, "color": "#00ff00", "pbr": {"metallic": 0.5, "roughness": 0.5, "dielectric_ior": 1.5}}),
|
||||
);
|
||||
run(s, "sheet.manage_rules", json!({"name": "R1", "thickness": "1 mm", "bend_radius": "1 mm", "active": true}));
|
||||
run(s, "sketch.create", json!({"plane": "XY", "name": "Base"}));
|
||||
run(s, "sketch.rectangle.two_point", json!({"p0": [60, 0], "p1": [100, 30]}));
|
||||
run(s, "sketch.finish", json!({}));
|
||||
run(s, "sheet.flange", json!({"sketch": "Base"}));
|
||||
run(s, "sketch.create", json!({"plane": "XZ", "name": "Shapes"}));
|
||||
run(s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 20]]}));
|
||||
run(s, "sketch.circle.center", json!({"center": [10, 10], "radius": 3}));
|
||||
run(s, "sketch.circle.center", json!({"center": [10, 10], "radius": 1}));
|
||||
run(s, "sketch.arc.three_point", json!({"start": [50, 0], "end": [60, 10], "through": [58, 3]}));
|
||||
run(s, "sketch.ellipse", json!({"center": [-30, 0], "major": [-20, 0], "minor_radius": 5}));
|
||||
run(s, "sketch.spline.fit_point", json!({"points": [[0, 40], [10, 50], [20, 40], [30, 50]]}));
|
||||
run(s, "sketch.spline.control_point", json!({"points": [[0, 60], [10, 70], [20, 60], [30, 70]]}));
|
||||
run(s, "sketch.conic", json!({"start": [0, 80], "end": [30, 80], "apex": [15, 100], "rho": 0.4}));
|
||||
run(s, "sketch.dimension", json!({"entities": ["c1"]}));
|
||||
run(s, "sketch.dimension", json!({"entities": ["l1"], "value": 40}));
|
||||
run(s, "sketch.construction", json!({"curves": ["l2"]}));
|
||||
let id = run(s, "sketch.inspect", json!({}))["id"].as_u64().unwrap_or_default();
|
||||
run(s, "sketch.finish", json!({}));
|
||||
run(s, "sketch.create", json!({"plane": {"origin": [0, 0, 30], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Top"}));
|
||||
run(s, "sketch.project", json!({"refs": [{"face": [5, 10, 30], "body": "Block"}]}));
|
||||
run(s, "sketch.finish", json!({}));
|
||||
id
|
||||
}
|
||||
|
||||
/// Real calls of `document.inspect` in Warn, each form: the replies match the output schema
|
||||
/// without `param_warnings`, and say what the design has.
|
||||
#[test]
|
||||
fn document_inspect_replies_match_its_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let shapes = design(&mut s);
|
||||
run(&mut s, "sketch.edit", json!({"sketch": shapes}));
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"measure": true}),
|
||||
json!({"sketch_counts": true}),
|
||||
json!({"measure": true, "sketch_counts": true}),
|
||||
json!({"measure": false, "sketch_counts": null}),
|
||||
] {
|
||||
let r = run(&mut s, "document.inspect", p.clone());
|
||||
matches::<DocumentInspectResult>("document.inspect", &r, false);
|
||||
assert_eq!(r["active_sketch"], json!(shapes), "{r}");
|
||||
assert_eq!(r["bodies"].as_array().map(Vec::len), Some(3), "{p}: {r}");
|
||||
assert_eq!(r["bodies"][0].get("area_mm2").is_some(), p["measure"] == true, "{p}: {r}");
|
||||
assert_eq!(r["bodies"][0].get("feature").is_some(), p["measure"] != true, "{p}: {r}");
|
||||
assert_eq!(r["sketches"][0].get("plane").is_some(), p["sketch_counts"] == true, "{p}: {r}");
|
||||
}
|
||||
let r = run(&mut s, "document.inspect", json!({"measure": true}));
|
||||
assert!(r["params"].as_array().is_some_and(|p| p.iter().any(|x| x["name"].is_string() && x["model"] == true)), "{r}");
|
||||
assert!(r["timeline"].as_array().is_some_and(|t| t.iter().any(|x| x["type"].is_string() && x["ms"].is_number())), "{r}");
|
||||
run(&mut s, "browser.visibility", json!({"items": ["Shaft"], "visible": false}));
|
||||
let r = run(&mut s, "document.inspect", json!({}));
|
||||
matches::<DocumentInspectResult>("document.inspect", &r, false);
|
||||
assert_eq!(r["bodies"][1]["visible"], false, "{r}");
|
||||
// A body that a rolled-back later feature deletes says so.
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.remove", json!({"bodies": ["Shaft"]}));
|
||||
run(&mut s, "timeline.roll_to", json!({"feature": "Shapes"}));
|
||||
run(&mut s, "sketch.edit", json!({"sketch": shapes}));
|
||||
let r = run(&mut s, "document.inspect", json!({}));
|
||||
matches::<DocumentInspectResult>("document.inspect", &r, false);
|
||||
assert!(r["bodies"].as_array().is_some_and(|b| b.iter().any(|b| b["removed_later"] == true)), "{r}");
|
||||
}
|
||||
|
||||
/// `inspect.measure` in each form: bodies (with sheet metal and a material), names only, one
|
||||
/// item and two, in Warn without warnings. Everything it ignores with `items` is ignored.
|
||||
#[test]
|
||||
fn measure_replies_match_its_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let shapes = design(&mut s);
|
||||
run(&mut s, "material.assign", json!({"bodies": ["Block"], "material": "Alloy"}));
|
||||
let id = "inspect.measure";
|
||||
let all = run(&mut s, id, json!({}));
|
||||
matches::<MeasureResult>(id, &all, false);
|
||||
assert_eq!(all["body_count"], 3, "{all}");
|
||||
assert_eq!(all["bodies"][0]["material"], "Alloy", "{all}");
|
||||
assert!((all["bodies"][0]["mass_g"].as_f64().unwrap_or_default() - 15.0).abs() < 1e-6, "{all}");
|
||||
assert!(all["bodies"].as_array().is_some_and(|b| b.iter().any(|b| b["sheet_metal"] == true)), "{all}");
|
||||
assert_eq!(all["total"]["open_bodies_skipped"], 0, "{all}");
|
||||
for p in [json!({"bodies": ["Block"]}), json!({"bodies": "Shaft", "names_only": false}), json!({"bodies": null})] {
|
||||
matches::<MeasureResult>(id, &run(&mut s, id, p), false);
|
||||
}
|
||||
let names = run(&mut s, id, json!({"names_only": true}));
|
||||
assert_eq!(names["bodies"][0], json!({"name": "Block", "definition": "Block"}), "{names}");
|
||||
matches::<MeasureResult>(id, &names, false);
|
||||
matches::<MeasureResult>(id, &run(&mut s, id, json!({"bodies": ["Block"], "names_only": true})), false);
|
||||
|
||||
let face = |body: &str, p: [i32; 3]| json!({"type": "face", "body": body, "point": p});
|
||||
let curve = |c: &str| json!({"type": "sketch_curve", "id": c, "sketch": shapes});
|
||||
for items in [
|
||||
json!([face("Block", [5, 10, 30])]),
|
||||
json!([face("Shaft", [44, 0, 10])]),
|
||||
json!([face("Block", [5, 10, 30]), face("Block", [5, 10, 0])]),
|
||||
json!([face("Block", [5, 10, 30]), face("Block", [10, 10, 15])]),
|
||||
json!([face("Shaft", [44, 0, 10]), face("Block", [5, 10, 30])]),
|
||||
json!([{"type": "edge", "body": "Block", "point": [5, 0, 30]}, {"type": "edge", "body": "Block", "point": [5, 20, 30]}]),
|
||||
json!([{"type": "body", "name": "Block"}]),
|
||||
json!([{"type": "body", "name": "Block"}, {"type": "body", "name": "Shaft"}]),
|
||||
json!([{"type": "vertex", "body": "Block", "point": [0, 0, 0]}, {"type": "vertex", "body": "Block", "point": [10, 20, 30]}]),
|
||||
json!([curve("c1")]),
|
||||
json!([curve("a1")]),
|
||||
json!([curve("l1")]),
|
||||
json!([curve("c1"), curve("c2")]),
|
||||
json!([curve("l1"), curve("l2")]),
|
||||
json!([curve("c1"), curve("l1")]),
|
||||
json!([curve("a1"), face("Block", [5, 10, 30])]),
|
||||
] {
|
||||
let r = run(&mut s, id, json!({ "items": items }));
|
||||
matches::<MeasureResult>(id, &r, false);
|
||||
assert!(r["items"].as_array().is_some_and(|i| i.len() == items.as_array().map_or(0, Vec::len)), "{r}");
|
||||
}
|
||||
let one = run(&mut s, id, json!({"items": [curve("c1")]}));
|
||||
assert!(one["diameter"] == 6.0 && one["circumference"].is_number() && one["center"].is_array(), "{one}");
|
||||
let arc = run(&mut s, id, json!({"items": [curve("a1")]}));
|
||||
assert!(arc["arc_length"].is_number() && arc["angle_deg"].is_number() && arc.get("circumference").is_none(), "{arc}");
|
||||
let two = run(&mut s, id, json!({"items": [face("Block", [5, 10, 30]), face("Block", [5, 10, 0])]}));
|
||||
assert!(two["distance_mm"] == 30.0 && two["min"] == 30.0 && two["measure"] == "min" && two["angle_deg"].is_number(), "{two}");
|
||||
let pair = run(&mut s, id, json!({"items": [curve("c1"), curve("c2")]}));
|
||||
assert!(pair["measure"] == "center" && pair["center_distance"].is_number(), "{pair}");
|
||||
// With `items`, `bodies` and `names_only` are not read at all.
|
||||
let r = run(&mut s, id, json!({"items": [face("Block", [5, 10, 30])], "bodies": 7, "names_only": "yes"}));
|
||||
matches::<MeasureResult>(id, &r, false);
|
||||
}
|
||||
|
||||
/// `sketch.inspect` of every curve kind, a dimension and a projected link, by id, by name and as
|
||||
/// the sketch being edited, in Warn without warnings.
|
||||
#[test]
|
||||
fn sketch_inspect_replies_match_its_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let shapes = design(&mut s);
|
||||
let id = "sketch.inspect";
|
||||
for p in [json!({"sketch": shapes}), json!({"sketch": "Shapes"}), json!({"sketch": "Top"}), json!({"sketch": "Base"})] {
|
||||
matches::<SketchInspected>(id, &run(&mut s, id, p), false);
|
||||
}
|
||||
let r = run(&mut s, id, json!({"sketch": "Shapes"}));
|
||||
let kinds: Vec<&str> = r["curves"].as_array().into_iter().flatten().filter_map(|c| c["type"].as_str()).collect();
|
||||
for kind in ["line", "circle", "arc", "ellipse", "spline", "conic"] {
|
||||
assert!(kinds.contains(&kind), "{kind} in {kinds:?}");
|
||||
}
|
||||
assert!(
|
||||
r["constraints"].as_array().is_some_and(|c| c.iter().any(|c| c["param"].is_string() && c["expression"].is_string() && c["type"].is_string())),
|
||||
"{r}"
|
||||
);
|
||||
assert!(r["profiles"][0]["holes"].is_array() && r["points"][0]["link"].is_null(), "{r}");
|
||||
let top = run(&mut s, id, json!({"sketch": "Top"}));
|
||||
assert!(top["links"][0]["id"].is_string() && top["curves"][0]["link"].is_string(), "{top}");
|
||||
run(&mut s, "sketch.edit", json!({"sketch": "Shapes"}));
|
||||
for p in [json!({}), json!({"sketch": null}), json!({"sketch": shapes.to_string()})] {
|
||||
let r = run(&mut s, id, p);
|
||||
matches::<SketchInspected>(id, &r, false);
|
||||
assert_eq!(r["name"], "Shapes", "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `material.assign` (a name, a list, the default material) and `material.list` (built-in
|
||||
/// materials and the design's, with and without a look) in Warn without warnings.
|
||||
#[test]
|
||||
fn material_replies_match_their_schemas() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
design(&mut s);
|
||||
let id = "material.assign";
|
||||
let r = run(&mut s, id, json!({"bodies": ["Block"], "material": "alloy"}));
|
||||
assert_eq!(r, json!({"bodies": ["Block"], "material": "Alloy"}));
|
||||
matches::<MaterialAssignResult>(id, &r, false);
|
||||
let r = run(&mut s, id, json!({"bodies": "Shaft", "material": " steel "}));
|
||||
assert_eq!(r["material"], "Steel", "{r}");
|
||||
matches::<MaterialAssignResult>(id, &r, false);
|
||||
matches::<MaterialAssignResult>(id, &run(&mut s, id, json!({"bodies": ["Block", "Shaft"], "material": "Painted"})), false);
|
||||
matches::<MaterialAssignResult>(id, &run(&mut s, id, json!({"bodies": ["Block"], "material": "Steel"})), false);
|
||||
|
||||
let listed = run(&mut s, "material.list", json!({}));
|
||||
matches::<MaterialListResult>("material.list", &listed, false);
|
||||
let materials = listed["materials"].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(materials[0].as_object().map(|m| m.len()), Some(2), "{listed}");
|
||||
let mine = |name: &str| materials.iter().find(|m| m["name"] == name).cloned().unwrap_or_default();
|
||||
assert!(mine("Alloy")["user"] == true && mine("Alloy")["appearance"]["color"] == "#ff0000", "{listed}");
|
||||
assert!(mine("Painted")["appearance"]["pbr"]["metallic"] == 0.5, "{listed}");
|
||||
assert!(mine("Steel").get("user").is_none() && mine("Steel").get("appearance").is_none(), "{listed}");
|
||||
run(&mut s, "material.create", json!({"name": "Bare", "density_g_cm3": 1.0}));
|
||||
let listed = run(&mut s, "material.list", json!({}));
|
||||
matches::<MaterialListResult>("material.list", &listed, false);
|
||||
let bare = listed["materials"].as_array().into_iter().flatten().find(|m| m["name"] == "Bare").cloned().unwrap_or_default();
|
||||
assert!(bare["appearance"].is_null() && bare["user"] == true, "{listed}");
|
||||
}
|
||||
|
||||
/// `engine.commands` replies with a list, which carries no `param_warnings`: Strict is where a
|
||||
/// stray key is refused. The list has every command, and each entry matches its schema.
|
||||
#[test]
|
||||
fn the_command_list_matches_its_schema() {
|
||||
let mut strict = Session { param_check: ParamCheck::Strict, ..Session::default() };
|
||||
let list = run(&mut strict, "engine.commands", json!({}));
|
||||
let schema = output_schema_for::<Vec<CommandEntry>>();
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &list), "{list}");
|
||||
assert_eq!(list.as_array().map(Vec::len), Some(crate::command_specs().len()));
|
||||
assert!(list.as_array().is_some_and(|l| l.iter().any(|c| c["id"] == "engine.commands" && c["enabled"] == true && c["shortcut"].is_null())));
|
||||
assert!(list.as_array().is_some_and(|l| l.iter().any(|c| c["id"] == "inspect.measure" && c["shortcut"] == "I")));
|
||||
let error = strict.execute("engine.commands", &json!({"lst": 1})).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("unknown key `lst`"), "{error}");
|
||||
let mut warn = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
assert!(run(&mut warn, "engine.commands", json!({"lst": 1})).is_array());
|
||||
}
|
||||
|
||||
/// A misspelt key runs in Warn and is reported, with a reply that still matches its schema.
|
||||
#[test]
|
||||
fn a_misspelt_key_is_reported_in_warn() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let shapes = design(&mut s);
|
||||
let schemas = |id: &str| match id {
|
||||
"document.inspect" => output_schema_for::<DocumentInspectResult>(),
|
||||
"inspect.measure" => output_schema_for::<MeasureResult>(),
|
||||
"material.assign" => output_schema_for::<MaterialAssignResult>(),
|
||||
"material.list" => output_schema_for::<MaterialListResult>(),
|
||||
_ => output_schema_for::<SketchInspected>(),
|
||||
};
|
||||
for (id, p, suggestion) in [
|
||||
("document.inspect", json!({"mesure": true}), "measure"),
|
||||
("document.inspect", json!({"sketch_count": true}), "sketch_counts"),
|
||||
("inspect.measure", json!({"bodes": ["Block"]}), "bodies"),
|
||||
("inspect.measure", json!({"name_only": true}), "names_only"),
|
||||
("material.assign", json!({"bodies": ["Block"], "materal": "Steel", "material": "Steel"}), "material"),
|
||||
("material.list", json!({"materials": true}), ""),
|
||||
("sketch.inspect", json!({"sketch": shapes, "sketchs": 1}), "sketch"),
|
||||
] {
|
||||
let r = run(&mut s, id, p.clone());
|
||||
let warnings: Vec<&str> = r["param_warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
assert_eq!(warnings.len(), 1, "{id} {p}: {r}");
|
||||
assert!(warnings[0].starts_with("unknown key `") && warnings[0].contains(suggestion), "{id}: {warnings:?}");
|
||||
let schema = schemas(id);
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &r), "{id}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Shapes the real designs above don't reach: a body whose measurement failed (a sheet metal
|
||||
/// one carries its corrected counts) and the null coordinates of two planes that meet.
|
||||
#[test]
|
||||
fn rare_reply_shapes_serialize_as_before_and_match_the_schema() {
|
||||
use super::{BodyFailure, BodyMeasurement, BodyOutcome, Measured, MeasuredItems};
|
||||
let failed = BodyMeasurement {
|
||||
name: "B".into(),
|
||||
outcome: BodyOutcome::Failed(BodyFailure { error: "boom".into(), faces: Some(2), edges: None, vertices: None }),
|
||||
};
|
||||
assert_eq!(serde_json::to_value(&failed).unwrap_or_default(), json!({"name": "B", "error": "boom", "faces": 2}));
|
||||
let items = MeasuredItems { from: Some([f64::NAN, 0.0, 0.0]), distance_mm: Some(0.0), ..MeasuredItems::default() };
|
||||
let reply = serde_json::to_value(MeasureResult { measured: Measured::Items(Box::new(items)), param_warnings: Vec::new() }).unwrap_or_default();
|
||||
assert_eq!(reply["from"], json!([null, 0.0, 0.0]));
|
||||
let schema = output_schema_for::<MeasureResult>();
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}");
|
||||
}
|
||||
|
||||
/// #11945: each body lists the features that built it, in timeline order: its own box, the fillet
|
||||
/// that changed it, and the cutting box a Combine consumed into it with that Combine. Another body
|
||||
/// keeps only its own. Rolled back before the Combine, neither it nor the tool's box are listed.
|
||||
|
||||
@@ -104,13 +104,16 @@ pub mod section;
|
||||
pub mod sheet;
|
||||
pub mod silhouette;
|
||||
pub mod sketch;
|
||||
pub mod sketch_3d;
|
||||
pub mod sketch_clipboard;
|
||||
pub mod sketch_constraints;
|
||||
pub mod sketch_create;
|
||||
pub mod sketch_ends;
|
||||
pub mod sketch_equation;
|
||||
pub mod sketch_import;
|
||||
pub mod sketch_inspect;
|
||||
pub mod sketch_modify;
|
||||
pub mod sketch_project;
|
||||
pub mod sketch_shapes;
|
||||
pub mod surface_analysis;
|
||||
pub mod surface_boundary;
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
//! Contracts and result types for the commands in `cmd/parameters.rs` that manage the design's
|
||||
//! user parameters by name (#11941): `parameters.add`, `.rename`, `.delete`, `.comment`,
|
||||
//! `.favorite` and `.move`.
|
||||
//! Contracts and result types for the commands in `cmd/parameters.rs`: those that manage the
|
||||
//! design's user parameters by name (#11941), `parameters.add`, `.rename`, `.delete`, `.comment`,
|
||||
//! `.favorite` and `.move`, and the rest (#12497): `parameters.change`, `.list`, `.users`,
|
||||
//! `.graph`, `.export`, `.import`, `.complete` and `expr.evaluate`.
|
||||
//!
|
||||
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
//! reads it and fails with the handler's message. Whether a parameter exists, and whether a new
|
||||
//! name, unit or expression is valid, stays the document's to check, with its messages.
|
||||
|
||||
use schemars::{JsonSchema, Schema};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
use serde_json::{Map, Value, json};
|
||||
use solidcraft_doc::expr::Kind;
|
||||
use solidcraft_doc::{ParamRow, ParamUser};
|
||||
|
||||
use super::check::whole;
|
||||
use super::check::{located, whole};
|
||||
|
||||
/// A parameter's name, as `cmd/parameters.rs`'s `param_name` reads `name`: text that isn't blank,
|
||||
/// with its message for anything else. Spaces at either end are dropped.
|
||||
@@ -296,6 +302,854 @@ pub struct ParamMoved {
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// #12497: `parameters.change`, `.list`, `.users`, `.graph`, `.export`, `.import`, `.complete`
|
||||
// and `expr.evaluate`.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Adds `key` to the schema's `required` list: for a key the type has optional so that the
|
||||
/// handler, not the check, refuses it when it's left out.
|
||||
fn require(schema: &mut Schema, key: &str) {
|
||||
match schema.get_mut("required") {
|
||||
Some(Value::Array(required)) => {
|
||||
if !required.iter().any(|k| k == key) {
|
||||
required.push(key.into());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
schema.insert("required".into(), Value::Array(vec![key.into()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `key` as text: `null` is left out, as `str_` reads it. Anything else is refused, though the
|
||||
/// handler would read it as left out; `message` is the handler's for that case, if it has one.
|
||||
fn text_or_null<'de, D: Deserializer<'de>>(d: D, message: &str) -> Result<Option<String>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
Value::String(s) => Ok(Some(s)),
|
||||
_ => Err(D::Error::custom(whole(message))),
|
||||
}
|
||||
}
|
||||
|
||||
/// What `parameters.change` takes, in the form it's read in: see [`ParamChangeParams`].
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = change_forms)]
|
||||
pub struct ParamChangeKeys {
|
||||
/// Several existing parameters at once, `{name: expression}`: they are checked together and
|
||||
/// the design is rebuilt once, all or nothing. Renaming isn't done this way. When given,
|
||||
/// no other key is read.
|
||||
#[serde(default, deserialize_with = "changes_map", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "changes_schema")]
|
||||
pub changes: Option<Map<String, Value>>,
|
||||
/// Delete this user parameter (refused while something uses it). When given as text, no
|
||||
/// other key but `changes` is read.
|
||||
#[serde(default, deserialize_with = "delete_text")]
|
||||
pub delete: Option<String>,
|
||||
/// The parameter to change, by name: a user parameter, a sketch dimension or a feature's
|
||||
/// named input. Spaces at either end are dropped.
|
||||
#[serde(default, deserialize_with = "change_name", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "String", length(min = 1))]
|
||||
pub name: Option<String>,
|
||||
/// The new value: a number, or an expression as text (`25 mm`, `W / 2`). A text
|
||||
/// parameter's expression is its text, quotes round it optional. `name = value` renames
|
||||
/// the parameter to `name` and sets the value (or sets `name` when the value is just
|
||||
/// `name`). Needed unless `new_name`, `favorite` or `comment` is given.
|
||||
#[serde(default, deserialize_with = "expression")]
|
||||
#[schemars(schema_with = "expression_schema")]
|
||||
pub expression: Option<Value>,
|
||||
/// Another name for `expression`, read when `expression` isn't a number or text.
|
||||
#[serde(default, deserialize_with = "expression")]
|
||||
#[schemars(schema_with = "expression_schema")]
|
||||
pub value: Option<Value>,
|
||||
/// The unit: `mm`, `cm`, `m`, `in`, `ft`, `deg`, `rad`, `""` (no unit) or `text`. Default:
|
||||
/// the parameter's own, or for a new one its value's unit, a length in the design's units.
|
||||
#[serde(default, deserialize_with = "unit_text")]
|
||||
pub unit: Option<String>,
|
||||
/// A note to show with the parameter.
|
||||
#[serde(default, deserialize_with = "comment_key")]
|
||||
pub comment: Option<String>,
|
||||
/// List it with the favourites, first, or not.
|
||||
#[serde(default, deserialize_with = "favorite_flag")]
|
||||
pub favorite: Option<bool>,
|
||||
/// Rename the parameter: the expressions, feature inputs and dimensions that use it follow.
|
||||
/// With an `expression` the new value is set too.
|
||||
#[serde(default, deserialize_with = "new_name_key")]
|
||||
pub new_name: Option<String>,
|
||||
}
|
||||
|
||||
fn changes_map<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Map<String, Value>>, D::Error> {
|
||||
let Value::Object(map) = Value::deserialize(d)? else {
|
||||
return Err(D::Error::custom(whole("`changes` must be an object of name: expression")));
|
||||
};
|
||||
if map.is_empty() {
|
||||
return Err(D::Error::custom(whole("`changes` is empty")));
|
||||
}
|
||||
for (name, e) in &map {
|
||||
// `expr_arg`: text, or a number.
|
||||
if !matches!(e, Value::String(_) | Value::Number(_)) {
|
||||
return Err(D::Error::custom(whole(format!("`changes.{name}` must be a number or text"))));
|
||||
}
|
||||
}
|
||||
Ok(Some(map))
|
||||
}
|
||||
|
||||
fn changes_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "Several existing parameters at once, `{name: expression}`: they are checked together and the design is rebuilt once, all or nothing. Renaming isn't done this way (`name = value` is refused). When given, no other key is read.",
|
||||
"type": "object",
|
||||
"minProperties": 1,
|
||||
"additionalProperties": {"type": ["number", "string"]}
|
||||
})
|
||||
}
|
||||
|
||||
fn delete_text<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "`delete` must be text")
|
||||
}
|
||||
|
||||
fn unit_text<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "`unit` must be text")
|
||||
}
|
||||
|
||||
fn comment_key<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "`comment` must be text")
|
||||
}
|
||||
|
||||
fn new_name_key<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "`new_name` must be text")
|
||||
}
|
||||
|
||||
fn favorite_flag<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
Value::Bool(b) => Ok(Some(b)),
|
||||
_ => Err(D::Error::custom(whole("`favorite` must be true or false"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` of a single change, as `param_name` reads it: text that isn't blank, `null` included
|
||||
/// in what is refused.
|
||||
fn change_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
param_name(d).map(Some)
|
||||
}
|
||||
|
||||
/// `parameters.change` takes one of three forms: `changes`, `delete` or `name` with what to
|
||||
/// change about it.
|
||||
fn change_forms(schema: &mut Schema) {
|
||||
let name_with = json!({
|
||||
"required": ["name"],
|
||||
"properties": {"name": {"type": "string"}},
|
||||
"anyOf": [
|
||||
{"required": ["expression"], "properties": {"expression": {"type": ["number", "string"]}}},
|
||||
{"required": ["value"], "properties": {"value": {"type": ["number", "string"]}}},
|
||||
{"required": ["new_name"]},
|
||||
{"required": ["favorite"]},
|
||||
{"required": ["comment"]}
|
||||
]
|
||||
});
|
||||
schema.insert(
|
||||
"anyOf".into(),
|
||||
json!([
|
||||
{"required": ["changes"]},
|
||||
{"required": ["delete"], "properties": {"delete": {"type": "string"}}},
|
||||
name_with
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/// Change a parameter: set its expression, unit, comment or favourite, rename it (references
|
||||
/// follow), delete it, or set several existing parameters at once. The design is rebuilt once
|
||||
/// and the features that changed are named in the reply. One undo step.
|
||||
///
|
||||
/// The handler reads `changes` alone when it is given, else `delete` alone when that is text,
|
||||
/// else the keys of a single change; the keys of a form it doesn't read are left unchecked.
|
||||
#[derive(Debug)]
|
||||
pub struct ParamChangeParams(pub ParamChangeKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for ParamChangeParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
if let Some(keys) = value.as_object_mut() {
|
||||
let only = if keys.contains_key("changes") {
|
||||
Some("changes")
|
||||
} else if matches!(keys.get("delete"), Some(Value::String(_))) {
|
||||
Some("delete")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Otherwise a single change: `changes` isn't there, and `delete` isn't text.
|
||||
if let Some(only) = only {
|
||||
keys.retain(|k, _| k == only || !CHANGE_KEYS.contains(&k.as_str()));
|
||||
}
|
||||
// `value` is read only when `expression` isn't a number or text.
|
||||
else if matches!(keys.get("expression"), Some(Value::String(_) | Value::Number(_))) {
|
||||
keys.remove("value");
|
||||
}
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(ParamChangeParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
const CHANGE_KEYS: [&str; 9] = ["changes", "delete", "name", "expression", "value", "unit", "comment", "favorite", "new_name"];
|
||||
|
||||
impl JsonSchema for ParamChangeParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ParamChangeParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
ParamChangeKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// A feature that failed to rebuild: its name and error.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct FailedFeature {
|
||||
/// The feature's name.
|
||||
pub feature: String,
|
||||
/// Why it failed.
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
impl FailedFeature {
|
||||
/// The features of `results` that failed.
|
||||
pub fn of(results: &[solidcraft_doc::FeatureResult]) -> Vec<FailedFeature> {
|
||||
results.iter().filter_map(|r| r.error.as_ref().map(|e| FailedFeature { feature: r.name.clone(), error: e.clone() })).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A feature a configuration rule switched on or off.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SwitchedFeature {
|
||||
/// The feature's id.
|
||||
pub feature: u64,
|
||||
/// Its name; `null` if it is gone.
|
||||
pub name: Option<String>,
|
||||
/// Whether it is suppressed now.
|
||||
pub suppressed: bool,
|
||||
}
|
||||
|
||||
/// A parameter that was renamed.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParamRename {
|
||||
/// The old name.
|
||||
pub from: String,
|
||||
/// The new name.
|
||||
pub to: String,
|
||||
/// How many expressions, feature inputs and dimensions were changed to use the new name.
|
||||
pub references_updated: usize,
|
||||
}
|
||||
|
||||
/// What `parameters.change` returns: one of three shapes, by what was asked.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParamChanged {
|
||||
#[serde(flatten)]
|
||||
pub body: ParamChangedBody,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The shapes of a `parameters.change` reply.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum ParamChangedBody {
|
||||
/// A parameter was deleted (`delete`).
|
||||
Deleted {
|
||||
/// The deleted parameter's name.
|
||||
deleted: String,
|
||||
},
|
||||
/// Several parameters were set (`changes`).
|
||||
Many {
|
||||
/// Each changed parameter's value, in mm for a length and degrees for an angle; `null`
|
||||
/// where it can't be worked out.
|
||||
changed: BTreeMap<String, Option<f64>>,
|
||||
/// How many features were rebuilt.
|
||||
recomputed: usize,
|
||||
/// How many features reused an earlier result for the same inputs (a value set back).
|
||||
restored: usize,
|
||||
/// The features that failed to rebuild.
|
||||
errors: Vec<FailedFeature>,
|
||||
/// The features the configuration rules switched, when they did.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
switched: Vec<SwitchedFeature>,
|
||||
},
|
||||
/// One parameter was changed.
|
||||
One(Box<ParamChangedOne>),
|
||||
}
|
||||
|
||||
/// What changing one parameter returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParamChangedOne {
|
||||
/// Set when the parameter was renamed (`new_name`, or `name = expression`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub renamed: Option<ParamRename>,
|
||||
/// Set when `name = expression` set the parameter that the changed value's expression named:
|
||||
/// the name asked for.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub changed_through: Option<String>,
|
||||
/// The features the configuration rules switched, when they did.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub switched: Vec<SwitchedFeature>,
|
||||
/// The parameter's name now.
|
||||
pub name: String,
|
||||
/// The expression it has now; `null` when only its name, comment or favourite changed.
|
||||
pub expression: Option<String>,
|
||||
/// A text parameter's text.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<String>,
|
||||
/// Its value in mm for a length and degrees for an angle, as in every reply; `null` if it
|
||||
/// can't be worked out.
|
||||
pub value: Option<f64>,
|
||||
/// Its value in its own unit; `null` if it can't be worked out.
|
||||
pub display_value: Option<f64>,
|
||||
/// How many features were rebuilt.
|
||||
pub recomputed: usize,
|
||||
/// How many features reused an earlier result for the same inputs (a value set back).
|
||||
pub restored: usize,
|
||||
/// The features that failed to rebuild.
|
||||
pub errors: Vec<FailedFeature>,
|
||||
}
|
||||
|
||||
/// List the parameters: the user's, the sketch dimensions' and the feature inputs', favourites
|
||||
/// first, with each one's expression, value, uses and users, and any cycles. Changes nothing.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ParamListKeys {
|
||||
/// Only the favourites. When true, `filter` isn't read. Default: false.
|
||||
#[serde(default, deserialize_with = "list_favorites")]
|
||||
pub favorites: Option<bool>,
|
||||
/// Which parameters, ignoring case: `all`, `user`, `sketch` (dimensions), `feature` (inputs),
|
||||
/// `model` (every one but the user's) or `favorites`. Anything else lists all. Default: all.
|
||||
#[serde(default, deserialize_with = "list_filter")]
|
||||
pub filter: Option<String>,
|
||||
}
|
||||
|
||||
fn list_favorites<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
Value::Bool(b) => Ok(Some(b)),
|
||||
_ => Err(D::Error::custom(whole("`favorites` must be true or false"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_filter<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "`filter` must be text")
|
||||
}
|
||||
|
||||
/// `parameters.list`'s parameters: [`ParamListKeys`], with `filter` left unread when
|
||||
/// `favorites` is true, as the handler leaves it.
|
||||
#[derive(Debug)]
|
||||
pub struct ParamListParams(pub ParamListKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for ParamListParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
if let Some(keys) = value.as_object_mut().filter(|o| o.get("favorites") == Some(&Value::Bool(true))) {
|
||||
keys.remove("filter");
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(ParamListParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ParamListParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ParamListParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
ParamListKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of the parameters table.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParameterRow {
|
||||
pub name: String,
|
||||
pub expression: String,
|
||||
/// Its unit; `""` for none, `text` for a text parameter.
|
||||
pub unit: String,
|
||||
/// Its value in mm for a length and degrees for an angle, whatever its own unit; `null` if
|
||||
/// it can't be worked out (a text parameter has none).
|
||||
pub value: Option<f64>,
|
||||
/// Its value in its own unit, as the Parameters window shows it.
|
||||
pub display_value: Option<f64>,
|
||||
/// Why it can't be worked out, when it can't.
|
||||
pub error: Option<String>,
|
||||
pub comment: String,
|
||||
/// `user`, `sketch` (a dimension) or `feature` (a feature's named input).
|
||||
pub source: String,
|
||||
/// For a feature input: the feature.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub feature: Option<String>,
|
||||
/// For a feature input: the input's label.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub input: Option<String>,
|
||||
pub favorite: bool,
|
||||
/// The names its expression uses.
|
||||
pub uses: Vec<String>,
|
||||
/// The names whose expressions use it.
|
||||
pub used_by: Vec<String>,
|
||||
/// A text parameter's text.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
impl From<ParamRow> for ParameterRow {
|
||||
fn from(r: ParamRow) -> Self {
|
||||
ParameterRow {
|
||||
name: r.name,
|
||||
expression: r.expression,
|
||||
unit: r.unit,
|
||||
value: r.value,
|
||||
display_value: r.display_value,
|
||||
error: r.error,
|
||||
comment: r.comment,
|
||||
source: r.source.to_string(),
|
||||
feature: r.feature,
|
||||
input: r.input.map(str::to_string),
|
||||
favorite: r.favorite,
|
||||
uses: r.uses,
|
||||
used_by: r.used_by,
|
||||
text: r.text,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `parameters.list` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParamListResult {
|
||||
/// The parameters listed, favourites first.
|
||||
pub parameters: Vec<ParameterRow>,
|
||||
/// How many there are.
|
||||
pub count: usize,
|
||||
/// The names whose expressions refer to themselves, directly or through others.
|
||||
pub cycles: Vec<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// List what uses a parameter: other parameters, feature inputs, sketch dimensions,
|
||||
/// configurations, joints, rules and canvases, and the features it drives. Changes nothing.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ParamUsersParams {
|
||||
/// The parameter, by name: a user parameter, a dimension or a feature's named input.
|
||||
#[serde(deserialize_with = "param_name")]
|
||||
#[schemars(length(min = 1))]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Something that uses a parameter.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ParameterUser {
|
||||
/// Another parameter's expression (a stored one or a feature input).
|
||||
Parameter { name: String },
|
||||
/// A feature input (`input` is its label, e.g. `Distance`).
|
||||
Feature { feature: u64, name: String, input: String },
|
||||
/// A sketch dimension (`constraint` is its id).
|
||||
Dimension { feature: u64, name: String, constraint: String },
|
||||
/// A configured column or an expression saved in a configuration row.
|
||||
Configuration { row: Option<String>, column: String },
|
||||
/// A joint's offset, angle or value, or a motion link's gear, rack or screw length (`input`
|
||||
/// says which).
|
||||
Joint { joint: u64, name: String, input: String },
|
||||
/// A sheet metal or plastic rule's value (`kind` says which, `field` which value).
|
||||
Rule { kind: String, name: String, field: String },
|
||||
/// The plane a canvas lies on (`input` is its label, e.g. `Offset`).
|
||||
Canvas { canvas: u64, name: String, input: String },
|
||||
}
|
||||
|
||||
impl From<ParamUser> for ParameterUser {
|
||||
fn from(u: ParamUser) -> Self {
|
||||
match u {
|
||||
ParamUser::Parameter { name } => ParameterUser::Parameter { name },
|
||||
ParamUser::Feature { feature, name, input } => ParameterUser::Feature { feature, name, input },
|
||||
ParamUser::Dimension { feature, name, constraint } => ParameterUser::Dimension { feature, name, constraint },
|
||||
ParamUser::Configuration { row, column } => ParameterUser::Configuration { row, column },
|
||||
ParamUser::Joint { joint, name, input } => ParameterUser::Joint { joint, name, input },
|
||||
ParamUser::Rule { kind, name, field } => ParameterUser::Rule { kind, name, field },
|
||||
ParamUser::Canvas { canvas, name, input } => ParameterUser::Canvas { canvas, name, input },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A feature a parameter drives.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DrivenFeature {
|
||||
/// The feature's id.
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// What `parameters.users` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParamUsersResult {
|
||||
/// The parameter's name, spaces at either end dropped.
|
||||
pub name: String,
|
||||
/// What uses it directly.
|
||||
pub users: Vec<ParameterUser>,
|
||||
/// The features it drives, directly or through other parameters.
|
||||
pub drives: Vec<DrivenFeature>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// `parameters.graph` takes no parameters.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ParamGraphParams {}
|
||||
|
||||
/// What `parameters.graph` returns: the dependency graph of the parameters.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParamGraphResult {
|
||||
/// Every parameter name: the user's, the dimensions' and the feature inputs'.
|
||||
pub nodes: Vec<String>,
|
||||
/// `[user, used]`: the first's expression uses the second; a user may be `Feature:<name>`.
|
||||
pub edges: Vec<[String; 2]>,
|
||||
/// The names whose expressions refer to themselves, directly or through others.
|
||||
pub cycles: Vec<String>,
|
||||
/// The parameters that can't be worked out, with why, by name.
|
||||
pub errors: BTreeMap<String, String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Export the user parameters as CSV or JSON text, and write it to a file when a path is
|
||||
/// given. Changes nothing in the design.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ParamExportParams {
|
||||
/// `csv` or `json`, ignoring case. Default: `json` when `path` ends in `.json`, else `csv`.
|
||||
#[serde(default)]
|
||||
pub format: Option<String>,
|
||||
/// A file to write the text to. Default: none is written.
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
/// What `parameters.export` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParamExportResult {
|
||||
/// The format used, `csv` or `json`.
|
||||
pub format: String,
|
||||
/// The file written; `null` if none was.
|
||||
pub path: Option<String>,
|
||||
/// The exported text.
|
||||
pub text: String,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `parameters.import` takes, as the handler reads it: see [`ParamImportParams`].
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = import_forms)]
|
||||
pub struct ParamImportKeys {
|
||||
/// The table as text: CSV with a header (`name`, `expression`, and optionally `unit` and
|
||||
/// `comment`), or JSON `[{name, expression, unit?, comment?}]`. When given, `path` isn't
|
||||
/// read.
|
||||
#[serde(default, deserialize_with = "import_text", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "String")]
|
||||
pub text: Option<String>,
|
||||
/// A file to read the table from, in the same forms. Read when `text` isn't given.
|
||||
#[serde(default, deserialize_with = "import_text", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "String")]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
/// `text` and `path`: text; `null` is left out, as `str_` reads it. Anything else gets the
|
||||
/// message the handler gives when it finds neither.
|
||||
fn import_text<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "give `text` or `path`")
|
||||
}
|
||||
|
||||
/// `parameters.import` needs `text` or `path` as text.
|
||||
fn import_forms(schema: &mut Schema) {
|
||||
schema.insert(
|
||||
"anyOf".into(),
|
||||
json!([
|
||||
{"required": ["text"], "properties": {"text": {"type": "string"}}},
|
||||
{"required": ["path"], "properties": {"path": {"type": "string"}}}
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/// Add the parameters in a CSV or JSON table, all or nothing. A name that exists is refused.
|
||||
/// One undo step.
|
||||
///
|
||||
/// `path` is not read when `text` is text, as the handler leaves it.
|
||||
#[derive(Debug)]
|
||||
pub struct ParamImportParams(pub ParamImportKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for ParamImportParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
if let Some(keys) = value.as_object_mut() {
|
||||
match keys.get("text") {
|
||||
Some(Value::String(_)) => {
|
||||
keys.remove("path");
|
||||
}
|
||||
// Not text, so the handler reads `path`: when that works, this is the one thing
|
||||
// wrong; when it doesn't, the handler's message says what is needed.
|
||||
Some(Value::Number(_) | Value::Bool(_) | Value::Array(_) | Value::Object(_))
|
||||
if matches!(keys.get("path"), Some(Value::String(_))) =>
|
||||
{
|
||||
return Err(D::Error::custom(whole("`text` must be text")));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(ParamImportParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ParamImportParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ParamImportParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
ParamImportKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// What `parameters.import` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParamImportResult {
|
||||
/// The names of the parameters added, in order.
|
||||
pub imported: Vec<String>,
|
||||
/// The features that failed to rebuild with them.
|
||||
pub errors: Vec<FailedFeature>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `expr.evaluate` takes, as the handler reads it: see [`ExprEvaluateParams`].
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = expression_required)]
|
||||
pub struct ExprEvaluateKeys {
|
||||
/// The expression: text (`25 mm`, `W / 2`, `name = 3 * W`) or a number. With unit `text`, the
|
||||
/// text a text parameter would hold.
|
||||
// Optional in the type and required in the schema (`expression_required`): left out, the
|
||||
// handler refuses it with its own message.
|
||||
#[serde(default, deserialize_with = "evaluate_expression", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ExpressionText")]
|
||||
pub expression: Option<ExpressionText>,
|
||||
/// The unit the answer is shown in, and what bare numbers mean: `mm`, `cm`, `m`, `in`, `ft`,
|
||||
/// `deg`, `rad`, `""` (none) or `text` (a text parameter's text). Default: none; bare numbers
|
||||
/// follow the design's length unit.
|
||||
#[serde(default, deserialize_with = "evaluate_unit")]
|
||||
pub unit: Option<String>,
|
||||
/// What it must evaluate to: `length`, `angle` or `unitless` (`number` too). Default: the
|
||||
/// unit's kind, or what the expression is. Not read when `unit` is `text`.
|
||||
#[serde(default, deserialize_with = "evaluate_kind")]
|
||||
pub kind: Option<String>,
|
||||
}
|
||||
|
||||
/// An expression given as text or as a number, as `expr_arg` reads it.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ExpressionText(pub String);
|
||||
|
||||
impl JsonSchema for ExpressionText {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ExpressionText".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "An expression as text, or a number.", "type": ["number", "string"]})
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate_expression<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ExpressionText>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(Some(ExpressionText(s))),
|
||||
Value::Number(n) => n
|
||||
.as_f64()
|
||||
.filter(|v| v.is_finite())
|
||||
.map(|v| Some(ExpressionText(format!("{v}"))))
|
||||
.ok_or_else(|| D::Error::custom(whole("`expression` must be text or a number"))),
|
||||
_ => Err(D::Error::custom(whole("`expression` must be text or a number"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate_unit<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "`unit` must be text")
|
||||
}
|
||||
|
||||
fn evaluate_kind<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "`kind` must be text")
|
||||
}
|
||||
|
||||
fn expression_required(schema: &mut Schema) {
|
||||
require(schema, "expression");
|
||||
}
|
||||
|
||||
/// Evaluate an expression against the design's parameters, without changing anything: its
|
||||
/// value (in mm for a length, radians for an angle), its value in the unit asked for, what it
|
||||
/// names, or why it fails. `name = expression` is worth its expression and says what it would
|
||||
/// define.
|
||||
///
|
||||
/// `kind` is not read when `unit` is `text`, as the handler leaves it.
|
||||
#[derive(Debug)]
|
||||
pub struct ExprEvaluateParams(pub ExprEvaluateKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for ExprEvaluateParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
if let Some(keys) = value.as_object_mut()
|
||||
&& keys.get("unit").and_then(Value::as_str).is_some_and(solidcraft_doc::text_params::is_text_unit)
|
||||
{
|
||||
keys.remove("kind");
|
||||
}
|
||||
serde_path_to_error::deserialize(&value).map(ExprEvaluateParams).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ExprEvaluateParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ExprEvaluateParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
ExprEvaluateKeys::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// What an evaluated expression is.
|
||||
#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum EvalKind {
|
||||
Length,
|
||||
Angle,
|
||||
Unitless,
|
||||
}
|
||||
|
||||
impl From<Kind> for EvalKind {
|
||||
fn from(k: Kind) -> Self {
|
||||
match k {
|
||||
Kind::Length => EvalKind::Length,
|
||||
Kind::Angle => EvalKind::Angle,
|
||||
Kind::Unitless => EvalKind::Unitless,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EvalKind {
|
||||
/// The word for it, as it's serialized.
|
||||
pub fn word(self) -> &'static str {
|
||||
match self {
|
||||
EvalKind::Length => "length",
|
||||
EvalKind::Angle => "angle",
|
||||
EvalKind::Unitless => "unitless",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `expr.evaluate` returns: one of three shapes.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExprEvaluated {
|
||||
#[serde(flatten)]
|
||||
pub body: ExprEvaluatedBody,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The shapes of an `expr.evaluate` reply.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum ExprEvaluatedBody {
|
||||
/// With unit `text`: the text a text parameter would hold.
|
||||
Text {
|
||||
/// Always true.
|
||||
ok: bool,
|
||||
/// Always `text`.
|
||||
kind: String,
|
||||
/// The text, without the quotes round it.
|
||||
text: String,
|
||||
/// Always empty.
|
||||
references: Vec<String>,
|
||||
},
|
||||
/// The expression evaluated.
|
||||
Value {
|
||||
/// Always true.
|
||||
ok: bool,
|
||||
/// Its value: mm for a length, radians for an angle.
|
||||
value: f64,
|
||||
/// What it is.
|
||||
kind: EvalKind,
|
||||
/// Its value in the unit asked for; with none, degrees for an angle and the value itself
|
||||
/// otherwise.
|
||||
display_value: f64,
|
||||
/// The parameters it names.
|
||||
references: Vec<String>,
|
||||
/// For `name = expression`: the name it would define.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
defines: Option<String>,
|
||||
},
|
||||
/// The expression didn't evaluate.
|
||||
Failed {
|
||||
/// Always false.
|
||||
ok: bool,
|
||||
/// Why.
|
||||
error: String,
|
||||
/// The parameters it names.
|
||||
references: Vec<String>,
|
||||
/// For `name = expression`: the name it would define.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
defines: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Suggest completions for the word at the end of some expression text: parameters (by name,
|
||||
/// anywhere in it), functions, constants and units. Changes nothing.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExprCompleteParams {
|
||||
/// The text before the cursor; the word being typed is its trailing letters, digits and
|
||||
/// underscores. Default: empty, which lists every parameter, function and constant.
|
||||
#[serde(default, deserialize_with = "complete_prefix")]
|
||||
pub prefix: Option<String>,
|
||||
}
|
||||
|
||||
fn complete_prefix<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
text_or_null(d, "`prefix` must be text")
|
||||
}
|
||||
|
||||
/// What a completion is.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CompletionKind {
|
||||
Parameter,
|
||||
Function,
|
||||
Unit,
|
||||
Constant,
|
||||
}
|
||||
|
||||
/// One suggestion.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Completion {
|
||||
/// The text to insert: a parameter's name, a function's name and `(`, a constant or a unit.
|
||||
pub text: String,
|
||||
pub kind: CompletionKind,
|
||||
/// A parameter's expression and value, a function's signature, or a unit's kind.
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// What `parameters.complete` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExprCompletions {
|
||||
/// The word being completed; empty when the text ends in something else.
|
||||
pub word: String,
|
||||
/// Parameters first (names that start with the word, then the rest; favourites and user
|
||||
/// parameters first, at most 200), then functions, the constant `pi` and units.
|
||||
pub suggestions: Vec<Completion>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "parameters_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
ParamAddParams, ParamAdded, ParamCommentParams, ParamCommented, ParamDeleted, ParamFavoriteParams, ParamFavorited, ParamMoveParams, ParamMoved,
|
||||
ParamNameParams, ParamRenameParams, ParamRenamed,
|
||||
ExprCompleteParams, ExprCompletions, ExprEvaluateParams, ExprEvaluated, ParamAddParams, ParamAdded, ParamChangeParams, ParamChanged,
|
||||
ParamChangedBody, ParamCommentParams, ParamCommented, ParamDeleted, ParamExportParams, ParamExportResult, ParamFavoriteParams, ParamFavorited,
|
||||
ParamGraphParams, ParamGraphResult, ParamImportParams, ParamImportResult, ParamListParams, ParamListResult, ParamMoveParams, ParamMoved,
|
||||
ParamNameParams, ParamRenameParams, ParamRenamed, ParamUsersParams, ParamUsersResult, SwitchedFeature,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
@@ -16,6 +18,17 @@ fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<ParamCommentParams>(), &["comment", "name"]);
|
||||
assert_keys(input_schema_for::<ParamFavoriteParams>(), &["favorite", "name"]);
|
||||
assert_keys(input_schema_for::<ParamMoveParams>(), &["after", "before", "name"]);
|
||||
assert_keys(
|
||||
input_schema_for::<ParamChangeParams>(),
|
||||
&["changes", "comment", "delete", "expression", "favorite", "name", "new_name", "unit", "value"],
|
||||
);
|
||||
assert_keys(input_schema_for::<ParamListParams>(), &["favorites", "filter"]);
|
||||
assert_keys(input_schema_for::<ParamUsersParams>(), &["name"]);
|
||||
assert_keys(input_schema_for::<ParamGraphParams>(), &[]);
|
||||
assert_keys(input_schema_for::<ParamExportParams>(), &["format", "path"]);
|
||||
assert_keys(input_schema_for::<ParamImportParams>(), &["path", "text"]);
|
||||
assert_keys(input_schema_for::<ExprEvaluateParams>(), &["expression", "kind", "unit"]);
|
||||
assert_keys(input_schema_for::<ExprCompleteParams>(), &["prefix"]);
|
||||
}
|
||||
|
||||
/// The calls fail on a design without parameters, with the handlers' messages or the
|
||||
@@ -49,6 +62,39 @@ fn strict_keeps_todays_errors() {
|
||||
("parameters.move", json!({"name": "W", "before": "A", "after": "B"})),
|
||||
("parameters.move", json!({"name": "W", "before": 5})),
|
||||
("parameters.move", json!({"name": "Nope", "before": "A"})),
|
||||
("parameters.change", json!({})),
|
||||
("parameters.change", json!({"name": "W"})),
|
||||
("parameters.change", json!({"name": " ", "expression": 1})),
|
||||
("parameters.change", json!({"name": "W", "expression": true})),
|
||||
("parameters.change", json!({"name": "W", "expression": null})),
|
||||
("parameters.change", json!({"changes": null})),
|
||||
("parameters.change", json!({"changes": [1]})),
|
||||
("parameters.change", json!({"changes": {}})),
|
||||
("parameters.change", json!({"changes": {"W": true}})),
|
||||
("parameters.change", json!({"changes": {"W": [1]}, "name": "W", "expression": 2})),
|
||||
("parameters.change", json!({"changes": {"Nope": 1}})),
|
||||
("parameters.change", json!({"delete": "Nope"})),
|
||||
("parameters.change", json!({"delete": " "})),
|
||||
("parameters.change", json!({"name": "Nope", "favorite": true})),
|
||||
("parameters.change", json!({"name": "Nope", "new_name": "X"})),
|
||||
("parameters.users", json!({})),
|
||||
("parameters.users", json!({"name": 5})),
|
||||
("parameters.users", json!({"name": "Nope"})),
|
||||
("parameters.export", json!({"format": "xml"})),
|
||||
("parameters.export", json!({"format": "CSV", "path": "/nonexistent-dir/x/y.csv"})),
|
||||
("parameters.import", json!({})),
|
||||
("parameters.import", json!({"text": null, "path": null})),
|
||||
("parameters.import", json!({"text": 5})),
|
||||
("parameters.import", json!({"path": 5})),
|
||||
("parameters.import", json!({"text": "name,expression\n1W,1"})),
|
||||
("parameters.import", json!({"path": "/nonexistent-dir/x/y.csv"})),
|
||||
("expr.evaluate", json!({})),
|
||||
("expr.evaluate", json!({"expression": null})),
|
||||
("expr.evaluate", json!({"expression": true})),
|
||||
("expr.evaluate", json!({"expression": ["1"]})),
|
||||
("expr.evaluate", json!({"expression": "1", "unit": "furlong"})),
|
||||
("expr.evaluate", json!({"expression": "1", "kind": "colour"})),
|
||||
("expr.evaluate", json!({"expression": "1", "unit": "mm", "kind": "colour"})),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -144,3 +190,348 @@ fn parameter_edits_reply_with_their_schemas() {
|
||||
let error = warned.execute("parameters.favorite", &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("`favourite`"), "{error}");
|
||||
}
|
||||
|
||||
/// Whether the contract reports anything for the call, and what: the warnings of Warn.
|
||||
fn issues(id: &str, p: Value) -> Vec<String> {
|
||||
crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect()
|
||||
}
|
||||
|
||||
/// `parameters.change` reads `changes` alone when it is there, `delete` alone when that is text,
|
||||
/// else the keys of one change: a call that works today in any of the forms gets no warning for
|
||||
/// a key of a form it doesn't read, and each form has the handler's messages.
|
||||
#[test]
|
||||
fn change_reads_only_the_keys_of_the_form_it_is_in() {
|
||||
let none = Vec::<String>::new();
|
||||
// The keys of another form are not read: a wrong one is no problem.
|
||||
assert_eq!(
|
||||
issues("parameters.change", json!({"changes": {"W": 1, "H": "2 mm"}, "name": 5, "expression": true, "unit": 1, "favorite": "x"})),
|
||||
none
|
||||
);
|
||||
assert_eq!(issues("parameters.change", json!({"delete": "W", "name": 5, "expression": true, "favorite": "x", "unit": 3})), none);
|
||||
assert_eq!(issues("parameters.change", json!({"changes": {"W": 1}, "delete": 5})), none);
|
||||
// A `delete` that isn't text is read as left out: the single change form it falls to
|
||||
// reports it.
|
||||
assert_eq!(issues("parameters.change", json!({"delete": 5, "name": "W", "expression": 1})), ["`delete` must be text"]);
|
||||
assert_eq!(issues("parameters.change", json!({"delete": null, "name": "W", "expression": 1})), none);
|
||||
// The single change form.
|
||||
for p in [
|
||||
json!({"name": "W", "expression": 5}),
|
||||
json!({"name": " W ", "value": "2 mm", "unit": "mm", "comment": "c", "favorite": true}),
|
||||
json!({"name": "W", "new_name": "X"}),
|
||||
json!({"name": "W", "favorite": false}),
|
||||
json!({"name": "W", "comment": "x"}),
|
||||
json!({"name": "W", "expression": null, "value": 3}),
|
||||
json!({"name": "W", "favorite": null}),
|
||||
] {
|
||||
assert_eq!(issues("parameters.change", p.clone()), none, "{p}");
|
||||
}
|
||||
for (p, message) in [
|
||||
(json!({"name": 5, "expression": 1}), "`name` is required"),
|
||||
(json!({"name": null, "expression": 1}), "`name` is required"),
|
||||
(json!({"name": "W", "expression": true}), "`expression` must be a number or text"),
|
||||
(json!({"name": "W", "new_name": 5}), "`new_name` must be text"),
|
||||
(json!({"name": "W", "expression": 1, "unit": 5}), "`unit` must be text"),
|
||||
(json!({"name": "W", "expression": 1, "comment": 5}), "`comment` must be text"),
|
||||
(json!({"name": "W", "expression": 1, "favorite": "yes"}), "`favorite` must be true or false"),
|
||||
(json!({"changes": null}), "`changes` must be an object of name: expression"),
|
||||
(json!({"changes": ["W"]}), "`changes` must be an object of name: expression"),
|
||||
(json!({"changes": {}}), "`changes` is empty"),
|
||||
(json!({"changes": {"W": 1, "H": null}}), "`changes.H` must be a number or text"),
|
||||
] {
|
||||
assert_eq!(issues("parameters.change", p.clone()), [message], "{p}");
|
||||
}
|
||||
// `value` is read only when `expression` isn't a number or text.
|
||||
assert_eq!(issues("parameters.change", json!({"name": "W", "expression": "5", "value": true})), none);
|
||||
assert_eq!(issues("parameters.change", json!({"name": "W", "expression": null, "value": true})), ["`expression` must be a number or text"]);
|
||||
// A missing key is the handler's to refuse, with its own message.
|
||||
for p in [json!({}), json!({"name": "W"}), json!({"expression": 1})] {
|
||||
assert_eq!(issues("parameters.change", p.clone()), Vec::<String>::new(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `parameters.list` doesn't read `filter` when `favorites` is true; `parameters.import` doesn't
|
||||
/// read `path` when `text` is text; `expr.evaluate` doesn't read `kind` when `unit` is `text`.
|
||||
#[test]
|
||||
fn list_import_and_evaluate_read_keys_only_where_the_handlers_do() {
|
||||
let none = Vec::<String>::new();
|
||||
assert_eq!(issues("parameters.list", json!({"favorites": true, "filter": 5})), none);
|
||||
assert_eq!(issues("parameters.list", json!({"favorites": false, "filter": 5})), ["`filter` must be text"]);
|
||||
assert_eq!(issues("parameters.list", json!({"filter": ["user"]})), ["`filter` must be text"]);
|
||||
assert_eq!(issues("parameters.list", json!({"favorites": "yes"})), ["`favorites` must be true or false"]);
|
||||
assert_eq!(issues("parameters.list", json!({"filter": null, "favorites": null})), none);
|
||||
assert_eq!(issues("parameters.list", json!({"filter": "bogus"})), none);
|
||||
|
||||
assert_eq!(issues("parameters.import", json!({"text": "name,expression\nW,1", "path": 5})), none);
|
||||
assert_eq!(issues("parameters.import", json!({"text": "", "path": []})), none);
|
||||
assert_eq!(issues("parameters.import", json!({"path": "p.csv"})), none);
|
||||
assert_eq!(issues("parameters.import", json!({"text": null, "path": "p.csv"})), none);
|
||||
assert_eq!(issues("parameters.import", json!({"path": 5})), ["give `text` or `path`"]);
|
||||
assert_eq!(issues("parameters.import", json!({"text": 5})), ["give `text` or `path`"]);
|
||||
assert_eq!(issues("parameters.import", json!({"text": 5, "path": "p.csv"})), ["`text` must be text"]);
|
||||
|
||||
assert_eq!(issues("expr.evaluate", json!({"expression": "a b", "unit": "text", "kind": 5})), none);
|
||||
assert_eq!(issues("expr.evaluate", json!({"expression": "a b", "unit": " TEXT ", "kind": "bogus"})), none);
|
||||
assert_eq!(issues("expr.evaluate", json!({"expression": 5, "unit": "mm", "kind": 5})), ["`kind` must be text"]);
|
||||
assert_eq!(issues("expr.evaluate", json!({"expression": 5, "unit": 5})), ["`unit` must be text"]);
|
||||
assert_eq!(issues("expr.evaluate", json!({"expression": 5, "kind": "angle", "unit": null})), none);
|
||||
assert_eq!(issues("expr.evaluate", json!({"expression": 2.5})), none);
|
||||
assert_eq!(issues("expr.evaluate", json!({"expression": {}})), ["`expression` must be text or a number"]);
|
||||
assert_eq!(issues("parameters.complete", json!({"prefix": 5})), ["`prefix` must be text"]);
|
||||
assert_eq!(issues("parameters.complete", json!({"prefix": null})), none);
|
||||
assert_eq!(issues("parameters.export", json!({"format": "JSON", "path": "x.csv"})), none);
|
||||
assert_eq!(issues("parameters.users", json!({"name": " "})), ["`name` is required"]);
|
||||
assert_eq!(issues("parameters.graph", json!({"nodes": 1})), ["unknown key `nodes`"]);
|
||||
}
|
||||
|
||||
/// The schemas say which forms and keys the handlers need: `parameters.change`'s three forms,
|
||||
/// `parameters.import`'s `text` or `path`, `expr.evaluate`'s `expression`.
|
||||
#[test]
|
||||
fn the_new_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
takes(
|
||||
input_schema_for::<ParamChangeParams>(),
|
||||
&[
|
||||
(json!({"name": "W", "expression": "10 mm"}), true),
|
||||
(json!({"name": "W", "new_name": "X"}), true),
|
||||
(json!({"name": "W", "favorite": true}), true),
|
||||
(json!({"changes": {"W": 1}}), true),
|
||||
(json!({"delete": "W"}), true),
|
||||
(json!({}), false),
|
||||
(json!({"name": "W"}), false),
|
||||
(json!({"expression": 1}), false),
|
||||
(json!({"delete": 5}), false),
|
||||
(json!({"name": "W", "expression": true}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ParamImportParams>(),
|
||||
&[(json!({"text": "x"}), true), (json!({"path": "p.csv"}), true), (json!({}), false), (json!({"text": 5}), false)],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ExprEvaluateParams>(),
|
||||
&[
|
||||
(json!({"expression": "1 + 2"}), true),
|
||||
(json!({"expression": 3, "unit": "mm", "kind": "length"}), true),
|
||||
(json!({}), false),
|
||||
(json!({"expression": true}), false),
|
||||
],
|
||||
);
|
||||
takes(input_schema_for::<ParamUsersParams>(), &[(json!({"name": "W"}), true), (json!({}), false), (json!({"name": ""}), false)]);
|
||||
takes(
|
||||
input_schema_for::<ParamListParams>(),
|
||||
&[(json!({}), true), (json!({"favorites": true, "filter": "user"}), true), (json!({"favorites": "x"}), false)],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ParamExportParams>(),
|
||||
&[(json!({}), true), (json!({"format": "json", "path": "p.json"}), true), (json!({"path": 1}), false)],
|
||||
);
|
||||
takes(input_schema_for::<ExprCompleteParams>(), &[(json!({}), true), (json!({"prefix": "si"}), true), (json!({"prefix": 1}), false)]);
|
||||
// `conforms` doesn't read nested `anyOf` inside a branch's `properties`; the forms are pinned.
|
||||
let change = input_schema_for::<ParamChangeParams>();
|
||||
assert_eq!(
|
||||
change.as_value()["anyOf"],
|
||||
json!([
|
||||
{"required": ["changes"]},
|
||||
{"required": ["delete"], "properties": {"delete": {"type": "string"}}},
|
||||
{
|
||||
"required": ["name"],
|
||||
"properties": {"name": {"type": "string"}},
|
||||
"anyOf": [
|
||||
{"required": ["expression"], "properties": {"expression": {"type": ["number", "string"]}}},
|
||||
{"required": ["value"], "properties": {"value": {"type": ["number", "string"]}}},
|
||||
{"required": ["new_name"]},
|
||||
{"required": ["favorite"]},
|
||||
{"required": ["comment"]}
|
||||
]
|
||||
}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, id: &str, reply: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
|
||||
assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");
|
||||
}
|
||||
|
||||
/// #12497: every command of the group, run in every form in Warn, replies as its output schema
|
||||
/// says and without warnings (Warn runs a call the contract refuses anyway, so the absence of
|
||||
/// `param_warnings` is what shows the contract accepts the call).
|
||||
#[test]
|
||||
fn the_parameter_commands_reply_with_their_schemas() {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-params-schema-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}"));
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
run("parameters.add", json!({"name": "W", "expression": "10 mm", "favorite": true}));
|
||||
run("parameters.add", json!({"name": "H", "expression": 5, "unit": "mm"}));
|
||||
run("parameters.add", json!({"name": "Label", "expression": "Rev A", "unit": "text"}));
|
||||
run("solid.box", json!({"length": "W", "width": "H * 2", "height": 4, "body_name": "Block"}));
|
||||
|
||||
// Change: one parameter in each of its forms, several at once, a delete.
|
||||
let r = run("parameters.change", json!({"name": "W", "expression": "12 mm", "comment": "wall"}));
|
||||
assert!(r["value"] == 12.0 && r["expression"] == "12 mm" && r.get("renamed").is_none(), "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
let r = run("parameters.change", json!({"name": "W", "value": 14, "unit": "mm", "favorite": false}));
|
||||
assert_eq!(r["value"], 14.0, "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
let r = run("parameters.change", json!({"name": "W", "new_name": "Wall"}));
|
||||
assert!(r["renamed"]["from"] == "W" && r["renamed"]["to"] == "Wall" && r["expression"].is_null(), "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
let r = run("parameters.change", json!({"name": "Wall", "comment": "thin", "favorite": true}));
|
||||
assert!(r["expression"].is_null() && r["name"] == "Wall", "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
let r = run("parameters.change", json!({"name": "Wall", "expression": "Wide = 16"}));
|
||||
assert!(r["renamed"]["to"] == "Wide" && r["name"] == "Wide", "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
let r = run("parameters.change", json!({"name": "Label", "expression": "Rev B"}));
|
||||
assert_eq!(r["text"], "Rev B", "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
let r = run("parameters.change", json!({"changes": {"Wide": 20, "H": "6 mm"}}));
|
||||
assert!(r["changed"]["Wide"] == 20.0 && r["changed"]["H"] == 6.0, "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
// The other forms' keys are not read, so a bad one doesn't warn.
|
||||
let r = run("parameters.change", json!({"changes": {"H": 7}, "name": 5, "expression": true}));
|
||||
assert_eq!(r["changed"]["H"], 7.0, "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
run("parameters.add", json!({"name": "Spare", "expression": 1}));
|
||||
let r = run("parameters.change", json!({"delete": " Spare ", "name": 5}));
|
||||
assert_eq!(r["deleted"], "Spare", "{r}");
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);
|
||||
|
||||
// List: all forms of the filter, favourites first.
|
||||
let all = run("parameters.list", json!({}));
|
||||
assert_eq!(all["count"], all["parameters"].as_array().map_or(0, Vec::len), "{all}");
|
||||
matches(output_schema_for::<ParamListResult>(), "parameters.list", &all);
|
||||
for p in [
|
||||
json!({"favorites": true}),
|
||||
json!({"favorites": true, "filter": 5}),
|
||||
json!({"filter": "USER"}),
|
||||
json!({"filter": "feature"}),
|
||||
json!({"filter": "sketch"}),
|
||||
json!({"filter": "model"}),
|
||||
json!({"filter": "bogus"}),
|
||||
] {
|
||||
let r = run("parameters.list", p);
|
||||
matches(output_schema_for::<ParamListResult>(), "parameters.list", &r);
|
||||
}
|
||||
let favorites = run("parameters.list", json!({"favorites": true}));
|
||||
assert!(favorites["parameters"].as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|r| r["favorite"] == true)), "{favorites}");
|
||||
let feature = run("parameters.list", json!({"filter": "feature"}));
|
||||
assert!(feature["parameters"].as_array().is_some_and(|a| a.iter().all(|r| r["source"] == "feature")), "{feature}");
|
||||
|
||||
// Users and graph.
|
||||
let users = run("parameters.users", json!({"name": " H "}));
|
||||
assert_eq!(users["name"], "H", "{users}");
|
||||
assert!(users["users"].as_array().is_some_and(|u| !u.is_empty()) && users["drives"][0]["name"] == "Box1", "{users}");
|
||||
matches(output_schema_for::<ParamUsersResult>(), "parameters.users", &users);
|
||||
let graph = run("parameters.graph", json!({}));
|
||||
assert!(graph["nodes"].as_array().is_some_and(|n| n.contains(&json!("H"))), "{graph}");
|
||||
matches(output_schema_for::<ParamGraphResult>(), "parameters.graph", &graph);
|
||||
|
||||
// Export in both formats, to text and to a file; import them back.
|
||||
let csv = run("parameters.export", json!({}));
|
||||
assert!(csv["format"] == "csv" && csv["path"].is_null(), "{csv}");
|
||||
matches(output_schema_for::<ParamExportResult>(), "parameters.export", &csv);
|
||||
let json_text = run("parameters.export", json!({"format": "JSON"}));
|
||||
assert_eq!(json_text["format"], "json", "{json_text}");
|
||||
matches(output_schema_for::<ParamExportResult>(), "parameters.export", &json_text);
|
||||
let file = dir.join("parameters.json");
|
||||
let written = run("parameters.export", json!({"path": file}));
|
||||
assert!(written["format"] == "json" && written["path"].is_string(), "{written}");
|
||||
matches(output_schema_for::<ParamExportResult>(), "parameters.export", &written);
|
||||
let mut other = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let imported = other.execute("parameters.import", &json!({"path": file})).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(imported["imported"].as_array().is_some_and(|n| n.len() == 3), "{imported}");
|
||||
matches(output_schema_for::<ParamImportResult>(), "parameters.import", &imported);
|
||||
let from_text = other.execute("parameters.import", &json!({"text": "name,expression\nZ,3", "path": 5})).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(from_text["imported"], json!(["Z"]), "{from_text}");
|
||||
matches(output_schema_for::<ParamImportResult>(), "parameters.import", &from_text);
|
||||
|
||||
// Evaluate: a length, an angle, a unitless number, a definition, an error, a text.
|
||||
for p in [
|
||||
json!({"expression": "H * 2"}),
|
||||
json!({"expression": 3, "unit": "in"}),
|
||||
json!({"expression": "90 deg"}),
|
||||
json!({"expression": "30", "unit": "deg"}),
|
||||
json!({"expression": "2 * 3", "kind": "unitless"}),
|
||||
json!({"expression": "Wide", "kind": "length"}),
|
||||
json!({"expression": "len = 3 mm"}),
|
||||
json!({"expression": "nope + 1"}),
|
||||
json!({"expression": "Rev \"A\"", "unit": "text", "kind": 5}),
|
||||
] {
|
||||
let r = run("expr.evaluate", p.clone());
|
||||
matches(output_schema_for::<ExprEvaluated>(), "expr.evaluate", &r);
|
||||
assert_eq!(r["ok"], !p["expression"].as_str().is_some_and(|e| e.starts_with("nope")), "{r}");
|
||||
}
|
||||
let r = run("expr.evaluate", json!({"expression": "len = 3 mm"}));
|
||||
assert!(r["defines"] == "len" && r["kind"] == "length" && r["value"] == 3.0, "{r}");
|
||||
let r = run("expr.evaluate", json!({"expression": "'Rev A'", "unit": "text"}));
|
||||
assert!(r["kind"] == "text" && r["text"] == "Rev A" && r["references"] == json!([]), "{r}");
|
||||
let r = run("expr.evaluate", json!({"expression": "nope + 1"}));
|
||||
assert!(r["ok"] == false && r["error"].is_string() && r["references"] == json!(["nope"]), "{r}");
|
||||
|
||||
// Complete: parameters, functions, constants, units.
|
||||
for p in
|
||||
[json!({}), json!({"prefix": "H"}), json!({"prefix": "2 * si"}), json!({"prefix": "p"}), json!({"prefix": "3 m"}), json!({"prefix": null})]
|
||||
{
|
||||
let r = run("parameters.complete", p);
|
||||
matches(output_schema_for::<ExprCompletions>(), "parameters.complete", &r);
|
||||
}
|
||||
let r = run("parameters.complete", json!({"prefix": "3 m"}));
|
||||
assert!(r["suggestions"].as_array().is_some_and(|a| a.iter().any(|c| c["kind"] == "unit" && c["detail"] == "length")), "{r}");
|
||||
let r = run("parameters.complete", json!({"prefix": "p"}));
|
||||
assert!(r["suggestions"].as_array().is_some_and(|a| a.iter().any(|c| c["kind"] == "constant")), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A misspelt key runs in Warn and is reported, with a reply that still matches; strict refuses
|
||||
/// it. Each command of the group.
|
||||
#[test]
|
||||
fn a_misspelt_key_is_reported_for_each_command() {
|
||||
let calls = [
|
||||
("parameters.change", json!({"name": "W", "comment": "c", "favorit": true}), "favorit"),
|
||||
("parameters.list", json!({"favourites": true}), "favourites"),
|
||||
("parameters.users", json!({"name": "W", "nam": 1}), "nam"),
|
||||
("parameters.graph", json!({"node": 1}), "node"),
|
||||
("parameters.export", json!({"formt": "csv"}), "formt"),
|
||||
("parameters.import", json!({"text": "name,expression\nQ,1", "pth": "x"}), "pth"),
|
||||
("expr.evaluate", json!({"expression": "1", "unt": "mm"}), "unt"),
|
||||
("parameters.complete", json!({"prefx": "W"}), "prefx"),
|
||||
];
|
||||
for (id, p, key) in calls {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
s.execute("parameters.add", &json!({"name": "W", "expression": "10 mm"})).unwrap_or_else(|e| panic!("{e}"));
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert!(r["param_warnings"].to_string().contains(key), "{id}: {r}");
|
||||
let schema = crate::cmd::find_command(id).and_then(|c| c.output).map(|f| f()).unwrap_or_else(|| panic!("{id} has no output schema"));
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &r), "{id}: {r} doesn't match {}", schema.as_value());
|
||||
s.param_check = ParamCheck::Strict;
|
||||
let error = s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains(&format!("`{key}`")), "{id}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A configuration rule's switch has the shape the schema describes.
|
||||
#[test]
|
||||
fn a_switched_feature_serializes_as_the_schema_says() {
|
||||
let body = ParamChangedBody::Many {
|
||||
changed: [("W".to_string(), Some(1.0))].into(),
|
||||
recomputed: 2,
|
||||
restored: 0,
|
||||
errors: Vec::new(),
|
||||
switched: vec![SwitchedFeature { feature: 3, name: Some("Hole".into()), suppressed: true }],
|
||||
};
|
||||
let reply = serde_json::to_value(ParamChanged { body, param_warnings: Vec::new() }).unwrap_or_default();
|
||||
assert_eq!(
|
||||
reply,
|
||||
json!({"changed": {"W": 1.0}, "recomputed": 2, "restored": 0, "errors": [], "switched": [{"feature": 3, "name": "Hole", "suppressed": true}]})
|
||||
);
|
||||
matches(output_schema_for::<ParamChanged>(), "parameters.change", &reply);
|
||||
}
|
||||
|
||||
@@ -338,8 +338,8 @@ pub struct Constrained {
|
||||
pub determined_by: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// What `sketch.constraint.horizontal_vertical`, `tangent`, `parallel`, `perpendicular`,
|
||||
/// `collinear`, `concentric` and `midpoint` return.
|
||||
/// What `sketch.constraint.horizontal_vertical`, `parallel`, `perpendicular`, `collinear`,
|
||||
/// `concentric` and `midpoint` return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ConstraintResult {
|
||||
#[serde(flatten)]
|
||||
@@ -349,6 +349,35 @@ pub struct ConstraintResult {
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.constraint.tangent` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct TangentResult {
|
||||
#[serde(flatten)]
|
||||
pub made: TangentMade,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What a Tangent call added.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum TangentMade {
|
||||
/// Two curves: one Tangent constraint.
|
||||
Curves(Constrained),
|
||||
/// A curve's end point for `a` or `b` (#12092): the end now lies on the other curve (a
|
||||
/// point-on-curve or, for two end points, a coincident constraint, left out when the end was
|
||||
/// already there) and its curve is tangent there.
|
||||
End {
|
||||
/// The Tangent constraint.
|
||||
constraint: String,
|
||||
/// Every constraint added, the Tangent last.
|
||||
constraints: Vec<String>,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
sketch: Value,
|
||||
},
|
||||
}
|
||||
|
||||
/// What `sketch.constraint.coincident` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct CoincidentResult {
|
||||
@@ -493,10 +522,11 @@ macro_rules! two_operands {
|
||||
}
|
||||
|
||||
two_operands! {
|
||||
/// Make two curves, or a curve and a sketch axis, tangent. Two different curves are needed.
|
||||
/// Make two curves, a curve and a sketch axis, or a curve's end point and another curve,
|
||||
/// tangent. Two different curves are needed.
|
||||
TangentParams,
|
||||
a: "A curve's id, or `x` / `y` for the sketch's own axis (a curve with that id wins; an axis becomes a linked construction line, reported in `created`), or a model edge.",
|
||||
b: "The other curve, as `a`.",
|
||||
a: "A curve's id, or `x` / `y` for the sketch's own axis (a curve with that id wins; an axis becomes a linked construction line, reported in `created`), or a model edge, or the end point of a line or an arc (such as `l1.end`): that end then lies on the other curve, and its curve is tangent there (`constraints` lists both).",
|
||||
b: "The other curve or end point, as `a`.",
|
||||
what: "a curve id, or x / y for a sketch axis"
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
//! Contracts and result types for the commands in `cmd/sketch_3d.rs`: `sketch.line3d`,
|
||||
//! `sketch.spline3d`, `sketch.point3d` and `sketch.move3d`.
|
||||
//!
|
||||
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
//! reads it and fails with the handler's message. Whether the sketch has 3D Sketch on, a wire
|
||||
//! exists or a point is in range stays the handler's to check, as does `move3d` being given
|
||||
//! neither `to` nor `by`. A call with several problems may get a different one first in strict
|
||||
//! than with the check off (the check goes key by key, the handlers in their own order).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec3;
|
||||
|
||||
use super::check::whole;
|
||||
use super::motion::require;
|
||||
use super::sketch_ends::SketchTarget;
|
||||
use super::types::Point3;
|
||||
use crate::params;
|
||||
|
||||
/// Draw 3D lines through world points, one line per segment, joined end to end. Needs 3D Sketch
|
||||
/// on for the sketch (`sketch.options` with `sketch_3d: true`). One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = points_required)]
|
||||
pub struct Line3dParams {
|
||||
// Optional in the type and required in the schema (`points_required`): left out, the handler
|
||||
// refuses it with its own message, not the check's "is required".
|
||||
/// The world points [x, y, z] in mm, 2 to 500: one line per segment between neighbours.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "DrawnPoints")]
|
||||
pub points: Option<DrawnPoints>,
|
||||
/// The sketch to draw in: its feature id or its name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// Draw a smooth 3D curve through world fit points. Needs 3D Sketch on for the sketch
|
||||
/// (`sketch.options` with `sketch_3d: true`). One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = points_required)]
|
||||
pub struct Spline3dParams {
|
||||
// Optional in the type and required in the schema, as `Line3dParams::points`.
|
||||
/// The world fit points [x, y, z] in mm, 2 to 500, which the curve passes through.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "DrawnPoints")]
|
||||
pub points: Option<DrawnPoints>,
|
||||
/// The sketch to draw in: its feature id or its name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// Draw a 3D point at a world point. Needs 3D Sketch on for the sketch (`sketch.options` with
|
||||
/// `sketch_3d: true`). One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = point_required)]
|
||||
pub struct Point3dParams {
|
||||
// Optional in the type and required in the schema, as `Line3dParams::points`.
|
||||
/// The world point [x, y, z] in mm.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "WorldPoint")]
|
||||
pub point: Option<WorldPoint>,
|
||||
/// The sketch to draw in: its feature id or its name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// Move one fit point of a drawn 3D curve or point, to a world point or by a world offset. The
|
||||
/// points joined to it move too. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = move_required)]
|
||||
pub struct Move3dParams {
|
||||
// Optional in the type and required in the schema, as `Line3dParams::points`.
|
||||
/// The drawn 3D curve or point to move, by id.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "WireId")]
|
||||
pub wire: Option<WireId>,
|
||||
/// Which fit point of the curve (0 is the first), below 500. Default: 0.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "FitIndex")]
|
||||
pub index: Option<FitIndex>,
|
||||
/// Where the fit point goes, as a world point [x, y, z] in mm. Wins over `by`. The schema
|
||||
/// requires `to` or `by`; the handler refuses a call with neither.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "MoveTarget")]
|
||||
pub to: Option<MoveTarget>,
|
||||
/// How far the fit point moves, as a world offset [dx, dy, dz] in mm. Used when `to` is not
|
||||
/// given.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "MoveTarget")]
|
||||
pub by: Option<MoveTarget>,
|
||||
/// The sketch the curve is in: its feature id or its name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// A key that, once given (`null` included), must parse as `T`, as the handlers read it.
|
||||
fn some<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {
|
||||
T::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
fn points_required(schema: &mut Schema) {
|
||||
require(schema, "points");
|
||||
}
|
||||
|
||||
fn point_required(schema: &mut Schema) {
|
||||
require(schema, "point");
|
||||
}
|
||||
|
||||
fn move_required(schema: &mut Schema) {
|
||||
require(schema, "wire");
|
||||
schema.insert("anyOf".into(), json!([{"required": ["to"]}, {"required": ["by"]}]));
|
||||
}
|
||||
|
||||
/// The `points` of `sketch.line3d` and `sketch.spline3d`: a list of 2 to 500 points, as their
|
||||
/// `points` reader takes it, with its messages.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DrawnPoints(pub Vec<Vec3>);
|
||||
|
||||
impl<'de> Deserialize<'de> for DrawnPoints {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let max = solidcraft_sketch::MAX_FIT_POINTS;
|
||||
let Value::Array(a) = Value::deserialize(d)? else {
|
||||
return Err(D::Error::custom(whole("`points` must list [x,y,z] points")));
|
||||
};
|
||||
if a.len() < 2 || a.len() > max {
|
||||
return Err(D::Error::custom(whole(format!("`points` needs 2 to {max} points"))));
|
||||
}
|
||||
a.iter()
|
||||
.map(|v| params::vec3(v).ok_or_else(|| D::Error::custom(whole("a point must be [x, y, z]"))))
|
||||
.collect::<Result<_, _>>()
|
||||
.map(DrawnPoints)
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for DrawnPoints {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"DrawnPoints".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let point = generator.subschema_for::<Point3>();
|
||||
json_schema!({
|
||||
"description": "World points [x, y, z] in mm, 2 to 500.",
|
||||
"type": "array",
|
||||
"items": point,
|
||||
"minItems": 2,
|
||||
"maxItems": solidcraft_sketch::MAX_FIT_POINTS
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The `point` of `sketch.point3d`: a [`Point3`], with the handler's message.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct WorldPoint(pub Vec3);
|
||||
|
||||
impl<'de> Deserialize<'de> for WorldPoint {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::vec3(&Value::deserialize(d)?).map(WorldPoint).ok_or_else(|| D::Error::custom("must be a point [x, y, z]"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for WorldPoint {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"WorldPoint".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<Point3>()
|
||||
}
|
||||
}
|
||||
|
||||
/// The `to` and `by` of `sketch.move3d`: a [`Point3`], with the handler's message.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MoveTarget(pub Vec3);
|
||||
|
||||
impl<'de> Deserialize<'de> for MoveTarget {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::vec3(&Value::deserialize(d)?).map(MoveTarget).ok_or_else(|| D::Error::custom("must be [x,y,z]"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for MoveTarget {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"MoveTarget".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<Point3>()
|
||||
}
|
||||
}
|
||||
|
||||
/// The `wire` of `sketch.move3d`: text, as the handler reads it. Whether a drawn curve or point
|
||||
/// has that id is the handler's to check.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WireId(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for WireId {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(WireId(s)),
|
||||
_ => Err(D::Error::custom("must be a 3D curve or point id")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for WireId {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"WireId".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": "string"})
|
||||
}
|
||||
}
|
||||
|
||||
/// The `index` of `sketch.move3d`: a whole number below 500, as the handler reads it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FitIndex(pub usize);
|
||||
|
||||
impl<'de> Deserialize<'de> for FitIndex {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
Value::deserialize(d)?
|
||||
.as_u64()
|
||||
.and_then(|v| usize::try_from(v).ok())
|
||||
.filter(|v| *v < solidcraft_sketch::MAX_FIT_POINTS)
|
||||
.map(FitIndex)
|
||||
.ok_or_else(|| D::Error::custom("must be a fit point index below 500"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for FitIndex {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"FitIndex".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": "integer", "minimum": 0, "maximum": solidcraft_sketch::MAX_FIT_POINTS - 1})
|
||||
}
|
||||
}
|
||||
|
||||
/// What `sketch.line3d` and `sketch.spline3d` return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Curves3dResult {
|
||||
/// The ids of the curves drawn: one per segment for a line, one for a spline.
|
||||
pub curves: Vec<String>,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.point3d` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Point3dResult {
|
||||
/// The id of the point drawn.
|
||||
pub point: String,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.move3d` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Move3dResult {
|
||||
/// How many fit points moved: the one asked for and the points joined to it.
|
||||
pub moved: usize,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_3d_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,241 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{Curves3dResult, Line3dParams, Move3dParams, Move3dResult, Point3dParams, Point3dResult, Spline3dParams};
|
||||
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::<Line3dParams>(), &["points", "sketch"]);
|
||||
assert_keys(input_schema_for::<Spline3dParams>(), &["points", "sketch"]);
|
||||
assert_keys(input_schema_for::<Point3dParams>(), &["point", "sketch"]);
|
||||
assert_keys(input_schema_for::<Move3dParams>(), &["by", "index", "sketch", "to", "wire"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
let many: Vec<Value> = (0..501).map(|i| json!([i, 0, 0])).collect();
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("sketch.line3d", json!({})),
|
||||
("sketch.line3d", json!({"points": null})),
|
||||
("sketch.line3d", json!({"points": "x"})),
|
||||
("sketch.line3d", json!({"points": {"0": [0, 0, 0]}})),
|
||||
("sketch.line3d", json!({"points": []})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0]]})),
|
||||
("sketch.line3d", json!({"points": many})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [1, 2]]})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], "a"]})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1]], "sketch": true})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1]], "sketch": -1})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1]], "sketch": 1.5})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1]], "sketch": [1]})),
|
||||
("sketch.spline3d", json!({})),
|
||||
("sketch.spline3d", json!({"points": [[0, 0, 0]]})),
|
||||
("sketch.spline3d", json!({"points": 5})),
|
||||
("sketch.spline3d", json!({"points": [[0, 0, 0], [1, 1]]})),
|
||||
("sketch.point3d", json!({})),
|
||||
("sketch.point3d", json!({"point": null})),
|
||||
("sketch.point3d", json!({"point": [1, 2]})),
|
||||
("sketch.point3d", json!({"point": "1,2,3"})),
|
||||
("sketch.point3d", json!({"point": [1, 2, 3], "sketch": {}})),
|
||||
("sketch.move3d", json!({})),
|
||||
("sketch.move3d", json!({"wire": 3, "to": [0, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": null, "to": [0, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": "w1", "index": -1, "to": [0, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": "w1", "index": 500, "to": [0, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": "w1", "index": 1.5, "to": [0, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": "w1", "index": "1", "to": [0, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": "w1", "index": null, "to": [0, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": "w1", "to": [0, 0]})),
|
||||
("sketch.move3d", json!({"wire": "w1", "to": null})),
|
||||
("sketch.move3d", json!({"wire": "w1", "by": "up"})),
|
||||
("sketch.move3d", json!({"wire": "w1", "by": null})),
|
||||
("sketch.move3d", json!({"wire": "w1", "to": [0, 0, 0], "by": [1]})),
|
||||
("sketch.move3d", json!({"wire": "w1", "to": [0, 0, 0], "sketch": true})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// A session with a 3D sketch being edited, and the ids of a drawn line's curves.
|
||||
fn three_d(level: ParamCheck) -> (Session, Vec<String>) {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
for (id, p) in [("sketch.create", json!({"plane": "XY", "name": "Path"})), ("sketch.options", json!({"sketch_3d": true}))] {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
}
|
||||
let drawn = s.execute("sketch.line3d", &json!({"points": [[0, 0, 0], [0, 0, 10], [10, 0, 10]]})).unwrap_or_else(|e| panic!("{e}"));
|
||||
let ids = drawn["curves"].as_array().into_iter().flatten().filter_map(|c| c.as_str().map(String::from)).collect();
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
/// Calls the handlers take today (every form of each key, `null` for `sketch`) get no issue from
|
||||
/// the contracts; calls they refuse are refused by strict with the same message.
|
||||
#[test]
|
||||
fn the_types_read_each_key_as_the_handlers_do() {
|
||||
let (_, ids) = three_d(ParamCheck::Off);
|
||||
let wire = ids[0].clone();
|
||||
let cases = [
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]]})),
|
||||
("sketch.line3d", json!({"points": [{"x": 0, "y": 0, "z": 0}, [1, 1, 1], [2, 2, 2]], "sketch": null})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": "Path"})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": 9999})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": "no such sketch"})),
|
||||
("sketch.line3d", json!({"points": [[0, 0, 0], [1e9, 1, 1]]})),
|
||||
("sketch.line3d", json!({"points": (0..500).map(|i| json!([i, 0, 0])).collect::<Vec<_>>()})),
|
||||
("sketch.spline3d", json!({"points": [[0, 0, 0], [1, 1, 1], [2, 0, 3]]})),
|
||||
("sketch.spline3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": null})),
|
||||
("sketch.point3d", json!({"point": [3, 4, 5]})),
|
||||
("sketch.point3d", json!({"point": {"x": 3, "y": 4, "z": 5}, "sketch": "Path"})),
|
||||
("sketch.move3d", json!({"wire": wire, "to": [1, 2, 3]})),
|
||||
("sketch.move3d", json!({"wire": wire, "index": 1, "by": [1, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": wire, "index": 0, "to": [1, 2, 3], "by": [1, 0, 0]})),
|
||||
("sketch.move3d", json!({"wire": wire, "by": {"x": 1, "y": 0, "z": 0}, "sketch": null})),
|
||||
("sketch.move3d", json!({"wire": wire, "by": [1, 0, 0], "to": null})),
|
||||
("sketch.move3d", json!({"wire": wire})),
|
||||
("sketch.move3d", json!({"wire": "no such wire", "to": [1, 2, 3]})),
|
||||
("sketch.move3d", json!({"wire": wire, "index": 7, "to": [1, 2, 3]})),
|
||||
];
|
||||
for (id, p) in cases {
|
||||
let (mut off, _) = three_d(ParamCheck::Off);
|
||||
let (mut strict, _) = three_d(ParamCheck::Strict);
|
||||
let (mut warn, _) = three_d(ParamCheck::Warn);
|
||||
let today = off.execute(id, &p).map_err(|e| e.to_string());
|
||||
let checked = strict.execute(id, &p).map_err(|e| e.to_string());
|
||||
let warned = warn.execute(id, &p);
|
||||
let issues: Vec<_> = crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect();
|
||||
match &today {
|
||||
// A refusal the handler gives about the document (no such sketch, wire or point).
|
||||
Err(e) if issues.is_empty() => {
|
||||
let document = ["no sketch", "is not an editable drawn 3D curve", "has no drawn point", "give `to` or `by`"];
|
||||
assert!(document.iter().any(|m| e.contains(m)), "{id} {p}: refused for another reason: {e}");
|
||||
assert_eq!(checked.as_ref().err(), Some(e), "{id} {p}");
|
||||
assert!(warned.is_err(), "{id} {p}");
|
||||
}
|
||||
Err(e) => assert_eq!(checked.as_ref().err(), Some(e), "{id} {p}: {issues:?}"),
|
||||
Ok(reply) => {
|
||||
assert!(issues.is_empty(), "{id} {p}: {issues:?}");
|
||||
assert_eq!(checked.as_ref().ok(), Some(reply), "{id} {p}");
|
||||
assert_eq!(warned.ok().as_ref(), Some(reply), "{id} {p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The schemas say what the handlers need: the keys they refuse without are required, `to` or
|
||||
/// `by` is needed, and a point is `[x, y, z]` or `{x, y, z}`.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
let two = json!([[0, 0, 0], [1, 1, 1]]);
|
||||
for schema in [input_schema_for::<Line3dParams>(), input_schema_for::<Spline3dParams>()] {
|
||||
takes(
|
||||
schema,
|
||||
&[
|
||||
(json!({"points": two}), true),
|
||||
(json!({"points": [{"x": 0, "y": 0, "z": 0}, [1, 1, 1]], "sketch": "Path"}), true),
|
||||
(json!({"points": two, "sketch": 4}), true),
|
||||
(json!({}), false),
|
||||
(json!({"points": [[0, 0, 0]]}), false),
|
||||
(json!({"points": [[0, 0, 0], [1, 1]]}), false),
|
||||
(json!({"points": two, "sketch": true}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
takes(
|
||||
input_schema_for::<Point3dParams>(),
|
||||
&[
|
||||
(json!({"point": [1, 2, 3]}), true),
|
||||
(json!({"point": {"x": 1, "y": 2, "z": 3}}), true),
|
||||
(json!({}), false),
|
||||
(json!({"point": [1, 2]}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<Move3dParams>(),
|
||||
&[
|
||||
(json!({"wire": "w1", "to": [1, 2, 3]}), true),
|
||||
(json!({"wire": "w1", "by": [1, 2, 3], "index": 499}), true),
|
||||
(json!({"wire": "w1", "to": [1, 2, 3], "by": [1, 2, 3], "sketch": "Path"}), true),
|
||||
(json!({"to": [1, 2, 3]}), false),
|
||||
(json!({"wire": "w1"}), false),
|
||||
(json!({"wire": "w1", "to": [1, 2, 3], "index": 500}), false),
|
||||
(json!({"wire": "w1", "to": [1, 2, 3], "index": -1}), false),
|
||||
(json!({"wire": 3, "to": [1, 2, 3]}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, id: &str, reply: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
|
||||
assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");
|
||||
}
|
||||
|
||||
/// Each command, in Warn: the real reply matches its output schema and carries no warning.
|
||||
#[test]
|
||||
fn replies_match_the_output_schema() {
|
||||
let (mut s, _) = three_d(ParamCheck::Warn);
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let line = run("sketch.line3d", json!({"points": [[0, 5, 0], [0, 5, 10], [10, 5, 10]]}));
|
||||
assert_eq!(line["curves"].as_array().map(Vec::len), Some(2), "{line}");
|
||||
matches(output_schema_for::<Curves3dResult>(), "sketch.line3d", &line);
|
||||
let by_name = run("sketch.line3d", json!({"points": [[0, 6, 0], [0, 6, 10]], "sketch": "Path"}));
|
||||
matches(output_schema_for::<Curves3dResult>(), "sketch.line3d", &by_name);
|
||||
let spline = run("sketch.spline3d", json!({"points": [[0, 8, 0], [5, 9, 5], [10, 8, 10]]}));
|
||||
assert_eq!(spline["curves"].as_array().map(Vec::len), Some(1), "{spline}");
|
||||
matches(output_schema_for::<Curves3dResult>(), "sketch.spline3d", &spline);
|
||||
let point = run("sketch.point3d", json!({"point": {"x": 3, "y": 4, "z": 5}}));
|
||||
assert!(point["point"].is_string(), "{point}");
|
||||
matches(output_schema_for::<Point3dResult>(), "sketch.point3d", &point);
|
||||
let curve = line["curves"][0].clone();
|
||||
for p in [
|
||||
json!({"wire": curve, "index": 1, "by": [0, 0, 5]}),
|
||||
json!({"wire": curve, "to": [1, 5, 1]}),
|
||||
json!({"wire": point["point"], "to": [3, 4, 6], "by": [9, 9, 9]}),
|
||||
] {
|
||||
let moved = run("sketch.move3d", p);
|
||||
assert!(moved["moved"].as_u64().is_some_and(|n| n >= 1), "{moved}");
|
||||
matches(output_schema_for::<Move3dResult>(), "sketch.move3d", &moved);
|
||||
}
|
||||
}
|
||||
|
||||
/// A misspelt key still runs in Warn, and says so, with a reply that still matches.
|
||||
#[test]
|
||||
fn a_misspelt_key_is_reported_in_warn() {
|
||||
let (mut s, ids) = three_d(ParamCheck::Warn);
|
||||
let calls = [
|
||||
("sketch.line3d", json!({"points": [[0, 5, 0], [0, 5, 10]], "skech": "Path"})),
|
||||
("sketch.spline3d", json!({"points": [[0, 5, 0], [0, 5, 10]], "skech": "Path"})),
|
||||
("sketch.point3d", json!({"point": [1, 2, 3], "pont": [1, 2, 3]})),
|
||||
("sketch.move3d", json!({"wire": ids[0], "to": [1, 2, 3], "inex": 1})),
|
||||
];
|
||||
for (id, p) in calls {
|
||||
let reply = s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
let warnings = reply["param_warnings"].as_array().cloned().unwrap_or_default();
|
||||
assert!(warnings.len() == 1 && warnings[0].as_str().is_some_and(|w| w.contains("unknown key")), "{id}: {reply}");
|
||||
let schema = match id {
|
||||
"sketch.point3d" => output_schema_for::<Point3dResult>(),
|
||||
"sketch.move3d" => output_schema_for::<Move3dResult>(),
|
||||
_ => output_schema_for::<Curves3dResult>(),
|
||||
};
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{id}: {reply}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The warning for what a key gets wrong is the handler's own wording.
|
||||
#[test]
|
||||
fn the_check_names_what_is_wrong_with_a_key() {
|
||||
let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
|
||||
assert_eq!(issues("sketch.line3d", json!({"points": [[0, 0, 0]]})), ["`points` needs 2 to 500 points"]);
|
||||
assert_eq!(issues("sketch.line3d", json!({"points": [[0, 0, 0], [1]]})), ["a point must be [x, y, z]"]);
|
||||
assert_eq!(issues("sketch.spline3d", json!({"points": 1})), ["`points` must list [x,y,z] points"]);
|
||||
assert_eq!(issues("sketch.point3d", json!({"point": [1]})), ["`point` must be a point [x, y, z]"]);
|
||||
assert_eq!(issues("sketch.move3d", json!({"wire": 1})), ["`wire` must be a 3D curve or point id"]);
|
||||
assert_eq!(issues("sketch.move3d", json!({"wire": "w", "index": 500})), ["`index` must be a fit point index below 500"]);
|
||||
assert_eq!(issues("sketch.move3d", json!({"wire": "w", "by": 1})), ["`by` must be [x,y,z]"]);
|
||||
assert_eq!(issues("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": true})), ["`sketch` must be an id or a name"]);
|
||||
}
|
||||
@@ -1,10 +1,28 @@
|
||||
//! Contracts and result types for the commands in `cmd/sketch_constraints.rs`.
|
||||
//! Contracts and result types for the commands in `cmd/sketch_constraints.rs`: the curvature and
|
||||
//! polygon constraints, the constrainer, Auto Constrain (three commands), Toggle Driven Dimension,
|
||||
//! Toggle Radius / Diameter, the constraint glyphs and Snap Inference.
|
||||
//!
|
||||
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
//! reads it and fails with the handler's message. What only the design can tell (whether a
|
||||
//! sketch, curve, point or dimension exists) stays the handler's to check. A key the handler
|
||||
//! refuses when it is left out (`a`, `b`, `lines`, `entities`, `constraint`, `at`) is optional in
|
||||
//! the type, so the handler keeps its own message, and required in the schema. A call with several
|
||||
//! problems may get a different one first in strict than with the check off (the check goes key by
|
||||
//! key, the handlers in their own order).
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::types::{SketchRef, present};
|
||||
use super::check::whole;
|
||||
use super::config::NameList;
|
||||
use super::motion::require;
|
||||
use super::sketch_ends::SketchTarget;
|
||||
use super::types::{Point2, SketchRef, present};
|
||||
use crate::params;
|
||||
|
||||
/// Switch a circle's or an arc's dimension between its radius and its diameter.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -44,6 +62,464 @@ pub struct ToggleDiameterResult {
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A curve's id, as `sketch.constraint.curvature` reads `a` and `b`: text, else its message.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CurveId(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for CurveId {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(CurveId(s)),
|
||||
_ => Err(D::Error::custom(whole("expected a curve id"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for CurveId {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"CurveId".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "A curve's id in the sketch, such as `c3`.", "type": "string"})
|
||||
}
|
||||
}
|
||||
|
||||
/// A dimension's constraint id, as `sketch.toggle_driven` reads `constraint`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DimensionId(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for DimensionId {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(DimensionId(s)),
|
||||
_ => Err(D::Error::custom("must be a dimension id")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for DimensionId {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"DimensionId".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "A dimension's constraint id in the sketch.", "type": "string"})
|
||||
}
|
||||
}
|
||||
|
||||
/// The point of `sketch.snap`'s `at`: `[x, y]` or `{x, y}` of numbers (below 1e9), with
|
||||
/// `params::req_vec2`'s message.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ClickPoint(pub solidcore_record::Vec2);
|
||||
|
||||
impl<'de> Deserialize<'de> for ClickPoint {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::vec2(&Value::deserialize(d)?).map(ClickPoint).ok_or_else(|| D::Error::custom("must be a point [x, y]"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ClickPoint {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ClickPoint".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<Point2>()
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the refusing-when-left-out keys are listed in the schema's `required`.
|
||||
fn require_keys(schema: &mut Schema, keys: &[&str]) {
|
||||
for key in keys {
|
||||
require(schema, key);
|
||||
}
|
||||
}
|
||||
|
||||
fn curvature_required(schema: &mut Schema) {
|
||||
require_keys(schema, &["a", "b"]);
|
||||
}
|
||||
|
||||
fn polygon_required(schema: &mut Schema) {
|
||||
require_keys(schema, &["lines"]);
|
||||
}
|
||||
|
||||
fn constrainer_required(schema: &mut Schema) {
|
||||
require_keys(schema, &["entities"]);
|
||||
}
|
||||
|
||||
fn driven_required(schema: &mut Schema) {
|
||||
require_keys(schema, &["constraint"]);
|
||||
}
|
||||
|
||||
fn snap_required(schema: &mut Schema) {
|
||||
require_keys(schema, &["at"]);
|
||||
}
|
||||
|
||||
/// Make two curves meet with curvature continuity (G2): they must share an end point.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = curvature_required)]
|
||||
pub struct CurvatureParams {
|
||||
// Optional in the type and required in the schema (`curvature_required`): left out, the
|
||||
// handler refuses it with its own message, not the check's "is required".
|
||||
/// The first curve's id.
|
||||
#[serde(default)]
|
||||
pub a: Option<CurveId>,
|
||||
/// The second curve's id.
|
||||
#[serde(default)]
|
||||
pub b: Option<CurveId>,
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// `refuse` (any case) refuses the constraint when the others already determine it. Anything
|
||||
/// else keeps it, shown dimmed as redundant. Read only then.
|
||||
#[serde(default)]
|
||||
pub if_redundant: Option<String>,
|
||||
}
|
||||
|
||||
/// Make a closed chain of lines a regular polygon: the sides equal and every corner on one
|
||||
/// (construction) circle, which is added.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = polygon_required)]
|
||||
pub struct PolygonParams {
|
||||
// Optional in the type and required in the schema, as `a` above.
|
||||
/// The ids of the lines of the closed chain: 3 to 200 of them, each a line whose end points
|
||||
/// are shared with its neighbours.
|
||||
#[serde(default)]
|
||||
pub lines: Option<NameList>,
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// Apply the constraint one or two sketch entities nearly have already: horizontal or vertical
|
||||
/// for one line; for two, coincident, point on curve, collinear, parallel, perpendicular, equal,
|
||||
/// concentric or tangent, whichever the geometry is closest to.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = constrainer_required)]
|
||||
pub struct ConstrainerParams {
|
||||
// Optional in the type and required in the schema, as `a` above.
|
||||
/// One or two sketch entity ids (curves or points): one line, or two entities.
|
||||
#[serde(default)]
|
||||
pub entities: Option<NameList>,
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// `refuse` (any case) refuses the constraint when the others already determine it. Anything
|
||||
/// else keeps it, shown dimmed as redundant. Read only then.
|
||||
#[serde(default)]
|
||||
pub if_redundant: Option<String>,
|
||||
}
|
||||
|
||||
/// Infer the constraints the sketch's geometry nearly has (coincident points, horizontal and
|
||||
/// vertical lines, tangent joints), then dimension what is left until it is fully constrained.
|
||||
/// A constraint that removes no freedom or that the sketch could not solve with is dropped.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct AutoConstrainParams {
|
||||
/// How close two points must be to be made coincident, in mm (a number of 0 or less, or of
|
||||
/// 1e9 or more, is read as the default). Default: 0.01.
|
||||
#[serde(default)]
|
||||
pub tolerance: Option<f64>,
|
||||
/// How far a line may be from horizontal or vertical, or a joint from tangent, in degrees (a
|
||||
/// number of 0 or less, or of 1e9 or more, is read as the default). Default: 1.
|
||||
#[serde(default)]
|
||||
pub angle_tolerance: Option<f64>,
|
||||
/// Add dimensions (lengths, radii, diameters, distances from the datum). Default: true.
|
||||
#[serde(default)]
|
||||
pub dimensions: Option<bool>,
|
||||
/// The point the position dimensions are measured from: a point id or a name the sketch
|
||||
/// resolves (as `sketch.auto_constrain_from_datum` takes it). Default: the sketch origin.
|
||||
#[serde(default)]
|
||||
pub datum: Option<String>,
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// Auto Constrain with the position dimensions measured from a datum point instead of the
|
||||
/// origin.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct AutoConstrainDatumParams {
|
||||
/// How close two points must be to be made coincident, in mm (a number of 0 or less, or of
|
||||
/// 1e9 or more, is read as the default). Default: 0.01.
|
||||
#[serde(default)]
|
||||
pub tolerance: Option<f64>,
|
||||
/// How far a line may be from horizontal or vertical, or a joint from tangent, in degrees (a
|
||||
/// number of 0 or less, or of 1e9 or more, is read as the default). Default: 1.
|
||||
#[serde(default)]
|
||||
pub angle_tolerance: Option<f64>,
|
||||
/// Add dimensions (lengths, radii, diameters, distances from the datum). Default: true.
|
||||
#[serde(default)]
|
||||
pub dimensions: Option<bool>,
|
||||
/// The point the position dimensions are measured from: a point id or a name the sketch
|
||||
/// resolves. Default: the sketch origin.
|
||||
#[serde(default)]
|
||||
pub datum: Option<String>,
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// Auto Constrain, then Finish Sketch: the sketch is closed when it is done.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct FinishAutoConstrainParams {
|
||||
/// How close two points must be to be made coincident, in mm (a number of 0 or less, or of
|
||||
/// 1e9 or more, is read as the default). Default: 0.01.
|
||||
#[serde(default)]
|
||||
pub tolerance: Option<f64>,
|
||||
/// How far a line may be from horizontal or vertical, or a joint from tangent, in degrees (a
|
||||
/// number of 0 or less, or of 1e9 or more, is read as the default). Default: 1.
|
||||
#[serde(default)]
|
||||
pub angle_tolerance: Option<f64>,
|
||||
/// Add dimensions (lengths, radii, diameters, distances from the datum). Default: true.
|
||||
#[serde(default)]
|
||||
pub dimensions: Option<bool>,
|
||||
/// The point the position dimensions are measured from: a point id or a name the sketch
|
||||
/// resolves. Default: the sketch origin.
|
||||
#[serde(default)]
|
||||
pub datum: Option<String>,
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// Make a dimension driven (it measures, and is no longer a parameter) or driving again (it gets
|
||||
/// a parameter holding its current value).
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = driven_required)]
|
||||
pub struct ToggleDrivenParams {
|
||||
// Optional in the type and required in the schema, as `a` above.
|
||||
/// The dimension's constraint id.
|
||||
#[serde(default)]
|
||||
pub constraint: Option<DimensionId>,
|
||||
/// `true` for driven, `false` for driving. Default: the other one from now.
|
||||
#[serde(default)]
|
||||
pub driven: Option<bool>,
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// List every constraint of a sketch with where its glyph is drawn (sketch coordinates), what it
|
||||
/// is and whether it fails or is redundant, with the sketch's freedom. Changes nothing.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct GlyphsParams {
|
||||
/// The sketch (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// What a click at a point in the sketch being edited would snap to or infer, best first: a
|
||||
/// point, a line's midpoint, a point on a curve, and horizontal or vertical alignment with the
|
||||
/// previous click. Changes nothing.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = snap_required)]
|
||||
pub struct SnapParams {
|
||||
// Optional in the type and required in the schema, as `a` above.
|
||||
/// The click, [x, y] in the sketch's coordinates, in mm.
|
||||
#[serde(default)]
|
||||
pub at: Option<ClickPoint>,
|
||||
/// The previous click, [x, y]: horizontal and vertical alignment with it is offered. Default:
|
||||
/// none.
|
||||
#[serde(default)]
|
||||
pub from: Option<Point2>,
|
||||
/// The snap distance in mm (a number of 0 or less, or of 1e9 or more, is read as the
|
||||
/// default). Default: 1.
|
||||
#[serde(default)]
|
||||
pub radius: Option<f64>,
|
||||
}
|
||||
|
||||
/// What the curvature constraint returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ConstraintAdded {
|
||||
/// The new constraint's id.
|
||||
pub constraint: String,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// `true` when the other constraints already determine it (present only then).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub redundant: bool,
|
||||
/// The constraints that already determine it, as "id (Name)" (present only when redundant).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub determined_by: Option<Vec<String>>,
|
||||
/// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists
|
||||
/// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.constrainer` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ConstrainerResult {
|
||||
/// The new constraint's id.
|
||||
pub constraint: String,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// `true` when the other constraints already determine it (present only then).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub redundant: bool,
|
||||
/// The constraints that already determine it, as "id (Name)" (present only when redundant).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub determined_by: Option<Vec<String>>,
|
||||
/// The kind of constraint applied, such as `Horizontal` or `Tangent`.
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
/// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists
|
||||
/// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What the polygon constraint returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PolygonResult {
|
||||
/// The new constraints' ids: equal sides, then the corners on the circle.
|
||||
pub constraints: Vec<String>,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists
|
||||
/// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What the Auto Constrain commands return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct AutoConstrainResult {
|
||||
/// The ids of the constraints and dimensions it added.
|
||||
pub added: Vec<String>,
|
||||
/// The degrees of freedom left (0: fully constrained).
|
||||
pub dof: usize,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists
|
||||
/// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.toggle_driven` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ToggleDrivenResult {
|
||||
/// The dimension's constraint id (unchanged).
|
||||
pub constraint: String,
|
||||
/// Whether it is driven now.
|
||||
pub driven: bool,
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists
|
||||
/// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// One constraint of `sketch.glyphs`, with where its glyph goes.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Glyph {
|
||||
/// The constraint's id.
|
||||
pub id: String,
|
||||
/// Its kind, such as `Horizontal` or `Radius`.
|
||||
pub name: String,
|
||||
/// Whether it is a dimension.
|
||||
pub dimension: bool,
|
||||
/// Whether it is driven (it measures; it does not constrain).
|
||||
pub driven: bool,
|
||||
/// A dimension's value (mm, or radians for an angle); `null` for another constraint.
|
||||
pub value: Option<f64>,
|
||||
/// The parameter a driving dimension takes its value from; `null` for none.
|
||||
pub param: Option<String>,
|
||||
/// Where to draw the glyph, [x, y] in sketch coordinates; `null` when it has no place.
|
||||
pub at: Option<[f64; 2]>,
|
||||
/// Whether it is one of the constraints the solver could not satisfy.
|
||||
pub failing: bool,
|
||||
/// Whether the others imply it (it removes no freedom) though it holds: shown dimmed.
|
||||
pub redundant: bool,
|
||||
}
|
||||
|
||||
/// What `sketch.glyphs` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct GlyphsResult {
|
||||
/// The sketch's feature id.
|
||||
pub sketch: u64,
|
||||
/// Its constraints, in order.
|
||||
pub glyphs: Vec<Glyph>,
|
||||
/// The degrees of freedom left.
|
||||
pub dof: usize,
|
||||
/// Whether nothing is left free.
|
||||
pub fully_constrained: bool,
|
||||
/// The ids of the constraints that fail.
|
||||
pub conflicts: Vec<String>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// One thing a click would snap to or infer.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Snap {
|
||||
/// An existing point (an end point, a centre, the origin): the click is made coincident.
|
||||
Coincident {
|
||||
/// The point's id.
|
||||
point: String,
|
||||
/// Where it is, [x, y].
|
||||
at: [f64; 2],
|
||||
},
|
||||
/// The middle of a line.
|
||||
Midpoint {
|
||||
/// The line's id.
|
||||
curve: String,
|
||||
/// The middle, [x, y].
|
||||
at: [f64; 2],
|
||||
},
|
||||
/// The nearest place on a curve.
|
||||
OnCurve {
|
||||
/// The curve's id.
|
||||
curve: String,
|
||||
/// That place, [x, y].
|
||||
at: [f64; 2],
|
||||
},
|
||||
/// Level with the previous click (`from`).
|
||||
Horizontal {
|
||||
/// The click moved to that level, [x, y].
|
||||
at: [f64; 2],
|
||||
},
|
||||
/// Straight above or below the previous click (`from`).
|
||||
Vertical {
|
||||
/// The click moved to that line, [x, y].
|
||||
at: [f64; 2],
|
||||
},
|
||||
}
|
||||
|
||||
/// What `sketch.snap` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SnapResult {
|
||||
/// At most eight, best first: the first is what a click would use.
|
||||
pub snaps: Vec<Snap>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_constraints_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -1,13 +1,29 @@
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{ToggleDiameterParams, ToggleDiameterResult};
|
||||
use super::{
|
||||
AutoConstrainDatumParams, AutoConstrainParams, AutoConstrainResult, ConstrainerParams, ConstrainerResult, ConstraintAdded, CurvatureParams,
|
||||
FinishAutoConstrainParams, GlyphsParams, GlyphsResult, PolygonParams, PolygonResult, SnapParams, SnapResult, ToggleDiameterParams,
|
||||
ToggleDiameterResult, ToggleDrivenParams, ToggleDrivenResult,
|
||||
};
|
||||
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};
|
||||
|
||||
const AUTO_KEYS: [&str; 5] = ["angle_tolerance", "datum", "dimensions", "sketch", "tolerance"];
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<ToggleDiameterParams>(), &["constraint", "diameter", "sketch"]);
|
||||
assert_keys(input_schema_for::<CurvatureParams>(), &["a", "b", "if_redundant", "sketch"]);
|
||||
assert_keys(input_schema_for::<PolygonParams>(), &["lines", "sketch"]);
|
||||
assert_keys(input_schema_for::<ConstrainerParams>(), &["entities", "if_redundant", "sketch"]);
|
||||
assert_keys(input_schema_for::<AutoConstrainParams>(), &AUTO_KEYS);
|
||||
assert_keys(input_schema_for::<AutoConstrainDatumParams>(), &AUTO_KEYS);
|
||||
assert_keys(input_schema_for::<FinishAutoConstrainParams>(), &AUTO_KEYS);
|
||||
assert_keys(input_schema_for::<ToggleDrivenParams>(), &["constraint", "driven", "sketch"]);
|
||||
// Snap Inference works in the sketch being edited: it reads no `sketch`.
|
||||
assert_keys(input_schema_for::<GlyphsParams>(), &["sketch"]);
|
||||
assert_keys(input_schema_for::<SnapParams>(), &["at", "from", "radius"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -17,9 +33,195 @@ fn strict_keeps_todays_errors() {
|
||||
("sketch.toggle_diameter", json!({"constraint": null})),
|
||||
("sketch.toggle_diameter", json!({"constraint": "c1"})),
|
||||
("sketch.toggle_diameter", json!({"constraint": "c1", "diameter": true})),
|
||||
// The keys these handlers read before they need a sketch.
|
||||
("sketch.constrainer", json!({"entities": 5})),
|
||||
("sketch.constrainer", json!({"entities": [1]})),
|
||||
("sketch.constrainer", json!({"entities": ["a", 2]})),
|
||||
("sketch.constrainer", json!({})),
|
||||
("sketch.constrainer", json!({"entities": null})),
|
||||
("sketch.constraint.polygon", json!({"lines": true})),
|
||||
("sketch.constraint.polygon", json!({"lines": [{}]})),
|
||||
("sketch.constraint.polygon", json!({})),
|
||||
("sketch.constraint.polygon", json!({"lines": ["l1", "l2"]})),
|
||||
("sketch.toggle_driven", json!({})),
|
||||
("sketch.toggle_driven", json!({"constraint": 5})),
|
||||
("sketch.toggle_driven", json!({"constraint": null})),
|
||||
("sketch.toggle_driven", json!({"constraint": ["k1"]})),
|
||||
("sketch.snap", json!({})),
|
||||
("sketch.snap", json!({"at": 5})),
|
||||
("sketch.snap", json!({"at": [1]})),
|
||||
("sketch.snap", json!({"at": null})),
|
||||
("sketch.snap", json!({"at": [1, "2"]})),
|
||||
("sketch.snap", json!({"at": [1, 2]})),
|
||||
("sketch.glyphs", json!({})),
|
||||
("sketch.auto_constrain", json!({})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// A session that is editing a sketch with a line and a circle in it.
|
||||
fn editing(level: ParamCheck) -> Session {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
for (id, p) in [
|
||||
("sketch.create", json!({"plane": "XY"})),
|
||||
("sketch.line", json!({"points": [[0, 0], [10, 0.5]]})),
|
||||
("sketch.circle.center", json!({"center": [50, 0], "radius": 5})),
|
||||
] {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The same refusals in a sketch being edited, where the handlers go on to read the sketch, the
|
||||
/// curves and the points: strict says what the handler says.
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors_in_a_sketch() {
|
||||
let cases = [
|
||||
("sketch.constraint.curvature", json!({})),
|
||||
("sketch.constraint.curvature", json!({"a": 5, "b": "c1"})),
|
||||
("sketch.constraint.curvature", json!({"a": "c1"})),
|
||||
("sketch.constraint.curvature", json!({"a": "c1", "b": null})),
|
||||
("sketch.constraint.curvature", json!({"a": "c1", "b": ["c2"]})),
|
||||
("sketch.constraint.curvature", json!({"a": "c1", "b": "c2", "sketch": true})),
|
||||
("sketch.constraint.curvature", json!({"a": "c1", "b": "c2", "sketch": -1})),
|
||||
("sketch.constraint.curvature", json!({"a": "c1", "b": "c2", "sketch": 1.5})),
|
||||
("sketch.constraint.curvature", json!({"a": "c1", "b": "c2", "sketch": [1]})),
|
||||
("sketch.constrainer", json!({"entities": ["c1"], "sketch": {}})),
|
||||
("sketch.constraint.polygon", json!({"lines": ["c1", "c2", "c3"], "sketch": false})),
|
||||
("sketch.toggle_driven", json!({"constraint": "k1", "sketch": -3})),
|
||||
("sketch.glyphs", json!({"sketch": true})),
|
||||
("sketch.glyphs", json!({"sketch": 2.5})),
|
||||
("sketch.auto_constrain", json!({"sketch": ["a"]})),
|
||||
("sketch.auto_constrain_from_datum", json!({"sketch": -1})),
|
||||
("sketch.finish_auto_constrain", json!({"sketch": {}})),
|
||||
];
|
||||
for (index, (id, p)) in cases.iter().enumerate() {
|
||||
let error = |level: ParamCheck| editing(level).execute(id, p).err().map(|e| e.to_string());
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some(), "{index} {id} {p} should fail today");
|
||||
assert_eq!(error(ParamCheck::Strict), off, "{index} {id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What strict adds on purpose: a value of the wrong type the handlers read as if the key were
|
||||
/// left out (a wrong-typed option or `from`).
|
||||
#[test]
|
||||
fn strict_refuses_options_the_handlers_ignore() {
|
||||
let mut s = editing(ParamCheck::Strict);
|
||||
let line = s.execute("sketch.constrainer", &json!({"entities": ["c1"], "if_redundant": 5}));
|
||||
assert!(line.is_err_and(|e| e.to_string().contains("`if_redundant` must be text")));
|
||||
for (id, p) in [
|
||||
("sketch.auto_constrain", json!({"tolerance": "0.1"})),
|
||||
("sketch.auto_constrain", json!({"angle_tolerance": true})),
|
||||
("sketch.auto_constrain", json!({"dimensions": "no"})),
|
||||
("sketch.auto_constrain", json!({"datum": 3})),
|
||||
("sketch.snap", json!({"at": [1, 1], "from": "x"})),
|
||||
("sketch.snap", json!({"at": [1, 1], "radius": "1"})),
|
||||
] {
|
||||
let e = s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(e.contains("invalid parameters"), "{id} {p}: {e}");
|
||||
s.param_check = ParamCheck::Off;
|
||||
assert!(s.execute(id, &p).is_ok(), "{id} {p} works with the check off");
|
||||
s.param_check = ParamCheck::Strict;
|
||||
}
|
||||
}
|
||||
|
||||
/// The schemas take what the handlers read: the keys they refuse when left out are required.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let check = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value().clone();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(&schema, &schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
check(
|
||||
input_schema_for::<CurvatureParams>(),
|
||||
&[
|
||||
(json!({"a": "c1", "b": "c2"}), true),
|
||||
(json!({"a": "c1", "b": "c2", "sketch": 3, "if_redundant": "refuse"}), true),
|
||||
(json!({"a": "c1"}), false),
|
||||
(json!({"b": "c1"}), false),
|
||||
(json!({"a": 1, "b": "c2"}), false),
|
||||
(json!({"a": "c1", "b": "c2", "sketch": -1}), false),
|
||||
(json!({"a": "c1", "b": "c2", "from": 1}), false),
|
||||
],
|
||||
);
|
||||
check(
|
||||
input_schema_for::<PolygonParams>(),
|
||||
&[(json!({"lines": ["l1", "l2", "l3"]}), true), (json!({"lines": "l1", "sketch": "Sketch1"}), true), (json!({}), false)],
|
||||
);
|
||||
check(
|
||||
input_schema_for::<ConstrainerParams>(),
|
||||
&[(json!({"entities": ["l1"]}), true), (json!({"entities": "p1"}), true), (json!({}), false), (json!({"entities": [1]}), false)],
|
||||
);
|
||||
check(
|
||||
input_schema_for::<ToggleDrivenParams>(),
|
||||
&[(json!({"constraint": "k1"}), true), (json!({"constraint": "k1", "driven": false}), true), (json!({"driven": true}), false)],
|
||||
);
|
||||
check(
|
||||
input_schema_for::<SnapParams>(),
|
||||
&[
|
||||
(json!({"at": [1, 2]}), true),
|
||||
(json!({"at": {"x": 1, "y": 2}, "from": [0, 0], "radius": 2}), true),
|
||||
(json!({}), false),
|
||||
(json!({"at": [1, 2, 3]}), false),
|
||||
(json!({"at": [1, 2], "sketch": 1}), false),
|
||||
],
|
||||
);
|
||||
for schema in
|
||||
[input_schema_for::<AutoConstrainParams>(), input_schema_for::<AutoConstrainDatumParams>(), input_schema_for::<FinishAutoConstrainParams>()]
|
||||
{
|
||||
check(
|
||||
schema,
|
||||
&[
|
||||
(json!({}), true),
|
||||
(json!({"tolerance": 0.1, "angle_tolerance": 2, "dimensions": false, "datum": "p1", "sketch": 4}), true),
|
||||
(json!({"tolerance": "x"}), false),
|
||||
(json!({"dimension": true}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
check(input_schema_for::<GlyphsParams>(), &[(json!({}), true), (json!({"sketch": "S"}), true), (json!({"curve": 1}), false)]);
|
||||
}
|
||||
|
||||
/// Each key reads as its handler reads it: `null` is left out, a number is a whole sketch id,
|
||||
/// and every key the handler takes in only some cases (`if_redundant`, `datum`) is still read.
|
||||
#[test]
|
||||
fn the_types_read_each_key_like_the_handlers() {
|
||||
fn parses<T: serde::de::DeserializeOwned>(v: Value) -> bool {
|
||||
serde_json::from_value::<T>(v).is_ok()
|
||||
}
|
||||
// `null` is a key left out, as every reader reads it.
|
||||
assert!(parses::<CurvatureParams>(json!({"a": null, "b": null, "sketch": null, "if_redundant": null})));
|
||||
assert!(parses::<PolygonParams>(json!({"lines": null, "sketch": null})));
|
||||
assert!(parses::<ConstrainerParams>(json!({"entities": null})));
|
||||
assert!(parses::<ToggleDrivenParams>(json!({"constraint": null, "driven": null})));
|
||||
assert!(parses::<SnapParams>(json!({"at": null, "from": null, "radius": null})));
|
||||
assert!(parses::<GlyphsParams>(json!({"sketch": null})));
|
||||
// A key left out is the handler's to refuse, with its own message.
|
||||
assert!(parses::<CurvatureParams>(json!({})) && parses::<PolygonParams>(json!({})) && parses::<SnapParams>(json!({})));
|
||||
// `sketch`: a whole number or text.
|
||||
for ok in [json!(3), json!("Sketch1"), json!("7")] {
|
||||
assert!(parses::<GlyphsParams>(json!({"sketch": ok})), "{ok}");
|
||||
}
|
||||
for bad in [json!(-1), json!(2.5), json!(true), json!([1]), json!({})] {
|
||||
assert!(!parses::<GlyphsParams>(json!({"sketch": bad})), "{bad}");
|
||||
}
|
||||
// Lists of names, as `string_list` reads them.
|
||||
assert!(parses::<PolygonParams>(json!({"lines": "l1"})) && parses::<PolygonParams>(json!({"lines": ["l1", "l2"]})));
|
||||
assert!(!parses::<PolygonParams>(json!({"lines": [1]})) && !parses::<ConstrainerParams>(json!({"entities": 5})));
|
||||
// Points: `[x, y]` or `{x, y}`.
|
||||
assert!(parses::<SnapParams>(json!({"at": [1, 2]})) && parses::<SnapParams>(json!({"at": {"x": 1, "y": 2}, "from": {"x": 0, "y": 0}})));
|
||||
assert!(!parses::<SnapParams>(json!({"at": [1, 2, 3]})) && !parses::<SnapParams>(json!({"at": [1, 1], "from": [1]})));
|
||||
// Numbers the handlers read as the default (zero, negative) are still numbers.
|
||||
assert!(
|
||||
parses::<SnapParams>(json!({"at": [1, 2], "radius": 0})) && parses::<AutoConstrainParams>(json!({"tolerance": -1, "angle_tolerance": 0}))
|
||||
);
|
||||
// `datum` and the tolerances are read by all three Auto Constrain commands.
|
||||
let p = json!({"datum": "p1", "tolerance": 1, "angle_tolerance": 2, "dimensions": false});
|
||||
assert!(parses::<AutoConstrainParams>(p.clone()) && parses::<AutoConstrainDatumParams>(p.clone()) && parses::<FinishAutoConstrainParams>(p));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_diameter_reply_matches_its_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
@@ -46,3 +248,181 @@ fn toggle_diameter_reply_matches_its_schema() {
|
||||
assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, r: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
}
|
||||
|
||||
fn keys(r: &Value) -> Vec<&str> {
|
||||
r.as_object().map(|o| o.keys().map(String::as_str).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<String> {
|
||||
v.as_array().into_iter().flatten().filter_map(|x| x.as_str().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
/// Every command, in every form its handler takes, replies as its output schema says in Warn
|
||||
/// without a warning; a misspelt key still gets its warning and the reply still matches, and
|
||||
/// strict refuses it.
|
||||
#[test]
|
||||
fn replies_match_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let run = |s: &mut Session, id: &str, p: Value| {
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");
|
||||
r
|
||||
};
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
let sketch = s.active_sketch.unwrap_or_default();
|
||||
let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0.5]]}))["curves"])[0].clone();
|
||||
let b = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 5], [10, 6]]}))["curves"])[0].clone();
|
||||
|
||||
// The constrainer: one line; two lines; the same again (redundant), by `sketch` as an id.
|
||||
let r = run(&mut s, "sketch.constrainer", json!({"entities": [a]}));
|
||||
matches(output_schema_for::<ConstrainerResult>(), &r);
|
||||
assert_eq!((r["type"].as_str(), keys(&r)), (Some("Horizontal"), vec!["constraint", "created", "sketch", "type"]), "{r}");
|
||||
assert!(r["sketch"]["solved"] == true && r["sketch"]["dof"].is_u64(), "{r}");
|
||||
let r = run(&mut s, "sketch.constrainer", json!({"entities": [a, b]}));
|
||||
assert_eq!(r["type"], "Parallel", "{r}");
|
||||
let r = run(&mut s, "sketch.constrainer", json!({"entities": a, "sketch": sketch}));
|
||||
matches(output_schema_for::<ConstrainerResult>(), &r);
|
||||
assert_eq!((r["redundant"].clone(), r["determined_by"].is_array()), (json!(true), true), "{r}");
|
||||
assert_eq!(keys(&r), vec!["constraint", "created", "determined_by", "redundant", "sketch", "type"], "{r}");
|
||||
let e = s.execute("sketch.constrainer", &json!({"entities": [a], "if_redundant": "Refuse"})).err().map(|e| e.to_string());
|
||||
assert!(e.is_some_and(|e| e.contains("over-constrain")));
|
||||
|
||||
// Curvature continuity, and polygon.
|
||||
let l = ids(&run(&mut s, "sketch.line", json!({"points": [[-10, 0], [0, 0]], "infer": true}))["curves"])[0].clone();
|
||||
let sp =
|
||||
ids(&run(&mut s, "sketch.spline.control_point", json!({"points": [format!("{l}.end"), [5, 2], [10, 6], [15, 15]]}))["curves"])[0].clone();
|
||||
let r = run(&mut s, "sketch.constraint.curvature", json!({"a": l, "b": sp, "if_redundant": "keep"}));
|
||||
matches(output_schema_for::<ConstraintAdded>(), &r);
|
||||
assert_eq!(keys(&r), vec!["constraint", "created", "sketch"], "{r}");
|
||||
let r = run(&mut s, "sketch.constraint.curvature", json!({"a": l, "b": sp}));
|
||||
matches(output_schema_for::<ConstraintAdded>(), &r);
|
||||
assert_eq!(r["redundant"], true, "{r}");
|
||||
let quad = ids(&run(&mut s, "sketch.line", json!({"points": [[100, 0], [111, 1], [110, 9], [99, 10]], "closed": true}))["curves"]);
|
||||
let r = run(&mut s, "sketch.constraint.polygon", json!({"lines": quad}));
|
||||
matches(output_schema_for::<PolygonResult>(), &r);
|
||||
assert_eq!((r["constraints"].as_array().map(Vec::len), keys(&r)), (Some(7), vec!["constraints", "created", "sketch"]), "{r}");
|
||||
|
||||
// Glyphs, snaps.
|
||||
let g = run(&mut s, "sketch.glyphs", json!({}));
|
||||
matches(output_schema_for::<GlyphsResult>(), &g);
|
||||
assert!(g["glyphs"].as_array().is_some_and(|l| l.len() > 5) && g["glyphs"][0]["at"].is_array(), "{g}");
|
||||
assert_eq!(keys(&g["glyphs"][0]), vec!["at", "dimension", "driven", "failing", "id", "name", "param", "redundant", "value"], "{g}");
|
||||
assert_eq!(keys(&g), vec!["conflicts", "dof", "fully_constrained", "glyphs", "sketch"], "{g}");
|
||||
let g = run(&mut s, "sketch.glyphs", json!({"sketch": sketch}));
|
||||
matches(output_schema_for::<GlyphsResult>(), &g);
|
||||
for p in [
|
||||
json!({"at": [0.2, 0.1]}),
|
||||
json!({"at": {"x": 5, "y": 0.3}, "radius": 1}),
|
||||
json!({"at": [15.5, 6], "from": [0, 6.2], "radius": 2}),
|
||||
json!({"at": [3.2, 5], "from": [3, 20], "radius": 1.5}),
|
||||
json!({"at": [3, 3], "from": null}),
|
||||
] {
|
||||
let r = run(&mut s, "sketch.snap", p.clone());
|
||||
matches(output_schema_for::<SnapResult>(), &r);
|
||||
assert_eq!(keys(&r), vec!["snaps"], "{r}");
|
||||
}
|
||||
let snaps: Vec<String> = [
|
||||
json!({"at": [0.2, 0.1]}),
|
||||
json!({"at": [5.1, 0.3]}),
|
||||
json!({"at": [3, 5.2]}),
|
||||
json!({"at": [3.4, 50], "from": [3, 51], "radius": 1}),
|
||||
json!({"at": [3.4, 50], "from": [3.9, 53], "radius": 1}),
|
||||
json!({"at": [40, 10.4], "from": [30, 10], "radius": 1}),
|
||||
]
|
||||
.into_iter()
|
||||
.flat_map(|p| {
|
||||
let r = run(&mut s, "sketch.snap", p);
|
||||
matches(output_schema_for::<SnapResult>(), &r);
|
||||
r["snaps"].as_array().cloned().unwrap_or_default().into_iter().filter_map(|x| x["type"].as_str().map(str::to_string)).collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
for kind in ["coincident", "midpoint", "on_curve", "horizontal", "vertical"] {
|
||||
assert!(snaps.iter().any(|k| k == kind), "no {kind} in {snaps:?}");
|
||||
}
|
||||
let r = run(&mut s, "sketch.snap", json!({"at": [5.1, 0.3]}));
|
||||
assert!(r["snaps"][0]["curve"].is_string() && r["snaps"][0]["at"].is_array(), "{r}");
|
||||
// The end of `a` (made horizontal above) alone: the coincident snap names that point.
|
||||
let r = run(&mut s, "sketch.snap", json!({"at": [10.2, 0.1], "radius": 0.5}));
|
||||
let first = &r["snaps"][0];
|
||||
assert_eq!((first["type"].as_str(), first["point"].as_str()), (Some("coincident"), Some(format!("{a}.end").as_str())), "{r}");
|
||||
|
||||
// A dimension, driven and driving again.
|
||||
let c = ids(&run(&mut s, "sketch.circle.center", json!({"center": [50, 0], "radius": 5}))["curves"])[0].clone();
|
||||
let d = run(&mut s, "sketch.dimension", json!({"entities": [c]}));
|
||||
let g = run(&mut s, "sketch.glyphs", json!({}));
|
||||
let did = g["glyphs"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|x| x["param"] == d["param"])
|
||||
.and_then(|x| x["id"].as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
assert!(!did.is_empty(), "{g}");
|
||||
let dimension = g["glyphs"].as_array().into_iter().flatten().find(|x| x["id"] == json!(did)).cloned().unwrap_or_default();
|
||||
assert!(dimension["value"].is_number() && dimension["dimension"] == true, "{dimension}");
|
||||
for p in [json!({"constraint": did}), json!({"constraint": did, "driven": false}), json!({"constraint": did, "driven": true, "sketch": null})] {
|
||||
let r = run(&mut s, "sketch.toggle_driven", p);
|
||||
matches(output_schema_for::<ToggleDrivenResult>(), &r);
|
||||
assert_eq!(keys(&r), vec!["constraint", "created", "driven", "sketch"], "{r}");
|
||||
}
|
||||
let r = s.execute("sketch.toggle_driven", &json!({"constraint": did, "drivn": true})).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{r}");
|
||||
matches(output_schema_for::<ToggleDrivenResult>(), &r);
|
||||
|
||||
// Auto Constrain: with the default options, with every option, from a datum, and finishing.
|
||||
run(&mut s, "sketch.point", json!({"point": [5, 5], "id": "d"}));
|
||||
for (id, p) in [
|
||||
("sketch.auto_constrain", json!({})),
|
||||
("sketch.auto_constrain", json!({"tolerance": 0.05, "angle_tolerance": 2, "dimensions": false, "datum": "origin", "sketch": null})),
|
||||
("sketch.auto_constrain_from_datum", json!({"datum": "d"})),
|
||||
("sketch.auto_constrain_from_datum", json!({})),
|
||||
] {
|
||||
let r = run(&mut s, id, p);
|
||||
matches(output_schema_for::<AutoConstrainResult>(), &r);
|
||||
assert_eq!(keys(&r), vec!["added", "created", "dof", "sketch"], "{r}");
|
||||
}
|
||||
let r = run(&mut s, "sketch.finish_auto_constrain", json!({"datum": "d", "tolerance": 0.02}));
|
||||
matches(output_schema_for::<AutoConstrainResult>(), &r);
|
||||
assert!(s.active_sketch.is_none() && r["dof"] == 0, "{r}");
|
||||
|
||||
// More forms, still without a warning: a sketch by name, `from` as an object, `if_redundant`
|
||||
// on a constraint that is not redundant, Finish with every option.
|
||||
let mut t = editing(ParamCheck::Warn);
|
||||
let tname = t.doc.features.first().map(|f| f.name.clone()).unwrap_or_default();
|
||||
let tline = ids(&run(&mut t, "sketch.line", json!({"points": [[0, 30], [10, 30.5]]}))["curves"])[0].clone();
|
||||
run(&mut t, "sketch.glyphs", json!({"sketch": tname}));
|
||||
run(&mut t, "sketch.snap", json!({"at": [1, 1], "from": {"x": 0, "y": 1}}));
|
||||
run(&mut t, "sketch.constrainer", json!({"entities": [tline], "if_redundant": "refuse", "sketch": tname}));
|
||||
let r = run(&mut t, "sketch.finish_auto_constrain", json!({"sketch": tname, "dimensions": false, "angle_tolerance": 3}));
|
||||
matches(output_schema_for::<AutoConstrainResult>(), &r);
|
||||
|
||||
// A misspelt key runs in warn and says so; the reply still matches. Strict refuses it.
|
||||
let mut s = editing(ParamCheck::Warn);
|
||||
let p = json!({"tolerence": 0.1});
|
||||
let r = s.execute("sketch.auto_constrain", &p).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(
|
||||
r["param_warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|w| w.contains("did you mean `tolerance`"))),
|
||||
"{r}"
|
||||
);
|
||||
matches(output_schema_for::<AutoConstrainResult>(), &r);
|
||||
// A new line the constrainer can still act on.
|
||||
let line = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 20], [10, 20.5]]}))["curves"])[0].clone();
|
||||
for (id, p, reply) in [
|
||||
("sketch.snap", json!({"at": [1, 1], "radious": 2}), output_schema_for::<SnapResult>()),
|
||||
("sketch.glyphs", json!({"sketch_id": 1}), output_schema_for::<GlyphsResult>()),
|
||||
("sketch.constrainer", json!({"entities": [line], "if_redundent": "refuse"}), output_schema_for::<ConstrainerResult>()),
|
||||
] {
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{id}: {r}");
|
||||
matches(reply, &r);
|
||||
}
|
||||
s.param_check = ParamCheck::Strict;
|
||||
let e = s.execute("sketch.snap", &json!({"at": [1, 1], "radious": 2})).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(e.contains("`radious`") && e.contains("`radius`"), "{e}");
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,11 @@
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult};
|
||||
use super::{
|
||||
ArcSlotCenterParams, ArcSlotResult, ArcSlotThreePointParams, ArcTangentParams, BlendCurveParams, CenterlineParams, ConicParams,
|
||||
ControlPointSplineParams, DrawResult, EditTextParams, EditTextResult, EllipseParams, FitPointSplineParams, InfiniteLineParams, LineTypeResult,
|
||||
MidpointLineParams, SketchTextParams, SlotCenterPointParams, SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams,
|
||||
SplineReverseResult, TextResult, ThreeTangentCircleParams, TwoTangentCircleParams,
|
||||
};
|
||||
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};
|
||||
@@ -81,3 +86,825 @@ fn construction_line_contracts_and_replies_match() {
|
||||
}
|
||||
assert!(s.execute("sketch.construction_line", &json!({"at":[0,0],"mode":"unknown"})).is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The creation commands (#12550)
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A session at `level` editing a sketch with two lines meeting at (40, 0), a circle and a text.
|
||||
fn drawing(level: ParamCheck) -> Session {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[40, 0], [40, 30]]}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 4}));
|
||||
run(&mut s, "sketch.text", json!({"text": "Hi", "at": [0, 40]}));
|
||||
s
|
||||
}
|
||||
|
||||
/// The link of the text `drawing` makes.
|
||||
fn text_link() -> String {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[40, 0], [40, 30]]}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 4}));
|
||||
run(&mut s, "sketch.text", json!({"text": "Hi", "at": [0, 40]}))["link"].as_str().unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// Like `assert_strict_keeps_todays_errors`, in a sketch being edited: the calls whose refusal
|
||||
/// depends on the design (a point or curve that isn't there), or that the handler reaches only
|
||||
/// after it has found its sketch.
|
||||
fn assert_strict_keeps_todays_errors_in_a_sketch(cases: &[(&str, Value)]) {
|
||||
for (id, p) in cases {
|
||||
let error = |level: ParamCheck| drawing(level).execute(id, p).err().map(|e| e.to_string());
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some(), "{id} {p} should fail today");
|
||||
assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, r: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
}
|
||||
|
||||
fn issues(id: &str, p: Value) -> Vec<String> {
|
||||
crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creation_schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<MidpointLineParams>(), &["construction", "end", "mid", "sketch"]);
|
||||
assert_keys(input_schema_for::<ArcTangentParams>(), &["curve", "end", "sketch", "start"]);
|
||||
assert_keys(input_schema_for::<TwoTangentCircleParams>(), &["curves", "diameter", "near", "radius", "sketch"]);
|
||||
assert_keys(input_schema_for::<ThreeTangentCircleParams>(), &["curves", "near", "sketch"]);
|
||||
assert_keys(input_schema_for::<SlotCenterPointParams>(), &["center", "connect", "end", "sketch", "width"]);
|
||||
assert_keys(input_schema_for::<ArcSlotThreePointParams>(), &["end", "sketch", "start", "through", "width"]);
|
||||
assert_keys(input_schema_for::<ArcSlotCenterParams>(), &["center", "end", "sketch", "start", "sweep", "width"]);
|
||||
assert_keys(input_schema_for::<EllipseParams>(), &["axes", "center", "construction", "major", "minor", "minor_radius", "sketch"]);
|
||||
assert_keys(input_schema_for::<FitPointSplineParams>(), &["construction", "periodic", "points", "sketch"]);
|
||||
assert_keys(input_schema_for::<ControlPointSplineParams>(), &["construction", "periodic", "points", "sketch"]);
|
||||
assert_keys(input_schema_for::<ConicParams>(), &["apex", "construction", "end", "rho", "sketch", "start"]);
|
||||
assert_keys(input_schema_for::<BlendCurveParams>(), &["a", "b", "continuity", "sketch"]);
|
||||
assert_keys(input_schema_for::<CenterlineParams>(), &["curves", "sketch", "value"]);
|
||||
assert_keys(input_schema_for::<InfiniteLineParams>(), &["curves", "sketch", "value"]);
|
||||
// The texts go into the sketch being edited; `sketch` only picks what `created` compares.
|
||||
assert_keys(
|
||||
input_schema_for::<SketchTextParams>(),
|
||||
&[
|
||||
"align",
|
||||
"angle",
|
||||
"at",
|
||||
"bold",
|
||||
"font",
|
||||
"height",
|
||||
"italic",
|
||||
"letter_spacing",
|
||||
"line_spacing",
|
||||
"path",
|
||||
"reverse",
|
||||
"sketch",
|
||||
"text",
|
||||
"text_expression",
|
||||
],
|
||||
);
|
||||
assert_keys(
|
||||
input_schema_for::<EditTextParams>(),
|
||||
&[
|
||||
"align",
|
||||
"angle",
|
||||
"at",
|
||||
"bold",
|
||||
"edits",
|
||||
"entity",
|
||||
"font",
|
||||
"height",
|
||||
"italic",
|
||||
"letter_spacing",
|
||||
"line_spacing",
|
||||
"link",
|
||||
"live",
|
||||
"path",
|
||||
"reverse",
|
||||
"sketch",
|
||||
"text",
|
||||
"text_expression",
|
||||
],
|
||||
);
|
||||
// Every command has a contract and an output schema, and the edit's items too.
|
||||
for id in [
|
||||
"sketch.arc.tangent",
|
||||
"sketch.blend_curve",
|
||||
"sketch.centerline",
|
||||
"sketch.circle.three_tangent",
|
||||
"sketch.circle.two_tangent",
|
||||
"sketch.conic",
|
||||
"sketch.edit_text",
|
||||
"sketch.ellipse",
|
||||
"sketch.infinite",
|
||||
"sketch.line.midpoint",
|
||||
"sketch.slot.arc_center",
|
||||
"sketch.slot.arc_three_point",
|
||||
"sketch.slot.center_point",
|
||||
"sketch.spline.control_point",
|
||||
"sketch.spline.control_point_5",
|
||||
"sketch.spline.fit_point",
|
||||
"sketch.text",
|
||||
] {
|
||||
let c = crate::cmd::find_command(id).unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(c.contract.is_some() && c.output.is_some(), "{id}");
|
||||
}
|
||||
assert_eq!(solidcraft_sketch::MAX_SPLINE_POINTS, 500, "the handler's message and the type's say 500");
|
||||
}
|
||||
|
||||
/// The calls the handlers refuse before they look at a sketch: strict gives their messages.
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors_before_the_sketch() {
|
||||
let long = "x".repeat(solidcraft_sketch::MAX_TEXT_CHARS + 1);
|
||||
let at = json!([0, 0]);
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("sketch.line.midpoint", json!({})),
|
||||
("sketch.line.midpoint", json!({"mid": [1, 1]})),
|
||||
("sketch.line.midpoint", json!({"mid": [1, 1], "end": 5})),
|
||||
("sketch.line.midpoint", json!({"mid": [1, 1], "end": null})),
|
||||
("sketch.line.midpoint", json!({"mid": [1, 1], "end": [1]})),
|
||||
("sketch.arc.tangent", json!({"start": "l1.end"})),
|
||||
("sketch.arc.tangent", json!({"start": "l1.end", "end": true})),
|
||||
("sketch.arc.tangent", json!({"start": "l1.end", "end": null})),
|
||||
("sketch.circle.two_tangent", json!({})),
|
||||
("sketch.circle.two_tangent", json!({"radius": true})),
|
||||
("sketch.circle.two_tangent", json!({"radius": " "})),
|
||||
("sketch.circle.two_tangent", json!({"diameter": "5"})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": "x"})),
|
||||
("sketch.circle.two_tangent", json!({"diameter": 5, "near": null})),
|
||||
("sketch.circle.three_tangent", json!({})),
|
||||
("sketch.circle.three_tangent", json!({"near": [1]})),
|
||||
("sketch.slot.center_point", json!({})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0]})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0]})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": 0})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": -2})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": "2"})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": null})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [5], "width": 2})),
|
||||
("sketch.slot.arc_three_point", json!({})),
|
||||
("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 1]})),
|
||||
("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 1], "end": [2, 0]})),
|
||||
("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 1], "end": [2, 0], "width": 0})),
|
||||
("sketch.slot.arc_center", json!({})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0]})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "end": true})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": "x"})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": null})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": 1e9})),
|
||||
("sketch.ellipse", json!({})),
|
||||
("sketch.ellipse", json!({"center": [0, 0]})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0]})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor": true})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor": [1]})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": 0})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": -3})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": 1e8})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": "3"})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": 3, "axes": "yes"})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor": [1, 1], "axes": 0})),
|
||||
("sketch.conic", json!({"rho": 0})),
|
||||
("sketch.conic", json!({"rho": 1})),
|
||||
("sketch.conic", json!({"rho": -2})),
|
||||
("sketch.conic", json!({"rho": 1e-7})),
|
||||
("sketch.spline.fit_point", json!({"periodic": "yes"})),
|
||||
("sketch.spline.fit_point", json!({"periodic": null})),
|
||||
("sketch.spline.fit_point", json!({"periodic": 1, "points": [[0, 0], [1, 1]]})),
|
||||
("sketch.spline.control_point", json!({"periodic": true, "points": [[0, 0], [1, 1]]})),
|
||||
("sketch.spline.control_point", json!({"periodic": null})),
|
||||
("sketch.spline.control_point_5", json!({"periodic": true})),
|
||||
("sketch.blend_curve", json!({"continuity": "g9"})),
|
||||
("sketch.blend_curve", json!({"continuity": "g0"})),
|
||||
("sketch.blend_curve", json!({"continuity": 5})),
|
||||
("sketch.blend_curve", json!({"continuity": true})),
|
||||
("sketch.centerline", json!({})),
|
||||
("sketch.centerline", json!({"curves": []})),
|
||||
("sketch.centerline", json!({"curves": null})),
|
||||
("sketch.centerline", json!({"curves": 5})),
|
||||
("sketch.centerline", json!({"curves": [1]})),
|
||||
("sketch.centerline", json!({"curves": ["l1", true]})),
|
||||
("sketch.infinite", json!({})),
|
||||
("sketch.infinite", json!({"curves": []})),
|
||||
("sketch.infinite", json!({"curves": {"a": 1}})),
|
||||
("sketch.text", json!({})),
|
||||
("sketch.text", json!({"at": null})),
|
||||
("sketch.text", json!({"at": [1], "text": "x"})),
|
||||
("sketch.text", json!({"at": [1, 2, 3], "text": "x"})),
|
||||
("sketch.text", json!({"at": "x", "text": "x"})),
|
||||
("sketch.text", json!({"at": [1, true], "text": "x"})),
|
||||
("sketch.text", json!({"at": ["", 1], "text": "x"})),
|
||||
("sketch.text", json!({"at": {"x": "w", "y": 1}, "text": "x"})),
|
||||
("sketch.text", json!({"at": ["no_such_parameter", 1], "text": "x"})),
|
||||
("sketch.text", json!({"at": at})),
|
||||
("sketch.text", json!({"at": at, "text": ""})),
|
||||
("sketch.text", json!({"at": at, "text": " \n "})),
|
||||
("sketch.text", json!({"at": at, "text": 5})),
|
||||
("sketch.text", json!({"at": at, "text": long})),
|
||||
("sketch.text", json!({"at": at, "text_expression": 5})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "text_expression": "'y'"})),
|
||||
("sketch.text", json!({"at": at, "text": 5, "text_expression": 6})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "height": 0})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "height": 1e5})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "height": true})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "height": " "})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "height": "no_such_parameter"})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "angle": []})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "angle": 1e9})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "font": 5})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "font": "No Such Font Family 12345"})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "bold": "yes"})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "italic": 1})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "reverse": []})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "align": "up"})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "align": 5})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "letter_spacing": "wide"})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "line_spacing": 0})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "line_spacing": "2"})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "path": 5})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// The calls that need the design to be refused, or that the handlers refuse once they have
|
||||
/// found their sketch: strict gives their messages.
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors_in_a_sketch() {
|
||||
let at = json!([0, 0]);
|
||||
// The text `drawing` made.
|
||||
let t = text_link();
|
||||
assert_strict_keeps_todays_errors_in_a_sketch(&[
|
||||
("sketch.line.midpoint", json!({"end": [1, 1]})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": null})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": 5})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": [1]})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": [1, true]})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": ["", 1]})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": ["no_such_parameter", 1]})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": {"ref": 5}})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": {"vertex": [1, 2]}})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": "no_such_point"})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": [1, 1]})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": [3, 3], "sketch": true})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": [3, 3], "sketch": -1})),
|
||||
("sketch.line.midpoint", json!({"end": [1, 1], "mid": [3, 3], "sketch": 4096})),
|
||||
("sketch.arc.tangent", json!({"end": [1, 1]})),
|
||||
("sketch.arc.tangent", json!({"end": [1, 1], "start": null})),
|
||||
("sketch.arc.tangent", json!({"end": [1, 1], "start": 5})),
|
||||
("sketch.arc.tangent", json!({"end": [1, 1], "start": {"at": 5}})),
|
||||
("sketch.arc.tangent", json!({"end": [1, 1], "start": "on:l1:5,0"})),
|
||||
("sketch.arc.tangent", json!({"end": "no_such_point", "start": "l1.end"})),
|
||||
("sketch.arc.tangent", json!({"end": [50, 20], "start": "l1.end", "curve": "no_such_curve"})),
|
||||
("sketch.arc.tangent", json!({"end": [50, 0], "start": "l1.end"})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10]})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": null})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": ["l1"]})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": 5})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": [1, 2]})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": ["l1", true]})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": ["l1", "l1", "l2"]})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": ["l1", "no_such_curve"]})),
|
||||
("sketch.circle.two_tangent", json!({"radius": "no_such_parameter", "near": [20, 10], "curves": ["l1", "l2"]})),
|
||||
("sketch.circle.two_tangent", json!({"radius": 0, "near": [20, 10], "curves": ["l1", "l2"]})),
|
||||
("sketch.circle.three_tangent", json!({"near": [20, 10]})),
|
||||
("sketch.circle.three_tangent", json!({"near": [20, 10], "curves": ["l1", "l2"]})),
|
||||
("sketch.circle.three_tangent", json!({"near": [20, 10], "curves": {}})),
|
||||
("sketch.circle.three_tangent", json!({"near": [20, 10], "curves": ["l1", "l2", "no_such_curve"]})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [0, 0], "width": 2})),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": 2, "sketch": [1]})),
|
||||
("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 0], "end": [2, 0], "width": 1})),
|
||||
("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 1], "end": [2, 0], "width": 30})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [0, 0], "width": 1, "sweep": 90})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": 0})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1})),
|
||||
("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "end": [0, 0]})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [0, 0], "minor_radius": 3})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor": [20, 0]})),
|
||||
("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": 3, "sketch": 4096})),
|
||||
("sketch.conic", json!({"end": [2, 0], "apex": [1, 1]})),
|
||||
("sketch.conic", json!({"start": null, "end": [2, 0], "apex": [1, 1]})),
|
||||
("sketch.conic", json!({"start": [0, 0], "end": 5, "apex": [1, 1]})),
|
||||
("sketch.conic", json!({"start": [0, 0], "end": [2, 0]})),
|
||||
("sketch.conic", json!({"start": "l1.start", "end": "l1.start", "apex": [1, 1]})),
|
||||
("sketch.conic", json!({"start": [0, 0], "end": [2, 0], "apex": "no_such_point"})),
|
||||
("sketch.conic", json!({"start": [0, 0], "end": [2, 0], "apex": "x:l1+l1:1,1"})),
|
||||
("sketch.spline.fit_point", json!({})),
|
||||
("sketch.spline.fit_point", json!({"points": 5})),
|
||||
("sketch.spline.fit_point", json!({"points": null})),
|
||||
("sketch.spline.fit_point", json!({"points": [[0, 0]]})),
|
||||
("sketch.spline.fit_point", json!({"points": vec![json!([0, 1]); 501]})),
|
||||
("sketch.spline.fit_point", json!({"points": [[0, 0], 5]})),
|
||||
("sketch.spline.fit_point", json!({"points": [[0, 0], [1, 1], {"at": "x"}]})),
|
||||
("sketch.spline.fit_point", json!({"points": [[0, 0], [0, 0]]})),
|
||||
("sketch.spline.fit_point", json!({"points": [[0, 0], [1, 1]], "sketch": true})),
|
||||
("sketch.spline.control_point", json!({"points": [[0, 0], "no_such_point"]})),
|
||||
("sketch.spline.control_point_5", json!({"points": [[0, 0], [1, 1], ["", 3]]})),
|
||||
("sketch.blend_curve", json!({"b": "l2.end"})),
|
||||
("sketch.blend_curve", json!({"a": "l1.end"})),
|
||||
("sketch.blend_curve", json!({"a": null, "b": "l2.end"})),
|
||||
("sketch.blend_curve", json!({"a": "l1.end", "b": 5})),
|
||||
("sketch.blend_curve", json!({"a": "l1.end", "b": "l1.end"})),
|
||||
("sketch.blend_curve", json!({"a": [1, 1], "b": "l2.end"})),
|
||||
("sketch.blend_curve", json!({"a": "no_such_point", "b": "l2.end"})),
|
||||
("sketch.blend_curve", json!({"a": "l1.end", "b": "l2.end", "continuity": "g5"})),
|
||||
("sketch.centerline", json!({"curves": ["no_such_curve"]})),
|
||||
("sketch.centerline", json!({"curves": ["c1"]})),
|
||||
("sketch.infinite", json!({"curves": ["l1", "c1"]})),
|
||||
("sketch.infinite", json!({"curves": ["no_such_curve"]})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "path": "no_such_curve"})),
|
||||
("sketch.text", json!({"at": at, "text": "x", "path": t})),
|
||||
("sketch.edit_text", json!({})),
|
||||
("sketch.edit_text", json!({"link": 5})),
|
||||
("sketch.edit_text", json!({"link": null, "entity": null})),
|
||||
("sketch.edit_text", json!({"link": "no_such_link"})),
|
||||
("sketch.edit_text", json!({"entity": "no_such_curve"})),
|
||||
("sketch.edit_text", json!({"entity": "l1"})),
|
||||
("sketch.edit_text", json!({"link": t, "text": 5})),
|
||||
("sketch.edit_text", json!({"link": t, "text": ""})),
|
||||
("sketch.edit_text", json!({"link": t, "text": "x", "text_expression": "'y'"})),
|
||||
("sketch.edit_text", json!({"link": t, "text_expression": 5})),
|
||||
("sketch.edit_text", json!({"link": t, "at": [1]})),
|
||||
("sketch.edit_text", json!({"link": t, "at": "x"})),
|
||||
("sketch.edit_text", json!({"link": t, "height": -1})),
|
||||
("sketch.edit_text", json!({"link": t, "height": []})),
|
||||
("sketch.edit_text", json!({"link": t, "angle": {}})),
|
||||
("sketch.edit_text", json!({"link": t, "font": false})),
|
||||
("sketch.edit_text", json!({"link": t, "bold": "no"})),
|
||||
("sketch.edit_text", json!({"link": t, "align": "middle"})),
|
||||
("sketch.edit_text", json!({"link": t, "letter_spacing": true})),
|
||||
("sketch.edit_text", json!({"link": t, "line_spacing": -1})),
|
||||
("sketch.edit_text", json!({"link": t, "path": 3})),
|
||||
("sketch.edit_text", json!({"edits": []})),
|
||||
("sketch.edit_text", json!({"edits": "t1"})),
|
||||
("sketch.edit_text", json!({"edits": {"link": t}})),
|
||||
("sketch.edit_text", json!({"edits": [5]})),
|
||||
("sketch.edit_text", json!({"edits": [{}]})),
|
||||
("sketch.edit_text", json!({"edits": [{"link": t}, {"link": "no_such_link"}]})),
|
||||
("sketch.edit_text", json!({"edits": [{"link": t, "text": 5}]})),
|
||||
("sketch.edit_text", json!({"edits": [{"link": t, "at": [1, 2, 3]}]})),
|
||||
("sketch.edit_text", json!({"edits": vec![json!({"link": t}); 1001]})),
|
||||
("sketch.edit_text", json!({"edits": [{"link": t, "bold": 1}], "live": false})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// A key the handler reads leniently (a wrong type read as left out) is a mistake the check
|
||||
/// reports: the one place where strict refuses a call that runs today, as documented.
|
||||
#[test]
|
||||
fn wrong_types_the_handlers_ignore_are_reported() {
|
||||
for (id, p, message) in [
|
||||
("sketch.conic", json!({"start": [0, 0], "end": [2, 0], "apex": [1, 1], "rho": "x"}), "`rho` must be a number between 0 and 1"),
|
||||
("sketch.line.midpoint", json!({"mid": [0, 0], "end": [2, 0], "construction": "yes"}), "`construction` must be true or false"),
|
||||
("sketch.slot.center_point", json!({"center": [0, 0], "end": [2, 0], "width": 1, "connect": 1}), "`connect` must be true or false"),
|
||||
("sketch.arc.tangent", json!({"start": "l1.end", "end": [2, 0], "curve": 5}), "`curve` must be text"),
|
||||
("sketch.centerline", json!({"curves": ["l1"], "value": 1}), "`value` must be true or false"),
|
||||
("sketch.edit_text", json!({"link": "t1", "live": 1}), "`live` must be true or false"),
|
||||
] {
|
||||
assert_eq!(issues(id, p), [message], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Keys a handler reads only in some cases are checked only in those cases: a call that works
|
||||
/// never gets a warning for the rest.
|
||||
#[test]
|
||||
fn keys_read_only_in_some_cases_are_checked_only_then() {
|
||||
let ok = |id: &str, p: Value| assert_eq!(issues(id, p.clone()), Vec::<String>::new(), "{id} {p}");
|
||||
let near = json!([20, 10]);
|
||||
// radius wins over diameter, whatever the diameter is; without a radius, a diameter does.
|
||||
ok("sketch.circle.two_tangent", json!({"radius": 5, "diameter": "wide", "near": near, "curves": ["l1", "l2"]}));
|
||||
ok("sketch.circle.two_tangent", json!({"radius": "r / 2", "diameter": null, "near": near, "curves": ["l1", "l2"]}));
|
||||
ok("sketch.circle.two_tangent", json!({"radius": true, "diameter": 10, "near": near, "curves": ["l1", "l2"]}));
|
||||
ok("sketch.circle.two_tangent", json!({"diameter": 10, "near": near, "curves": ["l1", "l2"]}));
|
||||
assert_eq!(
|
||||
issues("sketch.circle.two_tangent", json!({"diameter": "wide", "near": near, "curves": ["l1", "l2"]})),
|
||||
["needs `radius` or `diameter`"]
|
||||
);
|
||||
// sweep wins over end, however end is written; without a sweep, end is read.
|
||||
let slot = |extra: Value| {
|
||||
let mut p = json!({"center": [0, 0], "start": [5, 0], "width": 1});
|
||||
p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
|
||||
p
|
||||
};
|
||||
ok("sketch.slot.arc_center", slot(json!({"sweep": 90, "end": "nowhere"})));
|
||||
ok("sketch.slot.arc_center", slot(json!({"sweep": 90, "end": null})));
|
||||
ok("sketch.slot.arc_center", slot(json!({"end": [0, 5]})));
|
||||
assert_eq!(issues("sketch.slot.arc_center", slot(json!({"end": "nowhere"}))), ["`end` must be a point [x, y]"]);
|
||||
assert_eq!(issues("sketch.slot.arc_center", slot(json!({"sweep": null, "end": [0, 5]}))), ["`sweep` must be finite degrees"]);
|
||||
// minor_radius wins over minor, and a minor_radius that is no number is not read when there is a minor.
|
||||
let ellipse = |extra: Value| {
|
||||
let mut p = json!({"center": [0, 0], "major": [10, 0]});
|
||||
p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
|
||||
p
|
||||
};
|
||||
ok("sketch.ellipse", ellipse(json!({"minor_radius": 3, "minor": "nowhere"})));
|
||||
ok("sketch.ellipse", ellipse(json!({"minor_radius": "wide", "minor": [1, 1]})));
|
||||
ok("sketch.ellipse", ellipse(json!({"minor_radius": null, "minor": [1, 1]})));
|
||||
ok("sketch.ellipse", ellipse(json!({"minor": {"x": 1, "y": 1}})));
|
||||
assert_eq!(issues("sketch.ellipse", ellipse(json!({"minor_radius": "wide", "minor": "x"}))), ["needs `minor` [x,y] or `minor_radius`"]);
|
||||
// Outside `edits` a text edit reads its own keys; with `edits` it reads only `edits` (and `live`).
|
||||
ok("sketch.edit_text", json!({"edits": [{"link": "t1"}], "link": 5, "text": 7, "at": "no", "bold": "yes"}));
|
||||
ok("sketch.edit_text", json!({"edits": null, "link": "t1", "text": "x"}));
|
||||
assert_eq!(issues("sketch.edit_text", json!({"edits": [{"entity": "c1", "bold": "yes"}]})), ["`bold` must be true or false"]);
|
||||
// A link that isn't text is read as left out when there is an entity, and the entity as left out when there is a link.
|
||||
ok("sketch.edit_text", json!({"link": 5, "entity": "l1"}));
|
||||
ok("sketch.edit_text", json!({"link": "t1", "entity": 5}));
|
||||
assert_eq!(issues("sketch.edit_text", json!({"link": 5, "entity": 5})), ["give `link` or `entity`"]);
|
||||
// The texts of a single edit read their own `at` as null: kept.
|
||||
ok("sketch.edit_text", json!({"link": "t1", "at": null, "height": null, "text": null}));
|
||||
// A text on a path: `at` is checked all the same, as the handler does.
|
||||
assert_eq!(issues("sketch.text", json!({"text": "x", "at": null})), [crate::cmd::AT_MUST]);
|
||||
ok("sketch.text", json!({"text": "x", "at": [0, 0], "sketch": 4}));
|
||||
ok("sketch.edit_text", json!({"link": "t1", "sketch": "S"}));
|
||||
}
|
||||
|
||||
/// Every form of every creation command runs in warn without warnings, replies as its output
|
||||
/// schema says, and a misspelt key gets its warning while the reply still matches.
|
||||
#[test]
|
||||
fn creation_replies_match_the_output_schema() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
run(&mut s, "parameters.add", json!({"name": "tall", "expression": "6 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
for points in [[[0, 0], [40, 0]], [[40, 0], [40, 30]], [[40, 30], [0, 30]]] {
|
||||
run(&mut s, "sketch.line", json!({"points": points}));
|
||||
}
|
||||
let run_ok = |s: &mut Session, id: &str, p: Value| {
|
||||
let r = run(s, id, p.clone());
|
||||
assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");
|
||||
r
|
||||
};
|
||||
let drawn = |s: &mut Session, id: &str, p: Value| {
|
||||
let r = run_ok(s, id, p);
|
||||
matches(output_schema_for::<DrawResult>(), &r);
|
||||
assert_eq!(
|
||||
r.as_object().map(|o| o.keys().cloned().collect::<std::collections::BTreeSet<_>>()),
|
||||
Some(["constraints", "created", "curves", "sketch"].map(String::from).into()),
|
||||
"{r}"
|
||||
);
|
||||
r
|
||||
};
|
||||
let near = json!([30, 10]);
|
||||
for p in [
|
||||
json!({"mid": [100, 5], "end": [110, 5]}),
|
||||
json!({"mid": [100, 15], "end": [110, 15], "construction": true}),
|
||||
json!({"mid": "l1.start", "end": [10, 10], "construction": null, "sketch": null}),
|
||||
json!({"mid": {"ref": "l1.end"}, "end": {"x": 50, "y": 10}}),
|
||||
json!({"mid": {"at": [100, 25]}, "end": [110, 25]}),
|
||||
json!({"mid": ["101 mm", "26"], "end": [111, 26]}),
|
||||
json!({"mid": "mid:l1", "end": [20, 10]}),
|
||||
json!({"mid": "on:l3:10,30", "end": [10, 20]}),
|
||||
] {
|
||||
drawn(&mut s, "sketch.line.midpoint", p);
|
||||
}
|
||||
drawn(&mut s, "sketch.arc.tangent", json!({"start": "l2.end", "end": [60, 40], "curve": "l2"}));
|
||||
drawn(&mut s, "sketch.circle.two_tangent", json!({"radius": 5, "near": near, "curves": ["l1", "l2"]}));
|
||||
drawn(&mut s, "sketch.circle.two_tangent", json!({"radius": "tall", "near": near, "curves": ["l1", "l2"]}));
|
||||
drawn(&mut s, "sketch.circle.two_tangent", json!({"diameter": 8, "near": near, "curves": ["l1", "l2"]}));
|
||||
drawn(&mut s, "sketch.circle.two_tangent", json!({"radius": 4, "diameter": "ignored", "near": near, "curves": ["l1", "l2"]}));
|
||||
drawn(&mut s, "sketch.circle.three_tangent", json!({"near": [25, 15], "curves": ["l1", "l2", "l3"]}));
|
||||
drawn(&mut s, "sketch.slot.center_point", json!({"center": [100, 100], "end": [110, 100], "width": 4}));
|
||||
drawn(&mut s, "sketch.slot.center_point", json!({"center": [100, 120], "end": [110, 120], "width": 4, "connect": false, "sketch": null}));
|
||||
for p in [
|
||||
json!({"start": [100, 0], "through": [110, 10], "end": [120, 0], "width": 2}),
|
||||
json!({"start": [130, 0], "through": [140, 10], "end": [150, 0], "width": 2, "sketch": null}),
|
||||
] {
|
||||
let r = run_ok(&mut s, "sketch.slot.arc_three_point", p);
|
||||
matches(output_schema_for::<ArcSlotResult>(), &r);
|
||||
assert!(r["centre_arc"].is_string(), "{r}");
|
||||
}
|
||||
for p in [
|
||||
json!({"center": [200, 0], "start": [210, 0], "end": [200, 10], "width": 2}),
|
||||
json!({"center": [200, 30], "start": [210, 30], "sweep": 90, "width": 2}),
|
||||
json!({"center": [200, 60], "start": [210, 60], "sweep": 90, "end": "nowhere", "width": 2}),
|
||||
] {
|
||||
let r = run_ok(&mut s, "sketch.slot.arc_center", p);
|
||||
matches(output_schema_for::<ArcSlotResult>(), &r);
|
||||
assert!(r["centre_arc"].is_string(), "{r}");
|
||||
}
|
||||
for p in [
|
||||
json!({"center": [300, 0], "major": [310, 0], "minor_radius": 4}),
|
||||
json!({"center": [300, 20], "major": [310, 20], "minor": [302, 24], "axes": false}),
|
||||
json!({"center": [300, 40], "major": [310, 40], "minor": [302, 44], "axes": null, "construction": true}),
|
||||
json!({"center": [300, 60], "major": [310, 60], "minor_radius": 4, "minor": "nowhere"}),
|
||||
json!({"center": [300, 80], "major": [310, 80], "minor_radius": "wide", "minor": {"x": 302, "y": 84}}),
|
||||
] {
|
||||
drawn(&mut s, "sketch.ellipse", p);
|
||||
}
|
||||
drawn(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 50], [10, 60], [20, 50]]}));
|
||||
drawn(&mut s, "sketch.spline.fit_point", json!({"points": [[30, 50], [40, 60], [50, 50], [45, 45]], "periodic": true, "construction": true}));
|
||||
drawn(&mut s, "sketch.spline.fit_point", json!({"points": ["l1.start", {"at": [10, 90]}, ["20 mm", 80]], "periodic": false}));
|
||||
drawn(&mut s, "sketch.spline.control_point", json!({"points": [[0, 110], [10, 120], [20, 110], [30, 120]], "periodic": false}));
|
||||
drawn(&mut s, "sketch.spline.control_point_5", json!({"points": [[0, 130], [10, 140], [20, 130], [30, 140], [40, 130], [50, 140]]}));
|
||||
drawn(&mut s, "sketch.conic", json!({"start": [0, 150], "end": [20, 150], "apex": [10, 160]}));
|
||||
drawn(&mut s, "sketch.conic", json!({"start": [30, 150], "end": [50, 150], "apex": [40, 160], "rho": 0.3, "construction": true}));
|
||||
drawn(&mut s, "sketch.blend_curve", json!({"a": "l1.start", "b": "l3.end"}));
|
||||
drawn(&mut s, "sketch.blend_curve", json!({"a": {"ref": "l1.end"}, "b": "l2.end", "continuity": " G2 "}));
|
||||
drawn(&mut s, "sketch.blend_curve", json!({"a": "l1.start", "b": "l2.end", "continuity": "", "sketch": null}));
|
||||
for (id, p) in [
|
||||
("sketch.centerline", json!({"curves": ["l1"], "value": true})),
|
||||
("sketch.centerline", json!({"curves": "l1", "value": null})),
|
||||
("sketch.infinite", json!({"curves": ["l2", "l3"], "value": true, "sketch": null})),
|
||||
("sketch.infinite", json!({"curves": "l2"})),
|
||||
] {
|
||||
let r = run_ok(&mut s, id, p);
|
||||
matches(output_schema_for::<LineTypeResult>(), &r);
|
||||
assert_eq!(
|
||||
r.as_object().map(|o| o.keys().cloned().collect::<std::collections::BTreeSet<_>>()),
|
||||
Some(["changed", "created", "sketch"].map(String::from).into()),
|
||||
"{r}"
|
||||
);
|
||||
}
|
||||
// Sketch text: its forms, and its edits.
|
||||
let text = |s: &mut Session, p: Value| {
|
||||
let r = run_ok(s, "sketch.text", p);
|
||||
matches(output_schema_for::<TextResult>(), &r);
|
||||
r
|
||||
};
|
||||
let first = text(&mut s, json!({"text": "Hello\nthere", "at": [0, 200]}));
|
||||
assert!(first["guide"].is_null() && first.get("exprs").is_none(), "{first}");
|
||||
let link = first["link"].as_str().unwrap_or_default().to_string();
|
||||
text(
|
||||
&mut s,
|
||||
json!({"text": "Styled", "at": {"x": 50, "y": 200}, "height": 8, "angle": 10, "font": "", "bold": false, "italic": true, "reverse": false, "align": "Center", "letter_spacing": 0.5, "line_spacing": 1.2, "path": ""}),
|
||||
);
|
||||
text(&mut s, json!({"text": null, "text_expression": "'A' + 'B'", "at": [0, 220], "bold": null, "align": null, "path": null}));
|
||||
let expr = text(&mut s, json!({"text": "Param", "at": ["1 + 1", 230], "height": "tall", "angle": "30 deg"}));
|
||||
// An expression that names no parameter is the number it comes to.
|
||||
assert_eq!(expr["exprs"], json!({"height": "tall"}), "{expr}");
|
||||
let on_path = text(&mut s, json!({"text": "Curve", "at": [0, 0], "path": "l1", "align": " RIGHT ", "reverse": true}));
|
||||
assert_eq!(on_path["guide"], json!("l1"), "{on_path}");
|
||||
let other = text(&mut s, json!({"text": "Other", "at": [0, 260]}));
|
||||
let outline = other["curves"][0].clone();
|
||||
for p in [
|
||||
json!({"link": link, "text": "Changed"}),
|
||||
json!({"link": link, "at": [5, 205], "height": "tall", "angle": null, "font": null, "line_spacing": null}),
|
||||
json!({"entity": outline, "italic": true, "live": false}),
|
||||
json!({"link": link, "entity": 5, "text": "Same", "edits": null}),
|
||||
json!({"edits": [{"link": link, "text": "One"}, {"entity": outline, "height": 9}], "link": 5, "text": 7, "at": "ignored"}),
|
||||
] {
|
||||
let r = run_ok(&mut s, "sketch.edit_text", p.clone());
|
||||
matches(output_schema_for::<EditTextResult>(), &r);
|
||||
assert!(r["edits"].is_array() == p.get("edits").is_some_and(|e| !e.is_null()), "{r}");
|
||||
}
|
||||
// A misspelt key runs in warn and says so; the reply still matches. Strict refuses it.
|
||||
let misspelt: [(&str, Value); 17] = [
|
||||
("sketch.line.midpoint", json!({"mid": [100, 45], "end": [110, 45], "constrution": true})),
|
||||
("sketch.arc.tangent", json!({"start": "l2.end", "end": [62, 42], "curv": "l2"})),
|
||||
("sketch.circle.two_tangent", json!({"radious": 3, "diameter": 6, "near": near, "curves": ["l1", "l2"]})),
|
||||
("sketch.circle.three_tangent", json!({"nere": 1, "near": [25, 15], "curves": ["l1", "l2", "l3"]})),
|
||||
("sketch.slot.center_point", json!({"center": [100, 140], "end": [110, 140], "widht": 1, "width": 4})),
|
||||
("sketch.slot.arc_three_point", json!({"start": [160, 0], "through": [170, 10], "end": [180, 0], "width": 2, "throgh": 1})),
|
||||
("sketch.slot.arc_center", json!({"center": [200, 90], "start": [210, 90], "sweep": 90, "width": 2, "swep": 1})),
|
||||
("sketch.ellipse", json!({"center": [300, 100], "major": [310, 100], "minor_radius": 4, "axs": false})),
|
||||
("sketch.spline.fit_point", json!({"points": [[60, 50], [70, 60], [80, 50]], "periodc": true})),
|
||||
("sketch.spline.control_point", json!({"points": [[60, 110], [70, 120], [80, 110]], "point": 1})),
|
||||
("sketch.spline.control_point_5", json!({"points": [[60, 130], [70, 140], [80, 130], [90, 140], [100, 130], [110, 140]], "constructon": 1})),
|
||||
("sketch.conic", json!({"start": [60, 150], "end": [80, 150], "apex": [70, 160], "rhoo": 0.4})),
|
||||
("sketch.blend_curve", json!({"a": "l1.start", "b": "l3.end", "continuty": "g1"})),
|
||||
("sketch.centerline", json!({"curves": ["l1"], "vlaue": true})),
|
||||
("sketch.infinite", json!({"curves": ["l2"], "vlaue": true})),
|
||||
("sketch.text", json!({"text": "Oops", "at": [0, 240], "hieght": 3})),
|
||||
("sketch.edit_text", json!({"link": link, "txt": "x"})),
|
||||
];
|
||||
for (id, p) in &misspelt {
|
||||
let r = s.execute(id, p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert!(
|
||||
r["param_warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|m| m.contains("unknown key"))),
|
||||
"{id}: {r}"
|
||||
);
|
||||
}
|
||||
s.param_check = ParamCheck::Strict;
|
||||
for (id, p) in &misspelt {
|
||||
let error = s.execute(id, p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("unknown key"), "{id}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each command's schemas describe it: a summary, and a description on every key.
|
||||
#[test]
|
||||
fn creation_schemas_are_described() {
|
||||
for id in [
|
||||
"sketch.arc.tangent",
|
||||
"sketch.blend_curve",
|
||||
"sketch.centerline",
|
||||
"sketch.circle.three_tangent",
|
||||
"sketch.circle.two_tangent",
|
||||
"sketch.conic",
|
||||
"sketch.edit_text",
|
||||
"sketch.ellipse",
|
||||
"sketch.infinite",
|
||||
"sketch.line.midpoint",
|
||||
"sketch.slot.arc_center",
|
||||
"sketch.slot.arc_three_point",
|
||||
"sketch.slot.center_point",
|
||||
"sketch.spline.control_point",
|
||||
"sketch.spline.control_point_5",
|
||||
"sketch.spline.fit_point",
|
||||
"sketch.text",
|
||||
] {
|
||||
let c = crate::cmd::find_command(id).unwrap_or_else(|| panic!("{id}"));
|
||||
let input = c.contract.map(|c| c.input_schema()).unwrap_or_else(|| panic!("{id}"));
|
||||
let input = input.as_value();
|
||||
assert!(input["description"].as_str().is_some_and(|d| d.len() > 20), "{id}: no summary");
|
||||
for (key, property) in input["properties"].as_object().into_iter().flatten() {
|
||||
assert!(property.get("description").is_some() || property.get("$ref").is_some(), "{id}: `{key}` has no description");
|
||||
}
|
||||
let output = (c.output.unwrap_or_else(|| panic!("{id}")))();
|
||||
assert!(
|
||||
output.as_value().get("properties").is_some() || output.as_value().get("oneOf").is_some() || output.as_value().get("anyOf").is_some(),
|
||||
"{id}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The schemas ask for what the handlers can't do without, and take what they read.
|
||||
#[test]
|
||||
fn the_creation_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
takes(
|
||||
input_schema_for::<TwoTangentCircleParams>(),
|
||||
&[
|
||||
(json!({"radius": 5, "near": [1, 2], "curves": ["l1", "l2"]}), true),
|
||||
(json!({"diameter": 5, "near": {"x": 1, "y": 2}, "curves": ["l1", "l2"]}), true),
|
||||
(json!({"diameter": 5, "near": [1, 2], "curves": "l1"}), false),
|
||||
(json!({"radius": "r / 2", "near": [1, 2], "curves": ["l1", "l2"], "sketch": 3}), true),
|
||||
(json!({"near": [1, 2], "curves": ["l1", "l2"]}), false),
|
||||
(json!({"radius": 5, "curves": ["l1", "l2"]}), false),
|
||||
(json!({"radius": 5, "near": [1, 2]}), false),
|
||||
(json!({"radius": 5, "near": [1, 2], "curves": ["l1"]}), false),
|
||||
(json!({"radius": 5, "near": [1, 2], "curves": ["l1", "l2", "l3"]}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ArcSlotCenterParams>(),
|
||||
&[
|
||||
(json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": 90}), true),
|
||||
(json!({"center": [0, 0], "start": [5, 0], "width": 1, "end": [0, 5]}), true),
|
||||
(json!({"center": [0, 0], "start": [5, 0], "width": 1}), false),
|
||||
(json!({"center": [0, 0], "start": [5, 0], "sweep": 90}), false),
|
||||
(json!({"center": [0, 0], "start": [5, 0], "width": 0, "sweep": 90}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<EllipseParams>(),
|
||||
&[
|
||||
(json!({"center": [0, 0], "major": [5, 0], "minor_radius": 2}), true),
|
||||
(json!({"center": [0, 0], "major": [5, 0], "minor": [1, 1], "axes": false}), true),
|
||||
(json!({"center": [0, 0], "major": [5, 0]}), false),
|
||||
(json!({"center": [0, 0], "minor_radius": 2}), false),
|
||||
(json!({"center": [0, 0], "major": [5, 0], "minor_radius": 0}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ConicParams>(),
|
||||
&[
|
||||
(json!({"start": [0, 0], "end": "l1.end", "apex": {"vertex": [1, 2, 3]}, "rho": 0.2}), true),
|
||||
(json!({"start": ["w / 2", 0], "end": {"ref": "p1"}, "apex": "mid:l1"}), true),
|
||||
(json!({"start": [0, 0], "end": [1, 0]}), false),
|
||||
(json!({"start": [0, 0], "end": [1, 0], "apex": [0, 1], "rho": 1}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<FitPointSplineParams>(),
|
||||
&[
|
||||
(json!({"points": [[0, 0], [1, 1]], "periodic": true}), true),
|
||||
(json!({"points": [[0, 0]]}), false),
|
||||
(json!({"points": vec![json!([0, 0]); 501]}), false),
|
||||
(json!({"periodic": true}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<ControlPointSplineParams>(),
|
||||
&[(json!({"points": [[0, 0], [1, 1]], "periodic": false}), true), (json!({"points": [[0, 0]]}), false)],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<BlendCurveParams>(),
|
||||
&[
|
||||
(json!({"a": "l1.end", "b": "l2.start", "continuity": "G3"}), true),
|
||||
(json!({"a": "l1.end", "b": "l2.start", "continuity": ""}), true),
|
||||
(json!({"a": "l1.end"}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<CenterlineParams>(),
|
||||
&[
|
||||
(json!({"curves": "l1"}), true),
|
||||
(json!({"curves": ["l1", "l2"], "value": false}), true),
|
||||
(json!({"curves": []}), false),
|
||||
(json!({}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<SketchTextParams>(),
|
||||
&[
|
||||
(json!({"text": "x", "at": [0, 0]}), true),
|
||||
(json!({"text_expression": "'x'", "at": ["w / 2", "5"]}), true),
|
||||
(json!({"text": "x", "at": {"x": 1, "y": 2}, "height": "h", "angle": "30 deg", "align": "CENTRE", "path": ""}), true),
|
||||
(json!({"text": "x"}), false),
|
||||
(json!({"at": [0, 0]}), false),
|
||||
(json!({"text": "x", "at": [0, 0], "height": 0}), false),
|
||||
],
|
||||
);
|
||||
takes(
|
||||
input_schema_for::<EditTextParams>(),
|
||||
&[
|
||||
(json!({"link": "j1", "text": "y"}), true),
|
||||
(json!({"entity": "n1", "at": [1, 2]}), true),
|
||||
(json!({"edits": [{"link": "j1"}, {"entity": "n1", "height": 4}], "live": false}), true),
|
||||
(json!({"edits": []}), false),
|
||||
(json!({"edits": [{"text": "y"}]}), false),
|
||||
(json!({"text": "y"}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// The point forms the types take are the forms the handlers read: `sketch.line.midpoint` snaps
|
||||
/// its points, `sketch.blend_curve` does not.
|
||||
#[test]
|
||||
fn point_forms_match_the_point_readers() {
|
||||
let refused =
|
||||
|e: &crate::EngineError| e.to_string().contains("a point must be [x, y]") || e.to_string().contains("a point's coordinates must be");
|
||||
let forms = [
|
||||
json!([1, 2]),
|
||||
json!({"x": 1, "y": 2}),
|
||||
json!([1e9, 2]),
|
||||
json!([1, "2"]),
|
||||
json!(["1 mm", "2"]),
|
||||
json!(["1", true]),
|
||||
json!([true, "2"]),
|
||||
json!(["", 2]),
|
||||
json!([" ", 2]),
|
||||
json!(["x".repeat(4097), 2]),
|
||||
json!([1e9, "2"]),
|
||||
json!([null, "2"]),
|
||||
json!([1, 2, 3]),
|
||||
json!([1]),
|
||||
json!([]),
|
||||
json!("l1.end"),
|
||||
json!(""),
|
||||
json!("mid:l1"),
|
||||
json!("vertex:1,2,3"),
|
||||
json!({"ref": "l1.end"}),
|
||||
json!({"ref": 5}),
|
||||
json!({"ref": 5, "at": [1, 2]}),
|
||||
json!({"ref": "l1.end", "at": 5}),
|
||||
json!({"at": [1, 2]}),
|
||||
json!({"at": {"x": 1, "y": 2}}),
|
||||
json!({"at": [1, "2"]}),
|
||||
json!({"at": 5}),
|
||||
json!({"vertex": [1, 2, 3]}),
|
||||
json!({"vertex": [1, 2]}),
|
||||
json!({"vertex": [1, 2], "at": [1, 2]}),
|
||||
json!({"on_edge": {"x": 1, "y": 2, "z": 3}}),
|
||||
json!({"on_edge": "x"}),
|
||||
json!({}),
|
||||
json!({"x": 1}),
|
||||
json!(5),
|
||||
json!(true),
|
||||
json!(null),
|
||||
json!([[1, 2]]),
|
||||
];
|
||||
for v in forms {
|
||||
let mut s = drawing(ParamCheck::Off);
|
||||
let snapped = s.execute("sketch.line.midpoint", &json!({"mid": v, "end": [7, 7]}));
|
||||
assert_eq!(crate::cmd::point_arg_form(&v, true).is_ok(), !snapped.as_ref().err().is_some_and(refused), "mid {v}: {snapped:?}");
|
||||
let mut s = drawing(ParamCheck::Off);
|
||||
let plain = s.execute("sketch.blend_curve", &json!({"a": v, "b": "l2.end"}));
|
||||
assert_eq!(crate::cmd::point_arg_form(&v, false).is_ok(), !plain.as_ref().err().is_some_and(refused), "a {v}: {plain:?}");
|
||||
// The type says the same.
|
||||
assert_eq!(serde_json::from_value::<super::SnapPoint>(v.clone()).is_ok(), crate::cmd::point_arg_form(&v, true).is_ok(), "{v}");
|
||||
assert_eq!(serde_json::from_value::<super::SketchPoint>(v.clone()).is_ok(), crate::cmd::point_arg_form(&v, false).is_ok(), "{v}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A text edit made `live` goes to the live runner, which the check doesn't wrap yet: it still
|
||||
/// replies as the output schema says, and says nothing about its keys.
|
||||
#[test]
|
||||
fn a_live_text_edit_replies_as_its_schema_says() {
|
||||
let mut s = drawing(ParamCheck::Warn);
|
||||
let link = text_link();
|
||||
let r = run(&mut s, "sketch.edit_text", json!({"link": link, "height": 7, "live": true, "unknown": 1}));
|
||||
matches(output_schema_for::<EditTextResult>(), &r);
|
||||
assert!(r.get("param_warnings").is_none() && r["link"] == json!(link), "{r}");
|
||||
}
|
||||
|
||||
/// The patterns that spell what a handler reads ignoring case and blanks.
|
||||
#[test]
|
||||
fn the_case_blind_patterns_say_what_the_handlers_read() {
|
||||
assert_eq!(
|
||||
super::word_pattern(&["left", "right"]),
|
||||
format!("^[{0}]*([Ll][Ee][Ff][Tt]|[Rr][Ii][Gg][Hh][Tt])[{0}]*$", crate::schema::types::whitespace_class())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
//! Contracts and result types for the commands in `cmd/sketch_import.rs`: `sketch.insert_dxf`,
|
||||
//! `sketch.insert_svg` and `sketch.export_dxf`.
|
||||
//!
|
||||
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
//! reads it and fails with the handler's message. Whether a file can be read or written, a sketch
|
||||
//! exists or a drawing has anything to import stays the handler's to check. A call with several
|
||||
//! problems may get a different one first in strict than with the check off (the check goes key
|
||||
//! by key, the handlers in their own order).
|
||||
//!
|
||||
//! Two insert keys are read only in some cases, and the contract reads them in the same cases:
|
||||
//! `path` only when `text` is not given, and of `width`, `height` and `scale` only the first one
|
||||
//! given, in that order (a `height` next to a `width`, or a `scale` next to either, is never read).
|
||||
//! A value of the wrong type that the handler reads as if the key were left out (`text: 5` next
|
||||
//! to a good `path`, a text for `scale`) is refused by the contract, as schemas.md has it: that
|
||||
//! difference is what warn and strict report.
|
||||
//! `plane` and `name` are read only when no sketch is being edited, which the check can't see
|
||||
//! (it has no session), so they take any value.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
use solidcraft_io::MAX_DRAWING_BYTES;
|
||||
|
||||
use super::check::{located, whole};
|
||||
use super::sketch_ends::SketchTarget;
|
||||
use super::types::{Point2, not_blank_pattern};
|
||||
|
||||
/// A key that, once given (`null` included), must parse as `T`, as the handler reads it.
|
||||
fn some<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {
|
||||
T::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
/// The keys the two insert commands read. See [`InsertDxfParams`] and [`InsertSvgParams`], which
|
||||
/// leave `path`, `height` and `scale` unread in the cases the handler does.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = source_required)]
|
||||
pub struct InsertDrawingKeys {
|
||||
/// The drawing itself, as text. Wins over `path`. At most 16 MiB (`MAX_DRAWING_BYTES`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<DrawingText>,
|
||||
/// The drawing file to read (not blank, fewer than 4096 UTF-8 bytes). Used when `text` is
|
||||
/// not given; ignored when it is.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "path_schema")]
|
||||
pub path: Option<DrawingPath>,
|
||||
/// An offset, in mm, [x, y]. Default: [0, 0]. With `align` "origin" it is where the file's
|
||||
/// origin goes; with "center", where the drawing's middle goes.
|
||||
#[serde(default)]
|
||||
pub at: Option<Point2>,
|
||||
/// A size factor, 1e-9 to 1e6 (a value outside is read as 1). Default: 1. Used only when
|
||||
/// neither `width` nor `height` is given.
|
||||
#[serde(default)]
|
||||
pub scale: Option<f64>,
|
||||
/// The drawing's width in mm after sizing, before rotation; the aspect ratio is kept. Wins
|
||||
/// over `height` and `scale`. The drawing must have a width.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "PositiveMm")]
|
||||
pub width: Option<PositiveMm>,
|
||||
/// The drawing's height in mm after sizing, before rotation; the aspect ratio is kept. Wins
|
||||
/// over `scale`; ignored when `width` is given. The drawing must have a height.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "PositiveMm")]
|
||||
pub height: Option<PositiveMm>,
|
||||
/// A turn in degrees, about the drawing's origin (with `align` "center": about its middle).
|
||||
/// Default: 0.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "AngleDegrees")]
|
||||
pub angle: Option<AngleDegrees>,
|
||||
/// What `at` places: the file's origin ("origin") or the drawing's middle ("center", which it
|
||||
/// then also turns and scales about). Default: origin.
|
||||
#[serde(default)]
|
||||
pub align: Option<DrawingAlign>,
|
||||
/// The distance in mm within which ends join into one point, 1e-9 to 10 (a value outside is
|
||||
/// brought inside; one that is not above 0 reads as the default). Default: 0.0001.
|
||||
#[serde(default)]
|
||||
pub tolerance: Option<f64>,
|
||||
/// Read only when no sketch is being edited: the plane of the new sketch, as `sketch.create`
|
||||
/// takes it. Default: XY. Ignored (and not checked) while a sketch is being edited.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub plane: Option<Value>,
|
||||
/// Read only when no sketch is being edited: the new sketch's name. Ignored (and not checked)
|
||||
/// while a sketch is being edited.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<Value>,
|
||||
/// The sketch to insert into: its feature id or its name. Default: the one being edited (a
|
||||
/// new one when none is).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
}
|
||||
|
||||
/// Leaves out the keys the handler never reads for this call: `path` next to a `text` that is
|
||||
/// text, `height` next to a `width`, and `scale` next to either.
|
||||
fn leave_unread(value: &mut Value) {
|
||||
let Some(keys) = value.as_object_mut() else { return };
|
||||
if keys.get("text").is_some_and(Value::is_string) {
|
||||
keys.remove("path");
|
||||
}
|
||||
if keys.contains_key("width") {
|
||||
keys.remove("height");
|
||||
}
|
||||
if keys.contains_key("width") || keys.contains_key("height") {
|
||||
keys.remove("scale");
|
||||
}
|
||||
}
|
||||
|
||||
fn read_keys<'de, D: Deserializer<'de>>(d: D) -> Result<InsertDrawingKeys, D::Error> {
|
||||
let mut value = Value::deserialize(d)?;
|
||||
leave_unread(&mut value);
|
||||
serde_path_to_error::deserialize(&value).map_err(|e| D::Error::custom(located(&e)))
|
||||
}
|
||||
|
||||
/// Insert an ASCII DXF drawing into a sketch as curves: the active sketch, or a new one when none
|
||||
/// is being edited. Give the drawing as `path` or as `text`. Blocks are expanded. It can be
|
||||
/// sized, turned and placed. Text in the drawing becomes sketch text. One undo step.
|
||||
#[derive(Debug)]
|
||||
pub struct InsertDxfParams(pub InsertDrawingKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for InsertDxfParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
read_keys(d).map(InsertDxfParams)
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for InsertDxfParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"InsertDxfParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let mut schema = InsertDrawingKeys::json_schema(generator);
|
||||
schema.insert("description".into(), INSERT_DXF.into());
|
||||
schema
|
||||
}
|
||||
}
|
||||
|
||||
const INSERT_DXF: &str = "Insert an ASCII DXF drawing into a sketch as curves: the active sketch, or a new one when none is being edited. Give the drawing as `path` or as `text`. Blocks are expanded. It can be sized, turned and placed. Text in the drawing becomes sketch text. One undo step.";
|
||||
|
||||
/// Insert an SVG drawing into a sketch as curves: the active sketch, or a new one when none is
|
||||
/// being edited. Give the drawing as `path` or as `text`. It can be sized, turned and placed.
|
||||
/// Text in the drawing becomes sketch text. One undo step.
|
||||
#[derive(Debug)]
|
||||
pub struct InsertSvgParams(pub InsertDrawingKeys);
|
||||
|
||||
impl<'de> Deserialize<'de> for InsertSvgParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
read_keys(d).map(InsertSvgParams)
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for InsertSvgParams {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"InsertSvgParams".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let mut schema = InsertDrawingKeys::json_schema(generator);
|
||||
schema.insert("description".into(), INSERT_SVG.into());
|
||||
schema
|
||||
}
|
||||
}
|
||||
|
||||
const INSERT_SVG: &str = "Insert an SVG drawing into a sketch as curves: the active sketch, or a new one when none is being edited. Give the drawing as `path` or as `text`. It can be sized, turned and placed. Text in the drawing becomes sketch text. One undo step.";
|
||||
|
||||
/// The insert commands need `path` or `text`; the handler says so when both are left out. A
|
||||
/// `path` it reads (no `text`) is not blank and under 4096 bytes; `maxLength` counts
|
||||
/// characters, so 4095 is as close as the schema gets. `height` is read only without a `width`
|
||||
/// and `scale` only without either, so their shapes apply only then, as [`leave_unread`] has it.
|
||||
fn source_required(schema: &mut Schema) {
|
||||
let read_path = serde_json::json!({"type": "string", "maxLength": 4095, "pattern": not_blank_pattern()});
|
||||
schema.insert("anyOf".into(), serde_json::json!([{"required": ["text"]}, {"required": ["path"], "properties": {"path": read_path}}]));
|
||||
let Some(props) = schema.get_mut("properties").and_then(Value::as_object_mut) else { return };
|
||||
let mut read_only_without = |key: &str| {
|
||||
let shape = props.get_mut(key).map(Value::take).unwrap_or_default();
|
||||
props.insert(key.into(), serde_json::json!({"description": shape.get("description").cloned().unwrap_or_default()}));
|
||||
shape
|
||||
};
|
||||
let height = read_only_without("height");
|
||||
let scale = read_only_without("scale");
|
||||
schema.insert(
|
||||
"allOf".into(),
|
||||
serde_json::json!([
|
||||
{"anyOf": [{"required": ["width"]}, {"properties": {"height": height}}]},
|
||||
{"anyOf": [{"required": ["width"]}, {"required": ["height"]}, {"properties": {"scale": scale}}]},
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/// `path` is checked by [`source_required`] only when it is read (no `text`).
|
||||
fn path_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({})
|
||||
}
|
||||
|
||||
/// A drawing's text, as `source_text` reads it: at most 16 MiB, or the handler's refusal.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DrawingText(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for DrawingText {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let text = String::deserialize(d)?;
|
||||
if text.len() > MAX_DRAWING_BYTES {
|
||||
return Err(D::Error::custom(whole("the drawing is too large")));
|
||||
}
|
||||
Ok(DrawingText(text))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for DrawingText {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"DrawingText".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": "string"})
|
||||
}
|
||||
}
|
||||
|
||||
/// A drawing file name, as `source_text` reads `path`: not blank and under 4096 bytes, or the
|
||||
/// handler's "give `path` or `text`" (anything but text reads as no `path`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DrawingPath(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for DrawingPath {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) if !s.trim().is_empty() && s.len() < 4096 => Ok(DrawingPath(s)),
|
||||
_ => Err(D::Error::custom(whole("give `path` or `text`"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A size in mm above 0, as the insert commands' `width` and `height` are read.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PositiveMm(pub f64);
|
||||
|
||||
/// The message the insert commands give for `width` or `height`: the check puts the key first.
|
||||
const POSITIVE_MM: &str = "must be a positive number (mm)";
|
||||
|
||||
impl<'de> Deserialize<'de> for PositiveMm {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
Value::deserialize(d)?.as_f64().filter(|w| w.is_finite() && *w > 0.0).map(PositiveMm).ok_or_else(|| D::Error::custom(POSITIVE_MM))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for PositiveMm {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"PositiveMm".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "A size in mm, above 0.", "type": "number", "exclusiveMinimum": 0})
|
||||
}
|
||||
}
|
||||
|
||||
/// An angle in degrees as `angle` is read: a number, whatever its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct AngleDegrees(pub f64);
|
||||
|
||||
impl<'de> Deserialize<'de> for AngleDegrees {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
Value::deserialize(d)?.as_f64().filter(|a| a.is_finite()).map(AngleDegrees).ok_or_else(|| D::Error::custom("must be a number (degrees)"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for AngleDegrees {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"AngleDegrees".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "An angle in degrees.", "type": "number"})
|
||||
}
|
||||
}
|
||||
|
||||
/// What an insert's `at` places, as `align` is read (the words are case-sensitive).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum DrawingAlign {
|
||||
/// `at` is where the file's origin goes.
|
||||
Origin,
|
||||
/// `at` is where the drawing's middle goes, and it turns and scales about it.
|
||||
Center,
|
||||
}
|
||||
|
||||
impl JsonSchema for DrawingAlign {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"DrawingAlign".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "What `at` places: \"origin\" (the file's origin goes there) or \"center\" (the drawing's middle goes there, and it turns and scales about it). Lower case only.",
|
||||
"type": "string",
|
||||
"enum": ["origin", "center"]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for DrawingAlign {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)?.as_str() {
|
||||
Some("origin") => Ok(DrawingAlign::Origin),
|
||||
Some("center") => Ok(DrawingAlign::Center),
|
||||
_ => Err(D::Error::custom("must be \"origin\" or \"center\"")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `sketch.insert_dxf` and `sketch.insert_svg` return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DrawingInserted {
|
||||
/// The sketch the drawing went into, by feature id.
|
||||
pub sketch: u64,
|
||||
/// The new sketch's id when no sketch was being edited and one was made; else null.
|
||||
pub created_sketch: Option<u64>,
|
||||
/// How many curves were added.
|
||||
pub curves: usize,
|
||||
/// How many sketch texts were added.
|
||||
pub texts: usize,
|
||||
/// The sketch's solve afterwards; null when it was not solved.
|
||||
pub info: Option<SketchSolve>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A sketch's solve, as the sketch commands report it.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchSolve {
|
||||
/// Whether the solve kept the sketch's orientation.
|
||||
pub solved: bool,
|
||||
/// The degrees of freedom left (0 = fully constrained).
|
||||
pub dof: usize,
|
||||
}
|
||||
|
||||
/// Save a sketch's curves as an ASCII DXF: to the file `path`, or, without it, as text in the
|
||||
/// reply. Construction curves are left out; splines and other curves are written as line
|
||||
/// segments.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ExportDxfParams {
|
||||
/// The sketch: its feature id or its name. Default: the one being edited.
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchTarget>,
|
||||
/// The file to write. Default (also when blank): none, and the DXF text is returned.
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
/// The drawing's units (any case): `design` (the design's length unit), `mm`, `in` or
|
||||
/// `inch`, `cm`, `m` or `ft`. Default: mm.
|
||||
#[serde(default, deserialize_with = "dxf_units")]
|
||||
#[schemars(schema_with = "dxf_units_schema")]
|
||||
pub units: Option<String>,
|
||||
/// The layer of the profiles (blank: the default). Default: `0`.
|
||||
#[serde(default, deserialize_with = "dxf_layer")]
|
||||
#[schemars(schema_with = "dxf_layer_schema")]
|
||||
pub layer: Option<String>,
|
||||
/// `single` (any case, the default): everything on `layer`; `roles`: outer loops on
|
||||
/// `OUTLINE` and holes on `CUT`.
|
||||
#[serde(default, deserialize_with = "dxf_layers")]
|
||||
#[schemars(schema_with = "dxf_layers_schema")]
|
||||
pub layers: Option<String>,
|
||||
/// `true` writes closed loops as LWPOLYLINE with arc bulges. Default: false (LINE and ARC).
|
||||
#[serde(default, deserialize_with = "dxf_join")]
|
||||
pub join: Option<bool>,
|
||||
}
|
||||
|
||||
/// The units `sketch.export_dxf` takes, in lower case (the handler reads them in any case).
|
||||
const DXF_UNITS: [&str; 7] = ["design", "mm", "in", "inch", "cm", "m", "ft"];
|
||||
|
||||
fn dxf_units<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
match Option::<Value>::deserialize(d)? {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(units)) => {
|
||||
let lower = units.to_ascii_lowercase();
|
||||
if DXF_UNITS.contains(&lower.as_str()) {
|
||||
Ok(Some(lower))
|
||||
} else {
|
||||
Err(D::Error::custom(whole(format!("unsupported unit `{lower}` (use \"design\", \"mm\", \"in\", \"cm\", \"m\", or \"ft\")"))))
|
||||
}
|
||||
}
|
||||
Some(_) => Err(D::Error::custom(whole("`units` must be a string"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn dxf_units_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": ["string", "null"], "description": "design, mm, in, inch, cm, m or ft, in any case. Default: mm."})
|
||||
}
|
||||
|
||||
fn dxf_layer<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
match Option::<Value>::deserialize(d)? {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(layer)) => Ok(Some(layer)),
|
||||
Some(_) => Err(D::Error::custom(whole("`layer` must be a string"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn dxf_layer_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": ["string", "null"], "description": "The profiles' layer (blank: the default). Default: 0."})
|
||||
}
|
||||
|
||||
fn dxf_layers<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
match Option::<Value>::deserialize(d)? {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(layers)) if ["single", "roles"].contains(&layers.to_ascii_lowercase().as_str()) => Ok(Some(layers.to_ascii_lowercase())),
|
||||
Some(_) => Err(D::Error::custom(whole("`layers` must be \"single\" or \"roles\""))),
|
||||
}
|
||||
}
|
||||
|
||||
fn dxf_layers_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": ["string", "null"], "description": "single or roles, in any case. Default: single."})
|
||||
}
|
||||
|
||||
fn dxf_join<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
|
||||
match Option::<Value>::deserialize(d)? {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Bool(join)) => Ok(Some(join)),
|
||||
Some(_) => Err(D::Error::custom(whole("`join` must be true or false"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// What `sketch.export_dxf` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ExportDxfResult {
|
||||
#[serde(flatten)]
|
||||
pub exported: DxfExported,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Where the DXF went.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum DxfExported {
|
||||
/// With a `path`: the file was written.
|
||||
Written {
|
||||
/// The file written, as given.
|
||||
path: String,
|
||||
/// How many entities it holds.
|
||||
entities: usize,
|
||||
},
|
||||
/// Without one: the DXF as text.
|
||||
Text {
|
||||
/// The DXF file's text.
|
||||
dxf: String,
|
||||
/// How many entities it holds.
|
||||
entities: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_import_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,313 @@
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_io::MAX_DRAWING_BYTES;
|
||||
|
||||
use super::{DrawingInserted, ExportDxfParams, ExportDxfResult, InsertDxfParams, InsertSvgParams};
|
||||
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};
|
||||
|
||||
/// A 30 x 20 rectangle as DXF lines.
|
||||
const DXF: &str = "0\nSECTION\n2\nENTITIES\n0\nLINE\n10\n0\n20\n0\n11\n30\n21\n0\n0\nLINE\n10\n30\n20\n0\n11\n30\n21\n20\n0\nLINE\n10\n30\n20\n20\n11\n0\n21\n20\n0\nLINE\n10\n0\n20\n20\n11\n0\n21\n0\n0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
const SVG: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="20mm" height="10mm" viewBox="0 0 20 10"><rect x="0" y="0" width="20" height="10"/><text x="2" y="5" font-size="3">Hi</text></svg>"#;
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-12508-{tag}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
let insert = ["align", "angle", "at", "height", "name", "path", "plane", "scale", "sketch", "text", "tolerance", "width"];
|
||||
assert_keys(input_schema_for::<InsertDxfParams>(), &insert);
|
||||
assert_keys(input_schema_for::<InsertSvgParams>(), &insert);
|
||||
assert_keys(input_schema_for::<ExportDxfParams>(), &["join", "layer", "layers", "path", "sketch", "units"]);
|
||||
}
|
||||
|
||||
/// Strict gives the handlers' messages for the calls they refuse for a key (a missing `path` and
|
||||
/// `text` included: the handler's words, not "is required"). The session has a sketch being edited.
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
let too_big = "x".repeat(MAX_DRAWING_BYTES + 1);
|
||||
let mut cases: Vec<(&str, Value)> = vec![
|
||||
("sketch.insert_dxf", json!({})),
|
||||
("sketch.insert_dxf", json!({"path": ""})),
|
||||
("sketch.insert_dxf", json!({"path": " "})),
|
||||
("sketch.insert_dxf", json!({"path": 5})),
|
||||
("sketch.insert_dxf", json!({"path": null})),
|
||||
("sketch.insert_dxf", json!({"path": "x".repeat(4096)})),
|
||||
("sketch.insert_dxf", json!({"text": too_big})),
|
||||
("sketch.insert_svg", json!({})),
|
||||
("sketch.insert_svg", json!({"path": " "})),
|
||||
("sketch.insert_svg", json!({"text": null})),
|
||||
("sketch.export_dxf", json!({"sketch": true})),
|
||||
("sketch.export_dxf", json!({"sketch": [1]})),
|
||||
("sketch.export_dxf", json!({"sketch": -1})),
|
||||
("sketch.export_dxf", json!({"sketch": 1.5})),
|
||||
];
|
||||
for (id, text) in [("sketch.insert_dxf", DXF), ("sketch.insert_svg", SVG)] {
|
||||
for extra in [
|
||||
json!({"width": 0}),
|
||||
json!({"width": -2}),
|
||||
json!({"width": null}),
|
||||
json!({"width": "wide"}),
|
||||
json!({"width": [1]}),
|
||||
json!({"height": 0}),
|
||||
json!({"height": null}),
|
||||
json!({"height": true}),
|
||||
json!({"angle": "x"}),
|
||||
json!({"angle": null}),
|
||||
json!({"angle": {}}),
|
||||
json!({"align": "left"}),
|
||||
json!({"align": "Center"}),
|
||||
json!({"align": ""}),
|
||||
json!({"sketch": true}),
|
||||
json!({"sketch": null, "width": 0}),
|
||||
json!({"sketch": [1]}),
|
||||
json!({"sketch": 1.5}),
|
||||
] {
|
||||
let mut p = json!({"text": text});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
cases.push((id, p));
|
||||
}
|
||||
}
|
||||
assert_strict_keeps_todays_errors(&cases);
|
||||
}
|
||||
|
||||
/// The same refusals for a sketch that is named but doesn't exist, a width the drawing can't
|
||||
/// give (a drawing with no width to size is refused by the handler alone), and the export's
|
||||
/// options, which the handler reads only once a sketch is being edited.
|
||||
#[test]
|
||||
fn strict_keeps_the_handlers_own_refusals() {
|
||||
// A vertical line has no width to size.
|
||||
let vertical = "0\nSECTION\n2\nENTITIES\n0\nLINE\n10\n0\n20\n0\n11\n0\n21\n9\n0\nENDSEC\n0\nEOF\n";
|
||||
for (id, p) in [
|
||||
("sketch.insert_dxf", json!({"text": DXF, "sketch": "Nope"})),
|
||||
("sketch.insert_dxf", json!({"text": DXF, "sketch": 9999})),
|
||||
("sketch.insert_dxf", json!({"text": vertical, "width": 10})),
|
||||
("sketch.insert_dxf", json!({"text": "0\nEOF\n"})),
|
||||
("sketch.export_dxf", json!({"sketch": "Nope"})),
|
||||
("sketch.export_dxf", json!({"sketch": 9999})),
|
||||
("sketch.export_dxf", json!({"units": 5})),
|
||||
("sketch.export_dxf", json!({"units": "Yard"})),
|
||||
("sketch.export_dxf", json!({"layer": 1})),
|
||||
("sketch.export_dxf", json!({"layers": "all"})),
|
||||
("sketch.export_dxf", json!({"layers": true})),
|
||||
("sketch.export_dxf", json!({"join": "yes"})),
|
||||
] {
|
||||
let error = |level: ParamCheck| {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
||||
s.execute(id, &p).err().map(|e| e.to_string())
|
||||
};
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some(), "{id} {p} should fail today");
|
||||
assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The types read each key as the handler does: keys it never reads in a call are not read by the
|
||||
/// contract either, and the ones it reads fail with its words.
|
||||
#[test]
|
||||
fn the_types_read_like_the_handler() {
|
||||
let reads = |p: Value| serde_json::from_value::<InsertDxfParams>(p).is_ok();
|
||||
let issues = |p: Value| crate::schema::issues("sketch.insert_svg", &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
|
||||
// `path` is not read when `text` is given; `height` not when `width` is; `scale` not when
|
||||
// either is.
|
||||
assert!(reads(json!({"text": "x", "path": 5})) && reads(json!({"text": "x", "path": ""})));
|
||||
assert!(reads(json!({"width": 5, "height": "x", "scale": "y"})) && reads(json!({"width": 5, "height": null})));
|
||||
assert!(reads(json!({"height": 5, "scale": "y"})) && reads(json!({"height": 5, "scale": null})));
|
||||
assert!(reads(json!({"path": "a.dxf", "scale": 2, "tolerance": 0.01, "at": [1, 2], "angle": 90, "align": "center"})));
|
||||
assert!(reads(json!({"text": "x", "at": {"x": 1, "y": 2}, "angle": 720.5, "width": 1e12, "scale": 0, "tolerance": -1})));
|
||||
// They are read when the handler reads them.
|
||||
// Stricter than the handler, which reads a `text` that isn't text as left out.
|
||||
assert!(!reads(json!({"text": 5, "path": "a.dxf"})) && !reads(json!({"path": "a.dxf", "scale": "y"})));
|
||||
assert!(!reads(json!({"path": ""})) && !reads(json!({"path": 5, "scale": 1})));
|
||||
assert!(!reads(json!({"text": "x", "height": 0})) && !reads(json!({"text": "x", "height": "x", "scale": 2})));
|
||||
assert!(!reads(json!({"text": "x", "width": null, "height": 5})) && !reads(json!({"text": "x", "scale": "y", "width": 0})));
|
||||
// Only while no sketch is being edited does `plane` or `name` matter, which the check can't
|
||||
// see: they take anything.
|
||||
assert!(reads(json!({"text": "x", "plane": 5, "name": [1]})) && reads(json!({"text": "x", "plane": null, "name": null})));
|
||||
assert_eq!(issues(json!({"text": "x", "width": 0})), ["`width` must be a positive number (mm)"]);
|
||||
assert_eq!(issues(json!({"text": "x", "height": -1})), ["`height` must be a positive number (mm)"]);
|
||||
assert_eq!(issues(json!({"text": "x", "angle": "1"})), ["`angle` must be a number (degrees)"]);
|
||||
assert_eq!(issues(json!({"text": "x", "align": "left"})), ["`align` must be \"origin\" or \"center\""]);
|
||||
assert_eq!(issues(json!({"path": " "})), ["give `path` or `text`"]);
|
||||
assert_eq!(issues(json!({"text": "x", "sketch": true})), ["`sketch` must be an id or a name"]);
|
||||
assert_eq!(issues(json!({"text": "x", "wdth": 5})), ["unknown key `wdth`; did you mean `width`?"]);
|
||||
assert!(issues(json!({"text": "x", "width": 5, "height": "x", "path": 5})).is_empty());
|
||||
let export = |p: Value| serde_json::from_value::<ExportDxfParams>(p).is_ok();
|
||||
assert!(export(json!({})) && export(json!({"sketch": null, "path": null})) && export(json!({"sketch": "S", "path": ""})));
|
||||
assert!(export(json!({"sketch": 3, "path": "a.dxf"})) && !export(json!({"sketch": true})) && !export(json!({"path": 5})));
|
||||
}
|
||||
|
||||
/// What the schemas take: a drawing from `path` or `text`, and the keys' own shapes.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(schema, schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
for schema in [input_schema_for::<InsertDxfParams>(), input_schema_for::<InsertSvgParams>()] {
|
||||
takes(
|
||||
schema,
|
||||
&[
|
||||
(json!({"text": "x"}), true),
|
||||
(json!({"path": "a.svg", "at": [1, 2], "scale": 2, "angle": 45, "align": "center", "tolerance": 0.01}), true),
|
||||
(json!({"text": "x", "width": 40, "plane": "XZ", "name": "Logo", "sketch": "Sketch1"}), true),
|
||||
(json!({"text": "x", "plane": {"origin": [0, 0, 1], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "sketch": 4}), true),
|
||||
(json!({}), false),
|
||||
(json!({"width": 40}), false),
|
||||
(json!({"text": "x", "width": 0}), false),
|
||||
(json!({"text": "x", "height": -1}), false),
|
||||
(json!({"text": "x", "angle": "x"}), false),
|
||||
(json!({"text": "x", "align": "left"}), false),
|
||||
(json!({"text": "x", "at": [1]}), false),
|
||||
(json!({"text": "x", "wdth": 5}), false),
|
||||
(json!({"path": "x".repeat(4096)}), false),
|
||||
(json!({"text": "x", "path": " "}), true),
|
||||
// Unread keys take anything, as in the handler; read ones keep their shapes.
|
||||
(json!({"text": "x", "path": 5}), true),
|
||||
(json!({"text": "x", "width": 5, "height": -1}), true),
|
||||
(json!({"text": "x", "width": 5, "scale": "y"}), true),
|
||||
(json!({"text": "x", "height": 5, "scale": "y"}), true),
|
||||
(json!({"path": 5}), false),
|
||||
(json!({"text": "x", "height": "x", "scale": 2}), false),
|
||||
(json!({"text": "x", "scale": "y"}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
// A `path` read without `text` is not blank (`conforms` doesn't check patterns).
|
||||
for schema in [input_schema_for::<InsertDxfParams>(), input_schema_for::<InsertSvgParams>()] {
|
||||
let read_path = &schema.as_value()["anyOf"][1]["properties"]["path"];
|
||||
assert_eq!(read_path["pattern"], json!(crate::schema::types::not_blank_pattern()));
|
||||
}
|
||||
takes(
|
||||
input_schema_for::<ExportDxfParams>(),
|
||||
&[
|
||||
(json!({}), true),
|
||||
(json!({"sketch": "S", "path": "a.dxf"}), true),
|
||||
(json!({"sketch": 2}), true),
|
||||
(json!({"sketch": true}), false),
|
||||
(json!({"file": "a.dxf"}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
fn matches(schema: schemars::Schema, r: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
}
|
||||
|
||||
/// Every form of the three commands replies as its output schema says, in Warn without warnings;
|
||||
/// the replies carry the keys they always had; a misspelt key gets its warning and the reply still
|
||||
/// matches, and strict refuses it.
|
||||
#[test]
|
||||
fn replies_match_the_output_schema() {
|
||||
let dir = temp_dir("replies");
|
||||
let svg_file = dir.join("plate.svg");
|
||||
let dxf_file = dir.join("plate.dxf");
|
||||
std::fs::write(&svg_file, SVG).unwrap();
|
||||
std::fs::write(&dxf_file, DXF).unwrap();
|
||||
let (svg_path, dxf_path) = (svg_file.to_string_lossy().into_owned(), dxf_file.to_string_lossy().into_owned());
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let run = |s: &mut Session, id: &str, p: Value| {
|
||||
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");
|
||||
r
|
||||
};
|
||||
// The session adds `created` (the ids a sketch command made) to every `sketch.*` reply, outside
|
||||
// the handlers; it is not part of what they build.
|
||||
let keys = |r: &Value| {
|
||||
r.as_object().map(|o| o.keys().filter(|k| *k != "created").cloned().collect::<std::collections::BTreeSet<_>>()).unwrap_or_default()
|
||||
};
|
||||
let insert_keys: std::collections::BTreeSet<String> = ["created_sketch", "curves", "info", "sketch", "texts"].map(String::from).into();
|
||||
|
||||
// With no sketch being edited: a new one is made, on the plane and with the name given.
|
||||
let r = run(&mut s, "sketch.insert_dxf", json!({"text": DXF, "plane": "XZ", "name": "Plate", "at": [5, 5]}));
|
||||
matches(output_schema_for::<DrawingInserted>(), &r);
|
||||
assert_eq!(keys(&r), insert_keys, "{r}");
|
||||
assert_eq!((r["curves"].as_u64(), r["texts"].as_u64()), (Some(4), Some(0)), "{r}");
|
||||
assert_eq!(r["created_sketch"], r["sketch"], "{r}");
|
||||
// Exactly what the handler returned before it built its reply from the type.
|
||||
let mut handler_reply = r.clone();
|
||||
handler_reply.as_object_mut().unwrap().remove("created");
|
||||
assert_eq!(
|
||||
handler_reply,
|
||||
json!({"sketch": r["sketch"], "created_sketch": r["sketch"], "curves": 4, "texts": 0, "info": {"solved": true, "dof": 8}})
|
||||
);
|
||||
assert!(r["info"]["solved"].is_boolean() && r["info"]["dof"].is_u64(), "{r}");
|
||||
// With one: into it, and `plane` and `name` (of any kind) are not read.
|
||||
let id = s.active_sketch.unwrap();
|
||||
for p in [
|
||||
json!({"text": DXF, "path": 5, "plane": 7, "name": [1]}),
|
||||
json!({"text": DXF, "width": 60, "height": "x", "scale": "y", "angle": 90, "align": "center", "at": {"x": 1, "y": 2}}),
|
||||
json!({"text": DXF, "height": 10, "scale": "y", "tolerance": 0.01}),
|
||||
json!({"text": DXF, "scale": 2, "align": "origin", "sketch": id}),
|
||||
json!({"text": DXF, "sketch": s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default()}),
|
||||
json!({"path": dxf_path, "text": null, "sketch": null}),
|
||||
] {
|
||||
let r = run(&mut s, "sketch.insert_dxf", p);
|
||||
matches(output_schema_for::<DrawingInserted>(), &r);
|
||||
assert_eq!(keys(&r), insert_keys);
|
||||
assert_eq!((r["sketch"].as_u64(), r["created_sketch"].clone(), r["curves"].as_u64()), (Some(id), Value::Null, Some(4)), "{r}");
|
||||
}
|
||||
let r = run(&mut s, "sketch.insert_svg", json!({"text": SVG, "angle": 15}));
|
||||
matches(output_schema_for::<DrawingInserted>(), &r);
|
||||
assert_eq!((r["curves"].as_u64(), r["texts"].as_u64()), (Some(4), Some(1)), "{r}");
|
||||
let r = run(&mut s, "sketch.insert_svg", json!({"path": svg_path, "width": 40, "align": "center", "at": [10, 10]}));
|
||||
assert_eq!(r["texts"], 1, "{r}");
|
||||
s.execute("sketch.finish", &json!({})).unwrap();
|
||||
let r = run(&mut s, "sketch.insert_svg", json!({"path": svg_path, "plane": "YZ"}));
|
||||
matches(output_schema_for::<DrawingInserted>(), &r);
|
||||
assert_ne!(r["created_sketch"], Value::Null, "{r}");
|
||||
s.execute("sketch.finish", &json!({})).unwrap();
|
||||
|
||||
// Export: the text, or a file.
|
||||
let r = run(&mut s, "sketch.export_dxf", json!({"sketch": id}));
|
||||
matches(output_schema_for::<ExportDxfResult>(), &r);
|
||||
assert_eq!(keys(&r), ["dxf", "entities"].map(String::from).into(), "{r}");
|
||||
assert!(r["dxf"].as_str().is_some_and(|t| t.contains("ENTITIES")), "{r}");
|
||||
assert!(r["entities"].as_u64().is_some_and(|n| n >= 4), "{r}");
|
||||
let out = dir.join("out.dxf");
|
||||
let out_path = out.to_string_lossy().into_owned();
|
||||
let r = run(&mut s, "sketch.export_dxf", json!({"sketch": id, "path": out_path}));
|
||||
matches(output_schema_for::<ExportDxfResult>(), &r);
|
||||
assert_eq!(r["path"], json!(out_path), "{r}");
|
||||
assert_eq!(keys(&r), ["entities", "path"].map(String::from).into(), "{r}");
|
||||
assert!(std::fs::read_to_string(&out).unwrap().contains("ENTITIES"));
|
||||
// A blank `path` and a null `sketch` read as left out.
|
||||
s.execute("sketch.edit", &json!({"sketch": id})).unwrap();
|
||||
let r = run(&mut s, "sketch.export_dxf", json!({"sketch": null, "path": " "}));
|
||||
assert!(r.get("dxf").is_some(), "{r}");
|
||||
matches(output_schema_for::<ExportDxfResult>(), &r);
|
||||
// The units and layer options, in any case; null and a blank layer read as left out.
|
||||
for p in [
|
||||
json!({"units": "IN", "layer": "PART"}),
|
||||
json!({"units": "design", "layers": "Roles"}),
|
||||
json!({"join": true, "layer": " "}),
|
||||
json!({"units": null, "layer": null, "layers": null, "join": null}),
|
||||
] {
|
||||
let r = run(&mut s, "sketch.export_dxf", p);
|
||||
matches(output_schema_for::<ExportDxfResult>(), &r);
|
||||
assert_eq!(keys(&r), ["dxf", "entities"].map(String::from).into(), "{r}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
// A misspelt key runs in warn and says so; the reply still matches. Strict refuses it.
|
||||
let p = json!({"text": DXF, "wdth": 5});
|
||||
let r = s.execute("sketch.insert_dxf", &p).unwrap();
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| w.iter().any(|m| m.as_str().is_some_and(|m| m.contains("`wdth`")))), "{r}");
|
||||
matches(output_schema_for::<DrawingInserted>(), &r);
|
||||
let r = s.execute("sketch.export_dxf", &json!({"pth": "a.dxf"})).unwrap();
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");
|
||||
matches(output_schema_for::<ExportDxfResult>(), &r);
|
||||
let r = s.execute("sketch.insert_svg", &json!({"text": SVG, "angel": 5})).unwrap();
|
||||
assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");
|
||||
s.param_check = ParamCheck::Strict;
|
||||
let error = s.execute("sketch.insert_dxf", &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(error.contains("`wdth`") && error.contains("did you mean `width`"), "{error}");
|
||||
}
|
||||
@@ -0,0 +1,767 @@
|
||||
//! Contracts and result types for the commands in `cmd/sketch_project.rs`: `sketch.project`,
|
||||
//! `sketch.intersect`, `sketch.include_3d`, `sketch.project_to_surface`,
|
||||
//! `sketch.intersection_curve`, `sketch.spun_profile`, `sketch.isoparametric_curve`,
|
||||
//! `sketch.fit_curves_to_section`, `sketch.break_link` and `sketch.auto_project`.
|
||||
//!
|
||||
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
|
||||
//! reads it and fails with the handler's message. What only the design can tell (a body, sketch or
|
||||
//! curve that exists, an axis name, whether a reference projects to anything) stays the handler's
|
||||
//! to check: a reference given as text, or as an axis name, passes here and is looked up there, and
|
||||
//! so does a reference to a sketch, whose `curve` or `point` the handler checks once it has found
|
||||
//! the sketch.
|
||||
//! A call with several problems may get a different one first in strict than with the check off
|
||||
//! (the check goes key by key, the handlers in their own order).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::check::whole;
|
||||
use super::motion::require;
|
||||
use super::types::Point3;
|
||||
use crate::cmd::{RefForm, ref_form};
|
||||
use crate::params;
|
||||
|
||||
/// What a reference to model geometry may look like, for the descriptions.
|
||||
const REF_FORMS: &str = "a reference: `{\"edge\": [x, y, z], \"body\"?}` (the edge through that point), `{\"face\": [x, y, z], \"body\"?}` (the edges of the face), `{\"vertex\": [x, y, z], \"body\"?}`, `{\"body\": name}` (its silhouette or outline), `{\"sketch\": id or name, \"curve\": id}` or `{\"sketch\": id or name, \"point\": id}` (a curve or point of another sketch), `\"origin\"` or `{\"origin\": …}`, `{\"axis\": \"X\"|\"Y\"|\"Z\"|a construction axis's name}`, `{\"plane\": \"XY\"|\"XZ\"|\"YZ\"|a plane's name}`; text alone is `origin`, X, Y, Z (any case) or a body's name";
|
||||
|
||||
/// The most references one `refs` takes into account: the handler reads no more.
|
||||
const MAX_REFS: usize = 1000;
|
||||
|
||||
/// Whether text is what `cmd/sketch_project.rs` reads as the origin or an origin axis, which is
|
||||
/// settled without the design; any other text may be a body's name.
|
||||
fn is_origin_or_axis(name: &str) -> bool {
|
||||
["origin", "x", "y", "z"].iter().any(|word| name.eq_ignore_ascii_case(word))
|
||||
}
|
||||
|
||||
/// The handler's message for a reference that says nothing a design could be asked about, in its
|
||||
/// own words, or `None` when the form is fine. A sketch reference with neither `curve` nor `point`
|
||||
/// is fine here: the handler refuses it only once it has looked the sketch up, and says "no sketch"
|
||||
/// first when there is none.
|
||||
fn ref_problem(v: &Value) -> Option<String> {
|
||||
ref_form(v).err()
|
||||
}
|
||||
|
||||
/// One reference of `sketch.project`, `sketch.intersect` and `sketch.include_3d`, kept as given
|
||||
/// for the handler.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ProjectRef(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for ProjectRef {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
match ref_problem(&v) {
|
||||
Some(why) => Err(D::Error::custom(whole(why))),
|
||||
None => Ok(ProjectRef(v)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ProjectRef {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ProjectRef".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let point = generator.subschema_for::<Point3>();
|
||||
let with_body = |key: &str| {
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": {key: point, "body": {"type": "string", "description": "The body's name. Default: any body. Text only: the handler reads anything else as left out, which the schema does not take."}},
|
||||
"required": [key]
|
||||
})
|
||||
};
|
||||
json_schema!({
|
||||
"description": REF_FORMS,
|
||||
"anyOf": [
|
||||
{"type": "string"},
|
||||
with_body("edge"),
|
||||
with_body("face"),
|
||||
with_body("vertex"),
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"sketch": {"type": ["number", "string"]}, "curve": {"type": "string"}},
|
||||
"required": ["sketch", "curve"]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"sketch": {"type": ["number", "string"]}, "point": {"type": "string"}},
|
||||
"required": ["sketch", "point"]
|
||||
},
|
||||
{"type": "object", "properties": {"body": {"type": "string"}}, "required": ["body"]},
|
||||
{"type": "object", "properties": {"axis": {"type": "string"}}, "required": ["axis"]},
|
||||
{"type": "object", "properties": {"plane": {"type": "string"}}, "required": ["plane"]},
|
||||
{"type": "object", "required": ["origin"]}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The references of `refs` (or `ref`): a list, or one reference. Only the first 1000 of a list
|
||||
/// count, as the handler reads no more.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ProjectRefs(pub Vec<Value>);
|
||||
|
||||
impl ProjectRefs {
|
||||
/// The references `v` lists, or the handler's message for them. A value that is not a list is
|
||||
/// one reference.
|
||||
fn read(v: &Value) -> Result<ProjectRefs, String> {
|
||||
let list: Vec<&Value> = match v {
|
||||
Value::Array(a) => a.iter().take(MAX_REFS).collect(),
|
||||
one => vec![one],
|
||||
};
|
||||
if list.is_empty() {
|
||||
return Err("`refs` is empty".into());
|
||||
}
|
||||
if let Some(why) = list.iter().find_map(|r| ref_problem(r)) {
|
||||
return Err(why);
|
||||
}
|
||||
Ok(ProjectRefs(list.into_iter().cloned().collect()))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for ProjectRefs {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"ProjectRefs".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let one = generator.subschema_for::<ProjectRef>();
|
||||
json_schema!({
|
||||
"description": "One reference or a non-empty list of them (the first 1000 count).",
|
||||
"anyOf": [one, {"type": "array", "items": one, "minItems": 1}]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `refs`, or `ref` when `refs` is absent (the handler reads `ref` only then, `null` included).
|
||||
fn read_refs(o: &Map<String, Value>) -> Result<(Option<ProjectRefs>, Option<ProjectRefs>), String> {
|
||||
match (o.get("refs"), o.get("ref")) {
|
||||
(Some(v), _) => Ok((Some(ProjectRefs::read(v)?), None)),
|
||||
(None, Some(v)) => Ok((None, Some(ProjectRefs::read(v)?))),
|
||||
(None, None) => Ok((None, None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `projection_link`: a boolean, and `null` is refused too (the message is the same for both
|
||||
/// commands that take it).
|
||||
fn read_link_flag(o: &Map<String, Value>) -> Result<Option<bool>, String> {
|
||||
match o.get("projection_link") {
|
||||
None => Ok(None),
|
||||
Some(Value::Bool(b)) => Ok(Some(*b)),
|
||||
Some(_) => Err("`projection_link` must be a boolean".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `refs` and `ref` are one of them required: left out, the handler refuses with its own message.
|
||||
fn refs_required(schema: &mut Schema) {
|
||||
schema.insert("anyOf".into(), json!([{"required": ["refs"]}, {"required": ["ref"]}]));
|
||||
}
|
||||
|
||||
/// Bring model edges, faces, bodies, other sketches' curves and points, the origin, an axis or a
|
||||
/// plane into the active sketch as linked reference geometry: fixed, drawn purple and updated
|
||||
/// when the upstream geometry changes. What the sketch already shows (the border of its face, an
|
||||
/// edge projected before) is skipped and listed in `already_projected`; a call that adds nothing is
|
||||
/// refused. One undo step.
|
||||
#[derive(Debug, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = refs_required)]
|
||||
pub struct ProjectParams {
|
||||
/// What to project: one reference or a list.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ProjectRefs")]
|
||||
pub refs: Option<ProjectRefs>,
|
||||
/// The same as `refs`, used only when `refs` is not given.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(rename = "ref", with = "ProjectRefs")]
|
||||
pub reference: Option<ProjectRefs>,
|
||||
/// Keep the geometry linked to its source (true), or make it normal sketch geometry at once
|
||||
/// (false: the replies' `link` is then null). Default: true.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub projection_link: Option<bool>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ProjectParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let o = Map::<String, Value>::deserialize(d)?;
|
||||
// The handler reads `projection_link` before the references.
|
||||
let projection_link = read_link_flag(&o).map_err(|why| D::Error::custom(whole(why)))?;
|
||||
let (refs, reference) = read_refs(&o).map_err(|why| D::Error::custom(whole(why)))?;
|
||||
Ok(ProjectParams { refs, reference, projection_link })
|
||||
}
|
||||
}
|
||||
|
||||
/// Intersect the sketch plane with model bodies, faces, edges and other sketches' curves, and
|
||||
/// bring the section curves (or points) into the active sketch as linked reference geometry. One
|
||||
/// undo step.
|
||||
#[derive(Debug, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = refs_required)]
|
||||
pub struct IntersectParams {
|
||||
/// What to intersect with the sketch plane: one reference or a list (`{body}`, `{face}`,
|
||||
/// `{edge}` or `{sketch, curve}` are the forms that make sense here).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ProjectRefs")]
|
||||
pub refs: Option<ProjectRefs>,
|
||||
/// The same as `refs`, used only when `refs` is not given.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(rename = "ref", with = "ProjectRefs")]
|
||||
pub reference: Option<ProjectRefs>,
|
||||
/// Keep the geometry linked to its source (true), or make it normal sketch geometry at once
|
||||
/// (false: the reply's `link` is then null). Default: true.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub projection_link: Option<bool>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for IntersectParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let o = Map::<String, Value>::deserialize(d)?;
|
||||
let projection_link = read_link_flag(&o).map_err(|why| D::Error::custom(whole(why)))?;
|
||||
let (refs, reference) = read_refs(&o).map_err(|why| D::Error::custom(whole(why)))?;
|
||||
Ok(IntersectParams { refs, reference, projection_link })
|
||||
}
|
||||
}
|
||||
|
||||
/// Include model edges, vertices, and other sketches' curves and points in the active sketch as
|
||||
/// linked geometry; curves out of the sketch plane are flattened onto it. Takes the references of
|
||||
/// `sketch.project`, and always keeps the link. One undo step.
|
||||
#[derive(Debug, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = refs_required)]
|
||||
pub struct Include3dParams {
|
||||
/// What to include: one reference or a list.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "ProjectRefs")]
|
||||
pub refs: Option<ProjectRefs>,
|
||||
/// The same as `refs`, used only when `refs` is not given.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(rename = "ref", with = "ProjectRefs")]
|
||||
pub reference: Option<ProjectRefs>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Include3dParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let o = Map::<String, Value>::deserialize(d)?;
|
||||
let (refs, reference) = read_refs(&o).map_err(|why| D::Error::custom(whole(why)))?;
|
||||
Ok(Include3dParams { refs, reference })
|
||||
}
|
||||
}
|
||||
|
||||
/// A key that, once given (`null` included), must parse as `T`, as the handlers read it.
|
||||
fn some<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {
|
||||
T::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
/// A point `[x, y, z]` or `{x, y, z}` with the handler's own message.
|
||||
macro_rules! point_with_message {
|
||||
($(#[$doc:meta])* $name:ident, $message:literal) => {
|
||||
$(#[$doc])*
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct $name(pub solidcore_record::Vec3);
|
||||
|
||||
impl<'de> Deserialize<'de> for $name {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::vec3(&Value::deserialize(d)?).map($name).ok_or_else(|| D::Error::custom(whole($message)))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for $name {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
stringify!($name).into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<Point3>()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
point_with_message!(
|
||||
/// `sketch.project_to_surface`'s `face`, with the handler's message.
|
||||
TargetFacePoint,
|
||||
"`face` must be a point [x,y,z] on the target face"
|
||||
);
|
||||
point_with_message!(
|
||||
/// `sketch.isoparametric_curve`'s `face`, with the handler's message.
|
||||
IsoFacePoint,
|
||||
"`face` must be a point [x,y,z] on the face"
|
||||
);
|
||||
|
||||
/// A curve to project onto a surface: `{sketch, curve}`, read as the handler reads it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SurfaceCurve(pub Value);
|
||||
|
||||
impl SurfaceCurve {
|
||||
fn problem(v: &Value) -> Option<String> {
|
||||
const EACH: &str = "each entry must be {sketch, curve}";
|
||||
match ref_form(v) {
|
||||
Err(why) => Some(why),
|
||||
// What the handler says of a sketch reference comes after it has found the sketch.
|
||||
Ok(RefForm::Sketch { .. }) => None,
|
||||
// Whether text names a body, or an axis a construction axis, only the design knows;
|
||||
// either way it is not a curve.
|
||||
Ok(RefForm::Name(name)) if !is_origin_or_axis(name) => None,
|
||||
Ok(RefForm::Axis(name)) if !is_origin_or_axis(name) => None,
|
||||
Ok(_) => Some(EACH.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `curves` of `sketch.project_to_surface`: 1 to 500 of them.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SurfaceCurves(pub Vec<Value>);
|
||||
|
||||
impl<'de> Deserialize<'de> for SurfaceCurves {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let list = match Value::deserialize(d)? {
|
||||
Value::Array(list) => list,
|
||||
_ => return Err(D::Error::custom(whole("`curves` must list {sketch, curve}"))),
|
||||
};
|
||||
if list.is_empty() || list.len() > 500 {
|
||||
return Err(D::Error::custom(whole("`curves` must list 1…500 curves")));
|
||||
}
|
||||
if let Some(why) = list.iter().find_map(SurfaceCurve::problem) {
|
||||
return Err(D::Error::custom(whole(why)));
|
||||
}
|
||||
Ok(SurfaceCurves(list))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SurfaceCurves {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SurfaceCurves".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "From 1 to 500 curves of other sketches, each {\"sketch\": id or name, \"curve\": curve id}.",
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 500,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {"sketch": {"type": ["number", "string"]}, "curve": {"type": "string"}},
|
||||
"required": ["sketch", "curve"]
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Project curves of other sketches along the active sketch's normal onto a face of the model,
|
||||
/// as linked 3D curves. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = surface_required)]
|
||||
pub struct ProjectToSurfaceParams {
|
||||
// Optional in the type and required in the schema (`surface_required`): left out, the handler
|
||||
// refuses it with its own message, not the check's "is required".
|
||||
/// The curves to project: 1 to 500 of `{"sketch": id or name, "curve": id}`, curves of other
|
||||
/// sketches.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "SurfaceCurves")]
|
||||
pub curves: Option<SurfaceCurves>,
|
||||
/// A point [x, y, z] in mm on the target face.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "TargetFacePoint")]
|
||||
pub face: Option<TargetFacePoint>,
|
||||
/// The face's body. Default: any body the point is on. Text only; anything else is read as
|
||||
/// left out.
|
||||
#[serde(default)]
|
||||
pub body: Option<String>,
|
||||
}
|
||||
|
||||
fn surface_required(schema: &mut Schema) {
|
||||
require(schema, "curves");
|
||||
require(schema, "face");
|
||||
}
|
||||
|
||||
/// One side of `sketch.intersection_curve`: a body, a face, or a curve of another sketch.
|
||||
macro_rules! intersection_side {
|
||||
($(#[$doc:meta])* $name:ident, $key:literal) => {
|
||||
$(#[$doc])*
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct $name(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for $name {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
let wrong = || D::Error::custom(whole(concat!("`", $key, "` must be a body, a face or a curve of another sketch")));
|
||||
match ref_form(&v) {
|
||||
Err(why) => Err(D::Error::custom(whole(why))),
|
||||
// A sketch reference is judged by the handler once it has found the sketch.
|
||||
Ok(RefForm::Body(_) | RefForm::Face { .. } | RefForm::Sketch { .. }) => Ok($name(v)),
|
||||
// Text is a body's name, or the origin or an axis; an axis name is looked up.
|
||||
Ok(RefForm::Name(name)) if !is_origin_or_axis(name) => Ok($name(v)),
|
||||
Ok(RefForm::Axis(name)) if !is_origin_or_axis(name) => Ok($name(v)),
|
||||
Ok(_) => Err(wrong()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for $name {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
stringify!($name).into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let point = generator.subschema_for::<Point3>();
|
||||
json_schema!({
|
||||
"description": "A body `{\"body\": name}` (or its name as text), a face `{\"face\": [x, y, z], \"body\"?}` (the face through that point), or a curve of another sketch `{\"sketch\": id or name, \"curve\": id}`, which stands for its extrusion along that sketch's normal.",
|
||||
"anyOf": [
|
||||
{"type": "string"},
|
||||
{"type": "object", "properties": {"body": {"type": "string"}}, "required": ["body"]},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"face": point, "body": {"type": "string"}},
|
||||
"required": ["face"]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {"sketch": {"type": ["number", "string"]}, "curve": {"type": "string"}},
|
||||
"required": ["sketch", "curve"]
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
intersection_side!(
|
||||
/// `sketch.intersection_curve`'s `a`.
|
||||
IntersectionSideA,
|
||||
"a"
|
||||
);
|
||||
intersection_side!(
|
||||
/// `sketch.intersection_curve`'s `b`.
|
||||
IntersectionSideB,
|
||||
"b"
|
||||
);
|
||||
|
||||
/// Add where two pieces of model geometry meet to the active sketch, as a linked 3D curve. One
|
||||
/// undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = sides_required)]
|
||||
pub struct IntersectionCurveParams {
|
||||
// Optional in the type and required in the schema, as `curves` above.
|
||||
/// The first side: a body, a face or a curve of another sketch.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "IntersectionSideA")]
|
||||
pub a: Option<IntersectionSideA>,
|
||||
/// The second side, of the same forms.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "IntersectionSideB")]
|
||||
pub b: Option<IntersectionSideB>,
|
||||
}
|
||||
|
||||
fn sides_required(schema: &mut Schema) {
|
||||
require(schema, "a");
|
||||
require(schema, "b");
|
||||
}
|
||||
|
||||
/// A body's name, with the handler's message for text it is not given as.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BodyName(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for BodyName {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(name) => Ok(BodyName(name)),
|
||||
_ => Err(D::Error::custom(whole("`body` must name a body"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for BodyName {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"BodyName".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "A body's name.", "type": "string"})
|
||||
}
|
||||
}
|
||||
|
||||
/// `sketch.spun_profile`'s `axis`: X, Y or Z (any case), or the id of a line of the active sketch.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SpunAxis(pub String);
|
||||
|
||||
impl<'de> Deserialize<'de> for SpunAxis {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(axis) => Ok(SpunAxis(axis)),
|
||||
_ => Err(D::Error::custom(whole("`axis` must be a sketch line or X|Y|Z"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SpunAxis {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SpunAxis".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "The axis to revolve about: X, Y or Z (any case: the origin's axis), or the id of a line of the active sketch.",
|
||||
"type": "string"
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the outline of a body, revolved about an axis, to the active sketch as a linked 3D curve
|
||||
/// in the sketch plane. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = spun_required)]
|
||||
pub struct SpunProfileParams {
|
||||
// Optional in the type and required in the schema, as `curves` above.
|
||||
/// The body to revolve.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "BodyName")]
|
||||
pub body: Option<BodyName>,
|
||||
/// The axis to revolve about: X, Y or Z, or the id of a line of the active sketch.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "SpunAxis")]
|
||||
pub axis: Option<SpunAxis>,
|
||||
}
|
||||
|
||||
fn spun_required(schema: &mut Schema) {
|
||||
require(schema, "body");
|
||||
require(schema, "axis");
|
||||
}
|
||||
|
||||
/// `sketch.isoparametric_curve`'s `direction`: `u` or `v` (any case), or a direction [x, y, z].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct IsoDirection(pub Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for IsoDirection {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
let word = matches!(&v, Value::String(d) if d.eq_ignore_ascii_case("u") || d.eq_ignore_ascii_case("v"));
|
||||
if word || params::vec3(&v).is_some() { Ok(IsoDirection(v)) } else { Err(D::Error::custom(whole("`direction` must be u, v or [x,y,z]"))) }
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for IsoDirection {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"IsoDirection".into()
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let point = generator.subschema_for::<Point3>();
|
||||
json_schema!({
|
||||
"description": "u or v (any case): along the face's parametric direction; or a direction [x, y, z].",
|
||||
"anyOf": [{"type": "string", "enum": ["u", "v", "U", "V"]}, point]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the curve of constant u or v through a point of a face to the active sketch, as a linked
|
||||
/// 3D curve. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = face_required)]
|
||||
pub struct IsoCurveParams {
|
||||
// Optional in the type and required in the schema, as `curves` above.
|
||||
/// A point [x, y, z] in mm on the face: the curve passes through it.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "IsoFacePoint")]
|
||||
pub face: Option<IsoFacePoint>,
|
||||
/// The face's body. Default: any body the point is on. Text only; anything else is read as
|
||||
/// left out.
|
||||
#[serde(default)]
|
||||
pub body: Option<String>,
|
||||
/// Which way the curve runs: u or v, or a direction [x, y, z]. Default: u.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "IsoDirection")]
|
||||
pub direction: Option<IsoDirection>,
|
||||
}
|
||||
|
||||
fn face_required(schema: &mut Schema) {
|
||||
require(schema, "face");
|
||||
}
|
||||
|
||||
/// Fit lines and arcs to the section of a mesh or solid body with the sketch plane, and add them
|
||||
/// to the active sketch as normal (unlinked) geometry. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = body_required)]
|
||||
pub struct FitCurvesParams {
|
||||
// Optional in the type and required in the schema, as `curves` above.
|
||||
/// The body to cut with the sketch plane.
|
||||
#[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "BodyName")]
|
||||
pub body: Option<BodyName>,
|
||||
}
|
||||
|
||||
fn body_required(schema: &mut Schema) {
|
||||
require(schema, "body");
|
||||
}
|
||||
|
||||
/// `sketch.break_link`'s `entities`: one id or a list of ids, as `params::string_list` reads them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct EntityIds(pub Vec<String>);
|
||||
|
||||
impl<'de> Deserialize<'de> for EntityIds {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = Value::deserialize(d)?;
|
||||
match params::string_list("", &json!({"entities": v}), "entities") {
|
||||
Ok(ids) => Ok(EntityIds(ids)),
|
||||
Err(crate::EngineError::BadParams { msg, .. }) => Err(D::Error::custom(whole(msg))),
|
||||
Err(other) => Err(D::Error::custom(whole(other))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for EntityIds {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"EntityIds".into()
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "The id of a curve or point, or a list of ids (at most 10000).",
|
||||
"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": 10000}]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn linked sketch geometry into normal sketch geometry, by its link or by any of its curves
|
||||
/// and points. Give `link` or `entities`. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = link_or_entities)]
|
||||
pub struct SketchBreakLinkParams {
|
||||
/// A link's id (`j1`). Text only; anything else is read as left out.
|
||||
#[serde(default)]
|
||||
pub link: Option<String>,
|
||||
/// The ids of linked curves or points: each one's whole link is broken. Default: none.
|
||||
#[serde(default)]
|
||||
pub entities: Option<EntityIds>,
|
||||
}
|
||||
|
||||
/// The handler refuses a call with neither key (or an empty list), with its own message.
|
||||
fn link_or_entities(schema: &mut Schema) {
|
||||
schema.insert("anyOf".into(), json!([{"required": ["link"]}, {"required": ["entities"]}]));
|
||||
}
|
||||
|
||||
/// Choose whether a sketch created on a face projects that face's edges into it at once, or
|
||||
/// toggle the choice. A setting the session keeps: not an undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct AutoProjectParams {
|
||||
/// True to project, false not to. Default: the opposite of what it is now. Anything but true
|
||||
/// or false is read as left out.
|
||||
#[serde(default)]
|
||||
pub value: Option<bool>,
|
||||
}
|
||||
|
||||
/// One link a projection made, and what it brought into the sketch.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ProjectedLink {
|
||||
/// The link's id (`j1`); null when `projection_link` was false: the geometry is normal sketch
|
||||
/// geometry then.
|
||||
pub link: Option<String>,
|
||||
/// The ids of the curves it made.
|
||||
pub curves: Vec<String>,
|
||||
/// The ids of the points it made.
|
||||
pub points: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.project`, `sketch.intersect` and `sketch.include_3d` return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ProjectResult {
|
||||
/// One entry for each reference that added something, in order.
|
||||
pub links: Vec<ProjectedLink>,
|
||||
/// What was left out because the sketch shows it already (`sketch.project` only).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub already_projected: Vec<String>,
|
||||
/// What the command added to the sketch, as every sketch command reports it (the engine adds
|
||||
/// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The link one command made: what `sketch.intersection_curve`, `sketch.spun_profile` and
|
||||
/// `sketch.isoparametric_curve` return, and each of the `links` of `sketch.project_to_surface`.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct LinkMade {
|
||||
/// The link's id (`j1`).
|
||||
pub link: String,
|
||||
/// The ids of the curves it made.
|
||||
pub curves: Vec<String>,
|
||||
/// The ids of the points it made.
|
||||
pub points: Vec<String>,
|
||||
/// The ids of the wires it made.
|
||||
pub wires: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.intersection_curve`, `sketch.spun_profile` and `sketch.isoparametric_curve`
|
||||
/// return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchLinkResult {
|
||||
#[serde(flatten)]
|
||||
pub made: LinkMade,
|
||||
/// What the command added to the sketch, as every sketch command reports it (the engine adds
|
||||
/// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.project_to_surface` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ProjectToSurfaceResult {
|
||||
/// One link for each curve, in order.
|
||||
pub links: Vec<LinkMade>,
|
||||
/// What the command added to the sketch, as every sketch command reports it (the engine adds
|
||||
/// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.fit_curves_to_section` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct FitSectionResult {
|
||||
/// The ids of the curves added.
|
||||
pub curves: Vec<String>,
|
||||
/// What the command added to the sketch, as every sketch command reports it (the engine adds
|
||||
/// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.break_link` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchBreakLinkResult {
|
||||
/// The ids of the links that were broken.
|
||||
pub broken: Vec<String>,
|
||||
/// What the command added to the sketch, as every sketch command reports it (the engine adds
|
||||
/// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.auto_project` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct AutoProjectResult {
|
||||
/// Whether a sketch created on a face projects its edges now.
|
||||
pub auto_project: bool,
|
||||
/// What the command added to the sketch, as every sketch command reports it (the engine adds
|
||||
/// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created: Option<Value>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_project_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,514 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
AutoProjectParams, AutoProjectResult, FitCurvesParams, FitSectionResult, Include3dParams, IntersectParams, IntersectionCurveParams,
|
||||
IsoCurveParams, ProjectParams, ProjectRef, ProjectResult, ProjectToSurfaceParams, ProjectToSurfaceResult, SketchBreakLinkParams,
|
||||
SketchBreakLinkResult, SketchLinkResult, SpunProfileParams,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, issues, output_schema_for};
|
||||
|
||||
/// A box and a tall cylinder through it (two bodies), a finished sketch `Src` with a line `source`,
|
||||
/// and a sketch being edited, on the XY plane at height 5.
|
||||
fn scene(level: ParamCheck) -> Session {
|
||||
scene_on(level, "XY")
|
||||
}
|
||||
|
||||
/// [`scene`] with the sketch being edited on `plane`.
|
||||
fn scene_on(level: ParamCheck, plane: &str) -> Session {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
for (id, p) in [
|
||||
("solid.box", json!({"corner": [0, 0, 0], "length": 20, "width": 20, "height": 10, "body_name": "Block"})),
|
||||
("solid.cylinder", json!({"base": [10, 10, -5], "radius": 4, "height": 30, "operation": "new", "body_name": "Pin"})),
|
||||
("sketch.create", json!({"plane": "XY", "offset": 20, "name": "Src"})),
|
||||
("sketch.line", json!({"points": [[2, 2], [18, 2]], "ids": ["source"]})),
|
||||
("sketch.line", json!({"points": [[2, 4], [18, 8]], "ids": ["other"]})),
|
||||
("sketch.finish", json!({})),
|
||||
("sketch.create", json!({"plane": plane, "offset": 5})),
|
||||
] {
|
||||
if let Err(e) = s.execute(id, &p) {
|
||||
panic!("{id} {p}: {e}");
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn error(level: ParamCheck, id: &str, p: &Value) -> Option<String> {
|
||||
scene(level).execute(id, p).err().map(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<ProjectParams>(), &["projection_link", "ref", "refs"]);
|
||||
assert_keys(input_schema_for::<IntersectParams>(), &["projection_link", "ref", "refs"]);
|
||||
assert_keys(input_schema_for::<Include3dParams>(), &["ref", "refs"]);
|
||||
assert_keys(input_schema_for::<ProjectToSurfaceParams>(), &["body", "curves", "face"]);
|
||||
assert_keys(input_schema_for::<IntersectionCurveParams>(), &["a", "b"]);
|
||||
assert_keys(input_schema_for::<SpunProfileParams>(), &["axis", "body"]);
|
||||
assert_keys(input_schema_for::<IsoCurveParams>(), &["body", "direction", "face"]);
|
||||
assert_keys(input_schema_for::<FitCurvesParams>(), &["body"]);
|
||||
assert_keys(input_schema_for::<SketchBreakLinkParams>(), &["entities", "link"]);
|
||||
assert_keys(input_schema_for::<AutoProjectParams>(), &["value"]);
|
||||
}
|
||||
|
||||
/// Strict gives the handlers' messages for the calls they refuse for a key. These fail before the
|
||||
/// handler looks at the sketch being edited, so they hold with none open.
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("sketch.project", json!({})),
|
||||
("sketch.project", json!({"refs": []})),
|
||||
("sketch.project", json!({"ref": []})),
|
||||
("sketch.project", json!({"refs": [], "ref": "origin"})),
|
||||
("sketch.project", json!({"projection_link": "no", "refs": ["origin"]})),
|
||||
("sketch.project", json!({"projection_link": null, "refs": ["origin"]})),
|
||||
("sketch.project", json!({"projection_link": 1})),
|
||||
("sketch.intersect", json!({})),
|
||||
("sketch.intersect", json!({"refs": []})),
|
||||
("sketch.intersect", json!({"projection_link": "no", "refs": [{"body": "Block"}]})),
|
||||
("sketch.include_3d", json!({})),
|
||||
("sketch.include_3d", json!({"refs": []})),
|
||||
("sketch.project_to_surface", json!({})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2]})),
|
||||
("sketch.project_to_surface", json!({"face": null})),
|
||||
("sketch.project_to_surface", json!({"face": "top"})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3]})),
|
||||
("sketch.spun_profile", json!({})),
|
||||
("sketch.spun_profile", json!({"body": 5, "axis": "Z"})),
|
||||
("sketch.spun_profile", json!({"body": null})),
|
||||
("sketch.spun_profile", json!({"body": "Block"})),
|
||||
("sketch.spun_profile", json!({"body": "Block", "axis": 3})),
|
||||
("sketch.spun_profile", json!({"body": "Block", "axis": null})),
|
||||
("sketch.isoparametric_curve", json!({})),
|
||||
("sketch.isoparametric_curve", json!({"face": [1, 2]})),
|
||||
("sketch.isoparametric_curve", json!({"face": {"x": 1, "y": 2}})),
|
||||
("sketch.fit_curves_to_section", json!({})),
|
||||
("sketch.fit_curves_to_section", json!({"body": 7})),
|
||||
("sketch.fit_curves_to_section", json!({"body": null})),
|
||||
("sketch.fit_curves_to_section", json!({"body": ["Block"]})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// The same for the calls that fail only once the handler has a sketch to work in: what it
|
||||
/// refuses in a reference or a list, with the sketch being edited open.
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors_in_a_sketch() {
|
||||
let cases = [
|
||||
("sketch.project", json!({"refs": null})),
|
||||
("sketch.project", json!({"refs": [true]})),
|
||||
("sketch.project", json!({"refs": [5]})),
|
||||
("sketch.project", json!({"refs": [null]})),
|
||||
("sketch.project", json!({"refs": [[1, 2, 3]]})),
|
||||
("sketch.project", json!({"refs": [{}]})),
|
||||
("sketch.project", json!({"refs": [{"edge": [1, 2]}]})),
|
||||
("sketch.project", json!({"refs": [{"edge": "x"}, {"plane": 3}]})),
|
||||
("sketch.project", json!({"refs": ["origin", {"sketch": [1], "curve": "source"}]})),
|
||||
("sketch.project", json!({"refs": [{"sketch": true}]})),
|
||||
("sketch.project", json!({"refs": [{"sketch": "Src"}]})),
|
||||
("sketch.project", json!({"refs": [{"sketch": "Src", "curve": 4}]})),
|
||||
("sketch.project", json!({"ref": {"axis": 5}})),
|
||||
("sketch.project", json!({"ref": 5})),
|
||||
("sketch.intersect", json!({"refs": [{"vertex": [1, 2]}]})),
|
||||
("sketch.intersect", json!({"ref": {"sketch": "Src", "point": 1}})),
|
||||
("sketch.include_3d", json!({"refs": [1.5]})),
|
||||
("sketch.include_3d", json!({"refs": {"colour": "red"}})),
|
||||
("sketch.include_3d", json!({"refs": null})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": 5})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": null})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": {"sketch": "Src", "curve": "source"}})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": []})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": vec![json!({"sketch": "Src", "curve": "source"}); 501]})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"edge": [1, 2, 3]}]})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"sketch": "Src", "point": "p1"}]})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"body": "Block"}]})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": ["origin"]})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"origin": true}]})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"nothing": 1}]})),
|
||||
("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"sketch": "Src"}]})),
|
||||
("sketch.intersection_curve", json!({})),
|
||||
("sketch.intersection_curve", json!({"a": {"body": "Block"}})),
|
||||
("sketch.intersection_curve", json!({"b": {"body": "Block"}})),
|
||||
("sketch.intersection_curve", json!({"a": null, "b": {"body": "Block"}})),
|
||||
("sketch.intersection_curve", json!({"a": 5, "b": {"body": "Block"}})),
|
||||
("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"nothing": 1}})),
|
||||
("sketch.intersection_curve", json!({"a": "origin", "b": {"body": "Block"}})),
|
||||
("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": "x"})),
|
||||
("sketch.intersection_curve", json!({"a": {"edge": [1, 2, 3]}, "b": {"body": "Block"}})),
|
||||
("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"vertex": [1, 2, 3]}})),
|
||||
("sketch.intersection_curve", json!({"a": {"plane": "XY"}, "b": {"body": "Block"}})),
|
||||
("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"sketch": "Src", "point": "p1"}})),
|
||||
("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"sketch": "Src"}})),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "direction": null})),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "direction": "w"})),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "direction": [1, 2]})),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "direction": 3})),
|
||||
("sketch.break_link", json!({})),
|
||||
("sketch.break_link", json!({"entities": []})),
|
||||
("sketch.break_link", json!({"entities": 5})),
|
||||
("sketch.break_link", json!({"entities": [1]})),
|
||||
("sketch.break_link", json!({"entities": ["a", true]})),
|
||||
("sketch.break_link", json!({"entities": {"a": 1}})),
|
||||
("sketch.break_link", json!({"link": "j9"})),
|
||||
];
|
||||
for (id, p) in cases {
|
||||
let off = error(ParamCheck::Off, id, &p);
|
||||
assert!(off.is_some(), "{id} {p} should fail today");
|
||||
assert_eq!(error(ParamCheck::Strict, id, &p), off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Strict says the same wherever the handler's message comes from the contract's reading: every
|
||||
/// shape of reference is read by the type as the handler reads it, so the contract refuses it
|
||||
/// exactly when the handler does for its form (a sketch that exists and is another sketch's).
|
||||
#[test]
|
||||
fn the_reference_type_reads_like_the_handler() {
|
||||
let forms = [
|
||||
json!("origin"),
|
||||
json!("ORIGIN"),
|
||||
json!("x"),
|
||||
json!("Z"),
|
||||
json!("Block"),
|
||||
json!("nothing"),
|
||||
json!({"edge": [10, 0, 5]}),
|
||||
json!({"edge": {"x": 10, "y": 0, "z": 5}, "body": "Block"}),
|
||||
json!({"edge": "bad", "body": "Block"}),
|
||||
json!({"edge": [1, 2], "face": [10, 10, 10]}),
|
||||
json!({"edge": [1, 2, 3, 4]}),
|
||||
json!({"face": [10, 10, 10], "body": 4}),
|
||||
json!({"vertex": [0, 0, 10]}),
|
||||
json!({"vertex": [1e9, 0, 0]}),
|
||||
json!({"sketch": "Src", "curve": "source"}),
|
||||
json!({"sketch": "Src", "point": "p1"}),
|
||||
json!({"sketch": "Src", "curve": "source", "point": "p1"}),
|
||||
json!({"sketch": "Src", "curve": 7, "point": "p1"}),
|
||||
json!({"sketch": "Src"}),
|
||||
json!({"sketch": "Src", "curve": null}),
|
||||
json!({"sketch": 1.5}),
|
||||
json!({"sketch": true}),
|
||||
json!({"sketch": null}),
|
||||
json!({"sketch": ["Src"]}),
|
||||
json!({"sketch": {"name": "Src"}, "body": "Block"}),
|
||||
json!({"body": "Block"}),
|
||||
json!({"body": 5}),
|
||||
json!({"body": "Block", "axis": "Z"}),
|
||||
json!({"axis": "X"}),
|
||||
json!({"axis": "x"}),
|
||||
json!({"axis": 5}),
|
||||
json!({"plane": "XY"}),
|
||||
json!({"plane": null}),
|
||||
json!({"origin": null}),
|
||||
json!({"origin": [0, 0, 0]}),
|
||||
json!({}),
|
||||
json!([]),
|
||||
json!(null),
|
||||
json!(true),
|
||||
json!(5),
|
||||
json!({"nothing": 1}),
|
||||
];
|
||||
for form in forms {
|
||||
let issues = issues("sketch.include_3d", &json!({"refs": [form]}));
|
||||
let off = error(ParamCheck::Off, "sketch.include_3d", &json!({"refs": [form]}));
|
||||
let strict = error(ParamCheck::Strict, "sketch.include_3d", &json!({"refs": [form]}));
|
||||
let typed = serde_json::from_value::<ProjectRef>(form.clone());
|
||||
// The type, the check and the handler agree on what is refused for its form.
|
||||
assert_eq!(typed.is_err(), !issues.is_empty(), "{form}");
|
||||
if typed.is_err() {
|
||||
assert_eq!(strict, off, "{form}");
|
||||
} else {
|
||||
let message = off.unwrap_or_default();
|
||||
// What the handler refuses of a form the type accepts needs the design.
|
||||
for shape in ["cannot project", "`sketch` must be", "`refs` is empty"] {
|
||||
assert!(!message.contains(shape), "{form}: {message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// A single reference is read as a list of one, and `ref` is read only without `refs`.
|
||||
let count = |p: Value| issues("sketch.project", &p).len();
|
||||
assert_eq!(count(json!({"refs": "origin"})), 0);
|
||||
assert_eq!(count(json!({"refs": {"origin": 1}})), 0);
|
||||
assert_eq!(count(json!({"ref": "origin"})), 0);
|
||||
assert_eq!(count(json!({"refs": ["origin"], "ref": 5})), 0, "`ref` is not read when `refs` is given");
|
||||
assert_eq!(count(json!({"refs": null, "ref": "origin"})), 1, "`refs` is read even when null");
|
||||
assert_eq!(count(json!({"ref": 5})), 1);
|
||||
assert_eq!(count(json!({"refs": []})), 1);
|
||||
assert_eq!(count(json!({"refs": [], "ref": "origin"})), 1);
|
||||
// Only the first 1000 references are read.
|
||||
let mut many = vec![json!("origin"); 1000];
|
||||
many.push(json!(5));
|
||||
assert_eq!(count(json!({"refs": many})), 0);
|
||||
many.insert(0, json!(5));
|
||||
assert_eq!(count(json!({"refs": many})), 1);
|
||||
// `include_3d` takes no `projection_link`: the handler never reads it, so strict names it.
|
||||
assert_eq!(issues("sketch.include_3d", &json!({"refs": ["origin"], "projection_link": false})).len(), 1);
|
||||
assert_eq!(issues("sketch.project", &json!({"refs": ["origin"], "projection_link": false})).len(), 0);
|
||||
}
|
||||
|
||||
/// What the contracts take and refuse in the schemas as well as the types.
|
||||
#[test]
|
||||
fn the_schemas_take_what_the_handlers_read() {
|
||||
let check = |schema: schemars::Schema, cases: &[(Value, bool)]| {
|
||||
let schema = schema.as_value().clone();
|
||||
for (p, takes) in cases {
|
||||
assert_eq!(conforms(&schema, &schema, p), *takes, "{p}");
|
||||
}
|
||||
};
|
||||
for schema in [input_schema_for::<ProjectParams>(), input_schema_for::<IntersectParams>()] {
|
||||
check(
|
||||
schema,
|
||||
&[
|
||||
(json!({"refs": [{"edge": [1, 2, 3], "body": "Block"}, {"face": [1, 2, 3]}, "origin", {"axis": "X"}]}), true),
|
||||
(json!({"refs": {"sketch": 2, "curve": "c1"}, "projection_link": false}), true),
|
||||
(json!({"ref": {"body": "Block"}}), true),
|
||||
(json!({"refs": [{"sketch": "Src", "point": "p1"}, {"plane": "XY"}, {"vertex": {"x": 1, "y": 2, "z": 3}}]}), true),
|
||||
(json!({}), false),
|
||||
(json!({"projection_link": true}), false),
|
||||
(json!({"refs": []}), false),
|
||||
(json!({"refs": [{"edge": [1, 2]}]}), false),
|
||||
(json!({"refs": ["origin"], "projection_link": "yes"}), false),
|
||||
(json!({"refs": ["origin"], "projection_lnk": true}), false),
|
||||
],
|
||||
);
|
||||
}
|
||||
check(
|
||||
input_schema_for::<Include3dParams>(),
|
||||
&[(json!({"refs": ["origin"]}), true), (json!({"refs": ["origin"], "projection_link": true}), false)],
|
||||
);
|
||||
check(
|
||||
input_schema_for::<ProjectToSurfaceParams>(),
|
||||
&[
|
||||
(json!({"face": [0, 0, 20], "curves": [{"sketch": 4, "curve": "source"}]}), true),
|
||||
(json!({"face": [0, 0, 20], "curves": [{"sketch": "Src", "curve": "source"}], "body": "Block"}), true),
|
||||
(json!({"face": [0, 0, 20]}), false),
|
||||
(json!({"curves": [{"sketch": 4, "curve": "source"}]}), false),
|
||||
(json!({"face": [0, 0, 20], "curves": []}), false),
|
||||
(json!({"face": [0, 0, 20], "curves": [{"sketch": 4}]}), false),
|
||||
],
|
||||
);
|
||||
check(
|
||||
input_schema_for::<IntersectionCurveParams>(),
|
||||
&[
|
||||
(json!({"a": {"body": "Block"}, "b": {"face": [1, 2, 3], "body": "Pin"}}), true),
|
||||
(json!({"a": {"sketch": "Src", "curve": "source"}, "b": "Pin"}), true),
|
||||
(json!({"a": {"body": "Block"}}), false),
|
||||
(json!({"a": {"body": "Block"}, "b": {"edge": [1, 2, 3]}}), false),
|
||||
],
|
||||
);
|
||||
check(
|
||||
input_schema_for::<SpunProfileParams>(),
|
||||
&[
|
||||
(json!({"body": "Pin", "axis": "Z"}), true),
|
||||
(json!({"body": "Pin"}), false),
|
||||
(json!({"axis": "Z"}), false),
|
||||
(json!({"body": 1, "axis": "Z"}), false),
|
||||
],
|
||||
);
|
||||
check(
|
||||
input_schema_for::<IsoCurveParams>(),
|
||||
&[
|
||||
(json!({"face": [1, 2, 3]}), true),
|
||||
(json!({"face": [1, 2, 3], "body": "Block", "direction": "v"}), true),
|
||||
(json!({"face": [1, 2, 3], "direction": [0, 1, 0]}), true),
|
||||
(json!({"direction": "u"}), false),
|
||||
(json!({"face": [1, 2, 3], "direction": "w"}), false),
|
||||
],
|
||||
);
|
||||
check(input_schema_for::<FitCurvesParams>(), &[(json!({"body": "Pin"}), true), (json!({}), false)]);
|
||||
check(
|
||||
input_schema_for::<SketchBreakLinkParams>(),
|
||||
&[
|
||||
(json!({"link": "j1"}), true),
|
||||
(json!({"entities": "c1"}), true),
|
||||
(json!({"entities": ["c1", "p2"], "link": "j1"}), true),
|
||||
(json!({}), false),
|
||||
(json!({"entities": [1]}), false),
|
||||
],
|
||||
);
|
||||
check(input_schema_for::<AutoProjectParams>(), &[(json!({}), true), (json!({"value": false}), true), (json!({"value": "no"}), false)]);
|
||||
}
|
||||
|
||||
/// Every command replies as its output schema says, in Warn without warnings, and in the same JSON
|
||||
/// as with the check off.
|
||||
#[test]
|
||||
fn replies_match_the_output_schema() {
|
||||
fn matches(schema: schemars::Schema, r: &Value) {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
}
|
||||
let calls: Vec<(&str, Value, fn() -> schemars::Schema)> = vec![
|
||||
("sketch.project", json!({"refs": [{"edge": [10, 0, 10]}]}), output_schema_for::<ProjectResult>),
|
||||
("sketch.project", json!({"refs": [{"vertex": [0, 0, 10]}, {"face": [10, 10, 10], "body": "Block"}]}), output_schema_for::<ProjectResult>),
|
||||
("sketch.project", json!({"refs": {"edge": [20, 10, 10], "body": "Block"}, "projection_link": true}), output_schema_for::<ProjectResult>),
|
||||
("sketch.project", json!({"ref": {"edge": [10, 20, 10]}, "projection_link": false}), output_schema_for::<ProjectResult>),
|
||||
("sketch.project", json!({"refs": ["origin"]}), output_schema_for::<ProjectResult>),
|
||||
(
|
||||
"sketch.project",
|
||||
json!({"refs": [{"axis": "X"}, {"plane": "XZ"}, {"sketch": "Src", "curve": "source"}]}),
|
||||
output_schema_for::<ProjectResult>,
|
||||
),
|
||||
("sketch.project", json!({"refs": [{"sketch": "Src", "point": "source.start"}]}), output_schema_for::<ProjectResult>),
|
||||
("sketch.project", json!({"refs": [{"edge": "bad", "body": "Pin"}]}), output_schema_for::<ProjectResult>),
|
||||
("sketch.project", json!({"refs": ["Pin"], "ref": 5}), output_schema_for::<ProjectResult>),
|
||||
("sketch.intersect", json!({"refs": [{"body": "Block"}]}), output_schema_for::<ProjectResult>),
|
||||
("sketch.intersect", json!({"refs": {"face": [0, 10, 5], "body": "Block"}, "projection_link": false}), output_schema_for::<ProjectResult>),
|
||||
("sketch.intersect", json!({"ref": {"edge": [0, 0, 5]}}), output_schema_for::<ProjectResult>),
|
||||
("sketch.include_3d", json!({"refs": [{"edge": [20, 10, 10]}]}), output_schema_for::<ProjectResult>),
|
||||
("sketch.include_3d", json!({"ref": {"vertex": [0, 0, 10]}}), output_schema_for::<ProjectResult>),
|
||||
(
|
||||
"sketch.project_to_surface",
|
||||
json!({"face": [10, 10, 10], "curves": [{"sketch": "Src", "curve": "source"}, {"sketch": "Src", "curve": "other"}]}),
|
||||
output_schema_for::<ProjectToSurfaceResult>,
|
||||
),
|
||||
(
|
||||
"sketch.project_to_surface",
|
||||
json!({"face": {"x": 10, "y": 10, "z": 10}, "body": "Block", "curves": [{"sketch": 3, "curve": "source"}]}),
|
||||
output_schema_for::<ProjectToSurfaceResult>,
|
||||
),
|
||||
("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"body": "Pin"}}), output_schema_for::<SketchLinkResult>),
|
||||
("sketch.intersection_curve", json!({"a": {"face": [10, 10, 10], "body": "Block"}, "b": "Pin"}), output_schema_for::<SketchLinkResult>),
|
||||
(
|
||||
"sketch.intersection_curve",
|
||||
json!({"a": {"sketch": "Src", "curve": "source"}, "b": {"body": "Block"}}),
|
||||
output_schema_for::<SketchLinkResult>,
|
||||
),
|
||||
("sketch.spun_profile", json!({"body": "Pin", "axis": "Z"}), output_schema_for::<SketchLinkResult>),
|
||||
("sketch.spun_profile", json!({"body": "Pin", "axis": "x"}), output_schema_for::<SketchLinkResult>),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10]}), output_schema_for::<SketchLinkResult>),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "body": "Block", "direction": "V"}), output_schema_for::<SketchLinkResult>),
|
||||
("sketch.isoparametric_curve", json!({"face": {"x": 10, "y": 10, "z": 10}, "direction": [1, 0, 0]}), output_schema_for::<SketchLinkResult>),
|
||||
("sketch.fit_curves_to_section", json!({"body": "Block"}), output_schema_for::<FitSectionResult>),
|
||||
("sketch.auto_project", json!({}), output_schema_for::<AutoProjectResult>),
|
||||
("sketch.auto_project", json!({"value": true}), output_schema_for::<AutoProjectResult>),
|
||||
];
|
||||
for (id, p, output) in calls {
|
||||
// The spun profile needs a plane the cylinder's axis lies in.
|
||||
let plane = if id == "sketch.spun_profile" { "XZ" } else { "XY" };
|
||||
let a = scene_on(ParamCheck::Off, plane).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let b = scene_on(ParamCheck::Warn, plane).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert!(b.get("param_warnings").is_none(), "{id} {p}: {b}");
|
||||
assert_eq!(a, b, "{id} {p}");
|
||||
matches(output(), &b);
|
||||
}
|
||||
let run = |p: Value| scene(ParamCheck::Warn).execute("sketch.project", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
|
||||
// The shapes a caller sees: the link, its curves and points; null where the link is not kept.
|
||||
let r = run(json!({"refs": [{"edge": [10, 0, 10]}]}));
|
||||
assert_eq!(r["links"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let l = &r["links"][0];
|
||||
assert!(l["link"].is_string() && l["curves"].is_array() && l["points"].is_array(), "{r}");
|
||||
assert_eq!(l.as_object().map(|o| o.len()), Some(3), "{r}");
|
||||
assert!(r.get("already_projected").is_none(), "no `already_projected` when all was projected: {r}");
|
||||
assert!(r["created"]["curves"].is_array(), "the engine reports what a sketch command created: {r}");
|
||||
let r = run(json!({"refs": [{"edge": [10, 0, 10]}], "projection_link": false}));
|
||||
assert!(r["links"][0]["link"].is_null() && r["links"][0]["curves"][0].is_string(), "{r}");
|
||||
matches(output_schema_for::<ProjectResult>(), &r);
|
||||
// Projecting what the sketch shows already says so, and the reply still matches.
|
||||
let mut s = scene(ParamCheck::Warn);
|
||||
s.execute("sketch.project", &json!({"refs": [{"edge": [10, 0, 10]}]})).unwrap_or_default();
|
||||
let r = s.execute("sketch.project", &json!({"refs": [{"edge": [10, 0, 10]}, {"edge": [10, 20, 10]}]})).unwrap_or_default();
|
||||
assert_eq!(r["already_projected"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
assert!(r.get("param_warnings").is_none(), "{r}");
|
||||
matches(output_schema_for::<ProjectResult>(), &r);
|
||||
// A `value` that is not true or false is read as left out, and the check says so.
|
||||
let r = scene(ParamCheck::Warn).execute("sketch.auto_project", &json!({"value": "maybe"})).unwrap_or_default();
|
||||
assert_eq!(r["param_warnings"], json!(["`value` must be true or false"]), "{r}");
|
||||
matches(output_schema_for::<AutoProjectResult>(), &r);
|
||||
// The shape of the others.
|
||||
let mut s = scene(ParamCheck::Warn);
|
||||
let r = s.execute("sketch.isoparametric_curve", &json!({"face": [10, 10, 10]})).unwrap_or_default();
|
||||
let mut keys: Vec<_> = r.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();
|
||||
keys.sort();
|
||||
assert_eq!(keys, ["created", "curves", "link", "points", "wires"], "{r}");
|
||||
let r = s.execute("sketch.auto_project", &json!({"value": true})).unwrap_or_default();
|
||||
assert_eq!(r["auto_project"], json!(true));
|
||||
let r = s.execute("sketch.auto_project", &json!({})).unwrap_or_default();
|
||||
assert_eq!(r["auto_project"], json!(false), "no value toggles");
|
||||
let r = s.execute("sketch.fit_curves_to_section", &json!({"body": "Block"})).unwrap_or_default();
|
||||
assert!(r["curves"].is_array(), "{r}");
|
||||
}
|
||||
|
||||
/// Breaking links: by `link`, by `entities` of both kinds (a curve, a point), and with both.
|
||||
#[test]
|
||||
fn break_link_replies_without_warnings() {
|
||||
let mut s = scene(ParamCheck::Warn);
|
||||
let linked = |s: &mut Session, p: Value| {
|
||||
let r = s.execute("sketch.project", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
|
||||
let l = &r["links"][0];
|
||||
let text = |v: &Value| v.as_str().unwrap_or_default().to_string();
|
||||
(text(&l["link"]), text(&l["curves"][0]), text(&l["points"][0]))
|
||||
};
|
||||
let (l1, _, _) = linked(&mut s, json!({"refs": [{"edge": [10, 0, 10]}]}));
|
||||
let (_, c2, _) = linked(&mut s, json!({"refs": [{"edge": [10, 20, 10]}]}));
|
||||
let (l3, _, _) = linked(&mut s, json!({"refs": [{"edge": [20, 10, 10]}]}));
|
||||
let (_, _, p4) = linked(&mut s, json!({"refs": [{"vertex": [0, 0, 10]}]}));
|
||||
assert!(!c2.is_empty() && !p4.is_empty());
|
||||
let schema = output_schema_for::<SketchBreakLinkResult>();
|
||||
for p in [json!({"link": l1}), json!({"entities": c2}), json!({"entities": [p4], "link": l3})] {
|
||||
let r = s.execute("sketch.break_link", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
|
||||
assert!(r.get("param_warnings").is_none(), "{p}: {r}");
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
|
||||
assert_eq!(r["broken"].as_array().map(Vec::len), Some(p.as_object().map_or(0, |o| o.len())), "{p}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A key spelt wrong runs in warn and says so (the reply still matches), and strict refuses it.
|
||||
#[test]
|
||||
fn a_misspelt_key_is_reported_in_warn_and_refused_in_strict() {
|
||||
let cases = [
|
||||
("sketch.project", json!({"refs": ["origin"], "projection_lnk": false})),
|
||||
("sketch.intersect", json!({"refs": [{"body": "Block"}], "projectionlink": false})),
|
||||
("sketch.include_3d", json!({"refs": [{"edge": [20, 10, 10]}], "projection_link": false})),
|
||||
("sketch.project_to_surface", json!({"face": [10, 10, 10], "curves": [{"sketch": "Src", "curve": "source"}], "bdy": "Block"})),
|
||||
("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"body": "Pin"}, "c": 1})),
|
||||
("sketch.spun_profile", json!({"body": "Pin", "axis": "Z", "axes": "Y"})),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "directon": "v"})),
|
||||
("sketch.fit_curves_to_section", json!({"body": "Block", "bodies": []})),
|
||||
("sketch.auto_project", json!({"vlaue": false})),
|
||||
];
|
||||
for (id, p) in cases {
|
||||
let plane = if id == "sketch.spun_profile" { "XZ" } else { "XY" };
|
||||
let r = scene_on(ParamCheck::Warn, plane).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let warnings = r["param_warnings"].as_array().unwrap_or_else(|| panic!("{id} {p}: {r}"));
|
||||
assert_eq!(warnings.len(), 1, "{id} {p}: {r}");
|
||||
assert!(warnings[0].as_str().is_some_and(|w| w.contains("unknown key")), "{id}: {r}");
|
||||
let error = error(ParamCheck::Strict, id, &p).unwrap_or_default();
|
||||
assert!(error.contains("unknown key"), "{id}: {error}");
|
||||
}
|
||||
let r = scene(ParamCheck::Warn).execute("sketch.auto_project", &json!({"vlaue": false})).unwrap_or_default();
|
||||
assert_eq!(r["param_warnings"], json!(["unknown key `vlaue`"]), "{r}");
|
||||
// The reply with its warnings still matches its schema.
|
||||
let schema = output_schema_for::<AutoProjectResult>();
|
||||
assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
|
||||
}
|
||||
|
||||
/// Wrong-typed values the handlers read as left out: the typed field names them in warn (and
|
||||
/// strict refuses), `null` is left out and gets no warning, and the reply is the same as with the
|
||||
/// check off.
|
||||
#[test]
|
||||
fn values_read_as_left_out_are_reported_but_change_nothing() {
|
||||
let cases = [
|
||||
("sketch.project_to_surface", json!({"face": [10, 10, 10], "curves": [{"sketch": "Src", "curve": "source"}], "body": 5}), true),
|
||||
("sketch.project_to_surface", json!({"face": [10, 10, 10], "curves": [{"sketch": "Src", "curve": "source"}], "body": null}), false),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "body": 5}), true),
|
||||
("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "body": null}), false),
|
||||
("sketch.auto_project", json!({"value": null}), false),
|
||||
("sketch.auto_project", json!({"value": 1}), true),
|
||||
];
|
||||
for (id, p, warns) in cases {
|
||||
let off = scene(ParamCheck::Off).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let mut warn = scene(ParamCheck::Warn).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert_eq!(warn.get("param_warnings").is_some(), warns, "{id} {p}: {warn}");
|
||||
if let Some(o) = warn.as_object_mut() {
|
||||
o.remove("param_warnings");
|
||||
}
|
||||
assert_eq!(off, warn, "{id} {p}");
|
||||
}
|
||||
// break_link: `link` of the wrong type is left out, so `entities` alone does the work.
|
||||
let mut s = scene(ParamCheck::Warn);
|
||||
let r = s.execute("sketch.project", &json!({"refs": [{"edge": [10, 0, 10]}]})).unwrap_or_default();
|
||||
let curve = r["links"][0]["curves"][0].clone();
|
||||
let r = s.execute("sketch.break_link", &json!({"link": 5, "entities": [curve]})).unwrap_or_default();
|
||||
assert_eq!(r["broken"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
assert_eq!(r["param_warnings"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let r = scene(ParamCheck::Warn).execute("sketch.break_link", &json!({"link": null}));
|
||||
assert!(r.is_err(), "nothing to break");
|
||||
}
|
||||
@@ -3,7 +3,7 @@ use serde_json::{Value, json};
|
||||
use super::{
|
||||
CoincidentParams, CoincidentResult, CollinearParams, ConcentricParams, ConstraintResult, EqualParams, EqualResult, FixParams, FixResult,
|
||||
HorizontalVerticalParams, MidpointParams, Operand, ParallelParams, PerpendicularParams, PointOperand, SketchKey, SymmetryParams, SymmetryResult,
|
||||
TangentParams,
|
||||
TangentParams, TangentResult,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
@@ -342,9 +342,16 @@ fn replies_match_the_output_schemas_and_real_calls_get_no_warnings() {
|
||||
let r = assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": "c3", "b": "c4"}));
|
||||
assert!(r["constraints"].as_array().is_some_and(|c| c.len() == 2) && r.get("constraint").is_some(), "{r}");
|
||||
|
||||
// Tangent, parallel, perpendicular, collinear.
|
||||
// Tangent: two curves, and a line's end point and a circle (#12092), which adds two
|
||||
// constraints.
|
||||
let mut s = new();
|
||||
let r = assert_clean::<TangentResult>(&mut s, "sketch.constraint.tangent", json!({"a": "l1", "b": "c1"}));
|
||||
assert!(r.get("constraints").is_none(), "{r}");
|
||||
let r = assert_clean::<TangentResult>(&mut s, "sketch.constraint.tangent", json!({"a": "l3.end", "b": "c2"}));
|
||||
assert!(r["constraints"].as_array().is_some_and(|c| c.len() == 2) && r.get("constraint").is_some(), "{r}");
|
||||
|
||||
// Parallel, perpendicular, collinear.
|
||||
let mut s = new();
|
||||
assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.tangent", json!({"a": "l1", "b": "c1"}));
|
||||
assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.parallel", json!({"a": "l2", "b": "l3"}));
|
||||
assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.parallel", json!({"a": "l4", "b": "x"}));
|
||||
assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.perpendicular", json!({"a": "l5", "b": "l6"}));
|
||||
|
||||
@@ -11,9 +11,6 @@ doc.open
|
||||
doc.recover
|
||||
doc.recovery_discard
|
||||
doc.recovery_list
|
||||
document.inspect
|
||||
engine.commands
|
||||
expr.evaluate
|
||||
face.delete
|
||||
file.export
|
||||
file.insert_mesh
|
||||
@@ -23,7 +20,6 @@ file.save
|
||||
file.save_as
|
||||
file.save_mesh
|
||||
file.slicers
|
||||
inspect.measure
|
||||
joint.cam
|
||||
joint.gear
|
||||
joint.motion_link
|
||||
@@ -33,8 +29,6 @@ joint.reach
|
||||
joint.rigid_group
|
||||
joint.screw
|
||||
joint.sweep
|
||||
material.assign
|
||||
material.list
|
||||
mesh.convert
|
||||
motion.export_animation
|
||||
motion.interference
|
||||
@@ -47,13 +41,6 @@ occurrence.drag
|
||||
occurrence.ground
|
||||
occurrence.move
|
||||
occurrence.properties
|
||||
parameters.change
|
||||
parameters.complete
|
||||
parameters.export
|
||||
parameters.graph
|
||||
parameters.import
|
||||
parameters.list
|
||||
parameters.users
|
||||
render.aging.describe
|
||||
render.backends
|
||||
render.cancel
|
||||
@@ -71,20 +58,7 @@ sheet.export_bend_table
|
||||
sheet.export_dxf
|
||||
sheet.flat_pattern
|
||||
sheet.path_flange
|
||||
sketch.arc.tangent
|
||||
sketch.auto_constrain
|
||||
sketch.auto_constrain_from_datum
|
||||
sketch.auto_project
|
||||
sketch.blend_curve
|
||||
sketch.break_link
|
||||
sketch.centerline
|
||||
sketch.chain
|
||||
sketch.circle.three_tangent
|
||||
sketch.circle.two_tangent
|
||||
sketch.conic
|
||||
sketch.constrainer
|
||||
sketch.constraint.curvature
|
||||
sketch.constraint.polygon
|
||||
sketch.construction
|
||||
sketch.create
|
||||
sketch.delete
|
||||
@@ -93,49 +67,18 @@ sketch.dimension_text
|
||||
sketch.drag
|
||||
sketch.drag_end
|
||||
sketch.draw.dimensioned
|
||||
sketch.edit_text
|
||||
sketch.ellipse
|
||||
sketch.export_dxf
|
||||
sketch.finish_auto_constrain
|
||||
sketch.fit_curves_to_section
|
||||
sketch.glyphs
|
||||
sketch.include_3d
|
||||
sketch.infinite
|
||||
sketch.insert_dxf
|
||||
sketch.insert_svg
|
||||
sketch.inspect
|
||||
sketch.intersect
|
||||
sketch.intersection_curve
|
||||
sketch.isoparametric_curve
|
||||
sketch.line.midpoint
|
||||
sketch.line3d
|
||||
sketch.move3d
|
||||
sketch.move_point
|
||||
sketch.options
|
||||
sketch.point3d
|
||||
sketch.polygon.circumscribed
|
||||
sketch.polygon.edge
|
||||
sketch.polygon.inscribed
|
||||
sketch.project
|
||||
sketch.project_to_surface
|
||||
sketch.rectangle.center
|
||||
sketch.rectangle.rounded
|
||||
sketch.rectangle.three_point
|
||||
sketch.rectangle.two_point
|
||||
sketch.slot.arc_center
|
||||
sketch.slot.arc_three_point
|
||||
sketch.slot.center_point
|
||||
sketch.slot.center_to_center
|
||||
sketch.slot.overall
|
||||
sketch.snap
|
||||
sketch.solve
|
||||
sketch.spline.control_point
|
||||
sketch.spline.control_point_5
|
||||
sketch.spline.fit_point
|
||||
sketch.spline3d
|
||||
sketch.spun_profile
|
||||
sketch.text
|
||||
sketch.toggle_driven
|
||||
solid.align
|
||||
solid.chamfer
|
||||
solid.coil
|
||||
|
||||
@@ -161,7 +161,16 @@ fn smlib_body(record: &solidcore_record::brep::Brep) -> std::result::Result<(Bod
|
||||
let (body, body_order) = crate::native::body_from_smlib_ordered(&brep).map_err(failed)?;
|
||||
// SMLib's face i is the record's `smlib_order` face and the body's `body_order` face (an
|
||||
// empty order is the same one).
|
||||
let (Some(smlib_order), Some(body_order)) = (smlib_order, body_order) else { return Err(renumbered()) };
|
||||
let Some(body_order) = body_order else { return Err(renumbered()) };
|
||||
// SMLib's export may number the edges and vertices otherwise than the record (a surface model
|
||||
// whose open shell uses faces against their surfaces beside closed shells: SMLib walks those
|
||||
// faces as their surfaces face). An import still lists SMLib's faces in the record's order;
|
||||
// that is taken where each face is checked to be the record's face it would be.
|
||||
let smlib_order = match smlib_order {
|
||||
Some(order) => order,
|
||||
None if faces_in_record_order(record, body.record(), &body_order.faces) => Default::default(),
|
||||
None => return Err(renumbered()),
|
||||
};
|
||||
let at = |order: &[usize], i: usize| if order.is_empty() { Some(i) } else { order.get(i).copied() };
|
||||
let faces = brep.counts().map_err(|e| failed(KernelError::Failed(format!("SMLib: {e}"))))?[0];
|
||||
let mut of_record = vec![usize::MAX; body.face_count()];
|
||||
@@ -177,6 +186,44 @@ fn smlib_body(record: &solidcore_record::brep::Brep) -> std::result::Result<(Bod
|
||||
Ok((body, of_record))
|
||||
}
|
||||
|
||||
/// Whether SMLib's face `i` of a body made from `record` (the body's face `body_order[i]`, or `i`
|
||||
/// for an empty order) is the record's face `i`, face by face: the same kind of surface, the same
|
||||
/// loops of the same lengths, each loop through the same corners (within the vertices' and the
|
||||
/// records' tolerances, whichever way and from wherever SMLib walks it).
|
||||
fn faces_in_record_order(record: &solidcore_record::brep::Brep, body: &solidcore_record::brep::Brep, body_order: &[usize]) -> bool {
|
||||
use solidcore_record::brep::{Brep, Loop};
|
||||
if record.faces.len() != body.faces.len() || !(body_order.is_empty() || body_order.len() == body.faces.len()) {
|
||||
return false;
|
||||
}
|
||||
// Each loop's corners: the start of each of its edges as the loop walks them, with its tolerance.
|
||||
let corners = |b: &Brep, l: &Loop| -> Option<Vec<([f64; 3], f64)>> {
|
||||
let vertex = |v: u32| b.vertices.get(usize::try_from(v).ok()?).map(|x| (x.point, x.tolerance));
|
||||
match l {
|
||||
Loop::Vertex { vertex: v } => Some(vec![vertex(*v)?]),
|
||||
Loop::Edges { edges } => edges
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let edge = b.edges.get(usize::try_from(e.edge).ok()?)?;
|
||||
vertex(if e.forward { edge.vertices[0] } else { edge.vertices[1] })
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
};
|
||||
let slack = record.tolerance + body.tolerance;
|
||||
(0..record.faces.len()).all(|i| {
|
||||
let at = if body_order.is_empty() { Some(i) } else { body_order.get(i).copied() };
|
||||
let (Some(a), Some(b)) = (record.faces.get(i), at.and_then(|k| body.faces.get(k))) else { return false };
|
||||
if std::mem::discriminant(&a.surface) != std::mem::discriminant(&b.surface) || a.loops.len() != b.loops.len() {
|
||||
return false;
|
||||
}
|
||||
a.loops.iter().zip(&b.loops).all(|(x, y)| {
|
||||
let (Some(p), Some(q)) = (corners(record, x), corners(body, y)) else { return false };
|
||||
p.len() == q.len()
|
||||
&& p.iter().all(|(u, tu)| q.iter().any(|(w, tw)| (0..3).map(|k| (u[k] - w[k]).powi(2)).sum::<f64>().sqrt() <= tu + tw + slack))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The face of its one operand each face of `body` is, from its history.
|
||||
fn kept_faces(body: &Body) -> Option<Vec<usize>> {
|
||||
let h = body.history()?;
|
||||
|
||||
@@ -662,6 +662,69 @@ fn a_surface_models_closed_shell_beside_a_sheet_is_a_solid_of_its_own() {
|
||||
assert!(imp.bodies.iter().all(|b| b.color == Some([1.0, 0.5, 0.0])));
|
||||
}
|
||||
|
||||
/// A surface model whose shells are all OPEN_SHELLs, one of them closed all the same (a unit
|
||||
/// cube) beside a sheet of two faces, the first used against its plane (as SolidWorks 2011 wrote
|
||||
/// a vendor part): SMLib's export walks that face as its plane faces and numbers the edges and
|
||||
/// vertices otherwise than the reader, its faces still in the reader's order. The model comes in
|
||||
/// as one body of all its faces, each the file's face it was; it once came in as nothing ("SMLib
|
||||
/// renumbered the solid's faces"), and the file with it.
|
||||
#[test]
|
||||
fn a_surface_model_of_open_shells_one_closed_beside_a_turned_sheet_imports() {
|
||||
let mut t = String::from(HEAD);
|
||||
t += &cube_entities().replace("#100=CLOSED_SHELL", "#100=OPEN_SHELL");
|
||||
// Two unit squares at z = 5 sharing the edge x = 1, both facing +z: the first on a plane
|
||||
// facing -z used against it, the second on a plane facing +z.
|
||||
let corners = [(0, 0), (1, 0), (2, 0), (2, 1), (1, 1), (0, 1)];
|
||||
for (i, (x, y)) in corners.iter().enumerate() {
|
||||
t += &format!("#{}=CARTESIAN_POINT('',({x}.,{y}.,5.));\n#{}=VERTEX_POINT('',#{});\n", 800 + i, 810 + i, 800 + i);
|
||||
}
|
||||
let edges = [(0, 1), (1, 4), (4, 5), (5, 0), (1, 2), (2, 3), (3, 4)];
|
||||
for (k, (a, b)) in edges.iter().enumerate() {
|
||||
let (p, q) = (corners[*a], corners[*b]);
|
||||
t += &format!("#{}=DIRECTION('',({}.,{}.,0.));\n#{}=VECTOR('',#{},1.);\n", 900 + 2 * k, q.0 - p.0, q.1 - p.1, 901 + 2 * k, 900 + 2 * k);
|
||||
t += &format!(
|
||||
"#{}=LINE('',#{},#{});\n#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n",
|
||||
820 + k,
|
||||
800 + a,
|
||||
901 + 2 * k,
|
||||
830 + k,
|
||||
810 + a,
|
||||
810 + b,
|
||||
820 + k
|
||||
);
|
||||
}
|
||||
let faces: [(&[(usize, bool)], i32, &str); 2] =
|
||||
[(&[(0, true), (1, true), (2, true), (3, true)], -1, ".F."), (&[(4, true), (5, true), (6, true), (1, false)], 1, ".T.")];
|
||||
for (f, (lp, nz, sense)) in faces.iter().enumerate() {
|
||||
let base = 940 + 20 * f;
|
||||
let oes: Vec<String> = lp
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(j, (e, fwd))| {
|
||||
t += &format!("#{}=ORIENTED_EDGE('',*,*,#{},{});\n", base + j, 830 + e, if *fwd { ".T." } else { ".F." });
|
||||
format!("#{}", base + j)
|
||||
})
|
||||
.collect();
|
||||
t += &format!("#{}=EDGE_LOOP('',({}));\n#{}=FACE_OUTER_BOUND('',#{},.T.);\n", base + 5, oes.join(","), base + 6, base + 5);
|
||||
t += &format!("#{}=CARTESIAN_POINT('',(0.,0.,5.));\n#{}=DIRECTION('',(0.,0.,{nz}.));\n", base + 7, base + 8);
|
||||
t += &format!("#{}=AXIS2_PLACEMENT_3D('',#{},#{},$);\n#{}=PLANE('',#{});\n", base + 9, base + 7, base + 8, base + 10, base + 9);
|
||||
t += &format!("#{}=ADVANCED_FACE('',(#{}),#{},{sense});\n", base + 11, base + 6, base + 10);
|
||||
}
|
||||
t += "#130=OPEN_SHELL('',(#951,#971));\n#110=SHELL_BASED_SURFACE_MODEL('Bracket',(#130,#100));\n";
|
||||
t += &context(20, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");
|
||||
t += "#60=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#110),#20);\n";
|
||||
t += TAIL;
|
||||
let imp = step_import(&t).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);
|
||||
let b = &imp.bodies[0];
|
||||
assert_eq!((b.source_item, b.file_faces, b.body.face_count()), (110, 8, 8), "{:?}", imp.warnings);
|
||||
assert!(b.refused.is_none(), "{:?}", b.refused);
|
||||
// Each face is the file's face it was: the sheet's first, then the cube's.
|
||||
assert_eq!(b.face_origin, [951, 971, 411, 431, 451, 471, 491, 511]);
|
||||
let m = measure(&b.body).unwrap();
|
||||
assert!(rel(m.area, 8.0) < 1e-9, "area {}", m.area);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_written_part_in_inches_with_colour() {
|
||||
let mut t = String::from(HEAD);
|
||||
|
||||
@@ -615,12 +615,13 @@ impl DialogComputation {
|
||||
}
|
||||
}
|
||||
|
||||
fn adopt_dialog(app: &mut SolveApp, prepared: solidcraft_engine::ComputedCommands) -> Result<(), String> {
|
||||
fn adopt_dialog(app: &mut SolveApp, prepared: solidcraft_engine::ComputedCommands, d: &Dialog) -> Result<(), String> {
|
||||
if app.file_load.busy() || app.file_picker_busy() {
|
||||
return Err("a file operation is in progress".into());
|
||||
}
|
||||
let replies = app.session.accept_commands(prepared).map_err(|e| e.to_string())?;
|
||||
app.big_operation = true;
|
||||
let made = crate::hole_place::holes_made(&replies);
|
||||
for (id, reply) in replies {
|
||||
let stop = (id == "joint.drive").then(|| crate::dialogs_assembly::drive_stop(&reply)).flatten();
|
||||
app.command_completed(&id, Ok(reply))?;
|
||||
@@ -628,6 +629,7 @@ fn adopt_dialog(app: &mut SolveApp, prepared: solidcraft_engine::ComputedCommand
|
||||
app.set_status(why, false);
|
||||
}
|
||||
}
|
||||
crate::hole_place::group_made(app, d, made);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -4138,7 +4140,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
Err(error) => d.refuse(app, error),
|
||||
}
|
||||
} else {
|
||||
let run = result.and_then(|prepared| adopt_dialog(app, prepared));
|
||||
let run = result.and_then(|prepared| adopt_dialog(app, prepared, &d));
|
||||
match run {
|
||||
Ok(()) => {
|
||||
cancel = !apply_again;
|
||||
@@ -4888,16 +4890,18 @@ pub(crate) fn run_dialog(app: &mut SolveApp, d: &Dialog) -> Result<(), String> {
|
||||
}
|
||||
if d.previews() {
|
||||
let prepared = DialogComputation::new(app, d)?.compute()?;
|
||||
return adopt_dialog(app, prepared);
|
||||
return adopt_dialog(app, prepared, d);
|
||||
}
|
||||
let commands = apply_commands(app, d)?;
|
||||
if let Some((_, marker)) = d.editing {
|
||||
// Record the actual pre-edit timeline state in the command's undo snapshot.
|
||||
roll_marker(app, marker)?;
|
||||
}
|
||||
let mut replies = Vec::new();
|
||||
for (cmd, params) in commands {
|
||||
match app.run(&cmd, params) {
|
||||
Ok(reply) => {
|
||||
replies.push((cmd.clone(), reply.clone()));
|
||||
// A drive that stopped short says where, and why.
|
||||
if cmd == "joint.drive"
|
||||
&& let Some(why) = crate::dialogs_assembly::drive_stop(&reply)
|
||||
@@ -4914,6 +4918,8 @@ pub(crate) fn run_dialog(app: &mut SolveApp, d: &Dialog) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let made = crate::hole_place::holes_made(&replies);
|
||||
crate::hole_place::group_made(app, d, made);
|
||||
if let Kind::Section { offset, flip, hatch } = &d.kind
|
||||
&& let Some(cut) = app.session.section
|
||||
{
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
//!
|
||||
//! Create Hole › Several holes on one face (`hole_several`): a pick elsewhere on a face that already
|
||||
//! has a hole adds another hole there (rather than moving it), and a pick on a hole takes it out.
|
||||
//! Create Hole › Group holes made together (`hole_group`): the holes one Hole dialog makes, two or
|
||||
//! more, go into a feature folder in History, closed at first.
|
||||
|
||||
use crate::ui_kit::BackingTooltipExt as _;
|
||||
use solidcraft_engine::geom::prelude::*;
|
||||
@@ -349,6 +351,42 @@ pub(crate) fn pick_several(app: &SolveApp, d: &mut Dialog, sel: &Sel) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The features the Hole commands among `replies` made, in order.
|
||||
pub(crate) fn holes_made(replies: &[(String, serde_json::Value)]) -> Vec<u64> {
|
||||
replies.iter().filter(|(id, _)| id == "solid.hole").filter_map(|(_, reply)| reply.get("feature").and_then(serde_json::Value::as_u64)).collect()
|
||||
}
|
||||
|
||||
/// With Group holes made together on (Preferences), the holes one Hole dialog made (two or more)
|
||||
/// go into a feature folder in History, closed at first: opened, each hole is edited on its own.
|
||||
/// The folder sits where the holes went (inside the folder they were added to, if any).
|
||||
pub(crate) fn group_made(app: &mut SolveApp, d: &Dialog, made: Vec<u64>) {
|
||||
if !app.preferences.hole_group || d.editing.is_some() || !matches!(d.kind, Kind::Hole { .. }) || made.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let parent = made.first().and_then(|first| app.session.doc.timeline_groups.iter().find(|g| g.features.contains(first))).map(|g| g.id);
|
||||
let made_count = made.len();
|
||||
match app.run("timeline.group", serde_json::json!({"name": "Holes", "features": made, "parent": parent})) {
|
||||
Ok(reply) => {
|
||||
if let Some(id) = reply.get("group").and_then(serde_json::Value::as_u64) {
|
||||
crate::timeline_folders::set_open(app, id, false);
|
||||
}
|
||||
// Keep one Undo step for all holes from this dialog, with folder creation after it.
|
||||
let undo = &mut app.session.undo;
|
||||
let first_hole =
|
||||
undo.len().checked_sub(made_count + 1).filter(|&first| undo[first..undo.len() - 1].iter().all(|step| step.label == "Hole"));
|
||||
if let Some(first_hole) = first_hole {
|
||||
let folder_step = undo.pop();
|
||||
if let Some(folder_step) = folder_step {
|
||||
drop(undo.drain(first_hole + 1..));
|
||||
undo.push(folder_step);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The holes stand; only the folder is missing.
|
||||
Err(error) => app.set_status(error, true),
|
||||
}
|
||||
}
|
||||
|
||||
/// The hovered face's snap marks, and the face places' handles when holes move by dragging.
|
||||
/// Called after the canvas draws the dialog's arrows, so a press on a hole's centre takes the
|
||||
/// hole, not the depth arrow.
|
||||
|
||||
@@ -288,7 +288,7 @@ fn editing_a_hole_drags_it_to_a_new_place() {
|
||||
fn snaps_and_moves_are_off_by_default_and_picks_behave_as_before() {
|
||||
let mut h = block_as_installed();
|
||||
assert!(
|
||||
!h.app.preferences.hole_snaps && !h.app.preferences.hole_moves && !h.app.preferences.hole_several,
|
||||
!h.app.preferences.hole_snaps && !h.app.preferences.hole_moves && !h.app.preferences.hole_several && !h.app.preferences.hole_group,
|
||||
"a new installation places holes as it always did"
|
||||
);
|
||||
h.step(&json!({"start": "solid.hole"})).unwrap();
|
||||
@@ -622,3 +622,54 @@ fn edit_holes_on_a_folder_changes_what_was_edited_in_every_hole_and_keeps_the_re
|
||||
assert!(crate::hole_folder::holes(&h.app, mixed).is_none());
|
||||
assert!(h.step(&json!({"call": "ui.editFolder", "params": {"folder": "Mixed"}})).is_err());
|
||||
}
|
||||
|
||||
/// Single holes on the block's top and front faces, made with OK; the new Hole features' ids.
|
||||
fn holes_on_two_faces(h: &mut Harness) -> Vec<u64> {
|
||||
let before = h.app.session.doc.features.len();
|
||||
h.step(&json!({"start": "solid.hole"})).unwrap();
|
||||
for p in [Vec3::new(30.0, 20.0, 20.0), Vec3::new(25.0, 0.0, 10.0)] {
|
||||
let at = screen(h, p);
|
||||
h.step(&json!({"click": at})).unwrap();
|
||||
}
|
||||
h.step(&json!({"click": {"handle": "dialog:ok"}})).unwrap();
|
||||
h.settle();
|
||||
assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|d| &d.error));
|
||||
h.app.session.doc.features[before..].iter().filter(|f| matches!(f.kind, FeatureKind::Hole { .. })).map(|f| f.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holes_made_together_share_a_closed_folder_when_preferences_say_so() {
|
||||
let mut h = block_as_installed();
|
||||
h.step(&json!({"call": "ui.view", "params": {"view": "iso"}})).unwrap();
|
||||
h.settle();
|
||||
// Off (the default): each hole is its own entry in History, as before.
|
||||
assert_eq!(holes_on_two_faces(&mut h).len(), 2);
|
||||
assert!(h.app.session.doc.timeline_groups.is_empty(), "no folder");
|
||||
// On: the two holes go into one folder, closed at first.
|
||||
crate::prefs::set(&mut h.app, &json!({"hole_group": true})).unwrap();
|
||||
let made = holes_on_two_faces(&mut h);
|
||||
assert_eq!(made.len(), 2);
|
||||
let [folder] = h.app.session.doc.timeline_groups.as_slice() else { panic!("one folder: {:?}", h.app.session.doc.timeline_groups) };
|
||||
assert_eq!((folder.name.as_str(), &folder.features, folder.parent), ("Holes", &made, None));
|
||||
assert!(!crate::timeline_folders::is_open(&h.app, folder.id, true), "closed at first, in both Histories");
|
||||
h.app.run("edit.undo", json!({})).unwrap();
|
||||
assert!(h.app.session.doc.timeline_groups.is_empty(), "first Undo removes the folder");
|
||||
assert_eq!(h.app.session.doc.features.iter().filter(|f| made.contains(&f.id)).count(), 2, "holes remain");
|
||||
h.app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(h.app.session.doc.features.iter().filter(|f| made.contains(&f.id)).count(), 0, "second Undo removes both holes");
|
||||
h.app.run("edit.redo", json!({})).unwrap();
|
||||
h.app.run("edit.redo", json!({})).unwrap();
|
||||
// One hole alone, or a hole edited, stays out of any new folder.
|
||||
h.step(&json!({"start": "solid.hole"})).unwrap();
|
||||
let at = screen(&mut h, Vec3::new(5.0, 25.0, 20.0));
|
||||
h.step(&json!({"click": at})).unwrap();
|
||||
h.step(&json!({"click": {"handle": "dialog:ok"}})).unwrap();
|
||||
h.settle();
|
||||
assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|d| &d.error));
|
||||
h.step(&json!({"call": "ui.editFeature", "params": {"feature": made[0]}})).unwrap();
|
||||
h.frames(4);
|
||||
h.step(&json!({"click": {"handle": "dialog:ok"}})).unwrap();
|
||||
h.settle();
|
||||
assert_eq!(h.app.session.doc.timeline_groups.len(), 1, "still the one folder");
|
||||
assert_eq!(h.app.session.doc.timeline_groups[0].features, made, "holding the same holes");
|
||||
}
|
||||
|
||||
@@ -1496,6 +1496,9 @@ preference_settings! {
|
||||
/// and a pick on a hole takes it out (`hole_place`). Off by default: a face takes one Single
|
||||
/// hole, and a second pick on it takes the hole out (or moves it, with `hole_moves`).
|
||||
hole_several: bool = false, PAGE_TOOLS => check_id("prefs.design_tools.hole_several");
|
||||
/// The holes one Hole command makes (two or more) go into a feature folder in History, closed
|
||||
/// at first (`hole_place`). Off by default: each hole is its own entry in History, as before.
|
||||
hole_group: bool = false, PAGE_TOOLS => check_id("prefs.design_tools.hole_group");
|
||||
/// The browser's Origin folder starts hidden in designs that don't keep its eye themselves.
|
||||
hide_origin: bool = false, PAGE_DESIGN => check_tr("ui.hide_origin_by_default");
|
||||
/// Handles on the preview of a feature placed on a face (Rest, Boss, Snap Fit): a marker that
|
||||
@@ -6412,6 +6415,7 @@ mod tests {
|
||||
("hole_snaps", json!(true), PAGE_TOOLS),
|
||||
("hole_moves", json!(true), PAGE_TOOLS),
|
||||
("hole_several", json!(true), PAGE_TOOLS),
|
||||
("hole_group", json!(true), PAGE_TOOLS),
|
||||
("extrude_arrow_face_stops", json!(false), PAGE_TOOLS),
|
||||
("extrude_auto_to_object", json!(false), PAGE_TOOLS),
|
||||
("extrude_view_isometric", json!(true), PAGE_TOOLS),
|
||||
|
||||
@@ -17,6 +17,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
),
|
||||
(setting::hole_moves, "prefs.design_tools.hole_moves_help", "hole_moves", "Move holes by clicking or dragging"),
|
||||
(setting::hole_several, "prefs.design_tools.hole_several_help", "hole_several", "Several holes on one face"),
|
||||
(setting::hole_group, "prefs.design_tools.hole_group_help", "hole_group", "Group holes made together"),
|
||||
] {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let response = setting(app, ui).backing_on_hover_text(app.tr(help));
|
||||
|
||||
@@ -1561,6 +1561,7 @@ mod tests {
|
||||
("Snap to face and edge centres", "Snap to face and edge centres", crate::prefs::PAGE_TOOLS, "prefs:hole_snaps"),
|
||||
("Move holes by clicking or dragging", "Move holes by clicking or dragging", crate::prefs::PAGE_TOOLS, "prefs:hole_moves"),
|
||||
("Several holes on one face", "prefs.design_tools.hole_several", crate::prefs::PAGE_TOOLS, "prefs:hole_several"),
|
||||
("Group holes made together", "prefs.design_tools.hole_group", crate::prefs::PAGE_TOOLS, "prefs:hole_group"),
|
||||
("Show moved parts' old place as a ghost", "prefs.design_tools.ghost", crate::prefs::PAGE_TOOLS, "prefs:drive_joints_ghost"),
|
||||
("Near-axis rotation step (°)", "joint_move.coarse", crate::prefs::PAGE_TOOLS, "prefs:joint_rotation_coarse"),
|
||||
("Far-axis rotation step (°)", "joint_move.fine", crate::prefs::PAGE_TOOLS, "prefs:joint_rotation_fine"),
|
||||
|
||||
@@ -340,7 +340,7 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {
|
||||
}
|
||||
}
|
||||
Kind::Pick(n) => {
|
||||
let hits = pick(app, proj, pos);
|
||||
let hits = curve_operands(tool.cmd, pick(app, proj, pos));
|
||||
// Symmetry's third pick may be an origin axis lying along the sketch's own x or y
|
||||
// (#1075); the command names those `x` / `y`.
|
||||
let axis_ok = tool.cmd == "sketch.constraint.symmetry" && tool.picks.len() == 2;
|
||||
@@ -895,6 +895,20 @@ fn run_pick(app: &mut SolveApp, t: &Tool) {
|
||||
let _ = app.run(t.cmd, params);
|
||||
}
|
||||
|
||||
/// Parallel, Perpendicular, Equal and Collinear constrain two curves, and their commands take no
|
||||
/// point. So a click on a curve's end point picks the curve under it, not the point, and a body's
|
||||
/// edge is taken rather than its vertex (#12092). Tangent also takes a curve's end point: that
|
||||
/// end then lies on the other curve. A body's vertex ends no sketch curve, so Tangent takes the
|
||||
/// edge there too.
|
||||
fn curve_operands(cmd: &str, hits: Vec<Hit>) -> Vec<Hit> {
|
||||
let points = match cmd {
|
||||
"sketch.constraint.collinear" | "sketch.constraint.equal" | "sketch.constraint.parallel" | "sketch.constraint.perpendicular" => false,
|
||||
"sketch.constraint.tangent" => true,
|
||||
_ => return hits,
|
||||
};
|
||||
hits.into_iter().filter(|h| !matches!(h, Hit::Vertex { .. }) && (points || !matches!(h, Hit::SketchPoint { .. }))).collect()
|
||||
}
|
||||
|
||||
/// Take back a pending spline point before undo or Backspace reaches the sketch.
|
||||
pub fn undo_spline_point(app: &mut SolveApp) -> bool {
|
||||
let Some(t) = app.tool.as_mut() else { return false };
|
||||
|
||||
@@ -160,6 +160,48 @@ fn ambiguous_selection_preserves_tool_first_workflow() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #12092: a tool that constrains two curves takes the line when the click lands on its end
|
||||
/// point. It used to pass the point on, and the command refused it ("unknown sketch curve
|
||||
/// `l1.end`"). Tangent keeps the end: the line's end then moves onto the circle, tangent there.
|
||||
#[test]
|
||||
fn a_click_on_a_line_end_picks_the_line_for_two_curve_constraints() {
|
||||
for command in ["parallel", "perpendicular", "equal", "collinear"] {
|
||||
let mut h = lines();
|
||||
let undo = h.app.session.undo.len();
|
||||
h.run(&json!([{"start":format!("sketch.constraint.{command}")}, {"click":{"sketch":[40,10]}}, {"click":{"sketch":[40,35]}}])).unwrap();
|
||||
assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{command}: {:?}", h.app.status);
|
||||
assert_eq!(h.app.session.undo.len(), undo + 1, "{command}");
|
||||
assert_line_geometry(&h, command);
|
||||
}
|
||||
let mut h = Harness::new();
|
||||
h.run(&json!([
|
||||
{"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}},
|
||||
{"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[0,20],[30,20]],"infer":false}}},
|
||||
{"call":"engine.execute","params":{"command":"sketch.circle.center","params":{"center":[50,0],"radius":10}}},
|
||||
{"call":"ui.view","params":{"view":"top"}},
|
||||
{"start":"sketch.constraint.tangent"},
|
||||
{"click":{"sketch":[30,20]}},
|
||||
{"click":{"sketch":[60,0]}}
|
||||
]))
|
||||
.unwrap();
|
||||
assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "tangent: {:?}", h.app.status);
|
||||
let sk = &h.app.session.model.state().sketches[0].sketch;
|
||||
assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Tangent { .. })), "tangent");
|
||||
// The line now touches the circle: its distance from the centre is the radius.
|
||||
let a = sk.point(sk.resolve_point("l1.start").unwrap()).unwrap();
|
||||
let b = sk.point(sk.resolve_point("l1.end").unwrap()).unwrap();
|
||||
let circle = sk.curves.iter().position(|c| matches!(c.kind, solidcraft_engine::sketch::CurveKind::Circle { .. })).unwrap();
|
||||
let centre = sk.point(sk.resolve_point(&format!("{}.center", sk.curves[circle].id)).unwrap()).unwrap();
|
||||
let radius = sk.radius(circle).unwrap();
|
||||
let distance = (b - a).normalized().unwrap().cross(centre - a).abs();
|
||||
assert!((distance - radius).abs() < 1e-6, "line {a:?}..{b:?} is {distance} from the centre, radius {radius}");
|
||||
// The clicked end lies on the circle, where the line touches it.
|
||||
assert!((b.dist(centre) - radius).abs() < 1e-6, "the line's end {b:?} is {} from the centre, radius {radius}", b.dist(centre));
|
||||
// Only that end moved: the line turned about its other end, and the circle stayed.
|
||||
assert!(a.x.abs() < 1e-9 && (a.y - 20.0).abs() < 1e-9, "the line's other end moved to {a:?}");
|
||||
assert!((centre.x - 50.0).abs() < 1e-9 && centre.y.abs() < 1e-9 && (radius - 10.0).abs() < 1e-9, "the circle moved: {centre:?}, radius {radius}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_preselection_preserves_document_and_error() {
|
||||
let mut h = lines();
|
||||
|
||||
@@ -61,9 +61,10 @@ handler and everything it passes `p` to:
|
||||
that take picks;
|
||||
- `live`, for a command with `.live(…)` (today `sketch.drag` and `sketch.edit_text`): a call
|
||||
with `live: true` goes to the live runner, which `checked!` doesn't wrap, so live calls aren't
|
||||
checked yet. Leave those two on the list until the engine checks the live path too. A new
|
||||
command that needs a live runner still gets its contract (declare `live` as an optional
|
||||
`bool`); say in its pull request that its live calls aren't checked.
|
||||
checked yet. Leave `sketch.drag` on the list until the engine checks the live path too;
|
||||
`sketch.edit_text` has its contract (with `live` declared as an optional `bool`) and its live
|
||||
calls aren't checked. A new command that needs a live runner gets its contract the same way;
|
||||
say in its pull request that its live calls aren't checked.
|
||||
|
||||
A key the handler reads only in some situations (thin-wall keys with `thin: true`) is still a
|
||||
field; its description says when it applies. Contracts don't check combinations of keys
|
||||
|
||||
@@ -895,6 +895,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own
|
||||
- `ground_shadow_follows_model` (Graphics, default false): raised models cast their ground shadow on the origin ground plane; true restores the shadow below the lowest visible body. Both modes keep the shadow below bodies extending beneath the origin, and follow the selected up axis.
|
||||
- `hidden_toolbar_tabs` (default `[]`: all existing tabs, including Sheet Metal and Weldments, stay visible; lists tabs to hide, each once, e.g. `["SURFACE", "SHEET METAL"]`; hidden tabs stay hidden regardless of the design's features; [ribbon layout](ribbon-layout.md))
|
||||
- `history_sketches` (`in_order` (default), `under_feature`: the History at the left lists a sketch under the first feature built from it, #6489; the timeline at the bottom keeps the creation order)
|
||||
- `hole_group` (default false: the holes one Hole command makes, two or more, go into a feature folder in History, closed at first)
|
||||
- `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there)
|
||||
- `hole_several` (default false: a face takes several Single holes; a pick elsewhere on a face that has a hole adds another, and a pick on a hole takes it out)
|
||||
- `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres)
|
||||
|
||||
@@ -13,6 +13,7 @@ Each group is a 120x64 figure at the left of its checkboxes, with a group name u
|
||||
| Hole: Snap to centres | Checkbox | `Prefs.hole_snaps` | `false` | "The middle of a face and the centres of its round edges." | `tool-hole` | Today's label "Snap to face and edge centres". |
|
||||
| Hole: Move by click or drag | Checkbox | `Prefs.hole_moves` | `false` | "Picking the face again moves the hole instead of removing it." | `tool-hole` | Today's label "Move holes by clicking or dragging". |
|
||||
| Hole: Several per face | Checkbox | `Prefs.hole_several` | `false` | "Picking elsewhere on a face adds another hole; picking a hole removes it." | `tool-hole` | Label "Several holes on one face". |
|
||||
| Hole: Group holes made together | Checkbox | `Prefs.hole_group` | `false` | "Holes made in one go share a folder in History, closed at first; open it to edit a hole on its own." | `tool-hole` | Label "Group holes made together". |
|
||||
| Extrude: Extrude to a picked target | Checkbox | `Prefs.extrude_auto_to_object` | `true` | "A face, vertex or parallel plane switches the extent to To Object." | `tool-extrude` | |
|
||||
| Extrude: Choose the operation automatically | Checkbox | `Prefs.auto_operation` | `true` | "Join, New Body or Cut, from what the material touches." | `tool-extrude` | |
|
||||
| Extrude: Turn the view to isometric when Extrude opens | Checkbox | `Prefs.extrude_view_isometric` | `false` | none | `tool-extrude` | Retained newer control, directly after automatic operation in the same group. |
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ ordinary `execute` tool: `render.preflight`, `render.start`, `render.status`,
|
||||
in the session until explicit PNG export. See [render jobs](render-jobs.md).
|
||||
|
||||
For sandboxed plugins and parametric timeline
|
||||
features that also use `run(command, args)`, see [plugins.md](plugins.md). Desktop MCP in this
|
||||
features that also use `run(command, args)`, see [RFC 0002](rfcs/0002-plugins.md). Desktop MCP in this
|
||||
document remains the reference implementation today.
|
||||
|
||||
## Start it
|
||||
|
||||
+2
-141
@@ -1,142 +1,3 @@
|
||||
# Plugins (design)
|
||||
# Plugins
|
||||
|
||||
Design companion to [#1221](https://github.com/bherbruck/solidcraft/issues/1221): sandboxed
|
||||
WebAssembly plugins with a WIT interface, the same `run(command, args)` JSON as
|
||||
[MCP](mcp.md) and the [control protocol](control-protocol.md).
|
||||
|
||||
This document adds **parametric timeline features**: a generic host-owned feature shell that
|
||||
plugins fill with parameters, display metadata, and rebuild logic, without a second timeline
|
||||
model or a private geometry API.
|
||||
|
||||
## Goals (unchanged from #1221)
|
||||
|
||||
- Sandboxed by default: manifest permissions, fuel/memory limits on desktop, broker enforcement on web.
|
||||
- Any language that compiles to Wasm components; Rust first.
|
||||
- **One command surface:** plugins change the model only through engine commands (undoable, journaled).
|
||||
- Versioned WIT world (`solidcraft:plugin@1.0.0`).
|
||||
|
||||
## Two plugin shapes
|
||||
|
||||
| Shape | Timeline | Rebuild | Milestone |
|
||||
|-------|----------|---------|-----------|
|
||||
| **One-shot** | Optional; often no persistent feature | N/A | 1 (first ship) |
|
||||
| **Parametric** | One **`Plugin` feature row** per plugin instance | Host calls plugin on param/timeline rebuild | 2 |
|
||||
|
||||
One-shot plugins call `execute(params)` once; they may emit ordinary native features (sketch,
|
||||
extrude, …) inside that transaction. Parametric plugins still use `run()` inside rebuild; the
|
||||
difference is that the document **records** a single feature whose params the user edits later.
|
||||
|
||||
## Generic feature shell (host-owned)
|
||||
|
||||
Add one variant to the parametric document (name illustrative):
|
||||
|
||||
```text
|
||||
FeatureKind::Plugin {
|
||||
plugin_id: String, // "gear_generator"
|
||||
api_version: u32, // matches WIT world
|
||||
params: Value, // JSON owned by the plugin schema
|
||||
display: PluginDisplay, // timeline + browser presentation
|
||||
provenance: PluginProvenance, // optional: manifest hash, build id
|
||||
}
|
||||
```
|
||||
|
||||
**`PluginDisplay`** (stored in the file, not recomputed from plugin code at open):
|
||||
|
||||
| Field | Role |
|
||||
|-------|------|
|
||||
| `label` | Primary timeline / browser text |
|
||||
| `icon_id` | Host icon registry name (same system as [`feature_icon`](https://github.com/bherbruck/solidcraft/blob/main/crates/ui-egui/src/workspace.rs)) |
|
||||
| `tooltip` | Hover text, `inspect` type string |
|
||||
| `type_name` | short feature type name for power users |
|
||||
|
||||
The timeline renders **any** `Plugin` feature through one code path: read `display`, draw icon +
|
||||
label, wire suppress/rename/delete/reorder like built-in features. No per-plugin egui in milestone 2.
|
||||
|
||||
Optional later: **`parameter_schema()`** in WIT returns `{ id, label, kind, min, max, … }` so the
|
||||
host renders sliders and dimension rows without custom UI per plugin.
|
||||
|
||||
## WIT entry points (phase 2 additions)
|
||||
|
||||
Milestone 1 (#1221): `manifest()`, `execute(params) -> result<string, string>`.
|
||||
|
||||
Milestone 2 parametric:
|
||||
|
||||
| Export | Purpose |
|
||||
|--------|---------|
|
||||
| `evaluate(params, ctx) -> result<string, string>` | Rebuild: plugin runs `run()` commands; result is success JSON or error |
|
||||
| `parameter_schema() -> string` | Optional JSON schema for generic parameter UI |
|
||||
| `fallback_policy() -> string` | Declares missing-plugin behaviour (see below) |
|
||||
|
||||
`ctx` is host-provided read-only hints (configuration name, units, feature id); plugins must not
|
||||
rely on it for correctness.
|
||||
|
||||
Inside **`evaluate`**, the plugin uses the same **`run(command, args)`** import as one-shot mode.
|
||||
The host applies commands to the current eval context (or a scratch session merged by the host).
|
||||
No second registry of geometry ops.
|
||||
|
||||
## Rebuild flow
|
||||
|
||||
```text
|
||||
Timeline rebuild reaches FeatureKind::Plugin
|
||||
-> load plugin (wasmtime desktop / broker web) if permitted + present
|
||||
-> evaluate(stored params)
|
||||
-> plugin calls run("sketch.line", …), run("solid.extrude", …), …
|
||||
-> host merges geometry like any native feature
|
||||
-> errors surface on the feature row like native eval errors
|
||||
```
|
||||
|
||||
Param changes (parameter panel, `parameters.change`, config switch) re-run **`evaluate`** for
|
||||
affected plugin features only when dependencies say so (same invalidation rules as native features).
|
||||
|
||||
## Missing plugin and API drift
|
||||
|
||||
Manifest declares **`fallback_policy`**:
|
||||
|
||||
| Policy | Behaviour |
|
||||
|--------|-----------|
|
||||
| `recorded_mesh` | Optional B-rep or mesh blob stored beside params; open works, edit disabled without plugin |
|
||||
| `recorded_script` | Stored list of native commands; rebuild without plugin if every command is built-in |
|
||||
| `suppress_with_warning` | Feature suppressed; user sees clear message |
|
||||
| `error_on_rebuild` | Hard fail on eval (strict teams) |
|
||||
|
||||
Shared design files should prefer a policy that **opens safely** (`recorded_mesh` or
|
||||
`recorded_script`). CI for plugins (#1221) should include: uninstall plugin, reopen file, assert
|
||||
document still opens and policy matches manifest.
|
||||
|
||||
## Icons and metadata
|
||||
|
||||
Plugins declare allowed **`icon_id`** values in `manifest()`; the host rejects unknown ids. Icons
|
||||
stay in the app registry so untrusted plugins cannot inject arbitrary raster assets into the tree
|
||||
without a reviewed icon pack.
|
||||
|
||||
**Rename** by the user updates the feature user label; **`display.label`** remains the default from
|
||||
creation unless the plugin updates it via a host callback (optional future).
|
||||
|
||||
Command naming: prefer **`plugin_id.function`** in `run()` or registered command aliases to avoid
|
||||
collisions ([#1221 discussion](https://github.com/bherbruck/solidcraft/issues/1221)).
|
||||
|
||||
## Group header variant (lighter-weight v2a)
|
||||
|
||||
Before full **`evaluate`**, a stepping stone: one-shot plugin creates a **feature folder** whose
|
||||
header carries `PluginDisplay` metadata while children are ordinary native features. Rebuild does
|
||||
not need the plugin until the user edits plugin-owned params on the header. Migrates cleanly to
|
||||
full `FeatureKind::Plugin` when `evaluate` lands.
|
||||
|
||||
## Where the code lives
|
||||
|
||||
Plugin **document model and eval** stay in SolidCraft (`crates/doc`, `crates/engine`).
|
||||
|
||||
## Phasing
|
||||
|
||||
1. WIT + wasmtime host + one-shot `execute` + permissions tests (#1221 milestone 1).
|
||||
2. `FeatureKind::Plugin` + `PluginDisplay` + timeline generic row + `evaluate` + fallback policy.
|
||||
3. Web broker runs same WIT; parametric features offline only if plugin module cached and policy
|
||||
allows.
|
||||
4. Parameter schema UI, cloud-signed plugin index, inspector extensions.
|
||||
|
||||
## Tests (parametric)
|
||||
|
||||
- Create plugin feature, change param, rebuild, measure geometry (oracle or bbox).
|
||||
- Undo/redo across plugin eval.
|
||||
- Remove plugin binary, reopen design, assert fallback policy.
|
||||
- Icon id from manifest appears on timeline (scenario or screenshot harness).
|
||||
Moved to [RFC 0002: Plugins](rfcs/0002-plugins.md).
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# RFC 0001: Craft bridge, handing work between Craft apps
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Status | Draft, open for comment |
|
||||
| Started | 2026-11-07 |
|
||||
| Apps | SolidCraft, CamCraft, PCBCraft |
|
||||
| Discussion | the pull request that adds this file, then an issue per phase |
|
||||
|
||||
Nothing here is built yet.
|
||||
|
||||
## 1. Goals and non-goals
|
||||
|
||||
**Goals**
|
||||
- One button: "Send to CamCraft" opens the current design in CamCraft, ready to set up.
|
||||
- Round trips that stay linked: edit the model in SolidCraft, and CamCraft sees the new revision, re-finds its picked faces and regenerates or marks paths stale.
|
||||
- The same for PCBCraft: board outline, holes and parts go to SolidCraft; the enclosure's outline and mounting points go back.
|
||||
- Nothing is lost quietly. A reference that no longer resolves is reported by name.
|
||||
|
||||
**Non-goals**
|
||||
- No merged app and no shared process. Each app runs and ships on its own.
|
||||
- No shared file format. `.sc`, `.camproj` and PCBCraft's project stay as they are. The bridge adds one small exchange format between them.
|
||||
- No editing another app's data. Each item has one owner app.
|
||||
|
||||
## 2. What crosses the bridge
|
||||
|
||||
One **exchange file**, `*.craftx`: a ZIP like the `.sc` container, with parts addressed by SHA-256 and a manifest.
|
||||
|
||||
| Part | Content | Notes |
|
||||
|---|---|---|
|
||||
| `manifest.json` | `format: "craft-exchange/1"`, source app and version, `source_id` (permanent design id), `revision`, content hash, units, the parts it has | Required. Readers ignore parts they don't know. |
|
||||
| `bodies/<n>.record` | Exact B-rep as a solidcore-record body file | Preferred geometry. CamCraft can read it once its Solidcore milestone (M12.1) lands. |
|
||||
| `bodies/<n>.step` | STEP of the same body | Fallback any app reads today. |
|
||||
| `mesh/<n>.bin` | Triangles, plus a per-triangle face index | For apps that cut or display meshes. CamCraft slices meshes today. |
|
||||
| `faces.json` | Per body: each face's index → persistent name, `exact` flag, surface type, aliases (names it also answers to after a merge). Edges the same way (`<face A>\|<face B>`). | The key to surviving edits. |
|
||||
| `params.json` | Exposed parameters: name, value, unit, expression (read-only) | So CAM can show "wall = 3 mm", and PCB can drive SolidCraft parameters later. |
|
||||
| `meta.json` | Material, part number, stock hint (box or offset), colour per face | Taken from design and component metadata. |
|
||||
| `board.json` | PCB only: outline, cutouts, holes with names, part placements and heights, keep-outs | Defined with PCBCraft. |
|
||||
|
||||
**Stable ids.** SolidCraft already names every face and edge from kernel history (`F2:top`, `F4:side:l4`, `F2:top#[…]` for pieces, `F5:blend:<edge>` for rounds). `model.faces` reports them, with `exact: false` where a name was found by geometry. The exchange carries these strings as given. Receivers treat them as opaque strings. CamCraft picks today are facet-geometry hashes; a linked model would also store the face name, which survives an added hole where a facet hash may not.
|
||||
|
||||
## 3. Transport
|
||||
|
||||
| Option | Desktop | Browser (wasm) | Good for | Weak at |
|
||||
|---|---|---|---|---|
|
||||
| **A. Exchange file + file watching** | Yes. Write beside the design, watch for changes. | Same-origin apps can share OPFS. No watching, so poll or use the `BroadcastChannel` below. | Durable, works with either app closed, easy to debug | Update waits for a save |
|
||||
| **B. Control channel session** (SolidCraft's existing loopback socket, token file, `control.subscribe` → `design.changed`) | Yes, already shipped | No sockets. The same messages can go over `postMessage` or `BroadcastChannel` between same-origin tabs. | Instant change notice, handshake | Both apps must run |
|
||||
| **C. MCP** | Yes (stdio) | No | Agents driving both apps | Made for agent to app, not app to app. No events between apps. |
|
||||
| **D. Launcher / "open in"** (start the other app with a path; later a registered file type or `camcraft://open?path=`) | Yes | `window.open` the other app's URL with the file in shared OPFS, or hand it over with `postMessage` | The button | Carries no updates by itself |
|
||||
|
||||
**Recommendation: A + D now, B as a speed-up.** The exchange file is the contract and the only thing an app must read. The button writes it and launches the other app with its path; live linking watches that file. A running app may also take a control-channel notice for faster updates. MCP stays for agents.
|
||||
|
||||
## 4. Linking and change propagation
|
||||
|
||||
- **A link** in the receiving project is `{source_id, path hint, revision, content hash}`. `source_id` is the permanent id. The path is only a hint, as in PCBCraft's file rules and SolidCraft's Insert Design links.
|
||||
- **Change detection**: the exchange file's hash differs from the linked one → there's a new revision. Taking it can be automatic or one click; the receiver decides.
|
||||
- **Re-resolving references** (each receiver does this, with the same outcomes SolidCraft uses for linked designs):
|
||||
|
||||
| Outcome | Meaning | Receiver does |
|
||||
|---|---|---|
|
||||
| exact | the name is there | keeps the pick |
|
||||
| merged | another face answers to it as an alias | keeps it, notes the merge |
|
||||
| split | several pieces carry the name | uses all pieces, or asks the user if that changes the meaning |
|
||||
| by geometry | the name only matched on an `exact: false` face | keeps it, flags "check this" |
|
||||
| missing | gone | **marks the operation broken, naming the face and where it was. It keeps the old path for viewing, refuses to post it, and asks the user to re-pick. Never dropped quietly.** |
|
||||
|
||||
- **Who owns what** (one owner per item; the other side holds a read-only linked copy, and Break Link turns it into its own editable copy):
|
||||
|
||||
| Item | Owner | Others get |
|
||||
|---|---|---|
|
||||
| Part geometry, parameters, face names | SolidCraft | CamCraft, PCBCraft (read) |
|
||||
| Setups, stock, WCS, tools, toolpaths, posts | CamCraft | Nothing yet (maybe stock and as-machined bodies later) |
|
||||
| Board outline, holes, part placement and heights | PCBCraft | SolidCraft (a linked body and sketch, like an inserted design) |
|
||||
| Enclosure-driven outline and mount points | SolidCraft | PCBCraft (read, shown as a constraint it can accept) |
|
||||
|
||||
To change something you don't own, "Edit in SolidCraft" (or the owner app) opens the source.
|
||||
|
||||
## 5. The SolidCraft side
|
||||
|
||||
Every step is a command with input and output schemas. Programmatic calls never open dialogs.
|
||||
|
||||
| Command | Does |
|
||||
|---|---|
|
||||
| `bridge.export {path?, bodies?, parts?: [record, step, mesh], mesh_tolerance?}` | Writes a `.craftx` and returns `{path, revision, hash, faces, warnings}`. Refuses with `BadParams` on a design with feature errors or no bodies, saying why. |
|
||||
| `bridge.send {app, bodies?}` | Exports, then launches `app` with the path. If the app isn't found, it returns an error that names the setting to fix. No file picker. |
|
||||
| `bridge.links` | Lists the targets this design exports to and the exchanges it has inserted, each with revision, `changed` and missing references. |
|
||||
| `bridge.auto {target, on}` | Rewrites the exchange on every save. |
|
||||
| `file.insert_exchange {path}` | Brings in a PCBCraft board (or any `.craftx`) as a linked component. It reuses Insert Design's link, Update Links and Break Link machinery and face matching. |
|
||||
| `component.update_links` | Also covers inserted exchanges. Reports joint and reference errors as it does today. |
|
||||
|
||||
Face names, `model.faces`, linked-design face matching, design metadata and `control.subscribe` already exist.
|
||||
|
||||
**Format additions** (one file per change in `crates/doc/src/format/pending/`):
|
||||
- `design-source-id.rs`: a permanent random id for each design, made on first save. Older designs get one when next saved. A copy made with Save As gets a new one.
|
||||
- `bridge-targets.rs`: the export targets (`app`, path hint, auto on or off).
|
||||
Inserted exchanges ride the existing Import feature link fields. An older release warns, opens what it can and keeps the rest. Another app's private data, if ever stored in a design, goes under its own reverse-DNS metadata key, which SolidCraft already preserves.
|
||||
|
||||
**UI**: a "Send to CamCraft" button, and later "Send to PCBCraft". It changes the default ribbon, so the owner decides where it goes before it merges.
|
||||
|
||||
## 6. A contract any Craft app can implement
|
||||
|
||||
- **Read**: `craft-exchange/1`. A reader reads the parts it knows, warns about the rest, and never refuses a file for a newer minor version.
|
||||
- **Versioning**: `craft-exchange/<major>`. Minor additions are new optional parts or fields. Only a major bump may change meaning. The manifest lists `requires` (the parts a reader must understand to use the file safely) separately from `parts`.
|
||||
- **Capabilities**: strings with versions, e.g. `brep.solidcore-record/1`, `step/ap214`, `mesh/1`, `faces.names/1`, `params/1`, `meta/1`, `board/1`. A writer includes what it can. A reader takes the best it supports, preferring record, then STEP, then mesh.
|
||||
- **Live session (optional)**: `bridge.hello {app, version, protocol: [1], capabilities}` gets the same answer back. Both use the highest common protocol and the capabilities they share. After that come `exchange.changed {source_id, revision, hash, path}` notices and `exchange.request {source_id}` asking for a fresh export. On desktop these go over the control channel. In the browser they go over `BroadcastChannel`, with the same JSON.
|
||||
- **Launch**: each app accepts `--open <file.craftx>` (or a file path argument). A running instance should take the file over instead of starting a second window.
|
||||
- **Units and frames**: millimetres, in the source design's world frame; the manifest carries the display unit. The receiver places bodies (WCS, component placement).
|
||||
|
||||
## 7. Phases
|
||||
|
||||
| Phase | Delivers | Who |
|
||||
|---|---|---|
|
||||
| 0 | Agree on this contract and the manifest | Both authors |
|
||||
| 1 | **Send to CamCraft**: `bridge.export` (STEP, mesh, face table) plus launching CamCraft with the path. CamCraft imports the STEP as it does today. | SolidCraft. CamCraft only needs a path argument. |
|
||||
| 2 | CamCraft reads `faces.json`: picks store face names, and re-sending updates the same model (its existing UpdateModel and stale marking), with the outcome table above | CamCraft |
|
||||
| 3 | Live: `bridge.auto` + file watching. CamCraft either marks paths stale or regenerates; it never posts on its own. Plus a control-channel notice for running apps. | Both |
|
||||
| 4 | Exact B-rep through solidcore-record, once CamCraft moves to Solidcore | Both |
|
||||
| 5 | PCBCraft: board → SolidCraft via `file.insert_exchange`, and enclosure outline → PCBCraft, once PCBCraft has boards | PCBCraft, SolidCraft |
|
||||
| 6 | Browser: shared OPFS, `BroadcastChannel`, `window.open` hand-off between same-origin web builds | All |
|
||||
|
||||
## 8. Open questions for CamCraft's author
|
||||
|
||||
1. **Would CamCraft store our face and edge names on its picks, next to its facet-hash ids, and re-resolve by name first?** That one choice decides whether CAM setups survive model edits.
|
||||
2. Does `camcraft-ui` accept a file path at launch, and can a running window take a second file instead of opening a new one?
|
||||
3. Should a linked model update automatically and mark paths stale, or regenerate them too, and with what confirmation?
|
||||
4. Should stock and material come from SolidCraft (a stock hint in `meta.json`), or stay CamCraft-only?
|
||||
5. Where should the exchange file live: beside the `.sc`, beside the `.camproj`, or copied into the project, as CamCraft keeps facets today?
|
||||
6. Is there anything CamCraft wants to send back, such as the as-machined body for drawings, or fixture bodies for assemblies?
|
||||
7. What's the timing for Solidcore (M12.1), so we know when to put the B-rep record first?
|
||||
8. Would CamCraft add the optional live session over a socket, or is watching the file enough?
|
||||
@@ -0,0 +1,143 @@
|
||||
# RFC 0002: Plugins, sandboxed WebAssembly extensions
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Status | Draft, open for comment |
|
||||
| Started | 2026-10-14 (when #1221 opened) |
|
||||
| Apps | SolidCraft |
|
||||
| Discussion | [#1221](https://github.com/tangency-labs/solidcraft/issues/1221) |
|
||||
| Related | [#4980](https://github.com/tangency-labs/solidcraft/pull/4980) (draft WIT proposal, `solidcraft:plugin@0.1.0`), [#4933](https://github.com/tangency-labs/solidcraft/pull/4933) (plugin commands in Utilities) |
|
||||
|
||||
This RFC replaces `docs/plugins.md` and folds in what the 37 comments on #1221 settled. Only the Preferences page exists today. No plugin runs.
|
||||
|
||||
## 1. Goals and non-goals
|
||||
|
||||
**Goals**
|
||||
- Drop in a file and get a new command, importer, exporter or sketch tool, without rebuilding the app.
|
||||
- Sandboxed by default. A plugin can do only what its manifest asks and the user allows. A crash or a hang cannot take down the app or the model.
|
||||
- Any language that compiles to a WebAssembly component. Rust first.
|
||||
- One command surface. Plugins change the model only through the engine commands that MCP and the control channel already use, so every edit is undoable and journaled. No private geometry API.
|
||||
- A plugin built for API 1 keeps loading after app updates.
|
||||
|
||||
**Non-goals**
|
||||
- Not a way to override core commands. Overrides would make a model behave differently depending on what is installed.
|
||||
- Not where core features go. CAM, for example, stays in-tree (#1153); plugins add vendor posts, niche strategies and importers on top.
|
||||
- No plugin-to-plugin calls. If plugins ever cooperate, it goes through host events, and a failing listener never fails the caller.
|
||||
|
||||
## 2. The WIT contract
|
||||
|
||||
World `solidcraft:plugin@1.0.0`. The interface stays thin: a few typed functions plus the JSON command set, so the WIT stays small while the commands keep growing.
|
||||
|
||||
| Host import | Notes |
|
||||
|---|---|
|
||||
| `run(command, args) -> result<string, string>` | The engine commands, JSON in and out, exactly as over MCP. Filtered by the plugin's permissions. |
|
||||
| `log`, `progress` | Always available. |
|
||||
| `read-file`, `write-file` | Only inside folders the user granted. |
|
||||
| `fetch` | Only with the `net` permission, only to origins named in the manifest, made by the host. |
|
||||
|
||||
| Export | Notes |
|
||||
|---|---|
|
||||
| `manifest() -> string` | JSON: id, name, version, kind, permissions, parameters. |
|
||||
| `execute(params) -> result<string, string>` | A command or one-shot feature. |
|
||||
| `import(...)` / `export(...)` | File formats. See below. |
|
||||
|
||||
**Settled in the comments**
|
||||
- Plugin commands are namespaced `plugin_id.function`. They appear in `list_commands` and the Assistant's tool list with their parameter docs.
|
||||
- Importers need the file name, not just bytes (the extension picks the format), and return a design plus a loss report. Assemblies need read access to the input's folder, granted as a permission. #4980 streams the input to keep each host call small.
|
||||
- A trap fails that one call ("the importer failed on this file") and the next call gets a fresh instance.
|
||||
- Entries declare `effect: read | edit`. A `read` entry is limited to query commands, so the agent chat can run it without asking.
|
||||
- Entry inputs should be schemas built from the same field types as the command contracts (#2829), so one declaration gives a native dialog, strict MCP checks and generated tests. A one-line `params` doc is accepted until 1.0.
|
||||
|
||||
**Permissions** sit in the manifest, are shown on an approval screen, and are approved before any plugin code runs. A change to what was approved stops the plugin until the user approves again. A code-only update never adds an entry or surface silently.
|
||||
|
||||
| Permission | Grants |
|
||||
|---|---|
|
||||
| (none) | `run`, `log`, `progress` |
|
||||
| `files` | Named folders, read or write |
|
||||
| `net` | Named `https` origins. On the web build, only through a host-approved fetch. |
|
||||
| `clock` | Wall clock. Without it, it reads a fixed epoch. |
|
||||
|
||||
## 3. Runtime and sandbox
|
||||
|
||||
| Item | Decision |
|
||||
|---|---|
|
||||
| Runtime | wasmtime on desktop, with the component model |
|
||||
| CPU | Fuel or epoch interruption; the loop is stopped and the call fails |
|
||||
| Memory | A per-plugin limit; a configurable stack (a real decoder needed about 16 MiB, wasmtime's default is 512 KiB) |
|
||||
| WASI | None unless a permission grants a narrow slice |
|
||||
| Failure | A fresh instance per call after a trap. The design and undo stack are untouched. |
|
||||
|
||||
**Binary-size trade-off.** wasmtime with Cranelift adds several MB to the app. wasmi is much smaller but runs core modules, not components. Options are wasmtime with Winch or Pulley, or accepting the size. Not decided.
|
||||
|
||||
**Component size.** #4980 caps components at 16 MiB. A real converter measured 28 MB (built for size) to 42 MB. Compiling happens in the app's process with no sandbox limit on the compiler, and the project forbids `unsafe`, so compiled code cannot be cached (`Component::deserialize` is `unsafe`). One plugin per format avoids most of this.
|
||||
|
||||
Rhai was proposed instead. The comments favour one runtime, WebAssembly, for isolation and language choice.
|
||||
|
||||
## 4. Plugin kinds
|
||||
|
||||
| Kind | Timeline | When |
|
||||
|---|---|---|
|
||||
| One-shot command | Optional. It may emit ordinary native features inside one undo step. | First |
|
||||
| Importer / exporter | None. Opens as a new unsaved design. | First |
|
||||
| Parametric feature | One `Plugin` feature row per instance, rebuilt when parameters change | Later |
|
||||
| Panels, overlays, workspaces | Host-drawn from a declared schema | Later, see questions |
|
||||
|
||||
**Parametric features** (from `docs/plugins.md`). A host-owned `FeatureKind::Plugin` row stores `plugin_id`, `api_version`, the plugin's JSON `params`, and a `PluginDisplay` (label, icon id from the app's registry, tooltip, type name), all recorded in the file. The timeline draws any such row through one code path. On rebuild the host calls `evaluate(params, ctx)`, which uses the same `run` import, and merges the result like a native feature. An optional `parameter_schema()` lets the host draw sliders and dimension rows.
|
||||
|
||||
**SolidCraft never refuses to open a file.** Every parametric plugin declares a recorded fallback, so a design opens without the plugin:
|
||||
|
||||
| Fallback | Behaviour without the plugin |
|
||||
|---|---|
|
||||
| `recorded_script` | Replays a stored list of native commands, when every command is built in |
|
||||
| `recorded_mesh` | Shows a stored B-rep or mesh; editing is disabled |
|
||||
| `suppress_with_warning` | Feature is suppressed with a clear message |
|
||||
| `error_on_rebuild` | Hard error; for strict teams only |
|
||||
|
||||
Shared designs should use one of the first two. A plugin's output should come from native features (sketches, extrudes, holes), so it works without the plugin. If a plugin cannot reach its goal that way, core is missing a building block. Opening a design never downloads or runs a missing package. Each instance keeps its plugin revision until the user updates it, and the update is undoable.
|
||||
|
||||
Design metadata under `plugin.<id>` survives a missing, disabled or newer plugin. Plugin store data is read additively across versions, and the first call after an update is told the previous version.
|
||||
|
||||
## 5. Distribution and signing
|
||||
|
||||
- **Now:** a folder per plugin, `{data}/plugins/<id>/plugin.json`.
|
||||
- **Next:** Install Plugin from a file or GitHub release. An Add-on Manager lists tools, versions and permissions, with enable, disable and remove.
|
||||
- **Later:** a curated index. Anyone can sideload. To be listed, a plugin must be open source and signed. The comments favour GitHub Releases as the artifact source and keeping packages independent of one host.
|
||||
- **Tools:** `solidcraft-cli plugin check <dir>` validates the manifest and schemas; `plugin test <dir>` runs every entry on the real host; `--plugin-dev <dir>` loads an unapproved folder, marked as dev, and reloads on change. The `plugin.json` schema is generated from the host's types.
|
||||
|
||||
## 6. Web build
|
||||
|
||||
wasmtime does not run in the browser tab. Options are jco-transpiled components, or desktop-only plugins at first. The same WIT world and manifest should serve both, with the same permission checks before `run` reaches the engine. Parametric features offline on the web need the module cached, so only plugins whose fallback allows it. Network access on the web goes through a host-approved fetch, never the page's own.
|
||||
|
||||
## 7. What exists today
|
||||
|
||||
**Built**
|
||||
- Preferences > Plugins (`crates/ui-egui/src/plugins.rs`, #2718): lists `{data}/plugins/<id>/plugin.json` folders, searches them, and turns each off. Turned-off ids are saved in `disabled_plugins`. Folders that are not plugins are listed with the reason.
|
||||
- The manifest it reads has only `id`, `name`, `version` and `description`. It is checked and capped at 16 KiB.
|
||||
|
||||
**Not built**
|
||||
- No wasmtime, no WIT file, no host, no example plugin, no permissions, no signing, no install flow (#4330 was closed), no `Plugin` feature kind. Nothing in the folder is loaded or run.
|
||||
- #4980 is an open draft of the WIT and a gear pilot, and is not merged.
|
||||
|
||||
## 8. Phases
|
||||
|
||||
| Phase | Delivers |
|
||||
|---|---|
|
||||
| 1 | WIT, a wasmtime host with fuel and memory limits, `execute`, permissions in the manifest, tests: no file access without a grant, a runaway loop is stopped, a crash leaves the model untouched, undo works |
|
||||
| 2 | Spur-gear example plugin, author guide, `plugin check` and `plugin test`, importers and exporters |
|
||||
| 3 | `FeatureKind::Plugin`, `evaluate`, recorded fallbacks, generic timeline row |
|
||||
| 4 | Install from file or GitHub, Add-on Manager, parameter schema dialogs |
|
||||
| 5 | Web host on the same WIT |
|
||||
| 6 | Curated, signed index; panels and overlays if agreed |
|
||||
|
||||
## 9. Open questions
|
||||
|
||||
1. **Wasmtime size and component limit.** Accept the binary growth, and raise the 16 MiB limit after measuring compile memory?
|
||||
2. **Plugin UI.** Declarative panels, viewport overlays, then workspaces (the slicer-as-a-tab case). Or should such tools live in-tree?
|
||||
3. **Defaults.** Are newly installed plugins on or off until approved?
|
||||
4. **Local network.** May a plugin reach a companion service on the user's machine, entered by the user? Starting a print also needs a confirmation level above `edit`.
|
||||
5. **Extending core commands.** Data-driven extension points, such as thread standards in the Hole dialog, later. Never overrides.
|
||||
6. **Signing and the index.** What signs, who hosts the index, and who reviews listings?
|
||||
7. **Web.** jco, or desktop only?
|
||||
8. **Result annotations.** Text a plugin adds to command results can steer a model, so it needs its own threat model.
|
||||
9. **Recorded macros.** A plugin kind or a core feature?
|
||||
10. **Version numbers.** #4980 uses `0.1.0` until the interface settles; this RFC says `1.0.0`.
|
||||
@@ -0,0 +1,10 @@
|
||||
# RFCs
|
||||
|
||||
Proposals for changes that cross apps or repositories, or that need agreement before code. Each RFC is one file, `NNNN-short-name.md`, numbered in order, with a status table at the top: Draft, Accepted, Rejected or Replaced.
|
||||
|
||||
A Draft is discussed in the pull request that adds it. Once accepted, the work is tracked in issues and the RFC links to them. An RFC records the decision; it is not a promise of a date.
|
||||
|
||||
| RFC | Title | Status |
|
||||
|---|---|---|
|
||||
| [0001](0001-craft-bridge.md) | Craft bridge: handing work between Craft apps | Draft |
|
||||
| [0002](0002-plugins.md) | Plugins: sandboxed WebAssembly extensions | Draft |
|
||||
@@ -75,19 +75,6 @@ staple() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# validate <path>: stapler validate looks the ticket up at Apple and can lose the connection
|
||||
# ("The network connection was lost", error 68), so try it a few times as staple does.
|
||||
validate() {
|
||||
local i
|
||||
for i in 1 2 3 4 5 6; do
|
||||
if xcrun stapler validate "$1"; then return 0; fi
|
||||
echo "stapler validate failed (attempt $i), retrying" >&2
|
||||
sleep "${STAPLE_RETRY_SLEEP:-20}"
|
||||
done
|
||||
echo "could not validate the staple of $1" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
ARCH=universal
|
||||
SKIP_BUILD=0
|
||||
BUILD_ONLY=
|
||||
@@ -202,7 +189,7 @@ if [ "$NOTARIZE" = 1 ]; then
|
||||
ditto -c -k --keepParent "$APP" "$WORK/SolidCraft-app.zip"
|
||||
notarize "$WORK/SolidCraft-app.zip"
|
||||
staple "$APP"
|
||||
validate "$APP"
|
||||
xcrun stapler validate "$APP"
|
||||
fi
|
||||
|
||||
# ---- DMG ---------------------------------------------------------------------------------------
|
||||
@@ -255,7 +242,7 @@ if [ "$NOTARIZE" = 1 ]; then
|
||||
echo "==> notarizing $DMG"
|
||||
notarize "$DMG"
|
||||
staple "$DMG"
|
||||
validate "$DMG"
|
||||
xcrun stapler validate "$DMG"
|
||||
# Gatekeeper's verdict on the DMG and on the app as a user gets it.
|
||||
spctl -a -t open --context context:primary-signature -vv "$DMG"
|
||||
MNT="$(mktemp -d)"
|
||||
|
||||
@@ -12,7 +12,6 @@ solidcraft-cli::naming_corpus::corpus_designs_name_alike_every_build_and_fail_wh
|
||||
solidcraft-doc::eval::cost_tests::a_tap_marking_searches_only_the_bodies_near_it main's mesh-based version (#10303) not taken; the exact replacement is to come
|
||||
solidcraft-doc::eval::cost_tests::a_tap_marking_still_searches_the_bodies_within_its_reach main's mesh-based version (#10303) not taken; the exact replacement is to come
|
||||
solidcraft-engine::cmd::edit::tests::inserting_variable_fillet_control_preserves_parameters_at_existing_positions solidcore refuses a variable fillet whose law has a corner (solidcore#430)
|
||||
solidcraft-engine::cmd::file::tests::each_format_has_an_export_command_of_its_own the box's planar faces are meshed into 124 triangles, not 12 (the STL is 6284 bytes, the test counts 84 + 50 x 12), as on SMLib
|
||||
solidcraft-engine::extent_tests::cut_to_the_far_side_of_a_curved_wall main's mesh-based version (#8634) not taken; the exact replacement is to come
|
||||
solidcraft-engine::face_name_tests::a_join_that_makes_the_body_bigger_leaves_round_walls_it_never_touched_alone main's edge lookup by a stored point (#11286) finds the edge on the display mesh (edge_near on the body's mesh), not taken; the exact replacement is to come
|
||||
solidcraft-engine::hole_face_tests::a_hole_wider_than_the_part_says_it_removes_all_of_it a 40 mm hole at (10, 10) touches the plate's edge y = 30 at one point; the kernel parts the plate there into 2 bodies, the test wants truck's 1, as on SMLib
|
||||
|
||||
Reference in New Issue
Block a user