omni.kit.context_menu

Context Menu Libraries

Python API Reference

class omni.kit.context_menu.ContextMenuEventType
ADDED = 0
REMOVED = 0
class omni.kit.context_menu.ContextMenuExtension

Context menu core functionality. See omni.kit.viewport_legacy.context_menu for datailed usage.

Example using viewport mouse event to trigger:

class ContextMenu:
    def on_startup(self):
        # get window event stream
        import omni.kit.viewport_legacy
        viewport_win = get_viewport_interface().get_viewport_window()
        # on_mouse_event called when event dispatched
        self._stage_event_sub = viewport_win.get_mouse_event_stream().create_subscription_to_pop(self.on_mouse_event)

    def on_shutdown(self):
        # remove event
        self._stage_event_sub = None

    def on_mouse_event(self, event):
        # check its expected event
        if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE):
            return

        # get context menu core functionality & check its enabled
        context_menu = omni.kit.context_menu.get_instance()
        if context_menu is None:
            carb.log_error("context_menu is disabled!")
            return

        # get parameters passed by event
        objects = {}
        objects["test_path"] = event.payload["test_path"]
        # setup objects, this is passed to all functions
        objects["test"] = "this is a test"

        # setup menu
        menu_list = [
            # name is name shown on menu. (if name is "" then a menu spacer is added. Can be combined with show_fn)
            # glyph is icon shown on menu
            # name_fn funcion to get menu item name
            # show_fn funcion or list of functions used to decide if menu item is shown. All functions must return True to show
            # enabled_fn funcion or list of functions used to decide if menu item is enabled. All functions must return True to be enabled
            # onclick_fn function called when user clicks menu item
            # populate_fn a fucntion to be called to populate the menu. Can be combined with show_fn
            # appear_after a identifier of menu name. Used by custom menus and will allow cusom menu to change order

            {"name": "Test Menu", "glyph": "question.svg", "show_fn": [ContextMenu.has_reason_to_show, ContextMenu.has_another_reason_to_show],
                     "onclick_fn": ContextMenu.clear_default_prim },
            {"name": "", "show_fn": ContextMenu.has_another_reason_to_show},
            {"populate_fn": context_menu.show_create_menu},
            {"name": ""},
            {"name": "Copy URL Link", "glyph": "menu_link.svg", "onclick_fn": ContextMenu.copy_prim_url},
        ]

        # add custom menus
        menu_list += omni.kit.context_menu.get_menu_dict("MENU", "")
        menu_list += omni.kit.context_menu.get_menu_dict("MENU", "stagewindow")
        omni.kit.context_menu.reorder_menu_dict(menu_dict)

        # show menu
        context_menu.show_context_menu("stagewindow", objects, menu_list)

    # show_fn functions
    def has_reason_to_show(objects: dict):
        if not "test_path" in objects:
            return False
        return True

    def has_another_reason_to_show(objects: dict):
        if not "test_path" in objects:
            return False
        return True

    def copy_prim_url(objects: dict):
        try:
            import pyperclip

            pyperclip.copy("My hovercraft is full of eels")
        except ImportError:
            carb.log_warn("Could not import pyperclip.")
bind_material_to_prims_dialog(stage: pxr.Usd.Stage, prims: list)
build_add_menu(objects: dict, prim_list: list, custom_menu: Optional[list] = None)
build_create_menu(objects: dict, prim_list: list, custom_menu: dict = [])
async can_assign_material_async(objects: dict, menu_item: omni.ui._ui.Widget)

async show function. The menu_item is created but not visible, if this item is shown then menu_item.visible = True This scans all the prims in the stage looknig for a material, if one is found then it can “assign material” and menu_item.visible = True

can_be_copied(objects: dict)

checks if prims can be copied

can_delete(objects: dict)

checks if prims can be deleted

can_show_find_in_browser(objects: dict)

checks if one prim is selected and have URL (authored)

can_use_find_in_browser(objects: dict)

