Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .fusion-addin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"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.",
"description": "Place SVGs and trace photos, logos and drawings into closed Autodesk Fusion sketch outlines.",
"initialized": true
}
9 changes: 8 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
os: [ubuntu-latest, macos-26-intel, windows-latest]
env:
ADDIN_NAME: ${{ needs.project.outputs.product }}
PACKAGE_VERSION: ${{ needs.version.outputs.version || '0.1.0' }}
Expand All @@ -92,6 +92,9 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.12'
- name: Install Linux image decoder for offline tracing tests
if: runner.os == 'Linux'
run: python -m pip install Pillow==13.0.0
- name: Compile without Autodesk Fusion
shell: bash
run: python -m compileall -q "$ADDIN_NAME" scripts tests
Expand All @@ -100,6 +103,10 @@ jobs:
- name: Generate reproducible Fusion ZIP and SHA-256
shell: bash
run: python scripts/build.py --version "$PACKAGE_VERSION" --allow-template
- name: Trace PNG and JPEG using the extracted product
if: needs.project.outputs.initialized == 'true'
shell: bash
run: python scripts/check_trace_package.py --archive "dist/${ADDIN_NAME}-${PACKAGE_VERSION}.zip"
- name: Validate package and embedded manifest
uses: 4FusionLab/.github/.github/actions/verify-archive@ad9d60ba4aabc494b4f2c85d6c566a50ca423751
with:
Expand Down
2 changes: 1 addition & 1 deletion InsertTo/InsertTo.manifest
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"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."
"": "Place SVGs and trace photos, logos and drawings into closed Autodesk Fusion sketch outlines."
},
"version": "0.1.0",
"runOnStartup": true,
Expand Down
116 changes: 100 additions & 16 deletions InsertTo/InsertTo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,78 @@
from pathlib import Path

import adsk.core
import adsk.fusion

from . import config, dialog, frame_link


_RESOURCES = Path(__file__).parent / 'resources'
_MENU_ID = '4FusionLab_InsertTo_SmartInsert'
_menu = None
_definition = None
_created = None
_definitions = []
_created = []
_sessions = []
_context = None


def _editing_sketch(app):
sketch = adsk.fusion.Sketch.cast(app.activeEditObject) if app.activeDocument else None
return bool(sketch and sketch.isValid)


class _SketchContext:
"""Refresh after Fusion finishes switching edit objects, and guard each launch immediately."""

event_id = _MENU_ID + '_UpdateContext'

def __init__(self, app):
self.app = app
self.listeners = []
self.pending = False
self.event = None

def start(self):
ui = self.app.userInterface
self.event = self.app.registerCustomEvent(self.event_id)
for event, base, callback in (
(self.event, adsk.core.CustomEventHandler, self.refresh),
(ui.commandStarting, adsk.core.ApplicationCommandEventHandler, self.starting),
(ui.commandCreated, adsk.core.ApplicationCommandEventHandler, self.schedule),
(ui.commandTerminated, adsk.core.ApplicationCommandEventHandler, self.schedule),
(ui.workspaceActivated, adsk.core.WorkspaceEventHandler, self.schedule),
(self.app.documentActivated, adsk.core.DocumentEventHandler, self.schedule),
(self.app.documentClosed, adsk.core.DocumentEventHandler, self.schedule),
):
self.listeners.append((event, dialog._listen(event, base, callback)))
self.refresh()

def schedule(self, args):
if not self.pending:
self.pending = self.app.fireCustomEvent(self.event_id)

def starting(self, args):
if args.commandId in (config.COMMAND_ID, config.TRACE_COMMAND_ID):
if not _editing_sketch(self.app):
args.isCanceled = True

def refresh(self, args=None):
self.pending = False
editing = _editing_sketch(self.app)
if _menu.isVisible != editing:
_menu.isVisible = editing
for definition in _definitions:
control = definition.controlDefinition
if control.isEnabled != editing:
control.isEnabled = editing
if control.isVisible != editing:
control.isVisible = editing

