Community
Fusion API and Scripts
Got a new add-in to share? Need something specialized to be scripted? Ask questions or share what you’ve discovered with the community.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Script to autofavorite named model parameters

13 REPLIES 13
SOLVED
Reply
Message 1 of 14
jjurban55
1726 Views, 13 Replies

Script to autofavorite named model parameters

It's really nice that model parameters such as sketch dimensions, extrude distances etc. can be named on the fly by typing a new name, the equal sign, and then the desired value.  However to then get these named model parameters to show in a popup list when typing a parameter in, it must be dug up and favorited in the Change Parameters tool.  I was just curious if there might be any scripting possibility to automatically favorite all custom named model parameters? 

Labels (1)
13 REPLIES 13
Message 2 of 14
Olle_Eriksson
in reply to: jjurban55

I just thought exact the same thing. I have no experience in making custom scripts for fusion but will follow this thread with interest. 

Message 3 of 14
kandennti
in reply to: jjurban55

Hi @jjurban55 .

 

'Parameter.isFavorite' is a read/write property.

https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-2ab75499-ce0d-4744-b6c5-e5a6fb4ac6cc 

import adsk.core, adsk.fusion, traceback

_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)

def run(context):
    try:
        global _app, _ui
        _app = adsk.core.Application.get()
        _ui = _app.userInterface
        des  :adsk.fusion.Design = _app.activeProduct

        # init UserParamete
        length = adsk.core.ValueInput.createByString("1 cm")
        prm = des.userParameters.add('test', length, 'cm', 'hoge')

        # Favorite
        prm.isFavorite = True

        _ui.messageBox('Done')
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
Message 4 of 14
kandennti
in reply to: kandennti

Sorry, I misunderstood.

 

import adsk.core, adsk.fusion, traceback

_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)

def run(context):
    try:
        global _app, _ui
        _app = adsk.core.Application.get()
        _ui = _app.userInterface

        # get ModelParameter
        prm = getModelParameter_itemByName('test')

        # Favorite
        if prm:
            prm.isFavorite = True

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

def getModelParameter_itemByName(
    targetName :str) -> adsk.fusion.ModelParameter:

    des  :adsk.fusion.Design = _app.activeProduct

    prm = adsk.fusion.ModelParameter.cast(None)
    for comp in des.allComponents:
        prm = comp.modelParameters.itemByName(targetName)
        if prm:
            return prm
    
    return prm
Message 5 of 14
jjurban55
in reply to: kandennti

Thanks @kandennti for the script!  I've never tried scripting before with Fusion and don't know python, but pasted your script into a newly created script in Visual Studio, saved it then ran it in Fusion.  After a little while a dialog box appeared that said "Done" and click ok.  However after I tried naming a new system variable, it does not appear that it automatically gets favorited 😞  Any suggestions?

Message 6 of 14
kandennti
in reply to: jjurban55

Try making the 'test' part the name of the desired parameter.

・・・
        # get ModelParameter
        prm = getModelParameter_itemByName('test')
・・・

 

Message 7 of 14
prainsberry
in reply to: jjurban55

Hello @jjurban55 I think maybe what you were looking for was a script that would determine if the parameter had ANY user defined name?  Here is another example where I assume any name that is not a "d" followed by an integer is something custom and then will add it as a favorite.  Also FYI @Olle_Eriksson .

Nice script though @kandennti !  

# Author - Patrick Rainsberry
# Description - Simple script to make favorites out of named parameters

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

def run(context):
    ui = None

    # This is not nnecessary but makes code complete work better
    app: adsk.core.Application
    document: adsk.fusion.FusionDocument
    parameter: adsk.fusion.Parameter
    
    try:
        
        # Get various application objects
        app = adsk.core.Application.get()
        ui  = app.userInterface
        document = app.activeDocument
        design = document.design
        all_params = design.allParameters
        
        # Lets count the number of favorites added
        count = 0

        # Iterate over all parameters in the design 
        # Note: Intentionally verbose to make it easier to follow.
        for parameter in all_params:
            is_named_parameter = True
            
            # Check if first character is not a "d"
            if parameter.name[0] == 'd':
                # Check if the rest of the name is not a positive integer
                if parameter.name[1:].isdigit():
                    is_named_parameter = False
            
            # Check if it has a user defined name
            if is_named_parameter:
                
                # Only increment count if it wasn't already a favorite
                if not parameter.isFavorite:
                    count += 1
                
                # Set the parameter as a favorite
                parameter.isFavorite = True              

        # Feedback message, uses Python Format String
        ui.messageBox(f'All done! {count} parameters added to favorites')
    
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


Patrick Rainsberry
Developer Advocate, Fusion 360
Message 8 of 14
jjurban55
in reply to: prainsberry

Thanks a lot, I will try this in the next day or so when I am at my computer.

Message 9 of 14
jjurban55
in reply to: prainsberry

Thanks @prainsberry the script works great!  My only last question is if it might be possible to somehow make this an Add-on continuously running in the background?  Perhaps it could detect when the model parameter count changed?

 

Message 10 of 14
prainsberry
in reply to: jjurban55