checks if prims are authored

convert_payload_to_reference(objects: dict)
convert_reference_to_payload(objects: dict)
copy_prim_path(objects: dict)None

copy prims path to clipboard

Parameters

objects – context_menu data

Returns

None

copy_prim_url(objects: dict)

Copies url of Prim in USDA references format. @planet.usda@</Planet>

create_material_and_assign(prim_list: List[pxr.Usd.Prim], blocking: bool = True)None

create material and bind to prim_list

Parameters
  • create_fn – create material function

  • prim_list – list is Usd.Prims

  • blocking – block and call create_fn

Returns

None

create_mesh_prim(prim_type: str)None

create mesh prims

Parameters
  • objects – context_menu data

  • prim_type – created prim’s type

Returns

None

create_prim(prim_type: str, attributes: dict, create_group_xform: bool = False)None

create prims

Parameters
  • objects – context_menu data

  • prim_type – created prim’s type

  • attributes – created prim’s cutsom attributes

  • create_group_xform – passed to CreatePrimWithDefaultXformCommand

Returns

None

delete_prim(objects: dict, destructive=False)

delete prims

Parameters
  • objects – context_menu data

  • destructive – If it’s true, it will remove all corresponding prims in all layers. Otherwise, it will deactivate the prim in current edit target if its def is not in the current edit target. By default, it will be non-destructive.

Returns

None

duplicate_prim(objects: dict)

duplicate prims

Parameters

objects – context_menu data

Returns

None

find_in_browser(objects: dict)None

select prim in content_browser

Parameters

objects – context_menu data

Returns

None

group_selected_prims(objects: dict)

group prims

Parameters

prims – list of prims

Returns

None

has_payload(objects: dict)

checks if prims have payloads

has_payload_or_reference(objects: dict)

checks if prims have payloads or references

has_reference(objects: dict)

checks if prims have references

is_material(objects: dict)

checks if prims are UsdShade.Material

is_material_bindable(objects: dict)

checks if prims support matrial binding

is_one_prim_selected(objects: dict)

checks if one prim is selected

is_prim_selected(objects: dict)

checks if any prims are selected

menu_item(name: str, triggered_fn: Optional[Callable] = None, enabled: bool = True, checkable: bool = False, checked: bool = False, is_async_func=False)
on_shutdown()
on_startup(ext_id)
prim_is_type(objects: dict, type: pxr.Tf.Type)bool

checks if prims are given class/schema

refresh_payload_or_reference(objects: dict)
refresh_reference_payload_name(objects: dict)

checks if prims have references/payload and returns name

select_prims_using_material(objects: dict)

select stage prims using material

Parameters

objects – context_menu data

Returns

None

separator(name: str = '')bool
show_context_menu(menu_name: str, objects: dict, menu_list: List[dict], min_menu_entries: int = 1)None

build context menu from menu_list

Parameters
  • menu_name – menu name

  • objects – context_menu data

  • menu_list – list of dictonaries containing context menu values

  • min_menu_entries – minimal number of menu needed for menu to be visible

Returns

None

show_create_menu(objects: dict)

populate function that builds create menu

Parameters

objects – context_menu data

Returns

None

show_selected_prims_names(objects: dict)None

populate function that builds menu items with selected prim info

Parameters

objects – context_menu data

Returns

None

class omni.kit.context_menu.MaterialDialogs
bind_material_to_prims_dialog(stage: pxr.Usd.Stage, prims: list)None

show dialog to user can select material and bind to prims

Parameters
  • stage – Usd.Stage

  • prims – list of prims

Returns

None

destroy()
class omni.kit.context_menu.Path(*args, **kwargs)

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

absolute()

Return an absolute version of this path. This function works even if the path doesn’t point to anything.

No normalization is done, i.e. all ‘.’ and ‘..’ will be kept along. Use resolve() to get the canonical path to a file.

chmod(mode)

Change the permissions of the path, like os.chmod().

