From bf621ea477fafca06ee0fc0df61c683e236d180c Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 11:53:36 +0300 Subject: [PATCH 01/13] feat: add Smart Insert for accurately scaled SVG sketches --- .fusion-addin.json | 8 +- .github/release-paths.txt | 4 +- .github/workflows/initialize.yml | 68 ---- AGENTS.md | 4 +- AGENTS.ru.md | 4 +- FusionAddin/FusionAddin.py | 110 ------ FusionAddin/config.py | 7 - FusionAddin/core.py | 10 - .../InsertTo.manifest | 4 +- InsertTo/InsertTo.py | 73 ++++ {FusionAddin => InsertTo}/__init__.py | 0 InsertTo/config.py | 7 + InsertTo/dialog.py | 173 +++++++++ InsertTo/fusion_import.py | 173 +++++++++ InsertTo/resources/bottom-center/16x16.png | Bin 0 -> 536 bytes InsertTo/resources/bottom-center/32x32.png | Bin 0 -> 978 bytes InsertTo/resources/bottom-left/16x16.png | Bin 0 -> 559 bytes InsertTo/resources/bottom-left/32x32.png | Bin 0 -> 931 bytes InsertTo/resources/bottom-right/16x16.png | Bin 0 -> 555 bytes InsertTo/resources/bottom-right/32x32.png | Bin 0 -> 962 bytes InsertTo/resources/center-left/16x16.png | Bin 0 -> 556 bytes InsertTo/resources/center-left/32x32.png | Bin 0 -> 1022 bytes InsertTo/resources/center-right/16x16.png | Bin 0 -> 571 bytes InsertTo/resources/center-right/32x32.png | Bin 0 -> 1038 bytes InsertTo/resources/center/16x16.png | Bin 0 -> 561 bytes InsertTo/resources/center/32x32.png | Bin 0 -> 1021 bytes InsertTo/resources/fit/16x16.png | Bin 0 -> 478 bytes InsertTo/resources/fit/32x32.png | Bin 0 -> 905 bytes InsertTo/resources/original/16x16.png | Bin 0 -> 508 bytes InsertTo/resources/original/32x32.png | Bin 0 -> 933 bytes InsertTo/resources/smart-insert/16x16.png | Bin 0 -> 583 bytes InsertTo/resources/smart-insert/32x32.png | Bin 0 -> 1088 bytes InsertTo/resources/stretch/16x16.png | Bin 0 -> 468 bytes InsertTo/resources/stretch/32x32.png | Bin 0 -> 698 bytes InsertTo/resources/svg/16x16.png | Bin 0 -> 616 bytes InsertTo/resources/svg/32x32.png | Bin 0 -> 1399 bytes InsertTo/resources/top-center/16x16.png | Bin 0 -> 553 bytes InsertTo/resources/top-center/32x32.png | Bin 0 -> 1003 bytes InsertTo/resources/top-left/16x16.png | Bin 0 -> 570 bytes InsertTo/resources/top-left/32x32.png | Bin 0 -> 968 bytes InsertTo/resources/top-right/16x16.png | Bin 0 -> 573 bytes InsertTo/resources/top-right/32x32.png | Bin 0 -> 966 bytes InsertTo/svg_geometry.py | 356 ++++++++++++++++++ README.md | 38 +- README.ru.md | 39 +- docs/DEVELOPMENT.md | 30 +- docs/DEVELOPMENT.ru.md | 30 +- scripts/build.py | 2 +- scripts/check_project.py | 2 +- tests/test_core.py | 29 -- tests/test_dialog.py | 87 +++++ tests/test_fusion_import.py | 61 +++ tests/test_package.py | 12 +- tests/test_svg_geometry.py | 131 +++++++ 54 files changed, 1132 insertions(+), 330 deletions(-) delete mode 100644 .github/workflows/initialize.yml delete mode 100644 FusionAddin/FusionAddin.py delete mode 100644 FusionAddin/config.py delete mode 100644 FusionAddin/core.py rename FusionAddin/FusionAddin.manifest => InsertTo/InsertTo.manifest (55%) create mode 100644 InsertTo/InsertTo.py rename {FusionAddin => InsertTo}/__init__.py (100%) create mode 100644 InsertTo/config.py create mode 100644 InsertTo/dialog.py create mode 100644 InsertTo/fusion_import.py create mode 100644 InsertTo/resources/bottom-center/16x16.png create mode 100644 InsertTo/resources/bottom-center/32x32.png create mode 100644 InsertTo/resources/bottom-left/16x16.png create mode 100644 InsertTo/resources/bottom-left/32x32.png create mode 100644 InsertTo/resources/bottom-right/16x16.png create mode 100644 InsertTo/resources/bottom-right/32x32.png create mode 100644 InsertTo/resources/center-left/16x16.png create mode 100644 InsertTo/resources/center-left/32x32.png create mode 100644 InsertTo/resources/center-right/16x16.png create mode 100644 InsertTo/resources/center-right/32x32.png create mode 100644 InsertTo/resources/center/16x16.png create mode 100644 InsertTo/resources/center/32x32.png create mode 100644 InsertTo/resources/fit/16x16.png create mode 100644 InsertTo/resources/fit/32x32.png create mode 100644 InsertTo/resources/original/16x16.png create mode 100644 InsertTo/resources/original/32x32.png create mode 100644 InsertTo/resources/smart-insert/16x16.png create mode 100644 InsertTo/resources/smart-insert/32x32.png create mode 100644 InsertTo/resources/stretch/16x16.png create mode 100644 InsertTo/resources/stretch/32x32.png create mode 100644 InsertTo/resources/svg/16x16.png create mode 100644 InsertTo/resources/svg/32x32.png create mode 100644 InsertTo/resources/top-center/16x16.png create mode 100644 InsertTo/resources/top-center/32x32.png create mode 100644 InsertTo/resources/top-left/16x16.png create mode 100644 InsertTo/resources/top-left/32x32.png create mode 100644 InsertTo/resources/top-right/16x16.png create mode 100644 InsertTo/resources/top-right/32x32.png create mode 100644 InsertTo/svg_geometry.py delete mode 100644 tests/test_core.py create mode 100644 tests/test_dialog.py create mode 100644 tests/test_fusion_import.py create mode 100644 tests/test_svg_geometry.py diff --git a/.fusion-addin.json b/.fusion-addin.json index 4724926..47d110a 100644 --- a/.fusion-addin.json +++ b/.fusion-addin.json @@ -1,6 +1,6 @@ { - "name": "FusionAddin", - "display_name": "Fusion Add-in Template", - "description": "A starter add-in for Autodesk Fusion by 4FusionLab.", - "initialized": false + "name": "InsertTo", + "display_name": "InsertTo", + "description": "Import SVG artwork into a sketch frame with accurate dimensions and live placement preview.", + "initialized": true } diff --git a/.github/release-paths.txt b/.github/release-paths.txt index 587bba5..084403f 100644 --- a/.github/release-paths.txt +++ b/.github/release-paths.txt @@ -1,4 +1,4 @@ -# Distribution inputs only; documentation, tests, CI and policy do not publish. -FusionAddin/** +# Only shipped add-in inputs may trigger an automatic GitHub Release. +InsertTo/** scripts/build.py .fusion-addin.json diff --git a/.github/workflows/initialize.yml b/.github/workflows/initialize.yml deleted file mode 100644 index b087259..0000000 --- a/.github/workflows/initialize.yml +++ /dev/null @@ -1,68 +0,0 @@ -name: Initialize add-in - -on: - workflow_dispatch: - inputs: - display_name: - description: 'Display name in Autodesk Fusion (default: repository name)' - required: false - type: string - description: - description: 'Short English product description' - required: false - type: string - -permissions: - contents: write - actions: write - -concurrency: - group: 4fl-initialize - cancel-in-progress: false - -jobs: - initialize: - name: Scaffold once with unique Fusion IDs - if: github.repository != '4FusionLab/.fusion-addin-template' && github.ref == 'refs/heads/main' - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: true # explicitly required to push setup commit - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: '3.12' - - name: Generate unique manifest and command identifiers - shell: bash - env: - DISPLAY_NAME: ${{ inputs.display_name }} - PRODUCT_DESCRIPTION: ${{ inputs.description }} - REPOSITORY: ${{ github.repository }} - run: | - set -euo pipefail - repo_name="${REPOSITORY#*/}" - python scripts/init_addin.py --name "$repo_name" \ - --display-name "$DISPLAY_NAME" --description "$PRODUCT_DESCRIPTION" \ - --repo "$REPOSITORY" - python scripts/check_project.py - python -m unittest discover -s tests -v - - name: Commit generated project to main - shell: bash - run: | - set -euo pipefail - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add -A - if git diff --cached --quiet; then - echo "Initialization made no changes" >&2 - exit 1 - fi - git commit -m "chore: initialize 4FusionLab add-in [skip release]" - git push origin HEAD:main - - name: Dispatch read-only CI on initialized commit - shell: bash - env: - GH_TOKEN: ${{ github.token }} - run: gh workflow run ci.yml --ref main - diff --git a/AGENTS.md b/AGENTS.md index cfbfbc8..0ed3a38 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,11 +6,11 @@ Read [4FusionLab shared engineering rules](https://github.com/4FusionLab/.github ## Working model -- This is an Autodesk Fusion Python add-in. The initial package is `FusionAddin/`; the initializer replaces its name and generates stable IDs. +- This is an Autodesk Fusion Python add-in. The initial package is `InsertTo/`; the initializer replaces its name and generates stable IDs. - Discuss requirements and plans in Russian. Use clear English for Fusion commands, controls, diagnostics, and stable API names. Write documents in English and maintain separate Russian versions of documentation; intermediate working notes do not require translation. - For README creation or edits, apply the [shared product README guidelines](https://github.com/4FusionLab/.github/blob/main/README_GUIDELINES.md). Check both languages, current release and license terms, and actual validation evidence before delivery. - Treat the official Autodesk Fusion API documentation as the source of truth. Never invent SDK symbols; do not imply successful CAD acceptance based solely on offline CI. -- Put calculations and domain rules into `FusionAddin/core.py` or modules that **do not import adsk**. Fusion API interactions belong in adapters, event handlers and commands running in Fusion's permitted execution context. +- Put calculations and domain rules into `InsertTo/svg_geometry.py` or modules that **do not import adsk**. Fusion API interactions belong in adapters, event handlers and commands running in Fusion's permitted execution context. - Design commands to be safe: validate active document, entities, units, parameters, and timeline state; use native previews where applicable. Never modify a user's CAD data during tests or without an explicit command action. - Retain event handler instances while active; detach UI controls and command definitions in `stop(context)`. Keep identifiers stable after initial scaffolding. Avoid global state tied to stale documents. - Add meaningful unit and offline integration tests. Test real Fusion flows on Windows/macOS separately when they matter; report what has and has not actually been verified. diff --git a/AGENTS.ru.md b/AGENTS.ru.md index e0b9d40..df14eed 100644 --- a/AGENTS.ru.md +++ b/AGENTS.ru.md @@ -6,11 +6,11 @@ ## Порядок работы -- Это аддон Autodesk Fusion на Python. Начальный пакет — `FusionAddin/`; инициализатор заменяет его имя и создаёт стабильные идентификаторы. +- Это аддон Autodesk Fusion на Python. Начальный пакет — `InsertTo/`; инициализатор заменяет его имя и создаёт стабильные идентификаторы. - Обсуждайте требования и планы на русском. Для команд, элементов управления и диагностики Fusion и стабильных имён API используйте понятный английский. Документы ведите на английском, для документации поддерживайте отдельные русские версии; промежуточные рабочие заметки переводить не требуется. - При создании или изменении README следуйте [общим правилам README продуктов](https://github.com/4FusionLab/.github/blob/main/README_GUIDELINES.md). До передачи проверяйте оба языка, действующий релиз и условия лицензии и фактические результаты проверок. - Считайте официальную документацию Autodesk Fusion API источником истины. Никогда не выдумывайте символы SDK; успешный автономный CI сам по себе не означает приёмку CAD. -- Расчёты и предметные правила размещайте в `FusionAddin/core.py` или модулях, которые **не импортируют adsk**. Взаимодействия с Fusion API относятся к адаптерам, обработчикам событий и командам, выполняемым в разрешённом контексте Fusion. +- Расчёты и предметные правила размещайте в `InsertTo/svg_geometry.py` или модулях, которые **не импортируют adsk**. Взаимодействия с Fusion API относятся к адаптерам, обработчикам событий и командам, выполняемым в разрешённом контексте Fusion. - Делайте команды безопасными: проверяйте активный документ, объекты, единицы, параметры и состояние таймлайна; используйте нативный предпросмотр, где применимо. Никогда не изменяйте CAD-данные пользователя в тестах или без явного действия командой. - Сохраняйте экземпляры обработчиков событий на время работы; в `stop(context)` отсоединяйте элементы интерфейса и определения команд. После начального создания сохраняйте идентификаторы стабильными. Избегайте глобального состояния, связанного с устаревшими документами. - Добавляйте значимые модульные и автономные интеграционные тесты. Когда это важно, отдельно проверяйте реальные сценарии Fusion на Windows/macOS; сообщайте, что фактически проверено, а что нет. diff --git a/FusionAddin/FusionAddin.py b/FusionAddin/FusionAddin.py deleted file mode 100644 index 4923585..0000000 --- a/FusionAddin/FusionAddin.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Autodesk Fusion entry point: one non-destructive example command. - -The module is imported only by Fusion; tests target core.py without adsk. -""" - -import traceback - -import adsk.core - -from . import config, core - - -_ui = None -_command_definition = None -_control = None -_handlers = [] -_sessions = [] - - -class _Executed(adsk.core.CommandEventHandler): - def notify(self, args): - try: - app = adsk.core.Application.get() - document = app.activeDocument - document_name = document.name if document else None - app.userInterface.messageBox(core.ready_message(config.DISPLAY_NAME, document_name)) - except Exception: - adsk.core.Application.get().log(traceback.format_exc()) - - -class _Destroyed(adsk.core.CommandEventHandler): - def __init__(self, session): - super().__init__() - self.session = session - - def notify(self, args): - if self.session in _sessions: - _sessions.remove(self.session) - - -class _Session: - def __init__(self, command): - self.executed = _Executed() - self.destroyed = _Destroyed(self) - command.execute.add(self.executed) - command.destroy.add(self.destroyed) - command.commandInputs.addTextBoxCommandInput( - '4fl_intro', '', config.DESCRIPTION, 2, True - ) - - -class _Created(adsk.core.CommandCreatedEventHandler): - def notify(self, args): - try: - _sessions.append(_Session(args.command)) - except Exception: - adsk.core.Application.get().log(traceback.format_exc()) - - -def run(context): - """Register the add-in under SOLID -> ADD-INS. No document is modified.""" - global _ui, _command_definition, _control - - if not config.INITIALIZED: - raise RuntimeError('This is a template. Run scripts/init_addin.py before installing.') - - try: - app = adsk.core.Application.get() - _ui = app.userInterface - workspace = _ui.workspaces.itemById('FusionSolidEnvironment') - if workspace is None: - raise RuntimeError('Fusion SOLID workspace is not available.') - panel = workspace.toolbarPanels.itemById('SolidScriptsAddinsPanel') - if panel is None: - raise RuntimeError('Fusion ADD-INS toolbar panel is not available.') - - definition = _ui.commandDefinitions.itemById(config.COMMAND_ID) - if definition is None: - definition = _ui.commandDefinitions.addButtonDefinition( - config.COMMAND_ID, config.DISPLAY_NAME, config.DESCRIPTION - ) - _command_definition = definition - handler = _Created() - definition.commandCreated.add(handler) - _handlers.append(handler) - control = panel.controls.itemById(config.COMMAND_ID) - if control is None: - control = panel.controls.addCommand(definition) - _control = control - except Exception: - adsk.core.Application.get().log(traceback.format_exc()) - stop(context) - raise - - -def stop(context): - """Remove toolbar items and event references, including after a failed start.""" - global _ui, _command_definition, _control - - try: - if _control is not None and _control.isValid: - _control.deleteMe() - if _command_definition is not None and _command_definition.isValid: - _command_definition.deleteMe() - finally: - _control = None - _command_definition = None - _sessions.clear() - _handlers.clear() - _ui = None diff --git a/FusionAddin/config.py b/FusionAddin/config.py deleted file mode 100644 index 932fba6..0000000 --- a/FusionAddin/config.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Stable project identifiers. Generated once by scripts/init_addin.py.""" - -ADDIN_NAME = 'FusionAddin' -DISPLAY_NAME = 'Fusion Add-in Template' -DESCRIPTION = 'A starter add-in for Autodesk Fusion by 4FusionLab.' -COMMAND_ID = '4FusionLab_FusionAddin_Command' -INITIALIZED = False diff --git a/FusionAddin/core.py b/FusionAddin/core.py deleted file mode 100644 index 892e3ca..0000000 --- a/FusionAddin/core.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Example domain logic: never import adsk in this module.""" - - -def ready_message(display_name, document_name): - """Build a harmless user-facing message for the demonstration command.""" - if not display_name or not display_name.strip(): - raise ValueError('Display name must not be empty.') - if document_name: - return f'{display_name} is ready. Active document: {document_name}.' - return f'{display_name} is ready. Open a design to begin.' diff --git a/FusionAddin/FusionAddin.manifest b/InsertTo/InsertTo.manifest similarity index 55% rename from FusionAddin/FusionAddin.manifest rename to InsertTo/InsertTo.manifest index 26e0d17..e0528f7 100644 --- a/FusionAddin/FusionAddin.manifest +++ b/InsertTo/InsertTo.manifest @@ -1,10 +1,10 @@ { "autodeskProduct": "Fusion360", "type": "addin", - "id": "00000000-0000-4000-8000-000000000000", + "id": "d4f953a4-7cc6-4027-9699-dc025ebc8966", "author": "Pavel Kuznetsov", "description": { - "": "A starter add-in for Autodesk Fusion by 4FusionLab." + "": "Import SVG artwork into a sketch frame with accurate dimensions and live placement preview." }, "version": "0.1.0", "runOnStartup": false, diff --git a/InsertTo/InsertTo.py b/InsertTo/InsertTo.py new file mode 100644 index 0000000..be2253d --- /dev/null +++ b/InsertTo/InsertTo.py @@ -0,0 +1,73 @@ +"""Register Smart Insert in the sketch Insert menu.""" + +import traceback +from pathlib import Path + +import adsk.core + +from . import config, dialog + + +_RESOURCES = Path(__file__).parent / 'resources' +_MENU_ID = '4FusionLab_InsertTo_SmartInsert' +_menu = None +_definition = None +_created = None +_sessions = [] + + +class _Destroyed(adsk.core.CommandEventHandler): + def notify(self, args): + _sessions[:] = [pair for pair in _sessions if pair[1] is not self] + + +class _Created(adsk.core.CommandCreatedEventHandler): + def notify(self, args): + try: + session = dialog.attach(args.command) + destroyed = _Destroyed() + args.command.destroy.add(destroyed) + _sessions.append((session, destroyed)) + except Exception: + app = adsk.core.Application.get() + app.log(traceback.format_exc()) + app.userInterface.messageBox('Could not open Smart Insert. See the Fusion log for details.') + + +def run(context): + global _menu, _created, _definition + if _menu and _menu.isValid: + return + + ui = adsk.core.Application.get().userInterface + workspace = ui.workspaces.itemById('FusionSolidEnvironment') + sketch_tab = workspace.toolbarTabs.itemById('SketchTab') if workspace else None + panel = sketch_tab.toolbarPanels.itemById('InsertPanel') if sketch_tab else None + if not panel: + raise RuntimeError('The sketch Insert panel is unavailable.') + + try: + _definition = ui.commandDefinitions.addButtonDefinition( + config.COMMAND_ID, 'SVG', config.DESCRIPTION, str(_RESOURCES / 'svg') + ) + _created = _Created() + _definition.commandCreated.add(_created) + _menu = panel.controls.addDropDown( + 'Smart Insert', str(_RESOURCES / 'smart-insert'), _MENU_ID, 'SketchImportSVG', False + ) + _menu.controls.addCommand(_definition) + except Exception: + stop(context) + raise + + +def stop(context): + global _menu, _created, _definition + try: + if _menu and _menu.isValid: + _menu.deleteMe() + if _definition and _definition.isValid: + _definition.deleteMe() + finally: + _menu = _created = _definition = None + _sessions.clear() diff --git a/FusionAddin/__init__.py b/InsertTo/__init__.py similarity index 100% rename from FusionAddin/__init__.py rename to InsertTo/__init__.py diff --git a/InsertTo/config.py b/InsertTo/config.py new file mode 100644 index 0000000..c28ba61 --- /dev/null +++ b/InsertTo/config.py @@ -0,0 +1,7 @@ +"""Stable 4FusionLab project identifiers; do not change after release.""" + +ADDIN_NAME = 'InsertTo' +DISPLAY_NAME = 'InsertTo' +DESCRIPTION = 'Import SVG artwork into a sketch frame with accurate dimensions and live placement preview.' +COMMAND_ID = '4FusionLab_InsertTo_77ac0485344b' +INITIALIZED = True diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py new file mode 100644 index 0000000..94040ba --- /dev/null +++ b/InsertTo/dialog.py @@ -0,0 +1,173 @@ +"""Native Smart Insert command inputs and transactional sketch preview.""" + +from pathlib import Path +import traceback + +import adsk.core +import adsk.fusion + +from . import fusion_import, svg_geometry + + +_RESOURCES = Path(__file__).with_name('resources') +_MODES = (('Fit', 'fit'), ('Stretch', 'stretch'), ('Original size', 'original')) +_ANCHORS = ( + ('Top left', 'top-left'), ('Top center', 'top-center'), ('Top right', 'top-right'), + ('Center left', 'center-left'), ('Center', 'center'), ('Center right', 'center-right'), + ('Bottom left', 'bottom-left'), ('Bottom center', 'bottom-center'), ('Bottom right', 'bottom-right'), +) + + +def _icon_list(inputs, id_, label, choices, default): + control = inputs.addDropDownCommandInput( + id_, label, adsk.core.DropDownStyles.LabeledIconDropDownStyle + ) + for name, key in choices: + control.listItems.add(name, key == default, str(_RESOURCES / key)) + return control + + +def _listen(event, base, callback): + class Handler(base): + def notify(self, args): + callback(args) + + handler = Handler() + event.add(handler) + return handler + + +class _Dialog: + def __init__(self, command): + self.app = adsk.core.Application.get() + self.sketch = adsk.fusion.Sketch.cast(self.app.activeEditObject) + self.document = None + self.bounds = None + self.file_error = '' + self.preview_error = '' + + command.isExecutedWhenPreEmpted = False + command.okButtonText = 'Insert' + inputs = command.commandInputs + self.browse = inputs.addBoolValueInput('svgFile', 'SVG file', False, '', False) + self.browse.text = 'Choose file…' + self.frame = inputs.addSelectionInput( + 'frame', 'Frame', 'Select a sketch profile or a closed contour' + ) + self.frame.addSelectionFilter('Profiles') + self.frame.addSelectionFilter('SketchCurves') + self.frame.setSelectionLimits(1, 0) + self.frame.tooltip = 'Select a profile, a closed curve, or curves forming one closed contour.' + self.scaling = _icon_list(inputs, 'scale', 'Scale', _MODES, 'fit') + self.anchor = _icon_list(inputs, 'anchor', 'Anchor', _ANCHORS, 'center') + self.anchor.tooltip = 'Align this point on the SVG page with the same point on the frame.' + self.anchor.isVisible = False + self.status = inputs.addTextBoxCommandInput('importStatus', '', '', 2, True) + self.status.isFullWidth = True + self._status('Choose an SVG file.' if self.sketch else 'Edit a sketch to import an SVG.') + self.handlers = [ + _listen(command.inputChanged, adsk.core.InputChangedEventHandler, self._changed), + _listen(command.validateInputs, adsk.core.ValidateInputsEventHandler, self._validate), + _listen(command.executePreview, adsk.core.CommandEventHandler, self._preview), + _listen(command.execute, adsk.core.CommandEventHandler, self._execute), + ] + + def _status(self, message): + if self.status.text != message: + self.status.text = message + + def _choose_file(self): + picker = self.app.userInterface.createFileDialog() + picker.title = 'Insert SVG' + picker.filter = 'Scalable Vector Graphics (*.svg)' + picker.isMultiSelectEnabled = False + if picker.showOpen() != adsk.core.DialogResults.DialogOK: + return False + + filename = picker.filename + self.browse.text = Path(filename).name + self.browse.tooltip = filename + self.document = None + self.file_error = '' + try: + self.document = svg_geometry.read_svg(filename) + except (ValueError, OSError) as exc: + self.file_error = str(exc) + return True + + def _changed(self, args): + changed = args.input.id + if changed not in ('svgFile', 'frame', 'scale', 'anchor'): + return + try: + if changed == 'svgFile': + if not self._choose_file(): + return + elif changed == 'frame': + self.bounds = None + elif changed == 'scale': + self.anchor.isVisible = self._mode() == 'original' + self.preview_error = '' + except Exception as exc: + self.app.log(traceback.format_exc()) + self.preview_error = str(exc) + + def _mode(self): + return _MODES[self.scaling.selectedItem.index][1] + + def _placement(self): + if not self.sketch or not self.sketch.isValid or self.app.activeEditObject != self.sketch: + raise ValueError('Edit a sketch to import an SVG.') + if self.document is None: + raise ValueError(self.file_error or 'Choose an SVG file.') + if self.frame.selectionCount == 0: + raise ValueError('Select a sketch profile or a closed contour for the frame.') + if self.bounds is None: + entities = [self.frame.selection(i).entity for i in range(self.frame.selectionCount)] + self.bounds = fusion_import.frame_bounds(self.sketch, entities) + anchor = _ANCHORS[self.anchor.selectedItem.index][1] + return svg_geometry.placement(self.document, self.bounds, self._mode(), anchor) + + def _validate(self, args): + try: + target = self._placement() + if self.preview_error: + raise ValueError(self.preview_error) + except Exception as exc: + args.areInputsValid = False + self._status(str(exc)) + return + args.areInputsValid = True + self._status(f'SVG {self.document.width_mm:.6g} × {self.document.height_mm:.6g} mm\n' + f'Insert {target.width_mm:.6g} × {target.height_mm:.6g} mm') + + def _preview(self, args): + args.isValidResult = False + try: + target = self._placement() + except (ValueError, RuntimeError) as exc: + self._status(str(exc)) + return + try: + fusion_import.import_svg(self.sketch, self.document, target, self.bounds) + self.preview_error = '' + # Fusion owns the preview transaction and rolls it back on change or Cancel. + args.isValidResult = True + except Exception as exc: + self.app.log(traceback.format_exc()) + self.preview_error = f'Preview failed. {exc}' + self._status(self.preview_error) + + def _execute(self, args): + try: + target = self._placement() + fusion_import.import_svg(self.sketch, self.document, target, self.bounds) + except Exception as exc: + self.app.log(traceback.format_exc()) + args.executeFailed = True + args.executeFailedMessage = f'SVG import failed. {exc}' + + +def attach(command): + """Return the command session. Its owner retains it until command.destroy.""" + return _Dialog(command) diff --git a/InsertTo/fusion_import.py b/InsertTo/fusion_import.py new file mode 100644 index 0000000..e206626 --- /dev/null +++ b/InsertTo/fusion_import.py @@ -0,0 +1,173 @@ +"""Adapter between a selected Fusion sketch frame and an SVG viewport.""" + +from collections import defaultdict +from dataclasses import dataclass +import math +from pathlib import Path +import tempfile + +from . import svg_geometry + + +@dataclass(frozen=True) +class Frame: + bounds: tuple + angle: float = 0.0 + + def __iter__(self): + return iter(self.bounds) + + +def _xy(point): + return point.x, point.y + + +def _rotate(x, y, angle): + c, s = math.cos(angle), math.sin(angle) + return c * x - s * y, s * x + c * y + + +def _rectangle_angle(geometry): + """Choose the rectangle edge closest to sketch +X as its horizontal axis.""" + if len(geometry) != 4 or any(g.objectType != 'adsk::core::Line3D' for g in geometry): + return 0.0 + directions = [] + for line in geometry: + x = line.endPoint.x - line.startPoint.x + y = line.endPoint.y - line.startPoint.y + length = math.hypot(x, y) + if length == 0: + return 0.0 + directions.append((x / length, y / length)) + dx, dy = directions[0] + dots = [abs(x * dx + y * dy) for x, y in directions] + if sum(value < 1e-7 for value in dots) != 2 or sum(1 - value < 1e-7 for value in dots) != 2: + return 0.0 + # Snap the 45-degree tie consistently, regardless of curve order/direction. + right_angle = math.pi / 2 + angle = (math.atan2(dy, dx) + right_angle / 2) % right_angle - right_angle / 2 + if abs(angle + right_angle / 2) < 1e-9: + return right_angle / 2 + return 0.0 if abs(angle) < 1e-12 else angle + + +def _closed_chain(curves): + """Check all selected segments form one cycle, including coincident endpoints.""" + if len(curves) == 1 and curves[0].objectType in ( + 'adsk::fusion::SketchCircle', 'adsk::fusion::SketchEllipse' + ): + return True + # Bucket sketch-space coordinates and merge endpoints within Fusion's point tolerance. + tolerance = 1e-6 # cm + buckets = defaultdict(list) + nodes = [] + neighbours = defaultdict(list) + + def node(point): + x, y = _xy(point) + col, row = math.floor(x / tolerance), math.floor(y / tolerance) + for i in range(col - 1, col + 2): + for j in range(row - 1, row + 2): + for index in buckets.get((i, j), ()): + if math.dist((x, y), nodes[index]) <= tolerance: + return index + index = len(nodes) + nodes.append((x, y)) + buckets[col, row].append(index) + return index + + for curve in curves: + ok, first, last = curve.geometry.evaluator.getEndPoints() + if not ok or first is None or last is None: + return False + a, b = node(first), node(last) + neighbours[a].append(b) + neighbours[b].append(a) + if not nodes or any(len(edges) != 2 for edges in neighbours.values()): + return False + seen = set() + pending = [0] + while pending: + current = pending.pop() + if current not in seen: + seen.add(current) + pending.extend(neighbours[current]) + return len(seen) == len(nodes) + + +def _isolated_profile_loop(sketch, seed): + # Intersecting or coincident sketch edges can define a region even when + # their endpoints do not share SketchPoint objects. + result = None + for profile in sketch.profiles: + for loop in profile.profileLoops: + if loop.isOuter and any(edge.sketchEntity == seed for edge in loop.profileCurves): + if result is not None: + raise ValueError('This edge borders several profiles. Select the shaded frame.') + result = loop + return result + + +def frame_bounds(sketch, entities): + """Return local bounds in mm for a profile or a connected closed contour.""" + import adsk.fusion + + entities = list(entities) + if not entities: + raise ValueError('Select a sketch profile or a closed contour.') + if any(not e.isValid or e.parentSketch != sketch for e in entities): + raise ValueError('Choose a frame in the active sketch.') + profile = adsk.fusion.Profile.cast(entities[0]) + if profile: + if len(entities) != 1: + raise ValueError('Choose one profile, or only curves from one contour.') + outer = next(loop for loop in profile.profileLoops if loop.isOuter) + geometry = [curve.geometry for curve in outer.profileCurves] + boxes = [profile.boundingBox] + else: + curves = [adsk.fusion.SketchCurve.cast(e) for e in entities] + if not all(curves): + raise ValueError('Choose a sketch profile or sketch curves.') + loop = None + if len(curves) == 1 and not _closed_chain(curves): + seed = curves[0] + curves = list(sketch.findConnectedCurves(seed)) + if not _closed_chain(curves): + loop = _isolated_profile_loop(sketch, seed) + if loop is not None: + geometry = [edge.geometry for edge in loop.profileCurves] + boxes = [edge.boundingBox for edge in loop.profileCurves] + else: + if not _closed_chain(curves): + raise ValueError('Choose one closed contour, or select its shaded profile.') + geometry = [curve.geometry for curve in curves] + boxes = [curve.boundingBox for curve in curves] + + angle = _rectangle_angle(geometry) + if angle: + points = [_rotate(*_xy(p), -angle) for g in geometry for p in (g.startPoint, g.endPoint)] + else: + points = [_xy(p) for box in boxes for p in (box.minPoint, box.maxPoint)] + x, y = zip(*points) + bounds = (min(x) * 10, min(y) * 10, max(x) * 10, max(y) * 10) + if bounds[2] <= bounds[0] or bounds[3] <= bounds[1]: + raise ValueError('The selected frame has zero width or height.') + return Frame(bounds, angle) + + +def import_svg(sketch, doc, target, frame): + """Create editable native geometry using the same operation for preview and commit.""" + svg = svg_geometry.normalized_svg(doc, target, rotation=frame.angle) + x0, y0 = target.left_mm, target.bottom_mm + corners = [_rotate(x, y, frame.angle) + for x in (x0, x0 + target.width_mm) + for y in (y0, y0 + target.height_mm)] + # Fusion inserts at the SVG viewport's upper-left corner, in sketch cm. + left_cm = min(x for x, _ in corners) / 10 + top_cm = max(y for _, y in corners) / 10 + with tempfile.TemporaryDirectory(prefix='insertto-') as directory: + path = Path(directory) / 'drawing.svg' + path.write_text(svg, encoding='utf-8') + before = sketch.sketchCurves.count + if not sketch.importSVG(str(path), left_cm, top_cm, 1.0) or sketch.sketchCurves.count <= before: + raise ValueError('Fusion found no importable sketch curves in the SVG.') diff --git a/InsertTo/resources/bottom-center/16x16.png b/InsertTo/resources/bottom-center/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..489a1f7e732bc0872ada05a956f8b8e3c1e2761f GIT binary patch literal 536 zcmV+z0_XjSP)?n3?hO%YI(6 zeOE`vGZ6SjELcE{Y-+7p2m#I7$UYB=t`O0xQi`qAEzCiGXKlV-uMfsqe)#y=Zk))i z)G1)e;*H6Q=LIFl;dZw>auBpyTqu_jI1XcZ%cijcL?q)l_FXsr-CE+UU>;&>d5bay z5@5BsC{0lAcHz2i()oA+h89XG!OUjXW{m(qxW1p7jDbjziDGARBCOSF8bG1h3uoU4 zhfe?$ji70bh=*ewoF}3|zSE1R=Db(?^Pf6TA8qX2KI#wX!Ocr|KD=w*^OruxL?}oh zPMuiHqnNdrII`$?#b&BUuyYGL2Uj=NHwVN5-Z{IN&xNmHzka4lqA+vM a9R33GG3BV|SlRIa0000f_gA)1<-!$e=7NB@Zkq*5u7PN(HdL&qO7!;!tV zWjRdXb)GJbP&i;)*7>*k4}1!MnHh~LdgEeAfzbcvT~TJ7G>lL@9FC9>VqN}~C&#u) z0@Ob;{xCD=Q-DY_%ccaDz|iD-x+EjIP%Ky=Z-v3;<2udcdMjfl=2u2XyNvmrrFcBbGcyZo zjsVe|AnKMio(`&&6oP#dP(U!~rqjJ{vjl2|m1I6LJl@hq&~1j;B0yVDaGRm8*HC@S zh9s7LzUYPt0MM9OwO6mn-oKlK0EBXs&m#a}H-KIMF}1fGmCcPnT?j3i$!LSQ9FOJm zsv0^)+wCJEkDi^aB&r_h{yWUsIxx!2uVu4YJ(tVTjd+}snGDm_QcF^LE1_yz2S4wnB>3KpZ%{3C}C=ykp6g1nSCNob8O;ELFQ>?q2&KD|_yLg2{(TMIz zxj1!%O+yq43u1Em2KAVck3*4miblgEr6k8u0TAS_B?8P0)x`z}50wT+j=$i#^=F(~ z&0!%lt7=1syWN&}V0qa2`$hn%Ny?T)L4m84a_N!=ho$Fvx)IXtn)Q86uYA4SQCIyG zCLaLMaoMW>vg^a_wrleRj+ll}Gmqm*a_WwA_W8#HySmI?W?u6wt=~$JOlGtlJCYz8 zTwEuTNu8OCmW$z2`}e%w`|f9QzVwHyu1-SGNBj2%9_%o_P|nB3#sV`l2fY>BsYHS| zV=QM?11JSy1IK>)tz3WS=bL!r$LlyVTZRivUM!clt1$bi2ke){%47r}K}1gwQGkff zG4tt0x!-fiCy9SlP`@|d6cVZ&=doClwe_C!Cw+;_A#)w+hyVZp07*qoM6N<$g4y%b AxBvhE literal 0 HcmV?d00001 diff --git a/InsertTo/resources/bottom-left/16x16.png b/InsertTo/resources/bottom-left/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..8bf4cbf3e92760c870967bcbac355605dc19efd1 GIT binary patch literal 559 zcmV+~0?_@5P)u*=?NHcYy6Nbc`WCt*W5Dcwb87WVf#?O3>`V0Wf%vf!F z+$q^Sp~KB_2z((HEFfZ!W^vE=O2{I<&A!nFHYQT zs-DmSw^BJl+D} zI1U4l3&F}*b+Nwp)99(AyO?MCO}ubps*?b?Tq^0~qhnV})eo0u=a+F-r>0-OX`a0K z@NpxX9^#N$Yo%C7iRdICCx!UU#MqHGX=b@KGX0_&lHSDRLOpdz?Y?giqUU0v6{2!z z1yjZ!so4qF-bc-jp`uiiZkzHf~D6n2pK1CudmPvM`QupiV{@G^JteW?Hd002ovPDHLkV1h>$2ulC} literal 0 HcmV?d00001 diff --git a/InsertTo/resources/bottom-left/32x32.png b/InsertTo/resources/bottom-left/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..d78904137e603e8d1eed1c35a57ba505306ce25a GIT binary patch literal 931 zcmV;U16=%xP)jI)!QK({|ASE9KMbs)9G1{0(GBbHsUXo%eF{ag^V$aX;wz=n>d*;ps7{>n& z{LzBf>t#??#h~LCBUAwdf!zY(0Exc9FxmB(Ccw0^tzfE>z87 zi|cy#!TPnAi3kyqGPm%|L23g~{ekf=M7pM`TA9P)1jg8q;>$>8JPv{g>YG~TBBI|* z#C(V%D}fY{6mfzJP+j3qA)O%6h=lPJcN)Mx7c%zOY0lzF3|NVr545!nP?KjpT&f5P z6B1D3@V0e(;1{r?v1LBze6nd;X0~;n>o5Z1&Z9?1sUN0&E-Q24n>XRS6#xh_fH5M5 z&+T#~7{fsmkRZF=^7*Q*YzE4Oelu@xY{_|s!5;=2CIG`J_#0C&qPUnblvQA8zktDj ze>axZlVL@LzG3wiQW(RLIp(<}JY^6}(b))15Ph5BT9 ze{jZ-9>0D)YL44|DDd&iN>}9!`$U%}bb4|9W5lRO#IELMzwOSQ=K_}h{KaoWA-24= z72(zAoO$FjxRid+rEc3yx4ZpfZ`iZ`!fgl}CNM;{scP1ueV&TDQKDHzh%b_-+VZ+w zvIE-QblS{GprZqn>S~m=zV62RsAtvbYlfoPZJK6BBETazJB?yh9l34lxFehQpKK~| zXo_K2d9+v3HznQ}-qK1i#F%oINCm)EAAi}s|3L~aJ2={$4dGa=S z{27S^S2Z4w>0L1%d6YK#0QKuyU>^)HC+j?Z*~y1;9*zXUYVAWyL}$VX*K(L&L+Gni{3O zy?szEcA&BnbGGG_Dm3uHFy=*wy05+p(Y~&ibnaP@dSm9hsAa9m+*c4#T8U=AU&>!c zL|!7=OhjV~9vr@r$Qq=TNGW*m3=+~8+)pHx=r2?S!&j1Ao+vv{?i2t3002ovPDHLk FV1mHIzWD$E literal 0 HcmV?d00001 diff --git a/InsertTo/resources/bottom-right/16x16.png b/InsertTo/resources/bottom-right/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..38f537639e2c062c9daa1f1209bc3e6b9a7a0954 GIT binary patch literal 555 zcmV+`0@VG9P)@To*l7end3VIbU0YNWi$*GrsNW4@;^c39HgNGah zk0RnnwMv2n3Tpf!{YtS($R_(fvMZ4!Z3?9W!!W!v&ph+IL$pWZ{=~8zl}whfQ$x9& zV%JS;BHFQT*9_Qp9J5v3m{;c5WY_bEd5|5z5D|vfzxOM3Ih(ms5BdxM%*@#Qx)N1v z&S1XH0uENL4)Wx5q+?2n~i}f%(d2+#X>%xZ;zsUBX{qc-FxSWD!Op#9!7%{!e=2hhYqet1C)V6j?DJpAR2udUU+ zm#Z68jOcS`C*sj9O#g|4fN$uIgHSL4shcm#`oQfXPCkBzN1wkx1E98Sx}Ewx#akUr t7b-uB&wtkE0VGEKR!}_b|3QWe{{q0^@QkIx6V3nt002ovPDHLkV1jg@03QGV literal 0 HcmV?d00001 diff --git a/InsertTo/resources/bottom-right/32x32.png b/InsertTo/resources/bottom-right/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..6d1f5ed0f754b1a88de9898fdccd574fefd8b9b6 GIT binary patch literal 962 zcmV;z13mnSP)QqCjCjkKz#_}Ph)MNw6t1q1A)Hy^B@~Vi4O&<6x)iL#)sOw_n{A# zq0tRWDLb)y3xXI1^og%bZ&wcy1damJA|hBFef1szBoM3n3w@SIQGMK{$wnZk0PNVBZKe@x8HR(~}HXO8p-x z6c(r{>JDDZB~=IsC>;2B?-6(i^bh7<5JEiV`+;AtUo;wwfcVMDlk1{)pPg)P*YWo4 z%90fTuoytAbZ|^lUy?C=U;+xHX@O~W1@#V4Bg`M>LxZ`7V;KC)V5>nl2+1aToF`scfvKtc%fVdHn)UxvUtJWBtzQSP?%KQw z5w9wLA|i%!h9vGcna3E<BNY*r4J%WIx#ZXUQ^ws(x(t4Ppe zIhW{lYuf8a#B1{;unu$T9~x?w6@E+ES^UFWEhd_O+2@jg2#%D$d^29z@!r>$pyCC< z5a>X9D<0kX#Ke>X+uC92!SDSs6&`-~ z&2%Y|9jxz(i-UHNW;VsC{tcpoAl<~Df)3B_&Co$msnw+jd4o{3 zt8Wk-lv30@6dR-#nwUT++Mn?9-u>jJDv4=R#k<^lIOqG$cYZF>e;#f$1_!g!vT|q# z@O_(I_mn20wsHTYfX!oUdU|`|L*Xtf)f)x@F*mCN7(xh!*2S2V7e=mJTryY%)Rl1m z)!VxcCpu5=(6~m#6$l~$QFm&sSqK5m+R#2)A?hZgS;ui$889>0uK4ssPx74Sd260W?|Fq?#?A25wLI+JfwBqTGf)x!8{ zwQ7pNw`xE^i1^=5K`qxpzI>$TRz-`++4;rYrw?_$>D?Q9n9XKo*>&MKj_`e-Ez5%M zy4*qlz%=nWD#hcEzgC}}J)ruTd1bSVH!=^xCITXY1BkBl(855U-SN_&J2pHzUNO!{ z%Jnfu5eq3{ZUPcgh~G;1rvh^BO~tCqKv?GAg-7+d3{4w8-ueEIM1+V)bEojRjlu+=&SUifL^|v7s4IOwKQPA1vM()J zh5>>II{Ttq5%Efxi1i?fc?lGNq==JTfG3ciN@)akFA^FB?(_)zVwf|3m+G%t$AB%7 z{Uh=CBWm*b7QeV*1>G6_3lYFReq?VqECOA<(e0e`^_G>l<{RgawIykWjg9)jJs*?8 z7=}-uUbeKhHm!~=7q@SxOI83N$pGp^4oBUxB^bk^1gPL3&e=?+Qk&0T_?@S9Gk@T{ zgBgHZ1`#QUSaK*mbmpVI(W0c;L*tAgT^=8Q!6q8KC-}uc(yE{#j+yUz@}Hm_Rs(+?Brmi^zKhqP${Lu4NWx4iLX%i3S>>H1ax7& z&@p)JhCoEc!xgjz$+H1g<#k0b{XrAyTpIyY&mKj^NHBo7^C1Mdbkjnabfj$w=Ygl9DcKy$7Ud{(A9e)4Fgji5QW;<&iz`*`5zU`IWSCcm$#A3tlNFpIZu~^CS z-$|vIGkOqL78XWXQCQLI_$agl)_9B@vLQnF7!Q;PzGpyoh*ifkIXiEK3T& zK!(r15u4^P)1p84+sh#yd)r=>|sFC_tM}+qR_7Tse2TCL%~g z7XVpZsP-#ZCruDu6qXu+!NP5s#uzZOv_w=G1QYY$>bpc_rBo_WBE|wNHRj(uE|<&x z-y}~wnY=!-d&gD)#&um410a!v+IMiE;JQosTn?4xWhoF*tyW{(w&~@^>b-}v?}ryt z15cYGb{d$B0}zqYT6@K!UT@76Q2@eG+dgq??(^ugSCtlJ`?ssmzbzs&+{@(`KaFl` z>Z^x3iiCWh8lg@{e2EQX5yOt-u;+Pj97pbYURy64o?r=7DVP_^aEh3EdUN7BvFv#%V65*66^F=X3 z8`T-3Zor}>eUE$&{ON_S^`j%>m**%NBhYRUhSPNx|FvaVcfv3fF$5;vre-9`5J?}H zDV1J4GL)@e1x%a#PY*hZHraF_`lCo~H`6x&_R8C=pchC?!4D1->d3AUhHU@<002ov JPDHLkV1h3?{MP^g literal 0 HcmV?d00001 diff --git a/InsertTo/resources/center-right/32x32.png b/InsertTo/resources/center-right/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..c395bdbbffc4db7b2d404cb2433a2d3affe1aa02 GIT binary patch literal 1038 zcmV+p1o8WcP)apKf=Z-wv0 ztYtX}geCr67@i6(Ygv=;cOUwah!7DeKSa%6ECc{`A72wdq!GjL)KygYfH77QzhrW< zSrA0f-8a;Nh~p6=7DW^V1uOtb5ud06j6f=R+all}B4KtxJ1tRvKjg(9^!WUn7_gvx zKNXKJ$);Lx^D0G9ijaW#i8l`)gB9Rt-*CIGX`9Km3Yt*8-)02FqXPrg#;xYry1D?~ zxREM40|3|59Xs0T>nrCq%w*x0Yrm)E5r2C5GK&N7q6A2guDj7_*eztB<**p*%IA}x zk0`4jsfGhPw?2u8m!vI-h~c6S7?c^3oH0g|$>b_dG#uLVY^%1uLBQ(AhO$JX(|5Al zB)JqJrwd(*w-!)rKx!rQhb#`w1Wz4u{>cdq6^v(9*Uey#SK?o-#ymxImi=nfV+y zD>HYl$oLhO*tdBt@{BDQLr@ulrYIopq-hXF!U`WkD95!SV5J8yt4wfaz;lU+eiuH`MpM zh%@|99kCevqkzgJKso@r z*B|gA;yHPhN`>P%x!a!WOa-9kFQh^_lJ)k!KHJlG>J`_uyPQnM0mKqVA`+_MQL`Cq zBBRbN@HUO0rakzWU8qNAK0<{A>iM}-{x$y>67dMa{vGU07*qo IM6N<$f_EwLUjP6A literal 0 HcmV?d00001 diff --git a/InsertTo/resources/center/16x16.png b/InsertTo/resources/center/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..df2fc1d0bb379e246823dc4a8dfacf0aff8a4805 GIT binary patch literal 561 zcmV-10?z%3P)DgKoahyoLuP3L7Qf9WYw?lw!0PxcDJk+gr1aUT7pT6h& ze%!o^WC6fI#QHDH=!F|oriDXo4-(PImchI|zF!QFjXr%dcl1$ZzWjM%%sTagz!eY| zx(N^>-hFsK6p_tWUc9?>{&6LD{Ygb%tEz|k-TcjK_fQL$dp+kSuQ({b1g{{VUy6F{_SLK2@5A|*ip?zno8sFqa_uKMQICU zHHQ_=&P_);%sfE3?{3)GM~00000NkvXXu0mjfDfsu0 literal 0 HcmV?d00001 diff --git a/InsertTo/resources/center/32x32.png b/InsertTo/resources/center/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..fa32cf367849f98463205c765855059a1b8662f6 GIT binary patch literal 1021 zcmV@NC+3ikdGBfX&x4Q{x-K?`oz>57~80Nk2 zz5jdv`{sWS;5Pp6!1X#z(_}C(z@WIv2m=7q^Ydg64udGq3Ma3=QtPN9Xj#_5g{VdT8gsvqfP)C8rf|i($|`%CliSdV2o`jzKrC1 z9ta{B8p}U~h!Z9e%OQ%U0_s5G;sZs1W>gkR4na7IgkD`c-Jre|*6^RzJ399;U|q6( z+O}`VrqXn9Hy2bPB%tub8!sM%O<;I5->)djUf&P=X8lU5!3cl zTd8GW|NeXU!BcMqVB4$CK2<2_=Pq9kcg^l;WNDrO^avMcRQV+s!?p!Tkg5i`Tsl}W z5D_s%3??Qhma?E905||lA>!OxldYKf=xDy>wkgmC8o|Ya7YqUu$9|Zr_AZ445A2A~ zEfb9+;yaSV7+W>jKY>Lh76G^nUiSS%zREv)`pfgZkLJG#AOHAtnEvGK&YyjFdnu$b z$q_>EEf+8V@^7L}Cxqjf&(G1>3p0VPsXQK6`OLLN@yLf?1;3QtSBR(&5yNEiNxo$Q z5am<*cT<5Cn<1#!96MeE&yT20bLl>`r$@nwvp;P~EV}_7X{f z;P`ESP&tDbW8jAb#5p~@YrEvsj<22Nve?oL zOioTJhVufN@H(&=S8Pkp*mD09Z0WjdvPxL_EFDK^6(VFB8Dv z=JYfbfOYe*Z1&Z~;jxo12f^|)zU%scxWOwC2}RQt&vkxsmFoG1L2s?gDX!O%$yj{f rz6=3mHyvcUw-;~OYx!-!zm2~DG7Gw4MG>_800000NkvXXu0mjf8ByfQ literal 0 HcmV?d00001 diff --git a/InsertTo/resources/fit/16x16.png b/InsertTo/resources/fit/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..74d57c168f7aaaa2f5dac6bb2b010d0ecf155b08 GIT binary patch literal 478 zcmV<40U`d0P)@EpoBMIjjNCOVS+X}OzQu4Dm}lM@<`4ih8Vv>(7}&+#w18Htqgz|AJsv75 z!s@5bFH9J{O@5~VAp9p?B9&-tT=OLTvi@#m+ZHMBrC#;<_Zsr1gIH!$W{p|YCoY>m zgz5e0-aSHM)m%kB?H)UUNe{EW}>;nn$nHVCZm zIOqirOfnuQ``23#$|Tk{C!u-y2>w?UmShOP3gsYV6UY0;5Ch@At(*f4K~=>}Oj&!` zb2oq|aMAO)^S-I!p6AFEn;z-cDTCqXlJ3(P&fe$%V1UXZ#cr89Cz)XrdKr00VwD*r z9jzp7=){c!CEe(msD9}6CA^r@ODEBMqvAVX0h;f( U_08r+cK`qY07*qoM6N<$f(m)qQUCw| literal 0 HcmV?d00001 diff --git a/InsertTo/resources/fit/32x32.png b/InsertTo/resources/fit/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..43d6de9a6bd1605256da88b943221379706d0b06 GIT binary patch literal 905 zcmV;419tq0P)Ovw|WbF^k|y6Aw8}E+RS_@SvDQ zgdB3&ISUdrkyX#hN%!K_uQ6F>H=Et=uBs>1-IMHQXCN7BbI=EmS6xN(e($5+djAAJl)$a(h3=jk4Lg;o7W{|Tmv(4!zPWNyA^NP3mkAnww6#{@23oGRusVkqJ zd9#B(pm#2OeOQ3E3QPmN7%W(MCviiJH@!#>4#cXG&tt>O9dXrzg~^?^S&FNuos>@Z zF(pMJ*btTzgsqT#V6xd)t%agpw*Yt&Ij^J!%WCSFj%&x9k6M|DK`3$-zhws3O@O12;A?H>g!Awd#H&ZckJH2n$tCK$Ij$GZ*n zI?(U?45%kMx(-5vs_Qruz&#?6MIYy0TSW-^=qm#>hL&F*^^brwe380#t(4<27gA3} zqxA4d)GPwuGCl=B*=1kcmR)xc;tzr(v34SY8bf0Ix*OCfZkC%9-KC|%71+! z5}AZhDn!Ezkp&Qo1L;UhT=U(jSq%kY$XOsWNRVMDfIktrrxK01^|hN4vkj);Nj8FA_wY?tzE3rCGaDw{ZE}wn9`PIOsU zwTYKan)-lH$V%6CRLfGp%c_mU8^L<+dM1mc+*2F^tB#i}Zf|NR1C05-QsUE69XxT1yQ y96_NFj!Y!Z4Gz)k|5HCRS?9ws8eO2U&c6YFy2A~xTRX}C00001^i)U>4J`yp$sxgooI;P0ddj85rniu|Id60-*iJ|ZC5?Ry z!LWkf3O%I66bgmjdT7&9dMU)Ts-?)bywdK@yfQ00cI-5g?R7)Q2g~lvzMc2Yyf@#Q z1zva1&UV@J#9=!0%4I`DJP4UX12aGMr8c?h~Z^w&d$;#vESDB(rn-m0&ywjLXf&P`vLc;vb+samZjDwT?! zn)&k7$Vl<*O0)TZz~2ER05VDVHeew@Mk9KoP&_u#TK?xFJLjdbF|`o_KuEztN&}*A zrl&65z#-tujXUoGxD<2RfZA@r%z~KnuKUpT+bfYoXcT=}Y-Dvu{9f1@SGC)mOttz! zR3H0jPl_v(c|{w|eh&jfyYt6<-SsUSVUqorA1Uj^mzgLns`5S-0} zm;KWKKCCa+|C6@rHx@IEz;8$J*8(uDgYaA#eFlbeFggt&W}F>s^8N`35s;J$peLaY z-vdkw!^1$Uwc9u~N(h$Ok?F4}lN;x5C+Ii6>N}e)-DY&62C5fV`hGK03pbUvpQ*r0 zhU#mvRXPb7Rm5laWxo)B$*~I-Z{dRyAY)R{+6q$6klvN^T`X06w6ILDp! z2+XO26Ci%V*&_;U6qJ+0Ac#UBn+H1nnr-@z3wzgrcYbX~KL7|)-Fell>sW}|?ZJge zYfXw4Y^yY0GN|s6!13cJdhxq_aU}w7;Q%;RukT+6kU%kdk%fAWLs9lT*;w+Wtztke z?%W@Nw+WtS$=k7jKbyM(s5T#jh|f$6kYB4*Y}wpZIuC$&tf|@gI4PO8CZskWjFwLC ze8_KJyE%78Xh#|uCPRXy0BOSpCz%bCq^EmWmCI#gL^hMX5Ouqvw;IVQH8XQ6lNLd@{r$|RpL`qF z7}cjyxRB|Wz=@b-1bmr00000NkvXX Hu0mjf4Oqg4 literal 0 HcmV?d00001 diff --git a/InsertTo/resources/smart-insert/16x16.png b/InsertTo/resources/smart-insert/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..8b2a1e3eda7394ef75f234cc14ba0919e5d8ad4b GIT binary patch literal 583 zcmV-N0=WH&P)T%x)HaUW~B=S3q_EMO;8YqY!s75rMNIeD7a9F z3ApRB2)a`cL4+z4p%{g>Dkoy+g`niOEUvcLhWYz=mlG zpNt6pe=6nfu7jDTitlx1CcRKSp%q@I6|Cp0Z}oho=AV?SOv`-vEC;zh`9M?hm9!W; zmh)Cu?h@e~gT}z#LveWg3IAMuYG;zufA|F4d0aX)vM+Xi&1$}zpSk)~&sFCTjom_h zqpjp&G;Wa9c-a}ZFW*?P5(ne4(`{>Q@&3%UU%n}h>m4`3k%f@!OsKV+xj2i)#vJyK zjvx{@b$yyZ@N({fZzkHB{PZiFPXve`3gyyUXT!w zs8tW3Xid3r$FwIt1Y9T=R1R>cL@JUrcGmWOJTz-Naf}@j*C60YyI$|S_nY6mubCx` zE(GT8lfHHS{Kteww!Bfb;MZ+z1IX?Mc&$(y1x6g(!mTR(V{UA`Zbb5)VMq6jI(^(8 z<749~j3`VnLwnkgwH?jfpLi#8`A%u zfaA#{$NCt$>PUdPzRMIP&-b%*WZkh4;3V5)xl}n5)qc2xAAgRA>OS_ZMCo*}r&}&- zT}_xr3xUf5L~Ja6@`}uysH*If@1s(P;JO0n>v~$ZbUHAuc(2OrRMp5l@g7`P!R13e zCWel9oqAOsi>N;xLwslwI*unRl|uB!wbgT`l|C1TA%dXw z{nCZvg=EYD!ot}(wR{USF{w$kAmvHKI@uWzGKVM#VPy_X{+wG?w~4~}mDLr)FrOAm zq1D*Exp=;Kvpc8I1ZHNY6HhSnF4KZwzl#14IoQU@$qJC+}}=3di&ItEEx_ z@_GE`y6VnF=X$~mz_V^uoyu1@=^q{G+VU@3L#s^z;IMH5SLQ#@3#QhZ2ZmR)Q#sq977NJY^Wh=NN;8 zL4Yu7wNk=T0NX!K1t7lDuk!hg#M_i8Feko0e{F5b z6mpq}UX0^NFh9bFOYi&)mWC0Bt;V}c^QE`-p3@CC4KjH1$_F_sWhP_IhW|(;QkKol zhDl7d`0Az7_FtS2I4M2+O)?0Z2J>i#WSr9ediWQ9LH_}xH{yJUzZJg#0000*Z2be42ZvyDrKxPSu@r2V)M8=jm4c1wu1H~ZwO4CnrwATb zgs2I5?(U4t##{5wGjRC9+gWC3zWH`$9sxj-B>V%P8UKOB%ir4VwsU+GWRJarZ>#-U zWBb8-Vx9P)N?|0a8Bu6lpQ8o;aJs*{)pO?jC2r^J)6(WZ?h*0qKT#1>>kWJvkCzFU z5O`ug7!9+LPuHM&0~H3b1esAp$a6)c^HJZQ4~d`5?I!9#k-f9K!tU4GnG%xIYBW!d z0WJwjWIjfc*athIf|V7*#f73-iIHWc+XX=;yVDUQ2?{$6Yihf#IP3}VO2GIa_)Vj% zlF2nYeQe}r=PJQ?T|gjd`ZDi-ZCJ4fIQpKxAyAO0B1c9|9QOJU&){0v1FJkv6_0sC zK{<%>lAx**SL<=)M#G={G$dmLWs{13;LT?$NGi>RN^NjmF9}+dove@VS_Afupb|os|=Ec7il3qHb)Q?X1tGSX+@4*=T5OG8=>qO*tqPHUFT;2M5=%)J^pI|0000< KMNUMnLSTYaDb!Q| literal 0 HcmV?d00001 diff --git a/InsertTo/resources/stretch/32x32.png b/InsertTo/resources/stretch/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..5dc24fcb11e93c02bc6bd5acd499d7950dd53970 GIT binary patch literal 698 zcmV;r0!96aP)FPoXg(O;?t{nscHVn4-va+T=;!w+Nw}X0lPGdT zB)>zZZxE4AF5Pw!KyqbisdOp}E)F%D%Jd;Il?Lhc*2fn_l(s)uXphacTla^<(O~uS zP&l=b87Lx1uMz`r0+bbFB5S-gyV>lWo0r$(I3``M*SS`!+1qy)FQh}^)Z#Xo3h7t!5mQuhV&qEH;9(%C@ZZ)w> z;15RR{C7>L_Z}RxD8Oelq62oV*1RY@hlPTIEtKC8fkj~42r)kZq@weF`v$$AGzpmf zmOZue(KGY{ajbRaT!sVYPj`zE(iJ3$0^nD%9hjIPq^aOdHU>Gkj=F0wS%+H9B1w?j zBJdODKYC%scFV*#V(>8m9GBpT!N&yf*OtI}K_HYLr`{G>{wnl#phSO6fFLG6MrUTe z+G5M))_lsk<mQVWo=7AY;4XPy}HJY;O9yJ_P^bGE%I>d3{Erym%myhgt_2 z8kV4gV#;W{(T){nkx>R2N2I+D+()1xP7f+35oEi$6r$n05_AZ$+==y?7Y2^AGDKM* z=n#ma$obp<9WTEeZ|=OG8yi2F8kdWJo{CaHmkIi;-NBZl$KF3%t-73IzVk$K{oeBF z6G0G>X(?;H???Gm6uyBNaC)H38_mX(g&S8Nb+p1!{Ft;ybl((69LEey_wR6;241D9 g)QO5IEc}c30`a0GQBPGF^#A|>07*qoM6N<$f?x|kt^fc4 literal 0 HcmV?d00001 diff --git a/InsertTo/resources/svg/16x16.png b/InsertTo/resources/svg/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..cdbefe9c4ed476a83b4b722baf523f0090c875b3 GIT binary patch literal 616 zcmV-u0+;=XP)XWz?b{WOZfAc_d0kU|?9MTkOLc@NWwAtWHi%6wJ??`{?1y2wV2#srL| zZ$&!`n-q$b76t@AjhHQrA!6K3_V?}`d8>gKjaccxz;N%KIWza10se?QC-+6M`8Ua)7Z^mO0I0$AMAx<*yRW~0_j(-QGbX?UnWXy5REi_8 zRk;)df$)7_oy%t9u4=qwGP66MKblYr&odyVby0)B$oYPRih+@d4j9x6AeXLfeS{`^ z7nYY?n6+0Xu0Gso!`T83<*>uFYN5xm@CGy)rv7>)1U*Tm5cX##PiUr2hR&t?d+tH9AoL>Cx>ZywfN24! zifE(;(b#Npr2?vyck;M=ktl2*4mGSf7JYXIyFY#(hZM_fT(}M0Tw3}-tfd0IBy%Kp zAatB|C#;?>8&=C9Re0OR)zPv3uBrMj{-Dsfa{n+{u~A_=`&DuAxEk~xuiPV(zS;e$ zA%1JBWY5jH8(L5*&f8kQ0rac}HA09sif?X3sko#|#ZxNL`2aGok@RW;Qi@r!9Tz+^ zBt9QBmJ6OE#0(SdWnr8oVYGw97cMR)YlVe9_2fuUDZdJ$)s(L>Ic;L{X)`j<+%^2x z)%c4{BS+*>b;&<3N^~9-{LKQbE2O$YR~r07tKR_NX8efRinCq-0000 CCm90( literal 0 HcmV?d00001 diff --git a/InsertTo/resources/svg/32x32.png b/InsertTo/resources/svg/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..c86d5eefa49f8f4934def0959c04bb0d290cc004 GIT binary patch literal 1399 zcmV--1&I2IP)FpiK;;z@LwrHoecjg_Gk5J%@D(cl;3Ru@Gk4~E-*@Jl zGYedcYw;fjGtWp!fNC2sAd&|dn%4HphPU23=!fK~`gBKH zS0j~5i3un0@{Ui#mPLw~mXu8@Ut|}HiD+4(u3>A(0?V>gCX+GbL;!1r$<9vkc5;zj z+t@Z$O1WIIf*FZQ$FUVW>euu7`ug~a6VR%N$OqtW-0{JaB;{_;agGmMywDnnMCSOO zy)(VOrcZByu7bSMs*}m2zc!V=K2mu@yCLNhzURK)eBsP%uq|xed#qTdWOu#Lu6~_x8z#rZ=$n|?D7JLvG!jJ^Y>35|H2xEr`g&#mzlVZS(Lgfax0N8-0 z!EPv&smWn^^JDTy|jI*7}+wLE~wHuq^UQ#KA~^7zgtV_`b#xV7LGg zSkVXpMjm!S!L>^a?SdqtVvwZi@UUtPzJANQw;GAE_lb-Jp6ApzuUg(VOpeI2hP>9< zDZtfAZj0Ul5xEI&Q9%d+88Q)#f%Air5dy>-Rx_fKFG(;fLzn)RRF_s=9HqLI+3)rS z`fqP;eDRcSwLnuqZmfx6AW1&n%)Eq{6!3%xr3!HEZWQwdgHMbQ(BHwf2nkkooClooqwUVeMV&@wp);x@4I&0mRFwJKC&e=8kmsD2=q-MSXGYEoLNYb=(8wf zZIn$mk?Y^&)>k);=1GAG(;w|aBvwU*9Q(qk5Uf~)O>%7eSd}R3dnoL$@PzSoHlJVF zx~}Hroc5j&(2L%Riqh%PfHQw$B$I*Zf}E`%KMyHe;khx$PzauT+V#A9QJ9j$%m*3O zP`bjUv;R(}4CbUTROR55{_j`+5-!_JPEiTN2t{KtOe+kWJW+5S!^Wk@^@8CeF+NgV z(x@1y5{m0#$c1o<3WgLQy1-8EVXxtto}lN9I`%aD0MO97t2u6(PaiG%Hy)7JNk@Y@ zw(T3z3RrMpjkylsdkUejK-dIq`w$f`);b%OeS0bJzgi;i7X5z`bZ7B}WQKknT> zc=JJ+*+#`kQY1bjQ09B3j|LnjAOIl&GXgla0CP7A`Q2{a;yuCp%YYA8f9Pslo9BJ=tei)fQ3a)DF{|5%L;^}N3_+~ac>?{*>BB65sgJ)yNvSbK>WMGF>@}r?ysUclQB}vLi^$m zMDI(n>002ovPDHLk FV1g@&tyus7 literal 0 HcmV?d00001 diff --git a/InsertTo/resources/top-center/16x16.png b/InsertTo/resources/top-center/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..d47c7a48e97dcfc6b531d9afd3bfd66b42fa4f01 GIT binary patch literal 553 zcmV+^0@nSBP)6o5wXCj(WB0#!bWZGeXYK8hqdCcxLBDOUo&}@nT?szSo~g; zY@bQAp3qTLKRHyq`E2O$aAPB)(+38A?pfQs#!NAQ2O*OgXRCKS3S8v^qdkFLsC@SvS?TlT%GyOvf!HJe>2RcbuNC|Tj z;2P|&0B^l}*24KE5WTT&`(CTn0yMFpBqbR-bOKunhSp!>&2ZVo%jI(C2iba9sikep rF~wm%T04@Z<$>LJ-4gyMlIh?#CkoeDH7cSe00000NkvXXu0mjfwR-`} literal 0 HcmV?d00001 diff --git a/InsertTo/resources/top-center/32x32.png b/InsertTo/resources/top-center/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..334fc05bd1b49f4f14924c7975367c24c4699524 GIT binary patch literal 1003 zcmVbg9s^zY%+9$h~m_)eh`}|f`8Vk z6a`uQ=$CYeigZJTL_ZA0f}pdAx-r+O)YK(u(wF!0-n&O`mOv&=%^&)$zc25dcg{WM zch0@{oQKdRhzJ3IRYi%2)UL0VK}5WnZ<_)ls${*eKt3Y6n~3fqqV086+5F%++a1q2 z-kGnKSLxKBdHTInUM>^8ShHz`2sTnoO-(Tv8DWsVEDsG`$M^5=E3Z1vgSHSS9y)Ov zzWn8a2L!NlTQ~pY(J|P?;jJLYXWyBh*Die<^ePKS02VVDnj0VYS|YF>e1gLtMeEn` z&%V1Q{li%=5Dp1MfRa^~JzXL1>qqWogWZ8XL_7ygLadj0JRXzP1E5F zdBL>g*j>AC`Y~(nO8?)kPu)=%>y#K_@v+1627jr$=)dC@( zZJKA^m^l2A+M55~7Ev!;HUOG<{RRV(KGn3qwV{v>oOAG(Y;c($igsBQ?#jv$0W!{V z#Wga6`re+%)qA@Q9i)`t*fvNan3zf2iHHkRL@bUd8&&`SiOctd1kEVqvL=Byjl^xo zb8u;iiLu*nJ92%bN58m|MLno7A^^veKnUKRn|JU_=g-dO|H&+SW`Pq)weJT4dRHF< z7FOOD=jN^;FV@=^>gAFOgaqUrd;am4>UE||<&%f@y*m2t$8sfKbSuSR3_d(`pBUO6 z{#@U2$J6!plhcV|A;hhY<2p^9fqEbyzA!txO$qdBG4hk{~44S%A_P) z&ubGw6n<|eYgbgv7Nckn5l@=+$FWpAc<>^4)~g~S;>jOW{DG6bd8m4kf~7*iUd;Xj z9>fYlX+2aa?m{c|5D-g>SY4w@lbugy6GIyl&374Q=DqKI^Sw7j9RPr-M{qM(E`F38}@-OSfF)3YBo*)~J#q!PdoLYV#XW+~5lSI(`P{8Y47r=fuz zFNTinzc4!=>N9SZ_c_v=(NvU79JAC~YZgL4vu0wNC==}^qIXIuPSv$G9$d4nRAsTB z&Yw6ia5?L2pXes}#>jXvUbjy*eBg+PhVMKWKbbvx=$TRwbo`YFS5^}Fr6Ay)u8UG8 z!7j}`2Lf67lN$>s;0MWvj?v~ z9Qz`L;8@EqoUw&TRn>RoA$Q?%s;iY+|NxEo080OBo zGjqQA<~!$JfC3;QMnv2o;;@+@B2zx}_a&?ZGQ{sx=H2UMyh1Ra&5m<0s z$q?bQ_7?V4>z;JRwh#O?G&EgZ-G)DE^yZbN z+Q7Ys)VaGx|9W6}I+dQcIp?UPTlMV-GFnom<+ItzYnRU6TI#dc1OUunASGxy$3?~% z$?%ro#1I|N0}rsYtg80&8m$ZjE6xh)c{iU2Nd%Yr;|G+Xdx%)?5;KdsIz6a_at5PE z8+U(jdpsedWl^qpa%7O1UGO{JZ(y|?63IVihJgVCDOdHt%Wn--`lO`1VlM->O~n(Y z`MUA~0`2YKD`}q2&tLCss5|%Q!-G3+j*NStF#)cm*2a2%^GGw)FzC8=@$_AILv;7W z+k_B}uIssl=EX~%#NOS${n_7(&hc;B_6{Dd-_i8j%wM#ts+^8CylqvGeSyiRN=HEvMeHk~cDQmN)Y#d+?q8@BJP& zBB$6d@9F7by}iBia$o!(%_?3ELM1pNx}O3JbbWcFPlbPdJeCUE^M-UmvFtifqTe*D zQ^`yq*++*CX^6NOHmr3ATOLqKq|#|$8C@N=q%g`KqT6BCOK>3*|l`RU3;@XX+qZx qzHgsS0I`3aB+=A_D{afSu!R@tgQ|z0vEYvY0000 literal 0 HcmV?d00001 diff --git a/InsertTo/resources/top-right/16x16.png b/InsertTo/resources/top-right/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..37f8b3c5b20b78f52dd8d2f30ae75c146396408e GIT binary patch literal 573 zcmV-D0>b@?P)0v@6uoEWy|mI+Q!&;;gH{yeMY?q%?(IT!ll}+kMnT+Ic`qwBu~niAD-~A?dFvJg z1+#JELKK^oh+3PERxQ>hF)x|9GEY-X(qg=u`MBqvIdkR?QIEmQ*lFMTdy!0LrQt%Lb(M~`_QYqz6O{vz^S{~(c#4fW{oqZr8@uN|b_dJh8&(Aj}8p= zpSm(P|5XYBrDdoyYZQvf777+? zEwofZYC#l)8$}RQh~QqKU>gG>DS4=9LAO7oC7bQt+}xkNb7ay4c5!#RMwav;-^<+j zx$~X#&CEFmpv@p6Mnv2o;_c?D0TH1ht~17}#}L{8MTCg7_`MkbQUG8f;>6+@LqypQ z?j>@#UMO@0L{}zf%Fg$H&CvDf61hZUg|fS2$q3apRA6v$kU?J`1G9DVRO%)slS#ZA zjpE_Gd-Gr2wtA0zF$R|BONIz<_U&Y+dp8!#4(#p@!Jmr1T}N>6+xyO^{U3kn@sQrp zAvh8NxU*&Ny_YlE$?fYt*8mRYO_Pgyp67BodF<@S&Twa>-?eQYfm$+@bB^}BOSfkp zzCJSkyF|u?E;#yn?2G_o zH5a!r5J7W1a0$SgvxzZ=a^WfhEHsGV2NJzND&B=nMV(!U%S%Fn9 zwGy&1gb=J$wk5dEv-`Jh*#G0?t%@GjgnADQ8F&w^AhUfFe!GuhBcwc)w)1D)*DT$(;x!xIxbHu~)9ONq$t_1&S5G+n$OMx3q= zL=4&hWoSO17l(K4@{J#^7Dw~HVE>U*pT!WTjT<+#>L|#dO)yPUDkYM!sE9{G@O4H5F8^W6(w@C8U%jC4uKvf_g{DV1>a}4S>}nSYe3AE$|rQS;OE%riod@Xdx0l z!rfw#Weo%2?^4rLE}BiM^cR1lFguEemQ%ki1e~|eed7OT1035%4PyZj^7->UFAjWg zd5$qeDVwL`TBw>2RUCRs${E#|OmaJy#+r^pJ2J`&UQIU0ckOHMwBLfsH1zS%Yuck|ltl o|4lNLPUGl-15cLct9WAY4-;mdVI&O>=Kufz07*qoM6N<$g8nYZAOHXW literal 0 HcmV?d00001 diff --git a/InsertTo/svg_geometry.py b/InsertTo/svg_geometry.py new file mode 100644 index 0000000..e9b1cf3 --- /dev/null +++ b/InsertTo/svg_geometry.py @@ -0,0 +1,356 @@ +"""SVG viewport sizing and placement in sketch coordinates (millimetres, Y up).""" + +import copy +from dataclasses import dataclass +import math +import re +import xml.etree.ElementTree as ET + + +SVG = 'http://www.w3.org/2000/svg' +ET.register_namespace('', SVG) +ET.register_namespace('xlink', 'http://www.w3.org/1999/xlink') +MM_PER_PX = 25.4 / 96.0 +_UNITS = { + '': MM_PER_PX, 'px': MM_PER_PX, 'mm': 1.0, 'cm': 10.0, 'q': 0.25, + 'in': 25.4, 'pt': 25.4 / 72.0, 'pc': 25.4 / 6.0, +} +_NUMBER = r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?' +_LENGTH = re.compile(rf'({_NUMBER})([a-zA-Z]*|%)') +_ANCHORS = { + 'top-left': (0, 1), 'top-center': (.5, 1), 'top-right': (1, 1), + 'center-left': (0, .5), 'center': (.5, .5), 'center-right': (1, .5), + 'bottom-left': (0, 0), 'bottom-center': (.5, 0), 'bottom-right': (1, 0), +} + + +@dataclass(frozen=True) +class SvgDocument: + root: ET.Element + width_mm: float + height_mm: float + view_box: tuple + # Native user coordinates -> original viewport in CSS pixels. + viewport_transform: tuple + + +@dataclass(frozen=True) +class Placement: + left_mm: float + bottom_mm: float + width_mm: float + height_mm: float + + +def _positive(value, label): + if not math.isfinite(value) or value <= 0: + raise ValueError(f'{label} must be a positive finite number.') + return value + + +def _length_mm(value, label): + if value is None or value.strip().lower() == 'auto': + return None + match = _LENGTH.fullmatch(value.strip()) + if not match: + raise ValueError(f'Unsupported SVG {label}: {value}.') + number = _positive(float(match[1]), f'SVG {label}') + unit = match[2].lower() + if unit == '%': + # No outer viewport exists for a standalone percentage. Use intrinsic ratio. + return None + if unit not in _UNITS: + raise ValueError(f'Unsupported SVG {label} unit: {unit}.') + return _positive(number * _UNITS[unit], f'SVG {label}') + + +def _view_box(value): + if value is None: + return None + parts = re.split(r'\s*,\s*|\s+', value.strip()) + if len(parts) != 4 or any(not re.fullmatch(_NUMBER, p) for p in parts): + raise ValueError('SVG viewBox must contain four numbers.') + box = tuple(map(float, parts)) + if not all(map(math.isfinite, box)) or min(box[2:]) <= 0: + raise ValueError('SVG viewBox must have finite coordinates and positive dimensions.') + return box + + +def _viewport_transform(box, pixel_width, pixel_height, aspect): + x, y, width, height = box + sx, sy = pixel_width / width, pixel_height / height + parts = aspect.split() + if parts[:1] == ['defer']: + parts = parts[1:] + align = parts[0] if parts else 'xMidYMid' + method = parts[1] if len(parts) > 1 else 'meet' + if len(parts) > 2 or method not in ('meet', 'slice'): + raise ValueError('Invalid SVG preserveAspectRatio.') + if align == 'none': + return sx, sy, -x * sx, -y * sy + match = re.fullmatch(r'x(Min|Mid|Max)Y(Min|Mid|Max)', align) + if not match: + raise ValueError('Invalid SVG preserveAspectRatio alignment.') + factors = {'Min': 0, 'Mid': .5, 'Max': 1} + scale = (min if method == 'meet' else max)(sx, sy) + return (scale, scale, + (pixel_width - width * scale) * factors[match[1]] - x * scale, + (pixel_height - height * scale) * factors[match[2]] - y * scale) + + +def read_svg(path): + """Read the authored viewport; standalone viewBox-only art uses CSS pixels.""" + try: + root = ET.parse(path).getroot() + except ET.ParseError as error: + raise ValueError(f'Invalid SVG XML: {error}') from error + if root.tag not in ('svg', f'{{{SVG}}}svg'): + raise ValueError('Select an SVG document.') + box = _view_box(root.get('viewBox')) + style = {} + for entry in root.get('style', '').split(';'): + name, sep, value = entry.partition(':') + if sep: + style[name.strip().lower()] = value.strip().removesuffix('!important').strip() + w = _length_mm(style.get('width', root.get('width')), 'width') + h = _length_mm(style.get('height', root.get('height')), 'height') + if box: + ratio = box[2] / box[3] + if w is None: + w = h * ratio if h is not None else box[2] * MM_PER_PX + if h is None: + h = w / ratio + else: + # CSS default object size for an unsized standalone SVG. + w = 300 * MM_PER_PX if w is None else w + h = 150 * MM_PER_PX if h is None else h + width_px = _positive(w / MM_PER_PX, 'SVG width') + height_px = _positive(h / MM_PER_PX, 'SVG height') + if box is None: + box = (0, 0, width_px, height_px) + transform = _viewport_transform(box, width_px, height_px, root.get('preserveAspectRatio', '')) + if not all(map(math.isfinite, transform)): + raise ValueError('SVG viewport exceeds the supported coordinate range.') + return SvgDocument(root, w, h, box, transform) + + +def placement(doc, frame, mode='fit', anchor='center'): + """Align the SVG viewport to the selected frame bounding box, both in mm.""" + xmin, ymin, xmax, ymax = frame + if not all(map(math.isfinite, frame)): + raise ValueError('The selected frame must have finite coordinates.') + fw = _positive(xmax - xmin, 'Frame width') + fh = _positive(ymax - ymin, 'Frame height') + if mode == 'fit': + scale = min(fw / doc.width_mm, fh / doc.height_mm) + w, h = doc.width_mm * scale, doc.height_mm * scale + elif mode == 'stretch': + w, h = fw, fh + elif mode == 'original': + w, h = doc.width_mm, doc.height_mm + else: + raise ValueError('Select a supported scale mode.') + if mode == 'original' and anchor not in _ANCHORS: + raise ValueError('Select a supported anchor.') + ax, ay = _ANCHORS[anchor] if mode == 'original' else _ANCHORS['center'] + return Placement(xmin + ax * (fw - w), ymin + ay * (fh - h), w, h) + + +def _format(value): + return format(value, '.15g') if value else '0' + + +_PATH_COMMANDS = 'MmLlHhVvCcSsQqTtAaZz' +_PATH_NUMBER = re.compile(_NUMBER) +_PATH_SEPARATORS = re.compile(r'[\s,]*') +_PATH_ARITY = {'M': 2, 'L': 2, 'H': 1, 'V': 1, 'C': 6, 'S': 4, 'Q': 4, 'T': 2, 'A': 7} + + +def _arc_cubics(start, end, values): + """SVG endpoint arc -> cubic Béziers, following SVG 2 Appendix B.2.""" + rx, ry = abs(values[0]), abs(values[1]) + if start == end: + return [] + if not rx or not ry: + return ['L' + ' '.join(map(_format, end))] + phi = math.radians(values[2] % 360) + c, s = math.cos(phi), math.sin(phi) + dx, dy = (start[0] - end[0]) / 2, (start[1] - end[1]) / 2 + x, y = (c * dx + s * dy) / rx, (-s * dx + c * dy) / ry + radius = math.hypot(x, y) + if radius > 1: + rx, ry = rx * radius, ry * radius + x, y = x / radius, y / radius + radius = 1 + # Midpoint-relative centre expressed in ellipse unit-circle coordinates. + distance = math.sqrt(max(0, 1 - radius * radius)) + sign = -1 if values[3] == values[4] else 1 + cx, cy = sign * (y / radius) * distance, -sign * (x / radius) * distance + world_x = (start[0] + end[0]) / 2 + c * rx * cx - s * ry * cy + world_y = (start[1] + end[1]) / 2 + s * rx * cx + c * ry * cy + u, v = x - cx, y - cy + a, b = -x - cx, -y - cy + angle = math.atan2(v, u) + sweep = math.atan2(u * b - v * a, u * a + v * b) + if values[4] and sweep < 0: + sweep += math.tau + elif not values[4] and sweep > 0: + sweep -= math.tau + + def project(x, y): + return world_x + c * rx * x - s * ry * y, world_y + s * rx * x + c * ry * y + + # At most 22.5 degrees per segment keeps the relative radial error below 1e-7. + count = max(1, math.ceil(abs(sweep) / (math.pi / 8))) + step = sweep / count + handle = 4 / 3 * math.tan(step / 4) + commands = [] + for index in range(count): + p, q = math.cos(angle), math.sin(angle) + angle += step + a, b = math.cos(angle), math.sin(angle) + first = project(p - handle * q, q + handle * p) + second = project(a + handle * b, b - handle * a) + endpoint = end if index == count - 1 else project(a, b) + commands.append('C' + ' '.join(map(_format, (*first, *second, *endpoint)))) + return commands + + +def _expand_arcs(data): + """Expand only arcs, preserving SVG implicit commands and shorthand semantics.""" + cursor = 0 + current = origin = (0, 0) + command, previous = '', '' + output = [] + while True: + cursor = _PATH_SEPARATORS.match(data, cursor).end() + if cursor == len(data): + return ' '.join(output) + if data[cursor] in _PATH_COMMANDS: + command = data[cursor] + cursor += 1 + if not command: + raise ValueError('Invalid SVG path command.') + op = command.upper() + if op == 'Z': + output.append('Z') + current, command, previous = origin, '', 'Z' + continue + values = [] + for index in range(_PATH_ARITY[op]): + cursor = _PATH_SEPARATORS.match(data, cursor).end() + # Consecutive flags and the next coordinate may share a token (e.g. 0110). + if op == 'A' and index in (3, 4): + if cursor >= len(data) or data[cursor] not in '01': + raise ValueError('Invalid SVG arc flag.') + values.append(int(data[cursor])) + cursor += 1 + else: + number = _PATH_NUMBER.match(data, cursor) + if number is None: + raise ValueError('Invalid SVG path coordinate.') + values.append(float(number[0])) + cursor = number.end() + relative = command.islower() + x, y = current + if op == 'H': + end = (values[0] + (x if relative else 0), y) + elif op == 'V': + end = (x, values[0] + (y if relative else 0)) + else: + end = (values[-2] + (x if relative else 0), values[-1] + (y if relative else 0)) + if op == 'A': + output.extend(_arc_cubics(current, end, values)) + elif op == 'S' and previous == 'A': + # Following a real arc, SVG's reflected control point equals the endpoint. + first = (0, 0) if relative else current + output.append(('c' if relative else 'C') + ' '.join(map(_format, (*first, *values)))) + else: + output.append(command + ' '.join(map(_format, values))) + if op == 'M': + origin = end + command = 'l' if relative else 'L' + current, previous = end, op + + +def _resolve_shape_lengths(element, viewport, nonuniform): + """Keep absolute and percentage lengths in the original coordinate system.""" + shape = element.tag.rsplit('}', 1)[-1] + if shape == 'svg': # A nested SVG establishes its own viewport. + return + nonuniform = nonuniform or bool(element.get('transform')) + dimensions = { + 'rect': ('x', 'y', 'width', 'height', 'rx', 'ry'), + 'line': ('x1', 'x2', 'y1', 'y2'), 'circle': ('cx', 'cy', 'r'), + 'ellipse': ('cx', 'cy', 'rx', 'ry'), 'use': ('x', 'y'), + } + for name in dimensions.get(shape, ()): + match = _LENGTH.fullmatch(element.get(name, '').strip()) + if not match or not match[2]: + continue + value, unit = float(match[1]), match[2].lower() + if unit == '%': + if name == 'r': + extent = math.hypot(*viewport) / math.sqrt(2) + else: + vertical = name in ('y', 'y1', 'y2', 'ry', 'cy', 'height') + extent = viewport[int(vertical)] + value = value * extent / 100 + elif unit in _UNITS: + value = value * _UNITS[unit] / MM_PER_PX + else: + continue + element.set(name, _format(value)) + # Fusion scales a native circle uniformly even inside a nonuniform SVG group. + # An equal-radii SVG ellipse goes through Fusion's exact ellipse importer. + if nonuniform and shape == 'circle' and element.get('r') is not None: + element.tag = element.tag[:-6] + 'ellipse' + radius = element.attrib.pop('r') + element.set('rx', radius) + element.set('ry', radius) + if shape == 'path' and nonuniform: + data = element.get('d', '') + if 'A' in data or 'a' in data: + element.set('d', _expand_arcs(data)) + for child in element: + _resolve_shape_lengths(child, viewport, nonuniform) + + +def normalized_svg(doc, target, rotation=0.0): + """Rotate CCW in sketch radians and enclose the viewport in a local 96 dpi SVG.""" + w, h = target.width_mm / MM_PER_PX, target.height_mm / MM_PER_PX + cosine, sine = math.cos(rotation), math.sin(rotation) + # SVG's Y axis points down, reversing the sign of a sketch rotation. + # Translate the rotated viewport's minimum X/Y back to the new origin. + left = min(0, cosine * w) + min(0, sine * h) + top = min(0, -sine * w) + min(0, cosine * h) + width = _format(abs(cosine) * w + abs(sine) * h) + height = _format(abs(sine) * w + abs(cosine) * h) + root = copy.deepcopy(doc.root) + # The source root becomes the inner group, retaining inherited styles, IDs + # and any user-authored root transform apart from viewport sizing. + for attr in ('x', 'y', 'width', 'height', 'viewBox', 'preserveAspectRatio', 'version'): + root.attrib.pop(attr, None) + if 'style' in root.attrib: + root.set('style', ';'.join( + entry for entry in root.get('style').split(';') + if entry.partition(':')[0].strip().lower() not in ('width', 'height') + )) + root.tag = f'{{{SVG}}}g' + outer = ET.Element(f'{{{SVG}}}svg', { + 'width': width, 'height': height, 'viewBox': f'0 0 {width} {height}', + }) + sx, sy, tx, ty = doc.viewport_transform + rx, ry = target.width_mm / doc.width_mm, target.height_mm / doc.height_mm + nonuniform = not math.isclose(sx * rx, sy * ry, rel_tol=1e-10) + _resolve_shape_lengths(root, doc.view_box[2:], nonuniform) + matrix = ( + cosine * sx * rx, -sine * sx * rx, sine * sy * ry, cosine * sy * ry, + cosine * tx * rx + sine * ty * ry - left, + -sine * tx * rx + cosine * ty * ry - top, + ) + group = ET.SubElement(outer, f'{{{SVG}}}g', { + 'transform': 'matrix(' + ' '.join(map(_format, matrix)) + ')', + }) + group.append(root) + return ET.tostring(outer, encoding='unicode') diff --git a/README.md b/README.md index 6d04838..19ea660 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,27 @@ -# 4FusionLab · Fusion Add-in Template +# InsertTo -[Русская версия](README.ru.md) +Insert SVG artwork into an Autodesk Fusion sketch at its physical size or scale it to a selected frame. -A reusable **Autodesk Fusion add-in starter** for 4FusionLab. It includes a working command, a Fusion manifest, offline tests, cross-platform CI, deterministic ZIP packaging and the shared 4FusionLab automatic release policy. +[Русская версия](README.ru.md) · [Report an issue](https://github.com/4FusionLab/InsertTo/issues) -## Create a new add-in +## Insert an SVG -1. Click **Use this template** → **Create a new repository**, preferably in the `4FusionLab` organization. -2. In the new repository open **Actions → Initialize add-in → Run workflow**. The repository name becomes the Python add-in package name; you can enter a friendly display name and description. -3. The initialization commit generates a **new manifest UUID and command ID**, renames the add-in package and prepares the bilingual project README files. -4. Develop your add-in in its package directory. Run `python -m unittest discover -s tests -v` and `python scripts/build.py --version 0.1.0` for a local verification. -5. After initialization, every push or merged PR to `main` which touches **shipped runtime files** is eligible for an automatic release, subject to green CI. Documentation and test-only changes do not publish. +1. Edit a sketch and open **Insert → Smart Insert → SVG**. +2. Choose the SVG file. For **Frame**, select a shaded profile or a closed sketch contour. You can select one edge of an isolated closed chain or select the segments individually. +3. Choose a scale mode and check the preview and dimensions. Click **Insert** to keep the curves, or **Cancel** to discard the preview. -If Actions cannot be enabled yet, run the initializer locally: `python scripts/init_addin.py --name MyNewAddin --display-name "My New Add-in"`, commit its changes and push. +| Scale | Placement | +| --- | --- | +| Fit | Centers the SVG page and scales it proportionally until one dimension meets the frame. | +| Stretch | Scales width and height independently to fill the frame. | +| Original size | Preserves the SVG page size. Choose one of nine anchors to align matching corners, edge midpoints or centers on the page and frame. | -> Never install or publish the uninitialized `FusionAddin` placeholder as a real product. +A rectangular frame follows its sketch edges, including rotated rectangles. Other closed contours supply their bounding rectangle along the sketch axes. Curves can extend outside an irregular contour. Placement includes blank margins in the SVG page. A 50 mm page stays 50 mm wide in **Original size**. SVGs using pixels use 96 px per inch. The result consists of the vector curves supported by Fusion’s SVG importer. -## What is shared? +## Verified in Fusion -- GitVersion.Tool **6.8.2** and conventional commit conventions. -- Immutable, SHA-pinned composite Actions from [4FusionLab/.github](https://github.com/4FusionLab/.github). -- CI on Linux, macOS and Windows; offline tests are distinct from real Fusion acceptance. -- ZIP and SHA-256 verification; no manually created release tags. -- Separate English and Russian documentation and `AGENTS.md` rules for coding agents. +On macOS, Fusion 2706.1.17 produced a 50 × 50 mm sketch from a 50 mm medallion SVG. A 50 × 20 mm test drawing in an 80 × 60 mm frame measured 80 × 32 mm in **Fit** and 80 × 60 mm in **Stretch**. Native Windows acceptance is pending. -The repository is a template, not an existing 4FusionLab product. See `docs/DEVELOPMENT.md` after scaffolding is installed. +## Install from source -## Prepare product documentation - -The initializer creates starter pages, not finished product documentation. Before publishing a product, replace the starter description in **both** `README.md` and `README.ru.md` with accurate, separately written English and Russian text. Follow the [product README guidelines](https://github.com/4FusionLab/.github/blob/main/README_GUIDELINES.md): explain the user outcome and actual workflow, link real releases and support, give install steps, and state important limitations and verified platform status. Include safety warnings prominently when relevant; preserve existing examples and assets. Check links, language parity and the current license before delivery. Write documentation in English with a separate Russian version; intermediate working notes do not require translation. +In Fusion, open **Scripts and Add-Ins**, add the repository’s inner `InsertTo` folder (the folder containing `InsertTo.manifest`), and start **InsertTo**. For a local ZIP and the automated checks, see [Development](docs/DEVELOPMENT.md). diff --git a/README.ru.md b/README.ru.md index bcaf276..c06a2cd 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,32 +1,27 @@ -# 4FusionLab · Шаблон аддина Autodesk Fusion +# InsertTo -[English](README.md) +Вставляет SVG в эскиз Autodesk Fusion с сохранением физических размеров или масштабирует рисунок по выбранной рамке. -Готовая основа для новых аддинов **Autodesk Fusion / Fusion 360** от 4FusionLab: рабочая команда, манифест, тестируемая Python-логика, CI на трёх ОС, сборка ZIP, GitVersion и автоматические GitHub Releases. +[English](README.md) · [Сообщить о проблеме](https://github.com/4FusionLab/InsertTo/issues) -## Как создать аддин +## Вставка SVG -1. Нажми **Use this template → Create a new repository** в организации `4FusionLab`. -2. В новом репозитории запусти **Actions → Initialize add-in → Run workflow**. Имя репозитория станет именем Python-пакета; название в Fusion и описание можно задать отдельно. -3. Инициализатор создаст **уникальные UUID манифеста и ID команды**, переименует папку аддина, подготовит README на английском и русском. Повторная генерация ID запрещена. -4. Добавляй реализацию в Python-пакет. Запускай `python -m unittest discover -s tests -v` и `python scripts/build.py --version 0.1.0`. -5. После инициализации push/merge в `main` публикует релиз **только при изменении поставляемого кода или ресурсов**, после успешного CI. Документация и тесты сами по себе релиз не запускают. +1. Откройте эскиз на редактирование и выберите **Insert → Smart Insert → SVG**. +2. Укажите файл SVG. В поле **Frame** выберите закрашенный профиль или замкнутый контур эскиза. У изолированной замкнутой цепочки достаточно выбрать одно ребро. Также можно выбрать сегменты по отдельности. +3. Выберите режим и проверьте предпросмотр и размеры. Нажмите **Insert**, чтобы добавить кривые, или **Cancel**, чтобы отменить вставку. -При необходимости инициализируй локально: `python scripts/init_addin.py --name MyNewAddin --display-name "My New Add-in"`. Затем закоммить изменения и отправь в свой репозиторий. +| Режим | Размещение | +| --- | --- | +| Fit — вписать | Центрирует страницу SVG и пропорционально увеличивает или уменьшает её до границы рамки. | +| Stretch — растянуть | Подгоняет ширину и высоту страницы под рамку независимо друг от друга. | +| Original size — исходный размер | Сохраняет размер страницы. Девять значков позволяют совместить соответствующие углы, середины сторон или центры страницы и рамки. | -**Не устанавливай исходную папку `FusionAddin` как готовый продукт:** шаблон намеренно помечен неинициализированным. +У прямоугольной рамки учитывается поворот сторон. Для других контуров берётся габаритный прямоугольник по осям эскиза, поэтому рисунок может выходить за границу контура сложной формы. При размещении учитываются пустые поля внутри страницы SVG. В режиме **Original size** страница шириной 50 мм сохраняет ширину 50 мм. Для пикселей используется соотношение 96 px на дюйм. В эскизе создаются векторные кривые, которые поддерживает импортёр SVG в Fusion. -## Что унифицировано +## Проверка в Fusion -- GitVersion.Tool **6.8.2**, Conventional Commits, неизменяемые версии и автоматические теги без ручной работы. -- Общие GitHub Actions из [4FusionLab/.github](https://github.com/4FusionLab/.github), подключённые по точному SHA. -- Offline-тесты на Linux, macOS и Windows и отдельная проверка в самом Fusion. -- Проверка ZIP, манифеста, SHA-256 и release notes. -- Раздельные английская/русская документации и базовый `AGENTS.md` для AI-агентов. +В Fusion 2706.1.17 на macOS медальон из SVG размером 50 × 50 мм дал в эскизе ровно 50 × 50 мм. В рамке 80 × 60 мм контрольный рисунок 50 × 20 мм дал 80 × 32 мм в режиме **Fit** и 80 × 60 мм в режиме **Stretch**. Проверка в Fusion на Windows ещё предстоит. -Инструкция по разработке и приёмке — в [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md). +## Установка из исходников - -## Подготовка документации продукта - -Инициализатор создаёт начальные страницы, а не готовую документацию продукта. До публикации замените исходное описание в **обоих** файлах `README.md` и `README.ru.md` точными текстами на английском и русском. Следуйте [правилам README продукта](https://github.com/4FusionLab/.github/blob/main/README_GUIDELINES.ru.md): опишите пользу и реальный сценарий, добавьте ссылки на существующие релизы и поддержку, установку, важные ограничения и фактическую проверку платформ. Существенные предупреждения размещайте на видном месте; сохраняйте примеры и изображения. Перед передачей проверьте ссылки, соответствие языковых версий и действующую лицензию. Документацию ведите на английском с отдельной русской версией; промежуточные рабочие заметки переводить не требуется. +В Fusion откройте **Scripts and Add-Ins**, добавьте внутреннюю папку `InsertTo` с файлом `InsertTo.manifest` и запустите **InsertTo**. Сборка локального ZIP и автоматические проверки описаны в [руководстве по разработке](docs/DEVELOPMENT.ru.md). diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index fd98a53..1a7d8a1 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -4,24 +4,14 @@ ## Architecture -- `/.py`: Autodesk Fusion entry point, command and event lifecycle. This module imports `adsk`, so **do not import it in offline unit tests**. -- `/config.py`: stable command identifier and product metadata. Generated once. -- `/core.py`: plain Python, independently testable calculation and domain logic. -- `/.manifest`: Autodesk Fusion add-in metadata; the release builder stamps the computed version into the ZIP without rewriting the checkout. +- `InsertTo/InsertTo.py`: Autodesk Fusion entry point, command and event lifecycle. This module imports `adsk`, so **do not import it in offline unit tests**. +- `InsertTo/config.py`: stable command identifier and product metadata. Generated once. +- `InsertTo/svg_geometry.py`: plain Python, independently testable calculation and domain logic. +- `InsertTo/InsertTo.manifest`: Autodesk Fusion add-in metadata; the release builder stamps the computed version into the ZIP without rewriting the checkout. - `scripts/build.py`: deterministic archive, SHA-256, secret/symlink guardrails. - `.github/release-paths.txt`: reviewed allowlist of files that affect the shipped runtime. -## Workflow for a new product - -1. Create a new repository from the GitHub template. The source template deliberately cannot be published. -2. Run **Actions → Initialize add-in** on `main`. This workflow is unavailable on the template itself and deletes itself from the generated project. It creates the project-specific manifest UUID and command ID. -3. The initializer pushes a generated commit using GitHub's built-in token; that push does **not** automatically trigger other push workflows. It explicitly dispatches a read-only CI workflow to validate the generated project, without making a release. -4. If local initialization was used instead, run `python scripts/init_addin.py --name MyAddin --repo 4FusionLab/MyAddin`, `python scripts/check_project.py` and tests, then push to your repository. -5. Implement the command. Keep all Fusion API calls on the appropriate Fusion execution thread and separate them from pure computation. Add test coverage and native Fusion acceptance evidence. -6. When shipped runtime files change, push to `main` or merge a PR. Green CI and an eligible runtime path automatically publish a versioned stable GitHub Release. -7. Do not add direct releases for docs, tests, CI, or policy-only changes. Do not create tags manually. - -## Local validation +## Local build ```bash python scripts/check_project.py @@ -29,15 +19,7 @@ python -m unittest discover -s tests -v python scripts/build.py --version 0.1.0 ``` -An uninitialized source template may be tested using `--allow-template` but **cannot** publish; new products must not use that flag in release scripts. - -## Install in Fusion - -1. Download the ZIP from the product's GitHub Releases, or build it locally. -2. Extract it so the Fusion API AddIns folder contains `/.manifest` and `/.py`. Do not install the ZIP as a double-nested directory. -3. Open Autodesk Fusion, go to **Utilities → Add-Ins** and start the add-in. Check the add-in entry in the SOLID **ADD-INS** panel. -4. Run the starter command. It should show a message and **must not modify the design**. Disable the add-in and verify the command/control disappears. -5. Repeat on macOS and Windows for OS-specific dependencies/geometry/UI, noting differences. Do not claim that CI has run native Fusion acceptance. +The archive in `dist/` contains the installable InsertTo folder. For development, register that folder or the source package via **Scripts and Add-Ins**. Edit a sketch and open **Insert → Smart Insert → SVG**. ## Native acceptance checklist diff --git a/docs/DEVELOPMENT.ru.md b/docs/DEVELOPMENT.ru.md index 0ff8d67..dd84af6 100644 --- a/docs/DEVELOPMENT.ru.md +++ b/docs/DEVELOPMENT.ru.md @@ -4,24 +4,14 @@ ## Архитектура -- `/.py`: точка входа Autodesk Fusion, жизненный цикл команд и событий. Модуль импортирует `adsk`, поэтому **не импортируйте его в автономных модульных тестах**. -- `/config.py`: стабильный идентификатор команды и метаданные продукта. Создаётся один раз. -- `/core.py`: обычный Python, независимо тестируемые вычисления и предметная логика. -- `/.manifest`: метаданные аддона Autodesk Fusion; сборщик релиза записывает вычисленную версию в ZIP, не меняя рабочий каталог. +- `InsertTo/InsertTo.py`: точка входа Autodesk Fusion, жизненный цикл команд и событий. Модуль импортирует `adsk`, поэтому **не импортируйте его в автономных модульных тестах**. +- `InsertTo/config.py`: стабильный идентификатор команды и метаданные продукта. Создаётся один раз. +- `InsertTo/svg_geometry.py`: обычный Python, независимо тестируемые вычисления и предметная логика. +- `InsertTo/InsertTo.manifest`: метаданные аддона Autodesk Fusion; сборщик релиза записывает вычисленную версию в ZIP, не меняя рабочий каталог. - `scripts/build.py`: детерминированный архив, SHA-256, защита от секретов и символических ссылок. - `.github/release-paths.txt`: проверенный перечень файлов, влияющих на поставляемые компоненты. -## Работа над новым продуктом - -1. Создайте репозиторий из шаблона GitHub. Исходный шаблон намеренно нельзя публиковать. -2. Запустите **Actions → Initialize add-in** в `main`. Этот workflow недоступен в самом шаблоне и удаляет себя из созданного проекта. Он создаёт UUID манифеста и идентификатор команды для проекта. -3. Инициализатор отправляет созданный коммит со встроенным токеном GitHub; такой push **не** запускает автоматически другие workflows для push. Для проверки проекта без выпуска релиза он явно запускает workflow CI с доступом только на чтение. -4. При локальной инициализации выполните `python scripts/init_addin.py --name MyAddin --repo 4FusionLab/MyAddin`, `python scripts/check_project.py` и тесты, затем отправьте изменения в репозиторий. -5. Реализуйте команду. Все вызовы Fusion API выполняйте в соответствующем потоке Fusion и отделяйте от чистых вычислений. Добавьте тесты и результаты приёмки в Fusion. -6. При изменении поставляемых файлов выполните push в `main` или объедините PR. Успешный CI и подходящий путь исполняемого файла автоматически публикуют стабильный GitHub Release с версией. -7. Не создавайте прямые релизы для изменений только документации, тестов, CI или политик. Не создавайте теги вручную. - -## Локальная проверка +## Локальная сборка ```bash python scripts/check_project.py @@ -29,15 +19,7 @@ python -m unittest discover -s tests -v python scripts/build.py --version 0.1.0 ``` -Неинициализированный исходный шаблон можно тестировать с `--allow-template`, но он **не может** публиковаться; новые продукты не должны использовать этот флаг в сценариях релиза. - -## Установка в Fusion - -1. Скачайте ZIP из GitHub Releases продукта или соберите его локально. -2. Распакуйте его так, чтобы каталог Fusion API AddIns содержал `/.manifest` и `/.py`. Не устанавливайте ZIP с двойной вложенностью каталогов. -3. Откройте Autodesk Fusion, перейдите в **Utilities → Add-Ins** и запустите аддон. Проверьте запись аддона на панели SOLID **ADD-INS**. -4. Запустите стартовую команду. Она должна показать сообщение и **не должна изменять модель**. Отключите аддон и убедитесь, что команда и элемент управления исчезли. -5. Повторите на macOS и Windows для зависимостей, геометрии и интерфейса, специфичных для ОС, отмечая различия. Не утверждайте, что CI выполнил приёмку в Fusion. +Архив в `dist/` содержит папку InsertTo для установки. Для разработки подключите эту папку или папку исходников аддона через **Scripts and Add-Ins**. Откройте эскиз на редактирование и выберите **Insert → Smart Insert → SVG**. ## Контрольный список приёмки в Fusion diff --git a/scripts/build.py b/scripts/build.py index 84edbc8..6c88943 100644 --- a/scripts/build.py +++ b/scripts/build.py @@ -9,7 +9,7 @@ ROOT = Path(__file__).resolve().parents[1] VERSION_PATTERN = re.compile(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\Z') -SKIP_DIRS = {'__pycache__', '.git', '.venv', 'node_modules'} +SKIP_DIRS = {'__pycache__', '.git', '.venv', '.vscode', 'node_modules'} SKIP_FILES = {'.DS_Store'} FORBIDDEN_SUFFIXES = {'.pyc', '.pyo', '.pem', '.p12', '.pfx', '.key'} FORBIDDEN_NAMES = {'.env', '.env.local', '.env.production'} diff --git a/scripts/check_project.py b/scripts/check_project.py index e05577d..36030d7 100644 --- a/scripts/check_project.py +++ b/scripts/check_project.py @@ -36,7 +36,7 @@ def validate(root=ROOT, allow_template=False): if manifest.get('description', {}).get('') != metadata['description']: raise ValueError('Manifest description must match project metadata.') config = (package / 'config.py').read_text(encoding='utf-8') - pure_code = ast.parse((package / 'core.py').read_text(encoding='utf-8')) + pure_code = ast.parse((package / 'svg_geometry.py').read_text(encoding='utf-8')) for node in ast.walk(pure_code): if isinstance(node, ast.Import) and any( alias.name == 'adsk' or alias.name.startswith('adsk.') for alias in node.names diff --git a/tests/test_core.py b/tests/test_core.py deleted file mode 100644 index 1d7a3a3..0000000 --- a/tests/test_core.py +++ /dev/null @@ -1,29 +0,0 @@ -"""The domain core is importable without Autodesk Fusion installed.""" - -import importlib -import json -from pathlib import Path -import unittest - -ROOT = Path(__file__).resolve().parents[1] - - -class CoreTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - metadata = json.loads((ROOT / '.fusion-addin.json').read_text(encoding='utf-8')) - cls.core = importlib.import_module(metadata['name'] + '.core') - - def test_document_context(self): - self.assertIn('Example.f3d', self.core.ready_message('Sample', 'Example.f3d')) - - def test_no_document(self): - self.assertIn('Open a design', self.core.ready_message('Sample', None)) - - def test_missing_display_name(self): - with self.assertRaises(ValueError): - self.core.ready_message('', 'Example.f3d') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_dialog.py b/tests/test_dialog.py new file mode 100644 index 0000000..5f133ba --- /dev/null +++ b/tests/test_dialog.py @@ -0,0 +1,87 @@ +"""Offline checks for the command's decisions at Fusion event boundaries.""" + +import importlib.util +import sys +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from InsertTo import fusion_import, svg_geometry + + +def load_dialog(): + # Use a private module instance so the SDK stand-in cannot leak into other tests. + spec = importlib.util.spec_from_file_location( + 'InsertTo._dialog_under_test', Path(svg_geometry.__file__).with_name('dialog.py') + ) + module = importlib.util.module_from_spec(spec) + sdk = Mock() + modules = {'adsk': sdk, 'adsk.core': sdk.core, 'adsk.fusion': sdk.fusion} + with patch.dict(sys.modules, modules): + spec.loader.exec_module(module) + return module + + +class DialogEventsTests(unittest.TestCase): + def setUp(self): + module = load_dialog() + self.session = module._Dialog.__new__(module._Dialog) + self.session.app = Mock() + self.session.sketch = self.session.app.activeEditObject + self.session.sketch.isValid = True + self.session.document = SimpleNamespace(width_mm=20., height_mm=10.) + self.session.browse = SimpleNamespace(text='previous.svg') + self.session.file_error = self.session.preview_error = '' + self.session.frame = Mock(selectionCount=1) + self.session.status = SimpleNamespace(text='') + self.session.bounds = None + self.session.scaling = self.session.anchor = SimpleNamespace( + selectedItem=SimpleNamespace(index=0) + ) + + def changed(self, input_id): + self.session._changed(SimpleNamespace(input=SimpleNamespace(id=input_id))) + + def test_cancel_file_picker_preserves_failed_preview_and_chosen_file(self): + self.session.bounds = fusion_import.Frame((0, 0, 20, 10), 0) + args = SimpleNamespace() + with patch.object(fusion_import, 'import_svg', side_effect=ValueError('No curves.')): + self.session._preview(args) + self.assertFalse(args.isValidResult) + previous = self.session.document + self.changed('svgFile') # The picker did not return DialogOK. + self.assertIs(self.session.document, previous) + self.assertEqual(self.session.browse.text, 'previous.svg') + self.session._validate(args) + self.assertFalse(args.areInputsValid) + self.assertEqual(self.session.status.text, 'Preview failed. No curves.') + + def test_profile_replacement_after_preview_uses_new_frame_for_execute(self): + first = fusion_import.Frame((0, 0, 20, 10), 0) + second = fusion_import.Frame((30, 40, 90, 70), 0) + with patch.object(fusion_import, 'frame_bounds', side_effect=[first, second]) as bounds, \ + patch.object(fusion_import, 'import_svg') as insert: + args = SimpleNamespace() + self.session.frame.selection.return_value.entity = 'first profile' + self.session._preview(args) + self.assertTrue(args.isValidResult) + self.assertIs(insert.call_args.args[-1], first) + + self.session.frame.selectionCount = 0 + self.changed('frame') + self.session._validate(args) + self.assertFalse(args.areInputsValid) + + self.session.frame.selectionCount = 1 + self.session.frame.selection.return_value.entity = 'second profile' + self.changed('frame') + self.session._preview(args) + preview = insert.call_args + self.assertTrue(args.isValidResult) + self.assertIs(preview.args[-1], second) + self.assertEqual(preview.args[-2], svg_geometry.Placement(30, 40, 60, 30)) + self.session._execute(args) # Fallback if Fusion requests explicit execution. + self.assertEqual(insert.call_args, preview) + self.assertEqual([call.args[1] for call in bounds.call_args_list], + [['first profile'], ['second profile']]) diff --git a/tests/test_fusion_import.py b/tests/test_fusion_import.py new file mode 100644 index 0000000..411b13a --- /dev/null +++ b/tests/test_fusion_import.py @@ -0,0 +1,61 @@ +import math +from pathlib import Path +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +from InsertTo import fusion_import as adapter +from InsertTo.svg_geometry import Placement + + +def segment(a, b): + start = SimpleNamespace(x=a[0], y=a[1]) + end = SimpleNamespace(x=b[0], y=b[1]) + geometry = SimpleNamespace(objectType='adsk::core::Line3D', startPoint=start, endPoint=end, + evaluator=SimpleNamespace(getEndPoints=lambda: (True, start, end))) + return SimpleNamespace(objectType='adsk::fusion::SketchLine', geometry=geometry) + + +def loop(points): + return [segment(points[i - 1], point) for i, point in enumerate(points)] + + +class FrameTests(unittest.TestCase): + def test_only_one_complete_contour(self): + shape = loop([(0, 0), (3, 0), (3, 3), (0, 3)]) + self.assertTrue(adapter._closed_chain([shape[i] for i in [3, 1, 0, 2]])) + self.assertFalse(adapter._closed_chain(shape[:-1])) + self.assertFalse(adapter._closed_chain(shape + [segment((0, 0), (1, 1))])) + self.assertFalse(adapter._closed_chain(shape + loop([(6, 6), (7, 6), (7, 7)]))) + + def test_rotated_rectangle_has_reproducible_local_axes(self): + points = [(1, 1), (3, 2), (2.5, 3), (.5, 2)] + for order in (points, list(reversed(points)), points[1:] + points[:1]): + self.assertAlmostEqual(adapter._rectangle_angle([s.geometry for s in loop(order)]), + math.atan2(1, 2)) + + def test_general_polygon_uses_sketch_axes(self): + trapezoid = loop([(1, 1), (3, 2), (2, 4), (0, 2)]) + self.assertEqual(adapter._rectangle_angle([s.geometry for s in trapezoid]), 0) + + @patch.object(adapter.svg_geometry, 'normalized_svg', return_value='') + def test_native_origin_uses_rotated_top_left_in_centimetres(self, normalize): + angle = math.radians(30) + frame = adapter.Frame((10, 20, 50, 80), angle) + target = Placement(10, 20, 40, 60) + calls = [] + curves = SimpleNamespace(count=0) + + def insert(path, x, y, scale): + calls.append((Path(path), x, y, scale)) + self.assertEqual(Path(path).read_text(), '') + curves.count += 1 + return True + + adapter.import_svg(SimpleNamespace(sketchCurves=curves, importSVG=insert), None, target, frame) + path, x, y, scale = calls[0] + self.assertFalse(path.exists()) + self.assertAlmostEqual(x, math.cos(angle) - 8 * math.sin(angle)) + self.assertAlmostEqual(y, 5 * math.sin(angle) + 8 * math.cos(angle)) + self.assertEqual(scale, 1) + normalize.assert_called_once_with(None, target, rotation=angle) diff --git a/tests/test_package.py b/tests/test_package.py index 8ac91c6..4431988 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -7,13 +7,23 @@ import unittest import zipfile -from scripts.build import build +from scripts.build import build, candidate_files from scripts.check_project import validate ROOT = Path(__file__).resolve().parents[1] class PackageTests(unittest.TestCase): + def test_fusion_generated_editor_settings_stay_out_of_package(self): + with TemporaryDirectory() as temp: + root = Path(temp) + settings = root / '.vscode' + settings.mkdir() + (settings / 'launch.json').write_text('{}') + entry = root / 'InsertTo.py' + entry.touch() + self.assertEqual(candidate_files(root), [entry]) + def test_metadata_contract(self): product, initialized = validate(ROOT, allow_template=True) self.assertTrue(product) diff --git a/tests/test_svg_geometry.py b/tests/test_svg_geometry.py new file mode 100644 index 0000000..be63d24 --- /dev/null +++ b/tests/test_svg_geometry.py @@ -0,0 +1,131 @@ +"""Physical sizes, SVG viewport mapping and sketch frame alignment.""" + +import io +import math +import re +import unittest +import xml.etree.ElementTree as ET + +from InsertTo.svg_geometry import MM_PER_PX, SVG, normalized_svg, placement, read_svg + + +def document(attributes, content=''): + source = f'{content}' + return read_svg(io.BytesIO(source.encode('utf-8'))) + + +class GeometryTests(unittest.TestCase): + def test_physical_units_and_css_pixels(self): + for value in ('25.4mm', '2.54cm', '101.6Q', '1in', '72pt', '6pc', '96px', '96'): + with self.subTest(value=value): + doc = document(f'width="{value}" height="50mm"') + self.assertAlmostEqual(doc.width_mm, 25.4) + self.assertEqual(doc.height_mm, 50) + self.assertEqual(doc.viewport_transform, (1, 1, 0, 0)) + + def test_style_and_missing_dimension(self): + doc = document('width="1" style="width: 50mm" viewBox="5 -5 100 50"') + self.assertEqual((doc.width_mm, doc.height_mm), (50, 25)) + doc = document('height="100%" width="100%" viewBox="-20 15 96 48"') + self.assertAlmostEqual(doc.width_mm, 25.4) + self.assertAlmostEqual(doc.height_mm, 12.7) + + def test_off_center_viewport_alignment(self): + doc = document('width="200" height="100" viewBox="-10 20 50 50"') + self.assertEqual(doc.viewport_transform, (2, 2, 70, -40)) + doc = document('width="200" height="100" viewBox="-10 20 50 50" preserveAspectRatio="none"') + self.assertEqual(doc.viewport_transform, (4, 2, 40, -40)) + + def test_fit_and_stretch(self): + doc = document('width="50mm" height="20mm"') + fit = placement(doc, (-10, -5, 90, 75), 'fit') + self.assertEqual((fit.left_mm, fit.bottom_mm, fit.width_mm, fit.height_mm), (-10, 15, 100, 40)) + stretch = placement(doc, (-10, -5, 90, 75), 'stretch') + self.assertEqual((stretch.left_mm, stretch.bottom_mm, stretch.width_mm, stretch.height_mm), (-10, -5, 100, 80)) + + def test_all_nine_anchors_including_oversize_svg(self): + doc = document('width="50mm" height="20mm"') + for row, y in (('top', 20), ('center', 25), ('bottom', 30)): + for column, x in (('left', 10), ('center', -10), ('right', -30)): + anchor = 'center' if row == column == 'center' else f'{row}-{column}' + with self.subTest(anchor=anchor): + rect = placement(doc, (10, 30, 20, 40), 'original', anchor) + self.assertEqual((rect.width_mm, rect.height_mm), (50, 20)) + self.assertEqual((rect.left_mm, rect.bottom_mm), (x, y)) + + def test_normalization_preserves_margins_and_transforms_during_stretch(self): + doc = document('width="200px" height="100px" viewBox="-10 20 50 50"', + '') + target = placement(doc, (17, -34, 17 + 100 * MM_PER_PX, -34 + 200 * MM_PER_PX), 'stretch') + root = ET.fromstring(normalized_svg(doc, target)) + self.assertEqual(root.get('viewBox'), '0 0 100 200') + self.assertEqual(root[0].get('transform'), 'matrix(1 0 0 4 35 -80)') + self.assertEqual(root[0][0][0].get('transform'), 'translate(5 8)') + rect = root.find(f'.//{{{SVG}}}rect') + self.assertEqual((rect.get('x'), rect.get('width')), ('5', '96')) + self.assertEqual(doc.root[0][0].get('x'), '10%') + + def test_rotated_canvas_encloses_all_corners_and_preserves_orientation(self): + doc = document('width="120" height="80" viewBox="5 -9 120 80"') + target = placement(doc, (0, 0, 90, 50), 'original') + for degrees in (30, 90, 155, -65, -130): + with self.subTest(degrees=degrees): + angle = math.radians(degrees) + root = ET.fromstring(normalized_svg(doc, target, rotation=angle)) + a, b, c, d, e, f = map(float, root[0].get('transform')[7:-1].split()) + points = [(a*x+c*y+e, b*x+d*y+f) + for x in (5, 125) for y in (-9, 71)] + xs, ys = zip(*points) + self.assertAlmostEqual(min(xs), 0) + self.assertAlmostEqual(min(ys), 0) + self.assertAlmostEqual(max(xs), float(root.get('width'))) + self.assertAlmostEqual(max(ys), float(root.get('height'))) + # Top edge of the source viewport points up for a positive angle. + self.assertAlmostEqual(xs[2] - xs[0], 120 * math.cos(angle)) + self.assertAlmostEqual(ys[2] - ys[0], -120 * math.sin(angle)) + + def test_stretched_circle_uses_ellipse_and_path_arc_uses_beziers(self): + doc = document('width="100" height="100"', '' + '') + target = placement(doc, (0, 0, 80, 40), 'stretch') + xml = ET.fromstring(normalized_svg(doc, target)) + ellipse = xml.find(f'.//{{{SVG}}}ellipse') + self.assertEqual((ellipse.get('rx'), ellipse.get('ry')), ('50', '50')) + path = xml.find(f'.//{{{SVG}}}path').get('d') + self.assertNotIn('A', path) + segments = re.findall(r'C([^CZ]+)', path) + self.assertEqual(len(segments), 16) + current = (0, 50) + samples = [] + for segment in segments: + x1, y1, x2, y2, x3, y3 = map(float, segment.split()) + for k in range(11): + t = k / 10 + u = 1 - t + x = u**3*current[0] + 3*u*u*t*x1 + 3*u*t*t*x2 + t**3*x3 + y = u**3*current[1] + 3*u*u*t*y1 + 3*u*t*t*y2 + t**3*y3 + self.assertAlmostEqual(math.hypot(x - 50, y - 50), 50, delta=5e-6) + samples.append((x, y)) + current = (x3, y3) + xs, ys = zip(*samples) + self.assertEqual((min(xs), max(xs), min(ys), max(ys)), (0, 100, 0, 100)) + original = ET.fromstring(normalized_svg(doc, placement(doc, (0, 0, 80, 40), 'original'))) + self.assertIsNotNone(original.find(f'.//{{{SVG}}}circle')) + self.assertIn('A', original.find(f'.//{{{SVG}}}path').get('d')) + + def test_relative_compact_arcs_smooth_shorthand_and_degenerate_radii(self): + doc = document('width="10" height="10"', '') + xml = ET.fromstring(normalized_svg(doc, placement(doc, (0, 0, 50, 20), 'stretch'))) + path = xml.find(f'.//{{{SVG}}}path').get('d') + self.assertTrue(path.startswith('m1 2 l2 1 h1 v2 C')) + self.assertIn('13 4 c0 0 2 1 3 3 Z', path) + self.assertTrue(path.endswith('M0 0 L1 1')) + + def test_rejects_invalid_size_and_frame(self): + for attrs in ('width="0mm"', 'height="-1px"', 'viewBox="0 0 -1 4"', + 'viewBox="1,2,3"', 'width="1e309"', 'width="1rem"'): + with self.subTest(attrs=attrs), self.assertRaises(ValueError): + document(attrs) + with self.assertRaises(ValueError): + placement(document('width="25mm"'), (3, 5, 3, 10)) From 30e69b229a5a78c6c2726ad43ea4974dd5bc5257 Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 12:16:01 +0300 Subject: [PATCH 02/13] feat: keep fitted SVGs linked to their sketch frames --- .fusion-addin.json | 2 +- InsertTo/InsertTo.manifest | 4 +- InsertTo/InsertTo.py | 4 +- InsertTo/config.py | 2 +- InsertTo/dialog.py | 221 ++++++++++++++++++---- InsertTo/frame_link.py | 364 ++++++++++++++++++++++++++++++++++++ InsertTo/fusion_import.py | 156 +++++++++++++++- InsertTo/manipulator.py | 123 ++++++++++++ InsertTo/svg_geometry.py | 136 ++++++++++++-- README.md | 26 ++- README.ru.md | 26 ++- docs/DEVELOPMENT.md | 12 +- docs/DEVELOPMENT.ru.md | 12 +- tests/test_dialog.py | 107 ++++++++++- tests/test_frame_link.py | 74 ++++++++ tests/test_fusion_import.py | 85 ++++++++- tests/test_manipulator.py | 37 ++++ tests/test_svg_geometry.py | 83 +++++++- 18 files changed, 1374 insertions(+), 100 deletions(-) create mode 100644 InsertTo/frame_link.py create mode 100644 InsertTo/manipulator.py create mode 100644 tests/test_frame_link.py create mode 100644 tests/test_manipulator.py diff --git a/.fusion-addin.json b/.fusion-addin.json index 47d110a..d1160f5 100644 --- a/.fusion-addin.json +++ b/.fusion-addin.json @@ -1,6 +1,6 @@ { "name": "InsertTo", "display_name": "InsertTo", - "description": "Import SVG artwork into a sketch frame with accurate dimensions and live placement preview.", + "description": "Place SVG curves on a sketch plane or fit them to a linked frame with accurate dimensions and live preview.", "initialized": true } diff --git a/InsertTo/InsertTo.manifest b/InsertTo/InsertTo.manifest index e0528f7..03c4f4b 100644 --- a/InsertTo/InsertTo.manifest +++ b/InsertTo/InsertTo.manifest @@ -4,9 +4,9 @@ "id": "d4f953a4-7cc6-4027-9699-dc025ebc8966", "author": "Pavel Kuznetsov", "description": { - "": "Import SVG artwork into a sketch frame with accurate dimensions and live placement preview." + "": "Place SVG curves on a sketch plane or fit them to a linked frame with accurate dimensions and live preview." }, "version": "0.1.0", - "runOnStartup": false, + "runOnStartup": true, "supportedOS": "windows|mac" } diff --git a/InsertTo/InsertTo.py b/InsertTo/InsertTo.py index be2253d..ea5c6c4 100644 --- a/InsertTo/InsertTo.py +++ b/InsertTo/InsertTo.py @@ -5,7 +5,7 @@ import adsk.core -from . import config, dialog +from . import config, dialog, frame_link _RESOURCES = Path(__file__).parent / 'resources' @@ -56,6 +56,7 @@ def run(context): 'Smart Insert', str(_RESOURCES / 'smart-insert'), _MENU_ID, 'SketchImportSVG', False ) _menu.controls.addCommand(_definition) + frame_link.install(adsk.core.Application.get()) except Exception: stop(context) raise @@ -64,6 +65,7 @@ def run(context): def stop(context): global _menu, _created, _definition try: + frame_link.uninstall() if _menu and _menu.isValid: _menu.deleteMe() if _definition and _definition.isValid: diff --git a/InsertTo/config.py b/InsertTo/config.py index c28ba61..b627092 100644 --- a/InsertTo/config.py +++ b/InsertTo/config.py @@ -2,6 +2,6 @@ ADDIN_NAME = 'InsertTo' DISPLAY_NAME = 'InsertTo' -DESCRIPTION = 'Import SVG artwork into a sketch frame with accurate dimensions and live placement preview.' +DESCRIPTION = 'Place SVG curves on a sketch plane or fit them to a linked frame with accurate dimensions and live preview.' COMMAND_ID = '4FusionLab_InsertTo_77ac0485344b' INITIALIZED = True diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 94040ba..4404bc6 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -7,6 +7,7 @@ import adsk.fusion from . import fusion_import, svg_geometry +from .manipulator import TransformControls _RESOURCES = Path(__file__).with_name('resources') @@ -18,6 +19,15 @@ ) +_ALIGN_HORIZONTAL = (('Left', 'center-left'), ('Center', 'center'), ('Right', 'center-right')) +_ALIGN_VERTICAL = (('Top', 'top-center'), ('Center', 'center'), ('Bottom', 'bottom-center')) + + +def _show(control, visible): + if control.isVisible != visible: + control.isVisible = visible + + def _icon_list(inputs, id_, label, choices, default): control = inputs.addDropDownCommandInput( id_, label, adsk.core.DropDownStyles.LabeledIconDropDownStyle @@ -40,9 +50,13 @@ def notify(self, args): class _Dialog: def __init__(self, command): self.app = adsk.core.Application.get() + self.design = adsk.fusion.Design.cast(self.app.activeProduct) + self.owner_document = self.app.activeDocument self.sketch = adsk.fusion.Sketch.cast(self.app.activeEditObject) self.document = None self.bounds = None + self.frame_sketch = None + self.artwork_bounds = None self.file_error = '' self.preview_error = '' @@ -51,24 +65,52 @@ def __init__(self, command): inputs = command.commandInputs self.browse = inputs.addBoolValueInput('svgFile', 'SVG file', False, '', False) self.browse.text = 'Choose file…' + self.plane = inputs.addSelectionInput( + 'targetPlane', 'Sketch plane', 'Select a construction plane or a planar face' + ) + self.plane.addSelectionFilter('ConstructionPlanes') + self.plane.addSelectionFilter('PlanarFaces') + self.plane.setSelectionLimits(0, 1) + self.plane.tooltip = 'Create a sketch on this plane or face.' self.frame = inputs.addSelectionInput( - 'frame', 'Frame', 'Select a sketch profile or a closed contour' + 'frame', 'Frame (optional)', 'Select a sketch profile or a closed contour' ) self.frame.addSelectionFilter('Profiles') self.frame.addSelectionFilter('SketchCurves') - self.frame.setSelectionLimits(1, 0) - self.frame.tooltip = 'Select a profile, a closed curve, or curves forming one closed contour.' - self.scaling = _icon_list(inputs, 'scale', 'Scale', _MODES, 'fit') - self.anchor = _icon_list(inputs, 'anchor', 'Anchor', _ANCHORS, 'center') - self.anchor.tooltip = 'Align this point on the SVG page with the same point on the frame.' - self.anchor.isVisible = False + self.frame.setSelectionLimits(0, 0) + self.frame.tooltip = 'Select a profile or closed contour to fit the SVG to its frame.' + self.extent = inputs.addDropDownCommandInput( + 'svgBounds', 'Use bounds of', adsk.core.DropDownStyles.TextListDropDownStyle + ) + self.extent.listItems.add('SVG page', True) + self.extent.listItems.add('Artwork', False) + self.extent.tooltip = 'Artwork measures the imported paths and ignores empty margins in the SVG page.' + self.scaling = _icon_list(inputs, 'scale', 'Fit to frame', _MODES, 'fit') + self.anchor = _icon_list(inputs, 'anchor', 'Align from', _ANCHORS, 'center') + self.fit_x = _icon_list(inputs, 'fitAlignX', 'Align', _ALIGN_HORIZONTAL, 'center') + self.fit_y = _icon_list(inputs, 'fitAlignY', 'Align', _ALIGN_VERTICAL, 'center') + self.anchor.tooltip = 'Match this point on the source bounds to the same point on the frame.' + units = self.design.unitsManager.defaultLengthUnits if self.design else 'mm' + self.inset = inputs.addValueInput( + 'frameInset', 'Inset', units, adsk.core.ValueInput.createByReal(0) + ) + self.inset.minimumValue = 0 + self.inset.tooltip = 'Apply an equal margin inside all four sides of the frame.' + self.link = inputs.addBoolValueInput('linkFrame', 'Link to frame', True, '', True) + self.link.tooltip = 'Update the inserted curves when the source frame changes.' + self.transform = TransformControls(inputs, units) + self.command = command self.status = inputs.addTextBoxCommandInput('importStatus', '', '', 2, True) self.status.isFullWidth = True - self._status('Choose an SVG file.' if self.sketch else 'Edit a sketch to import an SVG.') + self._show_target_controls() + self._show_alignment(None) + self._status('Choose an SVG file.') self.handlers = [ _listen(command.inputChanged, adsk.core.InputChangedEventHandler, self._changed), _listen(command.validateInputs, adsk.core.ValidateInputsEventHandler, self._validate), _listen(command.executePreview, adsk.core.CommandEventHandler, self._preview), + _listen(command.mouseDragEnd, adsk.core.MouseEventHandler, self._dragged), + _listen(command.mouseDrag, adsk.core.MouseEventHandler, self._dragged), _listen(command.execute, adsk.core.CommandEventHandler, self._execute), ] @@ -88,6 +130,7 @@ def _choose_file(self): self.browse.text = Path(filename).name self.browse.tooltip = filename self.document = None + self.artwork_bounds = None self.file_error = '' try: self.document = svg_geometry.read_svg(filename) @@ -97,59 +140,164 @@ def _choose_file(self): def _changed(self, args): changed = args.input.id - if changed not in ('svgFile', 'frame', 'scale', 'anchor'): - return try: - if changed == 'svgFile': - if not self._choose_file(): - return - elif changed == 'frame': + if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor', + 'fitAlignX', 'fitAlignY', 'svgBounds', 'frameInset', 'linkFrame'): + if self.transform.handles(changed): + self.preview_error = '' + if self.transform.changed(changed): + self.command.doExecutePreview() + return + if changed == 'svgFile' and not self._choose_file(): + return + if changed in ('frame', 'targetPlane'): self.bounds = None - elif changed == 'scale': - self.anchor.isVisible = self._mode() == 'original' + self.frame_sketch = None + self._show_target_controls() self.preview_error = '' except Exception as exc: self.app.log(traceback.format_exc()) self.preview_error = str(exc) + def _dragged(self, args): + if self.transform.read_drag(): + self.preview_error = '' + self.command.doExecutePreview() + def _mode(self): + if not self.frame.selectionCount: + return 'original' return _MODES[self.scaling.selectedItem.index][1] - def _placement(self): - if not self.sketch or not self.sketch.isValid or self.app.activeEditObject != self.sketch: - raise ValueError('Edit a sketch to import an SVG.') + def _show_target_controls(self): + has_frame = bool(self.frame.selectionCount) + has_plane = bool(self.plane.selectionCount) + # Keep both available when starting outside a sketch. Once chosen, the + # active target stays visible so the user can clear or replace it. + _show(self.plane, self.sketch is None and (not has_frame or has_plane)) + _show(self.frame, self.sketch is not None or not has_plane or has_frame) + _show(self.scaling, has_frame) + _show(self.inset, has_frame) + _show(self.link, has_frame and self._mode() in ('fit', 'stretch')) + + def _show_alignment(self, fit_options): + _show(self.anchor, bool(self.frame.selectionCount) and self._mode() == 'original') + _show(self.fit_x, bool(fit_options and 'center-left' in fit_options)) + _show(self.fit_y, bool(fit_options and 'top-center' in fit_options)) + + def _destination(self): if self.document is None: raise ValueError(self.file_error or 'Choose an SVG file.') - if self.frame.selectionCount == 0: - raise ValueError('Select a sketch profile or a closed contour for the frame.') - if self.bounds is None: - entities = [self.frame.selection(i).entity for i in range(self.frame.selectionCount)] - self.bounds = fusion_import.frame_bounds(self.sketch, entities) - anchor = _ANCHORS[self.anchor.selectedItem.index][1] - return svg_geometry.placement(self.document, self.bounds, self._mode(), anchor) + if not self.design or not self.design.isValid or self.app.activeDocument != self.owner_document: + raise ValueError('Open a Fusion design to insert an SVG.') + if self.sketch and (not self.sketch.isValid or self.app.activeEditObject != self.sketch): + raise ValueError('The destination sketch is no longer being edited.') + if self.frame.selectionCount: + if self.plane.selectionCount: + raise ValueError('Choose a sketch frame or a new sketch plane.') + if self.bounds is None: + entities = [self.frame.selection(i).entity for i in range(self.frame.selectionCount)] + self.frame_sketch = self.sketch or entities[0].parentSketch + self.bounds = fusion_import.frame_bounds(self.frame_sketch, entities) + if not self.frame_sketch.isValid: + raise ValueError('The frame sketch is no longer available.') + return self.frame_sketch, None + if self.sketch: + return self.sketch, None + plane = self.plane.selection(0).entity if self.plane.selectionCount else None + fusion_import.validate_plane(plane) + return None, plane + + def _use_artwork(self): + return self.extent.selectedItem.index == 1 + + def _placements(self): + frame = self.bounds if self.frame.selectionCount else None + mode = self._mode() + artwork = self.artwork_bounds if self._use_artwork() else None + if frame and not self.inset.isValidExpression: + raise ValueError('Enter a valid inset distance.') + inset = self.inset.value * 10 if frame else 0 + fit_options = None + anchor = 'center' + if mode == 'fit': + fit_options = svg_geometry.fit_anchors(self.document, frame, bounds=artwork, inset_mm=inset) + if 'center-left' in fit_options: + anchor = _ALIGN_HORIZONTAL[self.fit_x.selectedItem.index][1] + elif 'top-center' in fit_options: + anchor = _ALIGN_VERTICAL[self.fit_y.selectedItem.index][1] + elif mode == 'original' and frame: + anchor = _ANCHORS[self.anchor.selectedItem.index][1] + self._show_alignment(fit_options) + settings = dict(mode=mode, anchor=anchor, bounds=artwork, inset_mm=inset) + baseline = svg_geometry.placement(self.document, frame, **settings) + dx, dy, angle, scale = self.transform.values() + settings.update(x_mm=dx, y_mm=dy, rotation=angle, scale=scale) + target = svg_geometry.placement(self.document, frame, **settings) + return baseline, target, settings + + def _dimensions(self, target): + left, bottom, right, top = target.selected_box + self._status(f'SVG page {self.document.width_mm:.6g} × {self.document.height_mm:.6g} mm\n' + f'Insert {right - left:.6g} × {top - bottom:.6g} mm') def _validate(self, args): try: - target = self._placement() + self._show_target_controls() + self._destination() + except Exception as exc: + args.areInputsValid = False + self._show_alignment(None) + self.transform.hide() + self._status(str(exc)) + return + try: if self.preview_error: raise ValueError(self.preview_error) + if self._use_artwork() and self.artwork_bounds is None: + # A temporary measuring sketch is allowed only in preview/execute. + self._show_alignment(None) + self._status('Measuring artwork…') + else: + _, target, _ = self._placements() + self._dimensions(target) + args.areInputsValid = True except Exception as exc: args.areInputsValid = False self._status(str(exc)) - return - args.areInputsValid = True - self._status(f'SVG {self.document.width_mm:.6g} × {self.document.height_mm:.6g} mm\n' - f'Insert {target.width_mm:.6g} × {target.height_mm:.6g} mm') + + def _insert(self, sketch, plane, preview): + destination = fusion_import.sketch_for_target(self.design, sketch, plane) + try: + if self._use_artwork() and self.artwork_bounds is None: + self.artwork_bounds = fusion_import.measure_artwork(destination, self.document) + baseline, target, settings = self._placements() + if preview: + self.transform.position(destination, baseline.pivot) + frame = self.bounds if self.frame.selectionCount else None + if frame and self.link.value and settings['mode'] in ('fit', 'stretch'): + from . import frame_link + + entities = [self.frame.selection(i).entity for i in range(self.frame.selectionCount)] + frame_link.insert(destination, self.document, target, entities, **settings) + else: + fusion_import.import_svg(destination, self.document, target, frame) + self._dimensions(target) + except Exception: + if sketch is None and destination.isValid: + destination.deleteMe() + raise def _preview(self, args): args.isValidResult = False try: - target = self._placement() - except (ValueError, RuntimeError) as exc: + sketch, plane = self._destination() + except Exception as exc: self._status(str(exc)) + self.transform.hide() return try: - fusion_import.import_svg(self.sketch, self.document, target, self.bounds) + self._insert(sketch, plane, preview=True) self.preview_error = '' # Fusion owns the preview transaction and rolls it back on change or Cancel. args.isValidResult = True @@ -160,12 +308,11 @@ def _preview(self, args): def _execute(self, args): try: - target = self._placement() - fusion_import.import_svg(self.sketch, self.document, target, self.bounds) + self._insert(*self._destination(), preview=False) except Exception as exc: self.app.log(traceback.format_exc()) args.executeFailed = True - args.executeFailedMessage = f'SVG import failed. {exc}' + args.executeFailedMessage = f'SVG insert failed. {exc}' def attach(command): diff --git a/InsertTo/frame_link.py b/InsertTo/frame_link.py new file mode 100644 index 0000000..ae31cea --- /dev/null +++ b/InsertTo/frame_link.py @@ -0,0 +1,364 @@ +"""Maintain fitted SVG geometry when a linked sketch frame changes.""" + +from dataclasses import dataclass +import json +import math +import traceback +from uuid import uuid4 + +from . import fusion_import, svg_geometry + + +_RECORD = '4FusionLab.InsertTo.FrameLink.v1' +_CURVES = '4FusionLab.InsertTo.LinkedCurves.v1' +_REFRESH = '4FusionLab_InsertTo_RefreshFrames' +_CHECK = '4FusionLab_InsertTo_CheckFrames' +_listeners = None + + +@dataclass(frozen=True) +class _Page: + width_mm: float + height_mm: float + + +def _pose(target): + return [target.left_mm, target.bottom_mm, target.width_mm, target.height_mm, target.rotation] + + +def _same_pose(a, b): + return all(math.isclose(x, y, rel_tol=1e-12, abs_tol=1e-7) for x, y in zip(a, b)) + + +def _matrix(old, new): + import adsk.core + + a, b, c, d, tx, ty = svg_geometry.placement_delta(old, new) + matrix = adsk.core.Matrix3D.create() + for row, values in enumerate(((a, c, 0, tx / 10), (b, d, 0, ty / 10))): + for col, value in enumerate(values): + matrix.setCell(row, col, value) + return matrix + + +def _frame_reference(sketch, selected): + import adsk.fusion + + frame = fusion_import.frame_bounds(sketch, selected) + profile = adsk.fusion.Profile.cast(selected[0]) + curves = list(selected) + if not profile and len(curves) == 1 and not fusion_import._closed_chain(curves): + curves = list(sketch.findConnectedCurves(selected[0])) + if not fusion_import._closed_chain(curves): + loop = fusion_import._isolated_profile_loop(sketch, selected[0]) + profile = loop.parentProfile if loop else None + if profile: + outer = next(loop for loop in profile.profileLoops if loop.isOuter) + curves = [edge.sketchEntity for edge in outer.profileCurves] + # Profile portions may be trimmed by intersections. In that case the + # whole defining curves do not represent the selected frame. + try: + candidate = fusion_import.frame_bounds(sketch, curves) + if not _same_pose((*frame, frame.angle), (*candidate, candidate.angle)): + curves = [] + except (ValueError, RuntimeError): + curves = [] + return {'curves': [c.entityToken for c in curves], + 'axis': fusion_import.capture_frame_axis(curves, frame), + 'profile': profile.entityToken if profile else None} + + +def _resolve_frame(design, sketch, reference): + def resolve(token): + entities = design.findEntityByToken(token) + if len(entities) == 1 and entities[0].parentSketch == sketch: + return entities[0] + return None + + # Whole source edges survive profile subdivision caused by the artwork. + curves = [resolve(token) for token in reference['curves']] + if curves and all(curves): + if reference.get('axis'): + oriented = fusion_import.resolve_frame_axis(curves, reference['axis']) + if oriented is not None: + return oriented + return fusion_import.frame_bounds(sketch, curves) + if reference['profile']: + profile = resolve(reference['profile']) + if profile: + return fusion_import.frame_bounds(sketch, [profile]) + raise ValueError('The linked frame is missing or has changed topology.') + + +def _source_geometry(sketch, doc): + component = sketch.parentComponent + scratch = component.sketches.addWithoutEdges(component.xYConstructionPlane) + try: + page = svg_geometry.Placement(0, 0, doc.width_mm, doc.height_mm) + fusion_import._insert_curves(scratch, doc, page) + result = [] + for curve in scratch.sketchCurves: + if not curve.isConstruction: + geometry = curve.geometry + result.append(geometry if geometry.objectType == 'adsk::core::NurbsCurve3D' + else geometry.asNurbsCurve) + return result + finally: + scratch.deleteMe() + + +def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, inset_mm=0, + x_mm=0, y_mm=0, rotation=0, scale=1): + """Create associative curves and their record in the preview/execute transaction.""" + if mode not in ('fit', 'stretch'): + raise ValueError('A frame link requires Fit or Stretch.') + reference = _frame_reference(sketch, list(frame_entities)) + geometry = _source_geometry(sketch, doc) + if not geometry: + raise ValueError('The SVG contains no curves that can be linked.') + matrix = _matrix(svg_geometry.Placement(0, 0, doc.width_mm, doc.height_mm), target) + link_id = uuid4().hex + added = [] + try: + for nurbs in geometry: + if not nurbs.transformBy(matrix): + raise ValueError('Fusion could not position a linked SVG curve.') + curve = sketch.sketchCurves.sketchFixedSplines.addByNurbsCurve(nurbs) + if not curve: + raise ValueError('Fusion could not create a linked SVG curve.') + added.append(curve) + curve.attributes.add(_CURVES, link_id, '1') + record = {'frame': reference, 'page': [doc.width_mm, doc.height_mm], + 'pose': _pose(target), 'count': len(added), + 'options': dict(mode=mode, anchor=anchor, bounds=bounds, inset_mm=inset_mm, + x_mm=x_mm, y_mm=y_mm, rotation=rotation, scale=scale)} + sketch.attributes.add(_RECORD, link_id, json.dumps(record)) + except Exception: + for curve in reversed(added): + if curve.isValid: + curve.deleteMe() + raise + + +def _changed(design, attr): + sketch = attr.parent + if not sketch or not sketch.isValid: + return None + record = json.loads(attr.value) + frame = _resolve_frame(design, sketch, record['frame']) + target = svg_geometry.placement(_Page(*record['page']), frame, **record['options']) + if _same_pose(record['pose'], _pose(target)): + return None + return record, target + + +def _owned_curves(design, attr): + sketch = attr.parent + curves = [tag.parent for tag in design.findAttributes(_CURVES, attr.name)] + return [c for c in curves if c and c.isValid and c.parentSketch == sketch] + + +class _RestoreFailed(RuntimeError): + """The entire Fusion command transaction must roll back.""" + + +def _refresh(attr, record, target, curves): + matrix = _matrix(svg_geometry.Placement(*record['pose']), target) + edits = [] + for curve in curves: + original = curve.geometry + updated = original.copy() + if not updated.transformBy(matrix): + raise ValueError('Fusion could not transform a linked curve.') + edits.append((curve, original, updated)) + + applied = [] + try: + for curve, original, updated in edits: + if not curve.replaceGeometry(updated): + raise ValueError('Fusion could not update a linked curve.') + applied.append((curve, original)) + attr.value = json.dumps(dict(record, pose=_pose(target))) + except Exception: + try: + for curve, original in reversed(applied): + if not curve.replaceGeometry(original): + raise _RestoreFailed('Fusion could not restore a linked curve.') + except Exception as error: + raise _RestoreFailed('Fusion could not restore the linked geometry.') from error + raise + + +def _attach(event, base, notify): + class Handler(base): + def notify(self, args): + notify(args) + + handler = Handler() + event.add(handler) + return event, handler + + +class _Listeners: + def __init__(self, app): + self.app = app + self.ui = app.userInterface + self.handlers = [] + self.pending = False + self.history_changed = False + self.suppressed = {} + self.definition = None + self.event = None + self.running = False + self.dispatched = False + + def start(self): + import adsk.core + + self.definition = self.ui.commandDefinitions.addButtonDefinition( + _REFRESH, 'Update linked SVG', 'Update SVG curves from their sketch frames.' + ) + self.event = self.app.registerCustomEvent(_CHECK) + self.handlers = [ + _attach(self.definition.commandCreated, adsk.core.CommandCreatedEventHandler, self.created), + _attach(self.event, adsk.core.CustomEventHandler, self.check), + _attach(self.ui.commandTerminated, adsk.core.ApplicationCommandEventHandler, self.terminated), + _attach(self.app.documentActivated, adsk.core.DocumentEventHandler, self.schedule), + _attach(self.app.documentOpened, adsk.core.DocumentEventHandler, self.schedule), + ] + self.schedule() + + def schedule(self, args=None): + if not self.pending and not self.running and not self.dispatched: + self.pending = True + self.app.fireCustomEvent(_CHECK) + + def terminated(self, args): + if args.commandId in (_REFRESH, 'SelectCommand'): + return + if 'undo' in args.commandId.lower() or 'redo' in args.commandId.lower(): + self.history_changed = True + self.schedule() + + def design(self): + import adsk.fusion + + design = adsk.fusion.Design.cast(self.app.activeProduct) + if design and (not design.timeline or design.timeline.markerPosition == design.timeline.count): + return design + return None + + def changes(self, design): + for attr in design.findAttributes(_RECORD, ''): + try: + change = _changed(design, attr) + except (ValueError, TypeError, RuntimeError, KeyError) as error: + self.app.log(f'Smart Insert frame link: {error}') + continue + key = (self.app.activeDocument.creationId, attr.name) + if self.history_changed: + if change: + self.suppressed[key] = _pose(change[1]) + else: + self.suppressed.pop(key, None) + elif change: + last = self.suppressed.get(key) + if last is None or not _same_pose(last, _pose(change[1])): + curves = _owned_curves(design, attr) + if len(curves) == change[0]['count']: + yield attr, *change, curves + else: + self.suppressed.pop(key, None) + + def check(self, args): + self.pending = False + if self.running or self.dispatched or self.ui.activeCommand != 'SelectCommand': + return + try: + design = self.design() + if design and next(self.changes(design), None): + self.dispatched = True + if not self.definition.execute(): + self.dispatched = False + self.history_changed = False + except Exception: + self.app.log(traceback.format_exc()) + + def created(self, args): + import adsk.core + + command = args.command + command.isAutoExecute = True + execute = _attach(command.execute, adsk.core.CommandEventHandler, self.execute) + self.handlers.append(execute) + + def destroyed(_args): + self.dispatched = False + self.handlers.remove(execute) + self.handlers.remove(destroy) + + destroy = _attach(command.destroy, adsk.core.CommandEventHandler, destroyed) + self.handlers.append(destroy) + + def execute(self, args): + self.running = True + try: + design = self.design() + if not design: + return + # A linked SVG can itself serve as the next SVG's frame. Resolve + # the full chain inside this same undoable command. + records = design.findAttributes(_RECORD, '') + for _ in range(len(records)): + updated = False + for attr, record, target, curves in self.changes(design): + try: + _refresh(attr, record, target, curves) + updated = True + except _RestoreFailed: + raise + except (ValueError, RuntimeError) as error: + self.suppressed[(self.app.activeDocument.creationId, attr.name)] = _pose(target) + self.app.log(f'Smart Insert frame link: {error}') + if not updated: + break + else: + if next(self.changes(design), None): + raise ValueError('The linked SVG frames have a circular dependency.') + except Exception as error: + # Failing a Fusion command rolls the whole refresh transaction back. + args.executeFailed = True + args.executeFailedMessage = f'Could not update linked SVG curves: {error}' + self.app.log(traceback.format_exc()) + finally: + self.running = False + + def stop(self): + for event, handler in reversed(self.handlers): + if event.isValid: + event.remove(handler) + self.handlers.clear() + if self.event: + self.app.unregisterCustomEvent(_CHECK) + if self.definition and self.definition.isValid: + self.definition.deleteMe() + + +def install(app): + global _listeners + if _listeners is None: + _listeners = _Listeners(app) + try: + _listeners.start() + except Exception: + uninstall() + raise + + +def uninstall(): + global _listeners + if _listeners: + try: + _listeners.stop() + finally: + _listeners = None diff --git a/InsertTo/fusion_import.py b/InsertTo/fusion_import.py index e206626..7f9084f 100644 --- a/InsertTo/fusion_import.py +++ b/InsertTo/fusion_import.py @@ -51,6 +51,56 @@ def _rectangle_angle(geometry): return 0.0 if abs(angle) < 1e-12 else angle +def resolve_frame_axis(curves, axis): + """Recover a linked rectangle from its original, directed horizontal edge.""" + if axis is None or len(curves) != 4: + return None + geometry = [curve.geometry for curve in curves] + if any(line.objectType != 'adsk::core::Line3D' for line in geometry): + return None + edge = geometry[axis['index']] + dx = (edge.endPoint.x - edge.startPoint.x) * axis['sign'] + dy = (edge.endPoint.y - edge.startPoint.y) * axis['sign'] + angle = math.atan2(dy, dx) + sides = [(_rotate(*_xy(line.startPoint), -angle), _rotate(*_xy(line.endPoint), -angle)) + for line in geometry] + xs, ys = zip(*(point for side in sides for point in side)) + left, right, bottom, top = min(xs), max(xs), min(ys), max(ys) + tol = 1e-6 # Fusion point tolerance, cm + if right - left <= tol or top - bottom <= tol: + return None + corners = ((left, bottom), (right, bottom), (right, top), (left, top)) + edges = set() + for side in sides: + indices = [] + for point in side: + index = min(range(4), key=lambda i: math.dist(point, corners[i])) + if math.dist(point, corners[index]) > tol: + return None + indices.append(index) + edges.add(tuple(sorted(indices))) + if edges != {(0, 1), (1, 2), (2, 3), (0, 3)}: + return None + return Frame((left * 10, bottom * 10, right * 10, top * 10), angle) + + +def capture_frame_axis(curves, frame): + """Persist an edge index in the link's ordered token list and its sense.""" + if len(curves) != 4: + return None + co, si = math.cos(frame.angle), math.sin(frame.angle) + for index, curve in enumerate(curves): + line = curve.geometry + if line.objectType != 'adsk::core::Line3D': + return None + dx, dy = line.endPoint.x - line.startPoint.x, line.endPoint.y - line.startPoint.y + length = math.hypot(dx, dy) + if length and abs(co * dy - si * dx) <= 1e-7 * length: + axis = {'index': index, 'sign': 1 if dx * co + dy * si >= 0 else -1} + return axis if resolve_frame_axis(curves, axis) is not None else None + return None + + def _closed_chain(curves): """Check all selected segments form one cycle, including coincident endpoints.""" if len(curves) == 1 and curves[0].objectType in ( @@ -123,7 +173,6 @@ def frame_bounds(sketch, entities): raise ValueError('Choose one profile, or only curves from one contour.') outer = next(loop for loop in profile.profileLoops if loop.isOuter) geometry = [curve.geometry for curve in outer.profileCurves] - boxes = [profile.boundingBox] else: curves = [adsk.fusion.SketchCurve.cast(e) for e in entities] if not all(curves): @@ -136,18 +185,22 @@ def frame_bounds(sketch, entities): loop = _isolated_profile_loop(sketch, seed) if loop is not None: geometry = [edge.geometry for edge in loop.profileCurves] - boxes = [edge.boundingBox for edge in loop.profileCurves] else: if not _closed_chain(curves): raise ValueError('Choose one closed contour, or select its shaded profile.') geometry = [curve.geometry for curve in curves] - boxes = [curve.boundingBox for curve in curves] angle = _rectangle_angle(geometry) - if angle: + if all(g.objectType == 'adsk::core::Line3D' for g in geometry): points = [_rotate(*_xy(p), -angle) for g in geometry for p in (g.startPoint, g.endPoint)] else: - points = [_xy(p) for box in boxes for p in (box.minPoint, box.maxPoint)] + # Fusion can expose the previous display boundingBox after loading a + # changed sketch. Its current transient curve geometry is authoritative. + wire, _ = adsk.fusion.TemporaryBRepManager.get().createWireFromCurves(geometry, True) + if not wire: + raise ValueError('Fusion could not measure the selected frame.') + box = wire.preciseBoundingBox + points = [_xy(box.minPoint), _xy(box.maxPoint)] x, y = zip(*points) bounds = (min(x) * 10, min(y) * 10, max(x) * 10, max(y) * 10) if bounds[2] <= bounds[0] or bounds[3] <= bounds[1]: @@ -155,11 +208,43 @@ def frame_bounds(sketch, entities): return Frame(bounds, angle) -def import_svg(sketch, doc, target, frame): - """Create editable native geometry using the same operation for preview and commit.""" - svg = svg_geometry.normalized_svg(doc, target, rotation=frame.angle) +def validate_plane(plane_or_face): + """Validate the command selection without changing the model.""" + import adsk.core + import adsk.fusion + + if plane_or_face and plane_or_face.isValid: + if adsk.fusion.ConstructionPlane.cast(plane_or_face): + return + face = adsk.fusion.BRepFace.cast(plane_or_face) + if face and adsk.core.Plane.cast(face.geometry): + return + raise ValueError('Select a construction plane or a planar face.') + + +def sketch_for_target(design, active_sketch, plane_or_face): + """Resolve the destination inside a preview or execute transaction.""" + if active_sketch is not None: + if not active_sketch.isValid: + raise ValueError('The destination sketch is no longer available.') + return active_sketch + validate_plane(plane_or_face) + sketches = design.activeComponent.sketches + occurrence = design.activeOccurrence + if occurrence: + sketch = sketches.addWithoutEdges(plane_or_face, occurrence) + else: + sketch = sketches.addWithoutEdges(plane_or_face) + if sketch is None: + raise ValueError('Fusion could not create a sketch on the selected plane.') + sketch.name = 'Smart Insert SVG' + return sketch + + +def _insert_curves(sketch, doc, target): + svg = svg_geometry.normalized_svg(doc, target, rotation=target.rotation) x0, y0 = target.left_mm, target.bottom_mm - corners = [_rotate(x, y, frame.angle) + corners = [_rotate(x, y, target.rotation) for x in (x0, x0 + target.width_mm) for y in (y0, y0 + target.height_mm)] # Fusion inserts at the SVG viewport's upper-left corner, in sketch cm. @@ -171,3 +256,56 @@ def import_svg(sketch, doc, target, frame): before = sketch.sketchCurves.count if not sketch.importSVG(str(path), left_cm, top_cm, 1.0) or sketch.sketchCurves.count <= before: raise ValueError('Fusion found no importable sketch curves in the SVG.') + + +def measure_artwork(sketch, doc): + """Measure only imported paths at 1:1, in mm relative to the SVG page.""" + import adsk.fusion + + component = sketch.parentComponent + scratch = component.sketches.addWithoutEdges(component.xYConstructionPlane) + try: + _insert_curves(scratch, doc, svg_geometry.Placement(0, 0, doc.width_mm, doc.height_mm)) + # A fresh sketch excludes existing geometry and projected face edges. + # Curve.geometry is in sketch space. Kernel extrema also handle splines + # whose control hull extends beyond the artwork itself. + manager = adsk.fusion.TemporaryBRepManager.get() + curves = [curve.geometry for curve in scratch.sketchCurves if not curve.isConstruction] + if not curves: + raise ValueError('The SVG contains no measurable curves.') + wire, _ = manager.createWireFromCurves(curves, True) + if wire is None: + raise ValueError('Fusion could not measure the imported artwork.') + box = wire.preciseBoundingBox + return (box.minPoint.x * 10, box.minPoint.y * 10, + box.maxPoint.x * 10, box.maxPoint.y * 10) + finally: + scratch.deleteMe() + + +def _add_outline(sketch, outline): + import adsk.core + + points = [adsk.core.Point3D.create(x / 10, y / 10, 0) for x, y in outline] + lines = sketch.sketchCurves.sketchLines + # In page-local coordinates, line artwork collapses one pair of sides. + # Rotation preserves edge lengths. Use Fusion's point tolerance in mm. + tolerance_mm = 1e-5 + if min(math.dist(outline[0], outline[i]) for i in (1, 3)) <= tolerance_mm: + if math.dist(outline[0], outline[2]) > tolerance_mm: + lines.addByTwoPoints(points[0], points[2]).isConstruction = True + return + first = lines.addByTwoPoints(points[0], points[1]) + first.isConstruction = True + previous = first.endSketchPoint + for end in (points[2], points[3], first.startSketchPoint): + line = lines.addByTwoPoints(previous, end) + line.isConstruction = True + previous = line.endSketchPoint + + +def import_svg(sketch, doc, target, frame): + """Draw the same sketch entities for native preview and commit.""" + _insert_curves(sketch, doc, target) + if frame is None: + _add_outline(sketch, target.outline) diff --git a/InsertTo/manipulator.py b/InsertTo/manipulator.py new file mode 100644 index 0000000..ad0a259 --- /dev/null +++ b/InsertTo/manipulator.py @@ -0,0 +1,123 @@ +"""Planar Fusion triad shared by the Transform fields and the on-canvas handles.""" + +import math + +import adsk.core + + +class TransformControls: + def __init__(self, inputs, length_units): + self.group = inputs.addGroupCommandInput('transformGroup', 'Transform') + children = self.group.children + real = adsk.core.ValueInput.createByReal + self.fields = [ + children.addValueInput('offsetX', 'Move X', length_units, real(0)), + children.addValueInput('offsetY', 'Move Y', length_units, real(0)), + children.addValueInput('rotateSVG', 'Rotation', 'deg', real(0)), + children.addValueInput('scaleSVG', 'Scale factor', '', real(1)), + ] + self.fields[-1].minimumValue = 0 + self.fields[-1].isMinimumLimited = True + self.fields[-1].isMinimumInclusive = False + self._properties = ('xTranslation', 'yTranslation', 'zRotation', 'xYPlaneScaleFactor') + self._last_values = (0., 0., 0., 1.) + self.group.isExpanded = True + self.group.isVisible = False + self.triad = None + self._basis = None + self._updating = False + + def handles(self, input_id): + return not self._updating and ( + input_id == 'placementTransform' or any(f.id == input_id for f in self.fields) + ) + + def changed(self, input_id): + if self._updating: + return False + for field, prop in zip(self.fields, self._properties): + if field.id == input_id and field.isValidExpression and self.triad: + if prop == 'xYPlaneScaleFactor' and field.value <= 0: + return False + self._updating = True + try: + setattr(self.triad, prop, field.value) + self._last_values = self._triad_values() + finally: + self._updating = False + return True + return self.read_drag() + + def _triad_values(self): + return tuple(getattr(self.triad, prop) for prop in self._properties) + + def read_drag(self): + if self._updating or self.triad is None or not self.group.isVisible: + return False + values = self._triad_values() + if all(math.isclose(a, b, abs_tol=1e-10) for a, b in zip(values, self._last_values)): + return False + self._updating = True + try: + for field, previous, current in zip(self.fields, self._last_values, values): + if not math.isclose(previous, current, abs_tol=1e-10): + field.value = current + self._last_values = values + finally: + self._updating = False + return True + + def hide(self): + if self.group.isVisible: + self.group.isVisible = False + + def values(self): + if not all(f.isValidExpression for f in self.fields): + raise ValueError('Enter valid Transform distances, angle and scale.') + x, y, angle, factor = (field.value for field in self.fields) + if not all(map(math.isfinite, (x, y, angle, factor))) or factor <= 0: + raise ValueError('Transform requires a positive scale and finite coordinates.') + return x * 10, y * 10, angle, factor + + def position(self, sketch, pivot_xy_mm): + """Keep the original triad basis stable throughout dragging and preview rollback.""" + if sketch.assemblyContext is None: + occurrence = sketch.parentComponent.parentDesign.activeOccurrence + if occurrence and occurrence.component == sketch.parentComponent: + sketch = sketch.createForAssemblyContext(occurrence) + point = adsk.core.Point3D.create + x, y = (v / 10 for v in pivot_xy_mm) + origin = sketch.sketchToModelSpace(point(x, y, 0)) + vx = origin.vectorTo(sketch.sketchToModelSpace(point(x + 1, y, 0))) + vy = origin.vectorTo(sketch.sketchToModelSpace(point(x, y + 1, 0))) + basis = (*origin.asArray(), *vx.asArray(), *vy.asArray()) + if self._basis and all(abs(a - b) < 1e-8 for a, b in zip(self._basis, basis)): + if not self.group.isVisible: + self.group.isVisible = True + return + + self._updating = True + try: + if self.triad: + self.triad.deleteMe() + self.triad = None + self._basis = None + initial = adsk.core.Matrix3D.create() + initial.setWithCoordinateSystem(origin, vx, vy, vx.crossProduct(vy)) + triad = self.group.children.addTriadCommandInput('placementTransform', initial) + self.triad = triad + triad.hideAll() + triad.isXTranslationVisible = True + triad.isYTranslationVisible = True + triad.isXYPlaneTranslationVisible = True + triad.isZRotationVisible = True + triad.isXYPlaneScalingVisible = True + for prop, field in zip(self._properties, self.fields): + setattr(triad, prop, field.value) + self._last_values = self._triad_values() + self._basis = basis + self.group.isVisible = True + triad.isVisible = True + triad.isEnabled = True + finally: + self._updating = False diff --git a/InsertTo/svg_geometry.py b/InsertTo/svg_geometry.py index e9b1cf3..4204404 100644 --- a/InsertTo/svg_geometry.py +++ b/InsertTo/svg_geometry.py @@ -1,7 +1,7 @@ """SVG viewport sizing and placement in sketch coordinates (millimetres, Y up).""" import copy -from dataclasses import dataclass +from dataclasses import dataclass, field import math import re import xml.etree.ElementTree as ET @@ -40,6 +40,29 @@ class Placement: bottom_mm: float width_mm: float height_mm: float + rotation: float = 0.0 + # Artwork extent in the same pre-rotation plane as the placed SVG page. + artwork_box: tuple = None + pivot: tuple = field(default=None, compare=False) + + @property + def selected_box(self): + if self.artwork_box is not None: + return self.artwork_box + return (self.left_mm, self.bottom_mm, + self.left_mm + self.width_mm, self.bottom_mm + self.height_mm) + + @property + def outline(self): + left, bottom, right, top = self.selected_box + return tuple(_rotate(x, y, self.rotation) for x, y in ( + (left, bottom), (right, bottom), (right, top), (left, top) + )) + + +def _rotate(x, y, angle): + cosine, sine = math.cos(angle), math.sin(angle) + return cosine * x - sine * y, sine * x + cosine * y def _positive(value, label): @@ -134,26 +157,103 @@ def read_svg(path): return SvgDocument(root, w, h, box, transform) -def placement(doc, frame, mode='fit', anchor='center'): - """Align the SVG viewport to the selected frame bounding box, both in mm.""" - xmin, ymin, xmax, ymax = frame +def _source_box(doc, bounds): + if bounds is None: + return (0, 0, doc.width_mm, doc.height_mm) + x0, y0, x1, y1 = bounds + if not all(map(math.isfinite, bounds)) or x1 < x0 or y1 < y0 or (x0, y0) == (x1, y1): + raise ValueError('The SVG artwork has no measurable curve extent.') + return bounds + + +def _inner_frame(frame, inset_mm): + if not math.isfinite(inset_mm) or inset_mm < 0: + raise ValueError('Inset must be a finite, nonnegative distance.') if not all(map(math.isfinite, frame)): raise ValueError('The selected frame must have finite coordinates.') - fw = _positive(xmax - xmin, 'Frame width') - fh = _positive(ymax - ymin, 'Frame height') - if mode == 'fit': - scale = min(fw / doc.width_mm, fh / doc.height_mm) - w, h = doc.width_mm * scale, doc.height_mm * scale - elif mode == 'stretch': - w, h = fw, fh - elif mode == 'original': - w, h = doc.width_mm, doc.height_mm - else: - raise ValueError('Select a supported scale mode.') - if mode == 'original' and anchor not in _ANCHORS: + x0, y0, x1, y1 = frame + w, h = x1 - x0 - 2 * inset_mm, y1 - y0 - 2 * inset_mm + if w <= 0 or h <= 0: + raise ValueError('The frame must have positive width and height after applying the inset.') + return x0 + inset_mm, y0 + inset_mm, w, h + + +def _fit_scale(w, h, fw, fh): + # A horizontal or vertical line is a valid drawing, also when fitted. + return min(fw / w if w else math.inf, fh / h if h else math.inf) + + +def fit_anchors(doc, frame, *, bounds=None, inset_mm=0): + """Offer alignment along just the axis with remaining space after fitting.""" + x0, y0, x1, y1 = _source_box(doc, bounds) + _, _, fw, fh = _inner_frame(frame, inset_mm) + w, h = x1 - x0, y1 - y0 + factor = _fit_scale(w, h, fw, fh) + if not math.isclose(factor * w, fw, rel_tol=1e-10, abs_tol=1e-9): + return ('center-left', 'center', 'center-right') + if not math.isclose(factor * h, fh, rel_tol=1e-10, abs_tol=1e-9): + return ('top-center', 'center', 'bottom-center') + return ('center',) + + +def placement(doc, frame, mode='fit', anchor='center', *, bounds=None, inset_mm=0, + x_mm=0, y_mm=0, rotation=0, scale=1): + """Place a page or measured drawing, expressed in original page-local Y-up mm. + + A free placement maps its anchor directly to the given sketch point. With a + frame, rotation follows the local frame axes and offsets use the sketch axes. + """ + if anchor not in _ANCHORS: raise ValueError('Select a supported anchor.') - ax, ay = _ANCHORS[anchor] if mode == 'original' else _ANCHORS['center'] - return Placement(xmin + ax * (fw - w), ymin + ay * (fh - h), w, h) + if not all(map(math.isfinite, (x_mm, y_mm, rotation))): + raise ValueError('Placement coordinates and angle must be finite.') + _positive(scale, 'Scale') + bx, by, right, top = _source_box(doc, bounds) + w, h = right - bx, top - by + ax, ay = _ANCHORS[anchor] + sx = sy = scale + if frame is None: + pivot_x, pivot_y = x_mm, y_mm + else: + xmin, ymin, fw, fh = _inner_frame(frame, inset_mm) + if mode == 'fit': + sx = sy = scale * _fit_scale(w, h, fw, fh) + elif mode == 'stretch': + if not w or not h: + raise ValueError('Stretch requires artwork with both width and height.') + sx, sy = scale * fw / w, scale * fh / h + elif mode != 'original': + raise ValueError('Select a supported scale mode.') + frame_angle = getattr(frame, 'angle', 0) + pivot_x, pivot_y = _rotate(xmin + ax * fw, ymin + ay * fh, frame_angle) + pivot_x, pivot_y = pivot_x + x_mm, pivot_y + y_mm + rotation += frame_angle + local_x, local_y = _rotate(pivot_x, pivot_y, -rotation) + left = local_x - (bx + ax * w) * sx + bottom = local_y - (by + ay * h) * sy + artwork_box = None if bounds is None else ( + left + bx * sx, bottom + by * sy, left + right * sx, bottom + top * sy + ) + return Placement(left, bottom, doc.width_mm * sx, doc.height_mm * sy, + rotation, artwork_box, (pivot_x, pivot_y)) + + +def placement_delta(old, new): + """Map old sketch coordinates to new ones in mm: (a*x+c*y+tx, b*x+d*y+ty). + + Both placements describe the same SVG page. The full page carries the + artwork offset even when positioning was computed from measured curves. + """ + sx = new.width_mm / _positive(old.width_mm, 'Previous page width') + sy = new.height_mm / _positive(old.height_mm, 'Previous page height') + # Rotate back to the old page axes, resize, then rotate into the new axes. + co, so = math.cos(old.rotation), math.sin(old.rotation) + cn, sn = math.cos(new.rotation), math.sin(new.rotation) + a, c = cn * sx * co + sn * sy * so, cn * sx * so - sn * sy * co + b, d = sn * sx * co - cn * sy * so, sn * sx * so + cn * sy * co + tx, ty = _rotate(new.left_mm - sx * old.left_mm, + new.bottom_mm - sy * old.bottom_mm, new.rotation) + return a, b, c, d, tx, ty def _format(value): diff --git a/README.md b/README.md index 19ea660..0bbd90d 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,32 @@ # InsertTo -Insert SVG artwork into an Autodesk Fusion sketch at its physical size or scale it to a selected frame. +Place SVG curves in an Autodesk Fusion sketch at their physical size, or fit them to a sketch profile. [Русская версия](README.ru.md) · [Report an issue](https://github.com/4FusionLab/InsertTo/issues) ## Insert an SVG -1. Edit a sketch and open **Insert → Smart Insert → SVG**. -2. Choose the SVG file. For **Frame**, select a shaded profile or a closed sketch contour. You can select one edge of an isolated closed chain or select the segments individually. -3. Choose a scale mode and check the preview and dimensions. Click **Insert** to keep the curves, or **Cancel** to discard the preview. +1. On the **Solid** or **Sketch** tab, open **Insert → Smart Insert → SVG** and choose the file. While editing a sketch, the curves go into that sketch. Outside sketch editing, select a construction plane or planar face in **Sketch plane** to create a sketch, or select a profile or contour in an existing sketch to insert there. +2. Choose **Use bounds of → SVG page** to include the file’s blank margins. Choose **Artwork** to position and scale the extents of the curves Fusion can import. +3. For free placement, leave **Frame (optional)** empty. The selected bounds start at their original size, centered on the sketch origin. Use **Transform** to move, rotate or uniformly scale the drawing with the handles or numeric inputs. Construction lines outline the selected bounds. +4. To fit the SVG to a frame, select a shaded profile or a closed sketch contour. One edge selects an isolated closed chain. You can also select its segments individually. Choose **Fit to frame** and, if needed, set an equal **Inset** on all four sides. +5. Check the preview and the dimensions beside **Insert** in the dialog. Click **Insert** to keep the curves or **Cancel** to discard the preview. -| Scale | Placement | +| Fit to frame | Result before manual transforms | | --- | --- | -| Fit | Centers the SVG page and scales it proportionally until one dimension meets the frame. | -| Stretch | Scales width and height independently to fill the frame. | -| Original size | Preserves the SVG page size. Choose one of nine anchors to align matching corners, edge midpoints or centers on the page and frame. | +| Fit | Preserves proportions and fits the selected bounds inside the inset frame. If there is spare space, **Align** offers three positions along that axis. | +| Stretch | Sets width and height independently to fill the inset frame. | +| Original size | Preserves the SVG’s physical dimensions. Use **Align from** to match any of nine points on the selected bounds to the corresponding point on the inset frame. | -A rectangular frame follows its sketch edges, including rotated rectangles. Other closed contours supply their bounding rectangle along the sketch axes. Curves can extend outside an irregular contour. Placement includes blank margins in the SVG page. A 50 mm page stays 50 mm wide in **Original size**. SVGs using pixels use 96 px per inch. The result consists of the vector curves supported by Fusion’s SVG importer. +In **Fit** and **Stretch**, **Link to frame** is enabled by default. InsertTo creates fixed splines for the SVG. Move the frame to move the drawing with it, or edit the frame dimensions to resize it. Fusion records the frame edit and the automatic SVG update as two undo steps. Keep InsertTo running so it can update the splines after the edit. For individually editable SVG curves, turn off **Link to frame** before inserting. To link a drawing inserted with an earlier version, insert it again with the option enabled. + +For example, fitting a 50 × 20 mm page in an 80 × 60 mm frame gives 80 × 32 mm. With **Align → Center**, there is 14 mm above and below. With **Align → Top**, the upper edges coincide and the 28 mm of spare space is below. This example uses a zero inset. + +A rectangular frame follows the direction of its sketch edges. Other closed contours use their bounding rectangle along the sketch axes, so the SVG can extend outside an irregular outline. A page declared 50 mm wide stays 50 mm wide at original size and scale 1. SVG pixel dimensions use 96 px per inch. ## Verified in Fusion -On macOS, Fusion 2706.1.17 produced a 50 × 50 mm sketch from a 50 mm medallion SVG. A 50 × 20 mm test drawing in an 80 × 60 mm frame measured 80 × 32 mm in **Fit** and 80 × 60 mm in **Stretch**. Native Windows acceptance is pending. +On macOS, Fusion 2706.1.17 produced a 50 × 50 mm sketch from a 50 mm medallion SVG. A 50 × 20 mm test drawing in an 80 × 60 mm frame measured 80 × 32 mm in **Fit** and 80 × 60 mm in **Stretch**. With **Stretch** and **Link to frame**, changing an 80 × 50 mm rectangular frame to 100 × 50 mm resized the linked ellipse after the edit. The 5 mm inset was preserved, and a 10 mm extrusion based on that profile updated from 21.99 to 28.27 cm³. Moving the frame 12 mm right and 4 mm down moved both linked drawings by the same amounts. For Fit, Stretch and free placement with the scale handle, the preview and inserted curves had matching bounds. Native Windows acceptance is pending. ## Install from source diff --git a/README.ru.md b/README.ru.md index c06a2cd..fab11b9 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,26 +1,32 @@ # InsertTo -Вставляет SVG в эскиз Autodesk Fusion с сохранением физических размеров или масштабирует рисунок по выбранной рамке. +Вставляет кривые SVG в эскиз Autodesk Fusion в исходном физическом размере или вписывает их в профиль эскиза. [English](README.md) · [Сообщить о проблеме](https://github.com/4FusionLab/InsertTo/issues) ## Вставка SVG -1. Откройте эскиз на редактирование и выберите **Insert → Smart Insert → SVG**. -2. Укажите файл SVG. В поле **Frame** выберите закрашенный профиль или замкнутый контур эскиза. У изолированной замкнутой цепочки достаточно выбрать одно ребро. Также можно выбрать сегменты по отдельности. -3. Выберите режим и проверьте предпросмотр и размеры. Нажмите **Insert**, чтобы добавить кривые, или **Cancel**, чтобы отменить вставку. +1. На вкладке **Solid** или **Sketch** откройте **Insert → Smart Insert → SVG** и выберите файл. Если эскиз открыт на редактирование, кривые появятся в нём. Вне режима редактирования выберите в **Sketch plane** конструкционную плоскость или плоскую грань для нового эскиза. Чтобы вставить рисунок в существующий эскиз, укажите его профиль или контур. +2. В поле **Use bounds of** выберите **SVG page**, чтобы учитывать пустые поля страницы. Выберите **Artwork**, чтобы разместить и масштабировать рисунок по габаритам кривых, которые импортирует Fusion. +3. Для свободной вставки оставьте **Frame (optional)** пустым. Рисунок появится в исходном размере, а центр выбранной области совпадёт с началом координат эскиза. В разделе **Transform** можно переместить, повернуть и пропорционально масштабировать рисунок ручками в эскизе или вводом чисел. Вспомогательные линии показывают границы выбранной области. +4. Для вставки в рамку выберите закрашенный профиль или замкнутый контур эскиза. У изолированной замкнутой цепочки достаточно выбрать одно ребро. Также можно выбрать сегменты по отдельности. Выберите режим **Fit to frame**. Поле **Inset** задаёт одинаковый отступ внутрь со всех четырёх сторон. +5. Проверьте предпросмотр и размеры в строке **Insert** в диалоге. Нажмите **Insert**, чтобы добавить кривые, или **Cancel**, чтобы отменить вставку. -| Режим | Размещение | +| Режим Fit to frame | Результат до ручного перемещения и масштабирования | | --- | --- | -| Fit — вписать | Центрирует страницу SVG и пропорционально увеличивает или уменьшает её до границы рамки. | -| Stretch — растянуть | Подгоняет ширину и высоту страницы под рамку независимо друг от друга. | -| Original size — исходный размер | Сохраняет размер страницы. Девять значков позволяют совместить соответствующие углы, середины сторон или центры страницы и рамки. | +| Fit — вписать | Вписывает выбранную область с сохранением пропорций и учётом отступа. Если остаётся место, **Align** предлагает три положения вдоль свободной оси. | +| Stretch — растянуть | Подгоняет ширину и высоту независимо, заполняя рамку с учётом отступа. | +| Original size — исходный размер | Сохраняет физические размеры SVG. В **Align from** можно выбрать любую из девяти точек и совместить её с соответствующей точкой рамки с учётом отступа. | -У прямоугольной рамки учитывается поворот сторон. Для других контуров берётся габаритный прямоугольник по осям эскиза, поэтому рисунок может выходить за границу контура сложной формы. При размещении учитываются пустые поля внутри страницы SVG. В режиме **Original size** страница шириной 50 мм сохраняет ширину 50 мм. Для пикселей используется соотношение 96 px на дюйм. В эскизе создаются векторные кривые, которые поддерживает импортёр SVG в Fusion. +В режимах **Fit** и **Stretch** флажок **Link to frame** включён по умолчанию. InsertTo создаёт кривые SVG как фиксированные сплайны. Рисунок перемещается вместе с рамкой и меняет размер при изменении её размеров. Правка рамки и автоматическое обновление SVG занимают два шага в истории отмены. Оставьте InsertTo запущенным, чтобы он обновил сплайны после правки. Чтобы редактировать кривые SVG по отдельности, снимите флажок перед вставкой. Если рисунок вставлен более ранней версией, вставьте его заново с включённым флажком для создания связи. + +Например, страница 50 × 20 мм в рамке 80 × 60 мм при **Fit** займёт 80 × 32 мм. С **Align → Center** сверху и снизу останется по 14 мм. С **Align → Top** верхние границы совпадут, а снизу останется 28 мм. В этом примере отступ равен нулю. + +У прямоугольной рамки учитывается поворот сторон. Для других контуров берётся габаритный прямоугольник по осям эскиза, поэтому рисунок может выходить за границу контура сложной формы. Страница шириной 50 мм сохраняет эту ширину в исходном размере при масштабе 1. Для размеров в пикселях используется соотношение 96 px на дюйм. ## Проверка в Fusion -В Fusion 2706.1.17 на macOS медальон из SVG размером 50 × 50 мм дал в эскизе ровно 50 × 50 мм. В рамке 80 × 60 мм контрольный рисунок 50 × 20 мм дал 80 × 32 мм в режиме **Fit** и 80 × 60 мм в режиме **Stretch**. Проверка в Fusion на Windows ещё предстоит. +В Fusion 2706.1.17 на macOS медальон из SVG размером 50 × 50 мм дал в эскизе ровно 50 × 50 мм. В рамке 80 × 60 мм контрольный рисунок 50 × 20 мм дал 80 × 32 мм в режиме **Fit** и 80 × 60 мм в режиме **Stretch**. В режиме **Stretch** с включённым **Link to frame** изменение прямоугольной рамки с 80 × 50 мм до 100 × 50 мм обновило связанный эллипс после правки. Отступ 5 мм сохранился, а объём выдавливания этого профиля на 10 мм изменился с 21,99 до 28,27 см³. При переносе рамки на 12 мм вправо и 4 мм вниз оба связанных рисунка сдвинулись на те же расстояния. Для Fit, Stretch и свободной вставки после масштабирования ручкой габариты кривых в предпросмотре и после вставки совпали. Проверка в Fusion на Windows ещё предстоит. ## Установка из исходников diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 1a7d8a1..6d4f44b 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -6,7 +6,10 @@ - `InsertTo/InsertTo.py`: Autodesk Fusion entry point, command and event lifecycle. This module imports `adsk`, so **do not import it in offline unit tests**. - `InsertTo/config.py`: stable command identifier and product metadata. Generated once. -- `InsertTo/svg_geometry.py`: plain Python, independently testable calculation and domain logic. +- `InsertTo/svg_geometry.py` resolves SVG units, normalizes paths and computes page and artwork placement in millimetres. It runs without Fusion. +- `InsertTo/fusion_import.py` reads sketch contours, measures imported curves and converts between page, frame and sketch coordinates. +- `InsertTo/frame_link.py` stores the frame reference and placement settings on the sketch. After a frame edit, it updates the existing fixed splines so downstream features can keep their references. +- `InsertTo/dialog.py` manages file and frame selections, inputs, preview and execution. - `InsertTo/InsertTo.manifest`: Autodesk Fusion add-in metadata; the release builder stamps the computed version into the ZIP without rewriting the checkout. - `scripts/build.py`: deterministic archive, SHA-256, secret/symlink guardrails. - `.github/release-paths.txt`: reviewed allowlist of files that affect the shipped runtime. @@ -24,7 +27,12 @@ The archive in `dist/` contains the installable InsertTo folder. For development ## Native acceptance checklist - Install, start, stop and restart without duplicated controls or leaking handlers. -- Command can be opened, cancelled and executed; result is correct and safe. +- Import a 50 × 20 mm SVG in an 80 × 60 mm rectangle. Fit should produce 80 × 32 mm. At **Align → Top**, the upper edges should meet and the lower gap should be 28 mm. Stretch should produce 80 × 60 mm. +- Insert with **Link to frame** enabled and finish the edit. Change the frame from 80 × 60 mm to 100 × 60 mm, keeping InsertTo running. The linked 50 × 20 mm SVG should become 100 × 40 mm in Fit or 100 × 60 mm in Stretch. Confirm the same fixed splines update and the frame dimensions remain editable. Repeat with the option off and check that the SVG keeps its inserted size. +- Repeat Fit with a 5 mm inset on every side. The fitted SVG should measure 70 × 28 mm, with 5 mm at the top when aligned there. +- Select an SVG with unequal blank margins. Compare placement using the page and the artwork, and repeat in a rotated rectangular frame. Check each result against the selected bounds. +- Insert without a frame. Check the original physical size, rotate and scale about an anchor and move the artwork in sketch coordinates. Compare the preview with the committed curves. +- Cancel with a preview active and verify the original sketch geometry and curve count. Execute, undo and redo a separate insertion. - Active document changes, missing documents and model deletion do not cause unsafe writes. - Test parametric and direct modeling as applicable; verify timeline updates, units, undo and redo. - CAD API interactions, UI event order, preview lifecycle and performance are checked inside Fusion. diff --git a/docs/DEVELOPMENT.ru.md b/docs/DEVELOPMENT.ru.md index dd84af6..672a33b 100644 --- a/docs/DEVELOPMENT.ru.md +++ b/docs/DEVELOPMENT.ru.md @@ -6,7 +6,10 @@ - `InsertTo/InsertTo.py`: точка входа Autodesk Fusion, жизненный цикл команд и событий. Модуль импортирует `adsk`, поэтому **не импортируйте его в автономных модульных тестах**. - `InsertTo/config.py`: стабильный идентификатор команды и метаданные продукта. Создаётся один раз. -- `InsertTo/svg_geometry.py`: обычный Python, независимо тестируемые вычисления и предметная логика. +- `InsertTo/svg_geometry.py` определяет размеры SVG, нормализует кривые и рассчитывает размещение страницы и рисунка в миллиметрах. Модуль работает без Fusion. +- `InsertTo/fusion_import.py` читает контуры эскиза, измеряет импортированные кривые и переводит координаты между страницей, рамкой и эскизом. +- `InsertTo/frame_link.py` сохраняет в эскизе ссылки на рамку и параметры размещения. После редактирования рамки модуль меняет геометрию существующих фиксированных сплайнов, чтобы зависимые операции Fusion сохранили свои ссылки. +- `InsertTo/dialog.py` управляет выбором файла и рамки, вводом параметров, предпросмотром и вставкой. - `InsertTo/InsertTo.manifest`: метаданные аддона Autodesk Fusion; сборщик релиза записывает вычисленную версию в ZIP, не меняя рабочий каталог. - `scripts/build.py`: детерминированный архив, SHA-256, защита от секретов и символических ссылок. - `.github/release-paths.txt`: проверенный перечень файлов, влияющих на поставляемые компоненты. @@ -24,7 +27,12 @@ python scripts/build.py --version 0.1.0 ## Контрольный список приёмки в Fusion - Установка, запуск, остановка и повторный запуск без дублирующихся элементов управления и утечек обработчиков. -- Команда открывается, отменяется и выполняется; результат корректен и безопасен. +- Вставьте SVG 50 × 20 мм в прямоугольник 80 × 60 мм. Проверьте размер 80 × 32 мм в режиме Fit. При выборе **Align → Top** верхние границы должны совпасть, а нижний зазор должен составить 28 мм. В режиме Stretch проверьте размер 80 × 60 мм. +- Вставьте SVG 50 × 20 мм с включённым **Link to frame** и завершите редактирование. При работающем InsertTo измените рамку с 80 × 60 мм на 100 × 60 мм. Проверьте размер рисунка 100 × 40 мм в режиме Fit или 100 × 60 мм в режиме Stretch. Должны обновиться те же фиксированные сплайны, а размеры рамки остаются доступны для редактирования. Повторите со снятым флажком и проверьте, что рисунок сохранил размер, заданный при вставке. +- Повторите Fit с внутренним отступом 5 мм со всех сторон. Ожидается рисунок 70 × 28 мм. При выравнивании по верху расстояние от верхней стороны рамки должно составить 5 мм. +- Возьмите SVG с неодинаковыми пустыми полями. Сравните размещение по границам страницы и рисунка, затем повторите в повёрнутой прямоугольной рамке. +- Вставьте SVG без рамки. Проверьте исходные физические размеры, поворот и масштабирование вокруг привязки и сдвиг по координатам эскиза. Сравните предпросмотр с добавленными кривыми. +- Отмените вставку при активном предпросмотре и проверьте исходную геометрию и количество кривых. Для отдельной вставки проверьте отмену и повтор действия. - Переключение активного документа, отсутствие документа и удаление модели не приводят к небезопасной записи. - Где применимо, проверьте параметрическое и прямое моделирование, обновление таймлайна, единицы, отмену и повтор действий. - Взаимодействия с CAD API, порядок событий интерфейса, жизненный цикл предпросмотра и производительность проверены внутри Fusion. diff --git a/tests/test_dialog.py b/tests/test_dialog.py index 5f133ba..0c0a1b5 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -7,6 +7,7 @@ from types import SimpleNamespace from unittest.mock import Mock, patch +import InsertTo from InsertTo import fusion_import, svg_geometry @@ -28,17 +29,26 @@ def setUp(self): module = load_dialog() self.session = module._Dialog.__new__(module._Dialog) self.session.app = Mock() + self.session.design = Mock(isValid=True) + self.session.owner_document = self.session.app.activeDocument self.session.sketch = self.session.app.activeEditObject self.session.sketch.isValid = True self.session.document = SimpleNamespace(width_mm=20., height_mm=10.) self.session.browse = SimpleNamespace(text='previous.svg') self.session.file_error = self.session.preview_error = '' self.session.frame = Mock(selectionCount=1) + self.session.frame_sketch = self.session.sketch + self.session.plane = Mock(selectionCount=0) + self.session.inset = Mock(isValidExpression=True, value=0.) + self.session.link = Mock(value=False) + self.session.artwork_bounds = None + self.session.transform = Mock() + self.session.transform.values.return_value = (0., 0., 0., 1.) self.session.status = SimpleNamespace(text='') self.session.bounds = None - self.session.scaling = self.session.anchor = SimpleNamespace( - selectedItem=SimpleNamespace(index=0) - ) + for name, index in [('scaling', 0), ('anchor', 4), ('fit_x', 1), ('fit_y', 1), ('extent', 0)]: + control = SimpleNamespace(selectedItem=SimpleNamespace(index=index), isVisible=True) + setattr(self.session, name, control) def changed(self, input_id): self.session._changed(SimpleNamespace(input=SimpleNamespace(id=input_id))) @@ -71,7 +81,8 @@ def test_profile_replacement_after_preview_uses_new_frame_for_execute(self): self.session.frame.selectionCount = 0 self.changed('frame') self.session._validate(args) - self.assertFalse(args.areInputsValid) + self.assertTrue(args.areInputsValid) # Clearing the frame enables free placement. + self.assertFalse(self.session.scaling.isVisible) self.session.frame.selectionCount = 1 self.session.frame.selection.return_value.entity = 'second profile' @@ -85,3 +96,91 @@ def test_profile_replacement_after_preview_uses_new_frame_for_execute(self): self.assertEqual(insert.call_args, preview) self.assertEqual([call.args[1] for call in bounds.call_args_list], [['first profile'], ['second profile']]) + + + def test_artwork_measurement_is_transactional_and_cached_across_transforms(self): + session = self.session + session.extent.selectedItem.index = 1 + session.frame.selectionCount = 0 + args = SimpleNamespace() + with patch.object(fusion_import, 'measure_artwork', return_value=(2, 1, 12, 8)) as measure, \ + patch.object(fusion_import, 'import_svg') as insert: + session._validate(args) + self.assertTrue(args.areInputsValid) + measure.assert_not_called() + session._preview(args) + self.assertTrue(args.isValidResult) + self.assertEqual(insert.call_args.args[2].selected_box, (-5, -3.5, 5, 3.5)) + session.transform.values.return_value = (4, 6, 0, 2) + session._preview(args) + self.assertEqual(insert.call_args.args[2].selected_box, (-6, -1, 14, 13)) + measure.assert_called_once_with(session.sketch, session.document) + self.assertEqual(session.transform.position.call_args.args[1], (0, 0)) + + def test_fit_alignment_follows_available_space_and_inset(self): + session = self.session + session.bounds = fusion_import.Frame((0, 0, 30, 30)) + session.inset.value = 0.2 # 2 mm in internal cm. + session.fit_y.selectedItem.index = 0 + _, target, _ = session._placements() + self.assertTrue(session.fit_y.isVisible) + self.assertFalse(session.fit_x.isVisible) + self.assertEqual(target.selected_box, (2, 15, 28, 28)) + session.scaling.selectedItem.index = 1 + _, target, _ = session._placements() + self.assertFalse(session.fit_y.isVisible) + self.assertFalse(session.anchor.isVisible) + self.assertEqual(target.selected_box, (2, 2, 28, 28)) + session.scaling.selectedItem.index = 2 + session.anchor.selectedItem.index = 8 + _, target, _ = session._placements() + self.assertTrue(session.anchor.isVisible) + self.assertEqual(target.selected_box, (8, 2, 28, 12)) + + def test_empty_plane_preview_is_removed_after_import_failure(self): + session = self.session + session.sketch = None + session.frame.selectionCount = 0 + session.plane.selectionCount = 1 + args = SimpleNamespace() + with patch.object(fusion_import, 'validate_plane'), \ + patch.object(fusion_import, 'sketch_for_target') as create, \ + patch.object(fusion_import, 'import_svg', side_effect=ValueError('No curves.')): + self.changed('targetPlane') + self.assertFalse(session.frame.isVisible) + session._validate(args) + self.assertTrue(args.areInputsValid) + create.assert_not_called() + session._preview(args) + create.return_value.deleteMe.assert_called_once() + self.assertFalse(args.isValidResult) + session.plane.selectionCount = 0 + self.changed('targetPlane') + self.assertTrue(session.frame.isVisible) + + def test_linked_fit_persists_the_same_settings_used_for_the_preview(self): + session = self.session + session.bounds = fusion_import.Frame((0, 0, 30, 40)) + session.inset.value = 0.1 + session.fit_y.selectedItem.index = 2 + session.link.value = True + session.transform.values.return_value = (2, 5, 0.3, 1.2) + args = SimpleNamespace() + with patch.object(InsertTo, 'frame_link', create=True) as link, \ + patch.object(fusion_import, 'import_svg') as plain: + session._preview(args) + self.assertTrue(args.isValidResult) + plain.assert_not_called() + sketch, doc, target, entities = link.insert.call_args.args + settings = link.insert.call_args.kwargs + self.assertEqual(settings, dict(mode='fit', anchor='bottom-center', bounds=None, + inset_mm=1., x_mm=2, y_mm=5, rotation=0.3, scale=1.2)) + self.assertIs(sketch, session.sketch) + self.assertEqual(entities, [session.frame.selection(0).entity]) + self.assertEqual(target, svg_geometry.placement(doc, session.bounds, **settings)) + + session.scaling.selectedItem.index = 2 + session._preview(args) + self.assertTrue(args.isValidResult) + plain.assert_called_once() + link.insert.assert_called_once() diff --git a/tests/test_frame_link.py b/tests/test_frame_link.py new file mode 100644 index 0000000..6a64b0d --- /dev/null +++ b/tests/test_frame_link.py @@ -0,0 +1,74 @@ +import json +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +from InsertTo import frame_link as links +from InsertTo import svg_geometry as geo + + +class LinkUpdates(unittest.TestCase): + def setUp(self): + self.app = Mock() + self.app.activeDocument.creationId = 'test' + self.listeners = links._Listeners(self.app) + self.attr = Mock() + self.attr.name = 'a' + self.design = Mock() + self.design.findAttributes.return_value = [self.attr] + self.target = geo.Placement(4, 5, 6, 7) + self.change = ({'count': 1}, self.target) + + def test_intermediate_undo_is_not_reapplied_before_frame_changes_again(self): + with patch.object(links, '_changed', return_value=self.change) as changed: + with patch.object(links, '_owned_curves', return_value=['owned']): + self.listeners.history_changed = True + self.assertEqual(list(self.listeners.changes(self.design)), []) + self.listeners.history_changed = False + self.assertEqual(list(self.listeners.changes(self.design)), []) + changed.return_value = ({'count': 1}, geo.Placement(4, 5, 8, 7)) + self.assertEqual(len(list(self.listeners.changes(self.design))), 1) + + def test_deleted_curve_skips_only_its_own_link(self): + second = Mock() + second.name = 'b' + self.design.findAttributes.return_value = [self.attr, second] + with patch.object(links, '_changed', return_value=self.change): + with patch.object(links, '_owned_curves', side_effect=[[], ['spline']]): + updated = list(self.listeners.changes(self.design)) + self.assertEqual([item[0].name for item in updated], ['b']) + + def test_check_is_coalesced_even_if_fusion_returns_false_after_queueing(self): + self.app.fireCustomEvent.return_value = False + for _ in range(3): + self.listeners.schedule() + self.app.fireCustomEvent.assert_called_once_with(links._CHECK) + + def test_refresh_updates_existing_curve_and_persists_geometry_pose(self): + self.attr.value = '{}' + old = [0, 0, 6, 7, 0] + record = {'pose': old, 'count': 1} + curve = Mock() + with patch.object(links, '_matrix', return_value=object()): + links._refresh(self.attr, record, self.target, [curve]) + self.assertEqual(curve.replaceGeometry.call_count, 1) + self.assertEqual(json.loads(self.attr.value)['pose'], [4, 5, 6, 7, 0]) + + def test_reference_resolution_avoids_curves_on_another_sketch(self): + sketch = object() + other = SimpleNamespace(parentSketch=object()) + self.design.findEntityByToken.return_value = [other] + with self.assertRaisesRegex(ValueError, 'missing'): + links._resolve_frame(self.design, sketch, {'curves': ['edge-id'], 'profile': None}) + + def test_partial_refresh_restores_only_curves_successfully_replaced(self): + first, second = Mock(), Mock() + second.replaceGeometry.return_value = False + record = {'pose': [0, 0, 4, 5, 0]} + self.attr.value = json.dumps(record) + with patch.object(links, '_matrix', return_value=object()): + with self.assertRaisesRegex(ValueError, 'could not update'): + links._refresh(self.attr, record, self.target, [first, second]) + first.replaceGeometry.assert_called_with(first.geometry) + self.assertEqual(first.replaceGeometry.call_count, 2) + self.assertEqual(json.loads(self.attr.value), record) diff --git a/tests/test_fusion_import.py b/tests/test_fusion_import.py index 411b13a..cef8385 100644 --- a/tests/test_fusion_import.py +++ b/tests/test_fusion_import.py @@ -1,8 +1,9 @@ import math +import sys from pathlib import Path from types import SimpleNamespace import unittest -from unittest.mock import patch +from unittest.mock import Mock, patch from InsertTo import fusion_import as adapter from InsertTo.svg_geometry import Placement @@ -34,6 +35,38 @@ def test_rotated_rectangle_has_reproducible_local_axes(self): self.assertAlmostEqual(adapter._rectangle_angle([s.geometry for s in loop(order)]), math.atan2(1, 2)) + def test_linked_rectangle_follows_its_original_edge_through_large_rotations(self): + def rotated_rectangle(degrees, reverse): + co, si = math.cos(math.radians(degrees)), math.sin(math.radians(degrees)) + points = [(co*x - si*y, si*x + co*y) for x, y in ((2, 5), (10, 5), (10, 9), (2, 9))] + edges = [(points[i], points[(i+1) % 4]) for i in (3, 0, 2, 1)] + if reverse: + edges = [(b, a) for a, b in reversed(edges)] + return [segment(a, b) for a, b in edges] + + for reverse in (False, True): + initial = rotated_rectangle(44, reverse) + frame = adapter.Frame((20, 50, 100, 90), math.radians(44)) + axis = adapter.capture_frame_axis(initial, frame) + self.assertIsNotNone(axis) + for degrees in (45, 46, 90, 134, 180, 224, 314): + with self.subTest(degrees=degrees, reverse=reverse): + updated = adapter.resolve_frame_axis(rotated_rectangle(degrees, reverse), axis) + self.assertAlmostEqual(math.cos(updated.angle), math.cos(math.radians(degrees))) + self.assertAlmostEqual(math.sin(updated.angle), math.sin(math.radians(degrees))) + for actual, expected in zip(updated.bounds, frame.bounds): + self.assertAlmostEqual(actual, expected) + + def test_linked_axis_rejects_an_open_or_deformed_rectangle(self): + edges = loop([(0, 0), (3, 0), (3, 1), (0, 1)]) + frame = adapter.Frame((0, 0, 30, 10)) + axis = adapter.capture_frame_axis(edges, frame) + self.assertIsNotNone(axis) + trapezoid = loop([(0, 0), (3, 0), (2, 1), (0, 1)]) + self.assertIsNone(adapter.resolve_frame_axis(trapezoid, axis)) + self.assertIsNone(adapter.capture_frame_axis(trapezoid, frame)) + self.assertIsNone(adapter.resolve_frame_axis(edges[:3] + [edges[0]], axis)) + def test_general_polygon_uses_sketch_axes(self): trapezoid = loop([(1, 1), (3, 2), (2, 4), (0, 2)]) self.assertEqual(adapter._rectangle_angle([s.geometry for s in trapezoid]), 0) @@ -42,7 +75,7 @@ def test_general_polygon_uses_sketch_axes(self): def test_native_origin_uses_rotated_top_left_in_centimetres(self, normalize): angle = math.radians(30) frame = adapter.Frame((10, 20, 50, 80), angle) - target = Placement(10, 20, 40, 60) + target = Placement(10, 20, 40, 60, rotation=angle) calls = [] curves = SimpleNamespace(count=0) @@ -59,3 +92,51 @@ def insert(path, x, y, scale): self.assertAlmostEqual(y, 5 * math.sin(angle) + 8 * math.cos(angle)) self.assertEqual(scale, 1) normalize.assert_called_once_with(None, target, rotation=angle) + + def test_free_placement_adds_only_its_transformed_outline(self): + target = Placement(4, 17, 15, 20, rotation=.3, artwork_box=(5, 18, 8, 24)) + sketch = object() + with patch.object(adapter, '_insert_curves') as insert, patch.object(adapter, '_add_outline') as outline: + adapter.import_svg(sketch, None, target, None) + insert.assert_called_once_with(sketch, None, target) + outline.assert_called_once_with(sketch, target.outline) + + def test_one_dimensional_artwork_adds_one_construction_line(self): + core = SimpleNamespace(Point3D=SimpleNamespace(create=lambda x, y, z: (x, y, z))) + modules = {'adsk': SimpleNamespace(core=core), 'adsk.core': core} + for box in ((2, 1, 2, 5), (1, 2, 5, 2), (1, 2, 5, 2 + 1e-10)): + with self.subTest(box=box), patch.dict(sys.modules, modules): + target = Placement(0, 0, 10, 10, rotation=.3, artwork_box=box) + sketch = Mock() + adapter._add_outline(sketch, target.outline) + add = sketch.sketchCurves.sketchLines.addByTwoPoints + start, end = target.outline[0], target.outline[2] + add.assert_called_once_with((start[0]/10, start[1]/10, 0), + (end[0]/10, end[1]/10, 0)) + self.assertIs(add.return_value.isConstruction, True) + + def test_existing_sketch_is_reused_and_invalid_reference_rejected(self): + valid = SimpleNamespace(isValid=True) + self.assertIs(adapter.sketch_for_target(None, valid, None), valid) + with self.assertRaisesRegex(ValueError, 'no longer available'): + adapter.sketch_for_target(None, SimpleNamespace(isValid=False), None) + + def test_artwork_measurement_is_isolated_and_always_removes_scratch_sketch(self): + drawing = SimpleNamespace(width_mm=100, height_mm=90) + sketch = Mock() + scratch = sketch.parentComponent.sketches.addWithoutEdges.return_value + scratch.sketchCurves = [SimpleNamespace(isConstruction=True, geometry='helper'), + SimpleNamespace(isConstruction=False, geometry='path')] + manager = Mock() + box = SimpleNamespace(minPoint=SimpleNamespace(x=1, y=2), maxPoint=SimpleNamespace(x=3, y=4)) + manager.createWireFromCurves.return_value = SimpleNamespace(preciseBoundingBox=box), [] + fusion = SimpleNamespace(TemporaryBRepManager=SimpleNamespace(get=lambda: manager)) + modules = {'adsk': SimpleNamespace(fusion=fusion), 'adsk.fusion': fusion} + with patch.dict(sys.modules, modules), patch.object(adapter, '_insert_curves') as insert: + self.assertEqual(adapter.measure_artwork(sketch, drawing), (10, 20, 30, 40)) + insert.assert_called_once_with(scratch, drawing, Placement(0, 0, 100, 90)) + manager.createWireFromCurves.assert_called_once_with(['path'], True) + insert.side_effect = ValueError('bad SVG') + with self.assertRaisesRegex(ValueError, 'bad SVG'): + adapter.measure_artwork(sketch, drawing) + self.assertEqual(scratch.deleteMe.call_count, 2) diff --git a/tests/test_manipulator.py b/tests/test_manipulator.py new file mode 100644 index 0000000..3351f2c --- /dev/null +++ b/tests/test_manipulator.py @@ -0,0 +1,37 @@ +"""The numeric controls and the canvas handles describe one placement.""" + +from types import SimpleNamespace +import unittest + +from test_dialog import load_dialog + + +class TransformTests(unittest.TestCase): + def setUp(self): + cls = load_dialog().TransformControls + self.t = cls.__new__(cls) + self.t._properties = ('xTranslation', 'yTranslation', 'zRotation', 'xYPlaneScaleFactor') + self.t._last_values = (0., 0., 0., 1.) + self.t.group = SimpleNamespace(isVisible=True) + self.t.fields = [SimpleNamespace(id=name, value=v, isValidExpression=True) + for name, v in zip(('x', 'y', 'angle', 'factor'), self.t._last_values)] + self.t.triad = SimpleNamespace(**dict(zip(self.t._properties, self.t._last_values))) + self.t._updating = False + + def test_drag_updates_fields_once_and_converts_distances_to_mm(self): + self.t.triad.xTranslation = 1.75 + self.t.triad.yTranslation = -.4 + self.t.triad.xYPlaneScaleFactor = 1.5 + self.assertTrue(self.t.read_drag()) + self.assertEqual(self.t.values(), (17.5, -4., 0., 1.5)) + self.assertFalse(self.t.read_drag()) + + def test_numeric_edit_moves_handle_and_preserves_input_until_another_drag(self): + self.t.fields[2].value = .3 + self.assertTrue(self.t.changed('angle')) + self.assertEqual(self.t.triad.zRotation, .3) + self.assertFalse(self.t.read_drag()) + self.t.fields[3].value = 0 + self.assertFalse(self.t.changed('factor')) + with self.assertRaisesRegex(ValueError, 'positive scale'): + self.t.values() diff --git a/tests/test_svg_geometry.py b/tests/test_svg_geometry.py index be63d24..17da711 100644 --- a/tests/test_svg_geometry.py +++ b/tests/test_svg_geometry.py @@ -6,7 +6,7 @@ import unittest import xml.etree.ElementTree as ET -from InsertTo.svg_geometry import MM_PER_PX, SVG, normalized_svg, placement, read_svg +from InsertTo.svg_geometry import MM_PER_PX, SVG, fit_anchors, normalized_svg, placement, placement_delta, read_svg def document(attributes, content=''): @@ -53,6 +53,87 @@ def test_all_nine_anchors_including_oversize_svg(self): self.assertEqual((rect.width_mm, rect.height_mm), (50, 20)) self.assertEqual((rect.left_mm, rect.bottom_mm), (x, y)) + def test_fit_with_inset_changes_available_axis_and_anchor(self): + doc = document('width="50mm" height="20mm"') + frame = (10, 30, 110, 110) + self.assertEqual(fit_anchors(doc, frame, inset_mm=10), + ('top-center', 'center', 'bottom-center')) + for anchor, bottom in [('top-center', 68), ('center', 54), ('bottom-center', 40)]: + p = placement(doc, frame, 'fit', anchor, inset_mm=10) + self.assertEqual(p.selected_box, (20, bottom, 100, bottom + 32)) + self.assertEqual(fit_anchors(doc, (0, 0, 150, 40)), + ('center-left', 'center', 'center-right')) + self.assertEqual(fit_anchors(doc, (0, 0, 100, 40)), ('center',)) + for inset in (-1, 40, 100): + with self.assertRaises(ValueError): + placement(doc, frame, inset_mm=inset) + + def test_artwork_placement_preserves_page_to_drawing_offset(self): + doc = document('width="100mm" height="80mm"') + # Artwork includes points beyond the left page edge. + bounds = (-5, 15, 15, 25) + p = placement(doc, (0, 0, 90, 50), 'stretch', inset_mm=5, bounds=bounds) + self.assertEqual(p.selected_box, (5, 5, 85, 45)) + self.assertEqual((p.left_mm, p.bottom_mm, p.width_mm, p.height_mm), (25, -55, 400, 320)) + self.assertEqual(p.outline, ((5, 5), (85, 5), (85, 45), (5, 45))) + + def test_free_placement_aligns_artwork_anchor_at_selected_point_after_rotation(self): + doc = document('width="100mm" height="80mm"') + p = placement(doc, None, anchor='top-right', bounds=(12, 19, 32, 29), + x_mm=-22, y_mm=45, rotation=math.pi/2, scale=2) + self.assertEqual(p.pivot, (-22, 45)) + for actual, expected in zip(p.outline, [(-2, 5), (-2, 45), (-22, 45), (-22, 5)]): + for value, reference in zip(actual, expected): + self.assertAlmostEqual(value, reference) + self.assertEqual((p.width_mm, p.height_mm), (200, 160)) + + def test_manual_offsets_use_sketch_axes_for_rotated_frame(self): + from InsertTo.fusion_import import Frame + doc = document('width="40mm" height="20mm"') + p = placement(doc, Frame((10, 20, 90, 80), math.pi/2), 'original', 'top-left', + x_mm=5, y_mm=3, rotation=-math.pi/2, scale=1.5) + self.assertAlmostEqual(p.rotation, 0) + self.assertAlmostEqual(p.pivot[0], -75) + self.assertAlmostEqual(p.pivot[1], 13) + for actual, expected in zip(p.selected_box, (-75, -17, -15, 13)): + self.assertAlmostEqual(actual, expected) + + def test_associative_delta_maps_artwork_corners_and_page_interior(self): + from InsertTo.fusion_import import Frame + doc = document('width="60mm" height="33mm"') + artwork = (12, -3, 41, 12) + old = placement(doc, Frame((2, 14, 122, 80), math.radians(65)), 'stretch', + bounds=artwork, x_mm=7, y_mm=-2, rotation=math.radians(18)) + new = placement(doc, Frame((-21, 3, 119, 43), math.radians(-38)), 'stretch', + bounds=artwork, inset_mm=3, scale=1.3, x_mm=41, y_mm=71) + a, b, c, d, tx, ty = placement_delta(old, new) + for (x, y), (new_x, new_y) in zip(old.outline, new.outline): + self.assertAlmostEqual(a*x + c*y + tx, new_x) + self.assertAlmostEqual(b*x + d*y + ty, new_y) + # A control point outside the measured artwork has the same affine map. + def page_point(target): + x = target.left_mm + target.width_mm * 1.4 + y = target.bottom_mm - target.height_mm * .2 + co, si = math.cos(target.rotation), math.sin(target.rotation) + return co*x - si*y, si*x + co*y + x, y = page_point(old) + new_x, new_y = page_point(new) + self.assertAlmostEqual(a*x + c*y + tx, new_x) + self.assertAlmostEqual(b*x + d*y + ty, new_y) + for actual, expected in zip(placement_delta(new, new), (1, 0, 0, 1, 0, 0)): + self.assertAlmostEqual(actual, expected) + + def test_one_dimensional_artwork_can_fit_and_align(self): + doc = document('width="100mm" height="80mm"') + bounds = (3, 10, 3, 30) + frame = (0, 0, 40, 60) + self.assertEqual(fit_anchors(doc, frame, bounds=bounds), + ('center-left', 'center', 'center-right')) + p = placement(doc, frame, 'fit', 'center-right', bounds=bounds) + self.assertEqual(p.selected_box, (40, 0, 40, 60)) + with self.assertRaises(ValueError): + placement(doc, frame, 'stretch', bounds=bounds) + def test_normalization_preserves_margins_and_transforms_during_stretch(self): doc = document('width="200px" height="100px" viewBox="-10 20 50 50"', '') From a948bfdab4396f95442f508c21f316bca6af34b2 Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 12:26:49 +0300 Subject: [PATCH 03/13] perf: move SVG previews interactively without rebuilding sketch curves --- InsertTo/InsertTo.py | 9 ++ InsertTo/dialog.py | 109 ++++++++++++++++++---- InsertTo/drag_graphics.py | 165 ++++++++++++++++++++++++++++++++++ InsertTo/frame_link.py | 16 +--- InsertTo/fusion_import.py | 12 +++ InsertTo/preview_source.py | 169 +++++++++++++++++++++++++++++++++++ InsertTo/svg_geometry.py | 32 +++++-- tests/test_dialog.py | 102 +++++++++++++++------ tests/test_drag_graphics.py | 79 ++++++++++++++++ tests/test_preview_source.py | 90 +++++++++++++++++++ 10 files changed, 717 insertions(+), 66 deletions(-) create mode 100644 InsertTo/drag_graphics.py create mode 100644 InsertTo/preview_source.py create mode 100644 tests/test_drag_graphics.py create mode 100644 tests/test_preview_source.py diff --git a/InsertTo/InsertTo.py b/InsertTo/InsertTo.py index ea5c6c4..adaa338 100644 --- a/InsertTo/InsertTo.py +++ b/InsertTo/InsertTo.py @@ -18,11 +18,16 @@ class _Destroyed(adsk.core.CommandEventHandler): def notify(self, args): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("InsertTo.py/notify",file=out) + for session, handler in _sessions: + if handler is self: + session.close() _sessions[:] = [pair for pair in _sessions if pair[1] is not self] class _Created(adsk.core.CommandCreatedEventHandler): def notify(self, args): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("InsertTo.py/notify",file=out) try: session = dialog.attach(args.command) destroyed = _Destroyed() @@ -35,6 +40,7 @@ def notify(self, args): def run(context): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("InsertTo.py/run",file=out) global _menu, _created, _definition if _menu and _menu.isValid: return @@ -63,6 +69,7 @@ def run(context): def stop(context): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("InsertTo.py/stop",file=out) global _menu, _created, _definition try: frame_link.uninstall() @@ -72,4 +79,6 @@ def stop(context): _definition.deleteMe() finally: _menu = _created = _definition = None + for session, _ in _sessions: + session.close() _sessions.clear() diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 4404bc6..32c8c72 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -6,7 +6,7 @@ import adsk.core import adsk.fusion -from . import fusion_import, svg_geometry +from . import drag_graphics, frame_link, fusion_import, preview_source, svg_geometry from .manipulator import TransformControls @@ -24,11 +24,13 @@ def _show(control, visible): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_show",file=out) if control.isVisible != visible: control.isVisible = visible def _icon_list(inputs, id_, label, choices, default): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_icon_list",file=out) control = inputs.addDropDownCommandInput( id_, label, adsk.core.DropDownStyles.LabeledIconDropDownStyle ) @@ -38,8 +40,10 @@ def _icon_list(inputs, id_, label, choices, default): def _listen(event, base, callback): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_listen",file=out) class Handler(base): def notify(self, args): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/notify",file=out) callback(args) handler = Handler() @@ -49,6 +53,7 @@ def notify(self, args): class _Dialog: def __init__(self, command): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/__init__",file=out) self.app = adsk.core.Application.get() self.design = adsk.fusion.Design.cast(self.app.activeProduct) self.owner_document = self.app.activeDocument @@ -60,6 +65,10 @@ def __init__(self, command): self.file_error = '' self.preview_error = '' + self.graphics = None + self.graphics_key = None + self.graphics_pivot = None + command.isExecutedWhenPreEmpted = False command.okButtonText = 'Insert' inputs = command.commandInputs @@ -115,10 +124,12 @@ def __init__(self, command): ] def _status(self, message): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_status",file=out) if self.status.text != message: self.status.text = message def _choose_file(self): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_choose_file",file=out) picker = self.app.userInterface.createFileDialog() picker.title = 'Insert SVG' picker.filter = 'Scalable Vector Graphics (*.svg)' @@ -139,6 +150,7 @@ def _choose_file(self): return True def _changed(self, args): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_changed",file=out) changed = args.input.id try: if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor', @@ -146,7 +158,7 @@ def _changed(self, args): if self.transform.handles(changed): self.preview_error = '' if self.transform.changed(changed): - self.command.doExecutePreview() + self._move_graphics() return if changed == 'svgFile' and not self._choose_file(): return @@ -160,16 +172,36 @@ def _changed(self, args): self.preview_error = str(exc) def _dragged(self, args): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_dragged",file=out) if self.transform.read_drag(): self.preview_error = '' - self.command.doExecutePreview() + self._move_graphics() + + def _move_graphics(self): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_move_graphics",file=out) + if self.graphics: + try: + _, target, _ = self._placements() + self.graphics.show(target) + self._dimensions(target) + except Exception as exc: + self.preview_error = str(exc) + self._status(self.preview_error) + + def close(self): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/close",file=out) + if self.graphics: + self.graphics.clear() + self.graphics = self.graphics_key = self.graphics_pivot = None def _mode(self): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_mode",file=out) if not self.frame.selectionCount: return 'original' return _MODES[self.scaling.selectedItem.index][1] def _show_target_controls(self): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_show_target_controls",file=out) has_frame = bool(self.frame.selectionCount) has_plane = bool(self.plane.selectionCount) # Keep both available when starting outside a sketch. Once chosen, the @@ -181,11 +213,13 @@ def _show_target_controls(self): _show(self.link, has_frame and self._mode() in ('fit', 'stretch')) def _show_alignment(self, fit_options): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_show_alignment",file=out) _show(self.anchor, bool(self.frame.selectionCount) and self._mode() == 'original') _show(self.fit_x, bool(fit_options and 'center-left' in fit_options)) _show(self.fit_y, bool(fit_options and 'top-center' in fit_options)) def _destination(self): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_destination",file=out) if self.document is None: raise ValueError(self.file_error or 'Choose an SVG file.') if not self.design or not self.design.isValid or self.app.activeDocument != self.owner_document: @@ -209,9 +243,11 @@ def _destination(self): return None, plane def _use_artwork(self): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_use_artwork",file=out) return self.extent.selectedItem.index == 1 def _placements(self): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_placements",file=out) frame = self.bounds if self.frame.selectionCount else None mode = self._mode() artwork = self.artwork_bounds if self._use_artwork() else None @@ -237,11 +273,13 @@ def _placements(self): return baseline, target, settings def _dimensions(self, target): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_dimensions",file=out) left, bottom, right, top = target.selected_box self._status(f'SVG page {self.document.width_mm:.6g} × {self.document.height_mm:.6g} mm\n' f'Insert {right - left:.6g} × {top - bottom:.6g} mm') def _validate(self, args): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_validate",file=out) try: self._show_target_controls() self._destination() @@ -266,22 +304,56 @@ def _validate(self, args): args.areInputsValid = False self._status(str(exc)) - def _insert(self, sketch, plane, preview): - destination = fusion_import.sketch_for_target(self.design, sketch, plane) + def _linked(self, settings): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_linked",file=out) + return self.frame.selectionCount and self.link.value and settings['mode'] in ('fit', 'stretch') + + def _preview_graphics(self, sketch, plane): + # Keep the SVG in its own coordinate system. Frame and Transform + # changes then affect only the graphics matrix and the outline. + key = (self.document, sketch, plane) + destination = sketch try: + if self.graphics is None or self.graphics_key != key: + self.close() + destination = fusion_import.sketch_for_target(self.design, sketch, plane) + source = svg_geometry.Placement(0, 0, self.document.width_mm, self.document.height_mm) + curves = preview_source.simple_curves(self.document) + if curves is None: + curves = fusion_import.source_curves(destination, self.document) + self.graphics = drag_graphics.DragGraphics.capture(destination, curves, source) + self.graphics_key = key if self._use_artwork() and self.artwork_bounds is None: - self.artwork_bounds = fusion_import.measure_artwork(destination, self.document) - baseline, target, settings = self._placements() - if preview: + self.artwork_bounds = self.graphics.artwork_bounds() + baseline, target, _ = self._placements() + if baseline.pivot != self.graphics_pivot: + if destination is None: + destination = fusion_import.sketch_for_target(self.design, sketch, plane) self.transform.position(destination, baseline.pivot) - frame = self.bounds if self.frame.selectionCount else None - if frame and self.link.value and settings['mode'] in ('fit', 'stretch'): - from . import frame_link + self.graphics_pivot = baseline.pivot + outline = None + if not self.frame.selectionCount: + outline = (self.artwork_bounds if self._use_artwork() else + (0, 0, self.document.width_mm, self.document.height_mm)) + self.graphics.set_outline(outline) + finally: + if sketch is None and destination is not None and destination.isValid: + destination.deleteMe() + self.graphics.show(target) + self._dimensions(target) + def _insert(self, sketch, plane): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_insert",file=out) + destination = fusion_import.sketch_for_target(self.design, sketch, plane) + try: + if self._use_artwork() and self.artwork_bounds is None: + self.artwork_bounds = fusion_import.measure_artwork(destination, self.document) + _, target, settings = self._placements() + if self._linked(settings): entities = [self.frame.selection(i).entity for i in range(self.frame.selectionCount)] frame_link.insert(destination, self.document, target, entities, **settings) else: - fusion_import.import_svg(destination, self.document, target, frame) + fusion_import.import_svg(destination, self.document, target, self.bounds) self._dimensions(target) except Exception: if sketch is None and destination.isValid: @@ -289,26 +361,30 @@ def _insert(self, sketch, plane, preview): raise def _preview(self, args): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_preview",file=out) args.isValidResult = False try: sketch, plane = self._destination() except Exception as exc: self._status(str(exc)) self.transform.hide() + self.close() return try: - self._insert(sketch, plane, preview=True) + self._preview_graphics(sketch, plane) self.preview_error = '' - # Fusion owns the preview transaction and rolls it back on change or Cancel. - args.isValidResult = True except Exception as exc: self.app.log(traceback.format_exc()) + self.close() self.preview_error = f'Preview failed. {exc}' self._status(self.preview_error) def _execute(self, args): + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_execute",file=out) try: - self._insert(*self._destination(), preview=False) + self.close() + self.transform.read_drag() + self._insert(*self._destination()) except Exception as exc: self.app.log(traceback.format_exc()) args.executeFailed = True @@ -317,4 +393,5 @@ def _execute(self, args): def attach(command): """Return the command session. Its owner retains it until command.destroy.""" + with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/attach",file=out) return _Dialog(command) diff --git a/InsertTo/drag_graphics.py b/InsertTo/drag_graphics.py new file mode 100644 index 0000000..2c6c284 --- /dev/null +++ b/InsertTo/drag_graphics.py @@ -0,0 +1,165 @@ +"""Display imported sketch curves using one graphics transform per drag update.""" + +from .svg_geometry import placement_delta + + +def _stroke_points(geometry, tolerance_cm): + if geometry.objectType == 'adsk::core::Line3D': + return (geometry.startPoint, geometry.endPoint) + evaluator = geometry.evaluator + bounded, first, last = evaluator.getParameterExtents() + if bounded: + ok, points = evaluator.getStrokes(first, last, tolerance_cm) + if ok and len(points) >= 2: + return points + raise ValueError('Fusion could not draw a preview of an SVG curve.') + + +def _world_matrix(basis, delta): + """Compose the sketch-to-model basis with the placement in sketch coordinates.""" + origin, vx, vy, vz = basis + a, b, c, d, tx, ty = delta + rows = [] + for o, x, y, z in zip(origin, vx, vy, vz): + rows.extend((x * a + y * b, x * c + y * d, z, o + (x * tx + y * ty) / 10)) + return rows + [0, 0, 0, 1] + + +class DragGraphics: + def __init__(self, root, basis, source, batches, artwork=()): + self._root = root + self._basis = basis + self._source = source + self._batches = batches + self._group = None + self._shown = None + self._artwork = artwork + self._bounds = None + self._outline_bounds = None + self._outline_lines = None + self._outline_dirty = False + + @classmethod + def capture(cls, sketch, curves, target): + """Cache only the imported curves in sketch coordinates, before rollback.""" + import adsk.core + + design = sketch.parentComponent.parentDesign + occurrence = design.activeOccurrence + if not sketch.assemblyContext and occurrence and occurrence.component == sketch.parentComponent: + sketch = sketch.createForAssemblyContext(occurrence) + point = adsk.core.Point3D.create + origin = sketch.sketchToModelSpace(point(0, 0, 0)) + vx = origin.vectorTo(sketch.sketchToModelSpace(point(1, 0, 0))) + vy = origin.vectorTo(sketch.sketchToModelSpace(point(0, 1, 0))) + basis = [v.asArray() for v in (origin, vx, vy, vx.crossProduct(vy))] + # Subdivide once to within 0.01 mm, tighter on small artwork. + tolerance = min(0.001, max(1e-6, max(target.width_mm, target.height_mm) / 100000)) + batches = {} + artwork = [] + for curve in curves: + # Linked placements already have transient Curve3D source geometry. + geometry = getattr(curve, 'geometry', curve) + construction = getattr(curve, 'isConstruction', False) + if not construction: + artwork.append(geometry) + coords, indices = batches.setdefault(construction, ([], [])) + points = _stroke_points(geometry, tolerance) + start = len(coords) // 3 + for index in range(start, start + len(points) - 1): + indices.extend((index, index + 1)) + for p in points: + coords.extend(p.asArray()) + if not batches: + raise ValueError('The SVG has no curves to preview.') + return cls(design.rootComponent, basis, target, [ + (construction, coords, indices) for construction, (coords, indices) in batches.items() + ], artwork) + + def artwork_bounds(self): + """Compute exact source-space extents in mm once, independently of tessellation.""" + import adsk.fusion + + if self._bounds is None: + wire, _ = adsk.fusion.TemporaryBRepManager.get().createWireFromCurves(self._artwork, True) + if wire is None: + raise ValueError('Fusion could not measure the imported artwork.') + box = wire.preciseBoundingBox + self._bounds = (box.minPoint.x * 10, box.minPoint.y * 10, + box.maxPoint.x * 10, box.maxPoint.y * 10) + self._artwork = () + return self._bounds + + def set_outline(self, bounds): + """Select source-space bounds in mm for a free-placement construction outline.""" + if bounds != self._outline_bounds: + self._outline_bounds = bounds + self._outline_dirty = True + + def _lines(self, coords, indices, construction): + import adsk.core + import adsk.fusion + + buffer = adsk.fusion.CustomGraphicsCoordinates.create(coords) + lines = self._group.addLines(buffer, indices, False) + lines.isSelectable = False + rgb = (206, 132, 50) if construction else (36, 149, 218) + lines.color = adsk.fusion.CustomGraphicsSolidColorEffect.create( + adsk.core.Color.create(*rgb, 255) + ) + if construction: + lines.lineStylePattern = adsk.fusion.LineStylePatterns.dashedLineStylePattern + lines.depthPriority = 5 + return lines + + def _draw_outline(self): + if self._outline_lines and self._outline_lines.isValid: + self._outline_lines.deleteMe() + self._outline_lines = None + if self._outline_bounds is not None: + x0, y0, x1, y1 = [v / 10 for v in self._outline_bounds] + coords = [x0, y0, 0, x1, y0, 0, x1, y1, 0, x0, y1, 0] + # A horizontal or vertical drawing has only one outline segment. + if min(x1 - x0, y1 - y0) > 1e-6: + indices = [0, 1, 1, 2, 2, 3, 3, 0] + elif max(x1 - x0, y1 - y0) > 1e-6: + indices = [0, 2] + else: + indices = [] + if indices: + self._outline_lines = self._lines(coords, indices, True) + self._outline_dirty = False + + def show(self, target): + """Reuse the vertex buffers and update their single group transform.""" + import adsk.core + + if self._group is None or not self._group.isValid: + self._group = self._root.customGraphicsGroups.add() + self._shown = None + self._outline_lines = None + self._outline_dirty = True + try: + self._group.isSelectable = False + for construction, coords, indices in self._batches: + self._lines(coords, indices, construction) + except Exception: + self.clear() + raise + if self._outline_dirty: + self._draw_outline() + if self._shown == target: + return + transform = adsk.core.Matrix3D.create() + cells = _world_matrix(self._basis, placement_delta(self._source, target)) + if not transform.setWithArray(cells): + raise ValueError('Fusion could not position the SVG preview.') + self._group.transform = transform + self._shown = target + + def clear(self): + if self._group and self._group.isValid: + self._group.deleteMe() + self._outline_lines = None + self._group = None + self._shown = None diff --git a/InsertTo/frame_link.py b/InsertTo/frame_link.py index ae31cea..00d055b 100644 --- a/InsertTo/frame_link.py +++ b/InsertTo/frame_link.py @@ -91,20 +91,8 @@ def resolve(token): def _source_geometry(sketch, doc): - component = sketch.parentComponent - scratch = component.sketches.addWithoutEdges(component.xYConstructionPlane) - try: - page = svg_geometry.Placement(0, 0, doc.width_mm, doc.height_mm) - fusion_import._insert_curves(scratch, doc, page) - result = [] - for curve in scratch.sketchCurves: - if not curve.isConstruction: - geometry = curve.geometry - result.append(geometry if geometry.objectType == 'adsk::core::NurbsCurve3D' - else geometry.asNurbsCurve) - return result - finally: - scratch.deleteMe() + return [g if g.objectType == 'adsk::core::NurbsCurve3D' else g.asNurbsCurve + for g in fusion_import.source_curves(sketch, doc)] def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, inset_mm=0, diff --git a/InsertTo/fusion_import.py b/InsertTo/fusion_import.py index 7f9084f..5ecc66e 100644 --- a/InsertTo/fusion_import.py +++ b/InsertTo/fusion_import.py @@ -258,6 +258,18 @@ def _insert_curves(sketch, doc, target): raise ValueError('Fusion found no importable sketch curves in the SVG.') +def source_curves(sketch, doc): + """Import once at physical size and return independent page-local curves.""" + component = sketch.parentComponent + scratch = component.sketches.addWithoutEdges(component.xYConstructionPlane) + try: + page = svg_geometry.Placement(0, 0, doc.width_mm, doc.height_mm) + _insert_curves(scratch, doc, page) + return [curve.geometry for curve in scratch.sketchCurves if not curve.isConstruction] + finally: + scratch.deleteMe() + + def measure_artwork(sketch, doc): """Measure only imported paths at 1:1, in mm relative to the SVG page.""" import adsk.fusion diff --git a/InsertTo/preview_source.py b/InsertTo/preview_source.py new file mode 100644 index 0000000..1b2fc0e --- /dev/null +++ b/InsertTo/preview_source.py @@ -0,0 +1,169 @@ +"""Transient preview geometry for plain SVG primitives in page-local sketch cm.""" + +import math +import re + +from . import svg_geometry + + +_ATTRIBUTES = { + 'g': set(), 'path': {'d'}, + 'line': {'x1', 'y1', 'x2', 'y2'}, + 'polyline': {'points'}, 'polygon': {'points'}, + 'rect': {'x', 'y', 'width', 'height'}, + 'circle': {'cx', 'cy', 'r'}, 'ellipse': {'cx', 'cy', 'rx', 'ry'}, +} +_NUMBER = re.compile(svg_geometry._NUMBER) + + +def _number(text): + if not _NUMBER.fullmatch(text.strip()): + raise ValueError + value = float(text) + if not math.isfinite(value): + raise ValueError + return value + + +def _path_segments(data): + """Yield lines and polynomial Bézier control polygons in SVG user space.""" + if re.search(r'[a-zA-Z]\s*,|,\s*(?:[,a-zA-Z]|$)', data): + raise ValueError + current = origin = (0., 0.) + previous = '' + control = None + for command, values in svg_geometry.path_commands(data): + op = command.upper() + if op == 'A' or (not previous and op != 'M') or not all(map(math.isfinite, values)): + raise ValueError + x, y = current + dx, dy = current if command.islower() else (0., 0.) + points = [(a + dx, b + dy) for a, b in zip(values[::2], values[1::2])] + if op == 'M': + origin = points[0] + elif op == 'Z': + if current != origin: + yield [current, origin] + points = [origin] + else: + if op == 'H': + points = [(values[0] + dx, y)] + elif op == 'V': + points = [(x, values[0] + dy)] + elif op in ('S', 'T'): + related = ('C', 'S') if op == 'S' else ('Q', 'T') + reflected = (2 * x - control[0], 2 * y - control[1]) if previous in related else current + points.insert(0, reflected) + yield [current, *points] + if op in ('C', 'S', 'Q', 'T'): + control = points[-2] + current, previous = points[-1], op + + +def simple_curves(doc): + """Return transient Curve3Ds, or None when Fusion must interpret the source.""" + import adsk.core as core + + root = doc.root + if root.attrib.keys() - {'id', 'width', 'height', 'viewBox', 'version', 'preserveAspectRatio'}: + return None + if ' '.join(root.get('preserveAspectRatio', '').split()) not in ('', 'xMidYMid', 'xMidYMid meet'): + return None + if (root.text or '').strip() or any( + root.get(key, '').strip().endswith('%') or root.get(key, '').strip() == 'auto' + for key in ('width', 'height') + ): + return None + + sx, sy, tx, ty = doc.viewport_transform + cm = svg_geometry.MM_PER_PX / 10 + height = doc.height_mm / 10 + width = doc.width_mm / 10 + prefix = root.tag[:-3] # Match only elements in the SVG root's own namespace. + curves = [] + + def coordinates(x, y): + px, py = (x * sx + tx) * cm, height - (y * sy + ty) * cm + # Paths crossing the page edge can depend on the importer's clipping behavior. + if not (-1e-10 <= px <= width + 1e-10 and -1e-10 <= py <= height + 1e-10): + raise ValueError + return px, py + + def point(x, y): + return core.Point3D.create(*coordinates(x, y), 0) + + try: + for element in root.iter(): + if element is root: + continue + tag = element.tag.removeprefix(prefix) if prefix else element.tag + if (tag not in _ATTRIBUTES or element.tag != prefix + tag + or element.attrib.keys() - _ATTRIBUTES[tag] - {'id'} + or (element.text or '').strip() or (element.tail or '').strip()): + return None + if tag == 'g': + continue + if len(element): + return None + + def value(attr): + return _number(element.get(attr, '0')) + + if tag == 'path': + for vertices in _path_segments(element.get('d', '')): + points = [point(x, y) for x, y in vertices] + count = len(points) + if count == 2: + (x1, y1), (x2, y2) = vertices + if math.hypot((x2 - x1) * sx, (y2 - y1) * sy) * cm <= 1e-6: + return None + curves.append(core.Line3D.create(*points)) + else: + knots = [0.] * count + [1.] * count + curves.append(core.NurbsCurve3D.createNonRational(points, count - 1, knots, False)) + continue + + if tag in ('circle', 'ellipse'): + cx, cy = value('cx'), value('cy') + rx, ry = (value('r'),) * 2 if tag == 'circle' else (value('rx'), value('ry')) + if min(rx, ry) <= 0: + return None + coordinates(cx - rx, cy - ry) + coordinates(cx + rx, cy + ry) + center = point(cx, cy) + normal = core.Vector3D.create(0, 0, 1) + rx, ry = rx * sx * cm, ry * sy * cm + if min(rx, ry) <= 1e-6: + return None + if rx == ry: + curve = core.Circle3D.createByCenter(center, normal, rx) + else: + axis = core.Vector3D.create(1, 0, 0) if rx > ry else core.Vector3D.create(0, 1, 0) + curve = core.Ellipse3D.create(center, normal, axis, max(rx, ry), min(rx, ry)) + curves.append(curve) + continue + + if tag == 'line': + vertices = [(value('x1'), value('y1')), (value('x2'), value('y2'))] + elif tag == 'rect': + x, y, w, h = map(value, ('x', 'y', 'width', 'height')) + if min(w, h) <= 0: + return None + vertices = [(x, y), (x + w, y), (x + w, y + h), (x, y + h)] + else: + numbers = [_number(v) for v in re.split(r'\s*,\s*|\s+', element.get('points', '').strip())] + if len(numbers) % 2 or len(numbers) < (6 if tag == 'polygon' else 4): + return None + vertices = list(zip(numbers[::2], numbers[1::2])) + if tag in ('rect', 'polygon') and vertices[0] != vertices[-1]: + vertices.append(vertices[0]) + if any(math.hypot((x2 - x1) * sx, (y2 - y1) * sy) * cm <= 1e-6 + for (x1, y1), (x2, y2) in zip(vertices, vertices[1:])): + # The native importer decides which sub-tolerance segments survive. + return None + points = [point(x, y) for x, y in vertices] + for start, end in zip(points, points[1:]): + curves.append(core.Line3D.create(start, end)) + except (ValueError, OverflowError, RuntimeError): + return None + return curves if curves and all(curves) else None diff --git a/InsertTo/svg_geometry.py b/InsertTo/svg_geometry.py index 4204404..1857d44 100644 --- a/InsertTo/svg_geometry.py +++ b/InsertTo/svg_geometry.py @@ -316,16 +316,14 @@ def project(x, y): return commands -def _expand_arcs(data): - """Expand only arcs, preserving SVG implicit commands and shorthand semantics.""" +def path_commands(data): + """Yield explicit SVG path commands, expanding implicit groups after moveto.""" cursor = 0 - current = origin = (0, 0) - command, previous = '', '' - output = [] + command = '' while True: cursor = _PATH_SEPARATORS.match(data, cursor).end() if cursor == len(data): - return ' '.join(output) + return if data[cursor] in _PATH_COMMANDS: command = data[cursor] cursor += 1 @@ -333,8 +331,8 @@ def _expand_arcs(data): raise ValueError('Invalid SVG path command.') op = command.upper() if op == 'Z': - output.append('Z') - current, command, previous = origin, '', 'Z' + yield command, [] + command = '' continue values = [] for index in range(_PATH_ARITY[op]): @@ -351,6 +349,22 @@ def _expand_arcs(data): raise ValueError('Invalid SVG path coordinate.') values.append(float(number[0])) cursor = number.end() + yield command, values + if op == 'M': + command = 'l' if command.islower() else 'L' + + +def _expand_arcs(data): + """Expand only arcs, preserving SVG implicit commands and shorthand semantics.""" + current = origin = (0, 0) + previous = '' + output = [] + for command, values in path_commands(data): + op = command.upper() + if op == 'Z': + output.append('Z') + current, previous = origin, 'Z' + continue relative = command.islower() x, y = current if op == 'H': @@ -369,8 +383,8 @@ def _expand_arcs(data): output.append(command + ' '.join(map(_format, values))) if op == 'M': origin = end - command = 'l' if relative else 'L' current, previous = end, op + return ' '.join(output) def _resolve_shape_lengths(element, viewport, nonuniform): diff --git a/tests/test_dialog.py b/tests/test_dialog.py index 0c0a1b5..d457fec 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -7,8 +7,7 @@ from types import SimpleNamespace from unittest.mock import Mock, patch -import InsertTo -from InsertTo import fusion_import, svg_geometry +from InsertTo import drag_graphics, frame_link, fusion_import, preview_source, svg_geometry def load_dialog(): @@ -27,7 +26,14 @@ def load_dialog(): class DialogEventsTests(unittest.TestCase): def setUp(self): module = load_dialog() - self.session = module._Dialog.__new__(module._Dialog) + command = Mock() + command.commandInputs.addSelectionInput.return_value.selectionCount = 0 + with patch.object(module, '_listen'): + self.session = module._Dialog(command) + self.capture = self.enterContext(patch.object(drag_graphics.DragGraphics, 'capture')) + self.simple = self.enterContext(patch.object(preview_source, 'simple_curves', return_value=None)) + self.source = self.enterContext(patch.object(fusion_import, 'source_curves')) + self.graphics = self.capture.return_value self.session.app = Mock() self.session.design = Mock(isValid=True) self.session.owner_document = self.session.app.activeDocument @@ -56,7 +62,7 @@ def changed(self, input_id): def test_cancel_file_picker_preserves_failed_preview_and_chosen_file(self): self.session.bounds = fusion_import.Frame((0, 0, 20, 10), 0) args = SimpleNamespace() - with patch.object(fusion_import, 'import_svg', side_effect=ValueError('No curves.')): + with patch.object(fusion_import, 'source_curves', side_effect=ValueError('No curves.')): self.session._preview(args) self.assertFalse(args.isValidResult) previous = self.session.document @@ -75,8 +81,8 @@ def test_profile_replacement_after_preview_uses_new_frame_for_execute(self): args = SimpleNamespace() self.session.frame.selection.return_value.entity = 'first profile' self.session._preview(args) - self.assertTrue(args.isValidResult) - self.assertIs(insert.call_args.args[-1], first) + self.assertFalse(args.isValidResult) + self.assertEqual(self.graphics.show.call_args.args[0], svg_geometry.Placement(0, 0, 20, 10)) self.session.frame.selectionCount = 0 self.changed('frame') @@ -88,12 +94,15 @@ def test_profile_replacement_after_preview_uses_new_frame_for_execute(self): self.session.frame.selection.return_value.entity = 'second profile' self.changed('frame') self.session._preview(args) - preview = insert.call_args - self.assertTrue(args.isValidResult) - self.assertIs(preview.args[-1], second) - self.assertEqual(preview.args[-2], svg_geometry.Placement(30, 40, 60, 30)) - self.session._execute(args) # Fallback if Fusion requests explicit execution. - self.assertEqual(insert.call_args, preview) + self.assertFalse(args.isValidResult) + preview = self.graphics.show.call_args.args[0] + self.assertEqual(preview, svg_geometry.Placement(30, 40, 60, 30)) + self.capture.assert_called_once() + self.graphics.clear.assert_not_called() + self.session._execute(args) + self.assertEqual(insert.call_args.args, ( + self.session.sketch, self.session.document, preview, second + )) self.assertEqual([call.args[1] for call in bounds.call_args_list], [['first profile'], ['second profile']]) @@ -103,20 +112,43 @@ def test_artwork_measurement_is_transactional_and_cached_across_transforms(self) session.extent.selectedItem.index = 1 session.frame.selectionCount = 0 args = SimpleNamespace() - with patch.object(fusion_import, 'measure_artwork', return_value=(2, 1, 12, 8)) as measure, \ + with patch.object(self.graphics, 'artwork_bounds', return_value=(2, 1, 12, 8)) as measure, \ patch.object(fusion_import, 'import_svg') as insert: session._validate(args) self.assertTrue(args.areInputsValid) measure.assert_not_called() session._preview(args) - self.assertTrue(args.isValidResult) - self.assertEqual(insert.call_args.args[2].selected_box, (-5, -3.5, 5, 3.5)) + self.assertFalse(args.isValidResult) + self.assertEqual(self.graphics.show.call_args.args[0].selected_box, (-5, -3.5, 5, 3.5)) + insert.assert_not_called() session.transform.values.return_value = (4, 6, 0, 2) session._preview(args) - self.assertEqual(insert.call_args.args[2].selected_box, (-6, -1, 14, 13)) - measure.assert_called_once_with(session.sketch, session.document) + self.assertEqual(self.graphics.show.call_args.args[0].selected_box, (-6, -1, 14, 13)) + self.capture.assert_called_once() + insert.assert_not_called() + measure.assert_called_once_with() + self.graphics.set_outline.assert_called_with((2, 1, 12, 8)) self.assertEqual(session.transform.position.call_args.args[1], (0, 0)) + def test_mouse_drag_updates_cached_graphics_without_another_command_preview(self): + session = self.session + session.frame.selectionCount = 0 + args = SimpleNamespace() + with patch.object(fusion_import, 'import_svg') as insert: + session._preview(args) + self.source.assert_called_once_with(session.sketch, session.document) + session.transform.read_drag.return_value = True + for x in range(1, 21): + session.transform.values.return_value = (x, -2, 0, 1) + session._dragged(args) + insert.assert_not_called() + self.capture.assert_called_once() + session.command.doExecutePreview.assert_not_called() + self.assertEqual(self.graphics.show.call_args.args[0].selected_box, (10, -7, 30, 3)) + self.graphics.clear.assert_not_called() + session.close() + self.graphics.clear.assert_called_once() + def test_fit_alignment_follows_available_space_and_inset(self): session = self.session session.bounds = fusion_import.Frame((0, 0, 30, 30)) @@ -145,7 +177,7 @@ def test_empty_plane_preview_is_removed_after_import_failure(self): args = SimpleNamespace() with patch.object(fusion_import, 'validate_plane'), \ patch.object(fusion_import, 'sketch_for_target') as create, \ - patch.object(fusion_import, 'import_svg', side_effect=ValueError('No curves.')): + patch.object(fusion_import, 'source_curves', side_effect=ValueError('No curves.')): self.changed('targetPlane') self.assertFalse(session.frame.isVisible) session._validate(args) @@ -166,21 +198,37 @@ def test_linked_fit_persists_the_same_settings_used_for_the_preview(self): session.link.value = True session.transform.values.return_value = (2, 5, 0.3, 1.2) args = SimpleNamespace() - with patch.object(InsertTo, 'frame_link', create=True) as link, \ + with patch.object(preview_source, 'simple_curves', return_value=[Mock()]) as source, \ + patch.object(frame_link, 'insert') as link, \ patch.object(fusion_import, 'import_svg') as plain: session._preview(args) - self.assertTrue(args.isValidResult) + self.assertFalse(args.isValidResult) plain.assert_not_called() - sketch, doc, target, entities = link.insert.call_args.args - settings = link.insert.call_args.kwargs + link.assert_not_called() + session.transform.values.return_value = (4, 5, 0.3, 1.2) + session._preview(args) + source.assert_called_once() + self.capture.assert_called_once() + session._execute(args) + sketch, doc, target, entities = link.call_args.args + self.assertEqual(target, self.graphics.show.call_args.args[0]) + settings = link.call_args.kwargs self.assertEqual(settings, dict(mode='fit', anchor='bottom-center', bounds=None, - inset_mm=1., x_mm=2, y_mm=5, rotation=0.3, scale=1.2)) + inset_mm=1., x_mm=4, y_mm=5, rotation=0.3, scale=1.2)) self.assertIs(sketch, session.sketch) self.assertEqual(entities, [session.frame.selection(0).entity]) self.assertEqual(target, svg_geometry.placement(doc, session.bounds, **settings)) - session.scaling.selectedItem.index = 2 + def test_scaling_alignment_and_inset_reuse_page_geometry(self): + session = self.session + session.bounds = fusion_import.Frame((0, 0, 30, 40)) + args = SimpleNamespace() + session._preview(args) + for mode, inset in ((1, 0), (0, 0.1), (2, 0.1)): + session.scaling.selectedItem.index = mode + session.inset.value = inset + self.changed('scale') session._preview(args) - self.assertTrue(args.isValidResult) - plain.assert_called_once() - link.insert.assert_called_once() + self.source.assert_called_once() + self.capture.assert_called_once() + self.assertEqual(self.graphics.show.call_count, 4) diff --git a/tests/test_drag_graphics.py b/tests/test_drag_graphics.py new file mode 100644 index 0000000..f631e6c --- /dev/null +++ b/tests/test_drag_graphics.py @@ -0,0 +1,79 @@ +"""Drawing updates stay independent of sketch size and handle non-XY sketch planes.""" + +import math +import sys +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +from InsertTo.drag_graphics import DragGraphics, _world_matrix +from InsertTo.svg_geometry import Placement, placement_delta + + +class DragGraphicsTests(unittest.TestCase): + def test_world_transform_for_a_rotated_drawing_on_offset_yz_plane(self): + basis = [(5, 6, 7), (0, 1, 0), (0, 0, 1), (1, 0, 0)] + source = Placement(10, 20, 100, 50) + target = Placement(70, 50, 200, 150, math.pi / 2) + cells = _world_matrix(basis, placement_delta(source, target)) + for point, expected in [([1, 2, 0, 1], [5, 1, 14]), + ([11, 7, 0, 1], [5, -14, 34])]: + for i, world in enumerate(expected): + actual = sum(cells[4*i+j]*p for j, p in enumerate(point)) + self.assertAlmostEqual(actual, world) + + def test_drag_reuses_uploaded_coordinates_and_recovers_after_rollback(self): + root, sdk, coords = Mock(), Mock(), [0, 0, 0, 0, 1, 0] + page = Placement(0, 0, 100, 50) + next_page = Placement(20, 10, 100, 50) + basis = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)] + group1, group2 = Mock(isValid=True), Mock(isValid=True) + root.customGraphicsGroups.add.side_effect = [group1, group2] + drawing = DragGraphics(root, basis, page, [(False, coords, [0, 1])]) + with patch.dict(sys.modules, {'adsk': sdk, 'adsk.core': sdk.core, 'adsk.fusion': sdk.fusion}): + drawing.show(page) + drawing.show(next_page) + drawing.show(next_page) + self.assertEqual(root.customGraphicsGroups.add.call_count, 1) + group1.addLines.assert_called_once_with(sdk.fusion.CustomGraphicsCoordinates.create.return_value, [0, 1], False) + self.assertEqual(sdk.core.Matrix3D.create.call_count, 2) + group1.isValid = False + drawing.show(next_page) + group2.addLines.assert_called_once_with(sdk.fusion.CustomGraphicsCoordinates.create.return_value, [0, 1], False) + drawing.clear() + group2.deleteMe.assert_called_once() + + def test_changing_free_outline_only_updates_outline_batch(self): + sdk, root = Mock(), Mock() + art, page_outline, art_outline = Mock(), Mock(), Mock() + group = root.customGraphicsGroups.add.return_value + group.addLines.side_effect = [art, page_outline, art_outline] + page = Placement(0, 0, 100, 50) + basis = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)] + drawing = DragGraphics(root, basis, page, [(False, [0, 0, 0, 0, 1, 0], [0, 1])]) + with patch.dict(sys.modules, {'adsk': sdk, 'adsk.core': sdk.core, 'adsk.fusion': sdk.fusion}): + drawing.set_outline((0, 0, 100, 50)) + drawing.show(page) + drawing.set_outline((12, 4, 12, 30)) + drawing.show(page) + page_outline.deleteMe.assert_called_once() + self.assertEqual(group.addLines.call_args.args[1], [0, 2]) + drawing.set_outline(None) + drawing.show(page) + art_outline.deleteMe.assert_called_once() + art.deleteMe.assert_not_called() + self.assertEqual(group.addLines.call_count, 3) + + def test_artwork_extents_are_measured_lazily_and_cached_in_mm(self): + sdk = Mock() + curves = [object(), object()] + drawing = DragGraphics(None, None, None, [], curves) + manager = sdk.fusion.TemporaryBRepManager.get.return_value + box = SimpleNamespace(minPoint=SimpleNamespace(x=1.5, y=-2), + maxPoint=SimpleNamespace(x=4, y=8)) + manager.createWireFromCurves.return_value = SimpleNamespace(preciseBoundingBox=box), [] + manager.createWireFromCurves.assert_not_called() + with patch.dict(sys.modules, {'adsk': sdk, 'adsk.fusion': sdk.fusion}): + self.assertEqual(drawing.artwork_bounds(), (15, -20, 40, 80)) + self.assertEqual(drawing.artwork_bounds(), (15, -20, 40, 80)) + manager.createWireFromCurves.assert_called_once_with(curves, True) diff --git a/tests/test_preview_source.py b/tests/test_preview_source.py new file mode 100644 index 0000000..4c057c0 --- /dev/null +++ b/tests/test_preview_source.py @@ -0,0 +1,90 @@ +"""Parity of the direct primitive preview with the SVG page coordinate system.""" + +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import Mock, patch + +from InsertTo import preview_source, svg_geometry + + +class PreviewSourceTests(unittest.TestCase): + def setUp(self): + sdk = Mock() + sdk.core.Point3D.create.side_effect = lambda *xyz: xyz + sdk.core.Vector3D.create.side_effect = lambda *xyz: xyz + for factory in ('Line3D.create', 'Circle3D.createByCenter', 'Ellipse3D.create', + 'NurbsCurve3D.createNonRational'): + getattr(getattr(sdk.core, factory.split('.')[0]), factory.split('.')[1]).side_effect = ( + lambda *args: args) + self.enterContext(patch.dict(sys.modules, {'adsk': sdk, 'adsk.core': sdk.core})) + directory = self.enterContext(tempfile.TemporaryDirectory()) + self.svg = Path(directory) / 'drawing.svg' + + def curves(self, content, attributes='width="50mm" height="30mm" viewBox="0 0 50 30"'): + self.svg.write_text(f'{content}') + return preview_source.simple_curves(svg_geometry.read_svg(self.svg)) + + def assertPoint(self, actual, expected): + for a, b in zip(actual, expected, strict=True): + self.assertAlmostEqual(a, b) + + def test_scales_and_flips_svg_coordinates_once_including_letterbox_and_viewbox_origin(self): + curves = self.curves('', + 'width="80mm" height="60mm" viewBox="20 30 40 20"') + self.assertEqual(len(curves), 1) + self.assertPoint(curves[0][0], (0, 5, 0)) + self.assertPoint(curves[0][1], (8, 1, 0)) + + def test_polygons_close_and_polylines_stay_open(self): + curves = self.curves('' + '' + '') + self.assertEqual(len(curves), 4 + 3 + 2) + self.assertPoint(curves[0][0], curves[3][1]) + self.assertPoint(curves[4][0], curves[6][1]) + self.assertPoint(curves[-1][1], (1, 2, 0)) + + def test_circle_radius_and_vertical_ellipse_major_axis_are_in_sketch_cm(self): + circle, ellipse = self.curves('' + '') + self.assertPoint(circle[0], (1, 1.8, 0)) + self.assertAlmostEqual(circle[-1], 0.5) + self.assertPoint(ellipse[0], (2.2, 1.2, 0)) + self.assertEqual(ellipse[2], (0, 1, 0)) + self.assertAlmostEqual(ellipse[-2], 0.7) + self.assertAlmostEqual(ellipse[-1], 0.3) + + def test_path_implicit_lines_relative_smooth_controls_and_multiple_subpaths(self): + curves = self.curves('') + self.assertEqual(len(curves), 9) + for i, end in enumerate(((.4, 2.7, 0), (.8, 2.7, 0), (.8, 2.4, 0))): + self.assertPoint(curves[i][-1], end) + cubic, smooth, quadratic, reflected = curves[3:7] + self.assertEqual(cubic[1:], (3, [0.] * 4 + [1.] * 4, False)) + self.assertEqual(quadratic[1:], (2, [0.] * 3 + [1.] * 3, False)) + self.assertPoint(smooth[0][1], (1.2, 2.3, 0)) + self.assertPoint(reflected[0][1], (1.7, 2.2, 0)) + self.assertPoint(curves[7][-1], (.2, 2.7, 0)) + self.assertPoint(curves[8][0][1], (3, 1, 0)) + + def test_malformed_and_unsupported_paths_fall_back_to_native_import(self): + for data in ('L1 1', 'M0 1 C2', 'M0 0,', 'M0 0,,1 1', 'M0 0 R1 1', 'M0 0 L1e999 2'): + with self.subTest(data=data): + self.assertIsNone(self.curves(f'')) + + def test_defer_whole_file_when_native_svg_semantics_are_needed(self): + for element in ( + '', '', + '', '', '', + '', '', '', + '', '', '', '', + '', '', + ): + with self.subTest(element=element): + self.assertIsNone(self.curves('' + element)) + for attr in ('style="opacity:0"', 'overflow="hidden"', 'preserveAspectRatio="none"'): + with self.subTest(attr=attr): + self.assertIsNone(self.curves('', 'viewBox="0 0 5 5" ' + attr)) From e8c73e19aec2ae033bef2ac5f0e5ae58af794a02 Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 12:27:06 +0300 Subject: [PATCH 04/13] fix: remove temporary preview timing instrumentation --- InsertTo/InsertTo.py | 4 ---- InsertTo/dialog.py | 24 ------------------------ 2 files changed, 28 deletions(-) diff --git a/InsertTo/InsertTo.py b/InsertTo/InsertTo.py index adaa338..7036b9a 100644 --- a/InsertTo/InsertTo.py +++ b/InsertTo/InsertTo.py @@ -18,7 +18,6 @@ class _Destroyed(adsk.core.CommandEventHandler): def notify(self, args): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("InsertTo.py/notify",file=out) for session, handler in _sessions: if handler is self: session.close() @@ -27,7 +26,6 @@ def notify(self, args): class _Created(adsk.core.CommandCreatedEventHandler): def notify(self, args): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("InsertTo.py/notify",file=out) try: session = dialog.attach(args.command) destroyed = _Destroyed() @@ -40,7 +38,6 @@ def notify(self, args): def run(context): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("InsertTo.py/run",file=out) global _menu, _created, _definition if _menu and _menu.isValid: return @@ -69,7 +66,6 @@ def run(context): def stop(context): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("InsertTo.py/stop",file=out) global _menu, _created, _definition try: frame_link.uninstall() diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 32c8c72..21db957 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -24,13 +24,11 @@ def _show(control, visible): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_show",file=out) if control.isVisible != visible: control.isVisible = visible def _icon_list(inputs, id_, label, choices, default): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_icon_list",file=out) control = inputs.addDropDownCommandInput( id_, label, adsk.core.DropDownStyles.LabeledIconDropDownStyle ) @@ -40,10 +38,8 @@ def _icon_list(inputs, id_, label, choices, default): def _listen(event, base, callback): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_listen",file=out) class Handler(base): def notify(self, args): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/notify",file=out) callback(args) handler = Handler() @@ -53,7 +49,6 @@ def notify(self, args): class _Dialog: def __init__(self, command): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/__init__",file=out) self.app = adsk.core.Application.get() self.design = adsk.fusion.Design.cast(self.app.activeProduct) self.owner_document = self.app.activeDocument @@ -124,12 +119,10 @@ def __init__(self, command): ] def _status(self, message): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_status",file=out) if self.status.text != message: self.status.text = message def _choose_file(self): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_choose_file",file=out) picker = self.app.userInterface.createFileDialog() picker.title = 'Insert SVG' picker.filter = 'Scalable Vector Graphics (*.svg)' @@ -150,7 +143,6 @@ def _choose_file(self): return True def _changed(self, args): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_changed",file=out) changed = args.input.id try: if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor', @@ -172,13 +164,11 @@ def _changed(self, args): self.preview_error = str(exc) def _dragged(self, args): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_dragged",file=out) if self.transform.read_drag(): self.preview_error = '' self._move_graphics() def _move_graphics(self): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_move_graphics",file=out) if self.graphics: try: _, target, _ = self._placements() @@ -189,19 +179,16 @@ def _move_graphics(self): self._status(self.preview_error) def close(self): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/close",file=out) if self.graphics: self.graphics.clear() self.graphics = self.graphics_key = self.graphics_pivot = None def _mode(self): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_mode",file=out) if not self.frame.selectionCount: return 'original' return _MODES[self.scaling.selectedItem.index][1] def _show_target_controls(self): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_show_target_controls",file=out) has_frame = bool(self.frame.selectionCount) has_plane = bool(self.plane.selectionCount) # Keep both available when starting outside a sketch. Once chosen, the @@ -213,13 +200,11 @@ def _show_target_controls(self): _show(self.link, has_frame and self._mode() in ('fit', 'stretch')) def _show_alignment(self, fit_options): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_show_alignment",file=out) _show(self.anchor, bool(self.frame.selectionCount) and self._mode() == 'original') _show(self.fit_x, bool(fit_options and 'center-left' in fit_options)) _show(self.fit_y, bool(fit_options and 'top-center' in fit_options)) def _destination(self): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_destination",file=out) if self.document is None: raise ValueError(self.file_error or 'Choose an SVG file.') if not self.design or not self.design.isValid or self.app.activeDocument != self.owner_document: @@ -243,11 +228,9 @@ def _destination(self): return None, plane def _use_artwork(self): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_use_artwork",file=out) return self.extent.selectedItem.index == 1 def _placements(self): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_placements",file=out) frame = self.bounds if self.frame.selectionCount else None mode = self._mode() artwork = self.artwork_bounds if self._use_artwork() else None @@ -273,13 +256,11 @@ def _placements(self): return baseline, target, settings def _dimensions(self, target): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_dimensions",file=out) left, bottom, right, top = target.selected_box self._status(f'SVG page {self.document.width_mm:.6g} × {self.document.height_mm:.6g} mm\n' f'Insert {right - left:.6g} × {top - bottom:.6g} mm') def _validate(self, args): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_validate",file=out) try: self._show_target_controls() self._destination() @@ -305,7 +286,6 @@ def _validate(self, args): self._status(str(exc)) def _linked(self, settings): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_linked",file=out) return self.frame.selectionCount and self.link.value and settings['mode'] in ('fit', 'stretch') def _preview_graphics(self, sketch, plane): @@ -343,7 +323,6 @@ def _preview_graphics(self, sketch, plane): self._dimensions(target) def _insert(self, sketch, plane): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_insert",file=out) destination = fusion_import.sketch_for_target(self.design, sketch, plane) try: if self._use_artwork() and self.artwork_bounds is None: @@ -361,7 +340,6 @@ def _insert(self, sketch, plane): raise def _preview(self, args): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_preview",file=out) args.isValidResult = False try: sketch, plane = self._destination() @@ -380,7 +358,6 @@ def _preview(self, args): self._status(self.preview_error) def _execute(self, args): - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/_execute",file=out) try: self.close() self.transform.read_drag() @@ -393,5 +370,4 @@ def _execute(self, args): def attach(command): """Return the command session. Its owner retains it until command.destroy.""" - with open("/tmp/insertto-drag-detailed.log","a") as out: print("dialog.py/attach",file=out) return _Dialog(command) From aa08b31d2fe7bb94c17da85cdd89827c6a7a5d42 Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 12:34:39 +0300 Subject: [PATCH 05/13] perf: batch linked SVG inserts and increase preview contrast --- InsertTo/dialog.py | 19 +++-- InsertTo/drag_graphics.py | 18 +++-- InsertTo/frame_link.py | 135 ++++++++++++++++++++++++------------ tests/test_dialog.py | 3 +- tests/test_drag_graphics.py | 7 ++ tests/test_frame_link.py | 78 +++++++++++++++++++++ 6 files changed, 206 insertions(+), 54 deletions(-) diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 21db957..8c77889 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -62,6 +62,8 @@ def __init__(self, command): self.graphics = None self.graphics_key = None + self.source_document = None + self.source_curves = None self.graphics_pivot = None command.isExecutedWhenPreEmpted = False @@ -146,6 +148,8 @@ def _changed(self, args): changed = args.input.id try: if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor', + self.source_document = None + self.source_curves = None 'fitAlignX', 'fitAlignY', 'svgBounds', 'frameInset', 'linkFrame'): if self.transform.handles(changed): self.preview_error = '' @@ -298,10 +302,13 @@ def _preview_graphics(self, sketch, plane): self.close() destination = fusion_import.sketch_for_target(self.design, sketch, plane) source = svg_geometry.Placement(0, 0, self.document.width_mm, self.document.height_mm) - curves = preview_source.simple_curves(self.document) - if curves is None: - curves = fusion_import.source_curves(destination, self.document) - self.graphics = drag_graphics.DragGraphics.capture(destination, curves, source) + if self.source_document is not self.document: + curves = preview_source.simple_curves(self.document) + if curves is None: + curves = fusion_import.source_curves(destination, self.document) + self.source_curves = curves + self.source_document = self.document + self.graphics = drag_graphics.DragGraphics.capture(destination, self.source_curves, source) self.graphics_key = key if self._use_artwork() and self.artwork_bounds is None: self.artwork_bounds = self.graphics.artwork_bounds() @@ -330,7 +337,9 @@ def _insert(self, sketch, plane): _, target, settings = self._placements() if self._linked(settings): entities = [self.frame.selection(i).entity for i in range(self.frame.selectionCount)] - frame_link.insert(destination, self.document, target, entities, **settings) + curves = self.source_curves if self.source_document is self.document else None + frame_link.insert(destination, self.document, target, entities, source_curves=curves, + **settings) else: fusion_import.import_svg(destination, self.document, target, self.bounds) self._dimensions(target) diff --git a/InsertTo/drag_graphics.py b/InsertTo/drag_graphics.py index 2c6c284..e773f45 100644 --- a/InsertTo/drag_graphics.py +++ b/InsertTo/drag_graphics.py @@ -103,13 +103,21 @@ def _lines(self, coords, indices, construction): buffer = adsk.fusion.CustomGraphicsCoordinates.create(coords) lines = self._group.addLines(buffer, indices, False) lines.isSelectable = False - rgb = (206, 132, 50) if construction else (36, 149, 218) - lines.color = adsk.fusion.CustomGraphicsSolidColorEffect.create( - adsk.core.Color.create(*rgb, 255) - ) if construction: + lines.color = adsk.fusion.CustomGraphicsSolidColorEffect.create( + adsk.core.Color.create(171, 108, 40, 255) + ) + lines.weight = 1.5 lines.lineStylePattern = adsk.fusion.LineStylePatterns.dashedLineStylePattern - lines.depthPriority = 5 + lines.depthPriority = 5 + else: + # Keep the drawing visible on a coplanar face or selected sketch profile. + lines.color = adsk.fusion.CustomGraphicsShowThroughColorEffect.create( + adsk.core.Color.create(132, 81, 184, 255), 1.0 + ) + lines.weight = 3.0 + lines.lineStylePattern = adsk.fusion.LineStylePatterns.continuousLineStylePattern + lines.depthPriority = 10 return lines def _draw_outline(self): diff --git a/InsertTo/frame_link.py b/InsertTo/frame_link.py index 00d055b..f1dacb1 100644 --- a/InsertTo/frame_link.py +++ b/InsertTo/frame_link.py @@ -1,5 +1,6 @@ """Maintain fitted SVG geometry when a linked sketch frame changes.""" +from contextlib import contextmanager from dataclasses import dataclass import json import math @@ -90,42 +91,93 @@ def resolve(token): raise ValueError('The linked frame is missing or has changed topology.') -def _source_geometry(sketch, doc): - return [g if g.objectType == 'adsk::core::NurbsCurve3D' else g.asNurbsCurve - for g in fusion_import.source_curves(sketch, doc)] +class _RestoreFailed(RuntimeError): + """The entire Fusion command transaction must roll back.""" + + +@contextmanager +def _batch_edit(sketch): + """Solve once while keeping downstream features out of the deferred edit.""" + if sketch.isComputeDeferred: + yield + return + timeline = sketch.parentComponent.parentDesign.timeline + marker = timeline.markerPosition if timeline else 0 + moved = False + try: + if timeline and timeline.count: + item = sketch.timelineObject + index = item.index if item else -1 + if index < 0 or marker <= index: + # A suppressed sketch or collapsed timeline group has no safe + # marker to roll to. Keep Fusion's normal per-curve solve. + yield + return + if marker != index + 1: + moved = True + try: + rolled = item.rollTo(False) + except RuntimeError: + rolled = False + if not rolled: + # Some edit contexts prohibit moving the timeline. + # Retain the usual eager insert in the original context. + if timeline.markerPosition != marker: + timeline.markerPosition = marker + yield + return + sketch.isComputeDeferred = True + try: + yield + finally: + try: + sketch.isComputeDeferred = False + except Exception as error: + raise _RestoreFailed('Fusion could not recompute the linked sketch.') from error + finally: + if moved and timeline.markerPosition != marker: + try: + timeline.markerPosition = marker + except Exception as error: + raise _RestoreFailed('Fusion could not restore the timeline position.') from error def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, inset_mm=0, - x_mm=0, y_mm=0, rotation=0, scale=1): - """Create associative curves and their record in the preview/execute transaction.""" + x_mm=0, y_mm=0, rotation=0, scale=1, source_curves=None): + """Create associative curves and their record in the execute transaction.""" if mode not in ('fit', 'stretch'): raise ValueError('A frame link requires Fit or Stretch.') reference = _frame_reference(sketch, list(frame_entities)) - geometry = _source_geometry(sketch, doc) + geometry = fusion_import.source_curves(sketch, doc) if source_curves is None else source_curves if not geometry: raise ValueError('The SVG contains no curves that can be linked.') matrix = _matrix(svg_geometry.Placement(0, 0, doc.width_mm, doc.height_mm), target) link_id = uuid4().hex added = [] - try: - for nurbs in geometry: - if not nurbs.transformBy(matrix): - raise ValueError('Fusion could not position a linked SVG curve.') - curve = sketch.sketchCurves.sketchFixedSplines.addByNurbsCurve(nurbs) - if not curve: - raise ValueError('Fusion could not create a linked SVG curve.') - added.append(curve) - curve.attributes.add(_CURVES, link_id, '1') - record = {'frame': reference, 'page': [doc.width_mm, doc.height_mm], - 'pose': _pose(target), 'count': len(added), - 'options': dict(mode=mode, anchor=anchor, bounds=bounds, inset_mm=inset_mm, - x_mm=x_mm, y_mm=y_mm, rotation=rotation, scale=scale)} - sketch.attributes.add(_RECORD, link_id, json.dumps(record)) - except Exception: - for curve in reversed(added): - if curve.isValid: - curve.deleteMe() - raise + with _batch_edit(sketch): + splines = sketch.sketchCurves.sketchFixedSplines + try: + for source in geometry: + # A preview can own these transient curves until command teardown. + nurbs = (source.copy() if source.objectType == 'adsk::core::NurbsCurve3D' + else source.asNurbsCurve) + if not nurbs or not nurbs.transformBy(matrix): + raise ValueError('Fusion could not position a linked SVG curve.') + curve = splines.addByNurbsCurve(nurbs) + if not curve: + raise ValueError('Fusion could not create a linked SVG curve.') + added.append(curve) + curve.attributes.add(_CURVES, link_id, '1') + record = {'frame': reference, 'page': [doc.width_mm, doc.height_mm], + 'pose': _pose(target), 'count': len(added), + 'options': dict(mode=mode, anchor=anchor, bounds=bounds, inset_mm=inset_mm, + x_mm=x_mm, y_mm=y_mm, rotation=rotation, scale=scale)} + sketch.attributes.add(_RECORD, link_id, json.dumps(record)) + except Exception: + for curve in reversed(added): + if curve.isValid: + curve.deleteMe() + raise def _changed(design, attr): @@ -146,10 +198,6 @@ def _owned_curves(design, attr): return [c for c in curves if c and c.isValid and c.parentSketch == sketch] -class _RestoreFailed(RuntimeError): - """The entire Fusion command transaction must roll back.""" - - def _refresh(attr, record, target, curves): matrix = _matrix(svg_geometry.Placement(*record['pose']), target) edits = [] @@ -160,21 +208,22 @@ def _refresh(attr, record, target, curves): raise ValueError('Fusion could not transform a linked curve.') edits.append((curve, original, updated)) - applied = [] - try: - for curve, original, updated in edits: - if not curve.replaceGeometry(updated): - raise ValueError('Fusion could not update a linked curve.') - applied.append((curve, original)) - attr.value = json.dumps(dict(record, pose=_pose(target))) - except Exception: + with _batch_edit(attr.parent): + applied = [] try: - for curve, original in reversed(applied): - if not curve.replaceGeometry(original): - raise _RestoreFailed('Fusion could not restore a linked curve.') - except Exception as error: - raise _RestoreFailed('Fusion could not restore the linked geometry.') from error - raise + for curve, original, updated in edits: + if not curve.replaceGeometry(updated): + raise ValueError('Fusion could not update a linked curve.') + applied.append((curve, original)) + attr.value = json.dumps(dict(record, pose=_pose(target))) + except Exception: + try: + for curve, original in reversed(applied): + if not curve.replaceGeometry(original): + raise _RestoreFailed('Fusion could not restore a linked curve.') + except Exception as error: + raise _RestoreFailed('Fusion could not restore the linked geometry.') from error + raise def _attach(event, base, notify): diff --git a/tests/test_dialog.py b/tests/test_dialog.py index d457fec..539f6cd 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -212,7 +212,8 @@ def test_linked_fit_persists_the_same_settings_used_for_the_preview(self): session._execute(args) sketch, doc, target, entities = link.call_args.args self.assertEqual(target, self.graphics.show.call_args.args[0]) - settings = link.call_args.kwargs + settings = link.call_args.kwargs.copy() + self.assertIs(settings.pop('source_curves'), source.return_value) self.assertEqual(settings, dict(mode='fit', anchor='bottom-center', bounds=None, inset_mm=1., x_mm=4, y_mm=5, rotation=0.3, scale=1.2)) self.assertIs(sketch, session.sketch) diff --git a/tests/test_drag_graphics.py b/tests/test_drag_graphics.py index f631e6c..5b5f420 100644 --- a/tests/test_drag_graphics.py +++ b/tests/test_drag_graphics.py @@ -54,6 +54,13 @@ def test_changing_free_outline_only_updates_outline_batch(self): with patch.dict(sys.modules, {'adsk': sdk, 'adsk.core': sdk.core, 'adsk.fusion': sdk.fusion}): drawing.set_outline((0, 0, 100, 50)) drawing.show(page) + self.assertGreater(art.weight, page_outline.weight) + self.assertGreater(art.depthPriority, page_outline.depthPriority) + styles = sdk.fusion.LineStylePatterns + self.assertEqual(art.lineStylePattern, styles.continuousLineStylePattern) + self.assertEqual(page_outline.lineStylePattern, styles.dashedLineStylePattern) + self.assertEqual(art.color, sdk.fusion.CustomGraphicsShowThroughColorEffect.create.return_value) + self.assertEqual(page_outline.color, sdk.fusion.CustomGraphicsSolidColorEffect.create.return_value) drawing.set_outline((12, 4, 12, 30)) drawing.show(page) page_outline.deleteMe.assert_called_once() diff --git a/tests/test_frame_link.py b/tests/test_frame_link.py index 6a64b0d..af41709 100644 --- a/tests/test_frame_link.py +++ b/tests/test_frame_link.py @@ -72,3 +72,81 @@ def test_partial_refresh_restores_only_curves_successfully_replaced(self): first.replaceGeometry.assert_called_with(first.geometry) self.assertEqual(first.replaceGeometry.call_count, 2) self.assertEqual(json.loads(self.attr.value), record) + + +class BulkSketchEdits(unittest.TestCase): + def setUp(self): + self.sketch = Mock() + self.sketch.isComputeDeferred = False + self.timeline = SimpleNamespace(count=8, markerPosition=6) + self.sketch.parentComponent.parentDesign.timeline = self.timeline + self.sketch.timelineObject.index = 2 + + def roll(before): + self.assertFalse(before) + self.timeline.markerPosition = 3 + return True + + self.sketch.timelineObject.rollTo.side_effect = roll + + def test_many_cached_curves_share_a_single_solve_and_retain_original_geometry(self): + geometry = Mock(objectType='adsk::core::NurbsCurve3D') + drawing = SimpleNamespace(width_mm=20, height_mm=30) + + def add(curve): + self.assertIs(curve, geometry.copy.return_value) + self.assertEqual(self.timeline.markerPosition, 3) + self.assertTrue(self.sketch.isComputeDeferred) + return Mock() + + splines = self.sketch.sketchCurves.sketchFixedSplines + splines.addByNurbsCurve.side_effect = add + with patch.object(links, '_matrix'), patch.object(links, '_frame_reference', return_value={}), \ + patch.object(links.fusion_import, 'source_curves') as read: + links.insert(self.sketch, drawing, geo.Placement(1, 2, 20, 30), [], 'fit', 'center', + source_curves=[geometry] * 411) + self.assertEqual(splines.addByNurbsCurve.call_count, 411) + geometry.transformBy.assert_not_called() + read.assert_not_called() + self.sketch.timelineObject.rollTo.assert_called_once_with(False) + self.assertFalse(self.sketch.isComputeDeferred) + self.assertEqual(self.timeline.markerPosition, 6) + record = json.loads(self.sketch.attributes.add.call_args.args[2]) + self.assertEqual(record['count'], 411) + self.assertNotIn('source_curves', record['options']) + + def test_bulk_edit_restores_marker_on_failure(self): + with self.assertRaisesRegex(ValueError, 'invalid curve'): + with links._batch_edit(self.sketch): + self.assertTrue(self.sketch.isComputeDeferred) + self.assertEqual(self.timeline.markerPosition, 3) + raise ValueError('invalid curve') + self.assertFalse(self.sketch.isComputeDeferred) + self.assertEqual(self.timeline.markerPosition, 6) + + def test_grouped_sketch_uses_normal_solve_and_preserves_marker(self): + self.sketch.timelineObject.index = -1 + with links._batch_edit(self.sketch): + self.assertFalse(self.sketch.isComputeDeferred) + self.sketch.timelineObject.rollTo.assert_not_called() + + def test_roll_disallowed_by_edit_context_keeps_standard_insert_available(self): + self.sketch.timelineObject.rollTo.side_effect = RuntimeError('Cannot roll while editing') + with links._batch_edit(self.sketch): + self.assertFalse(self.sketch.isComputeDeferred) + self.assertEqual(self.timeline.markerPosition, 6) + + def test_last_sketch_and_direct_design_need_no_timeline_roll(self): + for timeline in (SimpleNamespace(count=3, markerPosition=3), None): + self.sketch.parentComponent.parentDesign.timeline = timeline + with links._batch_edit(self.sketch): + self.assertTrue(self.sketch.isComputeDeferred) + self.assertFalse(self.sketch.isComputeDeferred) + self.sketch.timelineObject.rollTo.assert_not_called() + + def test_nested_bulk_edit_keeps_callers_deferred_state(self): + self.sketch.isComputeDeferred = True + with links._batch_edit(self.sketch): + self.assertTrue(self.sketch.isComputeDeferred) + self.assertTrue(self.sketch.isComputeDeferred) + self.sketch.timelineObject.rollTo.assert_not_called() From 5a5cd66716d0ae81fa60d59cac8a7b26fd29ece1 Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 12:34:54 +0300 Subject: [PATCH 06/13] fix: initialize the SVG source cache with its document --- InsertTo/dialog.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 8c77889..19d59ff 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -57,13 +57,13 @@ def __init__(self, command): self.bounds = None self.frame_sketch = None self.artwork_bounds = None + self.source_document = None + self.source_curves = None self.file_error = '' self.preview_error = '' self.graphics = None self.graphics_key = None - self.source_document = None - self.source_curves = None self.graphics_pivot = None command.isExecutedWhenPreEmpted = False @@ -137,6 +137,8 @@ def _choose_file(self): self.browse.tooltip = filename self.document = None self.artwork_bounds = None + self.source_document = None + self.source_curves = None self.file_error = '' try: self.document = svg_geometry.read_svg(filename) @@ -148,8 +150,6 @@ def _changed(self, args): changed = args.input.id try: if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor', - self.source_document = None - self.source_curves = None 'fitAlignX', 'fitAlignY', 'svgBounds', 'frameInset', 'linkFrame'): if self.transform.handles(changed): self.preview_error = '' From c1621613adf051ef9b61afc2fa8fe43f6e282476 Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 12:39:17 +0300 Subject: [PATCH 07/13] perf: persist fitted SVG curve references in a single sketch index --- InsertTo/frame_link.py | 59 ++++++++++++++++++++++++++---- tests/test_frame_link.py | 77 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 128 insertions(+), 8 deletions(-) diff --git a/InsertTo/frame_link.py b/InsertTo/frame_link.py index f1dacb1..fecf00b 100644 --- a/InsertTo/frame_link.py +++ b/InsertTo/frame_link.py @@ -12,6 +12,9 @@ _RECORD = '4FusionLab.InsertTo.FrameLink.v1' _CURVES = '4FusionLab.InsertTo.LinkedCurves.v1' +_CURVE_INDEX = '4FusionLab.InsertTo.CurveTokens.v1' +# Attribute values have a 2 MiB limit. Leave room even for UTF-16 storage. +_MAX_INDEX_CHARS = 1024 * 1024 - 1 _REFRESH = '4FusionLab_InsertTo_RefreshFrames' _CHECK = '4FusionLab_InsertTo_CheckFrames' _listeners = None @@ -156,6 +159,7 @@ def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, in added = [] with _batch_edit(sketch): splines = sketch.sketchCurves.sketchFixedSplines + index_attr = None try: for source in geometry: # A preview can own these transient curves until command teardown. @@ -167,13 +171,26 @@ def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, in if not curve: raise ValueError('Fusion could not create a linked SVG curve.') added.append(curve) - curve.attributes.add(_CURVES, link_id, '1') record = {'frame': reference, 'page': [doc.width_mm, doc.height_mm], 'pose': _pose(target), 'count': len(added), 'options': dict(mode=mode, anchor=anchor, bounds=bounds, inset_mm=inset_mm, x_mm=x_mm, y_mm=y_mm, rotation=rotation, scale=scale)} - sketch.attributes.add(_RECORD, link_id, json.dumps(record)) + tokens = [curve.entityToken for curve in added] + encoded = json.dumps(tokens, separators=(',', ':')) + if all(tokens) and len(encoded) <= _MAX_INDEX_CHARS: + index_attr = sketch.attributes.add(_CURVE_INDEX, link_id, encoded) + if not index_attr: + raise ValueError('Fusion could not save the linked curve references.') + record['curveIndex'] = True + else: + for curve in added: + if not curve.attributes.add(_CURVES, link_id, '1'): + raise ValueError('Fusion could not tag a linked curve.') + if not sketch.attributes.add(_RECORD, link_id, json.dumps(record)): + raise ValueError('Fusion could not save the frame link.') except Exception: + if index_attr and index_attr.isValid: + index_attr.deleteMe() for curve in reversed(added): if curve.isValid: curve.deleteMe() @@ -192,10 +209,36 @@ def _changed(design, attr): return record, target -def _owned_curves(design, attr): +def _owned_curves(design, attr, record): sketch = attr.parent - curves = [tag.parent for tag in design.findAttributes(_CURVES, attr.name)] - return [c for c in curves if c and c.isValid and c.parentSketch == sketch] + if not record.get('curveIndex'): + # Earlier drawings and oversized token lists store ownership on the curves. + curves = [tag.parent for tag in design.findAttributes(_CURVES, attr.name)] + return [c for c in curves if c and c.isValid and c.parentSketch == sketch + and c.objectType == 'adsk::fusion::SketchFixedSpline'] + + import adsk.core + + index = sketch.attributes.itemByName(_CURVE_INDEX, attr.name) + if not index: + return [] + tokens = json.loads(index.value) + if not isinstance(tokens, list) or len(tokens) != record['count']: + return [] + curves = adsk.core.ObjectCollection.create() + for token in tokens: + if not isinstance(token, str) or not token: + return [] + matches = design.findEntityByToken(token) + if len(matches) != 1: + return [] + curve = matches[0] + if (not curve.isValid or curve.objectType != 'adsk::fusion::SketchFixedSpline' + or curve.parentSketch != sketch or curves.contains(curve)): + return [] + if not curves.add(curve): + return [] + return curves def _refresh(attr, record, target, curves): @@ -301,7 +344,11 @@ def changes(self, design): elif change: last = self.suppressed.get(key) if last is None or not _same_pose(last, _pose(change[1])): - curves = _owned_curves(design, attr) + try: + curves = _owned_curves(design, attr, change[0]) + except (ValueError, TypeError, RuntimeError) as error: + self.app.log(f'Smart Insert curve references: {error}') + continue if len(curves) == change[0]['count']: yield attr, *change, curves else: diff --git a/tests/test_frame_link.py b/tests/test_frame_link.py index af41709..81d455e 100644 --- a/tests/test_frame_link.py +++ b/tests/test_frame_link.py @@ -1,4 +1,5 @@ import json +import sys from types import SimpleNamespace import unittest from unittest.mock import Mock, patch @@ -97,7 +98,7 @@ def add(curve): self.assertIs(curve, geometry.copy.return_value) self.assertEqual(self.timeline.markerPosition, 3) self.assertTrue(self.sketch.isComputeDeferred) - return Mock() + return Mock(entityToken=f'curve-{splines.addByNurbsCurve.call_count}') splines = self.sketch.sketchCurves.sketchFixedSplines splines.addByNurbsCurve.side_effect = add @@ -111,7 +112,11 @@ def add(curve): self.sketch.timelineObject.rollTo.assert_called_once_with(False) self.assertFalse(self.sketch.isComputeDeferred) self.assertEqual(self.timeline.markerPosition, 6) - record = json.loads(self.sketch.attributes.add.call_args.args[2]) + index_call, record_call = self.sketch.attributes.add.call_args_list + self.assertEqual(index_call.args[:2], (links._CURVE_INDEX, record_call.args[1])) + self.assertEqual(len(json.loads(index_call.args[2])), 411) + record = json.loads(record_call.args[2]) + self.assertTrue(record['curveIndex']) self.assertEqual(record['count'], 411) self.assertNotIn('source_curves', record['options']) @@ -150,3 +155,71 @@ def test_nested_bulk_edit_keeps_callers_deferred_state(self): self.assertTrue(self.sketch.isComputeDeferred) self.assertTrue(self.sketch.isComputeDeferred) self.sketch.timelineObject.rollTo.assert_not_called() + + def test_large_index_falls_back_to_tags_without_changing_original_format(self): + drawing = SimpleNamespace(width_mm=20, height_mm=30) + curve = Mock(entityToken='token-too-long') + self.sketch.sketchCurves.sketchFixedSplines.addByNurbsCurve.return_value = curve + with patch.object(links, '_matrix'), patch.object(links, '_frame_reference', return_value={}), \ + patch.object(links, '_MAX_INDEX_CHARS', 2): + links.insert(self.sketch, drawing, geo.Placement(0, 0, 20, 30), [], 'fit', 'center', + source_curves=[Mock()]) + record = self.sketch.attributes.add.call_args + self.sketch.attributes.add.assert_called_once() + self.assertNotIn('curveIndex', json.loads(record.args[2])) + curve.attributes.add.assert_called_once_with(links._CURVES, record.args[1], '1') + + def test_failed_record_removes_index_and_curve(self): + curve = Mock(entityToken='new') + index = Mock(isValid=True) + self.sketch.attributes.add.side_effect = [index, None] + self.sketch.sketchCurves.sketchFixedSplines.addByNurbsCurve.return_value = curve + with patch.object(links, '_matrix'), patch.object(links, '_frame_reference', return_value={}), \ + self.assertRaisesRegex(ValueError, 'save the frame link'): + links.insert(self.sketch, SimpleNamespace(width_mm=20, height_mm=30), + geo.Placement(0, 0, 20, 30), [], 'fit', 'center', source_curves=[Mock()]) + index.deleteMe.assert_called_once() + curve.deleteMe.assert_called_once() + self.assertFalse(self.sketch.isComputeDeferred) + + +class CurveOwnership(unittest.TestCase): + def setUp(self): + class Collection(list): + contains = list.__contains__ + + def add(self, item): + self.append(item) + return True + + core = SimpleNamespace(ObjectCollection=SimpleNamespace(create=Collection)) + self.enterContext(patch.dict(sys.modules, {'adsk': SimpleNamespace(core=core), 'adsk.core': core})) + self.design = Mock() + self.attr = Mock() + self.attr.name = 'link' + self.index = self.attr.parent.attributes.itemByName.return_value + self.index.value = '["old-token","other-token"]' + self.curves = [Mock(objectType='adsk::fusion::SketchFixedSpline', parentSketch=self.attr.parent, + isValid=True) for _ in range(2)] + self.record = dict(count=2, curveIndex=True) + + def test_resolves_index_and_reads_old_format_without_index(self): + self.design.findEntityByToken.side_effect = [[c] for c in self.curves] + self.assertEqual(list(links._owned_curves(self.design, self.attr, self.record)), self.curves) + self.attr.parent.attributes.itemByName.assert_called_once_with(links._CURVE_INDEX, 'link') + self.design.findAttributes.assert_not_called() + self.design.findAttributes.return_value = [SimpleNamespace(parent=c) for c in self.curves] + self.assertEqual(links._owned_curves(self.design, self.attr, dict(count=2)), self.curves) + + def test_deleted_ambiguous_moved_wrong_type_and_alias_tokens_skip_whole_link(self): + first = self.curves[0] + for matches in ([], self.curves, [first], [Mock(isValid=False)], + [Mock(isValid=True, objectType='adsk::fusion::SketchLine')], + [Mock(isValid=True, objectType=first.objectType, parentSketch=Mock())]): + with self.subTest(matches=matches): + self.design.findEntityByToken.side_effect = [[first], matches] + self.assertEqual(links._owned_curves(self.design, self.attr, self.record), []) + self.index.value = '["old-token"]' + self.assertEqual(links._owned_curves(self.design, self.attr, self.record), []) + self.attr.parent.attributes.itemByName.return_value = None + self.assertEqual(links._owned_curves(self.design, self.attr, self.record), []) From 171606f505a7b4010733f2b9e7e286f95ddf6132 Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 13:07:11 +0300 Subject: [PATCH 08/13] feat: size SVGs independently and keep scaling anchored --- InsertTo/canvas_grips.py | 162 ++++++++++++++++ InsertTo/dialog.py | 59 +++++- InsertTo/dimensions.py | 106 ++++++++++ InsertTo/frame_link.py | 4 +- InsertTo/manipulator.py | 181 ++++++++++-------- InsertTo/resources/aspect-linked/16x16.png | Bin 0 -> 576 bytes InsertTo/resources/aspect-linked/16x16@2x.png | Bin 0 -> 1383 bytes InsertTo/resources/aspect-linked/32x32.png | Bin 0 -> 1383 bytes InsertTo/resources/aspect-linked/32x32@2x.png | Bin 0 -> 3505 bytes InsertTo/resources/aspect-unlinked/16x16.png | Bin 0 -> 545 bytes .../resources/aspect-unlinked/16x16@2x.png | Bin 0 -> 1305 bytes InsertTo/resources/aspect-unlinked/32x32.png | Bin 0 -> 1305 bytes .../resources/aspect-unlinked/32x32@2x.png | Bin 0 -> 3026 bytes InsertTo/resources/canvas-grips/move.png | Bin 0 -> 1311 bytes InsertTo/resources/canvas-grips/scale.png | Bin 0 -> 917 bytes InsertTo/svg_geometry.py | 16 +- README.md | 2 + README.ru.md | 2 + tests/test_canvas_grips.py | 97 ++++++++++ tests/test_dialog.py | 21 +- tests/test_dimensions.py | 110 +++++++++++ tests/test_frame_link.py | 19 ++ tests/test_manipulator.py | 131 ++++++++++--- tests/test_svg_geometry.py | 27 +++ 24 files changed, 827 insertions(+), 110 deletions(-) create mode 100644 InsertTo/canvas_grips.py create mode 100644 InsertTo/dimensions.py create mode 100644 InsertTo/resources/aspect-linked/16x16.png create mode 100644 InsertTo/resources/aspect-linked/16x16@2x.png create mode 100644 InsertTo/resources/aspect-linked/32x32.png create mode 100644 InsertTo/resources/aspect-linked/32x32@2x.png create mode 100644 InsertTo/resources/aspect-unlinked/16x16.png create mode 100644 InsertTo/resources/aspect-unlinked/16x16@2x.png create mode 100644 InsertTo/resources/aspect-unlinked/32x32.png create mode 100644 InsertTo/resources/aspect-unlinked/32x32@2x.png create mode 100644 InsertTo/resources/canvas-grips/move.png create mode 100644 InsertTo/resources/canvas-grips/scale.png create mode 100644 tests/test_canvas_grips.py create mode 100644 tests/test_dimensions.py diff --git a/InsertTo/canvas_grips.py b/InsertTo/canvas_grips.py new file mode 100644 index 0000000..ffc0c68 --- /dev/null +++ b/InsertTo/canvas_grips.py @@ -0,0 +1,162 @@ +"""Screen-sized SVG move and scale handles projected onto the sketch plane.""" + +import math +from pathlib import Path + + +_ICONS = Path(__file__).with_name('resources') / 'canvas-grips' +_HIT_RADIUS = 12.0 # Viewport pixels. + + +def _dot(a, b): + return sum(x * y for x, y in zip(a, b)) + + +def _minus(a, b): + return tuple(x - y for x, y in zip(a, b)) + + +def _model_point(basis, sketch_mm): + origin, vx, vy, _ = basis + x, y = sketch_mm + return tuple(o + (x * i + y * j) / 10 for o, i, j in zip(origin, vx, vy)) + + +def _intersect(basis, start, direction): + origin, vx, vy, normal = basis + denominator = _dot(direction, normal) + if abs(denominator) <= 1e-10 * math.hypot(*direction): + return None + depth = _dot(_minus(origin, start), normal) / denominator + relative = tuple(p + depth * d - o for p, d, o in zip(start, direction, origin)) + return (10 * _dot(relative, vx), 10 * _dot(relative, vy)) + + +class CanvasGrips: + def __init__(self, viewport): + self.viewport = viewport + self._root = self._basis = self._group = None + self._points = () + self._handles = () + self._gesture = None + + def show(self, root_component, basis, target): + import adsk.fusion + + if root_component != self._root or self._basis != basis: + self.clear() + self._root = root_component + self._basis = basis + outline = target.outline + pivot = target.pivot + if pivot is None: + pivot = tuple((a + b) / 2 for a, b in zip(outline[0], outline[2])) + # Prefer the upper right for a centered drawing, including after a rotation. + corner = outline[2] + distance = math.dist(pivot, corner) + for candidate in outline: + d = math.dist(pivot, candidate) + if d > distance and not math.isclose(d, distance, rel_tol=1e-12): + corner, distance = candidate, d + handles = (pivot, corner) + if self._group and self._group.isValid and handles == self._handles: + return + + coordinates = [adsk.fusion.CustomGraphicsCoordinates.create( + list(_model_point(basis, pt))) for pt in handles] + if self._group and self._group.isValid: + for marker, coord in zip(self._points, coordinates): + marker.coordinates = coord + else: + group = root_component.customGraphicsGroups.add() + try: + group.isSelectable = False + kind = adsk.fusion.CustomGraphicsPointTypes.UserDefinedCustomGraphicsPointType + markers = [] + for coord, icon in zip(coordinates, ('move.png', 'scale.png')): + marker = group.addPointSet(coord, [], kind, str(_ICONS / icon)) + marker.isSelectable = False + marker.depthPriority = 20 + markers.append(marker) + except Exception: + group.deleteMe() + raise + self._group, self._points = group, markers + self._handles = handles + + def _screen(self, sketch_mm): + import adsk.core + + world = adsk.core.Point3D.create(*_model_point(self._basis, sketch_mm)) + projected = self.viewport.modelToViewSpace(world) + return projected.x, projected.y + + def _on_plane(self, view_point): + import adsk.core + + near = self.viewport.viewToModelSpace(view_point) + if near is None: + return None + camera = self.viewport.camera + eye, target, sample = camera.eye.asArray(), camera.target.asArray(), near.asArray() + types = adsk.core.CameraTypes + if camera.cameraType == types.OrthographicCameraType: + return _intersect(self._basis, sample, _minus(target, eye)) + perspective = _intersect(self._basis, eye, _minus(sample, eye)) + if camera.cameraType == types.PerspectiveCameraType: + return perspective + # The hybrid camera switches projection as it snaps to an orthogonal face. + # Test both rays against Fusion's current screen projection. + ortho = _intersect(self._basis, sample, _minus(target, eye)) + candidates = [p for p in (perspective, ortho) if p is not None] + mouse = view_point.x, view_point.y + return min(candidates, key=lambda p: math.dist(self._screen(p), mouse), default=None) + + @property + def dragging(self): + return self._gesture is not None + + def dragBegin(self, args, current_values_mm): + import adsk.core + + self.end() + mouse = args.viewportPosition + if (mouse is None or not self._handles or not self._group or not self._group.isValid + or not (args.button & adsk.core.MouseButtons.LeftMouseButton)): + return False + xy = (mouse.x, mouse.y) + distances = [math.dist(self._screen(pt), xy) for pt in self._handles] + hit = distances.index(min(distances)) + if distances[hit] > _HIT_RADIUS: + return False + start = self._on_plane(mouse) + if start is None: + return False + radius = _minus(self._handles[1], self._handles[0]) + if hit == 1 and _dot(radius, radius) < 1e-12: + return False + self._gesture = (hit, start, radius, tuple(current_values_mm)) + return True + + def drag(self, args): + if self._gesture is None or args.viewportPosition is None: + return None + current = self._on_plane(args.viewportPosition) + if current is None: + return None + hit, start, radius, (dx, dy, angle, scale) = self._gesture + delta = _minus(current, start) + if hit == 0: + return dx + delta[0], dy + delta[1], angle, scale + ratio = 1 + _dot(delta, radius) / _dot(radius, radius) + return dx, dy, angle, scale * max(ratio, 1e-4) + + def end(self): + self._gesture = None + + def clear(self): + self.end() + if self._group and self._group.isValid: + self._group.deleteMe() + self._root = self._basis = self._group = None + self._points = self._handles = () diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 19d59ff..47e33ce 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -7,6 +7,7 @@ import adsk.fusion from . import drag_graphics, frame_link, fusion_import, preview_source, svg_geometry +from .dimensions import SizeControls from .manipulator import TransformControls @@ -105,6 +106,8 @@ def __init__(self, command): self.link = inputs.addBoolValueInput('linkFrame', 'Link to frame', True, '', True) self.link.tooltip = 'Update the inserted curves when the source frame changes.' self.transform = TransformControls(inputs, units) + self.sizes = SizeControls(self.transform.group.children, units) if self.link is not None else None + self.grips = None self.command = command self.status = inputs.addTextBoxCommandInput('importStatus', '', '', 2, True) self.status.isFullWidth = True @@ -115,7 +118,11 @@ def __init__(self, command): _listen(command.inputChanged, adsk.core.InputChangedEventHandler, self._changed), _listen(command.validateInputs, adsk.core.ValidateInputsEventHandler, self._validate), _listen(command.executePreview, adsk.core.CommandEventHandler, self._preview), - _listen(command.mouseDragEnd, adsk.core.MouseEventHandler, self._dragged), + _listen(command.mouseMove, adsk.core.MouseEventHandler, self.transform.check_angle_origin), + _listen(command.mouseDown, adsk.core.MouseEventHandler, self._drag_begin), + _listen(command.mouseUp, adsk.core.MouseEventHandler, self._drag_end), + _listen(command.mouseDragBegin, adsk.core.MouseEventHandler, self._drag_begin), + _listen(command.mouseDragEnd, adsk.core.MouseEventHandler, self._drag_end), _listen(command.mouseDrag, adsk.core.MouseEventHandler, self._dragged), _listen(command.execute, adsk.core.CommandEventHandler, self._execute), ] @@ -149,6 +156,11 @@ def _choose_file(self): def _changed(self, args): changed = args.input.id try: + if self.sizes is not None and self.sizes.handles(changed): + self.preview_error = '' + if self.sizes.changed(changed): + self._move_graphics() + return if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor', 'fitAlignX', 'fitAlignY', 'svgBounds', 'frameInset', 'linkFrame'): if self.transform.handles(changed): @@ -167,8 +179,27 @@ def _changed(self, args): self.app.log(traceback.format_exc()) self.preview_error = str(exc) + def _drag_begin(self, args): + if self.grips and not self.grips.dragging: + try: + values = self.transform.values() + except ValueError: + return + self.grips.dragBegin(args, values) + + def _drag_end(self, args): + try: + self._dragged(args) + finally: + if self.grips: + self.grips.end() + def _dragged(self, args): - if self.transform.read_drag(): + values = self.grips.drag(args) if self.grips else None + if values is not None: + if self.transform.apply_drag(values): + self._move_graphics() + elif self.transform.read_drag(): self.preview_error = '' self._move_graphics() @@ -176,13 +207,24 @@ def _move_graphics(self): if self.graphics: try: _, target, _ = self._placements() - self.graphics.show(target) + self._show_preview(target) self._dimensions(target) except Exception as exc: self.preview_error = str(exc) self._status(self.preview_error) + def _show_preview(self, target): + from .canvas_grips import CanvasGrips + + self.graphics.show(target) + if self.grips is None: + self.grips = CanvasGrips(self.app.activeViewport) + self.grips.show(self.transform.root, self.transform.plane_basis, target) + def close(self): + if self.grips: + self.grips.clear() + self.grips = None if self.graphics: self.graphics.clear() self.graphics = self.graphics_key = self.graphics_pivot = None @@ -254,6 +296,15 @@ def _placements(self): self._show_alignment(fit_options) settings = dict(mode=mode, anchor=anchor, bounds=artwork, inset_mm=inset) baseline = svg_geometry.placement(self.document, frame, **settings) + if self.sizes is not None: + left, bottom, right, top = baseline.selected_box + original_w, original_h = self.document.width_mm, self.document.height_mm + if artwork is not None: + original_w, original_h = artwork[2] - artwork[0], artwork[3] - artwork[1] + aspect = original_w / original_h if original_w > 0 and original_h > 0 else None + width_factor, height_factor = self.sizes.update(right - left, top - bottom, aspect) + if width_factor != 1 or height_factor != 1: + settings.update(width_factor=width_factor, height_factor=height_factor) dx, dy, angle, scale = self.transform.values() settings.update(x_mm=dx, y_mm=dy, rotation=angle, scale=scale) target = svg_geometry.placement(self.document, frame, **settings) @@ -326,7 +377,7 @@ def _preview_graphics(self, sketch, plane): finally: if sketch is None and destination is not None and destination.isValid: destination.deleteMe() - self.graphics.show(target) + self._show_preview(target) self._dimensions(target) def _insert(self, sketch, plane): diff --git a/InsertTo/dimensions.py b/InsertTo/dimensions.py new file mode 100644 index 0000000..7ab6915 --- /dev/null +++ b/InsertTo/dimensions.py @@ -0,0 +1,106 @@ +"""Editable SVG width and height in Fusion document length units.""" + +import math +from pathlib import Path + + +_ICONS = Path(__file__).with_name('resources') + + +class SizeControls: + def __init__(self, children, length_units): + import adsk.core + + initial = adsk.core.ValueInput.createByReal + self.width = children.addValueInput('svgWidth', 'Width', length_units, initial(1.0)) + self.height = children.addValueInput('svgHeight', 'Height', length_units, initial(1.0)) + self.link = children.addBoolValueInput( + 'svgLockAspect', 'Link width and height', True, str(_ICONS / 'aspect-linked'), True + ) + self.link.tooltip = 'Use the original drawing proportions when editing width or height.' + self._fields = (self.width, self.height) + for field in self._fields: + field.minimumValue = 0 + field.isMinimumLimited = True + field.isMinimumInclusive = True # A vertical or horizontal drawing has one zero axis. + self._base = None + self._factors = [1., 1.] + self._display_mm = (None, None) + self._last_edited = None + self._locked = True + self._syncing = False + + def handles(self, input_id): + return not self._syncing and input_id in (self.width.id, self.height.id, self.link.id) + + def changed(self, input_id): + if not self.handles(input_id): + return False + if input_id == self.link.id: + if self.link.value == self._locked: + return False + self._locked = self.link.value + icon = _ICONS / ('aspect-linked' if self.link.value else 'aspect-unlinked') + if self.link.resourceFolder != str(icon): + self._syncing = True + try: + self.link.resourceFolder = str(icon) + finally: + self._syncing = False + if self.link.value and self._last_edited is None: + self._last_edited = 0 + return True + + axis = 0 if input_id == self.width.id else 1 + if self._base is None or self._base[axis] == 0: + return False + field = self._fields[axis] + if not field.isValidExpression or not math.isfinite(field.value) or field.value <= 0: + return True # Keep the entered expression; update reports the validation error. + mm = field.value * 10 + if math.isclose(mm, self._display_mm[axis], rel_tol=1e-12, abs_tol=1e-10): + return False + self._last_edited = axis + self._factors[axis] = mm / self._base[axis] + return True + + def update(self, base_width_mm, base_height_mm, aspect_of_original_w_over_h): + """Show pre-scale dimensions and return corrections relative to the current fitted size.""" + base = (base_width_mm, base_height_mm) + if any(not math.isfinite(length) or length < 0 for length in base): + raise ValueError('The selected SVG bounds have invalid dimensions.') + if self._base: + for field, previous in zip(self._fields, self._base): + if previous > 0 and (not field.isValidExpression or + not math.isfinite(field.value) or field.value <= 0): + raise ValueError('Enter a positive length for Width and Height.') + + self._base = base + ratio = aspect_of_original_w_over_h + can_link = min(base) > 0 and ratio is not None and math.isfinite(ratio) and ratio > 0 + axis = self._last_edited + if self.link.value and axis is not None and base[axis] > 0: + other = 1 - axis + if can_link: + length = base[axis] * self._factors[axis] + opposite = length / ratio if axis == 0 else length * ratio + self._factors[other] = opposite / base[other] + elif base[other] == 0: + self._factors[other] = self._factors[axis] + + self._display_mm = tuple(length * factor for length, factor in zip(base, self._factors)) + if not all(map(math.isfinite, self._display_mm)): + raise ValueError('The requested SVG dimensions are too large.') + self._syncing = True + try: + if self.link.isEnabled != can_link: + self.link.isEnabled = can_link + for field, length, mm in zip(self._fields, base, self._display_mm): + if field.isEnabled != (length > 0): + field.isEnabled = length > 0 + cm = mm / 10 + if not math.isclose(field.value, cm, rel_tol=1e-12, abs_tol=1e-11): + field.value = cm + finally: + self._syncing = False + return tuple(self._factors) diff --git a/InsertTo/frame_link.py b/InsertTo/frame_link.py index fecf00b..3a921da 100644 --- a/InsertTo/frame_link.py +++ b/InsertTo/frame_link.py @@ -146,7 +146,7 @@ def _batch_edit(sketch): def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, inset_mm=0, - x_mm=0, y_mm=0, rotation=0, scale=1, source_curves=None): + x_mm=0, y_mm=0, rotation=0, width_factor=1, height_factor=1, scale=1, source_curves=None): """Create associative curves and their record in the execute transaction.""" if mode not in ('fit', 'stretch'): raise ValueError('A frame link requires Fit or Stretch.') @@ -175,6 +175,8 @@ def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, in 'pose': _pose(target), 'count': len(added), 'options': dict(mode=mode, anchor=anchor, bounds=bounds, inset_mm=inset_mm, x_mm=x_mm, y_mm=y_mm, rotation=rotation, scale=scale)} + if width_factor != 1 or height_factor != 1: + record['options'].update(width_factor=width_factor, height_factor=height_factor) tokens = [curve.entityToken for curve in added] encoded = json.dumps(tokens, separators=(',', ':')) if all(tokens) and len(encoded) <= _MAX_INDEX_CHARS: diff --git a/InsertTo/manipulator.py b/InsertTo/manipulator.py index ad0a259..5a731e3 100644 --- a/InsertTo/manipulator.py +++ b/InsertTo/manipulator.py @@ -1,4 +1,4 @@ -"""Planar Fusion triad shared by the Transform fields and the on-canvas handles.""" +"""Planar Transform inputs and native translation and rotation handles.""" import math @@ -8,116 +8,145 @@ class TransformControls: def __init__(self, inputs, length_units): self.group = inputs.addGroupCommandInput('transformGroup', 'Transform') + self.group.isVisible = False + self.group.isExpanded = True children = self.group.children real = adsk.core.ValueInput.createByReal + # The distance and angle controls display the active document units. self.fields = [ - children.addValueInput('offsetX', 'Move X', length_units, real(0)), - children.addValueInput('offsetY', 'Move Y', length_units, real(0)), - children.addValueInput('rotateSVG', 'Rotation', 'deg', real(0)), + children.addDistanceValueCommandInput('offsetX', 'Move X', real(0)), + children.addDistanceValueCommandInput('offsetY', 'Move Y', real(0)), + children.addAngleValueCommandInput('rotateSVG', 'Rotation', real(0)), children.addValueInput('scaleSVG', 'Scale factor', '', real(1)), ] + self.fields[-1].tooltip = ('Drag the corner handle to scale about the anchor. ' + 'Scale is applied after Width and Height.') self.fields[-1].minimumValue = 0 self.fields[-1].isMinimumLimited = True self.fields[-1].isMinimumInclusive = False - self._properties = ('xTranslation', 'yTranslation', 'zRotation', 'xYPlaneScaleFactor') + self.root = self.plane_basis = self._pivot = None self._last_values = (0., 0., 0., 1.) - self.group.isExpanded = True - self.group.isVisible = False - self.triad = None - self._basis = None self._updating = False + self._angle_origin = None def handles(self, input_id): - return not self._updating and ( - input_id == 'placementTransform' or any(f.id == input_id for f in self.fields) - ) + return not self._updating and any(field.id == input_id for field in self.fields) - def changed(self, input_id): - if self._updating: - return False - for field, prop in zip(self.fields, self._properties): - if field.id == input_id and field.isValidExpression and self.triad: - if prop == 'xYPlaneScaleFactor' and field.value <= 0: - return False - self._updating = True - try: - setattr(self.triad, prop, field.value) - self._last_values = self._triad_values() - finally: - self._updating = False - return True - return self.read_drag() + def values(self): + if not all(f.isValidExpression for f in self.fields): + raise ValueError('Enter valid Transform distances, angle and scale.') + x, y, angle, scale = (f.value for f in self.fields) + if not all(map(math.isfinite, (x, y, angle, scale))) or scale <= 0: + raise ValueError('Transform requires a positive scale and finite coordinates.') + return x * 10, y * 10, angle, scale - def _triad_values(self): - return tuple(getattr(self.triad, prop) for prop in self._properties) + def changed(self, input_id): + return self.handles(input_id) and self.read_drag() def read_drag(self): - if self._updating or self.triad is None or not self.group.isVisible: + """Both a native drag and an expression edit change the same Fusion field.""" + if self._updating or self.plane_basis is None or not self.group.isVisible: + return False + try: + values = self.values() + except ValueError: return False - values = self._triad_values() - if all(math.isclose(a, b, abs_tol=1e-10) for a, b in zip(values, self._last_values)): + if values == self._last_values: return False self._updating = True try: - for field, previous, current in zip(self.fields, self._last_values, values): - if not math.isclose(previous, current, abs_tol=1e-10): - field.value = current + self._place_handles(values, previous=self._last_values) self._last_values = values finally: self._updating = False return True - def hide(self): - if self.group.isVisible: - self.group.isVisible = False + def apply_drag(self, values_mm): + """Apply an XY or scale grip result in sketch mm, radians and uniform factor.""" + if self._updating or self.plane_basis is None or not self.group.isVisible: + return False + x, y, angle, scale = values_mm + if not all(map(math.isfinite, (x, y, angle, scale))) or scale <= 0: + return False + self._updating = True + try: + for field, value in zip(self.fields, (x / 10, y / 10, angle, scale)): + if not math.isclose(field.value, value, rel_tol=1e-12, abs_tol=1e-12): + field.value = value + finally: + self._updating = False + return self.read_drag() - def values(self): - if not all(f.isValidExpression for f in self.fields): - raise ValueError('Enter valid Transform distances, angle and scale.') - x, y, angle, factor = (field.value for field in self.fields) - if not all(map(math.isfinite, (x, y, angle, factor))) or factor <= 0: - raise ValueError('Transform requires a positive scale and finite coordinates.') - return x * 10, y * 10, angle, factor + def _place_handles(self, values, previous=None): + origin, vx, vy, _ = self.plane_basis + px, py = self._pivot + dx, dy, _, _ = values + point = adsk.core.Point3D.create + vector = adsk.core.Vector3D.create + + def world(x_mm, y_mm): + return point(*(o + ax * x_mm / 10 + ay * y_mm / 10 for o, ax, ay in zip(origin, vx, vy))) + + # Fusion offsets a distance arrow from its manipulator origin by the + # input value. Only move its perpendicular base when the other axis changes. + if previous is None or dy != previous[1]: + if not self.fields[0].setManipulator(world(px, py + dy), vector(*vx)): + raise ValueError('Fusion could not position the X handle.') + if previous is None or dx != previous[0]: + if not self.fields[1].setManipulator(world(px + dx, py), vector(*vy)): + raise ValueError('Fusion could not position the Y handle.') + if previous is None or (dx, dy) != previous[:2]: + self._angle_origin = world(px + dx, py + dy) + if not self.fields[2].setManipulator(self._angle_origin, vector(*vx), vector(*vy)): + raise ValueError('Fusion could not position the rotation handle.') def position(self, sketch, pivot_xy_mm): - """Keep the original triad basis stable throughout dragging and preview rollback.""" + """Place all handles in root component coordinates, including occurrence sketches.""" + design = sketch.parentComponent.parentDesign if sketch.assemblyContext is None: - occurrence = sketch.parentComponent.parentDesign.activeOccurrence + occurrence = design.activeOccurrence if occurrence and occurrence.component == sketch.parentComponent: sketch = sketch.createForAssemblyContext(occurrence) point = adsk.core.Point3D.create - x, y = (v / 10 for v in pivot_xy_mm) - origin = sketch.sketchToModelSpace(point(x, y, 0)) - vx = origin.vectorTo(sketch.sketchToModelSpace(point(x + 1, y, 0))) - vy = origin.vectorTo(sketch.sketchToModelSpace(point(x, y + 1, 0))) - basis = (*origin.asArray(), *vx.asArray(), *vy.asArray()) - if self._basis and all(abs(a - b) < 1e-8 for a, b in zip(self._basis, basis)): - if not self.group.isVisible: - self.group.isVisible = True + origin = sketch.sketchToModelSpace(point(0, 0, 0)) + vx = origin.vectorTo(sketch.sketchToModelSpace(point(1, 0, 0))) + vy = origin.vectorTo(sketch.sketchToModelSpace(point(0, 1, 0))) + basis = tuple(tuple(item.asArray()) for item in (origin, vx, vy, vx.crossProduct(vy))) + pivot = tuple(pivot_xy_mm) + root = design.rootComponent + if self.group.isVisible and self.root == root and self.plane_basis == basis and self._pivot == pivot: return - self._updating = True try: - if self.triad: - self.triad.deleteMe() - self.triad = None - self._basis = None - initial = adsk.core.Matrix3D.create() - initial.setWithCoordinateSystem(origin, vx, vy, vx.crossProduct(vy)) - triad = self.group.children.addTriadCommandInput('placementTransform', initial) - self.triad = triad - triad.hideAll() - triad.isXTranslationVisible = True - triad.isYTranslationVisible = True - triad.isXYPlaneTranslationVisible = True - triad.isZRotationVisible = True - triad.isXYPlaneScalingVisible = True - for prop, field in zip(self._properties, self.fields): - setattr(triad, prop, field.value) - self._last_values = self._triad_values() - self._basis = basis + self.root, self.plane_basis, self._pivot = root, basis, pivot + values = self.values() self.group.isVisible = True - triad.isVisible = True - triad.isEnabled = True + for field in self.fields[:3]: + field.isVisible = True + field.isEnabled = True + self._place_handles(values) + self._last_values = values finally: self._updating = False + + def check_angle_origin(self, _args=None): + # Fusion can initialize the angle glyph at the global origin after the + # first preview. Restore it once the native control has been displayed. + expected = self._angle_origin + if expected is None or self._updating or not self.group.isVisible: + return + angle = self.fields[2] + actual = angle.manipulatorOrigin + if actual is not None and actual.distanceTo(expected) < 1e-8: + self._angle_origin = None + return + _, vx, vy, _ = self.plane_basis + vector = adsk.core.Vector3D.create + self._updating = True + try: + angle.setManipulator(expected, vector(*vx), vector(*vy)) + finally: + self._updating = False + + def hide(self): + self.group.isVisible = False diff --git a/InsertTo/resources/aspect-linked/16x16.png b/InsertTo/resources/aspect-linked/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..73a2d058d847edc4ab52e1a1e6f0c4516e02db67 GIT binary patch literal 576 zcmV-G0>Axn7#E)c@Xs1`9pBx-*^1TBJ0;m#H8W6>g%$VCy+ z>P{axT1d+lEkaj?E>v8l?gF)&bLZaoX=77}h5D=xocBHFaL(@mb|X@-C%LZHKD(|0 z*hL}Vw||G4(t>eN2vxDQEYCCyGm22kbj~-)bu=z?YXMe#|D=V2yrn*du)XpQqBR3zW zQ-@lgz{Fjkd1p-Au1P0kSb3~QpEK>e73kq83N9@UT=)!^YQv>MgbhPuIoqx;gHj=* z9HRJ)CX=TahIOJ=&e%GuWSL7#Cl`miS2vp)MG=Hckw{+C#Gew=A6w`9J7-AFG7N73 zbi_`qle{w5*O8we?p{USw;)0Qupz>>(JA};3XgIlxHVJqLI9AY9gCfM6mP7*oa^i8 zt?j7@LL{znkoSG7R4Bxa#W4?7q93MmUeviNPO67tczb@}?1Q$^sl@cs8sW7^+g)8Y z@kHa`#IvS*AJ&?N-cL8X6DR&ccjsyu`MPgAjCW`n>K~w}dvo3{E&B`Ywd}}j2C7m3 O00002v6g6!WjEOcO21_d68`>gecT# zs_{igB)bVlpanu|X`=ivZ6K%(O}l6%Q30Xv?(WRod;GC|^3YnKCWi0dN$#9;?sv|2 z?it_?{wYYlA|3U!?Tujom6t59kyN0(mtbH`w7jL zHcKY^7Isw>?Z@nm0qdvV=EK z4rWL@vHo0n!RMh!M2m(~C8J5zI|R)6$>$B|+J52n7lIkeu`dyEaYt$XJ^;w6Z8p%- zf|lhoRPe07Neg5=DF=Ga#2!rKAQVy{VgL~TDlh;IC zM``}PVcE45GYFxOg5nwg#GrfTozKVw5f7_EpP;-1hA3OGvthm=Wk4m9>sY#y zmD(FC&)+a|dgvS?5v?^GwqXHm9bOJV5zyz;)j-NCO`r$H$Sb(@@Cwq5GM4TVD5-;4 z6M=Mt?Zh&IO2C``u}bun#mZJ5TVzI!Rx500SJ%&Crai>!B@xIV+28$c%q%RPP!EjA zYg4@!cTqLK#lq_+RtiJ{Dme%Sz)GGbqWe6v7X<8!onOVu3tj|(?8>?V2&y5&yMTm% ziVvL7yzcXDgQo^yRWOk10lF^brb)0Ym1WlD3Xk}ZbWbioU?<+Lm`$+gAyTyf=916_ zzzLSBGFHBF`@CHz{oZ)*b^>oE!+>%eNyIxcJI|Xf9~C*N_knIG!(p3)TkE%wAZt`! zYOlvfZ?u-IxDu@VI!v0U1|(*)>qrRdVW?Mx5)Knr3XlIW0ASZ?Q&1bvmF72$jAI%N zer*D#DRSl(YTXxp|5Ec$Tf<6%UFRaeCByQ{s;t}TnR)jXxBC*N~up>J5kbUt?nKwryQOgV3?!5$^7O#; zKihkr`UMs#m@H5MzMAr@p^waUBF?F8HoCymiG(1<4FIsn{L#~DJ!Ge5{|OCNo~zHf zcUpGU(Y=5SlkNdi{Ls&D7k)o(2MCjdHL;mKRDTw*NM%(X`bH0AJR=8te@LdyTpH|6 zI{kCgsii2_0f2>7M^-ZEeKL#%AOhQo?{s0TI(w?C8zBJUu(}c5f5QL}S{$WlDx>$5 zlgty|z!J~E<(*Ad;cEaeZ`Vn`H_@|=8Jo$_NjbJ8q8*vPj*(ZCcrvfrHIpxB9sEQK zWNeV}ehK0|V9^TZSA}ol@|s)%%!CTiqFE;b$*#d~HGlde;L!y}xi(nJ&s--_{7>?l zTmoZm^T4*_GablkC|(ZcG}1(jU3X8cydW~#XhRRr?OCZ)m~S@v9{%9WjB(96C0j1@ pxGfjB+Mc>U44SIF{to^V`~^DJs2b1fsHy+}002ovPDHLkV1jyvk7ob? literal 0 HcmV?d00001 diff --git a/InsertTo/resources/aspect-linked/32x32.png b/InsertTo/resources/aspect-linked/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..e164f2da7ea787f23da767db84a4fa9e387bee85 GIT binary patch literal 1383 zcmV-t1(^DYP)2v6g6!WjEOcO21_d68`>gecT# zs_{igB)bVlpanu|X`=ivZ6K%(O}l6%Q30Xv?(WRod;GC|^3YnKCWi0dN$#9;?sv|2 z?it_?{wYYlA|3U!?Tujom6t59kyN0(mtbH`w7jL zHcKY^7Isw>?Z@nm0qdvV=EK z4rWL@vHo0n!RMh!M2m(~C8J5zI|R)6$>$B|+J52n7lIkeu`dyEaYt$XJ^;w6Z8p%- zf|lhoRPe07Neg5=DF=Ga#2!rKAQVy{VgL~TDlh;IC zM``}PVcE45GYFxOg5nwg#GrfTozKVw5f7_EpP;-1hA3OGvthm=Wk4m9>sY#y zmD(FC&)+a|dgvS?5v?^GwqXHm9bOJV5zyz;)j-NCO`r$H$Sb(@@Cwq5GM4TVD5-;4 z6M=Mt?Zh&IO2C``u}bun#mZJ5TVzI!Rx500SJ%&Crai>!B@xIV+28$c%q%RPP!EjA zYg4@!cTqLK#lq_+RtiJ{Dme%Sz)GGbqWe6v7X<8!onOVu3tj|(?8>?V2&y5&yMTm% ziVvL7yzcXDgQo^yRWOk10lF^brb)0Ym1WlD3Xk}ZbWbioU?<+Lm`$+gAyTyf=916_ zzzLSBGFHBF`@CHz{oZ)*b^>oE!+>%eNyIxcJI|Xf9~C*N_knIG!(p3)TkE%wAZt`! zYOlvfZ?u-IxDu@VI!v0U1|(*)>qrRdVW?Mx5)Knr3XlIW0ASZ?Q&1bvmF72$jAI%N zer*D#DRSl(YTXxp|5Ec$Tf<6%UFRaeCByQ{s;t}TnR)jXxBC*N~up>J5kbUt?nKwryQOgV3?!5$^7O#; zKihkr`UMs#m@H5MzMAr@p^waUBF?F8HoCymiG(1<4FIsn{L#~DJ!Ge5{|OCNo~zHf zcUpGU(Y=5SlkNdi{Ls&D7k)o(2MCjdHL;mKRDTw*NM%(X`bH0AJR=8te@LdyTpH|6 zI{kCgsii2_0f2>7M^-ZEeKL#%AOhQo?{s0TI(w?C8zBJUu(}c5f5QL}S{$WlDx>$5 zlgty|z!J~E<(*Ad;cEaeZ`Vn`H_@|=8Jo$_NjbJ8q8*vPj*(ZCcrvfrHIpxB9sEQK zWNeV}ehK0|V9^TZSA}ol@|s)%%!CTiqFE;b$*#d~HGlde;L!y}xi(nJ&s--_{7>?l zTmoZm^T4*_GablkC|(ZcG}1(jU3X8cydW~#XhRRr?OCZ)m~S@v9{%9WjB(96C0j1@ pxGfjB+Mc>U44SIF{to^V`~^DJs2b1fsHy+}002ovPDHLkV1jyvk7ob? literal 0 HcmV?d00001 diff --git a/InsertTo/resources/aspect-linked/32x32@2x.png b/InsertTo/resources/aspect-linked/32x32@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..7aae9e272f3ccc799dc195402d258bc4fe66c1e3 GIT binary patch literal 3505 zcmV;i4NmfjP){TBIF2LR1IeSfN?YneFZ zt7D!(009cs+x3tlR9=|ci&QGy@zb-BU0Y)4`e0@ z*EJZ8;}W1NN*!&FPJDN;NGN7~bI;~0C`kXUAKUK;iNkE&3@g?0^`*{bw;!q$=)E+4 zcJ6_6kUFgg%r`(h#6^h_s-BHCluAQg{QZdQuiw4$!oA4#TXZe*AW}f7W&Jk0?V5Ar zru@dg<4oP>eR;npA_lVph%^Z2?!0mFZsc-&FrviomGO-|8_o{Wr~j0L@CJ=4qAn5w z8HGBNX)tQ+OB%&jlsekJxO?S=dr>GDH0Le=qmuQ5R3TuXo5B4&+O@+#}xdCh|h85;TQlzNdY38nQqm&&5q>!((1M!pinT$ zgm{xQCQ>X|K)Y97xL3XZ3YcYLJjRhibtzP7AiwB%C;=tpx@gw)1z}jOf1HEx&WDix4fRa&|Dw%2olLlUQaUK;ZcZ{r|+jz(2a#u!z3B@U>0_sZpap-Km` z=iQtFxg29~0X2Vci!F6^MPbk8t4yZh<8EYMOhf^oVloXzoqG~&t|_ft{4@#$gYDZD zhe>8IxPSl<*t|f-o+DJzT4XsL)SLH!2r0D}z{M=RA@!QpYer)#O4h3u_qH46~Ej0`nkLEtrbA& z&E&H^R&`#?!UMqE+aCY0l=poI&PNEXN;Nu5U7V=-AY_TF&kngKu0>au0{ym>Z>`S# z)F zm=bc28Dv}C8Qoh>3)tMrOrMi#S%_d%#gVb3#6UsjA0n6Ifqd&RoC1?Nbz^tmw}`NonL=MJJ0fC$ zbh3H_Fy54eY>L&#zk~_C1Ce!{3QzHs5eE@(r=J?S@^H`2)t7X(7Ye4B&H8bbH$PWs zsHUdh!p5vn7eid^iO8s`;~=yOjIz?Fc62Uz=1@BV`;OFGvB=1_y5_Z;o0R!p6QnNo zWBVbhLc|H93sQ!I5ClM66&hCsAO^tdB7pczHuip%Dtu+c0f5O&3w<>95|Q~O0Q#Tp zGYP6RK;#;G`aT(v{-p`RvweA3pdcb}jX+ryzXz`R2Rl|@`V86&26^&Fe+o?E*G=79 zuOy<|$e5FTb<`2a0IE3uJ60Id;vJ00dAXw#?~zNL<+x z`RaAMS6}w4mi12s+pak`hAK6$d!!SpIS?6%D~>=GsvgXS(+yA;{}V~|YdbnG{mtRZ zVR~EYEnib_Vfr>U_6m*45bu*ToTT0q`e*L6Ft_VVt(A!}*t6vxX1hYFV~NJEr4z`2 zjClz_Z)sKAogmWrxk73%pN;0M*?5-N;64+i7W(qACQc((RcFFFtLjGp`gUp6l6w#I ziNo6p(GfMeS~qU$-P%ULy>C=+5U!hM#Kl7dzoN8i*&~3`{9G{@%x9xH-5Y;f*xpVe zpH}a5()T-w&S;#Ov!?yKb_>QDhdrfxb(9Q~_0xpwHLrQ63j z!I5l;=}3%kzGHKUQPTsWZysE|xd$teUjIVA?Ul)^spg)(>p|K}Y|~O1QGf*mns9=O zQYu60+%9DlS#(697jc;Rv_=)E_a5UJ7K9dnD5!hr=~vgFnDvKEn~&H5HRC_LcH?Zz z!9Q{;Z1Lq`NlKSUq27e`R>Z$d&~KDhwfz79TCQFnY+HY|o3nP)Jhj2CWK)+&Wdy3? z2*e!LvHBPqN5FVHP*n<2L_s>4dp?FlV^W)#07y*TG~-?MSyK6Gsbkqd!U;e}x(z-& zHCUVP^LqdN6vMWUtZi|luh!ICBFAiIx>a#oVvqAns}88QZNGbxfJikkXPZpJC4Ou; zQW3{&t*M*F5?Ak6?|#f-2DOw1h)7)|er(vev0*3GiU$a)>d6Mg={h4WUQboIpwzK! z0J(k(kiK2x51j$y+I`K&AKFaA@43-^F_8(N;<={Y6x1=aYRO-`sd}q5qo%bR*K=5Z zwYmrjybRKB4y|l^u(5m7wKlA~&y|O3wLLLnHHkSfnE)JSAaQjM6kjiOEcu5cZFFzX z0po{X*VjUdr!=b8y0!|Z>R8o3rJ~mibuRt+PUd0YM?6K1|QzRs$3cOe@XVurW~#AXMKEk@4Wy}NVio@BhW%h9+Od`luU z!Jp$eOX+%*xT2)wIbCPO`%Pgq{Mo^LHhRk)Jdr{bgG3{9y8q=Bn5UHQ#EBoCzsUaH}m_XFa7k1uw;cjG${BGX$AJhR0x6h>H1GEuDG_JZNstA#} z<;LFA|&MS2;+i)y8{5x-gwL>-cZe31nH%L@=P}rnteZcxkdF{~Z zWjBp)e#fJCX3y4nLUbPo;i5#n>1)-SxKRavd#Gc{J;!Ri9knUYUQkoal5bkG;U1G| zSm8!rbwq3d@?--N((86M@Bc2cS>Lk$sbJsBFMkohci5PNsJHm1qI&JljwQc%JL>J- ze<5C-LRA&iJv3)H zkL=r5Z|}`Bxf(5=)4lb4W%`-ASfL)tYDSL%T`wg-I$OiCH^a82eQ0iP-Jeun5y?-fM zbHcpdM^ABtE8*R86`2c21HctB=2;kixH2XWzL0Nw1%-k^d%GOgHP;D)_SZg2{MfC1 z_04zucxLk*Kbw9u9xt94P^E>re*1=pNVyy@%=O#XkR!bBA4}IBFi*(eDNJDsQ<%aO frZ9ym9QXJ?gy4s*1GyUL00000NkvXXu0mjf1HILJ literal 0 HcmV?d00001 diff --git a/InsertTo/resources/aspect-unlinked/16x16.png b/InsertTo/resources/aspect-unlinked/16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..b788c143a5f0e1e7999660af70ceecb16c05ae45 GIT binary patch literal 545 zcmV++0^a?JP)3i?~9NI|w5o>##!2UqYOgIRXQewCB4lpwr zV`Sgq`T4;uEB%kM*4j>}>WCEXqLlJf9LKMYpmTc*0W%X3asFQQv~}dQqv*^m4-Zo_ z4AXH{yPWa;w@Dm7OKtp`AV0v`(Z|*DyB%KA0g8xmeHH$hW*FKHc3WAGqL&SI=N3c$ zBq2BzA_aiI1VqGvF>jhs$CJTJCP>#%VAzCX|3A;Lu-lva`br_~yGNHA$+53|h z1&M6jX`i1~r5j0-ykYPN0E9tc*Kp{B_p9}}P@X#548ycH7XkpJ5R#c;VF&ZNHl4`~ zj1!Rp09C2ThA#d9(SntU+b^P&Q?Q9vCD4S)|^9 jAPD4v8n>yiue$yLZtmU90Y+ck00000NkvXXu0mjf6E+KO literal 0 HcmV?d00001 diff --git a/InsertTo/resources/aspect-unlinked/16x16@2x.png b/InsertTo/resources/aspect-unlinked/16x16@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..7368f7faa696a879b8b1e7d9fdf49dcfad369e3b GIT binary patch literal 1305 zcmV+!1?KvRP)%zoO^e7w^<2UHngIM+A2RuMIVBcgoFy^y#xl~hqS06ZF7HR=bl+kowL?V znh<3e)O&@9Gy<~-{E{UkYx*HUvlygg+3x@MJ?H7e?j4u4e+K%Ye7>ERbI$Mg{P{iS zd4cQpA2(uV0zlUs+4p@}x%PZt0(|v}Xsrc!5{PvF-bGr!7psg4W?Ia3u`z}L@JxF= z&y%TC$^t;^*1nes@&$Ibo**uhphMMRe2X!!q`^!e;&~G&fxG$aY3bg2yQqr3t(00V zgaq>hUnwQBne;csg*B@dUb+;Noe^`xGZ|ytrY*hqX+0dDuBgi3t!C#VG8R3qlv>RU zPgTlfa}& zaiLf&s_N=^*Q?Xp}p z1IPRe81>chY7vGZ*zs`O-Pml*#vC()N-|V)dGGtam<%)Erja89AY)9iL-(yI6!ITM zqS56_MV44=5d^_G2i`oOI}VobEQ8OQg36{cpPs;8@s%W1y=8Yk_uKiehK7a;Ww7~@^E_XsQVBb4h-di5 zt-5a|3Gt>>s!=J0FbrUw9SIA(?v2+vMrH!jT8m0`C6h@z9ogv!kk*NN zl0mU}mIOVcYSq1h#QH*^kdMXVcW^d*nuu8IWaX1fM8r)^O;s)Z{WT@$XkG+7-oouBr%w~y~Ko$uQ)Jfk8J$G|;P!_LfT(ftiIw=6xu zs#*7sz8g3-dw80zc3*fcm;1psY&`@>Sor8W!%Ab$NvE{Rx4 zE3I>P#cOKUHut>VWQ=j%l)+@i6aat&E1HN}SeDDsrcH&-y*oBIL7yuXS&++S#|6Y8 z0F+E7ZK>rt-}mK?o{o{Q7;Ge>0tj^_=Vq-51puc?FB1`c9R|f_lH&em-S>ecK5QKl zQphzV2-ey(F|X_IZ6DKG3nH3SK_Zc`%uLB-@<2K>{{3##eX7);W}PEwihPjf=qK^I zx~FUymO~3>Mi2zYoDE+ZFx@|1$$&EFLsL0;0EDK&!D#Gqwiirm8GMrW*V6t5yXTJ#l5I=s P00000NkvXXu0mjf=)-%5 literal 0 HcmV?d00001 diff --git a/InsertTo/resources/aspect-unlinked/32x32.png b/InsertTo/resources/aspect-unlinked/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..7368f7faa696a879b8b1e7d9fdf49dcfad369e3b GIT binary patch literal 1305 zcmV+!1?KvRP)%zoO^e7w^<2UHngIM+A2RuMIVBcgoFy^y#xl~hqS06ZF7HR=bl+kowL?V znh<3e)O&@9Gy<~-{E{UkYx*HUvlygg+3x@MJ?H7e?j4u4e+K%Ye7>ERbI$Mg{P{iS zd4cQpA2(uV0zlUs+4p@}x%PZt0(|v}Xsrc!5{PvF-bGr!7psg4W?Ia3u`z}L@JxF= z&y%TC$^t;^*1nes@&$Ibo**uhphMMRe2X!!q`^!e;&~G&fxG$aY3bg2yQqr3t(00V zgaq>hUnwQBne;csg*B@dUb+;Noe^`xGZ|ytrY*hqX+0dDuBgi3t!C#VG8R3qlv>RU zPgTlfa}& zaiLf&s_N=^*Q?Xp}p z1IPRe81>chY7vGZ*zs`O-Pml*#vC()N-|V)dGGtam<%)Erja89AY)9iL-(yI6!ITM zqS56_MV44=5d^_G2i`oOI}VobEQ8OQg36{cpPs;8@s%W1y=8Yk_uKiehK7a;Ww7~@^E_XsQVBb4h-di5 zt-5a|3Gt>>s!=J0FbrUw9SIA(?v2+vMrH!jT8m0`C6h@z9ogv!kk*NN zl0mU}mIOVcYSq1h#QH*^kdMXVcW^d*nuu8IWaX1fM8r)^O;s)Z{WT@$XkG+7-oouBr%w~y~Ko$uQ)Jfk8J$G|;P!_LfT(ftiIw=6xu zs#*7sz8g3-dw80zc3*fcm;1psY&`@>Sor8W!%Ab$NvE{Rx4 zE3I>P#cOKUHut>VWQ=j%l)+@i6aat&E1HN}SeDDsrcH&-y*oBIL7yuXS&++S#|6Y8 z0F+E7ZK>rt-}mK?o{o{Q7;Ge>0tj^_=Vq-51puc?FB1`c9R|f_lH&em-S>ecK5QKl zQphzV2-ey(F|X_IZ6DKG3nH3SK_Zc`%uLB-@<2K>{{3##eX7);W}PEwihPjf=qK^I zx~FUymO~3>Mi2zYoDE+ZFx@|1$$&EFLsL0;0EDK&!D#Gqwiirm8GMrW*V6t5yXTJ#l5I=s P00000NkvXXu0mjf=)-%5 literal 0 HcmV?d00001 diff --git a/InsertTo/resources/aspect-unlinked/32x32@2x.png b/InsertTo/resources/aspect-unlinked/32x32@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..2ce8aa801eb719a1106f7bfbf7d7961fbbbb3152 GIT binary patch literal 3026 zcmV;@3oZ1CP)C3SZY1lMO-s;qTR zghd2c1Q>+Hvlo|TUMYP(D!TrUuikq9?O&LC)EGne-FKgykq8hGtk>&QDi#?KWhLui z>-WR^W_Aeklp-pmY3dMBivS}6g<%9p2+le1)_OoxBH(nOwTL_mOmCm5l%K9tD%eh; zPUzJ%zE~_OMDzgQSL#GW6f-xsq4}HiPObD`q_zppTEAqxxG)U0^Pa7>_aVZwEb@*h zmw$7bGzAg0v(^^+`Zgs=QbxoCIHv4x#^*7VwLx%wX=H}+2C!SCDAmR;K zmN5W;QiR^~)3g{~GCNytw9nYNAFWn}1^^k{TfMrek{?C6Xb5d~b8E9@?NKU~s9vvo zdLf<49wiqIOZdI}VaMHR=fFUM2w4OH+wYcqK6*GIELU*ENZraBPEW4E=d zc$cltkL^G3R_EN`E;bfCB8DQsQ52B~|I)MHF|%jnTkXBu6@K8*q2T-{pY#i)?k1() z2Y`YgthA=g*^2<+!Amba^0J6uaRk)sbvDLOf%|@(WyueT6d(d+Y2uZlgF}0#FK)H4 zZuTMo0Bf@k2VtZ{KtzDUFd!EG*QDvLnAtP(tv1^`zP(i{6#@3tnUo@e0+;~+^!NA6 zsym>aQ*pdwK}WfdvG4*ZMc#V`!~%Ht%?_4!s+z+~bpYPY-0tsyEaC`w;O6S?rw<)E z6ttpAjzwWj-L`$ZLqtJ@4}0$bQ4j#hIR}d1aR7iLM~exyr%Z=#u)4vd?=1%H)N*&=$s2L`GL~<(`lMAA`pQ1Fv=kU z{zDvpB59?KtSJ#{^=}w5)8}cz3nxwa$L(h)+Wh4OwWjLzk{_y6?+SwOgGrKj0H7!r zk$J3tylpB#KpQV{YgceVTwDa~CL4xm$qU8BXr6MP~fK??z?F|mZ z!%qRgQ^i`XO^muiyGkR`y-0Ljy9QY27zuAJ@14SeTf7GIxm`c$ zjGQwrPIk~-EEa3(xMwR)hm#CnFZnKKSQUPWIJum|pKez%#^}yH+s{_&Xk3XnIa0mp z4e0!b7~Ffjmx~aASgZpPL^QgZO1i?pamPIzR&O0aUnZ0Lr&atzW z0i=-2<^SwmS6%(4`@jF)dp2+0O!M>eXI-Jy-Gn?MG62ZP-sw+?=P4rUTWmBOBC6Iv zg*wm(0N|{Z)<`Rjg$28A{rZo-*pUCN*XyHgu76g&Y3U~4KRvepynJ7Ht5W*fG-(1e zdqh+s;)5_$A_Cs~M?nO&4&ETb;GApEbWEfu2-IcO-R1di3CfA8{<5j{N+Q4*LzPNJ zvT)-j=acVhtuH%v>xd%2`My47)9eu<`pg9zbN3%Tx&bZy`aPEAHm!q;oO28S5=J3r zX}TQ%cD5phyC+076~{|a(@igybPk!PMOb|8!u4=n-KAV(}|!{YH%m1_BC$+Da$Fdz{S_8t)A zf{TCt^K+IivJ288g7tdI4^K>9r2sx$FPEp*6X6xs zW`HP&M1Vv`qx8HNTf)gJ9%_Dm9!sSXgGdvJK!jbIBrccBe{ire`N=qr-D zO1H%=0(cHHg9u0%hR7`6xh0NY7&xZPzKkRd3=9Og4!)>^aI^Q`gP>@oMF4&p$EB=A zXQd0N9cL?JgK6449OZHWh(MYqo(K=_ny9{`UMl(3NQILYK~@wX3kgeS&vXEQ@X$ji zYEf=vqIx-?x)n)XnI;J%q7oK|gh&Wq>y*8^klGQJnB~XW`-e%Zh`p!2b?Y`X8w-C4 z01x-~_v7mGfR-#ZWTv;Uxc@@Jb;9hG){2?``|%_H_Lh3R?gs`2f~{M(aw`p>JTbKs z0jf*lWZLElHlHs9NtXP}dP(000KA+E-j1rWsctK*Uw?a}(RiLjK093*`HC^8A-Q!+ zgxdXfm)U#m01WP(d7}cE(>nM-k~9IBTQZf{ zD3=S^`zJiopUjSzA3I$V6vr_SO-#n(eSJ3G{j)V6hJNe$iR!j6%-_D)Sg?o~hyX{q zh-{iY4v0Shkv>3pZx}|eOOocx#7XbmPbKx&PwyN3j}`Xs-x|EyqQ}W{2wTN4Y(Vs2 z5Js0LNz)=?03u##t#l9qh(KmDVDDQY{}OR>&K^}`H{CSY>_(hC6>7DbI&$QQtTr9i zuT+HMI8Ht{F;&dG|9&o?|HHJ|w17a~d+%IR+PZx!Z+yN`(B8Von0d#{o{?{NzVTh@ zK}%~Sb#*lijhY)TVIAC|wZ4kkgR>4q7z6+m5$GTQS)zPjcaC<>#^q<0D^8x3(_p6) zj4{;I>plj;C1$>ySzeEXfQV0#q6bLej>+-ifBKz>lV?Kw?EGGy`qKK{duQG_T0QtC zbLddvcPUPu(P*jFYU)Jnt5~e5ZbZ`84qAUuZaL%k=TFK#^w2{OJ@n8+53eQsKZP~g UFB8}Y3jhEB07*qoM6N<$g7SyORR910 literal 0 HcmV?d00001 diff --git a/InsertTo/resources/canvas-grips/move.png b/InsertTo/resources/canvas-grips/move.png new file mode 100644 index 0000000000000000000000000000000000000000..10db77dc6450213b023be87ca4d77e12de938b69 GIT binary patch literal 1311 zcmV+)1>pLLP)5|L zi=jeH_<;f@1|iXCVuC-=7(*k{)@qOyp>(_358B;jySwvo{IRp8pnQlgnY_%rdFRZ% z_uTUaxXmD`J9F(|JQ<6|lA|OyJI@qJ!QGAt;B^VZW@X)eKD@q-eF=jk1OJPJq~^@^ zDU!46J~FYQ$;L~~cG=opMr6z)$rk4wxfzLe3viNbNZHuAz#3WYUyQGvKU`4SmP z=#SR~&B#^5OLAXFM~4pJ&I$a^JQN=*dv5FJ=E44p@a@l5@#>w_UfIeIzdmg}(QuSl)_B<2 zDgedj^J%%%-ZbaVjUby>B>>J|jI@rVEUJ~;EG+k%J^iDMj9xt=xqYO-=hG%&jn^bs zNL@s1k`2*Va<7PxfY#9g?I@|{Oex*dH#iJkDGeeRO=eJ9>%02)cr9dI+N7Bs)S>q~H%FC`-H0kCpXoEWWu0H8#~29N;&R5y5+Za?1qUGr*? zOp8c8Nu@d9b!lYPa_WaO#raQmtt2Z*RseX!ljj;I$kP=7%*d@rMiQH==FV#A z=?+;{wLv2~W_w8nM8wib)}(CgT2Q~=>I#LGr=(c6EUmI1eBl0#J(mYJ0)Qrh3(*(= zLUg4%|LjA7;z8RcAmF`4MdE*PKG$9DSN+3rRka~#o@uMyL{emM^lJKP|0k}V^L=m^ zd4weLb%kWww3X5(77jLv9HGcHMOv0^=jZ8~Y1<%ybTWl$lS=Hft#4{N1Xdzt=+HC) zvp}(A8c3ToC0hdk0$tN|Crz1*0c6qWup?pUaJgL&0iZO*#?r_b2886M!4v~?-ri&O zk0kU$j~jv47uioeHbcvpR_^n0t~Y{p?O(yj7-(I)7*Ecc3K0d7Y)yW@7`8Wj{Eapg zOQJw2qob|X^=N5fdoKJyBx$kyjok*S8!~enkMhF6=n;~OoNG<*P>k+X0b)h7^~P#A1BE}&-hO2;}Rs<5>6Pb@E#=OP%)7k2@}ZJdHmP-YL;pV2K>)(6 z_OBZ!NqzD;sF^ciX(IKX{dUPSyS%7eL|!AQ`Two8bpap($0~FIFp@}a9!i?yR?!t6 zCCQ-V&J4#|)b&wcvkDQRh>)b1bi7FXA|fWM8@$iHf9!)(-66Xm&n4p0RadCjUcBQ( zEthO*5fKw2fCwzdvPp_#7ytBdlHv!%5Ad&nD_fr5exmu0?(QNr|5@BXvSTowH2bc^O_KX2tZTQz_#463 VMF-pLKF$CD002ovPDHLkV1f`Le?kBN literal 0 HcmV?d00001 diff --git a/InsertTo/resources/canvas-grips/scale.png b/InsertTo/resources/canvas-grips/scale.png new file mode 100644 index 0000000000000000000000000000000000000000..e070bb3c93aaf116ea15aea3b8aa3a1e59622de4 GIT binary patch literal 917 zcmV;G18V$iB4=te@ZDhe*# ziMTP@Dhi5FP!NM6f;3hd)Ch@~Fq*WPkN567$HlytzQjyz4PLnLKJGo|p7Z~o|GC1J zVP?V(hKN|tpJwLR;V`pclf(SUMa0qt6~O+3{icX?GFuxC%*=_1n%N}qCNQF^l0U$; zhco9e;4<)%h`gWKlw8gWz)!&b9cHNw>=Th?Gm|g_#>@s(b;A} z&jZ>`uNr%X1}qE$fD$kaECXE!84N%IxYbtM4!`)GtgN*tgaINDw<7Kx-^=Sy9L0b@ zgm&z4B78CT8%OWi&)s`RL{-f>mt;o6tt?A1VP&nwpKDDd3~&O;dWR_X+%YzUni6@X zQZ52;=bj-}o1HAGP1yCMWg!fZFrW|yIOiw~l$f1gV&BtmGyLQm%zQPsv9=X?0@sS@ z=bk#o3n%X5{DlP`edPoGTJL~J&!P#p`{-3UGJZQzoG?4Tg!c(iv%{cYyZ#a`vmSe4!Nw^&|k@Y?BPJd+wfF*Qxo zCpafOP&>qErOcU=N9^F}pr{(o$+(DIG&9!|gI45ec48XqZKh5=xMBSG)HKaFAuI$S z!pC3#$h)6>L*$d|PZ5A~LdPe(Q=g$^mmlZLb9El79mF>y z0@r1Z{)_Bxjli->{`C8w8NRs;K<&UNh7pLcyV4J;DRphL=6ClRTx~je77e8=s`w<~ z;$nkacHM*%LCwgr(uzE>PyQj~2SzFs3n6BR2zQCdoSC`2To-{~fYCIP8*QE09s_O@ zktH(|mv$Z}B5mL~paE#2YMD&rr5b2!!W8*P~atcl2C rzGeO&P2X+X^tW7FWCzz4&A Date: Wed, 2 Dec 2026 13:12:18 +0300 Subject: [PATCH 09/13] fix: create canvas manipulators only for SVG previews --- InsertTo/dialog.py | 1 + InsertTo/manipulator.py | 22 +++++++++++++++++----- tests/test_dialog.py | 2 ++ tests/test_manipulator.py | 18 ++++++++++++++++++ 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 47e33ce..b938bcd 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -413,6 +413,7 @@ def _preview(self, args): self.preview_error = '' except Exception as exc: self.app.log(traceback.format_exc()) + self.transform.hide() self.close() self.preview_error = f'Preview failed. {exc}' self._status(self.preview_error) diff --git a/InsertTo/manipulator.py b/InsertTo/manipulator.py index 5a731e3..f346d2b 100644 --- a/InsertTo/manipulator.py +++ b/InsertTo/manipulator.py @@ -10,6 +10,14 @@ def __init__(self, inputs, length_units): self.group = inputs.addGroupCommandInput('transformGroup', 'Transform') self.group.isVisible = False self.group.isExpanded = True + self.fields = [] + self.root = self.plane_basis = self._pivot = None + self._last_values = (0., 0., 0., 1.) + self._updating = False + self._angle_origin = None + + def _create_fields(self): + # Fusion draws native manipulators even when their parent group is hidden. children = self.group.children real = adsk.core.ValueInput.createByReal # The distance and angle controls display the active document units. @@ -24,15 +32,13 @@ def __init__(self, inputs, length_units): self.fields[-1].minimumValue = 0 self.fields[-1].isMinimumLimited = True self.fields[-1].isMinimumInclusive = False - self.root = self.plane_basis = self._pivot = None - self._last_values = (0., 0., 0., 1.) - self._updating = False - self._angle_origin = None def handles(self, input_id): return not self._updating and any(field.id == input_id for field in self.fields) def values(self): + if not self.fields: + return self._last_values if not all(f.isValidExpression for f in self.fields): raise ValueError('Enter valid Transform distances, angle and scale.') x, y, angle, scale = (f.value for f in self.fields) @@ -119,6 +125,8 @@ def position(self, sketch, pivot_xy_mm): self._updating = True try: self.root, self.plane_basis, self._pivot = root, basis, pivot + if not self.fields: + self._create_fields() values = self.values() self.group.isVisible = True for field in self.fields[:3]: @@ -149,4 +157,8 @@ def check_angle_origin(self, _args=None): self._updating = False def hide(self): - self.group.isVisible = False + if self.group.isVisible: + for field in self.fields[:3]: + field.isEnabled = False + field.isVisible = False + self.group.isVisible = False diff --git a/tests/test_dialog.py b/tests/test_dialog.py index 3f7d4c8..b401ee7 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -69,6 +69,8 @@ def test_cancel_file_picker_preserves_failed_preview_and_chosen_file(self): with patch.object(fusion_import, 'source_curves', side_effect=ValueError('No curves.')): self.session._preview(args) self.assertFalse(args.isValidResult) + self.session.transform.hide.assert_called_once() + self.make_grips.assert_not_called() previous = self.session.document self.changed('svgFile') # The picker did not return DialogOK. self.assertIs(self.session.document, previous) diff --git a/tests/test_manipulator.py b/tests/test_manipulator.py index 882a853..679530e 100644 --- a/tests/test_manipulator.py +++ b/tests/test_manipulator.py @@ -48,6 +48,24 @@ def setUp(self): self.sketch.sketchToModelSpace.side_effect = lambda p: Coordinates(5, 6 + p.x, 7 + p.y) self.t.position(self.sketch, (10, 20)) + def test_before_first_preview_no_native_handles_exist(self): + inputs = Mock() + controls = self.module.TransformControls(inputs, 'mm') + controls.hide() + controls.check_angle_origin() + self.assertEqual(controls.values(), (0., 0., 0., 1.)) + children = inputs.addGroupCommandInput.return_value.children + children.addDistanceValueCommandInput.assert_not_called() + children.addAngleValueCommandInput.assert_not_called() + + def test_hide_disables_native_handles_and_reshow_restores_them(self): + fields = self.t.fields[:3] + self.t.hide() + self.assertTrue(all(not f.isEnabled and not f.isVisible for f in fields)) + self.t.position(self.sketch, (10, 20)) + self.assertTrue(all(f.isEnabled and f.isVisible for f in fields)) + self.assertEqual(self.t.fields[:3], fields) + def test_positions_use_root_basis_at_nonzero_sketch_pivot(self): x, y, angle, _ = self.t.fields self.assertIs(self.t.root, self.design.rootComponent) From 98ef2d8ecc98ff14ba7834d791e98cb096a63f5b Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 13:39:22 +0300 Subject: [PATCH 10/13] fix: keep Smart Insert transforms in sync with its preview --- InsertTo/canvas_grips.py | 36 ++++++++++++++---- InsertTo/dialog.py | 29 ++++++++++++--- InsertTo/manipulator.py | 41 +++++++++++++-------- InsertTo/resources/canvas-grips/rotate.png | Bin 0 -> 1210 bytes InsertTo/svg_geometry.py | 18 ++++++--- tests/test_canvas_grips.py | 19 +++++++++- tests/test_dialog.py | 22 +++++++++++ 7 files changed, 130 insertions(+), 35 deletions(-) create mode 100644 InsertTo/resources/canvas-grips/rotate.png diff --git a/InsertTo/canvas_grips.py b/InsertTo/canvas_grips.py index ffc0c68..7b0e92e 100644 --- a/InsertTo/canvas_grips.py +++ b/InsertTo/canvas_grips.py @@ -1,4 +1,4 @@ -"""Screen-sized SVG move and scale handles projected onto the sketch plane.""" +"""Screen-sized SVG transform handles projected onto the sketch plane.""" import math from pathlib import Path @@ -6,6 +6,7 @@ _ICONS = Path(__file__).with_name('resources') / 'canvas-grips' _HIT_RADIUS = 12.0 # Viewport pixels. +_MOVE, _ROTATE = 0, 2 def _dot(a, b): @@ -58,7 +59,16 @@ def show(self, root_component, basis, target): d = math.dist(pivot, candidate) if d > distance and not math.isclose(d, distance, rel_tol=1e-12): corner, distance = candidate, d - handles = (pivot, corner) + # Keep the rotation control near the pivot even for a large page with + # uneven margins. Its direction follows the placed artwork's local Y. + direction = (-math.sin(target.rotation), math.cos(target.rotation)) + guide = tuple(p + d for p, d in zip(pivot, direction)) + pixels_per_mm = math.dist(self._screen(pivot), self._screen(guide)) + if pixels_per_mm > 1e-6: + rotate = tuple(p + d * 42 / pixels_per_mm for p, d in zip(pivot, direction)) + else: + rotate = pivot + handles = (pivot, corner, rotate) if self._group and self._group.isValid and handles == self._handles: return @@ -73,7 +83,7 @@ def show(self, root_component, basis, target): group.isSelectable = False kind = adsk.fusion.CustomGraphicsPointTypes.UserDefinedCustomGraphicsPointType markers = [] - for coord, icon in zip(coordinates, ('move.png', 'scale.png')): + for coord, icon in zip(coordinates, ('move.png', 'scale.png', 'rotate.png')): marker = group.addPointSet(coord, [], kind, str(_ICONS / icon)) marker.isSelectable = False marker.depthPriority = 20 @@ -132,10 +142,11 @@ def dragBegin(self, args, current_values_mm): start = self._on_plane(mouse) if start is None: return False - radius = _minus(self._handles[1], self._handles[0]) - if hit == 1 and _dot(radius, radius) < 1e-12: + pivot = self._handles[_MOVE] + radius = _minus(self._handles[hit], pivot) + if hit != _MOVE and _dot(radius, radius) < 1e-12: return False - self._gesture = (hit, start, radius, tuple(current_values_mm)) + self._gesture = (hit, start, pivot, radius, tuple(current_values_mm)) return True def drag(self, args): @@ -144,10 +155,19 @@ def drag(self, args): current = self._on_plane(args.viewportPosition) if current is None: return None - hit, start, radius, (dx, dy, angle, scale) = self._gesture + hit, start, pivot, radius, (dx, dy, angle, scale) = self._gesture delta = _minus(current, start) - if hit == 0: + if hit == _MOVE: return dx + delta[0], dy + delta[1], angle, scale + if hit == _ROTATE: + previous = _minus(start, pivot) + radial = _minus(current, pivot) + if math.hypot(*radial) < 1e-6: + return None + cross = previous[0] * radial[1] - previous[1] * radial[0] + angle += math.atan2(cross, _dot(previous, radial)) + self._gesture = (hit, current, pivot, radius, (dx, dy, angle, scale)) + return dx, dy, angle, scale ratio = 1 + _dot(delta, radius) / _dot(radius, radius) return dx, dy, angle, scale * max(ratio, 1e-4) diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index b938bcd..b128c16 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -105,8 +105,11 @@ def __init__(self, command): self.inset.tooltip = 'Apply an equal margin inside all four sides of the frame.' self.link = inputs.addBoolValueInput('linkFrame', 'Link to frame', True, '', True) self.link.tooltip = 'Update the inserted curves when the source frame changes.' - self.transform = TransformControls(inputs, units) + self.transform = TransformControls(inputs, units, native_handles=self.link is None) self.sizes = SizeControls(self.transform.group.children, units) if self.link is not None else None + if not self.transform.native_handles: + # Fusion binds input changes to the dialog built during command creation. + self.transform.create_fields() self.grips = None self.command = command self.status = inputs.addTextBoxCommandInput('importStatus', '', '', 2, True) @@ -118,7 +121,7 @@ def __init__(self, command): _listen(command.inputChanged, adsk.core.InputChangedEventHandler, self._changed), _listen(command.validateInputs, adsk.core.ValidateInputsEventHandler, self._validate), _listen(command.executePreview, adsk.core.CommandEventHandler, self._preview), - _listen(command.mouseMove, adsk.core.MouseEventHandler, self.transform.check_angle_origin), + _listen(command.mouseMove, adsk.core.MouseEventHandler, self._mouse_move), _listen(command.mouseDown, adsk.core.MouseEventHandler, self._drag_begin), _listen(command.mouseUp, adsk.core.MouseEventHandler, self._drag_end), _listen(command.mouseDragBegin, adsk.core.MouseEventHandler, self._drag_begin), @@ -187,6 +190,13 @@ def _drag_begin(self, args): return self.grips.dragBegin(args, values) + def _mouse_move(self, args): + if self.grips and self.grips.dragging: + if args.button & adsk.core.MouseButtons.LeftMouseButton: + self._dragged(args) + else: + self.transform.check_angle_origin(args) + def _drag_end(self, args): try: self._dragged(args) @@ -220,6 +230,7 @@ def _show_preview(self, target): if self.grips is None: self.grips = CanvasGrips(self.app.activeViewport) self.grips.show(self.transform.root, self.transform.plane_basis, target) + self.app.activeViewport.refresh() def close(self): if self.grips: @@ -276,6 +287,9 @@ def _destination(self): def _use_artwork(self): return self.extent.selectedItem.index == 1 + def _needs_artwork_bounds(self): + return self._use_artwork() or not self.frame.selectionCount + def _placements(self): frame = self.bounds if self.frame.selectionCount else None mode = self._mode() @@ -295,6 +309,9 @@ def _placements(self): anchor = _ANCHORS[self.anchor.selectedItem.index][1] self._show_alignment(fit_options) settings = dict(mode=mode, anchor=anchor, bounds=artwork, inset_mm=inset) + if frame is None and self.artwork_bounds is not None: + x0, y0, x1, y1 = self.artwork_bounds + settings['free_pivot'] = ((x0 + x1) / 2, (y0 + y1) / 2) baseline = svg_geometry.placement(self.document, frame, **settings) if self.sizes is not None: left, bottom, right, top = baseline.selected_box @@ -328,7 +345,7 @@ def _validate(self, args): try: if self.preview_error: raise ValueError(self.preview_error) - if self._use_artwork() and self.artwork_bounds is None: + if self._needs_artwork_bounds() and self.artwork_bounds is None: # A temporary measuring sketch is allowed only in preview/execute. self._show_alignment(None) self._status('Measuring artwork…') @@ -361,10 +378,10 @@ def _preview_graphics(self, sketch, plane): self.source_document = self.document self.graphics = drag_graphics.DragGraphics.capture(destination, self.source_curves, source) self.graphics_key = key - if self._use_artwork() and self.artwork_bounds is None: + if self._needs_artwork_bounds() and self.artwork_bounds is None: self.artwork_bounds = self.graphics.artwork_bounds() baseline, target, _ = self._placements() - if baseline.pivot != self.graphics_pivot: + if baseline.pivot != self.graphics_pivot or not self.transform.group.isVisible: if destination is None: destination = fusion_import.sketch_for_target(self.design, sketch, plane) self.transform.position(destination, baseline.pivot) @@ -383,7 +400,7 @@ def _preview_graphics(self, sketch, plane): def _insert(self, sketch, plane): destination = fusion_import.sketch_for_target(self.design, sketch, plane) try: - if self._use_artwork() and self.artwork_bounds is None: + if self._needs_artwork_bounds() and self.artwork_bounds is None: self.artwork_bounds = fusion_import.measure_artwork(destination, self.document) _, target, settings = self._placements() if self._linked(settings): diff --git a/InsertTo/manipulator.py b/InsertTo/manipulator.py index f346d2b..fa52dc8 100644 --- a/InsertTo/manipulator.py +++ b/InsertTo/manipulator.py @@ -1,4 +1,4 @@ -"""Planar Transform inputs and native translation and rotation handles.""" +"""Planar Transform inputs and root-space sketch coordinates.""" import math @@ -6,27 +6,36 @@ class TransformControls: - def __init__(self, inputs, length_units): + def __init__(self, inputs, length_units, *, native_handles=True): self.group = inputs.addGroupCommandInput('transformGroup', 'Transform') self.group.isVisible = False self.group.isExpanded = True + self.length_units = length_units + self.native_handles = native_handles self.fields = [] self.root = self.plane_basis = self._pivot = None self._last_values = (0., 0., 0., 1.) self._updating = False self._angle_origin = None - def _create_fields(self): - # Fusion draws native manipulators even when their parent group is hidden. + def create_fields(self): children = self.group.children real = adsk.core.ValueInput.createByReal - # The distance and angle controls display the active document units. - self.fields = [ - children.addDistanceValueCommandInput('offsetX', 'Move X', real(0)), - children.addDistanceValueCommandInput('offsetY', 'Move Y', real(0)), - children.addAngleValueCommandInput('rotateSVG', 'Rotation', real(0)), - children.addValueInput('scaleSVG', 'Scale factor', '', real(1)), - ] + if self.native_handles: + # Fusion draws native manipulators even when their parent group is hidden. + self.fields = [ + children.addDistanceValueCommandInput('offsetX', 'Move X', real(0)), + children.addDistanceValueCommandInput('offsetY', 'Move Y', real(0)), + children.addAngleValueCommandInput('rotateSVG', 'Rotation', real(0)), + ] + else: + self.fields = [ + children.addValueInput('offsetX', 'Move X', self.length_units, real(0)), + children.addValueInput('offsetY', 'Move Y', self.length_units, real(0)), + children.addValueInput('rotateSVG', 'Rotation', 'deg', real(0)), + ] + self.fields.append(children.addValueInput('scaleSVG', 'Scale factor', '', real(1))) + self.fields[2].tooltip = 'Drag the rotation handle to rotate about the pivot.' self.fields[-1].tooltip = ('Drag the corner handle to scale about the anchor. ' 'Scale is applied after Width and Height.') self.fields[-1].minimumValue = 0 @@ -61,14 +70,15 @@ def read_drag(self): return False self._updating = True try: - self._place_handles(values, previous=self._last_values) + if self.native_handles: + self._place_handles(values, previous=self._last_values) self._last_values = values finally: self._updating = False return True def apply_drag(self, values_mm): - """Apply an XY or scale grip result in sketch mm, radians and uniform factor.""" + """Apply a canvas drag in sketch mm, radians and uniform factor.""" if self._updating or self.plane_basis is None or not self.group.isVisible: return False x, y, angle, scale = values_mm @@ -126,13 +136,14 @@ def position(self, sketch, pivot_xy_mm): try: self.root, self.plane_basis, self._pivot = root, basis, pivot if not self.fields: - self._create_fields() + self.create_fields() values = self.values() self.group.isVisible = True for field in self.fields[:3]: field.isVisible = True field.isEnabled = True - self._place_handles(values) + if self.native_handles: + self._place_handles(values) self._last_values = values finally: self._updating = False diff --git a/InsertTo/resources/canvas-grips/rotate.png b/InsertTo/resources/canvas-grips/rotate.png new file mode 100644 index 0000000000000000000000000000000000000000..957174904db82258863e1e3d456b3d384e3c3ce6 GIT binary patch literal 1210 zcmV;r1V#IaP)P~NZ7(r(*r_c61xGoQK33|Z(BM1OeyoI7*R{mwbx z`R=_$w>ba^Z(d(tFEhXY(*VG(Edo#vV5Ya$*a*#A|2M!Q(;5a!0pPE5S8%#}a2tS$ znSpLA^7LfV*IoR8HF!faJH^ns#&6`rTa|FQi0CdHG$O0~^s~ZIB z>%TvEzVFSM@9ZpCv+uz2fJj$FQkQoq+tnW@hnbR=&E@wLYnxV9pr-OcavUc_M9PP= zQ6yA(0M;GuidD>hW0MJ=&*#{9jqvbiM8AXuQE}XI=v;RMe!oseB1tbSxDT&9G9y7m ztBAxlW;TXUq{?x@?=@|Dd*Sj|70RC(}@aD_5HyxwSjxb5VD4kHmO*Ky&73GsU)S~S;caIACWXrmx zV&RO*lr$|$CX%%AheJv^@3|P(kN|G>insX2eJJt7p4?WB(YX_{1B zx80Ie5(YCT+S}XH91EhPPuJ2JIskzN(Z=h1FFp2&GRBj zY8ta-eF{vPkud48SyO54a|>wdm=VV{DXbHnePtW>9-_^A4j?ao7!URiT1V?v>7|8% z<;=VlfX2+J>jGp{p%k!l*WpXgJh}RdWNs+m7dK4kQquIv zU47PvuU6_ci)XYF(OlIpg>g-tS*{8`5e^3@heE%8+j@4|vuk&z9Lr`7_!uess*|oU ztQ07faz0qLNPqW<2d)s&9A-Z0C7CrqrerThBB8PQ`CCtgW0f0rwa~sp?bO*nNJ=e* zdAT&Vw3t>^&Y|-01BxMY08|0k6CQ|nwO#1JkqbTO>>ca_&;($` z@-16*kKSxpe5)YrssVtKt2#sqs6(mc#@^jB^P2>c*|KwAyj#A-|M;Qy1mJyomHqGI YZ^Xri)tZHA^Z)<=07*qoM6N<$g0_uBga7~l literal 0 HcmV?d00001 diff --git a/InsertTo/svg_geometry.py b/InsertTo/svg_geometry.py index b13e2c8..e0f4d92 100644 --- a/InsertTo/svg_geometry.py +++ b/InsertTo/svg_geometry.py @@ -197,11 +197,13 @@ def fit_anchors(doc, frame, *, bounds=None, inset_mm=0): def placement(doc, frame, mode='fit', anchor='center', *, bounds=None, inset_mm=0, - x_mm=0, y_mm=0, rotation=0, width_factor=1, height_factor=1, scale=1): + x_mm=0, y_mm=0, rotation=0, width_factor=1, height_factor=1, scale=1, + free_pivot=None): """Place a page or measured drawing, expressed in original page-local Y-up mm. - A free placement maps its anchor directly to the given sketch point. With a - frame, rotation follows the local frame axes and offsets use the sketch axes. + A free placement starts with its anchor at the sketch origin and can rotate + and scale about a separate source-space point. With a frame, rotation follows + the local frame axes and offsets use the sketch axes. """ if anchor not in _ANCHORS: raise ValueError('Select a supported anchor.') @@ -213,9 +215,15 @@ def placement(doc, frame, mode='fit', anchor='center', *, bounds=None, inset_mm= bx, by, right, top = _source_box(doc, bounds) w, h = right - bx, top - by ax, ay = _ANCHORS[anchor] + source_x, source_y = bx + ax * w, by + ay * h sx = sy = 1 if frame is None: pivot_x, pivot_y = x_mm, y_mm + if free_pivot is not None: + cx, cy = free_pivot + pivot_x += cx - source_x + pivot_y += cy - source_y + source_x, source_y = cx, cy else: xmin, ymin, fw, fh = _inner_frame(frame, inset_mm) if mode == 'fit': @@ -235,8 +243,8 @@ def placement(doc, frame, mode='fit', anchor='center', *, bounds=None, inset_mm= page_width = _positive(doc.width_mm * sx, 'Placed width') page_height = _positive(doc.height_mm * sy, 'Placed height') local_x, local_y = _rotate(pivot_x, pivot_y, -rotation) - left = local_x - (bx + ax * w) * sx - bottom = local_y - (by + ay * h) * sy + left = local_x - source_x * sx + bottom = local_y - source_y * sy artwork_box = None if bounds is None else ( left + bx * sx, bottom + by * sy, left + right * sx, bottom + top * sy ) diff --git a/tests/test_canvas_grips.py b/tests/test_canvas_grips.py index 0a12d4c..39815ca 100644 --- a/tests/test_canvas_grips.py +++ b/tests/test_canvas_grips.py @@ -82,7 +82,7 @@ def test_misses_nonleft_clicks_edge_on_view_and_clear(self): target = placement(self.page, None) grips.show(self.root, self.basis, target) group = self.root.customGraphicsGroups.add.return_value - self.assertEqual(group.addPointSet.call_count, 2) + self.assertEqual(group.addPointSet.call_count, 3) grips.show(self.root, self.basis, target) self.assertEqual(self.root.customGraphicsGroups.add.call_count, 1) start = (0, 0, 0, 1) @@ -95,3 +95,20 @@ def test_misses_nonleft_clicks_edge_on_view_and_clear(self): grips.clear() self.assertIsNone(grips.drag(self.event(view, (0,0)))) self.assertEqual(group.deleteMe.call_count, 2) + + def test_rotation_keeps_the_pivot_and_tracks_past_half_a_turn(self): + view = CameraViewport(0, False) + grips = CanvasGrips(view) + target = placement(self.page, None, x_mm=9, y_mm=5, free_pivot=(13, 7)) + grips.show(self.root, self.basis, target) + px, py = target.pivot + handle = grips._handles[2] + self.assertTrue(grips.dragBegin(self.event(view, handle), (9, 5, 0, 1))) + x, y = handle[0] - px, handle[1] - py + for i in range(1, 4): + angle = i * math.pi / 2 + c, s = math.cos(angle), math.sin(angle) + point = (px + c*x - s*y, py + s*x + c*y) + dx, dy, rotation, scale = grips.drag(self.event(view, point)) + self.assertEqual((dx, dy, scale), (9, 5, 1)) + self.assertAlmostEqual(rotation, angle) diff --git a/tests/test_dialog.py b/tests/test_dialog.py index b401ee7..47bb0b3 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -38,6 +38,7 @@ def setUp(self): self.simple = self.enterContext(patch.object(preview_source, 'simple_curves', return_value=None)) self.source = self.enterContext(patch.object(fusion_import, 'source_curves')) self.graphics = self.capture.return_value + self.graphics.artwork_bounds.return_value = (0, 0, 20, 10) self.session.app = Mock() self.session.design = Mock(isValid=True) self.session.owner_document = self.session.app.activeDocument @@ -155,6 +156,27 @@ def test_mouse_drag_updates_cached_graphics_without_another_command_preview(self session.close() self.graphics.clear.assert_called_once() + def test_free_page_preview_keeps_the_page_placement_and_rotates_about_the_artwork_center(self): + session = self.session + session.frame.selectionCount = 0 + self.graphics.artwork_bounds.return_value = (12, 4, 18, 8) + args = SimpleNamespace() + with patch.object(fusion_import, 'import_svg') as insert: + session._preview(args) + initial = self.graphics.show.call_args.args[0] + self.assertEqual(initial.selected_box, (-10, -5, 10, 5)) + self.assertEqual(initial.pivot, (5, 1)) + session.transform.values.return_value = (4, 3, 0.6, 2) + session.transform.changed.return_value = True + self.changed('rotateSVG') + preview = self.graphics.show.call_args.args[0] + self.assertEqual(preview.pivot, (9, 4)) + self.assertEqual(preview.rotation, 0.6) + self.assertEqual(preview.width_mm, 40) + self.assertEqual(session.app.activeViewport.refresh.call_count, 2) + session._execute(args) + self.assertEqual(insert.call_args.args[2], preview) + def test_fit_alignment_follows_available_space_and_inset(self): session = self.session session.bounds = fusion_import.Frame((0, 0, 30, 30)) From a4942fc93fa91e65dd6defcd8af6355ceb422c75 Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 13:58:16 +0300 Subject: [PATCH 11/13] fix: use Fusion native handles for Smart Insert --- InsertTo/canvas_grips.py | 182 ------------------ InsertTo/dialog.py | 87 ++++----- InsertTo/manipulator.py | 206 ++++++++++++++++----- InsertTo/resources/canvas-grips/move.png | Bin 1311 -> 0 bytes InsertTo/resources/canvas-grips/rotate.png | Bin 1210 -> 0 bytes InsertTo/resources/canvas-grips/scale.png | Bin 917 -> 0 bytes README.md | 2 +- README.ru.md | 2 +- tests/test_canvas_grips.py | 114 ------------ tests/test_dialog.py | 6 +- tests/test_manipulator.py | 91 ++++++++- 11 files changed, 283 insertions(+), 407 deletions(-) delete mode 100644 InsertTo/canvas_grips.py delete mode 100644 InsertTo/resources/canvas-grips/move.png delete mode 100644 InsertTo/resources/canvas-grips/rotate.png delete mode 100644 InsertTo/resources/canvas-grips/scale.png delete mode 100644 tests/test_canvas_grips.py diff --git a/InsertTo/canvas_grips.py b/InsertTo/canvas_grips.py deleted file mode 100644 index 7b0e92e..0000000 --- a/InsertTo/canvas_grips.py +++ /dev/null @@ -1,182 +0,0 @@ -"""Screen-sized SVG transform handles projected onto the sketch plane.""" - -import math -from pathlib import Path - - -_ICONS = Path(__file__).with_name('resources') / 'canvas-grips' -_HIT_RADIUS = 12.0 # Viewport pixels. -_MOVE, _ROTATE = 0, 2 - - -def _dot(a, b): - return sum(x * y for x, y in zip(a, b)) - - -def _minus(a, b): - return tuple(x - y for x, y in zip(a, b)) - - -def _model_point(basis, sketch_mm): - origin, vx, vy, _ = basis - x, y = sketch_mm - return tuple(o + (x * i + y * j) / 10 for o, i, j in zip(origin, vx, vy)) - - -def _intersect(basis, start, direction): - origin, vx, vy, normal = basis - denominator = _dot(direction, normal) - if abs(denominator) <= 1e-10 * math.hypot(*direction): - return None - depth = _dot(_minus(origin, start), normal) / denominator - relative = tuple(p + depth * d - o for p, d, o in zip(start, direction, origin)) - return (10 * _dot(relative, vx), 10 * _dot(relative, vy)) - - -class CanvasGrips: - def __init__(self, viewport): - self.viewport = viewport - self._root = self._basis = self._group = None - self._points = () - self._handles = () - self._gesture = None - - def show(self, root_component, basis, target): - import adsk.fusion - - if root_component != self._root or self._basis != basis: - self.clear() - self._root = root_component - self._basis = basis - outline = target.outline - pivot = target.pivot - if pivot is None: - pivot = tuple((a + b) / 2 for a, b in zip(outline[0], outline[2])) - # Prefer the upper right for a centered drawing, including after a rotation. - corner = outline[2] - distance = math.dist(pivot, corner) - for candidate in outline: - d = math.dist(pivot, candidate) - if d > distance and not math.isclose(d, distance, rel_tol=1e-12): - corner, distance = candidate, d - # Keep the rotation control near the pivot even for a large page with - # uneven margins. Its direction follows the placed artwork's local Y. - direction = (-math.sin(target.rotation), math.cos(target.rotation)) - guide = tuple(p + d for p, d in zip(pivot, direction)) - pixels_per_mm = math.dist(self._screen(pivot), self._screen(guide)) - if pixels_per_mm > 1e-6: - rotate = tuple(p + d * 42 / pixels_per_mm for p, d in zip(pivot, direction)) - else: - rotate = pivot - handles = (pivot, corner, rotate) - if self._group and self._group.isValid and handles == self._handles: - return - - coordinates = [adsk.fusion.CustomGraphicsCoordinates.create( - list(_model_point(basis, pt))) for pt in handles] - if self._group and self._group.isValid: - for marker, coord in zip(self._points, coordinates): - marker.coordinates = coord - else: - group = root_component.customGraphicsGroups.add() - try: - group.isSelectable = False - kind = adsk.fusion.CustomGraphicsPointTypes.UserDefinedCustomGraphicsPointType - markers = [] - for coord, icon in zip(coordinates, ('move.png', 'scale.png', 'rotate.png')): - marker = group.addPointSet(coord, [], kind, str(_ICONS / icon)) - marker.isSelectable = False - marker.depthPriority = 20 - markers.append(marker) - except Exception: - group.deleteMe() - raise - self._group, self._points = group, markers - self._handles = handles - - def _screen(self, sketch_mm): - import adsk.core - - world = adsk.core.Point3D.create(*_model_point(self._basis, sketch_mm)) - projected = self.viewport.modelToViewSpace(world) - return projected.x, projected.y - - def _on_plane(self, view_point): - import adsk.core - - near = self.viewport.viewToModelSpace(view_point) - if near is None: - return None - camera = self.viewport.camera - eye, target, sample = camera.eye.asArray(), camera.target.asArray(), near.asArray() - types = adsk.core.CameraTypes - if camera.cameraType == types.OrthographicCameraType: - return _intersect(self._basis, sample, _minus(target, eye)) - perspective = _intersect(self._basis, eye, _minus(sample, eye)) - if camera.cameraType == types.PerspectiveCameraType: - return perspective - # The hybrid camera switches projection as it snaps to an orthogonal face. - # Test both rays against Fusion's current screen projection. - ortho = _intersect(self._basis, sample, _minus(target, eye)) - candidates = [p for p in (perspective, ortho) if p is not None] - mouse = view_point.x, view_point.y - return min(candidates, key=lambda p: math.dist(self._screen(p), mouse), default=None) - - @property - def dragging(self): - return self._gesture is not None - - def dragBegin(self, args, current_values_mm): - import adsk.core - - self.end() - mouse = args.viewportPosition - if (mouse is None or not self._handles or not self._group or not self._group.isValid - or not (args.button & adsk.core.MouseButtons.LeftMouseButton)): - return False - xy = (mouse.x, mouse.y) - distances = [math.dist(self._screen(pt), xy) for pt in self._handles] - hit = distances.index(min(distances)) - if distances[hit] > _HIT_RADIUS: - return False - start = self._on_plane(mouse) - if start is None: - return False - pivot = self._handles[_MOVE] - radius = _minus(self._handles[hit], pivot) - if hit != _MOVE and _dot(radius, radius) < 1e-12: - return False - self._gesture = (hit, start, pivot, radius, tuple(current_values_mm)) - return True - - def drag(self, args): - if self._gesture is None or args.viewportPosition is None: - return None - current = self._on_plane(args.viewportPosition) - if current is None: - return None - hit, start, pivot, radius, (dx, dy, angle, scale) = self._gesture - delta = _minus(current, start) - if hit == _MOVE: - return dx + delta[0], dy + delta[1], angle, scale - if hit == _ROTATE: - previous = _minus(start, pivot) - radial = _minus(current, pivot) - if math.hypot(*radial) < 1e-6: - return None - cross = previous[0] * radial[1] - previous[1] * radial[0] - angle += math.atan2(cross, _dot(previous, radial)) - self._gesture = (hit, current, pivot, radius, (dx, dy, angle, scale)) - return dx, dy, angle, scale - ratio = 1 + _dot(delta, radius) / _dot(radius, radius) - return dx, dy, angle, scale * max(ratio, 1e-4) - - def end(self): - self._gesture = None - - def clear(self): - self.end() - if self._group and self._group.isValid: - self._group.deleteMe() - self._root = self._basis = self._group = None - self._points = self._handles = () diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index b128c16..9970da0 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -2,13 +2,14 @@ from pathlib import Path import traceback +from uuid import uuid4 import adsk.core import adsk.fusion from . import drag_graphics, frame_link, fusion_import, preview_source, svg_geometry from .dimensions import SizeControls -from .manipulator import TransformControls +from .manipulator import TransformControls, TriadControls _RESOURCES = Path(__file__).with_name('resources') @@ -105,12 +106,13 @@ def __init__(self, command): self.inset.tooltip = 'Apply an equal margin inside all four sides of the frame.' self.link = inputs.addBoolValueInput('linkFrame', 'Link to frame', True, '', True) self.link.tooltip = 'Update the inserted curves when the source frame changes.' - self.transform = TransformControls(inputs, units, native_handles=self.link is None) - self.sizes = SizeControls(self.transform.group.children, units) if self.link is not None else None - if not self.transform.native_handles: - # Fusion binds input changes to the dialog built during command creation. + if self.link is None: + self.transform = TransformControls(inputs, units) + self.sizes = None + else: + self.transform = TriadControls(inputs) + self.sizes = SizeControls(self.transform.group.children, units) self.transform.create_fields() - self.grips = None self.command = command self.status = inputs.addTextBoxCommandInput('importStatus', '', '', 2, True) self.status.isFullWidth = True @@ -121,14 +123,21 @@ def __init__(self, command): _listen(command.inputChanged, adsk.core.InputChangedEventHandler, self._changed), _listen(command.validateInputs, adsk.core.ValidateInputsEventHandler, self._validate), _listen(command.executePreview, adsk.core.CommandEventHandler, self._preview), - _listen(command.mouseMove, adsk.core.MouseEventHandler, self._mouse_move), - _listen(command.mouseDown, adsk.core.MouseEventHandler, self._drag_begin), - _listen(command.mouseUp, adsk.core.MouseEventHandler, self._drag_end), - _listen(command.mouseDragBegin, adsk.core.MouseEventHandler, self._drag_begin), - _listen(command.mouseDragEnd, adsk.core.MouseEventHandler, self._drag_end), + _listen(command.mouseUp, adsk.core.MouseEventHandler, self._dragged), + _listen(command.mouseDragEnd, adsk.core.MouseEventHandler, self._dragged), _listen(command.mouseDrag, adsk.core.MouseEventHandler, self._dragged), _listen(command.execute, adsk.core.CommandEventHandler, self._execute), ] + if self.link is None: + self.handlers.append(_listen(command.mouseMove, adsk.core.MouseEventHandler, + self.transform.check_angle_origin)) + else: + self._triad_event_id = f'4FusionLab_InsertTo_PlaceTriad_{uuid4().hex}' + event = self.app.registerCustomEvent(self._triad_event_id) + self.handlers.extend(( + _listen(event, adsk.core.CustomEventHandler, self._apply_triad_pose), + _listen(command.destroy, adsk.core.CommandEventHandler, self._release_triad_event), + )) def _status(self, message): if self.status.text != message: @@ -182,37 +191,25 @@ def _changed(self, args): self.app.log(traceback.format_exc()) self.preview_error = str(exc) - def _drag_begin(self, args): - if self.grips and not self.grips.dragging: - try: - values = self.transform.values() - except ValueError: - return - self.grips.dragBegin(args, values) - - def _mouse_move(self, args): - if self.grips and self.grips.dragging: - if args.button & adsk.core.MouseButtons.LeftMouseButton: - self._dragged(args) - else: - self.transform.check_angle_origin(args) - - def _drag_end(self, args): - try: - self._dragged(args) - finally: - if self.grips: - self.grips.end() - - def _dragged(self, args): - values = self.grips.drag(args) if self.grips else None - if values is not None: - if self.transform.apply_drag(values): - self._move_graphics() - elif self.transform.read_drag(): + def _dragged(self, _args): + if self.transform.read_drag(): self.preview_error = '' self._move_graphics() + def _apply_triad_pose(self, _args): + try: + if self.transform.apply_position(): + self.app.activeViewport.refresh() + except Exception as exc: + self.app.log(traceback.format_exc()) + self.transform.hide() + self.close() + self.preview_error = f'Preview failed. {exc}' + self._status(self.preview_error) + + def _release_triad_event(self, _args): + self.app.unregisterCustomEvent(self._triad_event_id) + def _move_graphics(self): if self.graphics: try: @@ -224,18 +221,10 @@ def _move_graphics(self): self._status(self.preview_error) def _show_preview(self, target): - from .canvas_grips import CanvasGrips - self.graphics.show(target) - if self.grips is None: - self.grips = CanvasGrips(self.app.activeViewport) - self.grips.show(self.transform.root, self.transform.plane_basis, target) self.app.activeViewport.refresh() def close(self): - if self.grips: - self.grips.clear() - self.grips = None if self.graphics: self.graphics.clear() self.graphics = self.graphics_key = self.graphics_pivot = None @@ -384,7 +373,9 @@ def _preview_graphics(self, sketch, plane): if baseline.pivot != self.graphics_pivot or not self.transform.group.isVisible: if destination is None: destination = fusion_import.sketch_for_target(self.design, sketch, plane) - self.transform.position(destination, baseline.pivot) + if self.transform.position(destination, baseline.pivot): + # Fusion ignores writes to the native triad during executePreview. + self.app.fireCustomEvent(self._triad_event_id) self.graphics_pivot = baseline.pivot outline = None if not self.frame.selectionCount: diff --git a/InsertTo/manipulator.py b/InsertTo/manipulator.py index fa52dc8..89dbc08 100644 --- a/InsertTo/manipulator.py +++ b/InsertTo/manipulator.py @@ -5,13 +5,152 @@ import adsk.core +def _sketch_basis(sketch): + design = sketch.parentComponent.parentDesign + if sketch.assemblyContext is None: + occurrence = design.activeOccurrence + if occurrence and occurrence.component == sketch.parentComponent: + sketch = sketch.createForAssemblyContext(occurrence) + point = adsk.core.Point3D.create + origin = sketch.sketchToModelSpace(point(0, 0, 0)) + vx = origin.vectorTo(sketch.sketchToModelSpace(point(1, 0, 0))) + vy = origin.vectorTo(sketch.sketchToModelSpace(point(0, 1, 0))) + basis = tuple(tuple(item.asArray()) for item in (origin, vx, vy, vx.crossProduct(vy))) + return design.rootComponent, basis + + +def _transform_group(inputs): + group = inputs.addGroupCommandInput('transformGroup', 'Transform') + group.isVisible = False + group.isExpanded = True + return group + + +class TriadControls: + """Fusion's native planar translation, rotation, and uniform scale.""" + + def __init__(self, inputs): + self.group = _transform_group(inputs) + self.triad = None + self._position = None + self._pending = None + self._last_values = (0., 0., 0., 1.) + self._updating = False + + def create_fields(self): + triad = self.group.children.addTriadCommandInput( + 'placementTransform', adsk.core.Matrix3D.create() + ) + if triad is None or not triad.hideAll(): + raise ValueError('Fusion could not create the Transform manipulator.') + triad.isEnabled = False + triad.isVisible = False + triad.isXTranslationVisible = True + triad.isYTranslationVisible = True + triad.isXYPlaneTranslationVisible = True + triad.isZRotationVisible = True + triad.isXYPlaneScalingVisible = True + triad.tooltip = 'Scale Plane XY is applied after Width and Height.' + self.triad = triad + + def handles(self, input_id): + return not self._updating and input_id == self.triad.id + + def changed(self, input_id): + return self.handles(input_id) and self.read_drag() + + def values(self): + if self._position is None or not self.group.isVisible or self._pending is not None: + return self._last_values + if not self.triad.isValidExpressions: + raise ValueError('Enter valid Transform distances, angle and scale.') + _, (origin, vx, vy, _), (px, py) = self._position + pivot, x_axis, _, _ = self.triad.transform.getAsCoordinateSystem() + # The matrix contains the actual pose, including when a native planar + # move follows a rotation. Resolve it in the fixed sketch axes. + displacement = tuple(p - o for p, o in zip(pivot.asArray(), origin)) + x_axis = x_axis.asArray() + cosine = sum(a * b for a, b in zip(x_axis, vx)) + sine = sum(a * b for a, b in zip(x_axis, vy)) + # Fusion reports planar scale separately and resets its property when + # the user starts a different operation on the triad. + scale = self._last_values[3] + if self.triad.lastChangeMade == adsk.core.TriadChanges.TriadChangeXYScale: + scale = self.triad.xYPlaneScaleFactor + values = ( + 10 * sum(a * b for a, b in zip(displacement, vx)) - px, + 10 * sum(a * b for a, b in zip(displacement, vy)) - py, + math.atan2(sine, cosine), + scale, + ) + if not all(map(math.isfinite, values)) or scale <= 0: + raise ValueError('Transform requires a positive scale and finite coordinates.') + return values + + def read_drag(self): + if self._updating or self._position is None or not self.group.isVisible or self._pending: + return False + try: + values = self.values() + except ValueError: + return False + if all(math.isclose(a, b, rel_tol=1e-12, abs_tol=1e-10) + for a, b in zip(self._last_values, values)): + return False + self._last_values = values + return True + + def position(self, sketch, pivot_xy_mm): + root, basis = _sketch_basis(sketch) + position = (root, basis, tuple(pivot_xy_mm)) + if self.group.isVisible and self._position == position: + self._pending = None + return False + queue = self._pending is None + dx, dy, angle, _ = values = self.values() + px, py = pivot_xy_mm + origin, vx, vy, vz = basis + pivot = adsk.core.Point3D.create(*( + o + (x * (px + dx) + y * (py + dy)) / 10 for o, x, y in zip(origin, vx, vy) + )) + c, s = math.cos(angle), math.sin(angle) + vector = adsk.core.Vector3D.create + x_axis = vector(*(c*x + s*y for x, y in zip(vx, vy))) + y_axis = vector(*(c*y - s*x for x, y in zip(vx, vy))) + matrix = adsk.core.Matrix3D.create() + if not matrix.setWithCoordinateSystem(pivot, x_axis, y_axis, vector(*vz)): + raise ValueError('Fusion could not position the Transform manipulator.') + self._pending = (position, matrix, values) + return queue + + def apply_position(self): + if self._pending is None: + return False + position, matrix, values = self._pending + self._pending = None + self._updating = True + try: + self.group.isVisible = True + self.triad.isEnabled = True + self.triad.isVisible = True + self.triad.transform = matrix + self._position = position + self._last_values = values + finally: + self._updating = False + return True + + def hide(self): + self._pending = None + if self.group.isVisible: + self.triad.isEnabled = False + self.triad.isVisible = False + self.group.isVisible = False + + class TransformControls: - def __init__(self, inputs, length_units, *, native_handles=True): - self.group = inputs.addGroupCommandInput('transformGroup', 'Transform') - self.group.isVisible = False - self.group.isExpanded = True - self.length_units = length_units - self.native_handles = native_handles + def __init__(self, inputs, _length_units): + self.group = _transform_group(inputs) self.fields = [] self.root = self.plane_basis = self._pivot = None self._last_values = (0., 0., 0., 1.) @@ -21,20 +160,13 @@ def __init__(self, inputs, length_units, *, native_handles=True): def create_fields(self): children = self.group.children real = adsk.core.ValueInput.createByReal - if self.native_handles: - # Fusion draws native manipulators even when their parent group is hidden. - self.fields = [ - children.addDistanceValueCommandInput('offsetX', 'Move X', real(0)), - children.addDistanceValueCommandInput('offsetY', 'Move Y', real(0)), - children.addAngleValueCommandInput('rotateSVG', 'Rotation', real(0)), - ] - else: - self.fields = [ - children.addValueInput('offsetX', 'Move X', self.length_units, real(0)), - children.addValueInput('offsetY', 'Move Y', self.length_units, real(0)), - children.addValueInput('rotateSVG', 'Rotation', 'deg', real(0)), - ] - self.fields.append(children.addValueInput('scaleSVG', 'Scale factor', '', real(1))) + # Fusion draws native manipulators even when their parent group is hidden. + self.fields = [ + children.addDistanceValueCommandInput('offsetX', 'Move X', real(0)), + children.addDistanceValueCommandInput('offsetY', 'Move Y', real(0)), + children.addAngleValueCommandInput('rotateSVG', 'Rotation', real(0)), + children.addValueInput('scaleSVG', 'Scale factor', '', real(1)), + ] self.fields[2].tooltip = 'Drag the rotation handle to rotate about the pivot.' self.fields[-1].tooltip = ('Drag the corner handle to scale about the anchor. ' 'Scale is applied after Width and Height.') @@ -70,29 +202,12 @@ def read_drag(self): return False self._updating = True try: - if self.native_handles: - self._place_handles(values, previous=self._last_values) + self._place_handles(values, previous=self._last_values) self._last_values = values finally: self._updating = False return True - def apply_drag(self, values_mm): - """Apply a canvas drag in sketch mm, radians and uniform factor.""" - if self._updating or self.plane_basis is None or not self.group.isVisible: - return False - x, y, angle, scale = values_mm - if not all(map(math.isfinite, (x, y, angle, scale))) or scale <= 0: - return False - self._updating = True - try: - for field, value in zip(self.fields, (x / 10, y / 10, angle, scale)): - if not math.isclose(field.value, value, rel_tol=1e-12, abs_tol=1e-12): - field.value = value - finally: - self._updating = False - return self.read_drag() - def _place_handles(self, values, previous=None): origin, vx, vy, _ = self.plane_basis px, py = self._pivot @@ -118,18 +233,8 @@ def world(x_mm, y_mm): def position(self, sketch, pivot_xy_mm): """Place all handles in root component coordinates, including occurrence sketches.""" - design = sketch.parentComponent.parentDesign - if sketch.assemblyContext is None: - occurrence = design.activeOccurrence - if occurrence and occurrence.component == sketch.parentComponent: - sketch = sketch.createForAssemblyContext(occurrence) - point = adsk.core.Point3D.create - origin = sketch.sketchToModelSpace(point(0, 0, 0)) - vx = origin.vectorTo(sketch.sketchToModelSpace(point(1, 0, 0))) - vy = origin.vectorTo(sketch.sketchToModelSpace(point(0, 1, 0))) - basis = tuple(tuple(item.asArray()) for item in (origin, vx, vy, vx.crossProduct(vy))) + root, basis = _sketch_basis(sketch) pivot = tuple(pivot_xy_mm) - root = design.rootComponent if self.group.isVisible and self.root == root and self.plane_basis == basis and self._pivot == pivot: return self._updating = True @@ -142,8 +247,7 @@ def position(self, sketch, pivot_xy_mm): for field in self.fields[:3]: field.isVisible = True field.isEnabled = True - if self.native_handles: - self._place_handles(values) + self._place_handles(values) self._last_values = values finally: self._updating = False diff --git a/InsertTo/resources/canvas-grips/move.png b/InsertTo/resources/canvas-grips/move.png deleted file mode 100644 index 10db77dc6450213b023be87ca4d77e12de938b69..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1311 zcmV+)1>pLLP)5|L zi=jeH_<;f@1|iXCVuC-=7(*k{)@qOyp>(_358B;jySwvo{IRp8pnQlgnY_%rdFRZ% z_uTUaxXmD`J9F(|JQ<6|lA|OyJI@qJ!QGAt;B^VZW@X)eKD@q-eF=jk1OJPJq~^@^ zDU!46J~FYQ$;L~~cG=opMr6z)$rk4wxfzLe3viNbNZHuAz#3WYUyQGvKU`4SmP z=#SR~&B#^5OLAXFM~4pJ&I$a^JQN=*dv5FJ=E44p@a@l5@#>w_UfIeIzdmg}(QuSl)_B<2 zDgedj^J%%%-ZbaVjUby>B>>J|jI@rVEUJ~;EG+k%J^iDMj9xt=xqYO-=hG%&jn^bs zNL@s1k`2*Va<7PxfY#9g?I@|{Oex*dH#iJkDGeeRO=eJ9>%02)cr9dI+N7Bs)S>q~H%FC`-H0kCpXoEWWu0H8#~29N;&R5y5+Za?1qUGr*? zOp8c8Nu@d9b!lYPa_WaO#raQmtt2Z*RseX!ljj;I$kP=7%*d@rMiQH==FV#A z=?+;{wLv2~W_w8nM8wib)}(CgT2Q~=>I#LGr=(c6EUmI1eBl0#J(mYJ0)Qrh3(*(= zLUg4%|LjA7;z8RcAmF`4MdE*PKG$9DSN+3rRka~#o@uMyL{emM^lJKP|0k}V^L=m^ zd4weLb%kWww3X5(77jLv9HGcHMOv0^=jZ8~Y1<%ybTWl$lS=Hft#4{N1Xdzt=+HC) zvp}(A8c3ToC0hdk0$tN|Crz1*0c6qWup?pUaJgL&0iZO*#?r_b2886M!4v~?-ri&O zk0kU$j~jv47uioeHbcvpR_^n0t~Y{p?O(yj7-(I)7*Ecc3K0d7Y)yW@7`8Wj{Eapg zOQJw2qob|X^=N5fdoKJyBx$kyjok*S8!~enkMhF6=n;~OoNG<*P>k+X0b)h7^~P#A1BE}&-hO2;}Rs<5>6Pb@E#=OP%)7k2@}ZJdHmP-YL;pV2K>)(6 z_OBZ!NqzD;sF^ciX(IKX{dUPSyS%7eL|!AQ`Two8bpap($0~FIFp@}a9!i?yR?!t6 zCCQ-V&J4#|)b&wcvkDQRh>)b1bi7FXA|fWM8@$iHf9!)(-66Xm&n4p0RadCjUcBQ( zEthO*5fKw2fCwzdvPp_#7ytBdlHv!%5Ad&nD_fr5exmu0?(QNr|5@BXvSTowH2bc^O_KX2tZTQz_#463 VMF-pLKF$CD002ovPDHLkV1f`Le?kBN diff --git a/InsertTo/resources/canvas-grips/rotate.png b/InsertTo/resources/canvas-grips/rotate.png deleted file mode 100644 index 957174904db82258863e1e3d456b3d384e3c3ce6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1210 zcmV;r1V#IaP)P~NZ7(r(*r_c61xGoQK33|Z(BM1OeyoI7*R{mwbx z`R=_$w>ba^Z(d(tFEhXY(*VG(Edo#vV5Ya$*a*#A|2M!Q(;5a!0pPE5S8%#}a2tS$ znSpLA^7LfV*IoR8HF!faJH^ns#&6`rTa|FQi0CdHG$O0~^s~ZIB z>%TvEzVFSM@9ZpCv+uz2fJj$FQkQoq+tnW@hnbR=&E@wLYnxV9pr-OcavUc_M9PP= zQ6yA(0M;GuidD>hW0MJ=&*#{9jqvbiM8AXuQE}XI=v;RMe!oseB1tbSxDT&9G9y7m ztBAxlW;TXUq{?x@?=@|Dd*Sj|70RC(}@aD_5HyxwSjxb5VD4kHmO*Ky&73GsU)S~S;caIACWXrmx zV&RO*lr$|$CX%%AheJv^@3|P(kN|G>insX2eJJt7p4?WB(YX_{1B zx80Ie5(YCT+S}XH91EhPPuJ2JIskzN(Z=h1FFp2&GRBj zY8ta-eF{vPkud48SyO54a|>wdm=VV{DXbHnePtW>9-_^A4j?ao7!URiT1V?v>7|8% z<;=VlfX2+J>jGp{p%k!l*WpXgJh}RdWNs+m7dK4kQquIv zU47PvuU6_ci)XYF(OlIpg>g-tS*{8`5e^3@heE%8+j@4|vuk&z9Lr`7_!uess*|oU ztQ07faz0qLNPqW<2d)s&9A-Z0C7CrqrerThBB8PQ`CCtgW0f0rwa~sp?bO*nNJ=e* zdAT&Vw3t>^&Y|-01BxMY08|0k6CQ|nwO#1JkqbTO>>ca_&;($` z@-16*kKSxpe5)YrssVtKt2#sqs6(mc#@^jB^P2>c*|KwAyj#A-|M;Qy1mJyomHqGI YZ^Xri)tZHA^Z)<=07*qoM6N<$g0_uBga7~l diff --git a/InsertTo/resources/canvas-grips/scale.png b/InsertTo/resources/canvas-grips/scale.png deleted file mode 100644 index e070bb3c93aaf116ea15aea3b8aa3a1e59622de4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 917 zcmV;G18V$iB4=te@ZDhe*# ziMTP@Dhi5FP!NM6f;3hd)Ch@~Fq*WPkN567$HlytzQjyz4PLnLKJGo|p7Z~o|GC1J zVP?V(hKN|tpJwLR;V`pclf(SUMa0qt6~O+3{icX?GFuxC%*=_1n%N}qCNQF^l0U$; zhco9e;4<)%h`gWKlw8gWz)!&b9cHNw>=Th?Gm|g_#>@s(b;A} z&jZ>`uNr%X1}qE$fD$kaECXE!84N%IxYbtM4!`)GtgN*tgaINDw<7Kx-^=Sy9L0b@ zgm&z4B78CT8%OWi&)s`RL{-f>mt;o6tt?A1VP&nwpKDDd3~&O;dWR_X+%YzUni6@X zQZ52;=bj-}o1HAGP1yCMWg!fZFrW|yIOiw~l$f1gV&BtmGyLQm%zQPsv9=X?0@sS@ z=bk#o3n%X5{DlP`edPoGTJL~J&!P#p`{-3UGJZQzoG?4Tg!c(iv%{cYyZ#a`vmSe4!Nw^&|k@Y?BPJd+wfF*Qxo zCpafOP&>qErOcU=N9^F}pr{(o$+(DIG&9!|gI45ec48XqZKh5=xMBSG)HKaFAuI$S z!pC3#$h)6>L*$d|PZ5A~LdPe(Q=g$^mmlZLb9El79mF>y z0@r1Z{)_Bxjli->{`C8w8NRs;K<&UNh7pLcyV4J;DRphL=6ClRTx~je77e8=s`w<~ z;$nkacHM*%LCwgr(uzE>PyQj~2SzFs3n6BR2zQCdoSC`2To-{~fYCIP8*QE09s_O@ zktH(|mv$Z}B5mL~paE#2YMD&rr5b2!!W8*P~atcl2C rzGeO&P2X+X^tW7FWCzz4&A Date: Wed, 2 Dec 2026 14:09:17 +0300 Subject: [PATCH 12/13] fix: reset Smart Insert pose when selecting a frame --- InsertTo/dialog.py | 45 ++++++++++++++++++++++++++++++++++++++- InsertTo/dimensions.py | 30 ++++++++++++++++++++++++-- InsertTo/manipulator.py | 42 +++++++++++++++++++++++++++--------- tests/test_dialog.py | 27 +++++++++++++++++++++++ tests/test_dimensions.py | 24 +++++++++++++++++++++ tests/test_manipulator.py | 23 ++++++++++++++++++++ 6 files changed, 178 insertions(+), 13 deletions(-) diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 9970da0..9e3d80a 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -23,6 +23,7 @@ _ALIGN_HORIZONTAL = (('Left', 'center-left'), ('Center', 'center'), ('Right', 'center-right')) _ALIGN_VERTICAL = (('Top', 'top-center'), ('Center', 'center'), ('Bottom', 'bottom-center')) +_RESET_FIELDS = ('X Distance', 'Y Distance', 'Z Angle', 'Scale Plane XY') def _show(control, visible): @@ -67,6 +68,7 @@ def __init__(self, command): self.graphics = None self.graphics_key = None self.graphics_pivot = None + self._selected_target = None command.isExecutedWhenPreEmpted = False command.okButtonText = 'Insert' @@ -111,8 +113,19 @@ def __init__(self, command): self.sizes = None else: self.transform = TriadControls(inputs) - self.sizes = SizeControls(self.transform.group.children, units) + children = self.transform.group.children + self.sizes = SizeControls(children, units) self.transform.create_fields() + reset_all = children.addBoolValueInput('resetTransform', '', False, '', False) + reset_all.text = 'Reset all' + reset_all.isFullWidth = True + reset_all.tooltip = 'Restore the size and Transform values for the current placement.' + self.reset_field = children.addDropDownCommandInput( + 'resetTransformField', 'Reset field', adsk.core.DropDownStyles.TextListDropDownStyle + ) + self.reset_field.listItems.add('Choose…', True) + for name in _RESET_FIELDS: + self.reset_field.listItems.add(name, False) self.command = command self.status = inputs.addTextBoxCommandInput('importStatus', '', '', 2, True) self.status.isFullWidth = True @@ -168,6 +181,18 @@ def _choose_file(self): def _changed(self, args): changed = args.input.id try: + if changed == 'resetTransform': + self.sizes.reset() + self._reset_pose() + self.command.doExecutePreview() + return + if changed == 'resetTransformField': + index = self.reset_field.selectedItem.index + if index: + self.reset_field.listItems.item(0).isSelected = True + self._reset_pose((index - 1,)) + self.command.doExecutePreview() + return if self.sizes is not None and self.sizes.handles(changed): self.preview_error = '' if self.sizes.changed(changed): @@ -191,6 +216,22 @@ def _changed(self, args): self.app.log(traceback.format_exc()) self.preview_error = str(exc) + def _reset_pose(self, axes=None): + if axes is None: + self.transform.reset() + else: + self.transform.reset(axes) + self.graphics_pivot = None + self.preview_error = '' + + def _sync_target_selection(self): + selected = tuple(tuple(control.selection(i).entity for i in range(control.selectionCount)) + for control in (self.frame, self.plane)) + if self._selected_target is not None and selected != self._selected_target: + self.bounds = self.frame_sketch = None + self._reset_pose() + self._selected_target = selected + def _dragged(self, _args): if self.transform.read_drag(): self.preview_error = '' @@ -257,6 +298,8 @@ def _destination(self): raise ValueError('Open a Fusion design to insert an SVG.') if self.sketch and (not self.sketch.isValid or self.app.activeEditObject != self.sketch): raise ValueError('The destination sketch is no longer being edited.') + if self.sizes is not None: + self._sync_target_selection() if self.frame.selectionCount: if self.plane.selectionCount: raise ValueError('Choose a sketch frame or a new sketch plane.') diff --git a/InsertTo/dimensions.py b/InsertTo/dimensions.py index 7ab6915..11cf9ca 100644 --- a/InsertTo/dimensions.py +++ b/InsertTo/dimensions.py @@ -12,6 +12,9 @@ def __init__(self, children, length_units): import adsk.core initial = adsk.core.ValueInput.createByReal + table = children.addTableCommandInput('svgSizeTable', '', 3, '3:5:2') + table.isFullWidth = True + table.minimumVisibleRows = table.maximumVisibleRows = 2 self.width = children.addValueInput('svgWidth', 'Width', length_units, initial(1.0)) self.height = children.addValueInput('svgHeight', 'Height', length_units, initial(1.0)) self.link = children.addBoolValueInput( @@ -19,10 +22,18 @@ def __init__(self, children, length_units): ) self.link.tooltip = 'Use the original drawing proportions when editing width or height.' self._fields = (self.width, self.height) - for field in self._fields: + self._reset_ids = ('resetSvgWidth', 'resetSvgHeight') + for axis, (field, reset_id, name) in enumerate(zip(self._fields, self._reset_ids, ('Width', 'Height'))): field.minimumValue = 0 field.isMinimumLimited = True field.isMinimumInclusive = True # A vertical or horizontal drawing has one zero axis. + label = children.addTextBoxCommandInput(f'{field.id}Label', '', name, 1, True) + button = children.addBoolValueInput(reset_id, f'Reset {name}', False, '', False) + button.text = 'Reset' + button.tooltip = f'Restore {name.lower()} to the size for the current placement.' + table.addCommandInput(label, axis, 0) + table.addCommandInput(field, axis, 1) + table.addCommandInput(button, axis, 2) self._base = None self._factors = [1., 1.] self._display_mm = (None, None) @@ -31,11 +42,14 @@ def __init__(self, children, length_units): self._syncing = False def handles(self, input_id): - return not self._syncing and input_id in (self.width.id, self.height.id, self.link.id) + return not self._syncing and input_id in (self.width.id, self.height.id, self.link.id, *self._reset_ids) def changed(self, input_id): if not self.handles(input_id): return False + if input_id in self._reset_ids: + self.reset(self._reset_ids.index(input_id)) + return True if input_id == self.link.id: if self.link.value == self._locked: return False @@ -64,6 +78,18 @@ def changed(self, input_id): self._factors[axis] = mm / self._base[axis] return True + def reset(self, axis=None): + axes = (0, 1) if axis is None or self.link.value else (axis,) + self._last_edited = None + self._syncing = True + try: + for i in axes: + self._factors[i] = 1. + if self._base is not None: + self._fields[i].value = self._base[i] / 10 + finally: + self._syncing = False + def update(self, base_width_mm, base_height_mm, aspect_of_original_w_over_h): """Show pre-scale dimensions and return corrections relative to the current fitted size.""" base = (base_width_mm, base_height_mm) diff --git a/InsertTo/manipulator.py b/InsertTo/manipulator.py index 89dbc08..4f6f436 100644 --- a/InsertTo/manipulator.py +++ b/InsertTo/manipulator.py @@ -5,6 +5,11 @@ import adsk.core +_DEFAULT_POSE = (0., 0., 0., 1.) +_POSE_EXPRESSIONS = ('xTranslationExpression', 'yTranslationExpression', + 'zRotationExpression', 'xYPlaneScaleFactorExpression') + + def _sketch_basis(sketch): design = sketch.parentComponent.parentDesign if sketch.assemblyContext is None: @@ -34,7 +39,8 @@ def __init__(self, inputs): self.triad = None self._position = None self._pending = None - self._last_values = (0., 0., 0., 1.) + self._last_values = _DEFAULT_POSE + self._reset_axes = set() self._updating = False def create_fields(self): @@ -60,8 +66,11 @@ def changed(self, input_id): return self.handles(input_id) and self.read_drag() def values(self): - if self._position is None or not self.group.isVisible or self._pending is not None: + if self._position is None or not self.group.isVisible or self._pending or self._reset_axes: return self._last_values + return self._native_values(self._last_values[3]) + + def _native_values(self, scale): if not self.triad.isValidExpressions: raise ValueError('Enter valid Transform distances, angle and scale.') _, (origin, vx, vy, _), (px, py) = self._position @@ -72,11 +81,6 @@ def values(self): x_axis = x_axis.asArray() cosine = sum(a * b for a, b in zip(x_axis, vx)) sine = sum(a * b for a, b in zip(x_axis, vy)) - # Fusion reports planar scale separately and resets its property when - # the user starts a different operation on the triad. - scale = self._last_values[3] - if self.triad.lastChangeMade == adsk.core.TriadChanges.TriadChangeXYScale: - scale = self.triad.xYPlaneScaleFactor values = ( 10 * sum(a * b for a, b in zip(displacement, vx)) - px, 10 * sum(a * b for a, b in zip(displacement, vy)) - py, @@ -88,10 +92,15 @@ def values(self): return values def read_drag(self): - if self._updating or self._position is None or not self.group.isVisible or self._pending: + if self._updating or self._position is None or not self.group.isVisible or self._pending or self._reset_axes: return False try: - values = self.values() + # Fusion resets the native scale property when a different + # manipulation starts, so retain the last reported scale. + scale = self._last_values[3] + if self.triad.lastChangeMade == adsk.core.TriadChanges.TriadChangeXYScale: + scale = self.triad.xYPlaneScaleFactor + values = self._native_values(scale) except ValueError: return False if all(math.isclose(a, b, rel_tol=1e-12, abs_tol=1e-10) @@ -100,10 +109,20 @@ def read_drag(self): self._last_values = values return True + def reset(self, axes=(0, 1, 2, 3)): + try: + values = self.values() + except ValueError: + values = self._last_values + self._last_values = tuple(default if i in axes else value + for i, (value, default) in enumerate(zip(values, _DEFAULT_POSE))) + self._pending = None + self._reset_axes.update(axes) + def position(self, sketch, pivot_xy_mm): root, basis = _sketch_basis(sketch) position = (root, basis, tuple(pivot_xy_mm)) - if self.group.isVisible and self._position == position: + if self.group.isVisible and self._position == position and not self._reset_axes: self._pending = None return False queue = self._pending is None @@ -133,9 +152,12 @@ def apply_position(self): self.group.isVisible = True self.triad.isEnabled = True self.triad.isVisible = True + for axis in sorted(self._reset_axes): + setattr(self.triad, _POSE_EXPRESSIONS[axis], str(int(_DEFAULT_POSE[axis]))) self.triad.transform = matrix self._position = position self._last_values = values + self._reset_axes.clear() finally: self._updating = False return True diff --git a/tests/test_dialog.py b/tests/test_dialog.py index 3c277c8..d479812 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -111,6 +111,33 @@ def test_profile_replacement_after_preview_uses_new_frame_for_execute(self): self.assertEqual([call.args[1] for call in bounds.call_args_list], [['first profile'], ['second profile']]) + def test_selecting_a_frame_discards_the_free_placement_pose_before_preview(self): + session = self.session + session.frame.selectionCount = 0 + session.transform.values.return_value = (25., 0., 0., 1.) + session.transform.reset.side_effect = lambda: setattr(session.transform.values, 'return_value', + (0., 0., 0., 1.)) + args = SimpleNamespace() + session._preview(args) + self.assertEqual(self.graphics.show.call_args.args[0].pivot, (25, 0)) + + with patch.object(fusion_import, 'frame_bounds', return_value=fusion_import.Frame((30, 40, 90, 70))): + session.frame.selectionCount = 1 + session.frame.selection.return_value.entity = 'frame' + session._preview(args) + session.transform.reset.assert_called_once_with() + self.assertEqual(self.graphics.show.call_args.args[0].selected_box, (30, 40, 90, 70)) + self.changed('frame') + session.transform.reset.assert_called_once_with() + + def test_reset_all_requests_a_preview_after_restoring_size_and_pose(self): + self.session.graphics_pivot = (10, 20) + self.changed('resetTransform') + self.session.sizes.reset.assert_called_once_with() + self.session.transform.reset.assert_called_once_with() + self.session.command.doExecutePreview.assert_called_once_with() + self.assertIsNone(self.session.graphics_pivot) + def test_artwork_measurement_is_transactional_and_cached_across_transforms(self): session = self.session diff --git a/tests/test_dimensions.py b/tests/test_dimensions.py index bd1003a..d4c8af7 100644 --- a/tests/test_dimensions.py +++ b/tests/test_dimensions.py @@ -75,6 +75,30 @@ def test_zero_axis_is_read_only_and_nonzero_dimension_can_resize(self): self.assertEqual(s.update(0, 40, None), (.5, .5)) self.assertTrue(s.height.isEnabled) + def test_row_reset_preserves_the_unlinked_height_and_global_reset_restores_both(self): + s = self.size + s.link.value = False + s.changed(s.link.id) + s.update(80, 60, 2.) + s.width.value, s.height.value = 12, 4 + s.changed(s.width.id) + s.changed(s.height.id) + self.assertTrue(s.changed('resetSvgWidth')) + self.assertEqual(s.update(80, 60, 2.), (1., 2/3)) + self.assertEqual((s.width.value, s.height.value), (8, 4)) + s.reset() + self.assertEqual(s.update(80, 60, 2.), (1., 1.)) + self.assertEqual((s.width.value, s.height.value), (8, 6)) + + def test_linked_dimension_reset_restores_the_stretch_baseline(self): + s = self.size + s.update(80, 60, 2.) + s.width.value = 10 + s.changed(s.width.id) + self.assertEqual(s.update(80, 60, 2.), (1.25, 5/6)) + self.assertTrue(s.changed('resetSvgHeight')) + self.assertEqual(s.update(80, 60, 2.), (1., 1.)) + def test_programmatic_length_writes_do_not_trigger_manual_aspect_edits(self): s = self.size events = [] diff --git a/tests/test_manipulator.py b/tests/test_manipulator.py index c99bc34..d5afbc3 100644 --- a/tests/test_manipulator.py +++ b/tests/test_manipulator.py @@ -217,3 +217,26 @@ def test_native_matrix_motion_preserves_scale_and_can_reanchor(self): self.assertTrue(self.t.apply_position()) self.assertEqual(triad.transform.getAsCoordinateSystem()[0].asArray(), (5, 9.5, 9.6)) self.assertEqual(self.t.values()[3], 1.5) + + def test_reset_hides_stale_pose_before_reanchor_and_can_reset_one_axis_in_place(self): + triad = self.t.triad + self.t.position(self.sketch, (10, 20)) + self.t.apply_position() + triad.transform.setWithCoordinateSystem(Coordinates(5, 9, 10), Coordinates(0, 1, 0), + Coordinates(0, 0, 1), Coordinates(1, 0, 0)) + self.assertTrue(self.t.read_drag()) + triad.lastChangeMade = 14 + triad.xYPlaneScaleFactor = 1.5 + self.assertTrue(self.t.read_drag()) + self.t.reset((0,)) + self.assertEqual(self.t.values(), (0, 10, 0, 1.5)) + self.assertTrue(self.t.position(self.sketch, (10, 20))) + self.t.apply_position() + self.assertEqual(triad.xTranslationExpression, '0') + self.assertEqual(triad.transform.getAsCoordinateSystem()[0].asArray(), (5, 7, 10)) + self.t.reset() + self.assertEqual(self.t.values(), (0, 0, 0, 1)) + self.t.position(self.sketch, (40, 60)) + self.t.apply_position() + self.assertEqual(triad.transform.getAsCoordinateSystem()[0].asArray(), (5, 10, 13)) + self.assertEqual(triad.xYPlaneScaleFactorExpression, '1') From 4a8a36da5e15c6e0d15ee887774cba758d77263c Mon Sep 17 00:00:00 2001 From: Pavel Kuznetsov Date: Wed, 2 Dec 2026 14:15:35 +0300 Subject: [PATCH 13/13] fix: limit Smart Insert resizing to original size --- InsertTo/dialog.py | 46 ++++++++++----------------------------- InsertTo/dimensions.py | 35 ++++++----------------------- InsertTo/manipulator.py | 46 ++++++++++++++++++++++++--------------- README.md | 2 +- README.ru.md | 2 +- tests/test_dialog.py | 42 ++++++++++++++++++++++++----------- tests/test_dimensions.py | 24 -------------------- tests/test_manipulator.py | 23 +++++++++++++------- 8 files changed, 94 insertions(+), 126 deletions(-) diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py index 9e3d80a..e3b7730 100644 --- a/InsertTo/dialog.py +++ b/InsertTo/dialog.py @@ -23,7 +23,6 @@ _ALIGN_HORIZONTAL = (('Left', 'center-left'), ('Center', 'center'), ('Right', 'center-right')) _ALIGN_VERTICAL = (('Top', 'top-center'), ('Center', 'center'), ('Bottom', 'bottom-center')) -_RESET_FIELDS = ('X Distance', 'Y Distance', 'Z Angle', 'Scale Plane XY') def _show(control, visible): @@ -116,16 +115,6 @@ def __init__(self, command): children = self.transform.group.children self.sizes = SizeControls(children, units) self.transform.create_fields() - reset_all = children.addBoolValueInput('resetTransform', '', False, '', False) - reset_all.text = 'Reset all' - reset_all.isFullWidth = True - reset_all.tooltip = 'Restore the size and Transform values for the current placement.' - self.reset_field = children.addDropDownCommandInput( - 'resetTransformField', 'Reset field', adsk.core.DropDownStyles.TextListDropDownStyle - ) - self.reset_field.listItems.add('Choose…', True) - for name in _RESET_FIELDS: - self.reset_field.listItems.add(name, False) self.command = command self.status = inputs.addTextBoxCommandInput('importStatus', '', '', 2, True) self.status.isFullWidth = True @@ -181,21 +170,9 @@ def _choose_file(self): def _changed(self, args): changed = args.input.id try: - if changed == 'resetTransform': - self.sizes.reset() - self._reset_pose() - self.command.doExecutePreview() - return - if changed == 'resetTransformField': - index = self.reset_field.selectedItem.index - if index: - self.reset_field.listItems.item(0).isSelected = True - self._reset_pose((index - 1,)) - self.command.doExecutePreview() - return if self.sizes is not None and self.sizes.handles(changed): self.preview_error = '' - if self.sizes.changed(changed): + if self._mode() == 'original' and self.sizes.changed(changed): self._move_graphics() return if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor', @@ -210,26 +187,21 @@ def _changed(self, args): if changed in ('frame', 'targetPlane'): self.bounds = None self.frame_sketch = None + if changed in ('frame', 'targetPlane', 'scale'): self._show_target_controls() self.preview_error = '' except Exception as exc: self.app.log(traceback.format_exc()) self.preview_error = str(exc) - def _reset_pose(self, axes=None): - if axes is None: - self.transform.reset() - else: - self.transform.reset(axes) - self.graphics_pivot = None - self.preview_error = '' - def _sync_target_selection(self): selected = tuple(tuple(control.selection(i).entity for i in range(control.selectionCount)) for control in (self.frame, self.plane)) if self._selected_target is not None and selected != self._selected_target: self.bounds = self.frame_sketch = None - self._reset_pose() + self.transform.start_at_anchor() + self.graphics_pivot = None + self.preview_error = '' self._selected_target = selected def _dragged(self, _args): @@ -285,6 +257,10 @@ def _show_target_controls(self): _show(self.scaling, has_frame) _show(self.inset, has_frame) _show(self.link, has_frame and self._mode() in ('fit', 'stretch')) + if self.sizes is not None: + original = self._mode() == 'original' + self.sizes.set_visible(original) + self.transform.show_scale(original) def _show_alignment(self, fit_options): _show(self.anchor, bool(self.frame.selectionCount) and self._mode() == 'original') @@ -345,7 +321,7 @@ def _placements(self): x0, y0, x1, y1 = self.artwork_bounds settings['free_pivot'] = ((x0 + x1) / 2, (y0 + y1) / 2) baseline = svg_geometry.placement(self.document, frame, **settings) - if self.sizes is not None: + if self.sizes is not None and mode == 'original': left, bottom, right, top = baseline.selected_box original_w, original_h = self.document.width_mm, self.document.height_mm if artwork is not None: @@ -355,6 +331,8 @@ def _placements(self): if width_factor != 1 or height_factor != 1: settings.update(width_factor=width_factor, height_factor=height_factor) dx, dy, angle, scale = self.transform.values() + if self.sizes is not None and mode != 'original': + scale = 1. settings.update(x_mm=dx, y_mm=dy, rotation=angle, scale=scale) target = svg_geometry.placement(self.document, frame, **settings) return baseline, target, settings diff --git a/InsertTo/dimensions.py b/InsertTo/dimensions.py index 11cf9ca..d6937e8 100644 --- a/InsertTo/dimensions.py +++ b/InsertTo/dimensions.py @@ -12,9 +12,6 @@ def __init__(self, children, length_units): import adsk.core initial = adsk.core.ValueInput.createByReal - table = children.addTableCommandInput('svgSizeTable', '', 3, '3:5:2') - table.isFullWidth = True - table.minimumVisibleRows = table.maximumVisibleRows = 2 self.width = children.addValueInput('svgWidth', 'Width', length_units, initial(1.0)) self.height = children.addValueInput('svgHeight', 'Height', length_units, initial(1.0)) self.link = children.addBoolValueInput( @@ -22,18 +19,10 @@ def __init__(self, children, length_units): ) self.link.tooltip = 'Use the original drawing proportions when editing width or height.' self._fields = (self.width, self.height) - self._reset_ids = ('resetSvgWidth', 'resetSvgHeight') - for axis, (field, reset_id, name) in enumerate(zip(self._fields, self._reset_ids, ('Width', 'Height'))): + for field in self._fields: field.minimumValue = 0 field.isMinimumLimited = True field.isMinimumInclusive = True # A vertical or horizontal drawing has one zero axis. - label = children.addTextBoxCommandInput(f'{field.id}Label', '', name, 1, True) - button = children.addBoolValueInput(reset_id, f'Reset {name}', False, '', False) - button.text = 'Reset' - button.tooltip = f'Restore {name.lower()} to the size for the current placement.' - table.addCommandInput(label, axis, 0) - table.addCommandInput(field, axis, 1) - table.addCommandInput(button, axis, 2) self._base = None self._factors = [1., 1.] self._display_mm = (None, None) @@ -42,14 +31,16 @@ def __init__(self, children, length_units): self._syncing = False def handles(self, input_id): - return not self._syncing and input_id in (self.width.id, self.height.id, self.link.id, *self._reset_ids) + return not self._syncing and input_id in (self.width.id, self.height.id, self.link.id) + + def set_visible(self, visible): + for control in (*self._fields, self.link): + if control.isVisible != visible: + control.isVisible = visible def changed(self, input_id): if not self.handles(input_id): return False - if input_id in self._reset_ids: - self.reset(self._reset_ids.index(input_id)) - return True if input_id == self.link.id: if self.link.value == self._locked: return False @@ -78,18 +69,6 @@ def changed(self, input_id): self._factors[axis] = mm / self._base[axis] return True - def reset(self, axis=None): - axes = (0, 1) if axis is None or self.link.value else (axis,) - self._last_edited = None - self._syncing = True - try: - for i in axes: - self._factors[i] = 1. - if self._base is not None: - self._fields[i].value = self._base[i] / 10 - finally: - self._syncing = False - def update(self, base_width_mm, base_height_mm, aspect_of_original_w_over_h): """Show pre-scale dimensions and return corrections relative to the current fitted size.""" base = (base_width_mm, base_height_mm) diff --git a/InsertTo/manipulator.py b/InsertTo/manipulator.py index 4f6f436..e8d2a3b 100644 --- a/InsertTo/manipulator.py +++ b/InsertTo/manipulator.py @@ -6,8 +6,6 @@ _DEFAULT_POSE = (0., 0., 0., 1.) -_POSE_EXPRESSIONS = ('xTranslationExpression', 'yTranslationExpression', - 'zRotationExpression', 'xYPlaneScaleFactorExpression') def _sketch_basis(sketch): @@ -40,7 +38,7 @@ def __init__(self, inputs): self._position = None self._pending = None self._last_values = _DEFAULT_POSE - self._reset_axes = set() + self._new_anchor = False self._updating = False def create_fields(self): @@ -66,7 +64,7 @@ def changed(self, input_id): return self.handles(input_id) and self.read_drag() def values(self): - if self._position is None or not self.group.isVisible or self._pending or self._reset_axes: + if self._position is None or not self.group.isVisible or self._pending or self._new_anchor: return self._last_values return self._native_values(self._last_values[3]) @@ -92,13 +90,14 @@ def _native_values(self, scale): return values def read_drag(self): - if self._updating or self._position is None or not self.group.isVisible or self._pending or self._reset_axes: + if self._updating or self._position is None or not self.group.isVisible or self._pending or self._new_anchor: return False try: # Fusion resets the native scale property when a different # manipulation starts, so retain the last reported scale. scale = self._last_values[3] - if self.triad.lastChangeMade == adsk.core.TriadChanges.TriadChangeXYScale: + if (self.triad.isXYPlaneScalingVisible + and self.triad.lastChangeMade == adsk.core.TriadChanges.TriadChangeXYScale): scale = self.triad.xYPlaneScaleFactor values = self._native_values(scale) except ValueError: @@ -109,20 +108,29 @@ def read_drag(self): self._last_values = values return True - def reset(self, axes=(0, 1, 2, 3)): + def show_scale(self, visible): + triad = self.triad + if triad.isXYPlaneScalingVisible == visible: + return + self._updating = True try: - values = self.values() - except ValueError: - values = self._last_values - self._last_values = tuple(default if i in axes else value - for i, (value, default) in enumerate(zip(values, _DEFAULT_POSE))) + if not visible and self.group.isVisible and not triad.isValidExpressions: + triad.xYPlaneScaleFactorExpression = str(self._last_values[3]) + triad.isXYPlaneScalingVisible = visible + if visible and self.group.isVisible: + triad.xYPlaneScaleFactorExpression = str(self._last_values[3]) + finally: + self._updating = False + + def start_at_anchor(self): + self._last_values = _DEFAULT_POSE self._pending = None - self._reset_axes.update(axes) + self._new_anchor = True def position(self, sketch, pivot_xy_mm): root, basis = _sketch_basis(sketch) position = (root, basis, tuple(pivot_xy_mm)) - if self.group.isVisible and self._position == position and not self._reset_axes: + if self.group.isVisible and self._position == position and not self._new_anchor: self._pending = None return False queue = self._pending is None @@ -152,12 +160,16 @@ def apply_position(self): self.group.isVisible = True self.triad.isEnabled = True self.triad.isVisible = True - for axis in sorted(self._reset_axes): - setattr(self.triad, _POSE_EXPRESSIONS[axis], str(int(_DEFAULT_POSE[axis]))) + if self._new_anchor: + self.triad.xTranslationExpression = '0' + self.triad.yTranslationExpression = '0' + self.triad.zRotationExpression = '0' + if self.triad.isXYPlaneScalingVisible: + self.triad.xYPlaneScaleFactorExpression = '1' self.triad.transform = matrix self._position = position self._last_values = values - self._reset_axes.clear() + self._new_anchor = False finally: self._updating = False return True diff --git a/README.md b/README.md index 548509b..a6ebe9d 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Place SVG curves in an Autodesk Fusion sketch at their physical size, or fit the 4. To fit the SVG to a frame, select a shaded profile or a closed sketch contour. One edge selects an isolated closed chain. You can also select its segments individually. Choose **Fit to frame** and, if needed, set an equal **Inset** on all four sides. 5. Check the preview and the dimensions beside **Insert** in the dialog. Click **Insert** to keep the curves or **Cancel** to discard the preview. -In **Transform**, **Width** and **Height** set the size of the selected SVG bounds before rotation. The chain links these fields using the original aspect ratio. Unlock it to set both dimensions independently. **Scale Plane XY** multiplies both dimensions last. For example, 40 × 20 mm at a factor of 1.5 inserts at 60 × 30 mm. +In **Original size** and when placing without a frame, **Width** and **Height** set the size of the selected SVG bounds before rotation. The chain links these fields using the original aspect ratio. Unlock it to set both dimensions independently. **Scale Plane XY** multiplies both dimensions last. For example, 40 × 20 mm at a factor of 1.5 inserts at 60 × 30 mm. | Fit to frame | Result before manual transforms | | --- | --- | diff --git a/README.ru.md b/README.ru.md index 7a4c0ca..bd5b5f9 100644 --- a/README.ru.md +++ b/README.ru.md @@ -12,7 +12,7 @@ 4. Для вставки в рамку выберите закрашенный профиль или замкнутый контур эскиза. У изолированной замкнутой цепочки достаточно выбрать одно ребро. Также можно выбрать сегменты по отдельности. Выберите режим **Fit to frame**. Поле **Inset** задаёт одинаковый отступ внутрь со всех четырёх сторон. 5. Проверьте предпросмотр и размеры в строке **Insert** в диалоге. Нажмите **Insert**, чтобы добавить кривые, или **Cancel**, чтобы отменить вставку. -В разделе **Transform** поля **Width** и **Height** задают размеры выбранной области SVG до поворота. Цепочка сохраняет исходные пропорции при вводе размера. Отключите её, чтобы изменить ширину и высоту независимо. При размере 40 × 20 мм и **Scale Plane XY** 1,5 итоговый размер будет 60 × 30 мм. +В режиме **Original size** и при свободной вставке без рамки поля **Width** и **Height** задают размеры выбранной области SVG до поворота. Цепочка сохраняет исходные пропорции при вводе размера. Отключите её, чтобы изменить ширину и высоту независимо. При размере 40 × 20 мм и **Scale Plane XY** 1,5 итоговый размер будет 60 × 30 мм. | Режим Fit to frame | Результат до ручного перемещения и масштабирования | | --- | --- | diff --git a/tests/test_dialog.py b/tests/test_dialog.py index d479812..5e6beb4 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -115,8 +115,9 @@ def test_selecting_a_frame_discards_the_free_placement_pose_before_preview(self) session = self.session session.frame.selectionCount = 0 session.transform.values.return_value = (25., 0., 0., 1.) - session.transform.reset.side_effect = lambda: setattr(session.transform.values, 'return_value', - (0., 0., 0., 1.)) + session.transform.start_at_anchor.side_effect = lambda: setattr( + session.transform.values, 'return_value', (0., 0., 0., 1.) + ) args = SimpleNamespace() session._preview(args) self.assertEqual(self.graphics.show.call_args.args[0].pivot, (25, 0)) @@ -125,18 +126,10 @@ def test_selecting_a_frame_discards_the_free_placement_pose_before_preview(self) session.frame.selectionCount = 1 session.frame.selection.return_value.entity = 'frame' session._preview(args) - session.transform.reset.assert_called_once_with() + session.transform.start_at_anchor.assert_called_once_with() self.assertEqual(self.graphics.show.call_args.args[0].selected_box, (30, 40, 90, 70)) self.changed('frame') - session.transform.reset.assert_called_once_with() - - def test_reset_all_requests_a_preview_after_restoring_size_and_pose(self): - self.session.graphics_pivot = (10, 20) - self.changed('resetTransform') - self.session.sizes.reset.assert_called_once_with() - self.session.transform.reset.assert_called_once_with() - self.session.command.doExecutePreview.assert_called_once_with() - self.assertIsNone(self.session.graphics_pivot) + session.transform.start_at_anchor.assert_called_once_with() def test_artwork_measurement_is_transactional_and_cached_across_transforms(self): @@ -268,7 +261,7 @@ def test_linked_fit_persists_the_same_settings_used_for_the_preview(self): settings = link.call_args.kwargs.copy() self.assertIs(settings.pop('source_curves'), source.return_value) self.assertEqual(settings, dict(mode='fit', anchor='bottom-center', bounds=None, - inset_mm=1., x_mm=4, y_mm=5, rotation=0.3, scale=1.2)) + inset_mm=1., x_mm=4, y_mm=5, rotation=0.3, scale=1.)) self.assertIs(sketch, session.sketch) self.assertEqual(entities, [session.frame.selection(0).entity]) self.assertEqual(target, svg_geometry.placement(doc, session.bounds, **settings)) @@ -301,3 +294,26 @@ def test_numeric_size_uses_unrotated_artwork_dimensions_before_final_scale(self) self.assertAlmostEqual(right - left, 60) self.assertAlmostEqual(top - bottom, 40) self.assertEqual(settings['scale'], 2) + + def test_only_original_size_uses_manual_dimensions_and_scale(self): + session = self.session + session.bounds = fusion_import.Frame((0, 0, 80, 60)) + session.sizes.update.return_value = (2, 3) + session.transform.values.return_value = (4, 5, 0.3, 1.5) + for index, expected in ((0, (80, 40)), (1, (80, 60))): + session.scaling.selectedItem.index = index + self.changed('scale') + _, target, settings = session._placements() + self.assertEqual((target.width_mm, target.height_mm), expected) + self.assertEqual(target.rotation, 0.3) + self.assertEqual(target.pivot, (44, 35)) + self.assertEqual(settings['scale'], 1) + session.sizes.set_visible.assert_called_with(False) + session.transform.show_scale.assert_called_with(False) + session.sizes.update.assert_not_called() + session.scaling.selectedItem.index = 2 + self.changed('scale') + _, target, _ = session._placements() + self.assertEqual((target.width_mm, target.height_mm), (60, 45)) + session.sizes.set_visible.assert_called_with(True) + session.transform.show_scale.assert_called_with(True) diff --git a/tests/test_dimensions.py b/tests/test_dimensions.py index d4c8af7..bd1003a 100644 --- a/tests/test_dimensions.py +++ b/tests/test_dimensions.py @@ -75,30 +75,6 @@ def test_zero_axis_is_read_only_and_nonzero_dimension_can_resize(self): self.assertEqual(s.update(0, 40, None), (.5, .5)) self.assertTrue(s.height.isEnabled) - def test_row_reset_preserves_the_unlinked_height_and_global_reset_restores_both(self): - s = self.size - s.link.value = False - s.changed(s.link.id) - s.update(80, 60, 2.) - s.width.value, s.height.value = 12, 4 - s.changed(s.width.id) - s.changed(s.height.id) - self.assertTrue(s.changed('resetSvgWidth')) - self.assertEqual(s.update(80, 60, 2.), (1., 2/3)) - self.assertEqual((s.width.value, s.height.value), (8, 4)) - s.reset() - self.assertEqual(s.update(80, 60, 2.), (1., 1.)) - self.assertEqual((s.width.value, s.height.value), (8, 6)) - - def test_linked_dimension_reset_restores_the_stretch_baseline(self): - s = self.size - s.update(80, 60, 2.) - s.width.value = 10 - s.changed(s.width.id) - self.assertEqual(s.update(80, 60, 2.), (1.25, 5/6)) - self.assertTrue(s.changed('resetSvgHeight')) - self.assertEqual(s.update(80, 60, 2.), (1., 1.)) - def test_programmatic_length_writes_do_not_trigger_manual_aspect_edits(self): s = self.size events = [] diff --git a/tests/test_manipulator.py b/tests/test_manipulator.py index d5afbc3..6b42537 100644 --- a/tests/test_manipulator.py +++ b/tests/test_manipulator.py @@ -218,7 +218,7 @@ def test_native_matrix_motion_preserves_scale_and_can_reanchor(self): self.assertEqual(triad.transform.getAsCoordinateSystem()[0].asArray(), (5, 9.5, 9.6)) self.assertEqual(self.t.values()[3], 1.5) - def test_reset_hides_stale_pose_before_reanchor_and_can_reset_one_axis_in_place(self): + def test_new_anchor_discards_the_old_native_pose_before_repositioning(self): triad = self.t.triad self.t.position(self.sketch, (10, 20)) self.t.apply_position() @@ -228,15 +228,22 @@ def test_reset_hides_stale_pose_before_reanchor_and_can_reset_one_axis_in_place( triad.lastChangeMade = 14 triad.xYPlaneScaleFactor = 1.5 self.assertTrue(self.t.read_drag()) - self.t.reset((0,)) - self.assertEqual(self.t.values(), (0, 10, 0, 1.5)) - self.assertTrue(self.t.position(self.sketch, (10, 20))) - self.t.apply_position() - self.assertEqual(triad.xTranslationExpression, '0') - self.assertEqual(triad.transform.getAsCoordinateSystem()[0].asArray(), (5, 7, 10)) - self.t.reset() + self.t.start_at_anchor() self.assertEqual(self.t.values(), (0, 0, 0, 1)) self.t.position(self.sketch, (40, 60)) self.t.apply_position() self.assertEqual(triad.transform.getAsCoordinateSystem()[0].asArray(), (5, 10, 13)) self.assertEqual(triad.xYPlaneScaleFactorExpression, '1') + + def test_hidden_scale_handle_does_not_read_an_old_native_scale_event(self): + triad = self.t.triad + self.t.position(self.sketch, (10, 20)) + self.t.apply_position() + self.t.show_scale(False) + triad.lastChangeMade = 14 + triad.xYPlaneScaleFactor = 3 + self.assertFalse(self.t.read_drag()) + self.assertFalse(triad.isXYPlaneScalingVisible) + self.t.show_scale(True) + self.assertTrue(triad.isXYPlaneScalingVisible) + self.assertEqual(triad.xYPlaneScaleFactorExpression, '1.0')