Announcements
Attention for Customers without Multi-Factor Authentication or Single Sign-On - OTP Verification rolls out April 2025. Read all about it here.

API to select all text on Skech

pedro_babo
Advocate

API to select all text on Skech

pedro_babo
Advocate
Advocate

I'm trying to get all the text on a sketch named “inscricao” on a selection set.

The code is

import adsk.core, adsk.fusion, adsk.cam, traceback

 

def run(context):

    ui = None

    try:

        app = adsk.core.Application.get()

        ui  = app.userInterface

        doc = app.activeDocument

        selecttext = ui.activeSelections

        design = app.activeProduct

        components = design.rootComponent.occurrences

        i = components.count

        # limpa selecção.

        selecttext.clear()

        # mostra componentes ja existentes

        if i > 0 :

            for j in range(i) :

                components.item(j).isLightBulbOn = True #mostra Componente

                componente=components.item(j)

                elemento = componente.component

                sk = elemento.sketches.itemByName('inscricao')

                alltexts=sk.sketchTexts

                for text in alltexts:

                    ui.activeSelections.add(text)

               

        ui.messageBox('selecionado texto')

        cmd = ui.commandDefinitions.itemById('CreateSelectionGroupCmd')

        cmd.execute()

 

the error is:

Failed:

Traceback (most recent call last):

File "C:/Users/Pedro/AppData/Roaming/Autodesk/Autodesk Fusion 360/API/Scripts/SelectText/SelectAllTXT/SelectAllTXT.py", line 27, in run

ui.activeSelections.add(text)

File "C:/Users/Pedro/AppData/Local/Autodesk/webdeploy/production/50d1a2b00ac928c7781cbca6551e586a5384d498/Api/Python/packages\adsk\core.py", line 14924, in add

return _core.Selections_add(self, entity)

RuntimeError: 3 : invalid argument entity

 

why active selection is not working on this case?

0 Likes
Reply
Accepted solutions (1)
660 Views
8 Replies
Replies (8)

BrianEkins
Mentor
Mentor

Unfortunately, this is not currently possible.  It should be but there is something missing in the API.  There is a problem in your program that you're getting the sketch text in the context of the component where it needs to be in the context of the root component, which means you would use the createForAssemblyContext method to define the occurrence that you want the text to be in the context of. However, the SketchText object is missing the createForAssemblyContext method.  This is a known issue and is hopefully fixed soon.

 

To get a better understanding of what I'm talking about you should read this topic in the API User Manual.

https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-88A4DB43-CFDD-4CFF-B124-7EE67915A07A

---------------------------------------------------------------
Brian Ekins
Inventor and Fusion 360 API Expert
Website/Blog: https://EkinsSolutions.com
0 Likes

pedro_babo
Advocate
Advocate
Hi Brian many thanks.

Let’s keep this has it gets possible to do with the API.
0 Likes

kandennti
Mentor
Mentor

Hi @pedro_babo .

 

I tried it and was able to make it.

 

# Fusion360API Python script

import traceback
import adsk.fusion
import adsk.core

def run(context):
    ui = adsk.core.UserInterface.cast(None)
    try:
        app: adsk.core.Application = adsk.core.Application.get()
        ui = app.userInterface
        des: adsk.fusion.Design = app.activeProduct
        root: adsk.fusion.Component = des.rootComponent

        occs: adsk.fusion.Occurrences = root.occurrences
        if occs.count < 1:
            return

        sels: adsk.core.Selections = ui.activeSelections
        sels.clear()

        occ: adsk.fusion.Occurrence
        for occ in occs:
            comp: adsk.fusion.Component = occ.component
            skts: adsk.fusion.Sketches = comp.sketches
            skt = skts.itemByName('inscricao')
            if not skt:
                continue

            # get proxy
            proxy: adsk.fusion.Sketch = skt.createForAssemblyContext(occ)

            sktTxts: adsk.fusion.SketchTexts = proxy.sketchTexts
            if sktTxts.count < 1:
                continue

            for sktTxt in sktTxts:
                sels.add(sktTxt)

        if sels.count < 1:
            return

        cmdDefs: adsk.core.CommandDefinitions = ui.commandDefinitions
        cmdDef: adsk.core.CommandDefinition = cmdDefs.itemById('CreateSelectionGroupCmd')
        if cmdDef:
            cmdDef.execute()

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

0 Likes

BrianEkins
Mentor
Mentor

This sample is selecting the sketch. What he needs is the ability to select the text in the sketch.  SketchText is missing the createForAssemblyContext method, so it's not currently possible.

---------------------------------------------------------------
Brian Ekins
Inventor and Fusion 360 API Expert
Website/Blog: https://EkinsSolutions.com
1 Like

kandennti
Mentor
Mentor
Accepted solution

@BrianEkins .

 

Thanks for the reply.

I made another sample.
Please forgive me for using some TextCommands, but I can't find any other way.

# Fusion360API Python script

import traceback
import adsk.fusion
import adsk.core
import json