classmethod cwd()

Return a new path pointing to the current working directory (as returned by os.getcwd()).

exists()

Whether this path exists.

expanduser()

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

glob(pattern)

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

group()

Return the group name of the file gid.

classmethod home()

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

is_block_device()

Whether this path is a block device.

is_char_device()

Whether this path is a character device.

is_dir()

Whether this path is a directory.

is_fifo()

Whether this path is a FIFO.

is_file()

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()

Check if this path is a POSIX mount point

is_socket()

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

lchmod(mode)

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

lstat()

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

mkdir(mode=511, parents=False, exist_ok=False)

Create a new directory at this given path.

open(mode='r', buffering=- 1, encoding=None, errors=None, newline=None)

Open the file pointed by this path and return a file object, as the built-in open() function does.

owner()

Return the login name of the file owner.

read_bytes()

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)

Open the file in text mode, read it, and close the file.

rename(target)

Rename this path to the given path.

replace(target)

Rename this path to the given path, clobbering the existing destination if it exists.

resolve(strict=False)

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).

rglob(pattern)

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

rmdir()

Remove this directory. The directory must be empty.

samefile(other_path)

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

stat()

Return the result of the stat() system call on this path, like os.stat() does.

Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink’s.

touch(mode=438, exist_ok=True)

Create this file with the given access mode, if it doesn’t exist.

Remove this file or link. If the path is a directory, use rmdir() instead.

write_bytes(data)

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None)

Open the file in text mode, write to it, and close the file.

omni.kit.context_menu.Singleton(class_)

A singleton decorator

class omni.kit.context_menu.ViewportMenu
static bind_material_to_prim_dialog(objects)
static copy_prim_to_clipboard(objects)
static is_material_bindable(objects)
static is_on_clipboard(objects, name)
static is_prim_on_clipboard(objects)
static paste_prim_from_clipboard(objects)
static set_prim_to_pos(path, new_pos)
static show_create_menu(objects)
static show_menu(usd_context_name: str, prim_path: Optional[str] = None, world_pos: Optional[Sequence[float]] = None, stage=None)
omni.kit.context_menu.add_menu(menu_dict, index: str = 'MENU', extension_id: str = '')

add custom menu to any context_menu

Examples

menu = {“name”: “Open in Material Editor”, “onclick_fn”: open_material} # add to all context menus self._my_custom_menu = omni.kit.context_menu.add_menu(menu, “MENU”, “”) # add to omni.kit.widget.stage context menu self._my_custom_menu = omni.kit.context_menu.add_menu(menu, “MENU”, “omni.kit.widget.stage”)

Parameters
  • menu_dict – a dictonary containing menu settings. See ContextMenuExtension docs for infomation on values

  • index – name of the menu EG. “MENU”

  • extension_id – name of the target EG. “” or “omni.kit.widget.stage”

NOTE: index and extension_id are extension arbitary values. add_menu(menu, “MENU”, “omni.kit.widget.stage”) works

as omni.kit.widget.stage retreives custom context_menus with get_menu_dict(“MENU”, “omni.kit.widget.stage”) Adding a menu to an extension that doesn’t support context_menus would have no effect.

Returns

MenuSubscription. Keep a copy of this as the custom menu will be removed when release() is explictly called or this is garbage collected

omni.kit.context_menu.get_instance()

get instance of context menu class

omni.kit.context_menu.get_menu_dict(index: str = 'MENU', extension_id: str = '')List[dict]

get custom menus

see add_menu for dictonary info

Parameters
  • index – name of the menu

  • extension_id – name of the target

Returns

a list of dictonaries containing custom menu settings. See ContextMenuExtension docs for infomation on values

omni.kit.context_menu.get_menu_event_stream()

Gets menu event stream

omni.kit.context_menu.reorder_menu_dict(menu_dict: List[dict])

reorder menus using “appear_after” value in menu

Parameters

menu_dict – list of dictonaries

Returns

None