Anvil
How-to guides

Open API: add an action to the tool's UI

A resource reaches a modeller through three surfaces: the containment tree's shortcut menu, a diagram's shortcut menu, and the command bar above a diagram. All three take the same three objects and differ only in which configurator interface delivers them and which registration call installs it.

An action, a category, and a manager

Every entry in the tool's UI is an action, every action sits in a category, and every category sits in a manager. The same three types cover a menu, a toolbar and a shortcut menu:

ActionsManagerActionsCategoryNMAction
MenuThe menu barA menuA menu item
ToolbarAll toolbarsOne toolbarA button
Shortcut menuThe shortcut menuA submenuA menu item

A manager is one GUI element, being built right now. A category is a small group of actions, and a nested category is a submenu. A category is itself an NMAction, so it goes into a parent category the same way an action does.

ActionsManager.getActionFor(id) answers the action or category carrying that id, at whatever depth it sits, and falls back to the manager's parent when this one has nothing. That is how you find a group the tool built — and it is also what makes one command-bar mistake easy, because the answer to ActionsID.OPTIONS there is a category nested inside the bar rather than the bar itself. See The diagram command bar.

Write the action

Every action subclasses MDAction. Two subclasses cover the surfaces on this page: DefaultBrowserAction reads a tree selection, and DefaultDiagramAction reads the active diagram. Override actionPerformed at least.

import com.nomagic.magicdraw.ui.browser.actions.DefaultBrowserAction
import com.nomagic.ui.ScalableImageIcon
import java.awt.event.ActionEvent

class MyBrowserAction : DefaultBrowserAction(ACTION_ID, "Do the thing", null, null) {
    init {
        setDescription("What the modeller reads in the tooltip")
        smallIcon = ScalableImageIcon(MyBrowserAction::class.java, "my-icon-16.png")
        largeIcon = ScalableImageIcon(MyBrowserAction::class.java, "my-icon-16.png")
    }

    override fun actionPerformed(event: ActionEvent?) = doTheThing(tree?.selectedNodes.orEmpty())

    override fun updateState() {
        isEnabled = tree?.selectedNodes?.isNotEmpty() == true
    }
}

Give the action a stable, non-null id. A null id gets one generated, and then a shortcut the modeller assigns cannot be restored after a restart. A configurator also asks getActionFor(id) whether the entry it is about to add is already there, so an id that changes between builds lets the same entry be added twice. The constants on ActionsID name the tool's own actions — use them to find things, never as an id for one of yours.

A toolbar button needs a large icon. An action reaching a toolbar without one renders as a button carrying the action's name instead of an icon. A small icon covers menu rows.

ScalableImageIcon is the HiDPI-friendly icon: ship a .png and an .svg of the same name at the same location, and name the .png in the code. A regular-dpi monitor loads the raster and a HiDPI one loads the vector — the swap happens only when scaling is needed, and only when both files sit together. The vector is resized to the raster's size times the scaling factor, so a 16x16 .png beside an .svg gives 32x32 at a factor of two, whatever the vector's own dimensions are. With no .svg, the raster is scaled up instead. IconsFactory wraps the same loading and caches by URL.

updateState() decides whether the entry is enabled. It runs after any command and after a project or window opens or closes, and you can force a pass with ActionsStateUpdater.updateActionsState(). Let it throw and the menu suffers for it, so catch what your own state check can raise and fall back to disabled. The alternative is handing the action an ActionsGroups constant, which enables and disables it with every other action in that group under conditions you cannot change.

Put the action in a category

An action cannot go straight into a manager. It goes into a category, and you have two routes.

Join a group the tool built

For one or two entries, this is the one to reach for. A shortcut menu is long before a resource adds anything to it, and the tool has already grouped the commands a modeller looks for.

import com.nomagic.actions.ActionsCategory
import com.nomagic.magicdraw.actions.ActionsID

val tools = manager.getActionFor(ActionsID.TOOLS_CATEGORY) as? ActionsCategory
tools?.addAction(action)

Which group depends on what the command does. ActionsID names them all; these three cover most of what a resource adds:

GroupCollects
ActionsID.TOOLS_CATEGORYCommands acting on what is selected
ActionsID.MODEL_PROPERTIES_CATEGORYCommands about an element's properties
ActionsID.NEW_ELEMENT_POPUP_CATEGORY_IDCreate Element, Create Diagram