def run(context):
    ui = adsk.core.UserInterface.cast(None)
    try:
        app: adsk.core.Application = adsk.core.Application.get()
        ui = app.userInterface
        app.documents.add(
            adsk.core.DocumentTypes.FusionDesignDocumentType
        )
        des: adsk.fusion.Design = app.activeProduct
        des.designType = adsk.fusion.DesignTypes.ParametricDesignType
        root: adsk.fusion.Component = des.rootComponent

        # create Occurrence SketchText
        initOccSketchText(root, 'inscricao')

        # create SelectionSets
        initSelectionSets(root, 'inscricao')

        # select count check
        app.log(u'TextCommandWindow.Clear')
        sels: adsk.core.Selections = ui.activeSelections
        sels.clear()
        app.log(f'select count : {sels.count}')

        # Reselection using SelectionSets
        execSelectionSets()
        app.log(f'select count : {sels.count}')

        # Dump selected items
        for sel in sels:
            sktTxt = adsk.fusion.SketchText.cast(sel.entity)
            if not sktTxt:
                continue

            msg = f'Text:{sktTxt.text}  '
            msg += f'FontName:{sktTxt.fontName}  '
            msg += f'Height:{sktTxt.height}'
            
            app.log(msg)

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

def execSelectionSets():
    app: adsk.core.Application = adsk.core.Application.get()

    res = app.executeTextCommand(u'Managed.Child 22 0')
    infoJson = json.loads(res)
    txtCmd = f"Selections.Add 57:3:22:{infoJson['entityId']}"

    app.executeTextCommand(txtCmd)
    app.executeTextCommand(u'NuComponents.SelectSelectionGroupCmd')


def initSelectionSets(
    comp: adsk.fusion.Component,
    sktName: str):

    occs: adsk.fusion.Occurrences = comp.occurrences
    if occs.count < 1:
        return

    app: adsk.core.Application = adsk.core.Application.get()
    ui = app.userInterface
    sels: adsk.core.Selections = ui.activeSelections
    sels.clear()

    occ: adsk.fusion.Occurrence
    for occ in occs:
        comp: adsk.fusion.Component = occ.component
        skts: adsk.fusion.Sketches = comp.sketches
        skt = skts.itemByName(sktName)
        if not skt:
            continue

        # get proxy
        proxy: adsk.fusion.Sketch = skt.createForAssemblyContext(occ)

        sktTxts: adsk.fusion.SketchTexts = proxy.sketchTexts
        if sktTxts.count < 1:
            continue

        for sktTxt in sktTxts:
            sels.add(sktTxt)

    if sels.count < 1:
        return

    # cmdDefs: adsk.core.CommandDefinitions = ui.commandDefinitions
    # cmdDef: adsk.core.CommandDefinition = cmdDefs.itemById('CreateSelectionGroupCmd')
    # if cmdDef:
    #     cmdDef.execute()

    app.executeTextCommand(u'NuComponents.CreateSelectionGroupCmd')


def initOccSketchText(
    comp: adsk.fusion.Component,
    sktName: str):

    txtLst = [
        'hoge',
        'piyo'
    ]

    for idx, txt in enumerate(txtLst):
        newOcc: adsk.fusion.Occurrence = comp.occurrences.addNewComponent(
            adsk.core.Matrix3D.create()
        )
        newComp: adsk.fusion.Component = newOcc.component
        skt: adsk.fusion.Sketch = newComp.sketches.add(
            newComp.xYConstructionPlane
        )
        skt.name = sktName

        sktTxts: adsk.fusion.SketchTexts = skt.sketchTexts
        sktTxtIpt: adsk.fusion.SketchTextInput = skt.sketchTexts.createInput2(
            txt,
            2.0
        )

        sktTxtIpt.setAsMultiLine(
            adsk.core.Point3D.create(0, 0 + 10 * idx, 0),
            adsk.core.Point3D.create(10, 5 + 10 * idx, 0),
            adsk.core.HorizontalAlignments.LeftHorizontalAlignment,
            adsk.core.VerticalAlignments.TopVerticalAlignment,
            0
        )
        sktTxts.add(sktTxtIpt)

        sktLines: adsk.fusion.SketchLines = skt.sketchCurves.sketchLines
        sktLines.addCenterPointRectangle(
            adsk.core.Point3D.create(20, 2.5 + 10 * idx, 0),
            adsk.core.Point3D.create(25, 5 + 10 * idx, 0),
        )

 

I feel that I am able to create a selection set of sketch text only, because after the script is executed, the extrude command extrudes only the text.

0 Likes

pedro_babo
Advocate
Advocate

hi @kandennti and @BrianEkins 

 

Many thanks i was able to create the selection set on Design. do you guis have any idia how to do it from Manufacturing?

0 Likes

kandennti
Mentor
Mentor

@pedro_babo .

 

We won't know without looking for it, but the easiest and surest way is to switch workspaces and let it handle it.

# Fusion360API Python script

import traceback
import adsk.cam
import adsk.fusion
import adsk.core

def run(context):
    ui: adsk.core.UserInterface = None
    try:
        app: adsk.core.Application = adsk.core.Application.get()
        ui = app.userInterface

        if ui.activeWorkspace.id != 'FusionSolidEnvironment':
            ws: adsk.core.Workspace = ui.workspaces.itemById(
                'FusionSolidEnvironment'
                )
            ws.activate()

        # Perform necessary processing.

        if ui.activeWorkspace.id != 'CAMEnvironment':
            ws: adsk.core.Workspace = ui.workspaces.itemById(
                'CAMEnvironment'
                )
            ws.activate()

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
0 Likes

pedro_babo
Advocate
Advocate
Many thanks @kandennti I will try this
0 Likes