diff --git a/FEATURES.md b/FEATURES.md index 3e6cb4c..80ef606 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -8,7 +8,7 @@ edit those columns by hand, then re-run the script. the feature-tree level) · `done` (regenerates, round-trips save/load, undo/redo, command + MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). -**Totals:** 1000 rows — not started: 834 · in progress: 138 · done: 28 · verified: 0 +**Totals:** 1000 rows — not started: 833 · in progress: 139 · done: 28 · verified: 0 ## Platform (SPEC §2–§6, §8–§9) @@ -1120,7 +1120,7 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | `D/transparency` | Per-body/component transparency | not started | ForgeModel | — | — | | | `D/section-view-part` | Section view (dynamic display section in parts/assemblies) | not started | ForgeModel | — | — | | | `D/view-selector` | View selector cube, named/saved views, previous view | not started | ForgeModel | — | — | | -| `D/zoom-to-selection` | Zoom to selection / zoom to area | not started | ForgeModel | — | — | | +| `D/zoom-to-selection` | Zoom to selection / zoom to area | in progress | ForgeCommands / ForgeUI | SelectionFramingTests, SelectionFramingWorkflowTests, MCP framing workflow | `zoom_to_selection` | Selected visible body/subshape/sketch bounds, orientation/projection preserved, empty/hidden no-op and previous-view history on all desktop shells. Sketch outlines are sampled; rectangle zoom-to-area pending. | | `D/display-states-part` | Display states in parts | not started | ForgeModel | — | — | | | `D/feature-comments` | Comments/notes on features | not started | ForgeModel | — | — | | | `D/selection-sets` | Selection sets (saved selections) | not started | ForgeModel | — | — | | diff --git a/PROGRESS.md b/PROGRESS.md index 1709daf..8a021af 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -30,6 +30,56 @@ BSD find; those unrelated files are unchanged and all three pass in Linux CI. Remaining scope: curved/tangent/directed/reflex angle measurements, maximum/normal and projected distances, sketch-entity measurements and broader SolidWorks parity. +## 2026-10-02 — Portable Windows dependency packaging checks + +- Replaced GNU `find -printf` in OCCT DLL-directory discovery with batched portable + shell extraction, preserving spaces/quotes without installing GNU find on macOS. +- Corrected debug/plugin directory exclusions at the end of a path. The offline archive + fixture now includes excluded DLLs and asserts that the original PATH is preserved + exactly after the one permitted toolkit directory is prepended. Existing download, + incomplete-cache, quoting and cache-reuse assertions remain intact. +- Added the three offline packaging regressions to native Mac CI as well as Linux CI. + +Validation: shell syntax and all **three packaging regressions** pass locally on +macOS using BSD find; whitespace checks pass. No Swift product code changed. + +## PR #8 review follow-up — 2026-10-02 — Native camera intent ordering + +- Native orbit, pan, wheel, magnify, rotate and double-click fit invalidate pending + selection framing synchronously before camera mutation on macOS and the shared + Windows/Linux viewport. Deferred camera publication cannot admit an old result. +- Queued selection fits carry their request generation; both viewport consumers skip + fits invalidated by newer input before queue consumption. Deterministic regressions + cover an engine request held across input/deferred publication and input after enqueue. +- Merged the current default branch, preserving the user-merged angle measurement and + packaging fixes, all progress entries and both MCP workflows. + +Validation: native build, all four focused selection-framing workflow tests, seven MCP +workflows, three packaging regressions and shared frontend type-check pass. Matrix and +whitespace checks pass; full platform suites run in exact-head CI. + +## Navigation follow-on — 2026-10-02 — Zoom to Selection + +- Added read-only `view.zoom_to_selection` and MCP `zoom_to_selection`, with explicit + or current selection, tight body/subshape union bounds, placed sketch display bounds, + point framing and validated camera/aspect inputs. Hidden/isolation-excluded bodies, + planes and constraints are skipped; malformed or stale geometry references fail. +- Added macOS, Windows and GTK View/menu/viewport/body-context actions using shared + selection framing and existing Previous View history. Async results cannot replace + a newer document, selection or camera action. Orientation and projection are preserved. +- Returned cameras feed render/pick/candidate views directly. Perspective clipping also + accounts for a close selection when unrelated geometry is far from the camera. + +Validation: private macOS 27 / Swift 6.4 / OCCT 8.0.1 build and **386 Swift tests**, +**33 golden models** and **six MCP subprocess workflows** pass. A clean `/tmp` Swift +scratch directory avoids Finder metadata on generated test bundles. Native GTK menu +action assertions run in CI; no live desktop app windows were launched. The separate +packaging portability change is independent of this branch. Matrix and whitespace +checks pass. + +Remaining boundaries: sketch extents use sampled viewport polylines. Whole sketches +exclude the fixed origin and owned definition points. Rectangle zoom-to-area is pending. + ## Session 12 — 2026-09-30 — Selected contours, planar limits and selection filters - Added `sketch.regions` with stable complete-curve selectors, holes, nested islands, diff --git a/README.md b/README.md index 184ea50..524e515 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,14 @@ bus, reachable from the UI, scripts, `forge-cli` and MCP alike. ![Headless render of a golden model](docs/images/m0-multiview.png) +Zoom to Selection is available in the desktop View menu, viewport controls and body +context menu. It frames selected visible bodies, faces, edges, vertices and sketch +geometry while preserving orientation and projection, with Previous View restoring +the old camera. Empty or fully hidden selections leave the view unchanged. +`view.zoom_to_selection` (MCP `zoom_to_selection`) returns bounds and a camera that +can be supplied as `view.camera` to rendering and picking commands. Sketch bounds +use sampled display outlines; rectangle zoom-to-area remains pending. + ## Layout ``` diff --git a/Sources/CForgeWin/app.cpp b/Sources/CForgeWin/app.cpp index 1e29fcb..2971c03 100644 --- a/Sources/CForgeWin/app.cpp +++ b/Sources/CForgeWin/app.cpp @@ -1010,6 +1010,7 @@ static void buildMenu(fw_app *a) { for (int i = 0; i < 10; ++i) AppendMenuW(orient, MF_STRING, FW_MENU_FRONT + i, names[i]); AppendMenuW(view, MF_POPUP, (UINT_PTR)orient, L"&Orientation"); AppendMenuW(view, MF_STRING, FW_MENU_FIT, L"Zoom to &Fit\tF"); + AppendMenuW(view, MF_STRING, FW_MENU_ZOOM_SELECTION, L"Zoom to Selection"); AppendMenuW(view, MF_STRING, FW_MENU_PREVIOUS, L"&Previous View"); AppendMenuW(view, MF_SEPARATOR, 0, nullptr); AppendMenuW(display, MF_STRING, FW_MENU_SHADED_EDGES, L"Shaded With &Edges"); diff --git a/Sources/CForgeWin/gtk/gtk_shell.c b/Sources/CForgeWin/gtk/gtk_shell.c index 81571bc..41f0843 100644 --- a/Sources/CForgeWin/gtk/gtk_shell.c +++ b/Sources/CForgeWin/gtk/gtk_shell.c @@ -283,6 +283,7 @@ static GMenuModel *appMenu(void) { g_menu_append_submenu(view, "Display Style", d); g_menu_append_submenu(view, "Show", sh); item(view, "Zoom to Fit", FW_MENU_FIT); + item(view, "Zoom to Selection", FW_MENU_ZOOM_SELECTION); item(view, "Previous View", FW_MENU_PREVIOUS); item(view, "Perspective", FW_MENU_PERSPECTIVE); item(help, "About Forge", FW_MENU_ABOUT); @@ -303,7 +304,7 @@ static void buildActions(fw_app *a) { addAction(a, FW_MENU_IMPORT_STEP, 0); addAction(a, FW_MENU_UNDO, 0); addAction(a, FW_MENU_REDO, 0); - for (int id = FW_MENU_FRONT; id <= FW_MENU_PREVIOUS; ++id) addAction(a, id, 0); + for (int id = FW_MENU_FRONT; id <= FW_MENU_ZOOM_SELECTION; ++id) addAction(a, id, 0); for (int id = FW_MENU_PERSPECTIVE; id <= FW_MENU_DIMENSIONS; ++id) addAction(a, id, 1); for (int id = FW_MENU_SHADED_EDGES; id <= FW_MENU_HIDDEN_LINES; ++id) addAction(a, id, 1); addAction(a, FW_MENU_ABOUT, 0); @@ -1182,6 +1183,7 @@ static GtkWidget *buildHeadsUp(fw_app *a) { gtk_widget_set_valign(bar, GTK_ALIGN_START); gtk_widget_set_margin_top(bar, 12); gtk_box_append(GTK_BOX(bar), actionButton(a, "zoomFit", "Zoom to Fit (F)", FW_MENU_FIT)); + gtk_box_append(GTK_BOX(bar), actionButton(a, "zoomFit", "Zoom to Selection", FW_MENU_ZOOM_SELECTION)); gtk_box_append(GTK_BOX(bar), actionButton(a, "prevView", "Previous View", FW_MENU_PREVIOUS)); GtkWidget *sep = hbox(0); gtk_widget_add_css_class(sep, "forge-sep"); diff --git a/Sources/CForgeWin/include/CForgeWin.h b/Sources/CForgeWin/include/CForgeWin.h index 50eb857..df85ac4 100644 --- a/Sources/CForgeWin/include/CForgeWin.h +++ b/Sources/CForgeWin/include/CForgeWin.h @@ -62,7 +62,7 @@ enum { FW_MENU_NEW = 100, FW_MENU_OPEN, FW_MENU_SAVE, FW_MENU_SAVE_AS, FW_MENU_EXPORT_STEP, FW_MENU_EXPORT_STL, FW_MENU_EXIT, FW_MENU_IMPORT_STEP, FW_MENU_UNDO = 200, FW_MENU_REDO, FW_MENU_FRONT = 300, FW_MENU_BACK, FW_MENU_LEFT, FW_MENU_RIGHT, FW_MENU_TOP, FW_MENU_BOTTOM, FW_MENU_ISOMETRIC, - FW_MENU_DIMETRIC, FW_MENU_TRIMETRIC, FW_MENU_NORMAL_TO, FW_MENU_FIT, FW_MENU_PREVIOUS, + FW_MENU_DIMETRIC, FW_MENU_TRIMETRIC, FW_MENU_NORMAL_TO, FW_MENU_FIT, FW_MENU_PREVIOUS, FW_MENU_ZOOM_SELECTION, FW_MENU_PERSPECTIVE = 320, FW_MENU_PLANES, FW_MENU_RELATIONS, FW_MENU_DIMENSIONS, FW_MENU_SHADED_EDGES = 330, FW_MENU_SHADED, FW_MENU_WIREFRAME, FW_MENU_HIDDEN_LINES, FW_MENU_ABOUT = 400 diff --git a/Sources/ForgeApp/FeatureTree.swift b/Sources/ForgeApp/FeatureTree.swift index 277cd87..efa4063 100644 --- a/Sources/ForgeApp/FeatureTree.swift +++ b/Sources/ForgeApp/FeatureTree.swift @@ -65,6 +65,7 @@ struct FeatureTreeView: View { Button(model.hiddenBodyIDs.contains(b.id) ? "Show Body" : "Hide Body") { Task { await model.setBodiesVisible([b.id], model.hiddenBodyIDs.contains(b.id)) } } Button("Isolate Body") { Task { await model.isolateBodies([b.id]) } } Button("Rename…") { Task { await model.renameBody(b.id) } } + Button("Zoom to Selection") { Task { await model.select(b.id, extend: false); await model.zoomToSelection() } } Button("Mass Properties") { Task { await model.select(b.id, extend: false) diff --git a/Sources/ForgeApp/ForgeApp.swift b/Sources/ForgeApp/ForgeApp.swift index 6b66131..64745cf 100644 --- a/Sources/ForgeApp/ForgeApp.swift +++ b/Sources/ForgeApp/ForgeApp.swift @@ -80,6 +80,7 @@ struct ForgeApp: App { Button("Select Other (Tab)") { Task { await model.selectOther() } }.disabled(!model.canSelectOther) Divider() Button("Zoom to Fit (F)") { model.zoomToFit() } + Button("Zoom to Selection") { Task { await model.zoomToSelection() } }.disabled(model.selection.isEmpty) Button("Previous View") { model.previousView() } Divider() Button("Hide Selected Bodies") { Task { await model.setBodiesVisible(model.selectedBodies, false) } }.disabled(model.selectedBodies.isEmpty) diff --git a/Sources/ForgeApp/ViewportOverlays.swift b/Sources/ForgeApp/ViewportOverlays.swift index c1bce29..e4b4a35 100644 --- a/Sources/ForgeApp/ViewportOverlays.swift +++ b/Sources/ForgeApp/ViewportOverlays.swift @@ -60,6 +60,7 @@ struct HeadsUpToolbar: View { var body: some View { HStack(spacing: 1) { HUDButton(icon: .zoomFit, help: "Zoom to fit (F)") { model.zoomToFit() } + HUDButton(icon: .zoomFit, help: "Zoom to selection") { Task { await model.zoomToSelection() } } HUDButton(icon: .prevView, help: "Previous view") { model.previousView() } HUDDivider() Menu { @@ -438,6 +439,7 @@ struct ContextToolbar: View { item(.massProps, "Mass Properties") { model.begin(.massProperties) } } if model.isIsolatingBodies { item(.part, "Exit Isolation") { Task { await model.exitBodyIsolation() } } } + item(.zoomFit, "Zoom to Selection") { Task { await model.zoomToSelection() } } item(.zoomFit, "Zoom to Fit") { model.zoomToFit() } } } diff --git a/Sources/ForgeApp/ViewportView.swift b/Sources/ForgeApp/ViewportView.swift index 17d81a0..9840ddb 100644 --- a/Sources/ForgeApp/ViewportView.swift +++ b/Sources/ForgeApp/ViewportView.swift @@ -33,6 +33,7 @@ struct ViewportView: NSViewRepresentable { view.delegate = renderer } view.layer?.isOpaque = false + view.onCameraInput = { model.viewportCameraInput() } view.onCamera = { camera, width, height in let p = ViewProjection(camera: camera, width: width, height: height) if model.projection != p { model.projection = p } @@ -82,9 +83,11 @@ struct ViewportView: NSViewRepresentable { view.sketchPlane = model.viewportSketchPlane if context.coordinator.appliedCommands < commands.count { for c in commands[context.coordinator.appliedCommands...] { + guard model.acceptsViewportCommand(c) else { continue } switch c { case .orient(let o): view.orient(o) case .fit: view.fit() + case .fitSelection(let bounds, _): view.fitSelection(bounds) case .previous: view.previousView() case .style(let st): view.renderer?.style = st @@ -122,6 +125,8 @@ final class ForgeMTKView: MTKView { /// A sketch tool press in progress (for click-drag drawing). private var toolPress: NSPoint? var onCancel: (() -> Void)? + /// Synchronous intent notification before direct native camera mutations. + var onCameraInput: (() -> Void)? /// Called (asynchronously) whenever the camera or the view size changes. var onCamera: ((Camera, Double, Double) -> Void)? private var history: [Camera] = [] @@ -139,6 +144,13 @@ final class ForgeMTKView: MTKView { cameraChanged() } + func fitSelection(_ box: BoundingBox) { + guard let r = renderer else { return } + remember() + r.camera.fitSelection(box, aspect: Double(max(bounds.width, 1) / max(bounds.height, 1))) + cameraChanged() + } + func orient(_ o: ViewOrientation) { remember() renderer?.camera.setOrientation(o) @@ -261,10 +273,11 @@ final class ForgeMTKView: MTKView { /// SolidWorks middle button: drag rotates, Ctrl+drag pans, Shift+drag zooms; a double /// click zooms to fit. Works while a sketch tool is active. override func otherMouseDown(with event: NSEvent) { - if event.clickCount == 2 { fit() } + if event.clickCount == 2 { onCameraInput?(); fit() } } override func otherMouseDragged(with event: NSEvent) { + onCameraInput?() if event.modifierFlags.contains(.control) { pan(event) } else if event.modifierFlags.contains(.shift) { @@ -283,6 +296,7 @@ final class ForgeMTKView: MTKView { return } dragged = true + onCameraInput?() if event.modifierFlags.contains(.option) { pan(event) } else { @@ -324,6 +338,7 @@ final class ForgeMTKView: MTKView { } override func rightMouseDragged(with event: NSEvent) { + onCameraInput?() pan(event) cameraChanged() } @@ -334,6 +349,7 @@ final class ForgeMTKView: MTKView { override func scrollWheel(with event: NSEvent) { guard let r = renderer else { return } + onCameraInput?() if event.hasPreciseScrollingDeltas && event.phase != [] { // Trackpad two-finger scroll: pan. r.camera.pan(dxPixels: -Double(event.scrollingDeltaX), dyPixels: -Double(event.scrollingDeltaY), viewportHeight: Double(bounds.height)) @@ -346,12 +362,14 @@ final class ForgeMTKView: MTKView { } override func magnify(with event: NSEvent) { + onCameraInput?() renderer?.camera.zoom(factor: 1 + Double(event.magnification), anchor: anchor(for: event)) cameraChanged() } override func rotate(with event: NSEvent) { guard let r = renderer else { return } + onCameraInput?() let q = Quat(axis: r.camera.back, angle: Double(event.rotation) * .pi / 180) r.camera.orientation = (q * r.camera.orientation).normalized cameraChanged() diff --git a/Sources/ForgeCommands/Commands/SelectionFramingCommands.swift b/Sources/ForgeCommands/Commands/SelectionFramingCommands.swift new file mode 100644 index 0000000..4bd4d89 --- /dev/null +++ b/Sources/ForgeCommands/Commands/SelectionFramingCommands.swift @@ -0,0 +1,97 @@ +import ForgeCore +import ForgeKernel +import ForgeRender +import ForgeSketch +import Foundation + +/// Read-only selection framing, shared by desktop and headless view workflows. +public enum ViewZoomToSelection: Command { + public struct Params: Codable, Sendable, SchemaDocumented, ValidatableParams { + public var entities: [String]? + public var camera: Camera? + public var aspect: Double? + public static let fieldDocs: [String: FieldDoc] = [ + "entities": FieldDoc("Explicit body/face/edge/vertex or sketch/entity references; [] frames nothing", default: "current selection"), + "camera": "Current camera; omitted uses the standard isometric orthographic view. Returned camera can be passed as view.camera to render/pick.", + "aspect": FieldDoc("Viewport width divided by height; must be finite and positive", default: 1), + ] + public func validate() throws { + try camera?.validate() + if let aspect, !(aspect.isFinite && aspect > 0) { throw ForgeError(.invalidParams, "aspect must be finite and positive") } + } + } + public struct Output: Codable, Sendable { + public var camera: Camera + public var bounds: BoundingBox? + public var framed: [String] + public var skipped: [String] + } + public static let name = "view.zoom_to_selection" + public static let summary = "Frame selected visible geometry while preserving camera orientation and projection" + public static let discussion = "Returns a camera and union bounds without changing the document or selection. Empty/all-excluded selections leave the supplied camera unchanged. Hidden/isolation-excluded bodies, reference planes and sketch constraints are skipped. Body subshapes use tight kernel bounds; sketches use the same sampled polylines as the viewport, including independent points; whole sketches exclude the fixed origin and owned definition points. Point selections use a 1 mm minimum framing box. Rectangle zoom-to-area remains unsupported." + public static let category = CommandCategory.view + public static let undo = UndoBehavior.none + public static let errors: [ErrorCode] = [.invalidParams, .unknownEntity, .referenceLost, .kernelFailure] + public static let examples: [JSONValue] = [[:], ["entities": ["body-1/face-0"], "aspect": 1.5]] + + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { + let doc = try ctx.requireDocument() + var camera = p.camera ?? Camera() + if p.camera == nil { camera.setOrientation(.isometric) } + var bounds: BoundingBox? + var framed: [String] = [], skipped: [String] = [] + func include(_ box: BoundingBox) { bounds = bounds.map { $0.union(box) } ?? box } + for reference in p.entities ?? doc.selection { + let parts = reference.split(separator: "/", maxSplits: 1, omittingEmptySubsequences: false).map(String.init) + if let head = parts.first, let sketch = doc.sketches[head] { + let entities: [String] + if parts.count == 1 { + // Whole-sketch framing includes drawn curves and independent points, + // not the fixed origin or owned construction/control points. + entities = sketch.orderedEntities.filter { $0.id != Sketch.originID && ($0.kind != .point || $0.owner == nil) }.map(\.id) + } + else if sketch.entities[parts[1]] != nil { entities = [parts[1]] } + else if sketch.constraints.contains(where: { $0.id == parts[1] }) { + skipped.append(reference) + continue + } else { throw ForgeError(.unknownEntity, "no sketch entity '\(reference)'", entities: [reference]) } + var hadPoints = false + for entity in entities { + for (u, v) in sketch.polyline(entity) { + let point = sketch.plane.point(u, v) + include(BoundingBox(min: point, max: point)) + hadPoints = true + } + } + if hadPoints { framed.append(reference) } else { skipped.append(reference) } + continue + } + if (reference.hasPrefix("plane-") && StandardPlane(rawValue: String(reference.dropFirst(6))) != nil) || doc.refPlanes[reference] != nil { + skipped.append(reference) + continue + } + let ref = try EntityRef.parse(reference) + let body = try doc.body(ref.body) + let boxes: [BoundingBox] + switch ref.kind { + case .body: boxes = [try body.shape.boundingBox()] + case .face: + boxes = try doc.faceIndices([reference], of: body, sets: true).map { try body.shape.subshape(.face, index: $0).boundingBox() } + case .edge: + boxes = try doc.edgeIndices([reference], of: body).map { try body.shape.subshape(.edge, index: $0).boundingBox() } + case .vertex: + guard let i = ref.index, i < (try body.shape.topology().vertices) else { + throw ForgeError(.unknownEntity, "no vertex '\(reference)'", entities: [reference]) + } + let point = try body.shape.vertex(i) + boxes = [BoundingBox(min: point, max: point)] + } + if doc.isBodyVisible(body.id) { + for box in boxes { include(box) } + framed.append(reference) + } else { skipped.append(reference) } + } + if let bounds { camera.fitSelection(bounds, aspect: p.aspect ?? 1) } + return Output(camera: camera, bounds: bounds, framed: framed, skipped: skipped) + } +} diff --git a/Sources/ForgeCommands/Commands/ViewCommands.swift b/Sources/ForgeCommands/Commands/ViewCommands.swift index ce5e3b3..d4a12d5 100644 --- a/Sources/ForgeCommands/Commands/ViewCommands.swift +++ b/Sources/ForgeCommands/Commands/ViewCommands.swift @@ -104,6 +104,7 @@ public struct DocumentScene: Sendable { /// Shared view parameters for render/pick so an agent can pick on exactly the image it saw. public struct ViewSpec: Codable, Sendable, SchemaDocumented, ValidatableParams { + public var camera: Camera? public var orientation: ViewOrientation? public var style: RenderStyle? public var projection: ProjectionKind? @@ -117,6 +118,7 @@ public struct ViewSpec: Codable, Sendable, SchemaDocumented, ValidatableParams { public var sketches: Bool? public static let fieldDocs: [String: FieldDoc] = [ + "camera": "Exact camera snapshot from view.zoom_to_selection; overrides orientation, projection, yaw/pitch and automatic fit", "orientation": FieldDoc("Standard view", default: "isometric"), "style": FieldDoc("Display style", default: "shaded_with_edges"), "projection": FieldDoc("Projection", default: "orthographic"), @@ -130,6 +132,7 @@ public struct ViewSpec: Codable, Sendable, SchemaDocumented, ValidatableParams { ] public func validate() throws { + try camera?.validate() for (n, v) in [("width", width), ("height", height)] { if let v, !(16...4096).contains(v) { throw ForgeError(.invalidParams, "\(n) must be between 16 and 4096") } } @@ -138,6 +141,7 @@ public struct ViewSpec: Codable, Sendable, SchemaDocumented, ValidatableParams { var size: (Int, Int) { (width ?? 800, height ?? 600) } func camera(for scene: RenderScene) -> Camera { + if let camera { return camera } var cam = Camera(projection: projection ?? .orthographic) cam.setOrientation(orientation ?? .isometric) if yaw != nil || pitch != nil { cam.turntable(dx: (yaw ?? 0) * .pi / 180, dy: (pitch ?? 0) * .pi / 180) } diff --git a/Sources/ForgeCommands/StandardRegistry.swift b/Sources/ForgeCommands/StandardRegistry.swift index fabe0f8..77a6c1d 100644 --- a/Sources/ForgeCommands/StandardRegistry.swift +++ b/Sources/ForgeCommands/StandardRegistry.swift @@ -119,6 +119,7 @@ extension CommandRegistry { r.register(ViewIsolate.self) r.register(ViewExitIsolation.self) r.register(ViewShowAll.self) + r.register(ViewZoomToSelection.self) r.register(ViewRender.self) r.register(ViewRenderMultiview.self) r.register(ViewPick.self) diff --git a/Sources/ForgeMCP/Tools.swift b/Sources/ForgeMCP/Tools.swift index 8981d72..1eb7828 100644 --- a/Sources/ForgeMCP/Tools.swift +++ b/Sources/ForgeMCP/Tools.swift @@ -120,6 +120,7 @@ public enum ToolCatalog { alias("query_entity", "Query entity", "query.entity"), alias("get_mass_properties", "Mass properties", "query.mass_properties"), alias("measure", "Measure", "query.measure"), + alias("zoom_to_selection", "Zoom to selection", "view.zoom_to_selection"), // ---- mutate Tool( name: "execute", title: "Execute command", diff --git a/Sources/ForgeRender/Camera.swift b/Sources/ForgeRender/Camera.swift index 0d37d51..ea0a555 100644 --- a/Sources/ForgeRender/Camera.swift +++ b/Sources/ForgeRender/Camera.swift @@ -28,7 +28,7 @@ public enum ProjectionKind: String, Codable, Sendable, CaseIterable, SchemaEnum /// A CAD camera: orbit about a target, pan in the view plane, zoom toward a point. /// Orientation is a quaternion so free (SolidWorks-style) rotation never gimbal-locks. -public struct Camera: Sendable, Hashable { +public struct Camera: Codable, Sendable, Hashable { public var target: Vec3 /// Distance from eye to target. public var distance: Double @@ -50,6 +50,23 @@ public struct Camera: Sendable, Hashable { self.orthoHalfHeight = orthoHalfHeight } + /// Validate externally supplied camera snapshots before rendering or fitting. + public func validate() throws { + let norm = orientation.w * orientation.w + orientation.x * orientation.x + orientation.y * orientation.y + orientation.z * orientation.z + guard target.array.allSatisfy(\.isFinite), distance.isFinite, distance > 0, + orthoHalfHeight.isFinite, orthoHalfHeight > 0, fovY.isFinite, fovY > 0, fovY < .pi, + norm.isFinite, abs(norm - 1) < 1e-6 else { + throw ForgeError(.invalidParams, "camera requires finite coordinates, positive distance/scale, a field of view in (0, pi), and a unit orientation quaternion") + } + } + + /// Preserve orientation/projection and avoid an unusable microscopic view of a point. + public mutating func fitSelection(_ bounds: BoundingBox, aspect: Double = 1) { + let box = bounds.diagonal < 1e-6 + ? BoundingBox(min: bounds.center - Vec3(0.5, 0.5, 0.5), max: bounds.center + Vec3(0.5, 0.5, 0.5)) : bounds + fit(box, aspect: aspect) + } + public var right: Vec3 { orientation.rotate(.unitX) } public var up: Vec3 { orientation.rotate(.unitY) } /// Unit vector from target toward the eye. @@ -131,7 +148,8 @@ public struct Camera: Sendable, Hashable { let near = distance - r * 1.5, far = distance + r * 1.5 return .orthographic(halfWidth: orthoHalfHeight * aspect, halfHeight: orthoHalfHeight, near: near, far: far) case .perspective: - let near = max(distance - r * 1.5, r * 0.01), far = distance + r * 1.5 + // A selection can be much closer than unrelated, distant scene geometry. + let near = max(distance - r * 1.5, min(r * 0.01, distance * 0.01)), far = distance + r * 1.5 return .perspective(fovY: fovY, aspect: aspect, near: near, far: far) } } diff --git a/Sources/ForgeRender/Math.swift b/Sources/ForgeRender/Math.swift index f58315f..3de48ad 100644 --- a/Sources/ForgeRender/Math.swift +++ b/Sources/ForgeRender/Math.swift @@ -85,7 +85,7 @@ public struct Mat4: Sendable, Hashable { } /// Unit quaternion for camera orientation. -public struct Quat: Sendable, Hashable { +public struct Quat: Codable, Sendable, Hashable { public var w, x, y, z: Double public init(w: Double, x: Double, y: Double, z: Double) { diff --git a/Sources/ForgeUI/AppModel.swift b/Sources/ForgeUI/AppModel.swift index 07e8fa9..0c81272 100644 --- a/Sources/ForgeUI/AppModel.swift +++ b/Sources/ForgeUI/AppModel.swift @@ -209,6 +209,7 @@ package struct DisplayOptions { @MainActor @Observable package final class AppModel { package let engine = Engine() + @ObservationIgnored package var selectionZoomRequest = 0 /// Native dialogs of the front end. package var platform: any PlatformServices = HeadlessPlatform() package var documentName = "Part1" @@ -329,6 +330,7 @@ package final class AppModel { @discardableResult package func run(_ command: String, _ params: JSONValue = [:]) async -> CommandOutcome? { + selectionZoomRequest += 1 do { let o = try await engine.execute(command, params) interferenceRequest += 1 @@ -495,11 +497,44 @@ package final class AppModel { } } - package func setOrientation(_ o: ViewOrientation) { viewportCommands.send(.orient(o)) } - package func zoomToFit() { viewportCommands.send(.fit) } - package func previousView() { viewportCommands.send(.previous) } + package func setOrientation(_ o: ViewOrientation) { selectionZoomRequest += 1; viewportCommands.send(.orient(o)) } + package func zoomToFit() { selectionZoomRequest += 1; viewportCommands.send(.fit) } + /// Native gestures must call this synchronously before mutating their camera. + /// Camera publication may be deferred until a later main-loop turn. + package func viewportCameraInput() { selectionZoomRequest += 1 } + + /// Recheck intent when the viewport consumes an already queued framing result. + package func acceptsViewportCommand(_ command: ViewportCommandQueue.Command) -> Bool { + if case .fitSelection(_, let request) = command { return request == selectionZoomRequest } + return true + } + + package func zoomToSelection() async { + selectionZoomRequest += 1 + let request = selectionZoomRequest, selected = selection, version = sceneVersion, view = projection + guard !selected.isEmpty else { return } + do { + let aspect = view.map { max($0.width, 1) / max($0.height, 1) } ?? 1 + var params: [String: JSONValue] = ["entities": .array(selected.map(JSONValue.string)), "aspect": .number(aspect)] + if let view { params["camera"] = try JSONCoding.toJSON(view.camera) } + let result = try await engine.execute("view.zoom_to_selection", .object(params)).result + guard request == selectionZoomRequest, selected == selection, version == sceneVersion, view == projection else { return } + let output = try JSONCoding.fromJSON(ViewZoomToSelection.Output.self, result) + if let bounds = output.bounds { viewportCommands.send(.fitSelection(bounds, request: request)) } + lastError = nil + } catch let error as ForgeError { + guard request == selectionZoomRequest, selected == selection, version == sceneVersion, view == projection else { return } + lastError = error + } catch { + guard request == selectionZoomRequest, selected == selection, version == sceneVersion, view == projection else { return } + lastError = ForgeError(.internalError, error.localizedDescription) + } + } + + package func previousView() { selectionZoomRequest += 1; viewportCommands.send(.previous) } package func setStyle(_ s: RenderStyle) { viewportPickContext = nil; viewportCommands.send(.style(s)) } package func setPerspective(_ on: Bool) { + selectionZoomRequest += 1 display.perspective = on viewportCommands.send(.projection(on ? .perspective : .orthographic)) } @@ -510,8 +545,8 @@ package final class AppModel { package func viewportKey(_ key: String, at p: CGPoint) -> Bool { switch key { case "f": zoomToFit() - case "z": viewportCommands.send(.zoom(1 / 1.25)) - case "Z": viewportCommands.send(.zoom(1.25)) + case "z": selectionZoomRequest += 1; viewportCommands.send(.zoom(1 / 1.25)) + case "Z": selectionZoomRequest += 1; viewportCommands.send(.zoom(1.25)) case "s", "S": shortcutBarAt = p case "space": orientationPaletteShown.toggle() case "tab", "\t": @@ -537,16 +572,20 @@ package final class AppModel { package var canNormalTo: Bool { sketchState.plane != nil || selectedFace != nil || selection.contains { $0.hasPrefix("plane-") } } package func normalToSketch() { + selectionZoomRequest += 1 if let plane = sketchState.plane { viewportCommands.send(.normalTo(plane)) } else { Task { await normalToSelection() } } } package func normalToSelection() async { + selectionZoomRequest += 1 + let request = selectionZoomRequest if let plane = sketchState.plane { viewportCommands.send(.normalTo(plane)); return } guard let ref = selectedFace ?? selection.last(where: { $0.hasPrefix("plane-") }) else { return } do { guard let doc = await engine.activeDocument else { return } let placement = ref.hasPrefix("plane-") && StandardPlane(rawValue: String(ref.dropFirst(6))) != nil ? String(ref.dropFirst(6)) : ref + guard request == selectionZoomRequest else { return } viewportCommands.send(.normalTo(try doc.resolvePlacement(placement))) lastError = nil } catch { lastError = ForgeError.wrap(error) } @@ -630,7 +669,7 @@ package struct DocumentSceneBox { /// Commands from menus to the viewport, consumed in order by the viewport coordinator /// (which remembers how many it has applied, so SwiftUI updates never mutate model state). package struct ViewportCommandQueue { - package enum Command { case orient(ViewOrientation), fit, previous, style(RenderStyle), projection(ProjectionKind), zoom(Double), normalTo(SketchPlane) } + package enum Command { case orient(ViewOrientation), fit, fitSelection(BoundingBox, request: Int), previous, style(RenderStyle), projection(ProjectionKind), zoom(Double), normalTo(SketchPlane) } package private(set) var log: [Command] = [] package mutating func send(_ c: Command) { log.append(c) } } diff --git a/Sources/ForgeUI/SketchDimension.swift b/Sources/ForgeUI/SketchDimension.swift index 45cfc73..37178bf 100644 --- a/Sources/ForgeUI/SketchDimension.swift +++ b/Sources/ForgeUI/SketchDimension.swift @@ -184,7 +184,7 @@ extension AppModel { dimensionEdit = nil // The first dimension scaled the sketch: fit the view to it, so it neither shrinks // to a speck nor overflows the window. - if o.result["scaled_by"]?.doubleValue != nil { viewportCommands.send(.fit) } + if o.result["scaled_by"]?.doubleValue != nil { zoomToFit() } await select(nil, extend: false) } } diff --git a/Sources/ForgeUI/TreeSpec.swift b/Sources/ForgeUI/TreeSpec.swift index 70b820a..a1fa93d 100644 --- a/Sources/ForgeUI/TreeSpec.swift +++ b/Sources/ForgeUI/TreeSpec.swift @@ -61,6 +61,7 @@ extension AppModel { (hiddenBodyIDs.contains(b.id) ? "Show Body" : "Hide Body", { [unowned self] in Task { await setBodiesVisible([b.id], hiddenBodyIDs.contains(b.id)) } }), ("Isolate Body", { [unowned self] in Task { await isolateBodies([b.id]) } }), ("Rename…", { [unowned self] in Task { await renameBody(b.id) } }), + ("Zoom to Selection", { [unowned self] in Task { await select(b.id, extend: false); await zoomToSelection() } }), ("Mass Properties", { [unowned self] in Task { await select(b.id, extend: false); begin(.massProperties) } }), ("Export STEP…", { [unowned self] in Task { await select(b.id, extend: false); export("step") } }), ("Export STL…", { [unowned self] in Task { await select(b.id, extend: false); export("stl") } }), diff --git a/Sources/ForgeWin/WinShell.swift b/Sources/ForgeWin/WinShell.swift index 1b2175b..fa9bf62 100644 --- a/Sources/ForgeWin/WinShell.swift +++ b/Sources/ForgeWin/WinShell.swift @@ -421,6 +421,7 @@ final class WinShell { case FW_MENU_TRIMETRIC: model.setOrientation(.trimetric) case FW_MENU_NORMAL_TO: model.normalToSketch() case FW_MENU_FIT: model.zoomToFit() + case FW_MENU_ZOOM_SELECTION: Task { await model.zoomToSelection() } case FW_MENU_PREVIOUS: model.previousView() case FW_MENU_PERSPECTIVE: model.setPerspective(!model.display.perspective) case FW_MENU_PLANES: diff --git a/Sources/ForgeWin/WinViewport.swift b/Sources/ForgeWin/WinViewport.swift index f26a9f6..69cec6f 100644 --- a/Sources/ForgeWin/WinViewport.swift +++ b/Sources/ForgeWin/WinViewport.swift @@ -125,12 +125,16 @@ final class WinViewport { } private func apply(_ c: ViewportCommandQueue.Command) { + guard model.acceptsViewportCommand(c) else { return } switch c { case .orient(let o): remember() camera.setOrientation(o) fit() case .fit: fit() + case .fitSelection(let bounds, _): + remember() + camera.fitSelection(bounds, aspect: Double(max(width, 1)) / Double(max(height, 1))) case .previous: if let prev = history.popLast() { camera = prev } case .style(let s): @@ -417,6 +421,7 @@ final class WinViewport { case FW_EV_MOUSE_UP: mouseUp(x, y, button: Int(e.button), mods: mods) case FW_EV_MOUSE_WHEEL: + model.viewportCameraInput() camera.zoom(factor: pow(1.1, Double(e.wheel)), anchor: anchor(x, y)) cameraChanged() case FW_EV_MOUSE_LEAVE: @@ -441,6 +446,7 @@ final class WinViewport { dragged = false pressAt = (x, y) if button == 2 && clicks == 2 { + model.viewportCameraInput() fit() return } @@ -477,16 +483,20 @@ final class WinViewport { Task { await model.sketchDrag(q, curve: under) } } } else if mods & FW_MOD_ALT != 0 { + model.viewportCameraInput() camera.pan(dxPixels: dx, dyPixels: dy, viewportHeight: Double(height)) cameraChanged() } else if dragged { + model.viewportCameraInput() camera.orbit(dx: dx * 0.01, dy: dy * 0.01) cameraChanged() } case 1: + model.viewportCameraInput() camera.pan(dxPixels: dx, dyPixels: dy, viewportHeight: Double(height)) cameraChanged() case 2: + model.viewportCameraInput() if mods & FW_MOD_CTRL != 0 { camera.pan(dxPixels: dx, dyPixels: dy, viewportHeight: Double(height)) } else if mods & FW_MOD_SHIFT != 0 { diff --git a/Tests/ForgeCommandsTests/SelectionFramingTests.swift b/Tests/ForgeCommandsTests/SelectionFramingTests.swift new file mode 100644 index 0000000..addfeaa --- /dev/null +++ b/Tests/ForgeCommandsTests/SelectionFramingTests.swift @@ -0,0 +1,122 @@ +import ForgeCore +import ForgeRender +import Foundation +import Testing +@testable import ForgeCommands + +@Suite("Selection framing") +struct SelectionFramingTests { + func engine() async throws -> Engine { + let e = Engine() + try await e.execute("document.new") + try await e.execute("body.create_box", ["width": 10, "height": 20, "depth": 30]) + try await e.execute("body.create_box", ["width": 10, "height": 20, "depth": 30, "origin": [1000, 0, 0]]) + return e + } + func frame(_ e: Engine, _ refs: [String], camera: Camera? = nil, aspect: Double = 1) async throws -> ViewZoomToSelection.Output { + var params: [String: JSONValue] = ["entities": .array(refs.map(JSONValue.string)), "aspect": .number(aspect)] + if let camera { params["camera"] = try JSONCoding.toJSON(camera) } + return try JSONCoding.fromJSON(ViewZoomToSelection.Output.self, await e.execute("view.zoom_to_selection", .object(params)).result) + } + + @Test func explicitSubshapesAndUnionUseOnlySelectedBounds() async throws { + let e = try await engine() + let state = try await e.execute("document.state").result + let single = try await frame(e, ["body-1"]) + let both = try await frame(e, ["body-1", "body-2"]) + #expect(abs(single.bounds!.max.x - 10) < 1e-6) + #expect(abs(both.bounds!.max.x - 1010) < 1e-6) + #expect(single.camera.orthoHalfHeight < both.camera.orthoHalfHeight / 10) + let face = try await frame(e, ["body-1/face@feature-1:+z"]) + #expect(abs(face.bounds!.size.z) < 1e-6) + #expect(abs(face.bounds!.center.z - 30) < 1e-6) + let doc = try #require(await e.activeDocument) + let body = try doc.body("body-1") + let edge = try body.shape.edge(0) + let edgeFrame = try await frame(e, ["body-1/edge-0"]) + #expect(abs(edgeFrame.bounds!.diagonal - (edge.end - edge.start).length) < 1e-6) + let point = try body.shape.vertex(0) + let vertex = try await frame(e, ["body-1/vertex-0"]) + #expect(vertex.bounds?.center == point) + #expect(vertex.camera.target == point) + #expect(vertex.camera.orthoHalfHeight >= 0.5) + #expect(try await e.execute("document.state").result == state) + } + + @Test func emptyHiddenAndReferenceSelectionsDoNotChangeCamera() async throws { + let e = try await engine() + var camera = Camera(target: Vec3(3, 4, 5), distance: 90, projection: .perspective) + camera.setOrientation(.trimetric) + let empty = try await frame(e, [], camera: camera) + #expect(empty.bounds == nil && empty.camera == camera) + try await e.execute("view.set_visibility", ["bodies": ["body-1"], "visible": false]) + let hidden = try await frame(e, ["body-1/face-0", "plane-front"], camera: camera) + #expect(hidden.bounds == nil && hidden.camera == camera) + #expect(hidden.skipped == ["body-1/face-0", "plane-front"]) + try await e.execute("view.isolate", ["bodies": ["body-2"]]) + let mixed = try await frame(e, ["body-1", "body-2"], camera: camera) + #expect(mixed.framed == ["body-2"]) + #expect(abs(mixed.camera.target.x - 1005) < 1e-6) + #expect(mixed.camera.orientation == camera.orientation && mixed.camera.projection == camera.projection) + try await e.execute("selection.set", ["entities": ["body-2"]]) + let current = try JSONCoding.fromJSON(ViewZoomToSelection.Output.self, await e.execute("view.zoom_to_selection").result) + #expect(current.bounds == mixed.bounds) + } + + @Test func sketchGeometryUsesItsPlacementAndPointBounds() async throws { + let e = try await engine() + try await e.execute("sketch.create", ["plane": "front"]) + let empty = try await frame(e, ["sketch-1"]) + #expect(empty.bounds == nil) + try await e.execute("sketch.add_line", ["start": [2, 3], "end": [8, 9]]) + let selected = try await frame(e, ["sketch-1/line-1"]) + #expect(selected.bounds?.min == Vec3(2, 3, 0)) + #expect(selected.bounds?.max == Vec3(8, 9, 0)) + let all = try await frame(e, ["sketch-1"]) + #expect(all.bounds == selected.bounds) + let doc = try #require(await e.activeDocument) + let sketch = try #require(doc.sketches["sketch-1"]) + let pointID = try sketch.entity("line-1").points[0] + let point = try await frame(e, ["sketch-1/\(pointID)"]) + #expect(point.bounds?.center == Vec3(2, 3, 0)) + await #expect(throws: ForgeError.self) { try await frame(e, ["sketch-1/line-999"]) } + await #expect(throws: ForgeError.self) { try await frame(e, ["sketch-1/"]) } + try await e.execute("sketch.exit") + try await e.execute("sketch.create", ["plane": "right"]) + try await e.execute("sketch.add_line", ["start": [2, 3], "end": [8, 9]]) + let placed = try await frame(e, ["sketch-2"]) + #expect(placed.bounds?.min == Vec3(0, 3, -8)) + #expect(placed.bounds?.max == Vec3(0, 9, -2)) + } + + @Test func fittedCameraRendersAndPicksSelectionDespiteDistantGeometry() async throws { + let e = try await engine() + try await e.execute("body.transform", ["body": "body-2", "translate": [100000, 0, 0]]) + for kind in [ProjectionKind.orthographic, .perspective] { + var camera = Camera(projection: kind) + camera.setOrientation(.front) + let output = try await frame(e, ["body-1"], camera: camera, aspect: 0.5) + #expect(output.camera.orientation == camera.orientation && output.camera.projection == kind) + let view: JSONValue = ["camera": try JSONCoding.toJSON(output.camera), "width": 200, "height": 400] + let pick = try await e.execute("view.pick", ["x": 100, "y": 200, "view": view]).result + #expect(pick["hit"]?.stringValue?.hasPrefix("body-1/") == true) + let candidates = try await e.execute("view.pick_candidates", ["x": 100, "y": 200, "view": view]).result + #expect(candidates["candidates"]?.arrayValue?.isEmpty == false) + } + } + + @Test func rejectsStaleGeometryAndInvalidCameraInputs() async throws { + let e = try await engine() + for ref in ["body-1/face-999", "body-1/edge@missing", "body-1/vertex-999", "body-999"] { + await #expect(throws: ForgeError.self) { try await frame(e, [ref]) } + } + for aspect in [0.0, -1, Double.infinity] { + await #expect(throws: ForgeError.self) { try await frame(e, ["body-1"], aspect: aspect) } + } + var invalid = Camera() + invalid.orientation = Quat(w: 0, x: 0, y: 0, z: 0) + await #expect(throws: ForgeError.self) { try await frame(e, ["body-1"], camera: invalid) } + invalid = Camera(fovY: .pi) + await #expect(throws: ForgeError.self) { try await frame(e, ["body-1"], camera: invalid) } + } +} diff --git a/Tests/ForgeUITests/SelectionFramingWorkflowTests.swift b/Tests/ForgeUITests/SelectionFramingWorkflowTests.swift new file mode 100644 index 0000000..d9e7e81 --- /dev/null +++ b/Tests/ForgeUITests/SelectionFramingWorkflowTests.swift @@ -0,0 +1,125 @@ +import ForgeCommands +import ForgeCore +import ForgeRender +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Desktop selection framing") +struct SelectionFramingWorkflowTests { + @Test func selectedGeometryQueuesExplicitBoundsAndEmptyOrHiddenSelectionIsANoOp() async throws { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + await m.run("body.create_box", ["width": 10, "height": 20, "depth": 30, "origin": [1000, 0, 0]]) + await m.select("body-1/face@feature-1:+z", extend: false) + await m.zoomToSelection() + guard case .fitSelection(let bounds, _)? = m.viewportCommands.log.last else { Issue.record("selection fit missing"); return } + #expect(abs(bounds.center.z - 30) < 1e-6) + #expect(bounds.max.x < 11) + let count = m.viewportCommands.log.count + await m.select(nil, extend: false) + await m.zoomToSelection() + #expect(m.viewportCommands.log.count == count) + await m.setBodiesVisible(["body-1"], false) + await m.select("body-1", extend: false) + await m.zoomToSelection() + #expect(m.viewportCommands.log.count == count) + #expect(m.lastError == nil) + m.previousView() + guard case .previous? = m.viewportCommands.log.last else { Issue.record("previous view missing"); return } + } + + @Test func newerNavigationIsNeverOverwrittenByPendingSelectionFraming() async throws { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + await m.select("body-1", extend: false) + m.sketchState.plane = .front + for action in ["fit", "zoom", "normal"] { + let initial = m.selectionZoomRequest + let pending = Task { await m.zoomToSelection() } + // Wait until the request has started; completion before navigation is also valid. + while m.selectionZoomRequest == initial { await Task.yield() } + switch action { + case "fit": m.zoomToFit() + case "zoom": _ = m.viewportKey("z", at: .zero) + default: m.normalToSketch() + } + await pending.value + switch (action, m.viewportCommands.log.last) { + case ("fit", .fit?), ("zoom", .zoom?), ("normal", .normalTo?): break + default: Issue.record("older selection framing overwrote newer navigation") + } + } + } + @Test func nativeCameraIntentDiscardsFramingAlreadyQueuedForViewportConsumption() async throws { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + await m.select("body-1", extend: false) + await m.zoomToSelection() + let queued = try #require(m.viewportCommands.log.last) + #expect(m.acceptsViewportCommand(queued)) + // SwiftUI/desktop timer has not consumed the fit yet when native input occurs. + m.viewportCameraInput() + #expect(!m.acceptsViewportCommand(queued)) + #expect(m.acceptsViewportCommand(.zoom(1.25))) + await m.zoomToSelection() + let fresh = try #require(m.viewportCommands.log.last) + #expect(m.acceptsViewportCommand(fresh)) + #expect(!m.acceptsViewportCommand(queued)) + } + + @Test func nativeCameraIntentCancelsFramingBeforeDeferredProjectionPublication() async throws { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + await m.select("body-1", extend: false) + let oldView = ViewProjection(camera: Camera(), width: 800, height: 600) + m.projection = oldView + let engine = m.engine, gate = FramingEngineGate() + // Hold the engine so the test cannot accidentally complete framing before input. + let blocker = Task.detached { await engine.holdForCameraRace(gate) } + defer { gate.release.signal() } + while !gate.didStart() { await Task.yield() } + let initial = m.selectionZoomRequest, commandCount = m.viewportCommands.log.count + let framing = Task { await m.zoomToSelection() } + while m.selectionZoomRequest == initial { await Task.yield() } + // Native input has changed the renderer camera, but its async onCamera callback + // has not published yet. The stale cached projection must not admit the result. + m.viewportCameraInput() + var gestureCamera = oldView.camera + gestureCamera.orbit(dx: 0.2, dy: 0.1) + #expect(m.projection == oldView) + gate.release.signal() + await blocker.value + await framing.value + #expect(m.viewportCommands.log.count == commandCount) + #expect(m.lastError == nil) + // Deliver the deferred publication only after the framing result returned. + m.projection = ViewProjection(camera: gestureCamera, width: 800, height: 600) + #expect(m.projection?.camera == gestureCamera) + // A new request after publication still frames normally. + await m.zoomToSelection() + guard case .fitSelection? = m.viewportCommands.log.last else { + Issue.record("fresh selection framing missing after gesture publication"); return + } + } + +} + + +private final class FramingEngineGate: @unchecked Sendable { + let started = DispatchSemaphore(value: 0) + let release = DispatchSemaphore(value: 0) + func didStart() -> Bool { started.wait(timeout: .now()) == .success } +} + +private extension Engine { + func holdForCameraRace(_ gate: FramingEngineGate) { + gate.started.signal() + gate.release.wait() + } +} diff --git a/Tests/IntegrationTests/test_mcp_stdio.py b/Tests/IntegrationTests/test_mcp_stdio.py index 3f06173..dcd30e7 100644 --- a/Tests/IntegrationTests/test_mcp_stdio.py +++ b/Tests/IntegrationTests/test_mcp_stdio.py @@ -64,6 +64,28 @@ def test_angle_measurement_and_structured_errors(self): for response in responses[4:]: self.assertTrue(response["result"]["isError"], response) + def test_selection_framing_is_read_only_and_respects_visibility(self): + executable = os.environ.get("FORGE_CLI", ".build/debug/forge-cli") + responses = self.run_calls(executable, [ + ("new_document", {}), + ("execute", {"command": "body.create_box", "params": {"width": 10, "height": 20, "depth": 30}}), + ("execute", {"command": "body.create_box", "params": {"width": 10, "height": 20, "depth": 30, "origin": [1000, 0, 0]}}), + ("execute", {"command": "selection.set", "params": {"entities": ["body-1"]}}), + ("get_document_state", {}), + ("zoom_to_selection", {}), + ("get_document_state", {}), + ("execute", {"command": "view.set_visibility", "params": {"bodies": ["body-1"], "visible": False}}), + ("zoom_to_selection", {"entities": ["body-1", "plane-front"]}), + ]) + for response in responses: + self.assertFalse(response["result"]["isError"], response) + state = lambda i: responses[i]["result"]["structuredContent"] + self.assertEqual(state(4), state(6)) + self.assertEqual(state(5)["framed"], ["body-1"]) + self.assertAlmostEqual(state(5)["bounds"]["max"][0], 10, places=6) + self.assertEqual(state(8)["framed"], []) + self.assertNotIn("bounds", state(8)) + def test_invalid_step_keeps_stdout_valid_json(self): executable = os.environ.get("FORGE_CLI", ".build/debug/forge-cli") with tempfile.TemporaryDirectory() as temporary: diff --git a/Tests/NativeGTKTests/MenuActionTests.c b/Tests/NativeGTKTests/MenuActionTests.c index 30afb3a..6a3e399 100644 --- a/Tests/NativeGTKTests/MenuActionTests.c +++ b/Tests/NativeGTKTests/MenuActionTests.c @@ -5,6 +5,8 @@ #include typedef struct { + int zoomItems; + int zoomEvents; int importItems; int actions; int failures; @@ -13,6 +15,7 @@ typedef struct { static void receive(void *context, const fw_event *event) { TestState *state = context; + if (event->kind == FW_EV_MENU && event->id == FW_MENU_ZOOM_SELECTION) ++state->zoomEvents; if (event->kind == FW_EV_MENU && event->id == FW_MENU_IMPORT_STEP) ++state->importEvents; } @@ -35,6 +38,14 @@ static void checkMenu(fw_app *app, GMenuModel *menu, TestState *state) { ++state->failures; } } + snprintf(expected, sizeof expected, "win.m%d", FW_MENU_ZOOM_SELECTION); + if (strcmp(action, expected) == 0) { + ++state->zoomItems; + if (!gtk_widget_activate_action(app->window, action, NULL)) { + fprintf(stderr, "Zoom to Selection menu action could not be activated\n"); + ++state->failures; + } + } g_free(action); } const char *links[] = {G_MENU_LINK_SECTION, G_MENU_LINK_SUBMENU}; @@ -146,6 +157,10 @@ int main(void) { state.actions, state.importItems, state.importEvents); ++state.failures; } + if (state.zoomItems != 1 || state.zoomEvents != 1) { + fprintf(stderr, "Expected one Zoom to Selection item/event; found %d items, %d events\n", state.zoomItems, state.zoomEvents); + ++state.failures; + } checkNameDialog(app, &state, GTK_RESPONSE_ACCEPT, "机架 — café 🚀"); checkNameDialog(app, &state, GTK_RESPONSE_CANCEL, "discarded replacement"); checkNameDialog(app, &state, GTK_RESPONSE_ACCEPT, ""); diff --git a/docs/research/modeling-workflow-gaps.md b/docs/research/modeling-workflow-gaps.md index ab7fe61..cf90338 100644 --- a/docs/research/modeling-workflow-gaps.md +++ b/docs/research/modeling-workflow-gaps.md @@ -190,8 +190,11 @@ The whole edit pipeline should preserve unknown/unexposed stored parameters or explicitly refuse editing; reconstructing only visible controls is a corruption risk. Navigation has fit, previous view, standard orientations, styles, projection, -orbit/pan/zoom, sketch normal and a mac orientation palette. Remaining workflows: -zoom-to-selection/area, custom named views, selected-face normal including reverse, +orbit/pan/zoom, sketch normal and a mac orientation palette. The 2026-10-02 follow-on +adds Zoom to Selection across desktop shells and the typed/MCP command bus, including +explicit subshape bounds and previous-view history. Sketch outlines remain sampled. +The baseline appendix below is historical; FEATURES.md tracks current delivery. +Remaining workflows: rectangle zoom-to-area, custom named views, selected-face normal including reverse, section clipping/caps, per-entity transparency/display states, selection sets, 3Dconnexion and configurable shortcuts. Reference planes are rendered under a shared non-document object ID and picks ignore them; use tree selection until meaningful