diff --git a/CHANGELOG.md b/CHANGELOG.md index 491b4cef..087b173b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -126,6 +126,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`create_drawing_view` keeps the sheet's scale.** SolidWorks's "Automatically + scale new drawing views" option rescaled an empty sheet to fit its first + view: a sheet set to 1:2 read 2:1 after a front view of a 30 mm block. The + scale is now set back (the option itself is left alone); the reply gives + `sheet_scale`, `sheet_rescale_undone` and `fits_sheet`, and the message + says when a view runs off the paper. `fit_sheet_scale: true` keeps + SolidWorks's fit. The live test passes on SolidWorks 2026. - **A Bandit alert on the body tools.** The body operation's reply-fields callback was named `extra`, which Bandit's rule B610 reads as Django's `QuerySet.extra` (an SQL risk). There is no SQL; the callback is now diff --git a/README.md b/README.md index 845f1ad8..10bc2417 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,7 @@ Each GIF is a live test driving SolidWorks 2026 through the MCP tools, with the A plate of Hole Wizard holes placed from points, a mirror and a ring
A plate of Hole Wizard holes from points, a mirror and a ring A steel combination wrench sized by one global variable and lettered with its size: 13 mm, then 19 mm, then 8 mm in its own configuration
One variable sizes a combination wrench: equations and configurations +A cube and a sphere as separate bodies: joined, each cut by the other, their common quarter, and the exclusive or
Boolean logic on a cube and a sphere: every combine of two bodies diff --git a/docs/assets/demos/drawing-package/test_a_view_on_a_half_scale_sheet-motion.gif b/docs/assets/demos/drawing-package/test_a_view_on_a_half_scale_sheet-motion.gif new file mode 100644 index 00000000..d66d3a9e Binary files /dev/null and b/docs/assets/demos/drawing-package/test_a_view_on_a_half_scale_sheet-motion.gif differ diff --git a/docs/assets/progress/tool-list-size.md b/docs/assets/progress/tool-list-size.md index 7185f483..b6b84053 100644 --- a/docs/assets/progress/tool-list-size.md +++ b/docs/assets/progress/tool-list-size.md @@ -1,11 +1,11 @@ | `SOLIDWORKS_MCP_TOOLSETS` | `SOLIDWORKS_MCP_TOOL_MODE` | Tools listed | Size | Tokens (estimate) | Of the full list | | --- | --- | ---: | ---: | ---: | ---: | -| `all` | `list` | 173 | 284 KB | 72,744 | 100% | +| `all` | `list` | 173 | 284 KB | 72,811 | 100% | | `core` | `list` | 132 | 206 KB | 52,841 | 73% | -| `drawing` | `list` | 22 | 39 KB | 10,074 | 14% | +| `drawing` | `list` | 22 | 40 KB | 10,141 | 14% | | `automation` | `list` | 3 | 6 KB | 1,556 | 2% | | `vba` | `list` | 10 | 17 KB | 4,356 | 6% | | `docs` | `list` | 6 | 15 KB | 3,916 | 5% | -| `core,drawing` | `list` | 154 | 246 KB | 62,915 | 86% | +| `core,drawing` | `list` | 154 | 246 KB | 62,982 | 87% | | `all` | `search` | 4 | 4 KB | 908 | 1% | | `core` | `search` | 4 | 4 KB | 908 | 1% | diff --git a/docs/demos.md b/docs/demos.md index b1d8c363..3a40d275 100644 --- a/docs/demos.md +++ b/docs/demos.md @@ -743,6 +743,32 @@ from 30 to 15 mm in every view. A scale of 0:2 is refused. 2. `set_sheet_scale({"numerator": 1, "denominator": 2})` 3. `set_sheet_scale({"numerator": 0, "denominator": 2})`: `invalid_input` +### A view keeps the sheet's scale {#view-keeps-scale} + +![create_drawing_view adding an angle bracket's front, top and right views to an A3 sheet set to 1:2, the sheet still 1:2 afterwards; then, with fit_sheet_scale, SolidWorks's own 2:1 kept](assets/demos/drawing-package/test_a_view_on_a_half_scale_sheet-motion.gif) + +> *Example prompt:* On this 1:2 A3 sheet, add the bracket's front, top and +> right views. + +**What it shows.** SolidWorks sets a sheet's scale to its own choice when +the first view goes on, which here would turn a 1:2 sheet into 2:1. +`create_drawing_view` now keeps the scale the sheet had and says so in its +message; `fit_sheet_scale` keeps SolidWorks's choice instead: + +| Step | Tools | Expected | Measured | +| --- | --- | --- | --- | +| An A3 sheet set to 1:2 | `update_sheet_format`, `set_sheet_scale` | 1:2 | 1:2 | +| The bracket's front view | `create_drawing_view` | the sheet stays 1:2 | "kept its scale 1:2 (SolidWorks had changed it to 2:1)" | +| Its top and right views | `create_drawing_view` | still 1:2 | 1:2 | +| A new 1:2 sheet, the front view with `fit_sheet_scale` | `create_drawing_view` | SolidWorks's 2:1, the view on the sheet | 2:1, `fits_sheet` true | + +**Tool calls** + +1. A 60 x 40 x 40 mm angle bracket with three M6 holes, saved +2. `create_drawing`, `update_sheet_format({"sheet_format": "a3 - iso"})`, `set_sheet_scale({"numerator": 1, "denominator": 2})` +3. `create_drawing_view({"model_path": "...", "view_type": "front", "position_x": 140})`, then the top and right views +4. On a new drawing set up the same way: `create_drawing_view({"model_path": "...", "view_type": "front", "position_x": 140, "fit_sheet_scale": true})` + ### A BOM on an assembly drawing {#bom} ![insert_bom_table adding a BOM that lists both parts of a two-part assembly](assets/demos/drawing-package/test_insert_bom_table_lists_both_parts.gif) diff --git a/docs/user-guide/tool-catalog/drawing.md b/docs/user-guide/tool-catalog/drawing.md index 3a36fb13..b234dfeb 100644 --- a/docs/user-guide/tool-catalog/drawing.md +++ b/docs/user-guide/tool-catalog/drawing.md @@ -28,6 +28,7 @@ Place one named view of a part or assembly on the active drawing sheet. | `scale` | `float?` | — | `None` | The view's own scale, e.g. `0.5` for 1:2 (`UseSheetScale` off, `ScaleDecimal`, read back as `scale_applied`); left out, the sheet's scale (`set_sheet_scale`) | | `orientation` | `str?` | — | `None` | View orientation (front, top, right, isometric); left out, a `view_type` that names one is used, else front | | `exploded` | `bool` | — | `False` | Show the assembly's exploded view (`create_exploded_view`) in this view (`IView.ShowExploded`) | +| `fit_sheet_scale` | `bool` | — | `False` | Let SolidWorks rescale the sheet to fit the first view on it (its "Automatically scale new drawing views" option); by default the sheet keeps its scale and the reply gives `sheet_scale`, `sheet_rescale_undone` and `fits_sheet` | **Sample call:** diff --git a/openspec/changes/drawing-view-keeps-sheet-scale/.openspec.yaml b/openspec/changes/drawing-view-keeps-sheet-scale/.openspec.yaml new file mode 100644 index 00000000..d24126c0 --- /dev/null +++ b/openspec/changes/drawing-view-keeps-sheet-scale/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-28 diff --git a/openspec/changes/drawing-view-keeps-sheet-scale/design.md b/openspec/changes/drawing-view-keeps-sheet-scale/design.md new file mode 100644 index 00000000..cd37062e --- /dev/null +++ b/openspec/changes/drawing-view-keeps-sheet-scale/design.md @@ -0,0 +1,27 @@ +## Context + +Probe, SolidWorks 2026 SP4, 2026-11-28: `GetUserPreferenceToggle(86)` +(`swAutomaticScaling3ViewDrawings`) was true. A new drawing's sheet set to +1:2 with `ISheet.SetScale(1, 2, True, False)` read 2:1 after +`CreateDrawViewFromModelView3` placed the first view of a 30 mm block. +`SetScale(1, 2, ...)` then `EditRebuild3` put it back and the view shrank +with it; a second view did not rescale the sheet. + +## Goals / Non-Goals + +**Goals:** a scale set on a sheet holds when views are placed. + +**Non-Goals:** changing the user's SolidWorks option; choosing a scale for +the agent (`generate_drawing_package` already does). + +## Decisions + +1. **Set back, not switch off.** The scale read before the view is set back + after it, rather than turning option 86 off and on: that is a system + setting the user owns, and a failure between the two calls would leave it + changed. +2. **Tell, don't refuse.** A view that no longer fits the paper at the kept + scale is still placed; `fits_sheet` false says so, and the message points + to `set_sheet_scale` or `fit_sheet_scale`. +3. **Default keep.** Keeping is the default because the agent can see and set + the sheet's scale; a silent change it can't see is the bug. diff --git a/openspec/changes/drawing-view-keeps-sheet-scale/proposal.md b/openspec/changes/drawing-view-keeps-sheet-scale/proposal.md new file mode 100644 index 00000000..77cefc83 --- /dev/null +++ b/openspec/changes/drawing-view-keeps-sheet-scale/proposal.md @@ -0,0 +1,35 @@ +## Why + +`create_drawing_view` changed the sheet's scale behind the agent's back. With +SolidWorks's system option "Automatically scale new drawing views" on (the +default), the first view placed on an empty sheet rescales the sheet to fit +it: on 2026-11-28 a sheet set to 1:2 read 2:1 after a front view of a 30 mm +block was placed, so the view was four times the size asked for. A scale set +with `add_sheet` or `set_sheet_scale` should hold. + +## What Changes + +- `create_drawing_view` (and `add_drawing_view`) keep the active sheet's + scale: when SolidWorks rescales the sheet while placing the view, the scale + is set back. The reply gives `sheet_scale`, `sheet_rescale_undone` (the + scale SolidWorks chose, or null) and `fits_sheet` (whether the view lies + on the paper). +- A new input `fit_sheet_scale` (default false) lets SolidWorks fit the + sheet to the first view, as before. +- The user's SolidWorks option is never changed. + +## Capabilities + +### New Capabilities + +- `tools/drawing-view-placement`: the sheet scale around a placed view. + +### Modified Capabilities + +None. + +## Impact + +- `adapters/solidworks/io.py` (`_place_view`), the mock's `_mock_place_view`, + `tools/drawing.py` (`CreateDrawingViewInput.fit_sheet_scale`). +- Tests beside each module; a live test. diff --git a/openspec/changes/drawing-view-keeps-sheet-scale/specs/tools/drawing-view-placement/spec.md b/openspec/changes/drawing-view-keeps-sheet-scale/specs/tools/drawing-view-placement/spec.md new file mode 100644 index 00000000..19ec5c8a --- /dev/null +++ b/openspec/changes/drawing-view-keeps-sheet-scale/specs/tools/drawing-view-placement/spec.md @@ -0,0 +1,21 @@ +## ADDED Requirements + +### Requirement: A placed view keeps the sheet's scale +`create_drawing_view` SHALL leave the active sheet's scale as it was before +the view was placed, setting it back when SolidWorks rescaled the sheet, and +SHALL reply with `sheet_scale` (e.g. `"1:2"`), `sheet_rescale_undone` (the +scale SolidWorks had chosen, or null when it chose none) and `fits_sheet` +(whether the view's outline lies on the paper, or null when unread). With +`fit_sheet_scale` true it SHALL keep the scale SolidWorks chose. It SHALL NOT +change SolidWorks's own options. + +#### Scenario: A first view on a 1:2 sheet +- **WHEN** a front view of a 30 mm block is placed on an empty sheet at 1:2 + while SolidWorks's automatic view scaling is on +- **THEN** the sheet reads 1:2 afterwards, `sheet_rescale_undone` names the + scale SolidWorks had chosen, and `fits_sheet` is true + +#### Scenario: Letting SolidWorks fit the sheet +- **WHEN** the same view is placed with `fit_sheet_scale` true +- **THEN** the sheet keeps the scale SolidWorks chose and + `sheet_rescale_undone` is null diff --git a/openspec/changes/drawing-view-keeps-sheet-scale/tasks.md b/openspec/changes/drawing-view-keeps-sheet-scale/tasks.md new file mode 100644 index 00000000..69a2f029 --- /dev/null +++ b/openspec/changes/drawing-view-keeps-sheet-scale/tasks.md @@ -0,0 +1,16 @@ +## 1. Build + +- [x] 1.1 `_place_view`: read the sheet scale before, set it back after + unless `fit_sheet_scale`; reply `sheet_scale`, `sheet_rescale_undone`, + `fits_sheet` +- [x] 1.2 Mock and tool input `fit_sheet_scale`; the tool's message names a + view off the paper + +## 2. Tests + +- [x] 2.1 Unit tests beside each module, 100% coverage +- [x] 2.2 Live test `tests/live/test_live_sw_drawing_view_scale.py` + +## 3. Docs + +- [x] 3.1 CHANGELOG; tool catalog entry diff --git a/src/solidworks_mcp/adapters/mock_adapter.py b/src/solidworks_mcp/adapters/mock_adapter.py index cff53b7e..27cce339 100644 --- a/src/solidworks_mcp/adapters/mock_adapter.py +++ b/src/solidworks_mcp/adapters/mock_adapter.py @@ -3323,6 +3323,9 @@ def _mock_place_view(self, payload: Any) -> AdapterResult[dict[str, Any]]: }, "views_before": before, "views_after": len(self._drawing_views), + "sheet_scale": "1:1", + "sheet_rescale_undone": None, + "fits_sheet": True, }, execution_time=self._delays["model_operation"], ) diff --git a/src/solidworks_mcp/adapters/solidworks/io.py b/src/solidworks_mcp/adapters/solidworks/io.py index 9d197e55..a08b5cce 100644 --- a/src/solidworks_mcp/adapters/solidworks/io.py +++ b/src/solidworks_mcp/adapters/solidworks/io.py @@ -217,6 +217,51 @@ def _view_names(adapter: Any, drawing: Any) -> list[str]: return names +def _sheet_reading(adapter: Any, drawing: Any) -> tuple[Any, list[float] | None]: + """The active sheet and its ``GetProperties2`` values, or None unread. + + Args: + adapter: A connected ``PyWin32Adapter``. + drawing: The drawing document, flagged for ``IDrawingDoc``. + + Returns: + tuple: The sheet (``ISheet``) and its properties: paper size, template, + scale numerator and denominator, first angle, width and height (m). + """ + sheet = adapter._attempt( + lambda: _sw_type_info.flagged(drawing.GetCurrentSheet(), "ISheet"), + default=None, + ) + props = adapter._attempt(lambda: sheet.GetProperties2(), default=None) + if isinstance(props, (list, tuple)) and len(props) >= 7: + return sheet, [float(v) for v in props[:7]] + return sheet, None + + +def _scale_text(props: list[float]) -> str: + """A sheet's scale as ``"1:2"`` from its properties.""" + return f"{props[2]:g}:{props[3]:g}" + + +def _on_paper(adapter: Any, view: Any, props: list[float]) -> bool | None: + """Whether a view's outline lies on the sheet's paper, or None unread. + + Args: + adapter: A connected ``PyWin32Adapter``. + view: The placed view (``IView``), or None. + props: The sheet's ``GetProperties2`` values; width and height in m. + + Returns: + bool | None: True when the outline is inside the paper. + """ + wrapped: Any = _as_com(adapter, view, "IView") if view is not None else None + outline = adapter._attempt(lambda: wrapped.GetOutline(), default=None) + if not (isinstance(outline, (list, tuple)) and len(outline) >= 4): + return None + x0, y0, x1, y1 = (float(v) for v in outline[:4]) + return x0 >= 0 and y0 >= 0 and x1 <= props[5] and y1 <= props[6] + + def _component_transforms(adapter: Any, assembly: Any) -> dict[str, tuple[float, ...]]: """Snapshot every component's placement, for before/after comparison. @@ -3447,6 +3492,7 @@ def _place_view(self, payload: Any) -> AdapterResult[dict[str, Any]]: def _add() -> dict[str, Any]: drawing = _sw_type_info.flagged(adapter.currentModel, "IDrawingDoc") before = _view_names(adapter, drawing) + _, sheet_before = _sheet_reading(adapter, drawing) # The model has to be loaded before a view of it can be placed, # and OpenDoc6's errors/warnings out-params must be byref VARIANTs @@ -3519,6 +3565,30 @@ def _add() -> dict[str, Any]: scale_read, scale, rel_tol=1e-6 ) + # SolidWorks's "Automatically scale new drawing views" option + # rescales an empty sheet to fit its first view (a 1:2 sheet read + # 2:1). The scale is set back unless the caller asked for the fit; + # the user's option itself is never touched. + sheet, sheet_after = _sheet_reading(adapter, drawing) + rescale_undone = None + if ( + sheet_before is not None + and sheet_after is not None + and sheet_after[2:4] != sheet_before[2:4] + and not _first(data, "fit_sheet_scale", default=False) + ): + rescale_undone = _scale_text(sheet_after) + kept = sheet_before + adapter._attempt( + lambda: sheet.SetScale(kept[2], kept[3], True, False), + default=None, + ) + adapter._attempt( + lambda: adapter.currentModel.EditRebuild3(), default=None + ) + _, sheet_after = _sheet_reading(adapter, drawing) + fits_sheet = _on_paper(adapter, view, sheet_after) if sheet_after else None + shows_exploded = None if _first(data, "exploded", default=False): shown = _as_com(adapter, view, "IView") if view is not None else None @@ -3539,6 +3609,9 @@ def _add() -> dict[str, Any]: "scale_read": scale_read, "views_before": len(before), "views_after": len(after), + "sheet_scale": _scale_text(sheet_after) if sheet_after else None, + "sheet_rescale_undone": rescale_undone, + "fits_sheet": fits_sheet, } return cast( diff --git a/src/solidworks_mcp/tools/drawing.py b/src/solidworks_mcp/tools/drawing.py index 57a60f75..091591ce 100644 --- a/src/solidworks_mcp/tools/drawing.py +++ b/src/solidworks_mcp/tools/drawing.py @@ -35,6 +35,7 @@ class CreateDrawingViewInput(BaseModel): scale (float | None): The view's own scale; none uses the sheet's. view_type (str): The view type value. exploded (bool): Show the assembly's exploded view. + fit_sheet_scale (bool): Let SolidWorks rescale the sheet to fit the view. """ model_path: str = Field(description="Path to the SolidWorks model file") @@ -59,6 +60,35 @@ class CreateDrawingViewInput(BaseModel): description="Show the assembly's exploded view (create_exploded_view) in " "this view", ) + fit_sheet_scale: bool = Field( + default=False, + description="Let SolidWorks rescale the sheet to fit the first view on it; " + "by default the sheet keeps its scale (set_sheet_scale)", + ) + + +def _view_message(input_data: CreateDrawingViewInput, data: dict[str, Any]) -> str: + """The reply message for a placed view, naming a kept scale or an overflow. + + Args: + input_data: The view that was asked for. + data: The adapter's reply data. + + Returns: + str: The message. + """ + message = f"Created {input_data.view_type} view of {input_data.model_path}" + if data.get("sheet_rescale_undone"): + message += ( + f"; the sheet kept its scale {data.get('sheet_scale')} (SolidWorks had " + f"changed it to {data['sheet_rescale_undone']})" + ) + if data.get("fits_sheet") is False: + message += ( + "; the view runs off the paper: set a smaller scale with " + "set_sheet_scale, or place it with fit_sheet_scale" + ) + return message class AddDimensionInput(CompatInput): @@ -451,8 +481,9 @@ async def create_drawing_view(input_data: CreateDrawingViewInput) -> dict[str, A `create_technical_drawing`, and for a whole drawing from a model, use `generate_drawing_package`. Needs: an open, active drawing and the model file on disk. Changes: adds a view - to the sheet. Returns: `data` with the view's `name`, `orientation`, `position`, - `scale` and the view counts before and after. + to the sheet; the sheet keeps its scale unless `fit_sheet_scale`. Returns: `data` + with the view's `name`, `orientation`, `position`, `scale`, `sheet_scale`, + `fits_sheet` and the view counts before and after. Args: input_data: The view. `model_path` and `view_type` (front, back, left, right, top, bottom, isometric (iso), trimetric, dimetric or current) are @@ -472,7 +503,7 @@ async def create_drawing_view(input_data: CreateDrawingViewInput) -> dict[str, A require_success(result, "Failed to create drawing view") return { "status": "success", - "message": f"Created {input_data.view_type} view of {input_data.model_path}", + "message": _view_message(input_data, result.data or {}), "data": result.data, "execution_time": result.execution_time, } diff --git a/tests/live/drawing_parts.py b/tests/live/drawing_parts.py new file mode 100644 index 00000000..20689e5f --- /dev/null +++ b/tests/live/drawing_parts.py @@ -0,0 +1,81 @@ +"""A part worth drawing, for the live drawing demos. + +A plain block's front view is one rectangle, which shows nothing on a sheet. +The angle bracket here has an outline that changes from view to view and +holes that show as circles in one view and hidden lines in the others. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +#: An 8 mm base 60 mm long and an 8 mm upright 40 mm tall, both 40 mm deep +#: (centred on the Front Plane), on the Front Plane's x and y. +_BASE = {"x1": 0, "y1": 0, "x2": 60, "y2": 8} +_UPRIGHT = {"x1": 0, "y1": 8, "x2": 8, "y2": 40} +#: Two M6 holes in the base's top face. +_BASE_HOLES = { + "face_point": [40, 8, -10], + "positions": [[40, 8, 10]], + "hole_type": "simple", + "size": "M6", +} +#: An M6 clearance hole (6.4 mm) through the upright, 26 mm up: a circle on +#: the Right Plane (its y is the model's y) cut through both ways. +_UPRIGHT_CIRCLE = {"center_x": 0, "center_y": 26, "radius": 3.2} +_THROUGH = {"depth": 10, "end_condition": "ThroughAllBoth"} +#: swStandardViews_e.swTopView: looking down on the base's top face. +_TOP_VIEW = 5 + + +def _face_on(adapter: Any, view: int) -> None: + """Look square at the face a hole goes on (staging, not a tool call). + + ``create_hole`` picks its face at a point along the view direction, so + the face must face the camera: after a sketch on the Front Plane + SolidWorks looks straight at Front, where the base's top face is + edge-on. The upright's hole is a sketched cut instead, which no view + affects. + """ + model = adapter.currentModel + adapter._attempt(lambda: model.ClearSelection2(True), default=None) + adapter._attempt(lambda: model.ShowNamedView2("", view), default=None) + adapter._zoom_to_fit(model) + + +async def _ok(reply: dict[str, Any]) -> dict[str, Any]: + assert reply["status"] == "success", reply + return reply + + +async def saved_bracket(scratch: Any, tools: dict[str, Any], path: Path) -> str: + """Build the drilled angle bracket through the tools and save it. + + Args: + scratch: The live scratch fixture (its adapter saves the part and its + ``written_files`` list cleans the file up). + tools: Registered tools, name -> fn; needs the modelling tools. + path: Where to save the part. + + Returns: + str: The saved part's path. + """ + await _ok(await tools["create_part"]({"name": path.stem})) + for outline in (_BASE, _UPRIGHT): + await _ok(await tools["create_sketch"]({"plane": "Front"})) + await _ok(await tools["add_rectangle"](outline)) + await _ok(await tools["exit_sketch"]()) + await _ok( + await tools["create_extrusion"]({"depth": 40, "both_directions": True}) + ) + _face_on(scratch.adapter, _TOP_VIEW) + await _ok(await tools["create_hole"](_BASE_HOLES)) + await _ok(await tools["create_sketch"]({"plane": "Right"})) + await _ok(await tools["add_circle"](_UPRIGHT_CIRCLE)) + await _ok(await tools["exit_sketch"]()) + await _ok(await tools["create_cut_extrude"](_THROUGH)) + saved = await scratch.adapter.save_file(str(path)) + assert saved.is_success, saved.error + scratch.written_files.append(str(path)) + return str(path) diff --git a/tests/live/test_live_sw_drawing_view_scale.py b/tests/live/test_live_sw_drawing_view_scale.py new file mode 100644 index 00000000..43c67ca6 --- /dev/null +++ b/tests/live/test_live_sw_drawing_view_scale.py @@ -0,0 +1,101 @@ +"""A placed view keeps the sheet's scale, checked on real SolidWorks. + +SolidWorks's "Automatically scale new drawing views" option rescales an +empty sheet to fit its first view: a sheet set to 1:2 read 2:1 after a front +view of a 30 mm block was placed (2026-11-28). ``create_drawing_view`` now +sets the scale back; with ``fit_sheet_scale`` it keeps SolidWorks's choice. + +Run with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_drawing_view_scale.py::test_a_view_on_a_half_scale_sheet + +Collected only with ``SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1`` on Windows. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest + +from tests.live.drawing_parts import saved_bracket +from tests.live.evidence import evidence + +pytestmark = pytest.mark.asyncio + + +async def _tools(adapter: Any) -> dict[str, Any]: + """The drawing, drawing automation and modelling tools; name -> fn.""" + from fastmcp import FastMCP + + from solidworks_mcp.tools.drawing import register_drawing_tools + from solidworks_mcp.tools.drawing_automation import ( + register_drawing_automation_tools, + ) + from solidworks_mcp.tools.modeling import register_modeling_tools + from solidworks_mcp.tools.sketching import register_sketching_tools + + mcp = FastMCP("view-scale-live") + for register in ( + register_modeling_tools, + register_sketching_tools, + register_drawing_tools, + register_drawing_automation_tools, + ): + await register(mcp, adapter, {}) + return {t.name: t.fn for t in await mcp.list_tools()} + + +async def _ok(reply: dict[str, Any]) -> dict[str, Any]: + assert reply["status"] == "success", reply + return reply + + +async def _half_scale_drawing(tools: dict[str, Any], name: str) -> None: + """A new A3 drawing whose sheet is set to 1:2.""" + await _ok(await tools["create_drawing"]({"name": name})) + await _ok(await tools["update_sheet_format"]({"sheet_format": "a3 - iso"})) + await _ok(await tools["set_sheet_scale"]({"numerator": 1, "denominator": 2})) + + +async def test_a_view_on_a_half_scale_sheet(scratch: Any, tmp_path: Path) -> None: + """The sheet stays 1:2; with fit_sheet_scale SolidWorks's fit is kept.""" + adapter = scratch.adapter + tools = await _tools(adapter) + part = await saved_bracket(scratch, tools, tmp_path / "view-scale-bracket.SLDPRT") + + await _half_scale_drawing(tools, "kept-scale") + call = {"model_path": part, "view_type": "front", "position_x": 140} + kept = await _ok(await tools["create_drawing_view"](call)) + adapter._zoom_to_fit(adapter.currentModel) + evidence("a front view on a 1:2 sheet", kept, call="create_drawing_view(front)") + assert kept["data"]["sheet_scale"] == "1:2" + assert kept["data"]["sheet_rescale_undone"] not in (None, "1:2") + assert kept["data"]["fits_sheet"] is True + # The top and right views (first angle: below it and on its left). + for view_type, x, y in (("top", 140, 95), ("right", 80, 150)): + more = {"model_path": part, "view_type": view_type} + placed = await _ok( + await tools["create_drawing_view"]( + {**more, "position_x": x, "position_y": y} + ) + ) + adapter._zoom_to_fit(adapter.currentModel) + scale_now = placed["data"]["sheet_scale"] + evidence("the top and right views join it", {"sheet_scale": scale_now}) + assert scale_now == "1:2" + + await _half_scale_drawing(tools, "fitted-scale") + fitted = await _ok( + await tools["create_drawing_view"]({**call, "fit_sheet_scale": True}) + ) + adapter._zoom_to_fit(adapter.currentModel) + evidence( + "the same view with fit_sheet_scale: SolidWorks's choice kept", + fitted["data"], + call="create_drawing_view(front, fit_sheet_scale=True)", + ) + assert fitted["data"]["sheet_scale"] != "1:2" + assert fitted["data"]["sheet_rescale_undone"] is None diff --git a/tests/solidworks_mcp/adapters/solidworks/test_io.py b/tests/solidworks_mcp/adapters/solidworks/test_io.py index bffa939b..ce0391cf 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_io.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_io.py @@ -4904,3 +4904,77 @@ async def test_a_starred_name_is_used_as_given(self, monkeypatch, field) -> None assert result.data["orientation"] == "*Meine Ansicht" placed = adapter.currentModel.CreateDrawViewFromModelView3.call_args.args assert placed[1] == "*Meine Ansicht" + + +class _RescaledSheet: + """A Letter sheet at 1:2 that SolidWorks rescales to 2:1 on the first view.""" + + def __init__(self) -> None: + self.scale = (1.0, 2.0) + self.reads = 0 + self.set_to: list[tuple[float, float]] = [] + + def GetProperties2(self) -> list[float]: + self.reads += 1 + if self.reads == 2 and not self.set_to: + self.scale = (2.0, 1.0) # what the automatic scaling did + return [12, 12, *self.scale, 0, 0.2794, 0.2159, 0] + + def SetScale(self, top: float, bottom: float, _first: bool, _third: bool) -> bool: + self.set_to.append((top, bottom)) + self.scale = (top, bottom) + return True + + +def _sheet_adapter(monkeypatch, outline: object): # noqa: ANN202 + """A drawing whose sheet is rescaled when a view with ``outline`` lands.""" + view = SimpleNamespace(GetOutline=lambda: outline) + adapter = _view_adapter(monkeypatch, view) + sheet = _RescaledSheet() + adapter.currentModel.GetCurrentSheet.return_value = sheet + return adapter, sheet + + +class TestTheSheetKeepsItsScale: + """A first view no longer rescales the sheet (1:2 read 2:1, 2026-11-28).""" + + @pytest.mark.asyncio + async def test_the_scale_is_set_back(self, monkeypatch) -> None: + adapter, sheet = _sheet_adapter(monkeypatch, [0.1, 0.1, 0.13, 0.12]) + + result = await adapter.create_drawing_view({"model_path": __file__}) + + assert sheet.set_to == [(1.0, 2.0)] + assert result.data["sheet_scale"] == "1:2" + assert result.data["sheet_rescale_undone"] == "2:1" + assert result.data["fits_sheet"] is True + + @pytest.mark.asyncio + async def test_fit_sheet_scale_keeps_solidworks_choice(self, monkeypatch) -> None: + adapter, sheet = _sheet_adapter(monkeypatch, [0.2, 0.1, 0.3, 0.12]) + + result = await adapter.create_drawing_view( + {"model_path": __file__, "fit_sheet_scale": True} + ) + + assert sheet.set_to == [] + assert result.data["sheet_scale"] == "2:1" + assert result.data["sheet_rescale_undone"] is None + assert result.data["fits_sheet"] is False + + @pytest.mark.asyncio + async def test_an_unread_outline_is_unknown(self, monkeypatch) -> None: + adapter, _ = _sheet_adapter(monkeypatch, None) + + result = await adapter.create_drawing_view({"model_path": __file__}) + + assert result.data["fits_sheet"] is None + + @pytest.mark.asyncio + async def test_an_unread_sheet_is_left_alone(self, monkeypatch) -> None: + adapter = _view_adapter(monkeypatch, None) + + result = await adapter.create_drawing_view({"model_path": __file__}) + + assert result.data["sheet_scale"] is None + assert result.data["fits_sheet"] is None diff --git a/tests/solidworks_mcp/tools/test_drawing.py b/tests/solidworks_mcp/tools/test_drawing.py index c8591401..7c37e006 100644 --- a/tests/solidworks_mcp/tools/test_drawing.py +++ b/tests/solidworks_mcp/tools/test_drawing.py @@ -12,6 +12,7 @@ DimensionInput, DrawingCreationInput, DrawingViewInput, + _view_message, register_drawing_tools, ) @@ -584,3 +585,24 @@ def test_a_drawing_view_leaves_scale_and_orientation_to_the_sheet_and_view_type( assert made.scale is None assert made.orientation is None + + +@pytest.mark.parametrize( + ("data", "said"), + [ + ({}, "Created top view of p.sldprt"), + ( + {"sheet_scale": "1:2", "sheet_rescale_undone": "2:1"}, + "the sheet kept its scale 1:2 (SolidWorks had changed it to 2:1)", + ), + ({"fits_sheet": False}, "runs off the paper"), + ], +) +def test_a_view_message_names_a_kept_scale_or_an_overflow( + data: dict, said: str +) -> None: + """A rescale SolidWorks made and undid, or a view off the paper, is said.""" + made = CreateDrawingViewInput(model_path="p.sldprt", view_type="top") + + assert said in _view_message(made, data) + assert made.fit_sheet_scale is False