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: 

Can rows in tables (CommandTableInputs) be swapped?

9 REPLIES 9
Reply
Message 1 of 10
william-c-anderson
585 Views, 9 Replies

Can rows in tables (CommandTableInputs) be swapped?

In the add-in that I'm working on, I will need to have ordered rows in a table, and I wish the user to be able to specify the order of the rows. To do this in a reasonable, I will need to be able to swap rows in a TableCommandInput. I've tried several ways, but I'm not close to a solution. Can this be done? Swapping rows in a table is a pretty basic function for table manipulation, it would seem.

BTW, the table's control inputs are simply editable (and non-editable) stringValueCommandInputs, if it matters.

9 REPLIES 9
Message 2 of 10

I'll add that my latest attempt was this naive bit of Python:

# swap table rows
def swapRows(table, i, j):
    for c in list(range(table.numberOfColumns)):
        cmd = table.getInputAtPosition(i,c)
        table.removeInput(i,c)
        table.addCommandInput(table.getInputAtPosition(j,c),i,c)
        table.removeInput(j,c)
        table.addCommandInput(cmd,j,c)

and it failed on the last line with a "API Object refers to a deleted Object" runtime error:

 

Untitled.png

 

The documentation for tableCommandEntry has the following for the method "removeInput":

 

removeInputRemoves the command input that is at the specified row and column. This doesn't delete the command input (emphasis: OP) from the collection of inputs associated with the command but just removes it from being displayed in the table.

 

so I assumed that the assignment to the var "cmd" above would keep the associated commandInput in scope. Doesn't look like it did.

Message 3 of 10

Talking to myself again ... 😉

 

Clearly, tableCommandEntry.removeInput destroys the commandInput at (i,j). Either the code or the documentation is buggy. Since the commandInput is destroyed, there is no way to exchange the row contents, AFAIK.

 

Can one of the exceptionally helpful ADSK folks (@BrianEkins, @kandennti) respond to this with a workaround? I have everything else in my enhanced table code working...

Message 4 of 10

Hi Mr William-C-Anderson,

 

I haven't analysed the code too deeply and as a matter of fact, I have never ventured into CommandTable domain, but could you consider creating a spare copy (or twin) of commandInput at (i,j) with the purpose of recreating it after removing the row.

 

Regards

MichaelT 

 

MichaelT
Message 5 of 10

I'll get a sample piece of code that displays the issue tomorrow.

Message 6 of 10

Hi @william-c-anderson .

 

Certainly the @william-c-anderson code did not work.
Therefore, it is very inefficient, but we decided to rewrite everything in the table.


I made a sample of a very simple TableCommandInput.
1.png
Click the red part to replace the blue part.
The green area shows the row count of the current table.

The swapRows function is as follows.

def swapRows(table :adsk.core.TableCommandInput, i, j):
    # Current Row count
    rowcount = table.rowCount

    # List all table cells
    lst =[]
    for r in range(table.rowCount):
        lst.append([table.getInputAtPosition(r, c) for c in range(table.numberOfColumns)])

    # swap
    lst[i], lst[j] = lst[j], lst[i]

    # Clear the table - If you do this, later processing will not work
    # table.clear()

    # Reinsert into table
    for r, row in enumerate(lst):
        for c, cell in enumerate(row):
            table.addCommandInput(cell, r + rowcount, c)
            # Originally, I wanted to do this after clearing the table, but I got an error
            # table.addCommandInput(cell, r, c)

    # Delete near the beginning because it was added in the latter half with addCommandInput
    for r in range(rowcount):
        table.deleteRow(0)

Clicking the first time will certainly swap the first and second Rows.
2.png
However, the rows count of the table has increased even though the old one has been deleted.

Click again and Fusion360 will crash....


After trying various things, I felt the strongest was that the second parameter of "TableCommandInput.addCommandInput" was not working.
(Can only be added at the end)
It is likely that my code is also doing something wrong.

 

 


 

