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 @@

