fast rename dont work properly

fast rename dont work properly

nubrandao
Collaborator Collaborator
3,672 Views
44 Replies
Message 1 of 45

fast rename dont work properly

nubrandao
Collaborator
Collaborator
# Script zum schnellen umbennen von CAM Operationen
# Bei Rückfragen bitte an M.Toepke wenden
# Marcus.Toepke@gabler-naval.com

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

# Get the application and userInterface
app = adsk.core.Application.get()
ui = app.userInterface
ui_var = app.userInterface

# Get the value of the property.
propertyValue = ui.commandDefinitions

# Get the active product.
cam = adsk.cam.CAM.cast(app.activeProduct)

# Check if anything was returned.
if (cam is None😞
    ui.messageBox('Você deve estar na área de trabalho Concluído (CAM)!')
   
# Get the Setups collection object from the CAM object.
setups = cam.setups

# Get the first Setup object in the CAM product.
setup = setups.item(0)

# Get the Operations collection object that contains all the operations in the setup.
operations = setup.operations

# Get the first operation in the collection.
operation = operations.item(0)

# Get selected Operations
selections = ui.activeSelections
try:
    # print(f'Es sind {selections.count} Operationen ausgewählt!')
    a_selections = selections.asArray()
    if selections.count == 0:
        ui.messageBox('Nenhuma seleção de operação foi feita')
        adsk.terminate()
    if selections.count >= 1:
        # Abfrage Operations Bezeichnungen
        vorgabe = a_selections[0].entity.name
        user_input = ui_var.inputBox("Nome básico da operação", "Qual deve ser o nome básico das operações?", vorgabe)
        if user_input[1]:
            ui.messageBox('Eingabe wurde abgebrochen')
            adsk.terminate()

        if '~' not in user_input[0]:
            number = 1
            for sel_op in a_selections:
                sel_op.entity.name = f'{user_input[0]}_{number}'
                number += 1
               
        if '~(' in user_input[0]:
            # Input Auseinandernehmen und in Liste umformen
            input_list = re.search(r'~(.*)$', user_input[0])
            input_list = input_list[0]
            input_list = input_list.replace('~', '').replace('(', '').replace(')', '')
            input_list = input_list.split(',')
           
            # Zusatzargumente aus user_input entfernen
            extract = re.search(f"(.*?){re.escape('~')}", user_input[0])
            user_input = extract[0]
            user_input = user_input.replace('~', '')
           
            if len(a_selections) == len(input_list):
                count = 0
                for sel_op in a_selections:
                    sel_op.entity.name = f'{user_input}_{input_list[count]}'
                    count += 0
            else:
                ui.messageBox('A lista que você forneceu não corresponde ao número de operações selecionadas! O script terminará agora')
        if '~' in user_input[0]:
            # Input Auseinandernehmen und in Liste umformen
            input_list = re.search(r'~.*$', user_input[0])
            input_list = input_list[0]
            input_list = input_list.replace('~', '')
            input_list = input_list.split(',')
           
            # Zusatzargumente aus user_input entfernen
            extract = re.search(f"(.*?){re.escape('~')}", user_input[0])
            user_input = extract[0]
            user_input = user_input.replace('~', '')
           
            count = 0
            new_number = float(input_list[0])
            add_number = float(input_list[1])
            for sel_op in a_selections:
                if count == 0:
                    sel_op.entity.name = f'{user_input}_{new_number}'
                if count > 0:
                    new_number += add_number
                    sel_op.entity.name = f'{user_input}_{new_number}'
               
                count += 1
               
           
           
except Exception as err:
    if selections.count < 1:
        # error_message = f'Es wurde keine Auswahl getroffen!\nEs wurden {selections.count} operationen ausgewählt'
        ui.messageBox(err)
    if ui:
      ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
   
     

     
   i have copied this script, but there is a problem, 
 
rename everthing but when renumbering, it jumps numbers
 
por example, i input  "MOULD"
 
it appears
 
mould_01
mould_06
mould_02
mould_04
mould_07
mould_03
mould_05
0 Likes
Accepted solutions (4)
3,673 Views
44 Replies
Replies (44)
Message 2 of 45

kandennti
Mentor
Mentor
Accepted solution

Hi @nubrandao -San.

 

I think they are simply processed in the order in which they are selected.

I have fixed it this way.

・・・

            if '~' not in user_input[0]:
                number = 1
                # for sel_op in a_selections:
                #     sel_op.entity.name = f'{user_input[0]}_{number}'
                #     number += 1

                opeLst = [s.entity for s in a_selections]

                if isinstance(opeLst[0], adsk.cam.Operation):
                    setup = opeLst[0].parent

                    for ope in setup.operations:
                        if ope in opeLst:
                            ope.name = f'{user_input[0]}_{number}'
                            number += 1
・・・


The image on the right is the result of executing the script after selecting in the order of the numbers on the left of the image.
1.png

0 Likes
Message 3 of 45

Tomas_V_cz
Advocate
Advocate

 

so the script stopped working after I inserted the new code... I think I put it in a good place (we localized the comments and the output)

# Skript pro rychlé přejmenování CAM operací
# V případě dotazů se obraťte na M.Toepke
# Marcus.Toepke@gabler-naval.com

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

# Získání aplikace a uživatelského rozhraní
app = adsk.core.Application.get()
ui = app.userInterface
ui_var = app.userInterface

# Získání hodnoty vlastnosti.
propertyValue = ui.commandDefinitions

# Získání aktivního produktu.
cam = adsk.cam.CAM.cast(app.activeProduct)

# Kontrola, zda bylo něco vráceno.
if (cam is None):
    ui.messageBox('Musíte být v pracovním prostoru CAM (Fertigen)!')
    
# Získání kolekce nastavení z objektu CAM.
setups = cam.setups

# Získání prvního objektu nastavení v produktu CAM.
setup = setups.item(0)

# Získání kolekce operací, která obsahuje všechny operace v nastavení.
operations = setup.operations

# Získání první operace v kolekci.
operation = operations.item(0)

# Získání vybraných operací
selections = ui.activeSelections
try:
    # print(f'Bylo vybráno {selections.count} operací!')
    a_selections = selections.asArray()
    if selections.count == 0:
        ui.messageBox('Nebyl proveden žádný výběr operací')
        adsk.terminate()
    if selections.count >= 1:
        # Dotaz na názvy operací
        vorgabe = a_selections[0].entity.name
        user_input = ui_var.inputBox("Základní název operace", "Jak má základní název operací znít?", vorgabe)
        if user_input[1]:
            ui.messageBox('Vstup byl zrušen')
            adsk.terminate()

            if '~' not in user_input[0]:
                number = 1
                # for sel_op in a_selections:
                #     sel_op.entity.name = f'{user_input[0]}_{number}'
                #     number += 1

                opeLst = [s.entity for s in a_selections]

                if isinstance(opeLst[0], adsk.cam.Operation):
                    setup = opeLst[0].parent

                    for ope in setup.operations:
                        if ope in opeLst:
                            ope.name = f'{user_input[0]}_{number}'
                            number += 1
                
        if '~(' in user_input[0]:
            # Rozdělení vstupu a převedení do seznamu
            input_list = re.search(r'~(.*)$', user_input[0])
            input_list = input_list[0]
            input_list = input_list.replace('~', '').replace('(', '').replace(')', '')
            input_list = input_list.split(',')
            
            # Odstranění doplňkových argumentů z uživatelského vstupu
            extract = re.search(f"(.*?){re.escape('~')}", user_input[0])
            user_input = extract[0]
            user_input = user_input.replace('~', '')
            
            if len(a_selections) == len(input_list):
                count = 0
                for sel_op in a_selections:
                    sel_op.entity.name = f'{user_input}_{input_list[count]}'
                    count += 1
            else:
                ui.messageBox('Seznam, který jste poskytl, neodpovídá počtu vybraných operací! Skript bude nyní ukončen')
        if '~' in user_input[0]:
            # Rozdělení vstupu a převedení do seznamu
            input_list = re.search(r'~.*$', user_input[0])
            input_list = input_list[0]
            input_list = input_list.replace('~', '')
            input_list = input_list.split(',')
            
            # Odstranění doplňkových argumentů z uživatelského vstupu
            extract = re.search(f"(.*?){re.escape('~')}", user_input[0])
            user_input = extract[0]
            user_input = user_input.replace('~', '')
            
            count = 0
            new_number = float(input_list[0])
            add_number = float(input_list[1])
            for sel_op in a_selections:
                if count == 0:
                    sel_op.entity.name = f'{user_input}_{new_number}'
                if count > 0:
                    new_number += add_number
                    sel_op.entity.name = f'{user_input}_{new_number}'
                
                count += 1
                
            
            
except Exception as err:
    if selections.count < 1:
        # error_message = f'Nebyl proveden žádný výběr!\nBylo vybráno {selections.count}
        ui.messageBox(err)
    if ui:
      ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

 

0 Likes
Message 4 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

Here is what I tried.

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

ui = None
def run(context):
    # Get the application and userInterface
    app = adsk.core.Application.get()
    ui = app.userInterface
    ui_var = app.userInterface

    # Get the value of the property.
    propertyValue = ui.commandDefinitions

    # Get the active product.
    cam = adsk.cam.CAM.cast(app.activeProduct)

    # Check if anything was returned.
    if (cam is None):
        ui.messageBox('Você deve estar na área de trabalho Concluído (CAM)!')
    
    # Get the Setups collection object from the CAM object.
    setups = cam.setups

    # Get the first Setup object in the CAM product.
    setup = setups.item(0)

    # Get the Operations collection object that contains all the operations in the setup.
    operations = setup.operations

    # Get the first operation in the collection.
    operation = operations.item(0)

    # Get selected Operations
    selections = ui.activeSelections
    try:
        # print(f'Es sind {selections.count} Operationen ausgewählt!')
        a_selections = selections.asArray()
        if selections.count == 0:
            ui.messageBox('Nenhuma seleção de operação foi feita')
            adsk.terminate()
        if selections.count >= 1:
            # Abfrage Operations Bezeichnungen
            vorgabe = a_selections[0].entity.name
            user_input = ui_var.inputBox("Nome básico da operação", "Qual deve ser o nome básico das operações?", vorgabe)
            if user_input[1]:
                ui.messageBox('Eingabe wurde abgebrochen')
                adsk.terminate()

            if '~' not in user_input[0]:
                number = 1
                # for sel_op in a_selections:
                #     sel_op.entity.name = f'{user_input[0]}_{number}'
                #     number += 1

                opeLst = [s.entity for s in a_selections]

                if isinstance(opeLst[0], adsk.cam.Operation):
                    setup = opeLst[0].parent

                    for ope in setup.operations:
                        if ope in opeLst:
                            ope.name = f'{user_input[0]}_{number}'
                            number += 1

                
            if '~(' in user_input[0]:
                # Input Auseinandernehmen und in Liste umformen
                input_list = re.search(r'~(.*)$', user_input[0])
                input_list = input_list[0]
                input_list = input_list.replace('~', '').replace('(', '').replace(')', '')
                input_list = input_list.split(',')
            
                # Zusatzargumente aus user_input entfernen
                extract = re.search(f"(.*?){re.escape('~')}", user_input[0])
                user_input = extract[0]
                user_input = user_input.replace('~', '')
            
                if len(a_selections) == len(input_list):
                    count = 0
                    for sel_op in a_selections:
                        sel_op.entity.name = f'{user_input}_{input_list[count]}'
                        count += 0
                else:
                    ui.messageBox('A lista que você forneceu não corresponde ao número de operações selecionadas! O script terminará agora')
            if '~' in user_input[0]:
                # Input Auseinandernehmen und in Liste umformen
                input_list = re.search(r'~.*$', user_input[0])
                input_list = input_list[0]
                input_list = input_list.replace('~', '')
                input_list = input_list.split(',')
            
                # Zusatzargumente aus user_input entfernen
                extract = re.search(f"(.*?){re.escape('~')}", user_input[0])
                user_input = extract[0]
                user_input = user_input.replace('~', '')
            
                count = 0
                new_number = float(input_list[0])
                add_number = float(input_list[1])
                for sel_op in a_selections:
                    if count == 0:
                        sel_op.entity.name = f'{user_input}_{new_number}'
                    if count > 0:
                        new_number += add_number
                        sel_op.entity.name = f'{user_input}_{new_number}'
                
                    count += 1
                
    except Exception as err:
        if selections.count < 1:
            # error_message = f'Es wurde keine Auswahl getroffen!\nEs wurden {selections.count} operationen ausgewählt'
            ui.messageBox(err)
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


The data I used is also attached.

 

Message 5 of 45

Tomas_V_cz
Advocate
Advocate

thanks, now it works perfectly...

would it be possible to capture for example the diameter of the tool in the operation comment?

For example, I would select drilling operations and the script would complete the text- drill hole - tool diameter

0 Likes
Message 6 of 45

nubrandao
Collaborator
Collaborator
Awesome. Is perfect

Based in this script, is hard to create a NC program for each toolpath
selected?
0 Likes
Message 7 of 45

nubrandao
Collaborator
Collaborator

@kandennti hey mister

 

Thanks a lot for the help

 

Can you help with One more thing? Its very important and useful in my company.

 

I want to select all toolpaths, and create a single NC program for each toolpath selected 

0 Likes
Message 8 of 45

kandennti
Mentor
Mentor

@nubrandao -San.

 

I haven't worked on the Fusion360 API for a while, so I need some time to research and try it out.

0 Likes
Message 9 of 45

kandennti
Mentor
Mentor
Accepted solution

@Tomas_V_cz -San.

 

Perhaps I can do what you want, but I do not understand it in detail.

Since my native language is not English, I often cannot understand the meaning of the text alone.
I think it would be easier to understand the meaning and arrive at the answer if you could present images or data.
(This is not only you, but many others as well.)

0 Likes
Message 10 of 45

Tomas_V_cz
Advocate
Advocate

Good day, my language is also not English, but for demonstration we switched Fusion to English environment.

I would like to automate the output to the program as much as possible, and I think that using a macro would be possible - I think mainly for drilling operations. Example:

Drill bit diameter 6 drills holes.

diameter.png

Operation created:

 

drill.png

Then a script would be activated that would complete the text:

 

drill Now.png

script would create text, for example

drill a hole dia. 6

or

drill a hole 6

It would automatically for the text:

"drill  a hole" + tool diameter

Message 11 of 45

nubrandao
Collaborator
Collaborator

Thanks you very much

0 Likes
Message 12 of 45

nubrandao
Collaborator
Collaborator

Thank you very much

0 Likes
Message 13 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

Thanks for the clarification.

I have created a script to add the tool diameter for now.

# Fusion360API Python script

import traceback
import adsk
import adsk.core as core
import adsk.cam as cam
import re

_app: core.Application = None
_ui: core.UserInterface = None
_handlers = []

_setupSelIpt: core.SelectionCommandInput = None

CMD_INFO = {
    "id": "kantoku_rename_operations_by_diameter",
    "name": "rename operations by diameter",
    "tooltip": "rename operations by diameter"
}


class MyCommandCreatedHandler(core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args: core.CommandCreatedEventArgs):
        core.Application.get().log(args.firingEvent.name)
        try:
            global _handlers
            cmd: core.Command = core.Command.cast(args.command)

            onDestroy = MyCommandDestroyHandler()
            cmd.destroy.add(onDestroy)
            _handlers.append(onDestroy)

            onExecute = MyExecuteHandler()
            cmd.execute.add(onExecute)
            _handlers.append(onExecute)

            onPreSelect = MyPreSelectHandler()
            cmd.preSelect.add(onPreSelect)
            _handlers.append(onPreSelect)

            inputs: core.CommandInputs = cmd.commandInputs
            global _setupSelIpt
            _setupSelIpt = inputs.addSelectionInput(
                "_setupSelIptId",
                "Setup",
                "Please select Setup."
            )

        except:
            _ui.messageBox("Failed:\n{}".format(traceback.format_exc()))


class MyPreSelectHandler(core.SelectionEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args: core.SelectionEventArgs):
        ent = args.selection.entity
        if not ent.classType() == cam.Setup.classType():
            args.isSelectable = False


class MyExecuteHandler(core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args: core.CommandEventArgs):
        global _setupSelIpt
        rename_operations_by_diameter(_setupSelIpt.selection(0).entity)


class MyCommandDestroyHandler(core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args: core.CommandEventArgs):
        adsk.terminate()


def rename_operations_by_diameter(setup: cam.Setup):
    global _app
    camObj: cam.CAM = _app.activeProduct
    unitsMgr: core.UnitsManager = camObj.unitsManager
    ratio = unitsMgr.convert(
        1,
        unitsMgr.internalUnits,
        unitsMgr.defaultLengthUnits,
    )

    key = " Dia "
    for ope in setup.operations:
        if not hasattr(ope, "tool"): continue

        tool: cam.Tool = ope.tool
        dia = tool.parameters.itemByName(
            "tool_diameter"
        ).value.value

        if key in ope.name:
            pattern = key + r".*"
            name = re.sub(pattern, "", ope.name)
        else:
            name = ope.name

        newName = f"{name}{key}{dia * ratio}"
        if not ope.name == newName:
            ope.name = newName


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

        cmdDef: core.CommandDefinition = _ui.commandDefinitions.itemById(
            CMD_INFO["id"]
        )

        if not cmdDef:
            cmdDef = _ui.commandDefinitions.addButtonDefinition(
                CMD_INFO["id"],
                CMD_INFO["name"],
                CMD_INFO["tooltip"]
            )

        global _handlers
        onCommandCreated = MyCommandCreatedHandler()
        cmdDef.commandCreated.add(onCommandCreated)
        _handlers.append(onCommandCreated)

        cmdDef.execute()

        adsk.autoTerminate(False)

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

 

After running the script, a dialog appears.
Select "Setup" and press OK button to append the diameter.

1.png
If you change the tool after running the script once and the diameter changes, just run the script again.

 

I figured out to change "drill" -> "drill a hole", but I didn't know what to change it to for the other types of operations.

Message 14 of 45

Tomas_V_cz
Advocate
Advocate

thank you for your script.

It would be possible to add an option:

include only for drilling operations (I think it's unnecessary for other operations)

or:

include only for selected operations (the operations on which the script would be activated would have to be selected with the mouse)?

Alternatively, both options for faster selection (only those operations for which the script would be activated would be selected from the drilling operations).

and it would also be good if the text would be added after the existing one, or would replace it completely (the original text would be deleted)

Thank you very much

0 Likes
Message 15 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

I'm sorry, but I didn't understand what you meant.

0 Likes
Message 16 of 45

ArjanDijk
Advisor
Advisor

@Tomas_V_cz Have you tried without a script, just select all operations slowly click the top one, rename to "mould" and it will number all below?


Inventor HSM and Fusion 360 CAM trainer and postprocessor builder in the Netherlands and Belgium.


0 Likes
Message 17 of 45

Tomas_V_cz
Advocate
Advocate

Good day.

In this latest version, the script is applied to all operations - but I think that, for example, I want the diameter of the tool (drill) only for drilling operations (and only for some, where the diameter of the tool = the diameter of the hole).

  In the previous version, the operations were marked and the script was applied to them. This is not possible in this version. In this new version, the script is applied to all operations (which I think is not desirable). For example, I do not want the tool diameter to be displayed for milling operations, and this is not possible in this new version.

 

Furthermore, in this new version the original text remains and a new text is added after the old test (example Dia 50), in the old version the old (original) text was completely replaced by the new text, which I think is desirable.

Thank you

0 Likes
Message 18 of 45

nubrandao
Collaborator
Collaborator

Hi, did you tried to create NC program for each toolpath selected? Thanks on advance

0 Likes
Message 19 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

I understand what you mean.
I am attaching the file as it is long.

・I have stopped selecting "Setup" and only "Drill" operations can be selected.
・I can now select the option to add/remove the tool diameter to/from the name.
・The name of the tool can be checked after the change, though it is simple.

This is a script, so please be careful when registering it.

1.png

0 Likes
Message 20 of 45

kandennti
Mentor
Mentor
Accepted solution

@nubrandao -San.

 

I have worked on this a bit, but feel it is not easy.
At first I was going to manipulate this check button on the NCProgram to perform the process, but I could not find a function in the API to manipulate this check.

1.png


I think I will have to create a new NCProgram and either transcribe all the settings or duplicate them and do something with them, but I haven't fully researched it yet.

0 Likes