A menu that carries no such group gets no entry. Report that and move on rather than falling back to a category of your own: an entry that lands somewhere unexpected is worse than one missing from a single surface while the other surfaces still reach the command.

Report it once per run, not once per menu. A shortcut menu is created afresh on every invocation, so a missing group is rediscovered on every right-click, and the condition belongs to the tool build rather than to the gesture.

Make a category of your own

The tool's own examples create one and add it to the manager:

val category = MDActionsCategory("", "")
category.addAction(action)
manager.addCategory(category)

An unnamed, non-nested category is not a submenu — it renders as a separated group of its actions. That works, and the tool's own examples do it. What it does not do is put the entry beside the commands a modeller associates it with, which is the whole argument for the first route.

A named, nested category is a submenu, and that is the right answer for a set of related commands:

import com.nomagic.actions.ActionsCategory

class MyCategory(id: String, name: String) : ActionsCategory(id, name) {
    init {
        isNested = true
        icon = myIcon()
    }

    override fun updateState() {
        isEnabled = actions.isNotEmpty()
    }
}

Add it into a group the tool built, the same way you would add an action:

val workflows = MyCategory("MY_WORKFLOWS", "My Workflows")
workflows.addAction(MyBrowserAction())

val createElement = manager.getActionFor(ActionsID.NEW_ELEMENT_POPUP_CATEGORY_ID) as? ActionsCategory
createElement?.addAction(workflows)

In a shortcut menu this costs nothing. The category renders as the submenu a modeller expects, nesting further categories inside it works, and updateState greys the whole submenu out when it holds nothing worth showing.

Give it an explicit id and name. isNested is what makes it a submenu rather than a separated group.

The command bar is the one surface where a category of your own costs something, and its section says what.

The tree shortcut menu

Implement BrowserContextAMConfigurator, which is handed the manager and the tree being right-clicked.

import com.nomagic.actions.AMConfigurator
import com.nomagic.actions.ActionsManager
import com.nomagic.magicdraw.actions.BrowserContextAMConfigurator
import com.nomagic.magicdraw.ui.browser.Tree

class MyBrowserConfigurator(private val action: MyBrowserAction) : BrowserContextAMConfigurator {
    override fun configure(manager: ActionsManager, tree: Tree?) {
        if (manager.getActionFor(action.id) != null) return
        (manager.getActionFor(ActionsID.TOOLS_CATEGORY) as? ActionsCategory)?.addAction(action)
    }

    override fun getPriority(): Int = AMConfigurator.MEDIUM_PRIORITY
}

The containment tree and the Diagrams tree are two registrations, and one configurator instance serves both:

with(ActionsConfiguratorsManager.getInstance()) {
    addContainmentBrowserContextConfigurator(configurator)
    addDiagramsBrowserContextConfigurator(configurator)
}

A shortcut menu is created afresh on every invocation, so read any "is this feature switched on" state inside configure rather than at registration. A disabled feature then adds nothing to the menu, instead of adding a greyed-out row to it.

The diagram shortcut menu

Implement DiagramContextAMConfigurator, whose configure also receives the diagram, the selected symbols and the symbol the menu was raised on.

addDiagramContextConfigurator(DiagramTypeConstants.UML_ANY_DIAGRAM, configurator)

One registration under UML_ANY_DIAGRAM reaches every diagram type. The manager stores a diagram-scoped configurator under diagramType + "Context" and a menu build reads back the diagram's own type — but it does not stop there. AbstractCustomizableSymbolDiagramDescriptor.ContextConfigurator re-invokes the collection with getSuperType(), so the walk climbs to "Any Diagram" and finds what you registered. removeDiagramContextConfigurator undoes exactly it.

addBaseDiagramContextConfigurator also works, and is the wrong choice. It registers the configurator once per creatable type known when it runs, which is a snapshot — a diagram type registered afterwards is missed.

The diagram command bar

The strip of buttons above a diagram is a command bar, and it takes a plain AMConfigurator.

addAnyDiagramCommandBarConfigurator(configurator)

Never reach for addDiagramToolbarConfigurator. Despite the name it does not configure this strip: it configures the diagram's element palette, and DiagramWindowPanel.createPalette casts every category it finds there to DiagramInnerToolbarConfiguration. A plain category therefore throws a ClassCastException inside the panel's constructor and no diagram opens at all.

