Script to autofavorite named model parameters

Anonymous

Script to autofavorite named model parameters

Anonymous
Not applicable

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? 

1 Like
Reply
Accepted solutions (1)
2,304 Views
13 Replies
Replies (13)

Olle_Eriksson
Contributor
Contributor

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

0 Likes

kandennti
Mentor
Mentor

Hi @Anonymous .

 

'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()))
0 Likes

kandennti
Mentor
Mentor

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
1 Like

Anonymous
Not applicable

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?

0 Likes

kandennti
Mentor
Mentor

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

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

 

1 Like

prainsberry
Autodesk
Autodesk

Hello @Anonymous 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
2 Likes

Anonymous
Not applicable

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

0 Likes

Anonymous
Not applicable

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?

 

0 Likes

prainsberry
Autodesk
Autodesk
Accepted solution

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
5 Likes

Anonymous
Not applicable

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

0 Likes

Olle_Eriksson
Contributor
Contributor

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

0 Likes

ritste20
Collaborator
Collaborator

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
0 Likes

prainsberry
Autodesk
Autodesk

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
2 Likes