ADSK folks (@BrianEkins, @kandennti


Expert Elite is just the same user as you.
(I usually use CATIA & PowerMill.)
ADSK folks are probably people with this mark.
3.png

Message 7 of 10

Command tables were not designed and never intended to do what you're trying to do.  Their purpose is to support a layout of command inputs in something besides the standard vertical linear layout.  What is there is functionality that already exists in Fusion to support existing Fusion commands and was then exposed through the API.  The current command table has sufficient functionality for what Fusion needs.  There's no doubt that there's a need for a more generic type of table, but that's not what this is.

---------------------------------------------------------------
Brian Ekins
Inventor and Fusion 360 API Expert
Website/Blog: https://EkinsSolutions.com
Message 8 of 10


@BrianEkins wrote:

Command tables were not designed and never intended to do what you're trying to do.  ....


I certainly can see that, having struggled for several days to make a more flexible (or "generic", if you prefer) table module. Trying to make tables more "generic" has made me feel like a chainsaw sculptor, if you get my drift 😉. But this doesn't change the fact that the documentation is wrong, per my post above.

 

I'll post my script here, anyhow. It does a few things (has a header row that is always displayed, widen and narrows columns) and someone may find it useful. I did find some additional anomalies when working with this code, to wit:

 

  1. The enum "transparentBackgroundTablePresentationStyle" cannot be found by Python. Did I miss an import?
  2. addseparator() fails for inputs returned from addDropDownCommandInput(). Is this a case where addSeparator() is "not supposed" to work?
  3. As I've mentioned, CommandTableInputs.removeInputs() does not seem to work as documented. In line 99 below, the script crashes due to its inability to keep an inputCmd in scope.
  4. In my opinion, treating rows and columns differently in CommandTableInputs (e.g. tables cannot be scrolled horizontally, even as an option) belies the goal of making a table command "conceptually (comparable) to an Excel table where you have an infinite number of rows and columns available but use a small portion", per the command description. I'd sure like to see horizontal scrolling added as an option.

Here's the code - you should be able to just paste it into an empty script. Cheers, and thanks for the help.

 

#Author-Willie Anderson
#Description-Adjustable Table Demo

# This adjustable table testbench was adapted from table section of ADSK Input Sampler

import adsk.core, adsk.fusion, traceback

_app = None
_ui  = None

# Global set of event handlers to keep them referenced for the duration of the command
_handlers = []

# Units available for parameter input - see addRowToTable()
_units = ['integer','real','---','mm', 'cm','m','μ','---','"','ft','yd','mil','---','rad','°','grad']

# column header labels (sorry for shouting :-)
_columnLabels = ['Heading 0','Heading 1','Heading 2','Heading 3']

# other global parameters
#_tableStyle = transparentBackgroundTablePresentationStyle # Python cannot find this enum
_tableStyle = 2             # should be transparentBackgroundTablePresentationStyle
_tableSpace = 0             # padding between rows and columns
_min_rows = 1               # minimum rows shown in the data table
_max_rows = 5               # maximum rows shown in the data table
_column_width_basis = 30.0  # used for column widening / narrowing; if too large, wide columns fail
_cmd = 'testTable'          # command name
_colSpec = '8:16:4:4'       # initial column ratios

_rows_created = 0           # used in dummy addRowToTable() to generate unique IDs
_selected_column = -1
_tables = []

# build header (column label) table
# we build a separate table (as opposed to just having a special first row)
# so that we can keep this header list visible as the bottom table scrolls
def labelTable(inputs):

    table = inputs.addTableCommandInput(_cmd + 'Header', '', 0, _colSpec)
    table.tablePresentationStyle = _tableStyle
    table.minimumVisibleRows = 1
    table.maximumVisibleRows = 1
    table.rowSpacing = table.columnSpacing = _tableSpace
    cmds = adsk.core.CommandInputs.cast(table.commandInputs)

    for column in list(range(len(_columnLabels))):
        label = _columnLabels[column]
        header = cmds.addBoolValueInput((_cmd + 'Header{}').format(column),label,False)
        header.text = label
        header.isFullWidth = True # supress name when it would otherwise be shown
        table.addCommandInput(header, 0, column)
    
    return table


# adjust table column width
def adjustColumnWidth(tab,col,delta):

    # parse column ratio spec into list of integers
    width = list(map(int,tab.columnRatio.split(':')))
    if col != -1:
        width[col] += delta

    # normalize width[] so that its members sum to _column_width_basis but
    # maintain relative size; may cause issues for wide columns, be wary;
    # this algorithm is far from perfect, but user can work around it
    ratio = _column_width_basis/float(sum(width))
    for i in list(range(len(width))):
        width[i] = round(ratio * float(width[i]))

    # rebuild the column ratio spec
    columnSpec = ':'.join(map(str,width))
    tab.columnRatio = columnSpec


# convenience function for lambda in inputChangedHandler
def adjustAllColumns(column, delta):
    for t in _tables:
        adjustColumnWidth(t, column, delta)


# swap table rows - used to move rows up and down
def swapRows(table, i, j):

    global _ui # initialized by run()

    for c in list(range(table.numberOfColumns)):

        # ADSK documentation is wrong:
        # table.removeInput(i,j) destroys input at (i,j);
        # watch cmd_* in debug asafter table.removeInput()
        id_ic = table.getInputAtPosition(i,c).id
        id_jc = table.getInputAtPosition(j,c).id
        cmd_ic = table.commandInputs.itemById( id_ic )
        cmd_jc = table.commandInputs.itemById( id_jc )
        table.removeInput(i,c)
        table.addCommandInput(cmd_jc,i,c) 
        table.removeInput(j,c)
        table.addCommandInput(cmd_ic,j,c)   # KABOOM - cmd_ic is already gonzo


# Adds a new row to the table;
# Here's where the various columns are defined
def addRowToTable(tableInput):
    global _rows_created

    row = _rows_created
    col = len(_columnLabels)
    
    # Get the CommandInputs object associated with the parent command.
    cmdInputs = adsk.core.CommandInputs.cast(tableInput.commandInputs)
    
    # Create new command inputs and value display
    # just do something that fills in boxes
    for c in list(range(col)):
        ident = _cmd + '_{}_{}'.format(row, c)
        if c < col - 1:
            inputCmd = cmdInputs.addStringValueInput(ident,ident,ident)
        else:   # make the last column a drop down unit selector, just for fun
            inputCmd = cmdInputs.addDropDownCommandInput(ident,ident,adsk.core.DropDownStyles.TextListDropDownStyle)
            for unit in _units:
                if unit == _units[0]:
                    inputCmd.listItems.add(unit, True)
                elif unit == '---':
                    inputCmd.listItems.addSeparator(-1)        # addSeparator fails here
                else:
                    inputCmd.listItems.add(unit, False)
        inputCmd.isFullWidth = True
        tableInput.addCommandInput(inputCmd,row, c)

    _rows_created += 1


# Event handler that reacts to any changes the user makes to any of the command inputs.
class MyCommandInputChangedHandler(adsk.core.InputChangedEventHandler):

    def __init__(self):
        super().__init__()

    def notify(self, args):
        global _selected_column
        
        try:
            eventArgs = adsk.core.InputChangedEventArgs.cast(args)
            cmdInput = eventArgs.input
            table = eventArgs.inputs.itemById(_cmd)
            rows = table.rowCount
            selected = table.selectedRow

            cmdSwitch = {
                _cmd+'Add':
                    lambda:
                        addRowToTable(table) ,
                _cmd+'Delete':
                    lambda:
                        table.deleteRow(selected) if selected != -1
                            else _ui.messageBox('Select a row to delete.'),
                _cmd+'RowUp':
                    lambda:
                        swapRows(table, selected, selected - 1) if selected > 0
                            else _ui.messageBox('Select a row that can move up.'),
                _cmd+'RowDown':
                    lambda:
                        swapRows(table, selected, selected + 1) if selected < rows - 2
                            else _ui.messageBox('Select a row that can move down.'),
                _cmd+'ColumnWiden':
                    lambda:
                        adjustAllColumns(_selected_column, 1) if _selected_column != -1
                            else _ui.messageBox('Select a column to adjust.'),
                _cmd+'ColumnNarrow':
                    lambda:
                        adjustAllColumns(_selected_column, -1) if _selected_column != -1
                            else _ui.messageBox('Select a column to adjust.')
            }

            # the lambda default arg below allows other
            # strings to pass (e.g. column selections below)
            cmdSwitch.get(cmdInput.id, lambda: 0)()

            # detect column selections
            if cmdInput.id.startswith(_cmd+'Header'):
                _selected_column = int(cmdInput.id.replace(_cmd+'Header','',1))
            
            # handle other input changes here

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


# Event handler that reacts to when the command is destroyed. This terminates the script.            
class MyCommandDestroyHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # When the command is done, terminate the script
            # This will release all globals which will remove all event handlers
            adsk.terminate()
        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


# Event handler that reacts when the command definitio is executed which
# results in the command being created and this event being fired.
class MyCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # Get the command that was created.
            cmd = adsk.core.Command.cast(args.command)
 
            # Connect to the command destroyed event.
            onDestroy = MyCommandDestroyHandler()
            cmd.destroy.add(onDestroy)
            _handlers.append(onDestroy)

            # Connect to the input changed event.           
            onInputChanged = MyCommandInputChangedHandler()
            cmd.inputChanged.add(onInputChanged)
            _handlers.append(onInputChanged)    

            # Get the CommandInputs collection associated with the command.
            inputs = cmd.commandInputs

            # Create header table
            headers = labelTable(inputs)
            _tables.append(headers)

            # Create table input
            tableInput = inputs.addTableCommandInput(_cmd, _cmd, 0, _colSpec)
            tableInput.tablePresentationStyle = _tableStyle
            tableInput.minimumVisibleRows = 1
            tableInput.maximumVisibleRows = 6
            tableInput.rowSpacing = tableInput.columnSpacing = _tableSpace
            addRowToTable(tableInput)

            # Add buttons to the bottom of the table.
            for button in ['Add','Delete','RowUp','RowDown','ColumnWiden','ColumnNarrow']:
                tableInput.addToolbarCommandInput(inputs.addBoolValueInput(_cmd+button, button, False))

            _tables.append(tableInput)
  
        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


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

        # Get the existing command definition or create it if it doesn't already exist.
        cmdDef = _ui.commandDefinitions.itemById(_cmd+'Cmd')
        if not cmdDef:
            cmdDef = _ui.commandDefinitions.addButtonDefinition(_cmd+'Cmd', 'Table Input Testbench', 'Testbench for flexible table.')

        # Connect to the command created event.
        onCommandCreated = MyCommandCreatedHandler()
        cmdDef.commandCreated.add(onCommandCreated)
        _handlers.append(onCommandCreated)

        # Execute the command definition.
        cmdDef.execute()

        # Prevent this module from being terminated when the script returns, because we are waiting for event handlers to fire.
        adsk.autoTerminate(False)
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

Message 9 of 10

I know this may be a bit old, however, for anyone interested the issue I believe seems to be a bug in how the table command works in general. If the first item in a row gets re-assigned to the table, the entire row becomes almost inaccessible and it cannot be deleted since the first object would still technically reference an object I assume. I have become interested in this topic since i too want a more flexible table and I will post my code if I make progress

Message 10 of 10
zxynine
in reply to: zxynine

I have managed to create a workaround but it is not perfect as there will be an empty column at the end of table. With that said, the row swapping works perfectly now and does not even break when you remove or add any row.

 

 

It comes from me actually using the fact that adding to a pre-existing row in a position without a control results in a new row in front of it with only that one item while the old row gets pushed down with the rest.

#Author-Willie Anderson
#Description-Adjustable Table Demo

# This adjustable table testbench was adapted from table section of ADSK Input Sampler

import adsk.core, adsk.fusion, traceback
from copy import deepcopy

_app = None
_ui : adsk.core.UserInterface = None

# Global set of event handlers to keep them referenced for the duration of the command
_handlers = []

# Units available for parameter input - see addRowToTable()
_units = ['integer','real','---','mm', 'cm','m','μ','---','"','ft','yd','mil','---','rad','°','grad']

# column header labels (sorry for shouting :-)
_columnLabels = ['Heading 0','Heading 1','Heading 2','Heading 3']

# other global parameters
#_tableStyle = transparentBackgroundTablePresentationStyle # Python cannot find this enum
_tableStyle = 2             # should be transparentBackgroundTablePresentationStyle
_tableSpace = 0             # padding between rows and columns
_min_rows = 1               # minimum rows shown in the data table
_max_rows = 5               # maximum rows shown in the data table
_column_width_basis = 30.0  # used for column widening / narrowing; if too large, wide columns fail
_cmd = 'testTable'          # command name
_colSpec = '8:16:4:4'       # initial column ratios

_rows_created = 0           # used in dummy addRowToTable() to generate unique IDs
_selected_column = -1
_tables = []

_commandInputs: adsk.core.CommandInputs = None

# build header (column label) table
# we build a separate table (as opposed to just having a special first row)
# so that we can keep this header list visible as the bottom table scrolls
def labelTable(inputs):

	table = inputs.addTableCommandInput(_cmd + 'Header', '', 0, _colSpec)
	table.tablePresentationStyle = _tableStyle
	table.minimumVisibleRows = 1
	table.maximumVisibleRows = 1
	table.rowSpacing = table.columnSpacing = _tableSpace
	cmds = adsk.core.CommandInputs.cast(table.commandInputs)

	for column in list(range(len(_columnLabels))):
		label = _columnLabels[column]
		header = cmds.addBoolValueInput((_cmd + 'Header{}').format(column),label,False)
		header.text = label
		header.isFullWidth = True # supress name when it would otherwise be shown
		table.addCommandInput(header, 0, column)
	
	return table


# adjust table column width
def adjustColumnWidth(tab:adsk.core.TableCommandInput,col,delta):

	# parse column ratio spec into list of integers
	width = list(map(int,tab.columnRatio.split(':')))
	if col != -1:
		width[col] += delta

	# normalize width[] so that its members sum to _column_width_basis but
	# maintain relative size; may cause issues for wide columns, be wary;
	# this algorithm is far from perfect, but user can work around it
	ratio = _column_width_basis/float(sum(width))
	for i in list(range(len(width))):
		width[i] = round(ratio * float(width[i]))

	# rebuild the column ratio spec
	columnSpec = ':'.join(map(str,width))
	tab.columnRatio = columnSpec


# convenience function for lambda in inputChangedHandler
def adjustAllColumns(column, delta):
	for t in _tables:
		adjustColumnWidth(t, column, delta)


# swap table rows - used to move rows up and down
def swapRows(table : adsk.core.TableCommandInput, i, j, selected):

	global _ui, _commandInputs
	 # initialized by run()
	tableiRow = [_commandInputs.itemById(table.getInputAtPosition(i,c).id) for c in range(table.numberOfColumns)]
	tablejRow = [_commandInputs.itemById(table.getInputAtPosition(j,c).id) for c in range(table.numberOfColumns)]

	tableCols = table.numberOfColumns
	table.addCommandInput(tableiRow[0],i,table.numberOfColumns) 
	#These are two dummy inputs for the table to have something to delete
	tempinput =_commandInputs.addStringValueInput('tempID',  'tempName', ' ')
	tempinput2 =_commandInputs.addStringValueInput('tempID2',  'tempName2', ' ')
	#Moves the current rows first input to the end
	table.addCommandInput(tempinput, i,table.numberOfColumns)
	#Moves the next rows first input to the end
	table.addCommandInput(tempinput2, j, table.numberOfColumns)
	#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	table.removeInput(i,0)
	# #Creates a new row and starts moving objects into it
	for c in range(table.numberOfColumns - 3):
		table.addCommandInput(tablejRow[c], i, c)
	# #Creates a new row and starts moving objects into it
	for c in range(table.numberOfColumns - 3):
		table.addCommandInput(tableiRow[c], j, c)
	# Deletes the old rows with the dummy inputs
	table.deleteRow(i+2)
	table.deleteRow(i)
	table.selectedRow = selected



# Adds a new row to the table;
# Here's where the various columns are defined
def addRowToTable(tableInput: adsk.core.TableCommandInput):
	global _rows_created, _commandInputs

	row = _rows_created
	col = len(_columnLabels)
	tableRows = tableInput.rowCount
	# Get the CommandInputs object associated with the parent command.
	cmdInputs =_commandInputs
	# cmdInputs = adsk.core.CommandInputs.cast(tableInput.commandInputs)
	
	# Create new command inputs and value display
	# just do something that fills in boxes
	for c in list(range(col)):
		ident = _cmd + '_{}_{}'.format(row, c)
		if c < col - 1:
			inputCmd = cmdInputs.addStringValueInput(ident,ident,ident)
		else:   # make the last column a drop down unit selector, just for fun
			inputCmd = cmdInputs.addDropDownCommandInput(ident,ident,adsk.core.DropDownStyles.TextListDropDownStyle)
			for unit in _units:
				if unit == _units[0]:
					inputCmd.listItems.add(unit, True)
				elif unit == '---':
					inputCmd.listItems.addSeparator(-1)        # addSeparator fails here
				else:
					inputCmd.listItems.add(unit, False)
		inputCmd.isFullWidth = True
		tableInput.addCommandInput(inputCmd,tableRows, c)

	_rows_created += 1


# Event handler that reacts to any changes the user makes to any of the command inputs.
class MyCommandInputChangedHandler(adsk.core.InputChangedEventHandler):

	def __init__(self):
		super().__init__()

	def notify(self, args):
		global _selected_column, _commandInputs
		
		try:
			eventArgs = adsk.core.InputChangedEventArgs.cast(args)
			cmdInput = eventArgs.input
			table:adsk.core.TableCommandInput = eventArgs.inputs.itemById(_cmd)
			rows = table.rowCount
			selected = table.selectedRow

			cmdSwitch = {
				_cmd+'Add':
					lambda:
						addRowToTable(table) ,
				_cmd+'Delete':
					lambda:
						table.deleteRow(selected) if selected != -1
							else _ui.messageBox('Select a row to delete.'),
				_cmd+'RowUp':
					lambda:
						swapRows(table, selected, selected - 1, selected - 1) if selected > 0
							else _ui.messageBox('Select a row that can move up.'),
				_cmd+'RowDown':
					lambda:
						swapRows(table, selected + 1, selected, selected + 1) if selected - 1 < rows - 2
							else _ui.messageBox('Select a row that can move down.'),
				_cmd+'ColumnWiden':
					lambda:
						adjustAllColumns(_selected_column, 1) if _selected_column != -1
							else _ui.messageBox('Select a column to adjust.'),
				_cmd+'ColumnNarrow':
					lambda:
						adjustAllColumns(_selected_column, -1) if _selected_column != -1
							else _ui.messageBox('Select a column to adjust.')
			}

			# the lambda default arg below allows other
			# strings to pass (e.g. column selections below)
			cmdSwitch.get(cmdInput.id, lambda: 0)()

			# detect column selections
			if cmdInput.id.startswith(_cmd+'Header'):
				_selected_column = int(cmdInput.id.replace(_cmd+'Header','',1))
			
			# handle other input changes here
			
			for i in range(table.rowCount):
				if (table.getInputAtPosition(i, 2) is not None): table.getInputAtPosition(i, 2).value = 'testTable: row# {}'.format(i)
		except:
			_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


# Event handler that reacts to when the command is destroyed. This terminates the script.            
class MyCommandDestroyHandler(adsk.core.CommandEventHandler):
	def __init__(self):
		super().__init__()
	def notify(self, args):
		try:
			# When the command is done, terminate the script
			# This will release all globals which will remove all event handlers
			adsk.terminate()
		except:
			_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

# Event handler that reacts when the command definitio is executed which
# results in the command being created and this event being fired.
class MyCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
	def __init__(self):
		super().__init__()
	def notify(self, args):
		try:
			global _commandInputs
			# Get the command that was created.
			cmd = adsk.core.Command.cast(args.command)
 
			# Connect to the command destroyed event.
			onDestroy = MyCommandDestroyHandler()
			cmd.destroy.add(onDestroy)
			_handlers.append(onDestroy)

			# Connect to the input changed event.           
			onInputChanged = MyCommandInputChangedHandler()
			cmd.inputChanged.add(onInputChanged)
			_handlers.append(onInputChanged)    

			# Get the CommandInputs collection associated with the command.
			inputs = cmd.commandInputs
			_commandInputs = inputs

			# Create header table
			headers = labelTable(inputs)
			_tables.append(headers)

			# Create table input
			tableInput = inputs.addTableCommandInput(_cmd, _cmd, 0, _colSpec)
			# tableInput.tablePresentationStyle = _tableStyle
			tableInput.tablePresentationStyle = adsk.core.TablePresentationStyles.itemBorderTablePresentationStyle
			tableInput.minimumVisibleRows = 4
			tableInput.maximumVisibleRows = 12
			tableInput.rowSpacing = tableInput.columnSpacing = _tableSpace
			addRowToTable(tableInput)
			addRowToTable(tableInput)
			addRowToTable(tableInput)
			addRowToTable(tableInput)

			# Add buttons to the bottom of the table.
			for button in ['Add','Delete','RowUp','RowDown','ColumnWiden','ColumnNarrow']:
				tableInput.addToolbarCommandInput(inputs.addBoolValueInput(_cmd+button, button, False))

			_tables.append(tableInput)
  
		except:
			_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


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

		# Get the existing command definition or create it if it doesn't already exist.
		cmdDef = _ui.commandDefinitions.itemById(_cmd+'Cmd')
		if not cmdDef:
			cmdDef = _ui.commandDefinitions.addButtonDefinition(_cmd+'Cmd', 'Table Input Testbench', 'Testbench for flexible table.')

		# Connect to the command created event.
		onCommandCreated = MyCommandCreatedHandler()
		cmdDef.commandCreated.add(onCommandCreated)
		_handlers.append(onCommandCreated)

		# Execute the command definition.
		cmdDef.execute()

		# Prevent this module from being terminated when the script returns, because we are waiting for event handlers to fire.
		adsk.autoTerminate(False)
	except:
		if _ui:
			_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

 

 

 

 

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