def close(self):
for event, handler in reversed(self.listeners):
event.remove(handler)
self.listeners.clear()
if self.event:
self.app.unregisterCustomEvent(self.event_id)


class _Destroyed(adsk.core.CommandEventHandler):
Expand All @@ -25,9 +87,15 @@ def notify(self, args):


class _Created(adsk.core.CommandCreatedEventHandler):
def __init__(self, attach):
super().__init__()
self.attach = attach

def notify(self, args):
try:
session = dialog.attach(args.command)
if not _editing_sketch(adsk.core.Application.get()):
return
session = self.attach(args.command)
destroyed = _Destroyed()
args.command.destroy.add(destroyed)
_sessions.append((session, destroyed))
Expand All @@ -38,43 +106,59 @@ def notify(self, args):


def run(context):
global _menu, _created, _definition
global _menu, _context
if _menu and _menu.isValid:
return

ui = adsk.core.Application.get().userInterface
app = adsk.core.Application.get()
ui = app.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)
from . import trace_dialog

_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())
for identifier, label, description, resources, attach in (
(config.COMMAND_ID, 'SVG', config.DESCRIPTION, str(_RESOURCES / 'svg'), dialog.attach),
(config.TRACE_COMMAND_ID, 'Trace Image', 'Trace a PNG or JPEG as closed sketch curves.',
'', trace_dialog.TraceDialog),
):
definition = ui.commandDefinitions.addButtonDefinition(identifier, label, description, resources)
_definitions.append(definition)
created = _Created(attach)
_created.append(created)
definition.commandCreated.add(created)
_menu.controls.addCommand(definition)
_context = _SketchContext(app)
_context.start()
frame_link.install(app)
except Exception:
stop(context)
raise


def stop(context):
global _menu, _created, _definition
global _menu, _context
try:
if _context is not None:
_context.close()
_context = None
frame_link.uninstall()
if _menu and _menu.isValid:
_menu.deleteMe()
if _definition and _definition.isValid:
_definition.deleteMe()
for definition in reversed(_definitions):
if definition.isValid:
definition.deleteMe()
finally:
_menu = _created = _definition = None
_menu = None
_definitions.clear()
_created.clear()
for session, _ in _sessions:
session.close()
_sessions.clear()
1 change: 1 addition & 0 deletions InsertTo/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
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'
TRACE_COMMAND_ID = COMMAND_ID + '_TraceImage'
INITIALIZED = True
48 changes: 30 additions & 18 deletions InsertTo/dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ def notify(self, args):


class _Dialog:
file_id = 'svgFile'
file_label = 'SVG file'
file_prompt = 'Choose an SVG file.'
frame_tooltip = 'Select a profile or closed contour to fit the SVG to its frame.'

def __init__(self, command):
self.app = adsk.core.Application.get()
self.design = adsk.fusion.Design.cast(self.app.activeProduct)
Expand All @@ -63,7 +68,6 @@ def __init__(self, command):
self.source_curves = None
self.file_error = ''
self.preview_error = ''

