diff --git a/.fusion-addin.json b/.fusion-addin.json index 4724926..d1160f5 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": "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/.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.manifest b/FusionAddin/FusionAddin.manifest deleted file mode 100644 index 26e0d17..0000000 --- a/FusionAddin/FusionAddin.manifest +++ /dev/null @@ -1,12 +0,0 @@ -{ - "autodeskProduct": "Fusion360", - "type": "addin", - "id": "00000000-0000-4000-8000-000000000000", - "author": "Pavel Kuznetsov", - "description": { - "": "A starter add-in for Autodesk Fusion by 4FusionLab." - }, - "version": "0.1.0", - "runOnStartup": false, - "supportedOS": "windows|mac" -} 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/InsertTo/InsertTo.manifest b/InsertTo/InsertTo.manifest new file mode 100644 index 0000000..03c4f4b --- /dev/null +++ b/InsertTo/InsertTo.manifest @@ -0,0 +1,12 @@ +{ + "autodeskProduct": "Fusion360", + "type": "addin", + "id": "d4f953a4-7cc6-4027-9699-dc025ebc8966", + "author": "Pavel Kuznetsov", + "description": { + "": "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": true, + "supportedOS": "windows|mac" +} diff --git a/InsertTo/InsertTo.py b/InsertTo/InsertTo.py new file mode 100644 index 0000000..7036b9a --- /dev/null +++ b/InsertTo/InsertTo.py @@ -0,0 +1,80 @@ +"""Register Smart Insert in the sketch Insert menu.""" + +import traceback +from pathlib import Path + +import adsk.core + +from . import config, dialog, frame_link + + +_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): + 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): + 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) + frame_link.install(adsk.core.Application.get()) + except Exception: + stop(context) + raise + + +def stop(context): + global _menu, _created, _definition + try: + frame_link.uninstall() + if _menu and _menu.isValid: + _menu.deleteMe() + if _definition and _definition.isValid: + _definition.deleteMe() + finally: + _menu = _created = _definition = None + for session, _ in _sessions: + session.close() + _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..b627092 --- /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 = '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 new file mode 100644 index 0000000..e3b7730 --- /dev/null +++ b/InsertTo/dialog.py @@ -0,0 +1,463 @@ +"""Native Smart Insert command inputs and transactional sketch preview.""" + +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, TriadControls + + +_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'), +) + + +_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 + ) + 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.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.source_document = None + self.source_curves = None + self.file_error = '' + self.preview_error = '' + + self.graphics = None + self.graphics_key = None + self.graphics_pivot = None + self._selected_target = None + + command.isExecutedWhenPreEmpted = False + command.okButtonText = 'Insert' + 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 (optional)', 'Select a sketch profile or a closed contour' + ) + self.frame.addSelectionFilter('Profiles') + self.frame.addSelectionFilter('SketchCurves') + 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.' + if self.link is None: + self.transform = TransformControls(inputs, units) + self.sizes = None + else: + self.transform = TriadControls(inputs) + children = self.transform.group.children + self.sizes = SizeControls(children, units) + self.transform.create_fields() + self.command = command + self.status = inputs.addTextBoxCommandInput('importStatus', '', '', 2, True) + self.status.isFullWidth = True + 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.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: + 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.artwork_bounds = None + self.source_document = None + self.source_curves = 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 + try: + if self.sizes is not None and self.sizes.handles(changed): + self.preview_error = '' + if self._mode() == 'original' and 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): + self.preview_error = '' + if self.transform.changed(changed): + self._move_graphics() + return + if changed == 'svgFile' and not self._choose_file(): + return + 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 _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.transform.start_at_anchor() + self.graphics_pivot = None + self.preview_error = '' + self._selected_target = selected + + 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: + _, target, _ = self._placements() + 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): + self.graphics.show(target) + self.app.activeViewport.refresh() + + def close(self): + if self.graphics: + self.graphics.clear() + self.graphics = self.graphics_key = self.graphics_pivot = None + + def _mode(self): + if not self.frame.selectionCount: + return 'original' + return _MODES[self.scaling.selectedItem.index][1] + + 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')) + 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') + _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 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.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.') + 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 _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() + 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) + 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 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: + 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() + 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 + + 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: + 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._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…') + else: + _, target, _ = self._placements() + self._dimensions(target) + args.areInputsValid = True + except Exception as exc: + args.areInputsValid = False + self._status(str(exc)) + + def _linked(self, settings): + 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) + 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._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 or not self.transform.group.isVisible: + if destination is None: + destination = fusion_import.sketch_for_target(self.design, sketch, plane) + 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: + 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._show_preview(target) + self._dimensions(target) + + def _insert(self, sketch, plane): + destination = fusion_import.sketch_for_target(self.design, sketch, plane) + try: + 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): + entities = [self.frame.selection(i).entity for i in range(self.frame.selectionCount)] + 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) + except Exception: + if sketch is None and destination.isValid: + destination.deleteMe() + raise + + def _preview(self, args): + args.isValidResult = False + try: + sketch, plane = self._destination() + except Exception as exc: + self._status(str(exc)) + self.transform.hide() + self.close() + return + try: + self._preview_graphics(sketch, plane) + 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) + + def _execute(self, args): + try: + self.close() + self.transform.read_drag() + self._insert(*self._destination()) + except Exception as exc: + self.app.log(traceback.format_exc()) + args.executeFailed = True + args.executeFailedMessage = f'SVG insert failed. {exc}' + + +def attach(command): + """Return the command session. Its owner retains it until command.destroy.""" + return _Dialog(command) diff --git a/InsertTo/dimensions.py b/InsertTo/dimensions.py new file mode 100644 index 0000000..d6937e8 --- /dev/null +++ b/InsertTo/dimensions.py @@ -0,0 +1,111 @@ +"""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 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 == 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/drag_graphics.py b/InsertTo/drag_graphics.py new file mode 100644 index 0000000..e773f45 --- /dev/null +++ b/InsertTo/drag_graphics.py @@ -0,0 +1,173 @@ +"""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 + 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 + 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): + 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 new file mode 100644 index 0000000..3a921da --- /dev/null +++ b/InsertTo/frame_link.py @@ -0,0 +1,450 @@ +"""Maintain fitted SVG geometry when a linked sketch frame changes.""" + +from contextlib import contextmanager +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' +_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 + + +@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.') + + +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, 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.') + reference = _frame_reference(sketch, list(frame_entities)) + 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 = [] + 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. + 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) + 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)} + 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: + 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() + 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, record): + sketch = attr.parent + 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): + 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)) + + with _batch_edit(attr.parent): + 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])): + 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: + 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 new file mode 100644 index 0000000..5ecc66e --- /dev/null +++ b/InsertTo/fusion_import.py @@ -0,0 +1,323 @@ +"""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 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 ( + '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] + 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] + else: + if not _closed_chain(curves): + raise ValueError('Choose one closed contour, or select its shaded profile.') + geometry = [curve.geometry for curve in curves] + + angle = _rectangle_angle(geometry) + 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: + # 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]: + raise ValueError('The selected frame has zero width or height.') + return Frame(bounds, 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, 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. + 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.') + + +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 + + 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..e8d2a3b --- /dev/null +++ b/InsertTo/manipulator.py @@ -0,0 +1,313 @@ +"""Planar Transform inputs and root-space sketch coordinates.""" + +import math + +import adsk.core + + +_DEFAULT_POSE = (0., 0., 0., 1.) + + +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 = _DEFAULT_POSE + self._new_anchor = False + 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 or self._new_anchor: + 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 + 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)) + 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 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.isXYPlaneScalingVisible + and 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) + for a, b in zip(self._last_values, values)): + return False + self._last_values = values + return True + + def show_scale(self, visible): + triad = self.triad + if triad.isXYPlaneScalingVisible == visible: + return + self._updating = True + try: + 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._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._new_anchor: + 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 + 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._new_anchor = False + 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): + self.group = _transform_group(inputs) + 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): + children = self.group.children + real = adsk.core.ValueInput.createByReal + # 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.') + self.fields[-1].minimumValue = 0 + self.fields[-1].isMinimumLimited = True + self.fields[-1].isMinimumInclusive = False + + 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) + 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 changed(self, input_id): + return self.handles(input_id) and self.read_drag() + + def read_drag(self): + """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 + if values == self._last_values: + return False + self._updating = True + try: + self._place_handles(values, previous=self._last_values) + self._last_values = values + finally: + self._updating = False + return True + + 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): + """Place all handles in root component coordinates, including occurrence sketches.""" + root, basis = _sketch_basis(sketch) + pivot = tuple(pivot_xy_mm) + if self.group.isVisible and self.root == root and self.plane_basis == basis and self._pivot == pivot: + return + 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]: + 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): + if self.group.isVisible: + for field in self.fields[:3]: + field.isEnabled = False + field.isVisible = False + self.group.isVisible = False 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/resources/aspect-linked/16x16.png b/InsertTo/resources/aspect-linked/16x16.png new file mode 100644 index 0000000..73a2d05 Binary files /dev/null and b/InsertTo/resources/aspect-linked/16x16.png differ diff --git a/InsertTo/resources/aspect-linked/16x16@2x.png b/InsertTo/resources/aspect-linked/16x16@2x.png new file mode 100644 index 0000000..e164f2d Binary files /dev/null and b/InsertTo/resources/aspect-linked/16x16@2x.png differ diff --git a/InsertTo/resources/aspect-linked/32x32.png b/InsertTo/resources/aspect-linked/32x32.png new file mode 100644 index 0000000..e164f2d Binary files /dev/null and b/InsertTo/resources/aspect-linked/32x32.png differ diff --git a/InsertTo/resources/aspect-linked/32x32@2x.png b/InsertTo/resources/aspect-linked/32x32@2x.png new file mode 100644 index 0000000..7aae9e2 Binary files /dev/null and b/InsertTo/resources/aspect-linked/32x32@2x.png differ diff --git a/InsertTo/resources/aspect-unlinked/16x16.png b/InsertTo/resources/aspect-unlinked/16x16.png new file mode 100644 index 0000000..b788c14 Binary files /dev/null and b/InsertTo/resources/aspect-unlinked/16x16.png differ diff --git a/InsertTo/resources/aspect-unlinked/16x16@2x.png b/InsertTo/resources/aspect-unlinked/16x16@2x.png new file mode 100644 index 0000000..7368f7f Binary files /dev/null and b/InsertTo/resources/aspect-unlinked/16x16@2x.png differ diff --git a/InsertTo/resources/aspect-unlinked/32x32.png b/InsertTo/resources/aspect-unlinked/32x32.png new file mode 100644 index 0000000..7368f7f Binary files /dev/null and b/InsertTo/resources/aspect-unlinked/32x32.png differ diff --git a/InsertTo/resources/aspect-unlinked/32x32@2x.png b/InsertTo/resources/aspect-unlinked/32x32@2x.png new file mode 100644 index 0000000..2ce8aa8 Binary files /dev/null and b/InsertTo/resources/aspect-unlinked/32x32@2x.png differ diff --git a/InsertTo/resources/bottom-center/16x16.png b/InsertTo/resources/bottom-center/16x16.png new file mode 100644 index 0000000..489a1f7 Binary files /dev/null and b/InsertTo/resources/bottom-center/16x16.png differ diff --git a/InsertTo/resources/bottom-center/32x32.png b/InsertTo/resources/bottom-center/32x32.png new file mode 100644 index 0000000..562a1d4 Binary files /dev/null and b/InsertTo/resources/bottom-center/32x32.png differ diff --git a/InsertTo/resources/bottom-left/16x16.png b/InsertTo/resources/bottom-left/16x16.png new file mode 100644 index 0000000..8bf4cbf Binary files /dev/null and b/InsertTo/resources/bottom-left/16x16.png differ diff --git a/InsertTo/resources/bottom-left/32x32.png b/InsertTo/resources/bottom-left/32x32.png new file mode 100644 index 0000000..d789041 Binary files /dev/null and b/InsertTo/resources/bottom-left/32x32.png differ diff --git a/InsertTo/resources/bottom-right/16x16.png b/InsertTo/resources/bottom-right/16x16.png new file mode 100644 index 0000000..38f5376 Binary files /dev/null and b/InsertTo/resources/bottom-right/16x16.png differ diff --git a/InsertTo/resources/bottom-right/32x32.png b/InsertTo/resources/bottom-right/32x32.png new file mode 100644 index 0000000..6d1f5ed Binary files /dev/null and b/InsertTo/resources/bottom-right/32x32.png differ diff --git a/InsertTo/resources/center-left/16x16.png b/InsertTo/resources/center-left/16x16.png new file mode 100644 index 0000000..93251a2 Binary files /dev/null and b/InsertTo/resources/center-left/16x16.png differ diff --git a/InsertTo/resources/center-left/32x32.png b/InsertTo/resources/center-left/32x32.png new file mode 100644 index 0000000..2400314 Binary files /dev/null and b/InsertTo/resources/center-left/32x32.png differ diff --git a/InsertTo/resources/center-right/16x16.png b/InsertTo/resources/center-right/16x16.png new file mode 100644 index 0000000..944926f Binary files /dev/null and b/InsertTo/resources/center-right/16x16.png differ diff --git a/InsertTo/resources/center-right/32x32.png b/InsertTo/resources/center-right/32x32.png new file mode 100644 index 0000000..c395bdb Binary files /dev/null and b/InsertTo/resources/center-right/32x32.png differ diff --git a/InsertTo/resources/center/16x16.png b/InsertTo/resources/center/16x16.png new file mode 100644 index 0000000..df2fc1d Binary files /dev/null and b/InsertTo/resources/center/16x16.png differ diff --git a/InsertTo/resources/center/32x32.png b/InsertTo/resources/center/32x32.png new file mode 100644 index 0000000..fa32cf3 Binary files /dev/null and b/InsertTo/resources/center/32x32.png differ diff --git a/InsertTo/resources/fit/16x16.png b/InsertTo/resources/fit/16x16.png new file mode 100644 index 0000000..74d57c1 Binary files /dev/null and b/InsertTo/resources/fit/16x16.png differ diff --git a/InsertTo/resources/fit/32x32.png b/InsertTo/resources/fit/32x32.png new file mode 100644 index 0000000..43d6de9 Binary files /dev/null and b/InsertTo/resources/fit/32x32.png differ diff --git a/InsertTo/resources/original/16x16.png b/InsertTo/resources/original/16x16.png new file mode 100644 index 0000000..05e9b02 Binary files /dev/null and b/InsertTo/resources/original/16x16.png differ diff --git a/InsertTo/resources/original/32x32.png b/InsertTo/resources/original/32x32.png new file mode 100644 index 0000000..09c2884 Binary files /dev/null and b/InsertTo/resources/original/32x32.png differ diff --git a/InsertTo/resources/stretch/16x16.png b/InsertTo/resources/stretch/16x16.png new file mode 100644 index 0000000..f93e7f5 Binary files /dev/null and b/InsertTo/resources/stretch/16x16.png differ diff --git a/InsertTo/resources/stretch/32x32.png b/InsertTo/resources/stretch/32x32.png new file mode 100644 index 0000000..5dc24fc Binary files /dev/null and b/InsertTo/resources/stretch/32x32.png differ diff --git a/InsertTo/resources/top-center/16x16.png b/InsertTo/resources/top-center/16x16.png new file mode 100644 index 0000000..d47c7a4 Binary files /dev/null and b/InsertTo/resources/top-center/16x16.png differ diff --git a/InsertTo/resources/top-center/32x32.png b/InsertTo/resources/top-center/32x32.png new file mode 100644 index 0000000..334fc05 Binary files /dev/null and b/InsertTo/resources/top-center/32x32.png differ diff --git a/InsertTo/resources/top-left/16x16.png b/InsertTo/resources/top-left/16x16.png new file mode 100644 index 0000000..3c64166 Binary files /dev/null and b/InsertTo/resources/top-left/16x16.png differ diff --git a/InsertTo/resources/top-left/32x32.png b/InsertTo/resources/top-left/32x32.png new file mode 100644 index 0000000..6c3c2af Binary files /dev/null and b/InsertTo/resources/top-left/32x32.png differ diff --git a/InsertTo/resources/top-right/16x16.png b/InsertTo/resources/top-right/16x16.png new file mode 100644 index 0000000..37f8b3c Binary files /dev/null and b/InsertTo/resources/top-right/16x16.png differ diff --git a/InsertTo/resources/top-right/32x32.png b/InsertTo/resources/top-right/32x32.png new file mode 100644 index 0000000..a74b4a1 Binary files /dev/null and b/InsertTo/resources/top-right/32x32.png differ diff --git a/InsertTo/svg_geometry.py b/InsertTo/svg_geometry.py new file mode 100644 index 0000000..e0f4d92 --- /dev/null +++ b/InsertTo/svg_geometry.py @@ -0,0 +1,484 @@ +"""SVG viewport sizing and placement in sketch coordinates (millimetres, Y up).""" + +import copy +from dataclasses import dataclass, field +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 + 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): + 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 _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.') + 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, 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 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.') + if not all(map(math.isfinite, (x_mm, y_mm, rotation))): + raise ValueError('Placement coordinates and angle must be finite.') + _positive(scale, 'Scale') + _positive(width_factor, 'Width factor') + _positive(height_factor, 'Height factor') + 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': + sx = sy = _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 = fw / w, 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 + sx = sx * width_factor * scale + sy = sy * height_factor * scale + 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 - 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 + ) + return Placement(left, bottom, page_width, page_height, + 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): + 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 path_commands(data): + """Yield explicit SVG path commands, expanding implicit groups after moveto.""" + cursor = 0 + command = '' + while True: + cursor = _PATH_SEPARATORS.match(data, cursor).end() + if cursor == len(data): + return + 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': + yield command, [] + command = '' + 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() + 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': + 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 + current, previous = end, op + return ' '.join(output) + + +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 269304a..9a63e41 100644 --- a/README.md +++ b/README.md @@ -2,32 +2,36 @@