Its two neighbours are also wrong here: addSymbolDiagramCommandBarConfigurator excludes tables, matrices and maps, and the addDiagramCommandBarConfigurator(AMConfigurator) overload is deprecated in favour of the any-diagram form.

Join the bar holding the group, not the group

val options = manager.getActionFor(ActionsID.OPTIONS) as? ActionsCategory
val host = options?.let { manager.getActionParent(it) as? ActionsCategory ?: it }
host?.addAction(action)

ActionsID.OPTIONS on a diagram's command bar is nested, and a nested category on a bar is a gear rather than a group: MainCommandBarCreator.visit renders a child category carrying isNested() as an NMJideSplitButton and sends every action it holds into that button's popup. Add to OPTIONS itself and the button is one click deep. The category holding the gear renders its own actions as buttons, which is where an icon belongs — and getActionFor answering at any depth is exactly what makes it easy to grab the nested one by mistake.

getActionParent is the tool's own way up: it answers the parent of the action you hand it. Where the group already sits at the top level it is the bar itself, and there is nothing above it to find.

A category of your own becomes a docked toolbar

manager.addCategory(ActionsCategory("ID", "My Category")) is the documented way to add a category to a command bar, and on a dependency matrix that is what it does. On a diagram's command bar the same call costs two separate things.

MainCommandBarCreator.getRootComponent turns each category into CommandBar(category.id, category.name) and places it at getAllDockableBars().size() / 7 + 1. A bar arriving after the seventh therefore opens a second row above the diagram, which the modeller then has to drag back. That arithmetic runs whatever id you give the category.

The second cost is avoidable and easy to walk into. The no-argument ActionsCategory() takes its id from a per-JVM counter — !@#generatedIDID000000000000 — and the Jide layout is keyed on that id, so a placement the modeller fixes is forgotten at the next restart and the category shows in the bar's right-click list with a blank name. ActionsCategory(id, name) carries a stable id and does not.

Joining a group the tool already built adds no bar, so neither cost arises. The tool's own openapi/examples/simpleconfigurators adds a fresh category here and has both.

Draw the name, or don't

A large icon keeps a toolbar button from rendering as its name. Which of the two a given command bar draws is a separate decision, and it makes its own:

import com.nomagic.actions.NMAction

putValue(NMAction.DO_NO_SHOW_ACTION_NAME_IN_UI, true)

NMActionJideButton draws the action's name whenever its own isShowText() says so, and a diagram's command bar answers false where a table's and a matrix's answer true — so one action renders as a bare icon above a diagram and as icon-plus-text above a table. The property settles it everywhere.

The value must be a Boolean, because the button casts it before reading it.

Setting it on the action is safe when a shortcut menu shares the same action instance: only NMActionJideButton and BaseNMStateActionJideButton read the property, and a menu row renders from the name, which the property does not touch.

Register in init, remove in close

A configurator is registered against a manager that outlives your plugin, so whatever init registers, close must remove. Every add…Configurator call above has a matching remove….

Record what you registered before the registration calls run, not after. A call that throws partway through otherwise leaves everything registered before the throw stuck against the live singleton, with nothing recorded and the removal a permanent no-op over the leak:

installation = Installation(browser, diagram, commandBar)
with(ActionsConfiguratorsManager.getInstance()) { /* the four add… calls */ }

An environment options group is the one registration that is never removed in close() — see Open API: add an environment options group.

A diagram's command bar is built when its window opens, and a shortcut menu on every invocation. The command bar configurator runs once per diagram window, so a project restoring ten open diagrams runs it ten times; a log line in configure repeats accordingly. Once a bar is built, its actions "can be only disabled but not removed later" — so a modeller who switches a button off through your options keeps it, greyed, on every diagram already open, and a diagram opened afterwards carries none. Switching it back on reaches the next diagram opened. Say so in the option's description rather than letting them wonder.

Reference

  • Developer Guide — General › Adding new functionality, "Creating new actions", "Actions' hierarchy" and "Working with icons"; UML-based › Working with diagrams, "Configuring the command bar and shortcut keys"
  • Sample plugins — <install>/openapi/examples/actiontypes/, simpleconfigurators/, selectionactions/
  • API — com.nomagic.actions, com.nomagic.magicdraw.actions, com.nomagic.magicdraw.ui.actions, com.nomagic.magicdraw.ui.browser.actions, com.nomagic.ui
  • Local digest — dev-env/ai-docs/reference/guide/creating-new-actions.md

On this page