Here is a quick way to do that.  Basically it will check after every command.  It's a little over the top in how often it would run, but it is such a quick execution you probably won't really notice it.   Just create a new addin and paste this in:

#Author-Patrick Rainsberry
#Description-Continuously monitors Model Parameters for changes to name and then adds parameter to favorites.  

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

# Global variable used to maintain a reference to all event handlers.
handlers = []


def check_favorites():
    # This is not necessary but makes code complete work better
    app: adsk.core.Application
    document: adsk.fusion.FusionDocument
    parameter: adsk.fusion.Parameter

    # Get various application objects
    app = adsk.core.Application.get()
    document = app.activeDocument
    design = document.design
    all_params = design.allParameters

    # Lets count the number of favorites added
    count = 0

    # Iterate over all parameters in the design
    # Note: Intentionally verbose to make it easier to follow.
    for parameter in all_params:
        is_named_parameter = True

        # Check if first character is not a "d"
        if parameter.name[0] == 'd':
            # Check if the rest of the name is not a positive integer
            if parameter.name[1:].isdigit():
                is_named_parameter = False

        # Check if it has a user defined name
        if is_named_parameter:

            # Only increment count if it wasn't already a favorite
            if not parameter.isFavorite:
                count += 1

            # Set the parameter as a favorite
            parameter.isFavorite = True


# Event handler for the commandTerminated event.
class MyCommandTerminatedHandler(adsk.core.ApplicationCommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        event_args = adsk.core.ApplicationCommandEventArgs.cast(args)

        # Will check favorites after every command completes for anything except the select command.
        if event_args.commandId != "SelectCommand":
            check_favorites()


def run(context):
    global handlers
    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        onCommandTerminated = MyCommandTerminatedHandler()
        ui.commandTerminated.add(onCommandTerminated)
        handlers.append(onCommandTerminated)

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


def stop(context):
    global handlers
    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        for handler in handlers:
            ui.commandTerminated.remove(handler)
        ui.messageBox('Stopped Favorites addin')

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


Patrick Rainsberry
Developer Advocate, Fusion 360
Message 11 of 14
jjurban55
in reply to: prainsberry

Works great, thank you!  This Add-in should be made more widely available. 

Message 12 of 14
Olle_Eriksson
in reply to: prainsberry

This is really great! Makes the new feature of naming parameters as you dimension actually useful. Greatly appreciated!

Message 13 of 14
ritste20
in reply to: prainsberry

Your script seems to work perfectly so far as an add-in. I'm looking forward to using it more with the direct dimension naming.

 

Thanks @prainsberry 

 

Steve Ritter
Manufacturing Engineer

AutoCAD/Draftsight
Inventor/Solidworks
Fusion 360
Message 14 of 14
prainsberry
in reply to: ritste20

I was just made aware of an issue with this that caused the file to become "edited" constantly.   The issue is that regardless of whether the named parameter was already a favorite I "set" the flag anyway.  I think that is essentially telling Fusion that something "changed" in the file.  I just made one tiny change to the code and I think it should solve the problem.   Basically moving the last line of the check favorites function into the if statement.   You may want to update your code if you are using this.  Here is the updated version:

#Author-Patrick Rainsberry
#Description-Continuously monitors Model Parameters for changes to name and then adds parameter to favorites.  

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

# Global variable used to maintain a reference to all event handlers.
handlers = []


def check_favorites():
    # This is not necessary but makes code complete work better
    app: adsk.core.Application
    document: adsk.fusion.FusionDocument
    parameter: adsk.fusion.Parameter

    # Get various application objects
    app = adsk.core.Application.get()
    document = app.activeDocument
    design = document.design
    all_params = design.allParameters

    # Lets count the number of favorites added
    count = 0

    # Iterate over all parameters in the design
    # Note: Intentionally verbose to make it easier to follow.
    for parameter in all_params:
        is_named_parameter = True

        # Check if first character is not a "d"
        if parameter.name[0] == 'd':
            # Check if the rest of the name is not a positive integer
            if parameter.name[1:].isdigit():
                is_named_parameter = False

        # Check if it has a user defined name
        if is_named_parameter:

            # Only increment count if it wasn't already a favorite
            if not parameter.isFavorite:
                count += 1

                # Set the parameter as a favorite
                parameter.isFavorite = True


# Event handler for the commandTerminated event.
class MyCommandTerminatedHandler(adsk.core.ApplicationCommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        event_args = adsk.core.ApplicationCommandEventArgs.cast(args)

        # Will check favorites after every command completes for anything except the select command.
        if event_args.commandId != "SelectCommand":
            check_favorites()


def run(context):
    global handlers
    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        onCommandTerminated = MyCommandTerminatedHandler()
        ui.commandTerminated.add(onCommandTerminated)
        handlers.append(onCommandTerminated)

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


def stop(context):
    global handlers
    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        for handler in handlers:
            ui.commandTerminated.remove(handler)
        ui.messageBox('Stopped Favorites addin')

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

 

 



Patrick Rainsberry
Developer Advocate, Fusion 360

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report