self.graphics = None
self.graphics_key = None
self.graphics_pivot = None
Expand All @@ -72,7 +76,7 @@ def __init__(self, command):
command.isExecutedWhenPreEmpted = False
command.okButtonText = 'Insert'
inputs = command.commandInputs
self.browse = inputs.addBoolValueInput('svgFile', 'SVG file', False, '', False)
self.browse = inputs.addBoolValueInput(self.file_id, self.file_label, False, '', False)
self.browse.text = 'Choose file…'
self.plane = inputs.addSelectionInput(
'targetPlane', 'Sketch plane', 'Select a construction plane or a planar face'
Expand All @@ -87,13 +91,8 @@ def __init__(self, command):
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.frame.tooltip = self.frame_tooltip
self._source_options(inputs)
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')
Expand All @@ -105,8 +104,7 @@ def __init__(self, command):
)
self.inset.minimumValue = 0
self.inset.tooltip = 'Apply an equal margin inside all four sides of the frame.'
self.link = inputs.addBoolValueInput('linkFrame', 'Link to frame', True, '', True)
self.link.tooltip = 'Update the inserted curves when the source frame changes.'
self.link = self._link_option(inputs)
if self.link is None:
self.transform = TransformControls(inputs, units)
self.sizes = None
Expand All @@ -120,7 +118,7 @@ def __init__(self, command):
self.status.isFullWidth = True
self._show_target_controls()
self._show_alignment(None)
self._status('Choose an SVG file.')
self._status(self.file_prompt)
self.handlers = [
_listen(command.inputChanged, adsk.core.InputChangedEventHandler, self._changed),
_listen(command.validateInputs, adsk.core.ValidateInputsEventHandler, self._validate),
Expand All @@ -141,6 +139,19 @@ def __init__(self, command):
_listen(command.destroy, adsk.core.CommandEventHandler, self._release_triad_event),
))

def _source_options(self, inputs):
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.'

def _link_option(self, inputs):
link = inputs.addBoolValueInput('linkFrame', 'Link to frame', True, '', True)
link.tooltip = 'Update the inserted curves when the source frame changes.'
return link

def _status(self, message):
if self.status.text != message:
self.status.text = message
Expand Down Expand Up @@ -175,14 +186,14 @@ def _changed(self, args):
if self._mode() == 'original' and self.sizes.changed(changed):
self._move_graphics()
return
if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor',
if changed not in (self.file_id, '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():
if changed == self.file_id and not self._choose_file():
return
if changed in ('frame', 'targetPlane'):
self.bounds = None
Expand Down Expand Up @@ -256,7 +267,8 @@ def _show_target_controls(self):
_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.link is not None:
_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)
Expand All @@ -269,9 +281,9 @@ def _show_alignment(self, fit_options):

def _destination(self):
if self.document is None:
raise ValueError(self.file_error or 'Choose an SVG file.')
raise ValueError(self.file_error or self.file_prompt)
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.')
raise ValueError('Open a Fusion design to insert sketch curves.')
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:
Expand All @@ -296,7 +308,7 @@ def _use_artwork(self):
return self.extent.selectedItem.index == 1

def _needs_artwork_bounds(self):
return self._use_artwork() or not self.frame.selectionCount
return self._use_artwork() or (self.file_id == 'svgFile' and not self.frame.selectionCount)

def _placements(self):
frame = self.bounds if self.frame.selectionCount else None
Expand Down
8 changes: 4 additions & 4 deletions InsertTo/frame_link.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class _RestoreFailed(RuntimeError):


@contextmanager
def _batch_edit(sketch):
def batch_edit(sketch):
"""Solve once while keeping downstream features out of the deferred edit."""
if sketch.isComputeDeferred:
yield
Expand Down Expand Up @@ -136,7 +136,7 @@ def _batch_edit(sketch):
try:
sketch.isComputeDeferred = False
except Exception as error:
raise _RestoreFailed('Fusion could not recompute the linked sketch.') from error
raise _RestoreFailed('Fusion could not recompute the sketch.') from error
finally:
if moved and timeline.markerPosition != marker:
try:
Expand All @@ -157,7 +157,7 @@ def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, in
matrix = _matrix(svg_geometry.Placement(0, 0, doc.width_mm, doc.height_mm), target)
link_id = uuid4().hex
added = []
with _batch_edit(sketch):
with batch_edit(sketch):
splines = sketch.sketchCurves.sketchFixedSplines
index_attr = None
try:
Expand Down Expand Up @@ -253,7 +253,7 @@ def _refresh(attr, record, target, curves):
raise ValueError('Fusion could not transform a linked curve.')
edits.append((curve, original, updated))

with _batch_edit(attr.parent):
with batch_edit(attr.parent):
applied = []
try:
for curve, original, updated in edits:
Expand Down
Loading