InsertTo logo

-[Русская версия](README.ru.md) +Place SVG curves in an Autodesk Fusion sketch at their physical size, or fit them to a sketch profile. -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. 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. -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. +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. -> Never install or publish the uninitialized `FusionAddin` placeholder as a real product. +| Fit to frame | Result before manual transforms | +| --- | --- | +| 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. | -## What is shared? +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. -- 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. +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. -The repository is a template, not an existing 4FusionLab product. See `docs/DEVELOPMENT.md` after scaffolding is installed. +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. -## Prepare product documentation +## Verified in Fusion -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. +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 + +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 2ec10ba..3ad0f25 100644 --- a/README.ru.md +++ b/README.ru.md @@ -2,33 +2,36 @@

Логотип 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. На вкладке **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**, чтобы отменить вставку. -При необходимости инициализируй локально: `python scripts/init_addin.py --name MyNewAddin --display-name "My New Add-in"`. Затем закоммить изменения и отправь в свой репозиторий. +В режиме **Original size** и при свободной вставке без рамки поля **Width** и **Height** задают размеры выбранной области SVG до поворота. Цепочка сохраняет исходные пропорции при вводе размера. Отключите её, чтобы изменить ширину и высоту независимо. При размере 40 × 20 мм и **Scale Plane XY** 1,5 итоговый размер будет 60 × 30 мм. -**Не устанавливай исходную папку `FusionAddin` как готовый продукт:** шаблон намеренно помечен неинициализированным. +| Режим Fit to frame | Результат до ручного перемещения и масштабирования | +| --- | --- | +| Fit — вписать | Вписывает выбранную область с сохранением пропорций и учётом отступа. Если остаётся место, **Align** предлагает три положения вдоль свободной оси. | +| Stretch — растянуть | Подгоняет ширину и высоту независимо, заполняя рамку с учётом отступа. | +| Original size — исходный размер | Сохраняет физические размеры SVG. В **Align from** можно выбрать любую из девяти точек и совместить её с соответствующей точкой рамки с учётом отступа. | -## Что унифицировано +В режимах **Fit** и **Stretch** флажок **Link to frame** включён по умолчанию. InsertTo создаёт кривые SVG как фиксированные сплайны. Рисунок перемещается вместе с рамкой и меняет размер при изменении её размеров. Правка рамки и автоматическое обновление SVG занимают два шага в истории отмены. Оставьте InsertTo запущенным, чтобы он обновил сплайны после правки. Чтобы редактировать кривые SVG по отдельности, снимите флажок перед вставкой. Если рисунок вставлен более ранней версией, вставьте его заново с включённым флажком для создания связи. -- 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-агентов. +Например, страница 50 × 20 мм в рамке 80 × 60 мм при **Fit** займёт 80 × 32 мм. С **Align → Center** сверху и снизу останется по 14 мм. С **Align → Top** верхние границы совпадут, а снизу останется 28 мм. В этом примере отступ равен нулю. -Инструкция по разработке и приёмке — в [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md). +У прямоугольной рамки учитывается поворот сторон. Для других контуров берётся габаритный прямоугольник по осям эскиза, поэтому рисунок может выходить за границу контура сложной формы. Страница шириной 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**. В режиме **Stretch** с включённым **Link to frame** изменение прямоугольной рамки с 80 × 50 мм до 100 × 50 мм обновило связанный эллипс после правки. Отступ 5 мм сохранился, а объём выдавливания этого профиля на 10 мм изменился с 21,99 до 28,27 см³. При переносе рамки на 12 мм вправо и 4 мм вниз оба связанных рисунка сдвинулись на те же расстояния. Для Fit, Stretch и свободной вставки после масштабирования ручкой габариты кривых в предпросмотре и после вставки совпали. Проверка в Fusion на Windows ещё предстоит. -Инициализатор создаёт начальные страницы, а не готовую документацию продукта. До публикации замените исходное описание в **обоих** файлах `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..6d4f44b 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -4,24 +4,17 @@ ## 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` 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. -## 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,20 +22,17 @@ 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 - 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 0ff8d67..672a33b 100644 --- a/docs/DEVELOPMENT.ru.md +++ b/docs/DEVELOPMENT.ru.md @@ -4,24 +4,17 @@ ## Архитектура -- `/.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` определяет размеры 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`: проверенный перечень файлов, влияющих на поставляемые компоненты. -## Работа над новым продуктом - -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,20 +22,17 @@ 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 - Установка, запуск, остановка и повторный запуск без дублирующихся элементов управления и утечек обработчиков. -- Команда открывается, отменяется и выполняется; результат корректен и безопасен. +- Вставьте 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/docs/releases/1.0.0.md b/docs/releases/1.0.0.md new file mode 100644 index 0000000..9544316 --- /dev/null +++ b/docs/releases/1.0.0.md @@ -0,0 +1,11 @@ +[Русская версия](https://github.com/4FusionLab/InsertTo/blob/v1.0.0/docs/releases/1.0.0.ru.md) + +InsertTo brings SVG curves into Autodesk Fusion sketches. Place a drawing at its physical size or fit it to an existing sketch profile or closed contour. + +- Open **Insert → Smart Insert → SVG** on the **Solid** or **Sketch** tab. +- Choose **Fit**, **Stretch**, or **Original size**. Fit and Stretch can keep the inserted geometry linked to its frame. +- Use Fusion’s own handles to position the drawing. In Original size and without a frame, you can also edit Width and Height or scale both together. + +Unzip `InsertTo-1.0.0.zip` and add the `InsertTo` folder in Fusion’s **Scripts and Add-Ins** dialog. The ZIP includes the Fusion manifest. + +The SVG workflow was tested in Fusion on macOS. Native Fusion testing on Windows is pending. diff --git a/docs/releases/1.0.0.ru.md b/docs/releases/1.0.0.ru.md new file mode 100644 index 0000000..dd91237 --- /dev/null +++ b/docs/releases/1.0.0.ru.md @@ -0,0 +1,11 @@ +[English](1.0.0.md) + +InsertTo вставляет кривые SVG в эскизы Autodesk Fusion. Рисунок можно разместить в исходном физическом размере или вписать в профиль эскиза либо замкнутый контур. + +- Откройте **Insert → Smart Insert → SVG** на вкладке **Solid** или **Sketch**. +- Выберите **Fit**, **Stretch** или **Original size**. В режиме Fit или Stretch можно сохранить связь вставленной геометрии с рамкой. +- Используйте штатные ручки Fusion для размещения рисунка. В режиме Original size и без рамки можно также изменить Width и Height или пропорционально масштабировать рисунок. + +Распакуйте `InsertTo-1.0.0.zip` и добавьте папку `InsertTo` через диалог **Scripts and Add-Ins** в Fusion. В архив входит манифест Fusion. + +Вставка SVG проверена в Fusion на macOS. Проверка в Fusion на Windows ещё предстоит. 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..5e6beb4 --- /dev/null +++ b/tests/test_dialog.py @@ -0,0 +1,319 @@ +"""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 drag_graphics, frame_link, fusion_import, preview_source, 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() + command = Mock() + command.commandInputs.addSelectionInput.return_value.selectionCount = 0 + with patch.object(module, '_listen'), patch.object(module, 'SizeControls'): + self.session = module._Dialog(command) + self.session.sizes.update.return_value = (1, 1) + self.session.sizes.handles.return_value = False + 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.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 + 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 + 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))) + + 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, 'source_curves', side_effect=ValueError('No curves.')): + self.session._preview(args) + self.assertFalse(args.isValidResult) + self.session.transform.hide.assert_called_once() + self.session.transform.position.assert_not_called() + 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.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') + self.session._validate(args) + 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' + self.changed('frame') + self.session._preview(args) + 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']]) + + 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.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)) + + 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.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.start_at_anchor.assert_called_once_with() + + + 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(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.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(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_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('placementTransform') + 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)) + 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, 'source_curves', 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(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.assertFalse(args.isValidResult) + plain.assert_not_called() + 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.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.)) + self.assertIs(sketch, session.sketch) + self.assertEqual(entities, [session.frame.selection(0).entity]) + self.assertEqual(target, svg_geometry.placement(doc, session.bounds, **settings)) + + 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.source.assert_called_once() + self.capture.assert_called_once() + self.assertEqual(self.graphics.show.call_count, 4) + + def test_numeric_size_uses_unrotated_artwork_dimensions_before_final_scale(self): + session = self.session + session.frame.selectionCount = 0 + session.extent.selectedItem.index = 1 + session.artwork_bounds = (2, 1, 12, 6) + session.sizes.update.return_value = (3, 4) + session.transform.values.return_value = (15, -4, 0.6, 2) + _, target, settings = session._placements() + session.sizes.update.assert_called_once_with(10, 5, 2) + self.assertEqual(target.pivot, (15, -4)) + left, bottom, right, top = target.selected_box + 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 new file mode 100644 index 0000000..bd1003a --- /dev/null +++ b/tests/test_dimensions.py @@ -0,0 +1,110 @@ +"""Dimensional edits on the source bounds and their behavior on a changing frame.""" + +import sys +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from InsertTo.dimensions import SizeControls + + +class SizeTests(unittest.TestCase): + def setUp(self): + sdk, self.inputs = Mock(), Mock() + sdk.core.ValueInput.createByReal.side_effect = float + + def field(id_, _, units, initial): + return SimpleNamespace(id=id_, value=initial, units=units, + isValidExpression=True, isEnabled=True) + + def button(id_, _, checkbox, folder, initial): + return SimpleNamespace(id=id_, value=initial, isEnabled=True, resourceFolder=folder) + + self.inputs.addValueInput.side_effect = field + self.inputs.addBoolValueInput.side_effect = button + with patch.dict(sys.modules, {'adsk': sdk, 'adsk.core': sdk.core}): + self.size = SizeControls(self.inputs, 'in') + + def test_native_units_and_untouched_stretch(self): + s = self.size + self.assertEqual((s.width.units, s.height.units), ('in', 'in')) + self.assertTrue(s.link.value) + self.assertEqual(s.update(80, 60, 2.), (1., 1.)) + self.assertEqual((s.width.value, s.height.value), (8, 6)) # Internal Fusion cm. + self.assertFalse(s.changed(s.width.id)) # Ignore notifications from a prior sync. + self.assertEqual(s.update(95, 55, 2.), (1., 1.)) + + def test_manual_width_locks_original_aspect_and_follows_frame(self): + s = self.size + s.update(80, 60, 2.) + s.width.value = 10 + self.assertTrue(s.changed(s.width.id)) + self.assertEqual(s.update(80, 60, 2.), (1.25, 50/60)) + self.assertEqual(s.height.value, 5) + self.assertEqual(s.update(120, 75, 2.), (1.25, 1.)) + self.assertEqual((s.width.value, s.height.value), (15, 7.5)) + + def test_unlinked_edits_use_both_factors_and_relink_uses_last_edited_height(self): + s = self.size + s.update(80, 60, 2.) + s.link.value = False + self.assertTrue(s.changed(s.link.id)) + self.assertTrue(s.link.resourceFolder.endswith('aspect-unlinked')) + s.width.value = 10 + s.changed(s.width.id) + self.assertEqual(s.update(80, 60, 2.), (1.25, 1.)) + s.height.value = 3 + s.changed(s.height.id) + self.assertEqual(s.update(80, 60, 2.), (1.25, .5)) + s.update(120, 90, 2.) + self.assertEqual((s.width.value, s.height.value), (15, 4.5)) + s.link.value = True + s.changed(s.link.id) + self.assertTrue(s.link.resourceFolder.endswith('aspect-linked')) + self.assertEqual(s.update(120, 90, 2.), (.75, .5)) + self.assertEqual((s.width.value, s.height.value), (9., 4.5)) + + def test_zero_axis_is_read_only_and_nonzero_dimension_can_resize(self): + s = self.size + self.assertEqual(s.update(0, 40, None), (1., 1.)) + self.assertEqual(s.width.value, 0) + self.assertFalse(s.width.isEnabled) + self.assertFalse(s.link.isEnabled) + s.height.value = 2. + self.assertTrue(s.changed(s.height.id)) + self.assertEqual(s.update(0, 40, None), (.5, .5)) + self.assertTrue(s.height.isEnabled) + + def test_programmatic_length_writes_do_not_trigger_manual_aspect_edits(self): + s = self.size + events = [] + + class NotifyingField(SimpleNamespace): + def __setattr__(self, name, value): + super().__setattr__(name, value) + if name == 'value': + events.append(s.changed(self.id)) + + s.width = NotifyingField(**vars(s.width)) + s.height = NotifyingField(**vars(s.height)) + s._fields = s.width, s.height + self.assertEqual(s.update(80, 60, 2.), (1., 1.)) + self.assertEqual(events, [False, False]) + self.assertEqual(s.update(90, 50, 2.), (1., 1.)) + + def test_invalid_length_is_preserved_and_does_not_change_factors(self): + s = self.size + s.update(80, 60, 2.) + s.height.isValidExpression = False + s.changed(s.height.id) + with self.assertRaisesRegex(ValueError, 'positive length'): + s.update(80, 60, 2.) + s.height.isValidExpression = True + s.height.value = 0 + s.changed(s.height.id) + with self.assertRaisesRegex(ValueError, 'positive length'): + s.update(80, 60, 2.) + self.assertEqual(s.height.value, 0) + s.height.value = 6. + s.changed(s.height.id) + self.assertEqual(s.update(80, 60, 2.), (1., 1.)) diff --git a/tests/test_drag_graphics.py b/tests/test_drag_graphics.py new file mode 100644 index 0000000..5b5f420 --- /dev/null +++ b/tests/test_drag_graphics.py @@ -0,0 +1,86 @@ +"""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) + 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() + 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_frame_link.py b/tests/test_frame_link.py new file mode 100644 index 0000000..8d1c91a --- /dev/null +++ b/tests/test_frame_link.py @@ -0,0 +1,244 @@ +import json +import sys +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) + + +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(entityToken=f'curve-{splines.addByNurbsCurve.call_count}') + + 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) + 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']) + + def test_resized_frame_reapplies_stored_axis_factors_and_loads_legacy_links(self): + drawing = SimpleNamespace(width_mm=20, height_mm=30) + frame = (0, 0, 80, 60) + settings = dict(mode='stretch', anchor='top-right', width_factor=.5, height_factor=1.5, scale=2) + target = geo.placement(drawing, frame, **settings) + spline = Mock(entityToken='new') + self.sketch.sketchCurves.sketchFixedSplines.addByNurbsCurve.return_value = spline + with patch.object(links, '_matrix'), patch.object(links, '_frame_reference', return_value={}): + links.insert(self.sketch, drawing, target, [], source_curves=[Mock()], **settings) + attr = SimpleNamespace(parent=self.sketch, value=self.sketch.attributes.add.call_args.args[2]) + with patch.object(links, '_resolve_frame', return_value=(0, 0, 100, 90)): + record, resized = links._changed(Mock(), attr) + self.assertEqual((resized.width_mm, resized.height_mm), (100, 270)) + self.assertEqual(resized.pivot, (100, 90)) + del record['options']['width_factor'], record['options']['height_factor'] + attr.value = json.dumps(record) + _, legacy = links._changed(Mock(), attr) + self.assertEqual((legacy.width_mm, legacy.height_mm), (200, 180)) + + 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() + + 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), []) diff --git a/tests/test_fusion_import.py b/tests/test_fusion_import.py new file mode 100644 index 0000000..cef8385 --- /dev/null +++ b/tests/test_fusion_import.py @@ -0,0 +1,142 @@ +import math +import sys +from pathlib import Path +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, 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_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) + + @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, rotation=angle) + 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) + + 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..6b42537 --- /dev/null +++ b/tests/test_manipulator.py @@ -0,0 +1,249 @@ +"""Native translation, angle and custom canvas grips share one sketch placement.""" + +import math +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +from test_dialog import load_dialog + + +class Coordinates: + def __init__(self, x, y, z): + self.x, self.y, self.z = x, y, z + + def asArray(self): + return self.x, self.y, self.z + + def distanceTo(self, other): + return math.dist(self.asArray(), other.asArray()) + + def vectorTo(self, other): + return Coordinates(other.x - self.x, other.y - self.y, other.z - self.z) + + def crossProduct(self, other): + return Coordinates(self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, + self.x * other.y - self.y * other.x) + + +class TransformTests(unittest.TestCase): + def setUp(self): + self.module = load_dialog() + sdk = self.module.adsk.core + self.enterContext(patch.object(sdk.Point3D, 'create', side_effect=Coordinates)) + self.enterContext(patch.object(sdk.Vector3D, 'create', side_effect=Coordinates)) + self.inputs = Mock() + self.command_inputs = self.inputs.addGroupCommandInput.return_value.children + self.command_inputs.addDistanceValueCommandInput.side_effect = lambda id_, *_: Mock( + id=id_, value=0., isValidExpression=True) + self.command_inputs.addAngleValueCommandInput.return_value = Mock( + id='rotateSVG', value=0., isValidExpression=True) + self.command_inputs.addValueInput.return_value = Mock(id='scaleSVG', value=1., isValidExpression=True) + self.t = self.module.TransformControls(self.inputs, 'mm') + self.sketch = Mock() + self.sketch.assemblyContext = None + self.design = self.sketch.parentComponent.parentDesign + self.design.activeOccurrence = None + # The local sketch X,Y axes point along model Y,Z at an offset origin. + 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) + self.assertEqual(self.t.plane_basis, ((5, 6, 7), (0, 1, 0), (0, 0, 1), (1, 0, 0))) + self.assertEqual(x.setManipulator.call_args.args[0].asArray(), (5, 7, 9)) + self.assertEqual(y.setManipulator.call_args.args[0].asArray(), (5, 7, 9)) + self.assertEqual(angle.setManipulator.call_args.args[0].asArray(), (5, 7, 9)) + self.assertEqual(angle.setManipulator.call_args.args[1].asArray(), (0, 1, 0)) + self.assertEqual(angle.setManipulator.call_args.args[2].asArray(), (0, 0, 1)) + self.assertTrue(all(f.isVisible and f.isEnabled for f in (x, y, angle))) + + def test_fusion_resets_first_angle_glyph_to_global_origin(self): + angle = self.t.fields[2] + angle.manipulatorOrigin = Coordinates(0, 0, 0) + angle.setManipulator.reset_mock() + self.t.check_angle_origin() + expected = angle.setManipulator.call_args.args[0] + self.assertEqual(expected.asArray(), (5, 7, 9)) + angle.manipulatorOrigin = expected + self.t.check_angle_origin() + self.t.check_angle_origin() + angle.setManipulator.assert_called_once() + + def test_translating_one_axis_updates_other_handles_and_preserves_input_expression(self): + x, y, angle, _ = self.t.fields + x.value = 1.5 + self.assertTrue(self.t.changed('offsetX')) + self.assertEqual(self.t.values(), (15., 0., 0., 1.)) + x.setManipulator.assert_called_once() # No reset during its own drag. + self.assertEqual(y.setManipulator.call_args.args[0].asArray(), (5, 8.5, 9)) + self.assertEqual(angle.setManipulator.call_args.args[0].asArray(), (5, 8.5, 9)) + y.value = -.4 + self.assertTrue(self.t.read_drag()) + self.assertEqual(x.setManipulator.call_args.args[0].asArray(), (5, 7, 8.6)) + self.assertEqual(angle.setManipulator.call_args.args[0].asArray(), (5, 8.5, 8.6)) + self.assertFalse(self.t.read_drag()) + angle.value = math.radians(210) + self.assertTrue(self.t.changed('rotateSVG')) + self.assertEqual(self.t.values(), (15., -4., angle.value, 1.)) + + def test_scale_field_after_move_preserves_translated_rotation_center(self): + x, y, angle, scale = self.t.fields + x.value, y.value, angle.value = 1.5, -.4, .2 + self.assertTrue(self.t.read_drag()) + angle = self.t.fields[2] + angle.setManipulator.reset_mock() + scale.value = 2. + self.assertTrue(self.t.changed('scaleSVG')) + angle.setManipulator.assert_not_called() + self.assertEqual(self.t.values(), (15., -4., .2, 2.)) + self.assertFalse(self.t.read_drag()) + scale.value = 0. + self.assertFalse(self.t.read_drag()) + with self.assertRaisesRegex(ValueError, 'positive scale'): + self.t.values() + + def test_same_plane_reuses_controls_and_occurrence_basis_survives_scratch_sketch(self): + x = self.t.fields[0] + self.t.position(self.sketch, (10, 20)) + x.setManipulator.assert_called_once() + self.t.hide() + self.assertFalse(self.t.read_drag()) + self.design.activeOccurrence = SimpleNamespace(component=self.sketch.parentComponent) + proxy = self.sketch.createForAssemblyContext.return_value + proxy.sketchToModelSpace.side_effect = lambda p: Coordinates(8 + p.x, 12 + p.y, 14) + self.t.position(self.sketch, (20, 10)) + self.assertEqual(self.t.plane_basis[0], (8, 12, 14)) + self.assertEqual(x.setManipulator.call_args.args[0].asArray(), (10, 13, 14)) + self.assertEqual(self.command_inputs.addDistanceValueCommandInput.call_count, 2) + self.command_inputs.addAngleValueCommandInput.assert_called_once() + + def test_invalid_expression_is_not_propagated_to_handles(self): + self.t.fields[0].isValidExpression = False + self.assertFalse(self.t.changed('offsetX')) + with self.assertRaisesRegex(ValueError, 'valid Transform'): + self.t.values() + + +class TriadTests(unittest.TestCase): + def setUp(self): + module = load_dialog() + sdk = module.adsk.core + self.enterContext(patch.object(sdk.Point3D, 'create', side_effect=Coordinates)) + self.enterContext(patch.object(sdk.Vector3D, 'create', side_effect=Coordinates)) + self.enterContext(patch.object(sdk.Matrix3D, 'create', side_effect=self.matrix)) + self.enterContext(patch.object(sdk, 'TriadChanges', SimpleNamespace(TriadChangeXYScale=14))) + self.t = module.TriadControls(Mock()) + self.t.create_fields() + self.t.triad.id = 'placementTransform' + self.t.triad.isValidExpressions = True + self.t.triad.lastChangeMade = 0 + self.sketch = Mock(assemblyContext=None) + self.sketch.parentComponent.parentDesign.activeOccurrence = None + self.sketch.sketchToModelSpace.side_effect = lambda point: Coordinates(5, 6 + point.x, 7 + point.y) + + @staticmethod + def matrix(): + matrix = Mock() + + def set_basis(*basis): + matrix.getAsCoordinateSystem.return_value = basis + return True + + matrix.setWithCoordinateSystem.side_effect = set_basis + return matrix + + def test_native_control_is_hidden_until_queued_position_is_applied(self): + triad = self.t.triad + triad.hideAll.assert_called_once_with() + self.assertTrue(triad.isXYPlaneTranslationVisible) + self.assertTrue(triad.isXYPlaneScalingVisible) + self.assertFalse(triad.isVisible) + self.assertFalse(triad.isEnabled) + self.assertTrue(self.t.position(self.sketch, (10, 20))) + self.assertFalse(triad.isVisible) + self.assertTrue(self.t.apply_position()) + origin, vx, vy, _ = triad.transform.getAsCoordinateSystem() + self.assertEqual(origin.asArray(), (5, 7, 9)) + self.assertEqual(vx.asArray(), (0, 1, 0)) + self.assertEqual(vy.asArray(), (0, 0, 1)) + self.assertTrue(triad.isVisible) + self.assertEqual(self.t.values(), (0, 0, 0, 1)) + self.t.hide() + self.assertFalse(triad.isVisible) + + def test_native_matrix_motion_preserves_scale_and_can_reanchor(self): + triad = self.t.triad + self.t.position(self.sketch, (10, 20)) + self.t.apply_position() + triad.xYPlaneScaleFactor = 1.5 + triad.lastChangeMade = 14 + self.assertTrue(self.t.changed(triad.id)) + self.assertEqual(self.t.values(), (0, 0, 0, 1.5)) + + triad.lastChangeMade = 4 + triad.xYPlaneScaleFactor = 1. + pose = triad.transform + pose.setWithCoordinateSystem(Coordinates(5, 8.5, 8.6), Coordinates(0, 0, 1), + Coordinates(0, -1, 0), Coordinates(1, 0, 0)) + self.assertTrue(self.t.changed(triad.id)) + x, y, angle, scale = self.t.values() + self.assertAlmostEqual(x, 15) + self.assertAlmostEqual(y, -4) + self.assertAlmostEqual(angle, math.pi / 2) + self.assertEqual(scale, 1.5) + self.assertFalse(self.t.read_drag()) + + self.assertTrue(self.t.position(self.sketch, (20, 30))) + 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_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() + 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.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') 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_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)) diff --git a/tests/test_svg_geometry.py b/tests/test_svg_geometry.py new file mode 100644 index 0000000..3257123 --- /dev/null +++ b/tests/test_svg_geometry.py @@ -0,0 +1,239 @@ +"""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, fit_anchors, normalized_svg, placement, placement_delta, 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_width_height_then_uniform_scale_keep_rotated_artwork_anchor(self): + doc = document('width="60mm" height="40mm"') + for frame, mode, size in ( + (None, 'original', (30, 10)), + ((0, 0, 100, 50), 'fit', (90, 30)), + ((0, 0, 100, 50), 'stretch', (90, 40)), + ((0, 0, 100, 50), 'original', (30, 10)), + ): + with self.subTest(frame=frame, mode=mode): + options = dict(bounds=(4, 7, 34, 17), inset_mm=5, x_mm=9, y_mm=-3, rotation=.4) + baseline = placement(doc, frame, mode, 'top-right', **options) + target = placement(doc, frame, mode, 'top-right', **options, + width_factor=.5, height_factor=3, scale=2) + left, bottom, right, top = target.selected_box + self.assertAlmostEqual(right - left, size[0]) + self.assertAlmostEqual(top - bottom, 6 * size[1]) + self.assertEqual(target.pivot, baseline.pivot) + for actual, expected in zip(target.outline[2], baseline.pivot): + self.assertAlmostEqual(actual, expected) + + def test_independent_dimensions_require_positive_finite_factors(self): + doc = document('width="50mm" height="20mm"') + for key in ('width_factor', 'height_factor'): + for value in (0, -1, float('nan'), float('inf'), 1e308): + with self.subTest(key=key, value=value), self.assertRaises(ValueError): + placement(doc, None, **{key: value}) + + 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_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"', + '') + 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))