file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/main_model.py | """Manage the OGN data controlled by the OmniGraphNodeDescriptionEditor"""
from __future__ import annotations
import json
import pprint
from typing import Dict, Union
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_warn
from .attribute_properties import AttributeListModel
from .file_manager import FileManager
from .node_properties import NodePropertiesModel
from .ogn_editor_utils import OGN_DEFAULT_CONTENT, OGN_NEW_NODE_NAME
from .test_configurations import TestListModel
# ======================================================================
class Model:
"""Manager of the OGN contents in the node description editor.
External Properties:
input_attribute_model: The owned models containing all of the input attributes
is_dirty: True if the OGN has changed since being set clean
node_properties_model: The owned model containing just the properties of the node
ogn_data: Raw JSON containing the node's OGN data
output_attribute_model: The owned models containing all of the output attributes
state_attribute_model: The owned models containing all of the state attributes
tests_model: The owned model containing information about the tests
Internal Properties:
__checksum: Unique checksum of the current OGN data, to use for determining if the data needs to be saved
__extension: Information regarding the extension to which the node belongs
__file_manager: File manager for OGN data
"""
def __init__(self):
"""Set up initial empty contents of the editor
Args:
file_manager: File manager for OGN data
"""
ogt.dbg_ui("Initializing the model contents")
# Just set the data for now - parse only on request
self.input_attribute_model = None
self.node_properties_model = None
self.output_attribute_model = None
self.state_attribute_model = None
self.tests_model = None
self.__checksum = None
self.__extension = None
self.__file_manager = None
self.__node_name = None
# ----------------------------------------------------------------------
def destroy(self):
"""Runs when the model is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
# The main model owns all sub-models so destroy them here
ogt.destroy_property(self, "input_attribute_model")
ogt.destroy_property(self, "node_properties_model")
ogt.destroy_property(self, "output_attribute_model")
ogt.destroy_property(self, "tests_model")
self.__checksum = None
# ----------------------------------------------------------------------
def __set_data(self, new_contents: Dict):
"""
Initialize the OGN contents with a new dictionary of JSON data
Args:
new_contents: Dictionary of new data
Returns:
True if the data set is fully supported in the current codebase
"""
ogt.dbg_ui(f"Setting model OGN to {new_contents}")
try:
self.__node_name = list(new_contents.keys())[0]
node_data = new_contents[self.__node_name]
try:
# Construct the input attribute models
self.input_attribute_model = AttributeListModel(node_data[ogn.NodeTypeKeys.INPUTS], ogn.INPUT_GROUP)
except KeyError:
self.input_attribute_model = AttributeListModel(None, ogn.INPUT_GROUP)
try:
# Construct the output attribute models
self.output_attribute_model = AttributeListModel(node_data[ogn.NodeTypeKeys.OUTPUTS], ogn.OUTPUT_GROUP)
except KeyError:
self.output_attribute_model = AttributeListModel(None, ogn.OUTPUT_GROUP)
try:
# Construct the state attribute models
self.state_attribute_model = AttributeListModel(node_data[ogn.NodeTypeKeys.STATE], ogn.STATE_GROUP)
except KeyError:
self.state_attribute_model = AttributeListModel(None, ogn.STATE_GROUP)
try:
# Construct the tests model
self.tests_model = TestListModel(node_data[ogn.NodeTypeKeys.TESTS])
except KeyError:
self.tests_model = TestListModel(None)
# Construct the node properties model
filtered_keys = [
ogn.NodeTypeKeys.INPUTS,
ogn.NodeTypeKeys.OUTPUTS,
ogn.NodeTypeKeys.STATE,
ogn.NodeTypeKeys.TESTS,
]
self.node_properties_model = NodePropertiesModel(
self.__node_name,
self.__extension,
{key: value for key, value in node_data.items() if key not in filtered_keys},
self.__file_manager,
)
except (AttributeError, IndexError, KeyError) as error:
ogt.dbg_ui(f"Error setting new OGN data - {error}")
self.input_attribute_model = AttributeListModel(None, ogn.INPUT_GROUP)
self.output_attribute_model = AttributeListModel(None, ogn.OUTPUT_GROUP)
self.state_attribute_model = AttributeListModel(None, ogn.STATE_GROUP)
self.tests_model = TestListModel(None)
self.node_properties_model = NodePropertiesModel(
OGN_NEW_NODE_NAME, self.__extension, None, self.__file_manager
)
# By definition when new contents are just set they are clean
self.set_clean()
# ----------------------------------------------------------------------
def set_ogn_data(self, new_contents: Union[str, None, Dict] = None) -> bool:
"""Initialize the OGN content to the given contents, or an empty node if None.
Args:
new_contents: If None reset to default, else it is a path to the new contents
Return:
True if the data read in is fully supported in the current codebase
"""
if new_contents is None:
ogt.dbg_ui("Resetting the content to the default")
self.__set_data(OGN_DEFAULT_CONTENT)
elif isinstance(new_contents, dict):
self.__set_data(new_contents)
else:
ogt.dbg_ui(f"Setting the new content from file {new_contents}")
try:
with open(new_contents, "r", encoding="utf-8") as content_fd:
self.__set_data(json.load(content_fd))
except json.decoder.JSONDecodeError as error:
log_warn(f"Could not reset the contents due to a JSON error : {error}")
# ----------------------------------------------------------------------
def __compute_checksum(self) -> int:
"""Find the checksum for the current data in the class - used to automatically find dirty state."""
ogt.dbg_ui("Computing the checksum")
try:
as_string = pprint.pformat(self.ogn_data)
except Exception: # noqa: PLW0703
# If not printable then fall back on a raw representation of the dictionary
as_string = str(self.ogn_data)
checksum_value = hash(as_string)
ogt.dbg_ui(f"-> {checksum_value}")
return checksum_value
# ----------------------------------------------------------------------
def set_clean(self):
"""Reset the current status of the data to be clean (e.g. after a file save)."""
ogt.dbg_ui("Set clean")
self.__checksum = self.__compute_checksum()
# ----------------------------------------------------------------------
@property
def ogn_data(self) -> Dict:
"""
Return the current full OGN data content, as-is.
As the data is spread out among submodels it has to be reassembled first.
"""
ogt.dbg_ui("Regenerating the OGN data")
raw_data = self.node_properties_model.ogn_data
input_attribute_ogn = self.input_attribute_model.ogn_data()
if input_attribute_ogn:
raw_data.update(input_attribute_ogn)
output_attribute_ogn = self.output_attribute_model.ogn_data()
if output_attribute_ogn:
raw_data.update(output_attribute_ogn)
state_attribute_ogn = self.state_attribute_model.ogn_data()
if state_attribute_ogn:
raw_data.update(state_attribute_ogn)
if self.tests_model:
tests_ogn_data = self.tests_model.ogn_data
if tests_ogn_data:
raw_data[ogn.NodeTypeKeys.TESTS] = tests_ogn_data
return {self.node_properties_model.name: raw_data}
# ----------------------------------------------------------------------
def ogn_node(self) -> ogn.NodeInterface:
"""Return the current interface to the OGN data
Raises:
ParseError: If the current data cannot be interpreted by the OGN node interface builder
"""
return ogn.NodeInterfaceWrapper(None, self.ogn_data, self.__extension.name).node_interface
# ----------------------------------------------------------------------
def metadata(self) -> Dict[str, str]:
"""Returns the contents of the node's metadata, or empty dictionary if there is none"""
return self.node_properties_model.metadata
# ----------------------------------------------------------------------
@property
def is_dirty(self) -> bool:
"""Return True if the contents have been modified since being set clean"""
ogt.dbg_ui("Checking for dirty state")
return self.__compute_checksum() != self.__checksum
# ----------------------------------------------------------------------
@property
def extension(self) -> ogn.OmniGraphExtension:
"""Return the extension information on the current model"""
return self.__extension
# ----------------------------------------------------------------------
@extension.setter
def extension(self, extension: ogn.OmniGraphExtension):
"""Sets the extension information on the current model"""
self.__extension = extension
self.node_properties_model.extension = extension
# ----------------------------------------------------------------------
@property
def file_manager(self) -> FileManager:
"""Return the ogn file manager on the current model"""
return self.__file_manager
# ----------------------------------------------------------------------
@file_manager.setter
def file_manager(self, file_manager: FileManager):
"""Sets the ogn file manager on the current model"""
self.__file_manager = file_manager
self.node_properties_model.file_manager = self.__file_manager
| 10,792 | Python | 43.053061 | 119 | 0.569403 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/tests_data_manager.py | """
Classes and functions relating to the handling of a list of attribute values
"""
from contextlib import suppress
from typing import Any, Callable, Dict, List, Optional
import omni.graph.tools as ogt
from carb import log_warn
from omni import ui
from .attribute_list_manager import AttributeListManager
from .attribute_properties import AttributeAddedMessage, AttributeRemovedMessage
from .change_management import RenameMessage
from .ogn_editor_utils import DestructibleButton
# ======================================================================
def find_next_unused_name(current_values: Dict[str, Any], available_values: List[str]):
"""Find the first unused name from the available_values
Args:
current_values: Dictionary of currently used values; key is the value to be checked
available_values: Ordered list of available key values to check
Returns:
First value in available_values that is not a key in current_values, None if there are none
"""
for available_value in available_values:
if available_value not in current_values:
return available_value
return None
# ======================================================================
class AttributeNameValueTreeManager:
"""Class that provides a simple interface to ui.TreeView model and delegate management for name/value lists.
Usage:
def __on_model_changed(new_dictionary):
print(f"Model changed to {new_dictionary})
my_dictionary = {"Hello": "Greeting", "World": "Scope"}
my_manager = AttributeNameValueTreeManager(my_dictionary, _on_model_changed)
ui.TreeView(my_manager.model)
"""
# ----------------------------------------------------------------------
class AttributeNameValueModel(ui.AbstractItemModel):
"""Represents the model for name-value table."""
class AttributeNameValueItem(ui.AbstractItem):
"""Single key/value pair in the model, plus the index in the overall model of this item"""
def __init__(self, key: str, value: Any):
"""Initialize both of the models to the key/value pairs"""
super().__init__()
self.name_model = ui.SimpleStringModel(key)
self.value_model = ui.SimpleStringModel(str(value))
def __repr__(self):
"""Return a nice representation of the string pair"""
return f'"{self.name_model.as_string} : {self.value_model.as_string}"'
# ----------------------------------------------------------------------
def __init__(self, key_value_pairs: Dict[str, str], available_attribute_names: List[str]):
"""Initialize the children into sorted tuples from the dictionary"""
ogt.dbg_ui(f"AttributeNameValueModel({key_value_pairs}))")
super().__init__()
self.__children = []
self.__key_value_pairs = {}
self.set_values(key_value_pairs)
self.available_attribute_names = available_attribute_names
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def reset(self):
"""Initialize the children to an empty list"""
ogt.dbg_ui("Reset AttributeNameValueModel")
self.__key_value_pairs = {}
self.rebuild_children()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def set_values(self, key_value_pairs: Dict[str, str]):
"""Define the children based on the new dictionary of key/value pairs"""
ogt.dbg_ui(f"Set values in AttributeNameValueModel to {key_value_pairs}")
self.__key_value_pairs = key_value_pairs.copy()
self.rebuild_children()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def rebuild_children(self):
"""Set the child string list, either for the initial state or after editing"""
ogt.dbg_ui("Rebuilding children")
self.__children = [
self.AttributeNameValueItem(key, self.__key_value_pairs[key])
for key in sorted(self.__key_value_pairs.keys())
]
# Insert a blank entry at the begining for adding new values
self.__children.insert(0, self.AttributeNameValueItem("", ""))
self.__item_changed(None)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def add_child(self):
"""Add a new default child to the list"""
ogt.dbg_ui("Add a new key/value pair")
suggested_name = find_next_unused_name(self.__key_value_pairs, self.available_attribute_names)
if suggested_name is None:
log_warn("No unused attributes remain - modify an existing one")
else:
self.__key_value_pairs[suggested_name] = ""
self.rebuild_children()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def remove_child(self, key_value: str):
"""Remove the child corresponding to the given item from the list
Raises:
KeyError: If the key value was not in the list
"""
ogt.dbg_ui(f"Removing key {key_value}")
del self.__key_value_pairs[key_value]
self.rebuild_children()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def rename_child(self, old_key_name: str, new_key_name: str):
"""Rename the child corresponding to the given item from the list
Raises:
KeyError: If the old key value was not in the list
"""
ogt.dbg_ui(f"Renaming key {old_key_name} to {new_key_name}")
old_value = self.__key_value_pairs[old_key_name]
del self.__key_value_pairs[old_key_name]
self.__key_value_pairs[new_key_name] = old_value
self.rebuild_children()
# ----------------------------------------------------------------------
def on_available_attributes_changed(self, change_message):
"""Callback that executes when the attributes under control"""
ogt.dbg_ui(f"MODEL: Attribute list changed - {change_message}")
if isinstance(change_message, RenameMessage):
with suppress(KeyError):
self.rename_child(change_message.old_name, change_message.new_name)
elif isinstance(change_message, AttributeAddedMessage):
self.rebuild_children()
elif isinstance(change_message, AttributeRemovedMessage):
with suppress(IndexError, KeyError, ValueError):
self.remove_child(change_message.attribute_name)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def get_item_count(self):
"""Returns the number of children (i.e. rows in the tree widget)."""
return len(self.__children)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return the empty list.
return item.model if item is not None else self.__children
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def get_item_value_model_count(self, item):
"""The number of columns, always 2 since the data is key/value pairs"""
return 3
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def get_item_value_model(self, item, column_id: int):
"""Returns the model for the item's column. Only columns 0 and 1 will be requested"""
return [item.name_model, item.name_model, item.value_model][column_id]
# ----------------------------------------------------------------------
class EditableDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
External Properties:
add_tooltip: Text for the tooltip on the button to add a new value
available_attribute_names: List of attributes that can be selected
subscription: Subscription that watches the value editing
value_change_cb: Callback to execute when the value has been modified
Internal Properties:
__attribute_list_managers: Managers for each of the attribute lists within the test list
"""
def __init__(self, value_change_cb: Callable, add_tooltip: str, available_attribute_names: List[str]):
"""Initialize the state with no subscription on the end edit; it will be used later"""
super().__init__()
self.subscription = None
self.value_change_cb = value_change_cb
self.add_tooltip = add_tooltip
self.available_attribute_names = available_attribute_names
self.__attribute_list_managers = []
self.__remove_button = None
self.__add_button = None
def destroy(self):
"""Cleanup any hanging references"""
self.subscription = None
self.value_change_cb = None
self.add_tooltip = None
self.available_attribute_names = None
ogt.destroy_property(self, "__add_button")
ogt.destroy_property(self, "__remove_button")
ogt.destroy_property(self, "__attribute_list_managers")
def build_branch(self, model, item, column_id: int, level: int, expanded: bool):
"""Create a branch widget that opens or closes subtree - must be defined"""
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def __on_add_item(self, model):
"""Callback hit when the button to add a new item was pressed"""
ogt.dbg_ui("Add new item")
model.add_child()
if self.value_change_cb is not None:
self.value_change_cb(model)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def __on_remove_item(self, model, item):
"""Callback hit when the button to remove an existing item was pressed"""
ogt.dbg_ui(f"Remove item '{item.name_model.as_string}'")
model.remove_child(item.name_model.as_string)
if self.value_change_cb is not None:
self.value_change_cb(model)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def __on_attribute_selected(self, new_value: str, model, item):
"""Callback hit when the attribute selector for a particular item has a new value
Args:
new_value: Newly selected attribute name for the given item
model: AttributeNameValueModel controlling the item information
item: AttributeNameValueItem that generated the change
Raises:
ValueError: When the new value is not legal (i.e. the same value exists on another item)
"""
ogt.dbg_ui(f"Verifying new selection {new_value} from child list {model.get_item_children(None)} on {item}")
for child in model.get_item_children(None):
if child != item and child.name_model.as_string == new_value:
raise ValueError(f"{new_value} can only appear once in the test data list")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def build_widget(self, model, item, column_id: int, level: int, expanded: bool):
"""Create a widget per column per item"""
ogt.dbg_ui(
f"Build widget on {model.__class__.__name__} for item {item}"
f" in column {column_id} at {level} expansion {expanded}"
)
if column_id == 0:
if item.name_model.as_string:
self.__remove_button = DestructibleButton(
width=20,
height=20,
style_type_name_override="RemoveElement",
clicked_fn=lambda: self.__on_remove_item(model, item),
tooltip="Remove this value from the test",
)
assert self.__remove_button
else:
self.__add_button = DestructibleButton(
width=20,
height=20,
style_type_name_override="AddElement",
clicked_fn=lambda: self.__on_add_item(model),
tooltip=self.add_tooltip,
)
assert self.__add_button
elif column_id == 1:
# First row, marked by empty name_mode, only has the "add" icon
if item.name_model.as_string:
self.__attribute_list_managers.append(
AttributeListManager(
item.name_model.as_string,
self.available_attribute_names,
lambda new_selection: self.__on_attribute_selected(new_selection, model, item),
)
)
else:
ui.Label("")
elif not item.name_model.as_string:
# First row, marked by empty name_mode, only has the "add" icon
ui.Label("")
else:
# The default value is a field editable on double-click
stack = ui.ZStack(height=20)
with stack:
value_model = model.get_item_value_model(item, column_id)
label = ui.Label(
value_model.as_string,
style_type_name_override="LabelOverlay",
alignment=ui.Alignment.CENTER_BOTTOM,
)
field = ui.StringField(value_model, visible=False)
# Start editing when double clicked
stack.set_mouse_double_clicked_fn(
lambda x, y, b, m, f=field, l=label: self.on_double_click(b, f, l)
)
# ----------------------------------------------------------------------
def on_available_attributes_changed(self, change_message):
"""Callback that executes when the attributes in the available list have changed"""
ogt.dbg_ui(f"DELEGATE: Attribute list changed - {change_message}")
if isinstance(change_message, RenameMessage):
for list_manager in self.__attribute_list_managers:
list_manager.on_child_renamed(change_message.old_name, change_message.new_name)
elif isinstance(change_message, AttributeAddedMessage):
for list_manager in self.__attribute_list_managers:
list_manager.on_child_added(change_message.attribute_name)
elif isinstance(change_message, AttributeRemovedMessage):
try:
for list_manager in self.__attribute_list_managers:
list_manager.on_child_removed(change_message.attribute_name)
except KeyError:
log_warn(f"Tried to remove nonexistent attribute {change_message.attribute_name}")
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def on_double_click(self, button, field, label):
"""Called when the user double-clicked the item in TreeView"""
if button != 0:
return
# Make Field visible when double clicked
field.visible = True
field.focus_keyboard()
# When editing is finished (enter pressed of mouse clicked outside of the viewport)
self.subscription = field.model.subscribe_end_edit_fn(lambda m, f=field, l=label: self.on_end_edit(m, f, l))
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def on_end_edit(self, model, field, label):
"""Called when the user is editing the item and pressed Enter or clicked outside of the item"""
ogt.dbg_ui(f"Ended edit of '{label.text}' as '{model.as_string}'")
field.visible = False
label.text = model.as_string
self.subscription = None
if self.value_change_cb is not None:
self.value_change_cb(model)
# ----------------------------------------------------------------------
def __init__(self, controller, value_change_cb: Optional[Callable], add_tooltip: str):
"""Initialize the model and delegate information from the dictionary"""
self.value_change_cb = value_change_cb
self.original_values = controller.test_data
# This same list is referenced by the model and delegate for simplicity
self.available_attribute_names = controller.available_attribute_names()
controller.add_change_callback(self.on_available_attributes_changed)
self.model = self.AttributeNameValueModel(self.original_values, self.available_attribute_names)
self.delegate = self.EditableDelegate(value_change_cb, add_tooltip, self.available_attribute_names)
# ----------------------------------------------------------------------
def on_available_attributes_changed(self, change_message):
"""Callback that executes when the attributes in the available list have changed"""
ogt.dbg_ui(f"MGR: Attribute list changed - {change_message}")
# Make sure list modifications are made in-place so that every class gets it
if isinstance(change_message, RenameMessage):
try:
attribute_index = self.available_attribute_names.index(change_message.old_name)
self.available_attribute_names[attribute_index] = change_message.new_name
except KeyError:
log_warn(f"Tried to rename nonexistent attribute {change_message.old_name}")
elif isinstance(change_message, AttributeAddedMessage):
self.available_attribute_names.append(change_message.attribute_name)
elif isinstance(change_message, AttributeRemovedMessage):
try:
self.available_attribute_names.remove(change_message.attribute_name)
except KeyError:
log_warn(f"Tried to remove nonexistent attribute {change_message.attribute_name}")
else:
ogt.dbg_ui(f"Unknown test data message ignored -> {change_message}")
# Update the UI that relies on the list of available attribues
self.model.on_available_attributes_changed(change_message)
self.delegate.on_available_attributes_changed(change_message)
# ======================================================================
class TestsDataManager(AttributeNameValueTreeManager):
"""Class that handles interaction with the node metadata fields."""
def list_values_changed(self, what):
"""Callback invoked when any of the values in the attribute list change"""
ogt.dbg_ui(f"Changing list values {what}")
new_values = {}
for child in self.model.get_item_children(None):
if child.name_model.as_string:
new_values[child.name_model.as_string] = child.value_model.as_string
# Edit the test data based on new values and reset the widget to keep a single blank row.
# Throws an exception if the test data is not legal, which will skip setting the model values
try:
self.__controller.test_data = new_values
self.model.set_values(new_values)
except AttributeError:
pass
def __init__(self, controller, add_element_tooltip: str):
"""Initialize the fields inside the given controller and set up the initial frame
Args:
controller: Controller for the list of attribute values managed by this widget
add_element_tooltip: Tooltip to use on the "add element" button
"""
super().__init__(controller, self.list_values_changed, add_element_tooltip)
self.__controller = controller
self.attribute_value_tree = None
# ----------------------------------------------------------------------
def on_rebuild_ui(self):
"""Callback that runs when the frame in which this widget lives is rebuilding"""
# Whenever values are updated the metadata list is synchronized with the set of non-empty metadata name models.
# This allows creation of new metadata values by adding text in the final empty field, and removal
# of existing metadata values by erasing the name. This avoids extra clutter in the UI with add/remove
# buttons, though it's important that the tooltip explain this.
self.attribute_value_tree = ui.TreeView(
self.model,
delegate=self.delegate,
root_visible=False,
header_visible=False,
height=0,
column_widths=[30, ui.Percent(40), ui.Percent(40)],
)
| 21,488 | Python | 50.042755 | 120 | 0.544955 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/node_properties.py | """
Collection of classes managing the Node Properties section of the OmniGraphNodeDescriptionEditor
These classes use a Model-View-Controller paradigm to manage the interface between the UI and the raw OGN data.
"""
import os
import shutil
from contextlib import suppress
from functools import partial
from subprocess import Popen
from typing import Dict, Optional
import carb
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_error, log_warn
from omni import ui
from omni.kit.widget.prompt import Prompt
from ..style import VSTACK_ARGS, name_value_hstack, name_value_label # noqa: PLE0402
from .change_management import ChangeManager
from .file_manager import FileManager
from .memory_type_manager import MemoryTypeManager
from .metadata_manager import MetadataManager
from .node_language_manager import NodeLanguageManager
from .ogn_editor_utils import DestructibleButton, GhostedWidgetInfo, OptionalCallback, ghost_int, ghost_text, show_wip
# ======================================================================
# List of metadata elements that will not be edited directly in the "Metadata" section.
FILTERED_METADATA = [ogn.NodeTypeKeys.UI_NAME]
# ======================================================================
# ID values for widgets that are editable or need updating
ID_BTN_SAVE = "nodeButtonSave"
ID_BTN_SAVE_AS = "nodeButtonSaveAs"
ID_BTN_GENERATE_TEMPLATE = "nodeButtonGenerateTemplate"
ID_BTN_EDIT_NODE = "nodeEditImplButton"
ID_BTN_EDIT_OGN = "nodeEditOgnButton"
ID_NODE_DESCRIPTION = "nodeDescription"
ID_NODE_DESCRIPTION_PROMPT = "nodeDescriptionPrompt"
ID_NODE_LANGUAGE = "nodeLanguage"
ID_NODE_MEMORY_TYPE = "nodeMemoryType"
ID_NODE_NAME = "nodeName"
ID_NODE_NAME_PROMPT = "nodeNamePrompt"
ID_NODE_UI_NAME = "nodeUiName"
ID_NODE_UI_NAME_PROMPT = "nodeUiNamePrompt"
ID_NODE_UNSUPPORTED = "nodeUnsupported"
ID_NODE_VERSION = "nodeVersion"
ID_NODE_VERSION_PROMPT = "nodeVersionPrompt"
# ======================================================================
# ID for dictionary of classes that manage subsections of the editor, named for their class
ID_MGR_NODE_METADATA = "NodeMetadataManager"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {
ID_BTN_SAVE: "Save .ogn file",
ID_BTN_SAVE_AS: "Save .ogn file in a new location",
ID_BTN_GENERATE_TEMPLATE: "Generate an empty implementation of your node algorithm",
ID_BTN_EDIT_NODE: "Launch the text editor on your node implementation file, if it exists",
ID_BTN_EDIT_OGN: "Launch the text editor on your .ogn file, if it exists",
ID_NODE_DESCRIPTION: "Description of what the node's compute algorithm does, ideally with examples",
ID_NODE_NAME: "Name of the node type as it will appear in the graph",
ID_NODE_UI_NAME: "Name of the node type that will show up in user-interface elements",
ID_NODE_UNSUPPORTED: "This node contains one or more elements that, while legal, are not yet supported in code",
ID_NODE_VERSION: "Current version of the node type (integer value)",
}
# ======================================================================
# Dispatch table for generated file type exclusion checkboxes.
# Key is the ID of the checkbox for the file type exclusions.
# Value is a tuple of (CHECKBOX_TEXT, EXCLUSION_NAME, CHECKBOX_TOOLTIP)
NODE_EXCLUSION_CHECKBOXES = {
"nodeExclusionsCpp": ("C++", "c++", "Allow generation of C++ database interface header (if not a Python node)"),
"nodeExclusionsPython": ("Python", "python", "Allow generation of Python database interface class"),
"nodeExclusionsDocs": ("Docs", "docs", "Allow generation of node documentation file"),
"nodeExclusionsTests": ("Tests", "tests", "Allow generation of node test scripts"),
"nodeExclusionsUsd": ("USD", "usd", "Allow generation of USD template file with node description"),
"nodeExclusionsTemplate": (
"Template",
"template",
"Allow generation of template file with sample node implementation in the chosen language",
),
}
# ================================================================================
def is_node_name_valid(tentative_node_name: str) -> bool:
"""Returns True if the tentative node name is legal"""
try:
ogn.check_node_name(tentative_node_name)
return True
except ogn.ParseError:
return False
# ================================================================================
def is_node_ui_name_valid(tentative_node_ui_name: str) -> bool:
"""Returns True if the tentative node name is legal"""
try:
ogn.check_node_ui_name(tentative_node_ui_name)
return True
except ogn.ParseError:
return False
# ================================================================================
class NodePropertiesModel:
"""
Manager for the node description data. Handles the data in both the raw and parsed OGN form.
The raw form is used wherever possible for more flexibility in editing, allowing temporarily illegal
data that can have notifications to the user for fixing (e.g. duplicate names)
External Properties:
description
error
memory_type
metadata
name
node_language
ogn_data
ogn_directory
ui_name
version
Internal Properties:
__name: Name of the node
__comments: List of comment fields found at the node level
__data: Raw node data dictionary, not including the attributes or tests
__error: Error found in parsing the top level node data
"""
def __init__(
self,
node_name: str,
extension: ogn.OmniGraphExtension,
node_data: Optional[Dict],
file_manager: Optional[FileManager],
):
"""
Create an initial node model.
Args:
node_name: Name of the node; will be checked
extension: Information regarding the extension to which the node belongs
node_data: Dictionary of node data, in the .ogn format
file_manager: File manager for OGN data
"""
self.__error = None
self.__name = None
self.__comments = {}
self.__extension = extension
self.__file_manager = file_manager
self.name = node_name
if node_data is None:
self.__data = {ogn.NodeTypeKeys.DESCRIPTION: "", ogn.NodeTypeKeys.VERSION: 1}
else:
for key, value in node_data.items():
if key and key[0] == "$":
self.__comments[key] = value
self.__data = {key: value for key, value in node_data.items() if len(key) == 0 or key[0] != "$"}
# ----------------------------------------------------------------------
def destroy(self):
"""Called when this model is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__comments = {}
self.__data = {}
self.__error = None
self.__name = None
# ----------------------------------------------------------------------
def ogn_interface(self):
"""Returns the extracted OGN node manager for this node's data, None if it cannot be parsed"""
return ogn.NodeInterfaceWrapper({self.__name: self.__data}, self.extension_name, None).node_interface
# ----------------------------------------------------------------------
@staticmethod
def edit_file(file_path: Optional[str]):
"""Try to launch the editor on the file, giving appropriate messaging if it fails
Raises:
AttributeError: Path is not defined
"""
if not file_path or not os.path.isfile(file_path):
log_warn(f"Could not edit non-existent file {file_path}")
return
settings = carb.settings.get_settings()
# Find out which editor it's necessary to use
# Check the settings
editor = settings.get("/app/editor")
if not editor:
# If settings doesn't have it, check the environment variable EDITOR.
# It's the standard way to set the editor in Linux.
editor = os.environ.get("EDITOR", None)
if not editor:
# VSCode is the default editor
editor = "code"
# Remove quotes because it's a common way for windows to specify paths
if editor[0] == '"' and editor[-1] == '"':
editor = editor[1:-1]
# Check if editor is not executable
if shutil.which(editor) is None:
log_warn(f"Editor not found '{editor}', switching to default editor")
editor = None
if not editor:
if os.name == "nt":
# All Windows have notepad
editor = "notepad"
else:
# Most Linux systems have gedit
editor = "gedit"
if os.name == "nt":
# Using cmd on the case the editor is bat or cmd file
call_command = ["cmd", "/c"]
else:
call_command = []
call_command.append(editor)
call_command.append(file_path)
# Non blocking call
try:
Popen(call_command) # noqa: PLR1732
except Exception as error: # noqa: PLW0703
log_warn(f"Could not edit file {file_path} - {error}")
# ----------------------------------------------------------------------
def save_node(self, on_save_done: OptionalCallback = None):
"""Save the OGN file"""
if not self.__file_manager:
log_error("Unable to save node: File manager is not initialized")
return
self.__file_manager.save(on_save_done)
# ----------------------------------------------------------------------
def save_as_node(self, on_save_as_done: OptionalCallback = None):
"""Save the OGN file"""
if not self.__file_manager:
log_error("Unable to save node: File manager is not initialized")
return
self.__file_manager.save(on_save_as_done, open_save_dialog=True)
# ----------------------------------------------------------------------
def generate_template(self):
"""Generate a template implementaiton based on the OGN file"""
if not self.__file_manager:
log_error("Unable to generate template: File manager is not initialized")
return
# Ensure nodes/ directory exists
os.makedirs(self.__file_manager.ogn_directory, exist_ok=True)
# Ensure .ogn file was saved
self.save_node()
if self.__file_manager.save_failed() or not self.__file_manager.ogn_path:
log_error("Save failed")
return
# Generate the template file
try:
node_interface = self.ogn_interface()
base_name, _ = os.path.splitext(os.path.basename(self.__file_manager.ogn_path))
configuration = ogn.GeneratorConfiguration(
self.__file_manager.ogn_path,
node_interface,
self.__extension.import_path,
self.__extension.import_path,
base_name,
self.__file_manager.ogn_directory,
ogn.OGN_PARSE_DEBUG,
)
except ogn.ParseError as error:
log_error(f"Could not parse .ogn file : {error}")
Prompt("Parse Failure", f"Could not parse .ogn file : {error}", "Okay").show()
return
try:
ogn.generate_template(configuration)
except ogn.NodeGenerationError as error:
log_error(f"Template file could not be generated : {error}")
Prompt("Generation Failure", f"Template file could not be generated : {error}", "Okay").show()
return
# ----------------------------------------------------------------------
def edit_node(self):
"""Edit the OGN file implementation in an external editor"""
ogt.dbg_ui("Edit the Node file")
try:
ogn_path = self.__file_manager.ogn_path
node_path = ogn_path.replace(".ogn", ".py")
if os.path.exists(node_path):
self.edit_file(node_path)
else:
node_path = ogn_path.replace(".py", ".cpp")
self.edit_file(node_path)
except AttributeError:
log_warn("Node file not found, generate a blank implementation first")
Prompt(
"Node File Missing",
"Node file does not exist. Please generate a blank implementation first.",
"Okay",
).show()
# ----------------------------------------------------------------------
def edit_ogn(self):
"""Edit the ogn file in an external editor"""
ogt.dbg_ui("Edit the OGN file")
try:
if self.__file_manager.ogn_path and os.path.exists(self.__file_manager.ogn_path):
self.edit_file(self.__file_manager.ogn_path)
else:
raise AttributeError(f'No such file "{self.__file_manager.ogn_path}"')
except AttributeError as error:
ogt.dbg_ui(f"OGN edit error {error}")
log_warn(f'.ogn file "{self.__file_manager.ogn_path}" does not exist. Please save the node first.')
Prompt(
"OGN File Missing",
f'.ogn file "{self.__file_manager.ogn_path}" does not exist. Please save the node first.',
"Okay",
).show()
# ----------------------------------------------------------------------
@property
def ogn_data(self):
"""Returns the raw OGN data for this node's definition, putting the comments back in place"""
main_data = self.__comments.copy()
main_data.update(self.__data)
return main_data
# ----------------------------------------------------------------------
@property
def extension_name(self):
"""Returns the name of the extension to which the node belongs"""
return self.__extension.extension_name if self.__extension is not None else ""
# ----------------------------------------------------------------------
@property
def error(self):
"""Returns the current parse errors in the object, if any"""
return self.__error
# ----------------------------------------------------------------------
@property
def description(self) -> str:
"""Returns the current node description as a single line of text"""
try:
description_data = self.__data[ogn.NodeTypeKeys.DESCRIPTION]
if isinstance(description_data, list):
description_data = " ".join(description_data)
except KeyError:
description_data = ""
return description_data
@description.setter
def description(self, new_description: str):
"""Sets the node description to a new value"""
self.__data[ogn.NodeTypeKeys.DESCRIPTION] = new_description
# ----------------------------------------------------------------------
@property
def name(self) -> str:
"""Returns the current node name as a single line of text"""
return self.__name
@name.setter
def name(self, new_name: str):
"""Sets the node name to a new value"""
try:
ogn.check_node_name(new_name)
self.__name = new_name
except ogn.ParseError as error:
self.__error = error
log_warn(f"Node name {new_name} is not legal - {error}")
# ----------------------------------------------------------------------
@property
def ui_name(self) -> str:
"""Returns the current user-friendly node name as a single line of text, default to empty string"""
try:
return self.metadata[ogn.NodeTypeKeys.UI_NAME]
except (AttributeError, KeyError):
return ""
@ui_name.setter
def ui_name(self, new_ui_name: str):
"""Sets the user-friendly node name to a new value"""
try:
ogn.check_node_ui_name(new_ui_name)
self.set_metadata_value(ogn.NodeTypeKeys.UI_NAME, new_ui_name, True)
except ogn.ParseError as error:
self.__error = error
log_warn(f"User-friendly node name {new_ui_name} is not legal - {error}")
# ----------------------------------------------------------------------
@property
def version(self) -> int:
"""Returns the current node version as a single line of text"""
try:
version_number = int(self.__data[ogn.NodeTypeKeys.VERSION])
except KeyError:
version_number = 1
return version_number
@version.setter
def version(self, new_version: int):
"""Sets the node version to a new value"""
self.__data[ogn.NodeTypeKeys.VERSION] = new_version
# ----------------------------------------------------------------------
@property
def memory_type(self) -> str:
"""Returns the current node memory type"""
try:
memory_type = self.__data[ogn.NodeTypeKeys.MEMORY_TYPE]
except KeyError:
memory_type = ogn.MemoryTypeValues.CPU
return memory_type
@memory_type.setter
def memory_type(self, new_memory_type: str):
"""Sets the node memory_type to a new value"""
ogn.check_memory_type(new_memory_type)
if new_memory_type == ogn.MemoryTypeValues.CPU:
# Leave out the memory type if it is the default
with suppress(KeyError):
del self.__data[ogn.NodeTypeKeys.MEMORY_TYPE]
else:
self.__data[ogn.NodeTypeKeys.MEMORY_TYPE] = new_memory_type
# ----------------------------------------------------------------------
@property
def node_language(self) -> str:
"""Returns the current node node language"""
try:
node_language = self.__data[ogn.NodeTypeKeys.LANGUAGE]
except KeyError:
node_language = ogn.LanguageTypeValues.CPP
return node_language
@node_language.setter
def node_language(self, new_node_language: str):
"""Sets the node node_language to a new value"""
ogn.check_node_language(new_node_language)
if new_node_language == ogn.LanguageTypeValues.CPP:
# Leave out the language type if it is the default
with suppress(KeyError):
del self.__data[ogn.NodeTypeKeys.LANGUAGE]
else:
self.__data[ogn.NodeTypeKeys.LANGUAGE] = new_node_language
# ----------------------------------------------------------------------
def excluded(self, file_type: str):
"""
Returns whethe the named file type will not be generated by this node.
These are not properties as it is more efficient to use a parameter since they are all in the same list.
"""
try:
exclude = file_type in self.__data[ogn.NodeTypeKeys.EXCLUDE]
except KeyError:
exclude = False
return exclude
def set_excluded(self, file_type: str, new_value: bool):
"""Sets whether the given file type will not be generated by this node"""
if new_value:
exclusions = self.__data.get(ogn.NodeTypeKeys.EXCLUDE, [])
exclusions = list(set(exclusions + [file_type]))
self.__data[ogn.NodeTypeKeys.EXCLUDE] = exclusions
else:
try:
exclusions = self.__data[ogn.NodeTypeKeys.EXCLUDE]
exclusions.remove(file_type)
# Remove the list itself if it becomes empty
if not exclusions:
del self.__data[ogn.NodeTypeKeys.EXCLUDE]
except KeyError:
pass
# ----------------------------------------------------------------------
@property
def metadata(self):
"""Returns the current metadata dictionary"""
try:
return self.__data[ogn.NodeTypeKeys.METADATA]
except KeyError:
return {}
def set_metadata_value(self, new_key: str, new_value: str, remove_if_empty: bool):
"""Sets a new value in the node's metadata
Args:
new_key: Metadata name
new_value: Metadata value
remove_if_empty: If True and the new_value is empty then delete the metadata value
"""
try:
self.__data[ogn.NodeTypeKeys.METADATA] = self.__data.get(ogn.NodeTypeKeys.METADATA, {})
if remove_if_empty and not new_value:
# Delete the metadata key if requested, cascading to the entire metadata dictionary if
# removing this key empties it.
try:
del self.__data[ogn.NodeTypeKeys.METADATA][new_key]
if not self.__data[ogn.NodeTypeKeys.METADATA]:
del self.__data[ogn.NodeTypeKeys.METADATA]
except KeyError:
pass
else:
self.__data[ogn.NodeTypeKeys.METADATA][new_key] = new_value
except (AttributeError, IndexError, TypeError, ogn.ParseError) as error:
raise AttributeError(str(error)) from error
@metadata.setter
def metadata(self, new_metadata: Dict[str, str]):
"""Wholesale replacement of the node's metadata"""
try:
if not new_metadata:
with suppress(KeyError):
del self.__data[ogn.NodeTypeKeys.METADATA]
else:
self.__data[ogn.NodeTypeKeys.METADATA] = new_metadata
except (AttributeError, IndexError, TypeError, ogn.ParseError) as error:
raise AttributeError(str(error)) from error
# ----------------------------------------------------------------------
@property
def file_manager(self) -> "FileManager":
"""Return the file manager on the current ogn"""
return self.__file_manager
# ----------------------------------------------------------------------
@file_manager.setter
def file_manager(self, file_manager: "FileManager"):
"""Sets the file manager on the current model"""
self.__file_manager = file_manager
# ----------------------------------------------------------------------
@property
def extension(self) -> ogn.OmniGraphExtension:
"""Return the extension information on the current model"""
return self.__extension
# ----------------------------------------------------------------------
@extension.setter
def extension(self, extension: ogn.OmniGraphExtension):
"""Sets the extension information on the current model"""
self.__extension = extension
# ================================================================================
class NodePropertiesController(ChangeManager):
"""Interface between the view and the model, making changes to the model on request
External Methods:
generate_template(self)
save_node(self)
edit_node(self)
edit_ogn(self)
External Properties:
description
filtered_metadata
memory_type
metadata
name
node_language
ui_name
version
Internal Properties:
__model: The model this class controls
"""
def __init__(self, model: NodePropertiesModel):
"""Initialize the controller with the model it will control"""
super().__init__()
self.__model = model
def destroy(self):
"""Called when this controller is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
super().destroy()
self.__model = None
# ----------------------------------------------------------------------
def generate_template(self):
"""Generate a template implementaiton based on the OGN file"""
self.__model.generate_template()
def save_node(self):
"""Save the OGN file"""
self.__model.save_node()
def save_as_node(self):
"""Save the OGN file in a new location"""
self.__model.save_as_node()
def edit_node(self):
"""Edit the OGN file implementation in an external editor"""
self.__model.edit_node()
def edit_ogn(self):
"""Edit the ogn file in an external editor"""
self.__model.edit_ogn()
# ----------------------------------------------------------------------
@property
def name(self) -> str:
"""Returns the fully namespaced name of this node"""
return self.__model.name
@name.setter
def name(self, new_name: str):
"""Renames the node
Raises:
ogn.ParseError: If the new name is not a legal node name
"""
ogt.dbg_ui(f"Change name from {self.name} to {new_name}")
self.__model.name = new_name
self.on_change()
# ----------------------------------------------------------------------
@property
def ui_name(self) -> str:
"""Returns the fully namespaced name of this node"""
return self.__model.ui_name
@ui_name.setter
def ui_name(self, new_ui_name: str):
"""Sets a new user-friendly name for the node
Raises:
ogn.ParseError: If the new name is not a legal node name
"""
ogt.dbg_ui(f"Change name from {self.name} to {new_ui_name}")
self.__model.ui_name = new_ui_name
self.on_change()
# ----------------------------------------------------------------------
@property
def description(self) -> str:
"""Returns the description of this node"""
return self.__model.description
@description.setter
def description(self, new_description: str):
"""Sets the description of this node"""
ogt.dbg_ui(f"Set description of {self.name} to {new_description}")
self.__model.description = new_description
self.on_change()
# ----------------------------------------------------------------------
@property
def version(self) -> str:
"""Returns the version number of this node"""
return self.__model.version
@version.setter
def version(self, new_version: str):
"""Sets the version number of this node"""
ogt.dbg_ui(f"Set version of {self.name} to {new_version}")
self.__model.version = new_version
self.on_change()
# ----------------------------------------------------------------------
@property
def memory_type(self) -> str:
"""Returns the current memory type for this node"""
return self.__model.memory_type
@memory_type.setter
def memory_type(self, new_memory_type: str):
"""Sets the current memory type for this node"""
self.__model.memory_type = new_memory_type
self.on_change()
# ----------------------------------------------------------------------
@property
def node_language(self) -> str:
"""Returns the current implementation language for this node"""
return self.__model.node_language
@node_language.setter
def node_language(self, new_node_language: str):
"""Sets the current implementation language for this node"""
self.__model.node_language = new_node_language
self.on_change()
# ----------------------------------------------------------------------
def excluded(self, file_type: str):
"""
Returns whethe the named file type will not be generated by this node.
These are not properties as it is more efficient to use a parameter since they are all in the same list.
"""
return self.__model.excluded(file_type)
def set_excluded(self, file_type: str, new_value: bool):
"""Sets whether the given file type will not be generated by this node"""
self.__model.set_excluded(file_type, new_value)
self.on_change()
# ----------------------------------------------------------------------
@property
def metadata(self):
"""Returns the current metadata dictionary"""
return self.__model.metadata
def set_metadata_value(self, new_key: str, new_value: str):
"""Sets a new value in the node's metadata"""
self.__model.set_metadata_value(new_key, new_value, new_key == ogn.NodeTypeKeys.UI_NAME)
self.on_change()
@metadata.setter
def metadata(self, new_metadata: Dict[str, str]):
"""Wholesale replacement of the node's metadata"""
self.__model.metadata = new_metadata
self.on_change()
# ----------------------------------------------------------------------
@property
def filtered_metadata(self):
"""Returns the current metadata, not including the metadata handled by separate UI elements"""
return {key: value for key, value in self.__model.metadata.items() if key not in FILTERED_METADATA}
@filtered_metadata.setter
def filtered_metadata(self, new_metadata: Dict[str, str]):
"""Wholesale replacement of the node's metadata, not including the metadata handled by separate UI elements"""
extra_metadata = {key: value for key, value in self.__model.metadata.items() if key in FILTERED_METADATA}
extra_metadata.update(new_metadata)
self.__model.metadata = extra_metadata
self.on_change()
# ================================================================================
class NodePropertiesView:
"""
Manage the UI elements for the node properties frame. Instantiated as part of the editor.
Internal Properties:
__controller: Controller for the node properties
__frame: Main frame for the node property interface
__managers: Dictionary of ID:Manager for the components of the node's frame
__subscriptions: Dictionary of ID:Subscription for the components of the node's frame
__widget_models: Dictionary of ID:Model for the components of the node's frame
__widgets: Dictionary of ID:Widget for the components of the node's frame
"""
def __init__(self, controller: NodePropertiesController):
"""Initialize the view with the controller it will use to manipulate the model"""
self.__controller = controller
assert self.__controller
self.__subscriptions = {}
self.__widgets = {}
self.__widget_models = {}
self.__managers = {}
self.__frame = ui.CollapsableFrame(title="Node Properties", collapsed=False)
self.__frame.set_build_fn(self.__rebuild_frame)
def destroy(self):
"""Called when the view is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
with suppress(AttributeError):
self.__frame.set_build_fn(None)
self.__controller = None
ogt.destroy_property(self, "__widget_models")
ogt.destroy_property(self, "__subscriptions")
ogt.destroy_property(self, "__widgets")
ogt.destroy_property(self, "__managers")
ogt.destroy_property(self, "__frame")
# ----------------------------------------------------------------------
def __on_description_changed(self, new_description: str):
"""Callback that runs when the node description was edited"""
ogt.dbg_ui(f"__on_description_changed({new_description})")
self.__controller.description = new_description
def __on_name_changed(self, new_name: str):
"""Callback that runs when the node name was edited"""
ogt.dbg_ui(f"__on_name_changed({new_name})")
self.__controller.name = new_name
def __on_ui_name_changed(self, new_ui_name: str):
"""Callback that runs when the user-friendly version of the node name was edited"""
ogt.dbg_ui(f"__on_name_changed({new_ui_name})")
self.__controller.ui_name = new_ui_name
def __on_version_changed(self, new_version: str):
"""Callback that runs when the node version was edited"""
ogt.dbg_ui(f"__on_version_changed({new_version})")
self.__controller.version = int(new_version)
def __on_exclusion_changed(self, widget_id: str, mouse_x: int, mouse_y: int, mouse_button: int, value: str):
"""Callback executed when there is a request to change exclusion status for one of the generated file types"""
ogt.dbg_ui(f"__on_exclusion_changed({widget_id}, {mouse_x}, {mouse_y}, {mouse_button}, {value})")
new_exclusion = self.__widgets[widget_id].model.as_bool
exclusion_changed = NODE_EXCLUSION_CHECKBOXES[widget_id][1]
self.__controller.set_excluded(exclusion_changed, new_exclusion)
# ----------------------------------------------------------------------
def __on_save_button(self):
"""Callback executed when the Save button is clicked"""
self.__controller.save_node()
# ----------------------------------------------------------------------
def __on_save_as_button(self):
"""Callback executed when the Save As button is clicked"""
self.__controller.save_as_node()
# ----------------------------------------------------------------------
def __on_generate_template_button(self):
"""Callback executed when the Generate button is clicked"""
ogt.dbg_ui("Generate Template Button Clicked")
self.__controller.generate_template()
# ----------------------------------------------------------------------
def __on_edit_ogn_button(self):
"""Callback executed with the Edit OGN button was pressed - launch the editor if the file exists"""
self.__controller.edit_ogn()
# ----------------------------------------------------------------------
def __on_edit_node_button(self):
"""Callback executed with the Edit Node button was pressed - launch the editor if the file exists"""
self.__controller.edit_node()
# ----------------------------------------------------------------------
def __register_ghost_info(self, ghost_info: GhostedWidgetInfo, widget_name: str, prompt_widget_name: str):
"""Add the ghost widget information to the model data"""
self.__subscriptions[widget_name + "_begin"] = ghost_info.begin_subscription
self.__subscriptions[widget_name + "_end"] = ghost_info.end_subscription
self.__widgets[widget_name] = ghost_info.widget
self.__widget_models[widget_name] = ghost_info.model
self.__widgets[prompt_widget_name] = ghost_info.prompt_widget
# ----------------------------------------------------------------------
def __build_controls_ui(self):
self.__widgets[ID_BTN_SAVE] = DestructibleButton(
"Save Node",
name=ID_BTN_SAVE,
tooltip=TOOLTIPS[ID_BTN_SAVE],
clicked_fn=self.__on_save_button,
)
self.__widgets[ID_BTN_SAVE_AS] = DestructibleButton(
"Save Node As...",
name=ID_BTN_SAVE_AS,
tooltip=TOOLTIPS[ID_BTN_SAVE_AS],
clicked_fn=self.__on_save_as_button,
)
self.__widgets[ID_BTN_GENERATE_TEMPLATE] = DestructibleButton(
"Generate Blank Implementation",
name=ID_BTN_GENERATE_TEMPLATE,
tooltip=TOOLTIPS[ID_BTN_GENERATE_TEMPLATE],
clicked_fn=self.__on_generate_template_button,
)
self.__widgets[ID_BTN_EDIT_OGN] = DestructibleButton(
"Edit .ogn",
name=ID_BTN_EDIT_OGN,
tooltip=TOOLTIPS[ID_BTN_EDIT_OGN],
clicked_fn=self.__on_edit_ogn_button,
)
self.__widgets[ID_BTN_EDIT_NODE] = DestructibleButton(
"Edit Node",
name=ID_BTN_EDIT_NODE,
tooltip=TOOLTIPS[ID_BTN_EDIT_NODE],
clicked_fn=self.__on_edit_node_button,
)
# ----------------------------------------------------------------------
def __build_name_ui(self):
"""Build the contents implementing the node name editing widget"""
ghost_info = ghost_text(
label="Name:",
tooltip=TOOLTIPS[ID_NODE_NAME],
widget_id=ID_NODE_NAME,
initial_value=self.__controller.name,
ghosted_text="Enter Node Name...",
change_callback=self.__on_name_changed,
validation=(is_node_name_valid, ogn.NODE_NAME_REQUIREMENT),
)
self.__register_ghost_info(ghost_info, ID_NODE_NAME, ID_NODE_NAME_PROMPT)
# ----------------------------------------------------------------------
def __build_ui_name_ui(self):
"""Build the contents implementing the user-friendly node name editing widget"""
ghost_info = ghost_text(
label="UI Name:",
tooltip=TOOLTIPS[ID_NODE_UI_NAME],
widget_id=ID_NODE_UI_NAME,
initial_value=self.__controller.ui_name,
ghosted_text="Enter User-Friendly Node Name...",
change_callback=self.__on_ui_name_changed,
validation=(is_node_ui_name_valid, ogn.NODE_UI_NAME_REQUIREMENT),
)
self.__register_ghost_info(ghost_info, ID_NODE_UI_NAME, ID_NODE_UI_NAME_PROMPT)
# ----------------------------------------------------------------------
def __build_description_ui(self):
"""Build the contents implementing the node description editing widget"""
ghost_info = ghost_text(
label="Description:",
tooltip=TOOLTIPS[ID_NODE_DESCRIPTION],
widget_id=ID_NODE_DESCRIPTION,
initial_value=self.__controller.description,
ghosted_text="Enter Node Description...",
change_callback=self.__on_description_changed,
)
self.__register_ghost_info(ghost_info, ID_NODE_DESCRIPTION, ID_NODE_DESCRIPTION_PROMPT)
# ----------------------------------------------------------------------
def __build_version_ui(self):
"""Build the contents implementing the node version editing widget"""
ghost_info = ghost_int(
label="Version:",
tooltip=TOOLTIPS[ID_NODE_VERSION],
widget_id=ID_NODE_VERSION,
initial_value=self.__controller.version,
ghosted_text="Enter Node Version Number...",
change_callback=self.__on_version_changed,
)
self.__register_ghost_info(ghost_info, ID_NODE_VERSION, ID_NODE_VERSION_PROMPT)
# ----------------------------------------------------------------------
def __build_memory_type_ui(self):
"""Build the contents implementing the node memory type editing widget"""
self.__managers[ID_NODE_MEMORY_TYPE] = MemoryTypeManager(self.__controller)
# ----------------------------------------------------------------------
def __build_node_language_ui(self):
"""Build the contents implementing the node language type editing widget"""
self.__managers[ID_NODE_LANGUAGE] = NodeLanguageManager(self.__controller)
# ----------------------------------------------------------------------
def __build_node_exclusions_ui(self):
"""Build the contents implementing the set of checkboxes selecting which files will be generated"""
if show_wip():
name_value_label("Generated By Build:", "Select the file types the node is allowed to generate")
with ui.VStack(**VSTACK_ARGS):
for checkbox_id, checkbox_info in NODE_EXCLUSION_CHECKBOXES.items():
with ui.HStack(spacing=10):
model = ui.SimpleIntModel(not self.__controller.excluded(checkbox_info[1]))
widget = ui.CheckBox(
model=model,
mouse_released_fn=partial(self.__on_exclusion_changed, checkbox_id),
name=checkbox_id,
width=0,
style_type_name_override="WhiteCheck",
)
ui.Label(checkbox_info[0], alignment=ui.Alignment.LEFT_CENTER, tooltip=checkbox_info[2])
self.__widgets[checkbox_id] = widget
self.__widget_models[checkbox_id] = widget
# ----------------------------------------------------------------------
def __build_metadata_ui(self):
"""Build the contents implementing the metadata value list"""
self.__managers[ID_MGR_NODE_METADATA] = MetadataManager(self.__controller)
# ----------------------------------------------------------------------
def __rebuild_frame(self):
"""Rebuild the contents underneath the main node frame"""
with ui.VStack(**VSTACK_ARGS):
with ui.HStack(width=0):
self.__build_controls_ui()
with name_value_hstack():
self.__build_name_ui()
with name_value_hstack():
self.__build_description_ui()
with name_value_hstack():
self.__build_version_ui()
with name_value_hstack():
self.__build_ui_name_ui()
with name_value_hstack():
self.__build_memory_type_ui()
with name_value_hstack():
self.__build_node_language_ui()
with name_value_hstack():
self.__build_node_exclusions_ui()
with name_value_hstack():
self.__build_metadata_ui()
| 41,490 | Python | 40.532532 | 118 | 0.543938 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/attribute_properties.py | """
Collection of classes managing the Model-View-Controller paradigm for individual attributes within the node.
This attribute information is collected with the node information later to form the combined .ogn file.
""" # noqa: PLC0302
import json
from contextlib import suppress
from functools import partial
from typing import Dict, List, Optional
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_warn
from omni import ui
from ..style import VSTACK_ARGS # noqa: PLE0402
from ..style import name_value_hstack # noqa: PLE0402
from ..style import name_value_label # noqa: PLE0402
from .attribute_base_type_manager import AttributeBaseTypeManager
from .attribute_tuple_count_manager import AttributeTupleCountManager
from .attribute_union_type_adder_manager import ID_ATTR_UNION_TYPE_ADDER, AttributeUnionTypeAdderManager
from .change_management import ChangeManager, ChangeMessage, RenameMessage
from .memory_type_manager import MemoryTypeManager
from .metadata_manager import MetadataManager
from .ogn_editor_utils import DestructibleButton, GhostedWidgetInfo, find_unique_name, ghost_text
# ======================================================================
# List of metadata elements that will not be edited directly in the "Metadata" section.
FILTERED_METADATA = [ogn.AttributeKeys.UI_NAME]
# ======================================================================
# ID values for widgets that are editable or need updating
ID_ATTR_BASE_TYPE = "attributeBaseType"
ID_ATTR_DEFAULT = "attributeDefault"
ID_ATTR_DEFAULT_PROMPT = "attributeDefaultPrompt"
ID_ATTR_DESCRIPTION = "attributeDescription"
ID_ATTR_DESCRIPTION_PROMPT = "attributeDescriptionPrompt"
ID_ATTR_MAXIMUM = "attributeMaximum"
ID_ATTR_MEMORY_TYPE = "attributeMemoryType"
ID_ATTR_MINIMUM = "attributeMinium"
ID_ATTR_UNION_TYPES = "attributeUnionTypes"
ID_ATTR_UNION_TYPES_PROMPT = "attributeUnionTypesPrompt"
ID_ATTR_NAME = "attributeName"
ID_ATTR_NAME_PROMPT = "attributeNamePrompt"
ID_UI_ATTR_NAME = "attributeUiName"
ID_UI_ATTR_NAME_PROMPT = "attributeUiNamePrompt"
ID_ATTR_OPTIONAL = "attributeOptional"
ID_ATTR_TUPLE_COUNT = "attributeTupleCount"
ID_ATTR_TYPE = "attributeType"
ID_ATTR_TYPE_ARRAY_DEPTH = "attributeTypeIsArray"
ID_ATTR_TYPE_BASE_TYPE = "attributeTypeBaseType"
# ======================================================================
# ID for frames that will be dynamically rebuild
ID_ATTR_FRAME_TYPE = "attributeTypeFrame"
ID_ATTR_FRAME_RANGE = "attributeRange"
ID_ATTR_FRAME_UNION_TYPES = "attributeUnionTypesFrame"
# ======================================================================
# ID for dictionary of classes that manage subsections of the editor, named for their class
ID_MGR_ATTR_METADATA = "AttributeMetadataManager"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {
ID_ATTR_BASE_TYPE: "Base type of an attribute's data",
ID_ATTR_DEFAULT: "Default value of the attribute when none has been set",
ID_ATTR_DESCRIPTION: "Description of what information the attribute holds",
ID_ATTR_FRAME_RANGE: "Lowest and highest values the attribute is allowed to take",
ID_ATTR_FRAME_TYPE: "Properties defining the type of data the attribute manages",
ID_ATTR_MAXIMUM: "Maximum value of the attribute or attribute component",
ID_ATTR_MEMORY_TYPE: "Type of memory in which the attribute's data will reside",
ID_ATTR_MINIMUM: "Minimum value of the attribute or attribute component",
ID_ATTR_NAME: "Name of the attribute (without the inputs: or outputs: namespace)",
ID_ATTR_OPTIONAL: "Can the attribute be left off the node and still have it operate correctly?",
ID_ATTR_TUPLE_COUNT: "Number of base elements in the attribute",
ID_ATTR_TYPE: "Type of data the attribute holds",
ID_ATTR_UNION_TYPES: "Accepted union types if the attribute is a union",
ID_ATTR_TYPE_ARRAY_DEPTH: "Is the attribute data an array of elements?",
ID_ATTR_TYPE_BASE_TYPE: "Basic data elements in the attribute data",
ID_UI_ATTR_NAME: "User-friendly name for the attribute",
}
# ================================================================================
def attribute_key_from_group(attribute_group: str) -> str:
"""Returns the name of the attribute group key to use at the node level of the .ogn file"""
if attribute_group == ogn.INPUT_GROUP:
attribute_group_key = ogn.NodeTypeKeys.INPUTS
elif attribute_group == ogn.OUTPUT_GROUP:
attribute_group_key = ogn.NodeTypeKeys.OUTPUTS
else:
attribute_group_key = ogn.NodeTypeKeys.STATE
return attribute_group_key
# ================================================================================
def is_attribute_name_valid(attribute_group: str, tentative_attr_name: str) -> bool:
"""Returns True if the tentative attribute name is legal in the given group's namespace"""
try:
ogn.check_attribute_name(
ogn.attribute_name_in_namespace(tentative_attr_name, ogn.namespace_of_group(attribute_group))
)
return True
except ogn.ParseError:
return False
# ================================================================================
def is_attribute_ui_name_valid(tentative_attr_ui_name: str) -> bool:
"""Returns True if the tentative attribute name is legal"""
try:
ogn.check_attribute_ui_name(tentative_attr_ui_name)
return True
except ogn.ParseError:
return False
# ================================================================================
class AttributeAddedMessage(ChangeMessage):
"""Encapsulation of a message sent just after an attribute is added"""
def __init__(self, caller, attribute_name: str, attribute_group: str):
"""Set up a message with information needed to indicate an attribute addition"""
super().__init__(caller)
self.attribute_name = attribute_name
self.attribute_group = attribute_group
def __str__(self) -> str:
"""Returns a human-readable representation of the add information"""
caller_info = super().__str__()
namespace = ogn.namespace_of_group(self.attribute_group)
return f"Add {namespace}:{self.attribute_name} (from {caller_info})"
# ================================================================================
class AttributeRemovedMessage(ChangeMessage):
"""Encapsulation of a message sent just before an attribute is removed"""
def __init__(self, caller, attribute_name: str, attribute_group: str):
"""Set up a message with information needed to indicate an attribute removal"""
super().__init__(caller)
self.attribute_name = attribute_name
self.attribute_group = attribute_group
def __str__(self) -> str:
"""Returns a human-readable representation of the removal information"""
caller_info = super().__str__()
namespace = ogn.namespace_of_group(self.attribute_group)
return f"Remove {namespace}:{self.attribute_name} (from {caller_info})"
# ================================================================================
class AttributePropertiesModel:
"""
Manager for the attribute description data. Handles the data in both the raw and parsed OGN form.
The raw form is used wherever possible for more flexibility in editing, allowing temporarily illegal
data that can have notifications to the user for fixing (e.g. duplicate names)
External Properties:
array_depth
array_depths_supported
attribute_group
attribute_manager
base_name
default
description
full_type
is_output
maximum
memory_type
metadata
minimum
name
ogn_data
optional
tuple_count
tuples_supported
ui_name
union_types
Internal Properties:
__attribute_group: Enum with the attribute's group (input, output, or state)
__data: Raw attribute data dictionary
__error: Error found in parsing the attribute data
__name: Name of the attribute without the inputs: or outputs: namespace
__namespace: The inputs: or outputs: namespace of the attribute when checking the name
"""
def __init__(self, raw_attribute_name: str, attribute_group: str, attribute_data: Dict):
"""
Create an initial attribute model.
Args:
raw_attribute_name: Raw name of the attribute, may or may not be namespaced as input or output
_attribute_group: Is the attribute an output?
attribute_data: Dictionary of attribute data, in the .ogn format
"""
try:
self.__attribute_group = attribute_group
self.__data = attribute_data
self.__namespace = ogn.namespace_of_group(attribute_group)
self.__name = raw_attribute_name
except ogn.ParseError as error:
self.__error = error
# ----------------------------------------------------------------------
def ogn_interface(self):
"""Returns the extracted OGN attribute manager for this attribute's data, None if it cannot be parsed"""
try:
return ogn.get_attribute_manager(
ogn.attribute_name_in_namespace(self.__name, ogn.namespace_of_group(self.__attribute_group)),
attribute_data=self.__data,
)
except ogn.ParseError as error:
self.__error = error
return None
# ----------------------------------------------------------------------
@property
def ogn_data(self):
"""Returns the raw OGN data for this attribute's definition"""
return {self.__name: self.__data}
# ----------------------------------------------------------------------
@property
def attribute_group(self) -> str:
"""Returns the type of group to which this attribute belongs"""
return self.__attribute_group
# ----------------------------------------------------------------------
@property
def name(self) -> str:
"""Returns the current attribute name"""
return self.__name
@name.setter
def name(self, new_name: str):
"""Modifies the name of this attribute
Raises:
AttributeError: If the name was illegal or already taken
"""
try:
ogn.check_attribute_name(ogn.attribute_name_in_namespace(new_name, self.__namespace))
self.__name = new_name
except ogn.ParseError as error:
log_warn(f"Attribute name {new_name} is not legal - {error}")
# ----------------------------------------------------------------------
@property
def ui_name(self) -> str:
"""Returns the current user-friendly attribute name"""
try:
return self.metadata[ogn.AttributeKeys.UI_NAME]
except (AttributeError, KeyError):
return ""
@ui_name.setter
def ui_name(self, new_ui_name: str):
"""Modifies the user-friendly name of this attribute"""
try:
ogn.check_attribute_ui_name(new_ui_name)
self.set_metadata_value(ogn.AttributeKeys.UI_NAME, new_ui_name, True)
except ogn.ParseError as error:
self.__error = error
log_warn(f"User-friendly attribute name {new_ui_name} is not legal - {error}")
# ----------------------------------------------------------------------
@property
def description(self) -> str:
"""Returns the current attribute description as a single line of text"""
try:
description_data = self.__data[ogn.AttributeKeys.DESCRIPTION]
if isinstance(description_data, list):
description_data = " ".join(description_data)
except KeyError:
description_data = ""
return description_data
@description.setter
def description(self, new_description: str):
"""Sets the attribute description to a new value"""
self.__data[ogn.AttributeKeys.DESCRIPTION] = new_description
# ----------------------------------------------------------------------
@property
def attribute_manager(self) -> ogn.AttributeManager:
"""Returns the class type that this attribute uses to manage its properties. Changes when base type changes"""
try:
return ogn.ALL_ATTRIBUTE_TYPES[self.base_type]
except KeyError:
return None
# ----------------------------------------------------------------------
@property
def base_type(self) -> str:
"""Returns the current base data type for this attribute"""
try:
attribute_type = self.__data[ogn.AttributeKeys.TYPE]
attribute_type_name, _, _, _ = ogn.split_attribute_type_name(attribute_type)
except (KeyError, ogn.ParseError) as error:
log_warn(f"Type not parsed for {self.name} - {error}, defaulting to integer")
attribute_type_name = "int"
return attribute_type_name
@base_type.setter
def base_type(self, new_base_type: str):
"""Sets the current base data type for this attribute. Resets tuple and array information if needed."""
try:
_, tuple_count, array_depth, extra_info = ogn.split_attribute_type_name(self.__data[ogn.AttributeKeys.TYPE])
manager = ogn.ALL_ATTRIBUTE_TYPES[new_base_type]
if tuple_count not in manager.tuples_supported():
new_tuple_count = manager.tuples_supported()[0]
log_warn(f"Old tuple count of {tuple_count} not supported, defaulting to {new_tuple_count}")
tuple_count = new_tuple_count
if array_depth not in manager.array_depths_supported():
new_array_depth = manager.array_depths_supported()[0]
log_warn(f"Old array depth of {array_depth} not supported, defaulting to {new_array_depth}")
array_depth = new_array_depth
ogn.validate_attribute_type_name(new_base_type, tuple_count, array_depth)
self.full_type = ogn.assemble_attribute_type_name(new_base_type, tuple_count, array_depth, extra_info)
except (KeyError, ogn.ParseError) as error:
log_warn(f"Type not parsed for {self.name} - {error}, defaulting to integer")
self.full_type = ogn.assemble_attribute_type_name("int", 1, 0)
# ----------------------------------------------------------------------
@property
def tuple_count(self) -> int:
"""Returns the current tuple count for this attribute"""
try:
attribute_type = self.__data[ogn.AttributeKeys.TYPE]
_, tuple_count, _, _ = ogn.split_attribute_type_name(attribute_type)
except (KeyError, ogn.ParseError) as error:
log_warn(f"Type not parsed for {self.name} - {error}, defaulting to integer")
tuple_count = 1
return tuple_count
@tuple_count.setter
def tuple_count(self, new_tuple_count: int):
"""Sets the current tuple count for this attribute"""
try:
attribute_type_name, _, array_depth, extra_info = ogn.split_attribute_type_name(self.full_type)
self.full_type = ogn.assemble_attribute_type_name(
attribute_type_name, new_tuple_count, array_depth, extra_info
)
except ogn.ParseError as error:
log_warn(f"Tuple count {new_tuple_count} not supported on {self.name}, {error}")
@property
def tuples_supported(self) -> List[int]:
"""Returns the list of tuple counts this attribute type permits"""
try:
return self.attribute_manager.tuples_supported()
except (KeyError, ogn.ParseError) as error:
log_warn(f"Type not parsed for tuple counts on {self.name} - {error}, assuming only 1")
tuple_counts = [1]
return tuple_counts
# ----------------------------------------------------------------------
@property
def array_depth(self) -> int:
"""Returns the array depth of this attribute"""
try:
attribute_type = self.__data[ogn.AttributeKeys.TYPE]
_, _, array_depth, _ = ogn.split_attribute_type_name(attribute_type)
except (KeyError, ogn.ParseError) as error:
log_warn(f"Type not parsed for {self.name} - {error}, defaulting to integer")
array_depth = 0
return array_depth
@array_depth.setter
def array_depth(self, new_array_depth: int):
"""Sets the current array depth for this attribute"""
try:
attribute_type_name, tuple_count, _, extra_info = ogn.split_attribute_type_name(self.full_type)
self.full_type = ogn.assemble_attribute_type_name(
attribute_type_name, tuple_count, new_array_depth, extra_info
)
except ogn.ParseError as error:
log_warn(f"Array depth {new_array_depth} not supported on {self.name}, {error}")
@property
def array_depths_supported(self) -> List[int]:
"""Returns the list of array depth counts this attribute type permits"""
try:
return self.attribute_manager.array_depths_supported()
except (KeyError, ogn.ParseError) as error:
log_warn(f"Type not parsed for tuple counts on {self.name} - {error}, assuming only 1")
tuple_counts = [1]
return tuple_counts
# ----------------------------------------------------------------------
@property
def full_type(self) -> str:
"""Returns the combined type/tuple_count/array_depth representation for this attribute"""
try:
attribute_type = self.__data[ogn.AttributeKeys.TYPE]
except KeyError:
log_warn(f"Type not found for {self.name}, defaulting to integer")
attribute_type = "int"
return attribute_type
@full_type.setter
def full_type(self, new_type: str):
"""Sets the attribute information based on the fully qualified type name"""
# Splitting the type has the side effect of verifying the component parts and their combination
try:
_ = ogn.split_attribute_type_name(new_type)
self.__data[ogn.AttributeKeys.TYPE] = new_type
self.validate_default()
except ogn.ParseError as error:
log_warn(f"Type '{new_type}' on attribute '{self.name}' is invalid - {error}")
# ----------------------------------------------------------------------
@property
def memory_type(self) -> str:
"""Returns the current node memory type"""
try:
memory_type = self.__data[ogn.AttributeKeys.MEMORY_TYPE]
except KeyError:
memory_type = ogn.MemoryTypeValues.CPU
return memory_type
@memory_type.setter
def memory_type(self, new_memory_type: str):
"""Sets the node memory_type to a new value"""
ogn.check_memory_type(new_memory_type)
if new_memory_type == ogn.MemoryTypeValues.CPU:
# Leave out the memory type if it is the default
with suppress(KeyError):
del self.__data[ogn.AttributeKeys.MEMORY_TYPE]
else:
self.__data[ogn.AttributeKeys.MEMORY_TYPE] = new_memory_type
# ----------------------------------------------------------------------
@property
def metadata(self):
"""Returns the current metadata dictionary"""
try:
return self.__data[ogn.AttributeKeys.METADATA]
except KeyError:
return {}
def set_metadata_value(self, new_key: str, new_value: str, remove_if_empty: bool):
"""Sets a new value in the attribute's metadata
Args:
new_key: Metadata name
new_value: Metadata value
remove_if_empty: If True and the new_value is empty then delete the metadata value
"""
try:
self.__data[ogn.AttributeKeys.METADATA] = self.__data.get(ogn.AttributeKeys.METADATA, {})
if remove_if_empty and not new_value:
# Delete the metadata key if requested, cascading to the entire metadata dictionary if
# removing this key empties it.
with suppress(KeyError):
del self.__data[ogn.AttributeKeys.METADATA][new_key]
if not self.__data[ogn.AttributeKeys.METADATA]:
del self.__data[ogn.AttributeKeys.METADATA]
else:
self.__data[ogn.AttributeKeys.METADATA][new_key] = new_value
except (AttributeError, IndexError, TypeError, ogn.ParseError) as error:
raise AttributeError(str(error)) from error
@metadata.setter
def metadata(self, new_metadata: Dict[str, str]):
"""Wholesale replacement of the attribute's metadata"""
try:
if not new_metadata:
with suppress(KeyError):
del self.__data[ogn.AttributeKeys.METADATA]
else:
self.__data[ogn.AttributeKeys.METADATA] = new_metadata
except (AttributeError, IndexError, TypeError, ogn.ParseError) as error:
raise AttributeError(str(error)) from error
# ----------------------------------------------------------------------
@property
def minimum(self):
"""Returns the current minimum value of the attribute, None if it is not set"""
try:
return self.__data[ogn.AttributeKeys.MINIMUM]
except KeyError:
return None
@minimum.setter
def minimum(self, new_minimum):
"""Sets the new minimum value of the attribute, removing it if the new value is None"""
if new_minimum is None:
with suppress(KeyError):
del self.__data[ogn.AttributeKeys.MINIMUM]
else:
self.__data[ogn.AttributeKeys.MINIMUM] = new_minimum
# ----------------------------------------------------------------------
@property
def maximum(self):
"""Returns the current maximum value of the attribute, None if it is not set"""
try:
return self.__data[ogn.AttributeKeys.MAXIMUM]
except KeyError:
return None
@maximum.setter
def maximum(self, new_maximum):
"""Sets the new maximum value of the attribute, removing it if the new value is None"""
if new_maximum is None:
with suppress(KeyError):
del self.__data[ogn.AttributeKeys.MAXIMUM]
else:
self.__data[ogn.AttributeKeys.MAXIMUM] = new_maximum
# ----------------------------------------------------------------------
@property
def union_types(self) -> List[str]:
"""Returns the accepted union types value of the attribute, [] if it is not set"""
return self.full_type if self.base_type == "union" else []
@union_types.setter
def union_types(self, new_union_types: List[str]):
"""Sets the new accepted union types of the attribute, removing it if the new value is None"""
if self.base_type != "union":
return
if not new_union_types:
self.full_type = []
else:
self.full_type = new_union_types
# ----------------------------------------------------------------------
@property
def default(self):
"""Returns the current default value of the attribute, None if it is not set"""
try:
return self.__data[ogn.AttributeKeys.DEFAULT]
except KeyError:
return None
def validate_default(self):
"""Checks that the current default is valid for the current attribute type, resetting to empty if not"""
ogt.dbg_ui(f"Validating default {self.default} on type {self.full_type}")
try:
manager = ogn.get_attribute_manager_type(self.full_type)
if self.default is None and not manager.requires_default():
return
except (AttributeError, ogn.ParseError) as error:
# If the manager cannot be retrieved no validation can happen; trivial acceptance
ogt.dbg_ui(f"Could not retrieve manager for default value validation - {error}")
return
try:
manager.validate_value_structure(self.default)
ogt.dbg_ui("...the current default is okay")
except (AttributeError, ogn.ParseError):
empty_default = manager.empty_value()
log_warn(
f"Current default value of {self.default} is invalid, setting it to an empty value {empty_default}"
)
self.default = json.dumps(empty_default)
@default.setter
def default(self, new_default: str):
"""Sets the new default value of the attribute, removing it if the new value is None"""
ogt.dbg_ui(f"Setting new default to {new_default} on {self.ogn_data}")
# For deleting the default it has to be removed. For setting a new value the attribute manager
# will be created for validation and it should not have an existing value in that case.
try:
original_default = self.__data[ogn.AttributeKeys.DEFAULT]
del self.__data[ogn.AttributeKeys.DEFAULT]
except KeyError:
original_default = None
if new_default is None:
return
try:
# Use the JSON library to decode the string into Python types
try:
default_as_json = json.loads(new_default)
except json.decoder.JSONDecodeError as error:
raise AttributeError(f"Could not parse default '{new_default}'") from error
# Create a temporary attribute manager for validating data
try:
self.__data[ogn.AttributeKeys.DEFAULT] = default_as_json
original_default = None
temp_manager = self.ogn_interface()
temp_manager.validate_value_structure(default_as_json)
except AttributeError as error:
raise AttributeError(f"Current data for {self.name} cannot be parsed - {self.__error}.") from error
except ogn.ParseError as error:
raise AttributeError(f"New default for {self.name} is not valid.") from error
except Exception as error:
raise AttributeError(f"Unknown error setting default on {self.name}") from error
except AttributeError as error:
log_warn(str(error))
if original_default is not None:
self.__data[ogn.AttributeKeys.DEFAULT] = original_default
# ----------------------------------------------------------------------
@property
def optional(self) -> bool:
"""Returns the current optional flag on the attribute"""
try:
return self.__data[ogn.AttributeKeys.OPTIONAL]
except KeyError:
return False
@optional.setter
def optional(self, new_optional: bool):
"""Sets the new optional flag on the attribute"""
if new_optional:
with suppress(KeyError):
del self.__data[ogn.AttributeKeys.OPTIONAL]
else:
self.__data[ogn.AttributeKeys.OPTIONAL] = new_optional
# ================================================================================
class AttributePropertiesController(ChangeManager):
"""Interface between the view and the model, making changes to the model on request
External Properties:
array_depth
array_depths_supported
attribute_manager
base_name
default
description
filtered_metadata
full_type
base_type
is_output
maximum
memory_type
metadata
minimum
name
ogn_data
optional
tuple_count
tuples_supported
ui_name
union_types
Internal Properties:
_model: The model this class controls
__parent_controller: Controller for the list of properties, for changing membership callbacks
"""
def __init__(self, model: AttributePropertiesModel, parent_controller):
"""Initialize the controller with the model it will control"""
super().__init__()
self._model = model
self.__parent_controller = parent_controller
def destroy(self):
"""Called when the view is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
super().destroy()
self._model = None
self.__parent_controller = None
# ----------------------------------------------------------------------
def on_int_minimum_changed(self, new_value: ui.SimpleIntModel):
"""Callback executed when the minimum value of the attribute was changed"""
self._model.minimum = new_value.as_int
self.on_change()
# ----------------------------------------------------------------------
def on_int_maximum_changed(self, new_value: ui.SimpleIntModel):
"""Callback executed when the maximum value of the attribute was changed"""
self._model.maximum = new_value.as_int
self.on_change()
# ----------------------------------------------------------------------
def on_float_minimum_changed(self, new_value: ui.SimpleFloatModel):
"""Callback executed when the minimum value of the attribute was changed"""
self._model.minimum = new_value.as_float
self.on_change()
# ----------------------------------------------------------------------
def on_float_maximum_changed(self, new_value: ui.SimpleFloatModel):
"""Callback executed when the maximum value of the attribute was changed"""
self._model.maximum = new_value.as_float
self.on_change()
# ----------------------------------------------------------------------
def on_remove_attribute(self):
"""Callback that executes when the view wants to remove the named attribute"""
ogt.dbg_ui(f"Removing an existing attribute {self.name}")
self.__parent_controller.on_remove_attribute(self)
# ----------------------------------------------------------------------
@property
def attribute_manager(self) -> ogn.AttributeManager:
"""Returns the class type that this attribute uses to manage its properties. May change when type changes"""
return self._model.attribute_manager
# ----------------------------------------------------------------------
@property
def attribute_group(self) -> str:
"""Returns the type of group to which this attribute belongs"""
return self._model.attribute_group
# ----------------------------------------------------------------------
def is_output(self) -> bool:
"""Returns whether this attribute is an output or not"""
return self._model.is_output
# ----------------------------------------------------------------------
@property
def name(self) -> str:
"""Returns the base name (without the inputs: or outputs: namespace) of this attribute"""
return self._model.name
@name.setter
def name(self, new_name: str) -> str:
"""Modifies the name of this attribute
Raises:
AttributeError: If the name was illegal or already taken
"""
# The parent controller gets dibs on the name change as it may refuse to do it due to duplication
self.__parent_controller.on_name_change(self._model.name, new_name)
name_change_message = RenameMessage(self, self._model.name, new_name)
self._model.name = new_name
self.on_change(name_change_message)
@property
def namespace(self) -> str:
"""Returns the implicit namespace (inputs: or outputs:) of this attribute"""
return self._model._namespace # noqa: PLW0212
# ----------------------------------------------------------------------
@property
def ui_name(self) -> str:
"""Returns the user-friendly name of this attribute"""
return self._model.ui_name
@ui_name.setter
def ui_name(self, new_ui_name: str) -> str:
"""Modifies the user-friendly name of this attribute
Raises:
AttributeError: If the name was illegal
"""
self._model.ui_name = new_ui_name
self.on_change()
# ----------------------------------------------------------------------
@property
def description(self) -> str:
"""Returns the description of this attribute"""
return self._model.description
@description.setter
def description(self, new_description: str):
"""Sets the description of this attribute"""
ogt.dbg_ui(f"Set description of {self.name} to {new_description}")
self._model.description = new_description
self.on_change()
# ----------------------------------------------------------------------
@property
def base_type(self) -> str:
"""Returns the current base data type for this attribute"""
return self._model.base_type
@base_type.setter
def base_type(self, new_base_type: str):
"""Sets the current base data base type for this attribute"""
self._model.base_type = new_base_type
self.on_change()
# ----------------------------------------------------------------------
@property
def tuple_count(self) -> int:
"""Returns the current tuple count for this attribute"""
return self._model.tuple_count
@tuple_count.setter
def tuple_count(self, new_tuple_count: int):
"""Sets the current tuple count for this attribute"""
self._model.tuple_count = new_tuple_count
self.on_change()
@property
def tuples_supported(self) -> List[int]:
"""Returns the list of tuple counts this attribute type permits"""
return self._model.tuples_supported
# ----------------------------------------------------------------------
@property
def array_depth(self) -> int:
"""Returns the array depth of this attribute"""
return self._model.array_depth
@array_depth.setter
def array_depth(self, new_array_depth: int):
"""Sets the current array depth for this attribute"""
self._model.array_depth = new_array_depth
self.on_change()
@property
def array_depths_supported(self) -> List[int]:
"""Returns the list of array depths this attribute type permits"""
return self._model.array_depths_supported
# ----------------------------------------------------------------------
@property
def memory_type(self) -> str:
"""Returns the current memory type for this attribute"""
return self._model.memory_type
@memory_type.setter
def memory_type(self, new_memory_type: str):
"""Sets the current memory type for this attribute"""
self._model.memory_type = new_memory_type
self.on_change()
# ----------------------------------------------------------------------
@property
def metadata(self):
"""Returns the current metadata dictionary"""
return self._model.metadata
def set_metadata_value(self, new_key: str, new_value: str):
"""Sets a new value in the attribute's metadata"""
self._model.set_metadata_value(new_key, new_value)
self.on_change()
@metadata.setter
def metadata(self, new_metadata: Dict[str, str]):
"""Wholesale replacement of the attribute's metadata"""
self._model.metadata = new_metadata
self.on_change()
# ----------------------------------------------------------------------
@property
def filtered_metadata(self):
"""Returns the current metadata, not including the metadata handled by separate UI elements"""
return {key: value for key, value in self._model.metadata.items() if key not in FILTERED_METADATA}
@filtered_metadata.setter
def filtered_metadata(self, new_metadata: Dict[str, str]):
"""Wholesale replacement of the node's metadata, not including the metadata handled by separate UI elements"""
extra_metadata = {key: value for key, value in self._model.metadata.items() if key in FILTERED_METADATA}
extra_metadata.update(new_metadata)
self._model.metadata = extra_metadata
self.on_change()
# ----------------------------------------------------------------------
@property
def default(self) -> str:
"""Returns the default value of this attribute"""
return self._model.default
@default.setter
def default(self, new_default: str):
"""Sets the default value of this attribute"""
ogt.dbg_ui(f"Set default value of {self.name} to {new_default}")
self._model.default = new_default
self.on_change()
# ----------------------------------------------------------------------
@property
def optional(self) -> str:
"""Returns the optional flag for this attribute"""
return self._model.optional
@optional.setter
def optional(self, new_optional: str):
"""Sets the optional flag for this attribute"""
ogt.dbg_ui(f"Set optional of {self.name} to {new_optional}")
self._model.optional = new_optional
self.on_change()
# ----------------------------------------------------------------------
@property
def union_types(self) -> List[str]:
"""Returns the accepted union types of this attribute"""
return self._model.union_types
@union_types.setter
def union_types(self, new_union_types: List[str]):
"""Sets the accepted union types for this attribute"""
self._model.union_types = new_union_types
self.on_change()
# ================================================================================
class AttributePropertiesView:
"""UI for a single attribute's data
Internal Properties:
_controller: The controller used to manipulate the model's data
_frame: Main frame for this attribute's interface
_widgets: Dictionary of ID:Widget for the components of the attribute's frame
"""
def __init__(self, controller: AttributePropertiesController):
"""Initialize the view with the controller it will use to manipulate the model"""
self.__controller = controller
self.__subscriptions = {}
self.__type_managers = {}
self.__type_subscriptions = {}
self.__type_widgets = {}
self.__widgets = {}
self.__widget_models = {}
self.__managers = {}
with ui.HStack(spacing=0):
self.__remove_button = DestructibleButton(
width=20,
height=20,
style_type_name_override="RemoveElement",
clicked_fn=self._on_remove_attribute,
tooltip="Remove this attribute",
)
assert self.__remove_button
self.__frame = ui.CollapsableFrame(title=self.__controller.name, collapsed=False)
self.__frame.set_build_fn(self.__rebuild_frame)
def destroy(self):
"""Reset all of the attribute's widgets and delete the main frame (done when the attribute is removed)"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
with suppress(AttributeError, ValueError):
self.__controller.remove_change_callback(self.__on_controller_change)
self.__controller = None
self.destroy_frame_contents()
with suppress(AttributeError):
self.__frame.set_build_fn(None)
ogt.destroy_property(self, "__remove_button")
ogt.destroy_property(self, "__frame")
def destroy_frame_contents(self):
"""Destroy just the widgets within the attribute's frame, for rebuilding"""
self.destroy_type_ui_frame()
with suppress(AttributeError, KeyError):
self.__widgets[ID_ATTR_FRAME_RANGE].set_build_fn(None)
with suppress(AttributeError, KeyError):
self.__widgets[ID_ATTR_FRAME_TYPE].set_build_fn(None)
ogt.destroy_property(self, "__subscriptions")
ogt.destroy_property(self, "__managers")
ogt.destroy_property(self, "__widgets")
ogt.destroy_property(self, "__widget_models")
def destroy_type_ui_frame(self):
"""Gracefully release references to elements that are part of the type specification frame"""
ogt.destroy_property(self, "__type_managers")
ogt.destroy_property(self, "__type_subscriptions")
ogt.destroy_property(self, "__type_widgets")
# ----------------------------------------------------------------------
def __on_attribute_description_changed(self, new_description: str):
"""Callback that runs when the attribute description was edited"""
ogt.dbg_ui(f"_on_attribute_description_changed({new_description})")
self.__controller.description = new_description
def __on_attribute_name_changed(self, new_name: str):
"""Callback that runs when the attribute name was edited"""
ogt.dbg_ui(f"_on_attribute_name_changed({new_name})")
self.__controller.name = new_name
self.__frame.title = new_name
def __on_attribute_ui_name_changed(self, new_ui_name: str):
"""Callback that runs when the attribute name was edited"""
ogt.dbg_ui(f"_on_attribute_ui_name_changed({new_ui_name})")
self.__controller.ui_name = new_ui_name
def __on_attribute_default_changed(self, new_default: str):
"""Callback that runs when the attribute default was edited"""
ogt.dbg_ui(f"_on_attribute_default_changed({new_default})")
self.__controller.default = new_default
def _on_remove_attribute(self):
"""Callback that runs when this attribute was removed via the remove button"""
self.__controller.on_remove_attribute()
# The frame rebuild will take care of destroying this view
def __update_default(self):
"""Update the value in the default widget"""
self.__widget_models[ID_ATTR_DEFAULT].set_value(json.dumps(self.__controller.default))
def __on_union_types_changed(self, new_union_types_str: str):
"""Callback that runs when the attribute's union types were edited"""
ogt.dbg_ui(f"union_types changed ({new_union_types_str})")
# Format the input
new_union_types = [union_type.strip() for union_type in new_union_types_str.strip(" ,\t\n").split(",")]
new_union_types_str = ", ".join(new_union_types)
self.__controller.union_types = new_union_types
# Replace input box with formatted text if needed
if self.__widget_models[ID_ATTR_UNION_TYPES].as_string != new_union_types_str:
ogt.dbg_ui(f"Setting union types input to ({new_union_types_str})")
self.__widget_models[ID_ATTR_UNION_TYPES].set_value(new_union_types_str)
# Run end_edit to reset the prompt if needed
self.__widget_models[ID_ATTR_UNION_TYPES].end_edit()
# ----------------------------------------------------------------------
def __register_ghost_info(self, ghost_info: GhostedWidgetInfo, widget_name: str, prompt_widget_name: str):
"""Add the ghost widget information to the model data"""
self.__subscriptions[widget_name + "_begin"] = ghost_info.begin_subscription
self.__subscriptions[widget_name + "_end"] = ghost_info.end_subscription
self.__widgets[widget_name] = ghost_info.widget
self.__widget_models[widget_name] = ghost_info.model
self.__widgets[prompt_widget_name] = ghost_info.prompt_widget
# ----------------------------------------------------------------------
def __build_name_ui(self):
"""Build the contents implementing the attribute name editing widget"""
ghost_info = ghost_text(
label="Name:",
tooltip=TOOLTIPS[ID_ATTR_NAME],
widget_id=f"{self.__controller.name}_name",
initial_value=self.__controller.name,
ghosted_text="Enter Attribute Name...",
change_callback=self.__on_attribute_name_changed,
validation=(partial(is_attribute_name_valid, self.__controller.attribute_group), ogn.ATTR_NAME_REQUIREMENT),
)
self.__register_ghost_info(ghost_info, ID_ATTR_NAME, ID_ATTR_NAME_PROMPT)
# ----------------------------------------------------------------------
def __build_ui_name_ui(self):
"""Build the contents implementing the attribute user-friendly name editing widget"""
ghost_info = ghost_text(
label="UI Name:",
tooltip=TOOLTIPS[ID_UI_ATTR_NAME],
widget_id=f"{self.__controller.name}_ui_name",
initial_value=self.__controller.ui_name,
ghosted_text="Enter User-Friendly Attribute Name...",
change_callback=self.__on_attribute_ui_name_changed,
validation=(is_attribute_ui_name_valid, ogn.ATTR_UI_NAME_REQUIREMENT),
)
self.__register_ghost_info(ghost_info, ID_UI_ATTR_NAME, ID_UI_ATTR_NAME_PROMPT)
# ----------------------------------------------------------------------
def __build_description_ui(self):
"""Build the contents implementing the attribute description editing widget"""
ghost_info = ghost_text(
label="Description:",
tooltip=TOOLTIPS[ID_ATTR_DESCRIPTION],
widget_id=f"{self.__controller.name}_descripton",
initial_value=self.__controller.description,
ghosted_text="Enter Attribute Description...",
change_callback=self.__on_attribute_description_changed,
)
self.__register_ghost_info(ghost_info, ID_ATTR_DESCRIPTION, ID_ATTR_DESCRIPTION_PROMPT)
# ----------------------------------------------------------------------
def __build_default_ui(self):
"""Build the contents implementing the attribute default value editing widget"""
ghost_info = ghost_text(
label="Default:",
tooltip=TOOLTIPS[ID_ATTR_DEFAULT],
widget_id=f"{self.__controller.name}_default",
initial_value=str(self.__controller.default),
ghosted_text="Enter Attribute Default...",
change_callback=self.__on_attribute_default_changed,
)
self.__register_ghost_info(ghost_info, ID_ATTR_DEFAULT, ID_ATTR_DEFAULT_PROMPT)
# ----------------------------------------------------------------------
def __on_attribute_array_changed(self, model):
"""Callback executed when the checkbox for the array type is clicked"""
ogt.dbg_ui("_on_attribute_array_changed()")
new_array_setting = model.as_bool
self.__controller.array_depth = 1 if new_array_setting else 0
self.__update_default()
# ----------------------------------------------------------------------
def __on_tuple_count_changed(self, new_tuple_count: int):
"""Callback executed when a new tuple count is selected from the dropdown."""
ogt.dbg_ui("__on_tuple_count_changed")
self.__controller.tuple_count = new_tuple_count
self.__update_default()
# ---------------------------------------------------------------------
def __on_base_type_changed(self, new_base_type: str):
"""Callback executed when a new base type is selected from the dropdown."""
ogt.dbg_ui("__on_base_type_changed")
# Support extended attribute union groups
if new_base_type in ogn.ATTRIBUTE_UNION_GROUPS:
self.__on_base_type_changed("union")
self.__on_union_types_changed(new_base_type)
return
# Show / hide the union types editor
self.__set_union_type_ui_visibility(new_base_type == "union")
# Update defaults
has_default = new_base_type not in ["any", "bundle", "union"]
self.__widgets[ID_ATTR_DEFAULT].enabled = has_default
self.__widgets[ID_ATTR_DEFAULT_PROMPT].enabled = has_default
if not has_default:
self.__controller.default = None
self.__controller.base_type = new_base_type
self.__update_default()
# Use the old value of the union types field if available
if new_base_type == "union" and self.__widget_models[ID_ATTR_UNION_TYPES].as_string:
self.__on_union_types_changed(self.__widget_models[ID_ATTR_UNION_TYPES].as_string)
# ----------------------------------------------------------------------
def __rebuild_type_ui(self):
"""Build the contents implementing the attribute type editing widget"""
self.destroy_type_ui_frame()
with name_value_hstack():
name_value_label("Attribute Type:", TOOLTIPS[ID_ATTR_FRAME_TYPE])
with ui.HStack(spacing=5):
ui.Label("Base Type:", tooltip="Basic data element type")
self.__type_managers[ID_ATTR_BASE_TYPE] = AttributeBaseTypeManager(
self.__controller, self.__on_base_type_changed
)
if self.__controller.base_type not in ["union", "any"]:
ui.Label("Tuple Count:", tooltip="Number of elements in a tuple, e.g. 3 for a float[3]")
self.__type_managers[ID_ATTR_TUPLE_COUNT] = AttributeTupleCountManager(
self.__controller, self.__on_tuple_count_changed
)
ui.Label("Array:", tooltip=TOOLTIPS[ID_ATTR_TYPE_ARRAY_DEPTH], alignment=ui.Alignment.RIGHT_CENTER)
model = ui.SimpleIntModel(self.__controller.array_depth)
self.__type_subscriptions[ID_ATTR_TYPE_ARRAY_DEPTH] = model.subscribe_value_changed_fn(
self.__on_attribute_array_changed
)
widget = ui.CheckBox(
model=model,
name=ID_ATTR_TYPE_ARRAY_DEPTH,
width=0,
style_type_name_override="WhiteCheck",
alignment=ui.Alignment.LEFT_CENTER,
enabled=1 in self.__controller.array_depths_supported,
)
self.__type_widgets[ID_ATTR_TYPE_ARRAY_DEPTH] = widget
else:
# Spacers to left-justify the base type ComboBox.
# 3 spacers is the same space that the tuple count and array elements take up
ui.Spacer()
ui.Spacer()
ui.Spacer()
# ----------------------------------------------------------------------
def __on_controller_change(self, caller):
"""Callback executed when the controller data changes"""
self.__widgets[ID_ATTR_FRAME_TYPE].rebuild()
# ----------------------------------------------------------------------
def __build_type_ui(self):
"""Build the contents implementing the attribute type editing widget. In a frame because it is dynamic"""
self.__widgets[ID_ATTR_FRAME_TYPE] = ui.Frame()
self.__widgets[ID_ATTR_FRAME_TYPE].set_build_fn(self.__rebuild_type_ui)
self.__controller.add_change_callback(self.__on_controller_change)
# ----------------------------------------------------------------------
def __set_union_type_ui_visibility(self, visible: bool):
self.__widgets[ID_ATTR_FRAME_UNION_TYPES].visible = visible
# ----------------------------------------------------------------------
def __on_union_adder_selected(self, new_type):
ogt.dbg_ui(f"_on_union_adder_selected({new_type})")
union_types_str = self.__widget_models[ID_ATTR_UNION_TYPES].as_string
if new_type not in union_types_str:
self.__on_union_types_changed(union_types_str + ", " + new_type)
# ----------------------------------------------------------------------
def __rebuild_union_types_ui(self):
with name_value_hstack():
ghost_info = ghost_text(
label="Union Types:",
tooltip=TOOLTIPS[ID_ATTR_UNION_TYPES],
widget_id=f"{self.__controller.name}_union_types",
initial_value=", ".join(self.__controller.union_types),
ghosted_text="Enter comma-separated list of union types",
change_callback=self.__on_union_types_changed,
validation=None,
)
self.__register_ghost_info(ghost_info, ID_ATTR_UNION_TYPES, ID_ATTR_UNION_TYPES_PROMPT)
self.__widgets[ID_ATTR_UNION_TYPE_ADDER] = AttributeUnionTypeAdderManager(
self.__controller, self.__on_union_adder_selected
)
self.__set_union_type_ui_visibility(self.__controller.base_type == "union")
# ----------------------------------------------------------------------
def __build_union_types_ui(self):
"""
Build the contents implementing the union type editing widget.
These widgets are selectively enabled when the attribute type is a union.
"""
# Put it in a frame so it's easy to hide / show as needed
self.__widgets[ID_ATTR_FRAME_UNION_TYPES] = ui.Frame()
self.__widgets[ID_ATTR_FRAME_UNION_TYPES].set_build_fn(self.__rebuild_union_types_ui)
# ----------------------------------------------------------------------
def __build_memory_type_ui(self):
"""Build the contents implementing the attribute memory type editing widget"""
self.__managers[ID_ATTR_MEMORY_TYPE] = MemoryTypeManager(self.__controller)
# # ----------------------------------------------------------------------
# def __rebuild_min_max_ui(self):
# """
# Build the contents implementing the attribute minimum and maximum editing widget.
# These widgets are selectively enabled when the attribute type is one that allows for min/max values.
# """
# type_manager = self.__controller.attribute_manager
# try:
# visibility = True
# numeric_type = type_manager.numeric_type()
# if numeric_type == ogn.NumericAttributeManager.TYPE_INTEGER:
# is_integer = True
# elif numeric_type == ogn.NumericAttributeManager.TYPE_UNSIGNED_INTEGER:
# is_integer = True
# elif numeric_type == ogn.NumericAttributeManager.TYPE_DECIMAL:
# is_integer = False
# else:
# raise AttributeError("Not really a numeric type")
# name_value_label("Range:", TOOLTIPS[ID_ATTR_FRAME_RANGE])
# ui.Label("Minimum:", tooltip=TOOLTIPS[ID_ATTR_MINIMUM])
# if is_integer:
# model = ui.SimpleIntModel(self.__controller.minimum)
# widget = ui.IntField(
# alignment=ui.Alignment.RIGHT_BOTTOM,
# model=model,
# name=ID_ATTR_MINIMUM,
# tooltip=TOOLTIPS[ID_ATTR_MINIMUM],
# )
# subscription = widget.subscribe_value_changed_fn(self.__controller.on_int_minimum_changed)
# else:
# model = ui.SimpleFloatModel(self.__controller.minimum)
# widget = ui.FloatField(
# alignment=ui.Alignment.RIGHT_BOTTOM,
# model=model,
# name=ID_ATTR_MINIMUM,
# tooltip=TOOLTIPS[ID_ATTR_MINIMUM],
# )
# subscription = widget.subscribe_value_changed_fn(self.__controller.on_float_minimum_changed)
# self.__widgets[ID_ATTR_MINIMUM] = widget
# self.__subscriptions[ID_ATTR_MINIMUM] = subscription
# ui.Label("Maximum:", tooltip=TOOLTIPS[ID_ATTR_MAXIMUM])
# if is_integer:
# model = ui.SimpleIntModel(self.__controller.maximum)
# widget = ui.IntField(
# alignment=ui.Alignment.RIGHT_BOTTOM,
# model=model,
# name=ID_ATTR_MAXIMUM,
# tooltip=TOOLTIPS[ID_ATTR_MAXIMUM],
# )
# subscription = widget.subscribe_value_changed_fn(self.__controller.on_int_maximum_changed)
# else:
# model = ui.SimpleFloatModel(self.__controller.maximum)
# widget = ui.FloatField(
# alignment=ui.Alignment.RIGHT_BOTTOM,
# model=model,
# name=ID_ATTR_MAXIMUM,
# tooltip=TOOLTIPS[ID_ATTR_MAXIMUM],
# )
# subscription = widget.subscribe_value_changed_fn(self.__controller.on_float_maximum_changed)
# self.__widgets[ID_ATTR_MAXIMUM] = widget
# self.__subscriptions[ID_ATTR_MAXIMUM] = subscription
# except AttributeError:
# visibility = False
# self.__widgets[ID_ATTR_FRAME_RANGE].visible = visibility
# # ----------------------------------------------------------------------
# def __build_min_max_ui(self) -> bool:
# """
# Build the contents implementing the attribute minimum and maximum editing widget.
# These widgets are selectively enabled when the attribute type is one that allows for min/max values.
# Returns:
# True if the UI elements should be visible for the current attribute
# """
# self.__widgets[ID_ATTR_FRAME_RANGE] = ui.Frame()
# self.__widgets[ID_ATTR_FRAME_RANGE].set_build_fn(self.__rebuild_frame_min_max_ui)
# ----------------------------------------------------------------------
# def __on_optional_changed(self, model):
# """Callback executed when the checkbox for the optional flag is clicked"""
# ogt.dbg_ui("_on_optional_changed()")
# self.__controller.optional = model.as_bool
# ----------------------------------------------------------------------
# def __build_optional_ui(self):
# """Build the contents implementing the optional checkbox widget"""
# name_value_label("Optional:", TOOLTIPS[ID_ATTR_OPTIONAL])
# model = ui.SimpleIntModel(self.__controller.optional)
# subscription = model.subscribe_value_changed_fn(self.__on_optional_changed)
# widget = ui.CheckBox(
# model=model,
# name=ID_ATTR_OPTIONAL,
# width=0,
# style_type_name_override="WhiteCheck",
# alignment=ui.Alignment.LEFT_CENTER,
# enabled=self.__controller.optional,
# )
# self.__widgets[ID_ATTR_OPTIONAL] = widget
# self.__subscriptions[ID_ATTR_OPTIONAL] = subscription
# ----------------------------------------------------------------------
def __build_metadata_ui(self):
"""Build the contents implementing the attribute metadata editing widget"""
self.__managers[ID_MGR_ATTR_METADATA] = MetadataManager(self.__controller)
# ----------------------------------------------------------------------
def __rebuild_frame(self):
"""Rebuild the contents underneath the main attribute frame"""
self.destroy_frame_contents()
with ui.VStack(**VSTACK_ARGS):
with name_value_hstack():
self.__build_name_ui()
with name_value_hstack():
self.__build_description_ui()
self.__build_type_ui()
self.__build_union_types_ui()
with name_value_hstack():
self.__build_ui_name_ui()
with name_value_hstack():
self.__build_memory_type_ui()
with name_value_hstack():
self.__build_default_ui()
# It's unclear what value if any these provide so they are omitted from the UI for now.
# min_max_stack = name_value_hstack()
# with min_max_stack:
# min_max_stack.visible = self.__build_min_max_ui()
# with name_value_hstack():
# self.__build_optional_ui()
with name_value_hstack():
self.__build_metadata_ui()
# ================================================================================
class AttributeListModel:
"""
Manager for an entire list of attribute description data. It's used as an intermediary between the
input and output attribute lists and the individual attribute data in AttributePropertiesModel
External Properties
attribute_group
is_output
models
Internal Properties:
__attribute_group: Enum with the attribute's group (input, output, or state)
__is_output: bool True when the attributes owned by this list are output types
__models: List of AttributePropertiesModels for each attribute in the list
"""
def __init__(self, attribute_data: Optional[Dict], attribute_group: str):
"""
Create an initial attribute model from the list of attributes (empty list if None)
Args:
attribute_data: Dictionary of the initial attribute list
attribute_group: Enum with the attribute's group (input, output, or state)
"""
self.__attribute_group = attribute_group
self.__models = []
self.__is_output = False
if attribute_data is not None:
for name, data in attribute_data.items():
self.__models.append(AttributePropertiesModel(name, attribute_group, data))
def destroy(self):
"""Called when this model is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__models = [] # These are owned by their respective controllers
self.__attribute_group = None
# ----------------------------------------------------------------------
def ogn_data(self) -> Dict:
"""Return a dictionary representing the list of attributes in .ogn format, None if the list is empty"""
if self.__models:
raw_data = {}
for model in self.__models:
raw_data.update(model.ogn_data)
return {attribute_key_from_group(self.__attribute_group): raw_data}
return None
# ----------------------------------------------------------------------
def all_attribute_names(self) -> List[str]:
"""Returns a list of all currently existing attribute names"""
names = []
for model in self.__models:
names.append(model.name)
return names
# ----------------------------------------------------------------------
def add_new_attribute(self) -> AttributePropertiesModel:
"""Create a new default attribute and add it to the list
Returns:
Newly created attribute properties model
"""
attribute_key = attribute_key_from_group(self.__attribute_group)
default_name = find_unique_name(f"new_{attribute_key[0:-1]}", self.all_attribute_names())
default_data = {"type": "int", "description": ""}
self.__is_output = self.__attribute_group == ogn.OUTPUT_GROUP
if not self.__is_output:
default_data["default"] = 0
self.__models.append(AttributePropertiesModel(default_name, self.__attribute_group, default_data))
return self.__models[-1]
# ----------------------------------------------------------------------
def remove_attribute(self, attribute_model):
"""Remove the attribute encapsulated in the given model"""
try:
self.__models.remove(attribute_model)
except ValueError:
log_warn(f"Failed to remove attribute model for {attribute_model.name}")
# ----------------------------------------------------------------------
@property
def attribute_group(self):
"""Returns the group to which these attributes belong"""
return self.__attribute_group
# ----------------------------------------------------------------------
@property
def models(self):
"""Returns the list of models managing individual attributes"""
return self.__models
# ----------------------------------------------------------------------
@property
def is_output(self):
"""Returns whether this list represents output attributes or not"""
return self.__is_output
# ================================================================================
class AttributeListController(ChangeManager):
"""Interface between the view and the model, making changes to the model on request
External Properties:
all_attribute_controllers
all_attribute_names
attribute_group
is_output
Internal Properties:
__controllers: List of individual attribute property controllers
__model: The model this class controls
"""
def __init__(self, model: AttributeListModel):
"""Initialize the controller with the model it will control"""
super().__init__()
self.__model = model
self.__controllers = [AttributePropertiesController(model, self) for model in self.__model.models]
# Be sure to forward all change callbacks from the children to this parent
for controller in self.__controllers:
controller.forward_callbacks_to(self)
def destroy(self):
"""Called when the controller is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
super().destroy()
ogt.destroy_property(self, "__controllers")
self.__model = None
# ----------------------------------------------------------------------
def on_name_change(self, old_name: str, new_name: str):
"""Callback that executes when the individual attribute model wants to change its name.
Raises:
AttributeError: If the new name is a duplicate of an existing name
"""
# If the name is not changing assume that no duplicates exist
if old_name == new_name:
return
for controller in self.__controllers:
if controller.name == new_name:
raise AttributeError(f"Attribute with name {new_name} already exists. Names must be unique.")
# ----------------------------------------------------------------------
def on_new_attribute(self):
"""Callback that executes when the view wants to add a new attribute
Insert a new attribute with some default values into the OGN data.
"""
ogt.dbg_ui(f"Adding a new attribute in {attribute_key_from_group(self.attribute_group)}")
new_model = self.__model.add_new_attribute()
attribute_controller = AttributePropertiesController(new_model, self)
self.__controllers.append(attribute_controller)
attribute_controller.forward_callbacks_to(self)
self.on_change(AttributeAddedMessage(self, attribute_controller.name, attribute_controller.attribute_group))
# ----------------------------------------------------------------------
def on_remove_attribute(self, attribute_controller: AttributePropertiesController):
"""Callback that executes when the given controller's attribute was removed"""
ogt.dbg_ui(f"Removing an existing attribute from {attribute_key_from_group(self.attribute_group)}")
try:
(name, group) = (attribute_controller.name, attribute_controller.attribute_group)
self.__model.remove_attribute(attribute_controller._model) # noqa: PLW0212
attribute_controller.destroy()
self.__controllers.remove(attribute_controller)
self.on_change(AttributeRemovedMessage(self, name, group))
except ValueError:
log_warn(f"Failed removal of controller for {attribute_controller.name}")
# ----------------------------------------------------------------------
@property
def attribute_group(self):
"""Returns the group to which these attributes belong"""
return self.__model.attribute_group
# ----------------------------------------------------------------------
@property
def is_output(self):
"""Returns whether this list represents output attributes or not"""
return self.__model.is_output
# ----------------------------------------------------------------------
@property
def all_attribute_controllers(self) -> List[AttributePropertiesController]:
"""Returns the list of all controllers for attributes in this list"""
return self.__controllers
# ----------------------------------------------------------------------
@property
def all_attribute_names(self) -> List[str]:
"""Returns a list of all currently existing attribute names"""
return self.__model.all_attribute_names
# ================================================================================
class AttributeListView:
"""UI for a list of attributes
Internal Properties:
__add_button: Widget managing creation of a new attribute
__attribute_views: Per-attribute set of views, keyed by attribute name
__controller: The controller used to manipulate the model's data
__frame: Main frame for this attribute's interface
__widgets: Dictionary of ID:Widget for the components of the attribute's frame
"""
def __init__(self, controller: AttributeListController):
"""Initialize the view with the controller it will use to manipulate the model"""
self.__add_button = None
self.__controller = controller
self.__attribute_views = {}
if controller.attribute_group == ogn.INPUT_GROUP:
title = "Input Attributes"
elif controller.attribute_group == ogn.OUTPUT_GROUP:
title = "Output Attributes"
else:
title = "State Attributes"
self.__frame = ui.CollapsableFrame(title=title, collapsed=True)
self.__frame.set_build_fn(self.__rebuild_frame)
self.__controller.add_change_callback(self.__on_list_change)
def destroy(self):
"""Called when the view is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
with suppress(AttributeError):
self.__frame.set_build_fn(None)
with suppress(ValueError):
self.__controller.remove_change_callback(self.__on_list_change)
self.__controller = None
ogt.destroy_property(self, "__add_button")
ogt.destroy_property(self, "__frame")
ogt.destroy_property(self, "__attribute_views")
# ----------------------------------------------------------------------
def __on_list_change(self, change_message):
"""Callback executed when a member of the list changes.
Args:
change_message: Message with change information
"""
ogt.dbg_ui(f"List change called on {self.__class__.__name__} with {change_message}")
# Renaming does not require rebuilding of the attribute frame, other changes do
if isinstance(change_message, (AttributeAddedMessage, AttributeRemovedMessage)):
self.__frame.rebuild()
# ----------------------------------------------------------------------
def __rebuild_frame(self):
"""Rebuild the contents underneath the main attribute frame"""
ogt.dbg_ui(f"Rebuilding the frame for {attribute_key_from_group(self.__controller.attribute_group)}")
ogt.destroy_property(self, "__attribute_views")
with ui.VStack(**VSTACK_ARGS):
self.__add_button = DestructibleButton(
width=20,
height=20,
style_type_name_override="AddElement",
clicked_fn=self.__controller.on_new_attribute, # noqa: PLW0212
tooltip="Add a new attribute with default settings",
)
assert self.__add_button
# Reconstruct the list of per-attribute views. Construction instantiates their UI.
for controller in self.__controller.all_attribute_controllers:
self.__attribute_views[controller.name] = AttributePropertiesView(controller)
| 72,336 | Python | 44.041719 | 120 | 0.565514 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/attribute_union_type_adder_manager.py | """
Manager class for the attribute union type adder combo box.
"""
from typing import Callable, Optional
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_warn
from omni import ui
from .ogn_editor_utils import ComboBoxOptions
SelectionFinishedCallback = Optional[Callable[[str], None]]
# ======================================================================
# ID values for widgets that are editable or need updating
ID_ATTR_UNION_TYPE_ADDER = "attributeUnionTypeAdder"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {ID_ATTR_UNION_TYPE_ADDER: "Add data types to the union accepted by the attribute"}
# ======================================================================
class AttributeUnionTypeAdderComboBox(ui.AbstractItemModel):
"""Implementation of a combo box that shows data types addable to the attribute union
Internal Properties:
__controller: Controller managing the type information
__type_changed_callback: Option callback to execute when a new base type is chosen
__current_index: Model for the currently selected value
__subscription: Subscription object for the type change callback
__items: List of models for each legal value in the combobox
"""
OPTIONS = [""] + list(ogn.ATTRIBUTE_UNION_GROUPS.keys())
OPTIONS += sorted({t for attr_groups in ogn.ATTRIBUTE_UNION_GROUPS.values() for t in attr_groups})
OPTION_INDEX = {}
for (index, attribute_type_name) in enumerate(OPTIONS):
OPTION_INDEX[attribute_type_name] = index
def __init__(self, controller, selection_finished_callback: SelectionFinishedCallback = None):
"""Initialize the attribute base type combo box details"""
super().__init__()
self.__controller = controller
self.__current_index = ui.SimpleIntModel()
self.__selection_finished_callback = selection_finished_callback
self.__current_index.set_value(0)
self.__subscription = self.__current_index.subscribe_value_changed_fn(self.__on_selection_finished)
assert self.__subscription
# Using a list comprehension instead of values() guarantees the pre-sorted ordering
self.__items = [ComboBoxOptions(attribute_type_name) for attribute_type_name in self.OPTIONS]
def destroy(self):
"""Called when the widget is being destroyed, to remove callbacks"""
self.__controller = None
self.__subscription = None
self.__selection_finished_callback = None
ogt.destroy_property(self, "__current_index")
ogt.destroy_property(self, "__items")
def get_item_children(self, parent):
"""Get the model children of this item"""
return self.__items
def get_item_value_model(self, item: ui.AbstractItem = None, column_id: int = 0) -> ui.AbstractValueModel:
"""Get the model at the specified column_id"""
if item is None:
return self.__current_index
return item.model
def __on_selection_finished(self, new_value: ui.SimpleIntModel):
"""Callback executed when a new type was selected"""
self._item_changed(None)
try:
ogt.dbg_ui(f"Adding type to union: {new_value.as_int}")
new_type_name = self.OPTIONS[new_value.as_int]
ogt.dbg_ui(f"Type name is {new_type_name}")
if self.__selection_finished_callback and new_type_name:
self.__selection_finished_callback(new_type_name)
except KeyError:
log_warn(f"Union type add change was rejected - {new_value.as_int} not found")
except AttributeError as error:
log_warn(
f"Union type add '{new_value.as_int}' on attribute '{self.__controller.name}' was rejected - {error}"
)
# ======================================================================
class AttributeUnionTypeAdderManager:
"""Handle the combo box and responses for getting and adding union types
Internal Properties:
__controller: Controller for the data of the attribute this will modify
__widget: ComboBox widget controlling the base type
__widget_model: Model for the ComboBox value
"""
def __init__(self, controller, selection_finished_callback: SelectionFinishedCallback = None):
"""Set up the initial UI and model
Args:
controller: AttributePropertiesController in charge of the data for the attribute being managed
"""
self.__controller = controller
self.__widget_model = AttributeUnionTypeAdderComboBox(self.__controller, selection_finished_callback)
self.__widget = ui.ComboBox(
self.__widget_model,
alignment=ui.Alignment.LEFT_BOTTOM,
name=ID_ATTR_UNION_TYPE_ADDER,
tooltip=TOOLTIPS[ID_ATTR_UNION_TYPE_ADDER],
arrow_only=True,
width=ui.Length(7),
)
assert self.__widget
def destroy(self):
"""Called to clean up when the widget is being destroyed"""
self.__controller = None
ogt.destroy_property(self, "__widget")
ogt.destroy_property(self, "__widget_model")
| 5,262 | Python | 41.104 | 117 | 0.628468 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/extension_info_manager.py | """
Contains support for the UI to create and manage extensions containing OmniGraph nodes.
"""
import asyncio
import os
from contextlib import suppress
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_error, tokens
from omni import ui
from omni.kit.app import get_app_interface
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.widget.prompt import Prompt
from omni.kit.window.filepicker import FilePickerDialog
from ..style import VSTACK_ARGS, name_value_hstack, name_value_label # noqa: PLE0402
from .file_manager import FileManager
from .main_controller import Controller
from .main_generator import Generator
from .ogn_editor_utils import DestructibleButton, ValidatedStringModel
# ======================================================================
# Pattern recognizing a legal import path
IMPORT_PATH_EXPLANATION = (
"Import paths must start with a letter or underscore and only contain letters, numbers, underscores,"
" and periods as separators"
)
# ======================================================================
# ID values for widgets that are editable or need updating
ID_BTN_CHOOSE_ROOT = "extensionButtonChooseRoot"
ID_BTN_CLEAN_EXTENSION = "extensionButtonClean"
ID_BTN_POPULATE_EXTENSION = "extensionButtonCreate"
ID_EXTENSION_ROOT = "extensionRoot"
ID_EXTENSION_IMPORT = "extensionImport"
ID_WINDOW_CHOOSE_ROOT = "extensionWindowChooseRoot"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {
ID_BTN_CHOOSE_ROOT: "Select a new root location for your extension",
ID_BTN_CLEAN_EXTENSION: "Clean out all generated files from your extension",
ID_BTN_POPULATE_EXTENSION: "Populate a new python extension with your generated node files",
ID_EXTENSION_ROOT: "Root directory where the extension will be installed",
ID_EXTENSION_IMPORT: "Extension name, also used as the Python import path",
}
# ======================================================================
class ExtensionInfoManager:
"""Class encapsulating the tasks around management of extensions and .ogn file generation
Properties:
__controller: Main data controller
__extension: ogn.OmniGraphExtension that manages the extension location and default file generation
__file_manager: Object used to manage file-based interactions
__frame: Main frame for this subsection of the editor
__subscriptions: Diction of ID:Subscription for all callbacks, for easier destruction
__widgets: Dictionary of ID:Widget for all elements in this subsection of the editor
__widget_models: Dictionary of ID:Model for all elements in this subsection of the editor
The widgets do not maintain references to derived model classes so these must be explicit
"""
def __init__(self, file_manager: FileManager, controller: Controller):
"""Set up an initial empty default extension environment"""
# Carbonite has the notion of a shared extension location, default to that
shared_path = tokens.get_tokens_interface().resolve("${shared_documents}")
self.__extension = ogn.OmniGraphExtension(
os.path.join(os.path.normpath(shared_path), "exts"), "omni.new.extension"
)
self.__file_manager = file_manager
file_manager.ogn_directory = self.__extension.ogn_nodes_directory
self.__controller = controller
self.__subscription_to_enable = None
self.__frame = None
self.__subscriptions = {}
self.__widgets = {}
self.__widget_models = {}
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the manager is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__controller = None
self.__extension = None
self.__file_manager = None
self.__frame = None
self.__subscriptions = {}
self.__subscription_to_enable = None
ogt.destroy_property(self, "__widget_models")
ogt.destroy_property(self, "__widgets")
# ----------------------------------------------------------------------
@property
def extension(self) -> str:
"""Returns the information for the current extension"""
return self.__extension
# ----------------------------------------------------------------------
def __on_import_path_changed(self, new_import_path: ui.SimpleStringModel):
"""Callback executed when the user has selected a new import path"""
with suppress(ValueError):
self.__extension.import_path = new_import_path.as_string
ogt.dbg_ui(f"Import path changed to {new_import_path.as_string}")
self.__file_manager.ogn_directory = self.__extension.ogn_nodes_directory
# ----------------------------------------------------------------------
def __on_root_changed(self, new_root_path: ui.SimpleStringModel):
"""Callback executed when the user has selected a new root directory"""
ogt.dbg_ui(f"Root changed to {new_root_path.as_string}")
self.__extension.extension_root = new_root_path.as_string
self.__file_manager.ogn_directory = self.__extension.ogn_nodes_directory
# ----------------------------------------------------------------------
def __on_choose_root(self):
"""Callback executed when the Choose Root button is clicked"""
def __on_filter_roots(item: FileBrowserItem) -> bool:
"""Callback to filter the choices of file names in the open or save dialog"""
return not item or item.is_folder
def __on_click_cancel(file_name: str, directory_name: str):
"""Callback executed when the user cancels the file open dialog"""
ogt.dbg_ui("Clicked cancel in file open")
self.__widgets[ID_WINDOW_CHOOSE_ROOT].hide()
def __on_root_chosen(filename: str, dirname: str):
"""Callback executed when the user has selected a new root directory"""
self.__widget_models[ID_EXTENSION_ROOT].set_value(os.path.join(dirname, filename))
self.__widgets[ID_WINDOW_CHOOSE_ROOT].hide()
ogt.dbg_ui("Choose Root Button Clicked")
if ID_WINDOW_CHOOSE_ROOT not in self.__widgets:
self.__widgets[ID_WINDOW_CHOOSE_ROOT] = FilePickerDialog(
"Select Extension Root",
allow_multi_selection=False,
apply_button_label="Open",
click_apply_handler=__on_root_chosen,
click_cancel_handler=__on_click_cancel,
item_filter_fn=__on_filter_roots,
error_handler=log_error,
)
self.__widgets[ID_WINDOW_CHOOSE_ROOT].refresh_current_directory()
self.__widgets[ID_WINDOW_CHOOSE_ROOT].show(path=self.__extension.extension_root)
# ----------------------------------------------------------------------
def __on_clean_extension_button(self):
"""Callback executed when the Clean Extension button is clicked"""
ogt.dbg_ui("Clean Extension Button Clicked")
# Find and remove all generated files
self.__extension.remove_generated_files()
self.__extension.write_ogn_init(force=True)
# ----------------------------------------------------------------------
def __on_populate_extension_button(self):
"""Callback executed when the Populate Extension button is clicked"""
ogt.dbg_ui("Populate Extension Button Clicked")
# Verify that the node is implemented in Python
if self.__controller.node_properties_controller.node_language != ogn.LanguageTypeValues.PYTHON:
Prompt("Node Language", "Only Python nodes can be processed", "Okay").show()
# Create the extension directory tree if necessary
self.__extension.create_directory_tree()
self.__extension.remove_generated_files()
self.__extension.write_all_files(force=True)
# Ensure .ogn file was saved if it has already been defined
if self.__file_manager.ogn_path is not None:
self.__file_manager.save()
if self.__file_manager.save_failed():
Prompt(".ogn Not Generated", f"Could not generate {self.__file_manager.ogn_path}", "Okay").show()
return
# Generate the Python, USD, Tests, and Docs files
try:
generator = Generator(self.__extension)
generator.parse(self.__file_manager.ogn_path)
except ogn.ParseError as error:
Prompt("Parse Failure", f"Could not parse .ogn file : {error}", "Okay").show()
return
except FileNotFoundError as error:
Prompt(".ogn Not Found", f"Could not generate {self.__file_manager.ogn_path} - {error}", "Okay").show()
return
try:
generator.generate_python()
except ogn.NodeGenerationError as error:
Prompt("Generation Failure", f"Python file could not be generated : {error}", "Okay").show()
return
try:
generator.generate_tests()
except ogn.NodeGenerationError as error:
Prompt("Generation Failure", f"Test script could not be generated : {error}", "Okay").show()
return
try:
generator.generate_documentation()
except ogn.NodeGenerationError as error:
Prompt("Generation Failure", f"Documentation file could not be generated : {error}", "Okay").show()
return
try:
generator.generate_usd()
except ogn.NodeGenerationError as error:
Prompt("Generation Failure", f"USD file could not be generated : {error}", "Okay").show()
return
async def enable_extension_when_ready():
"""Wait for the load to be complete and then enable the new extension"""
ext_manager = get_app_interface().get_extension_manager()
if self.__extension:
ext_manager.set_extension_enabled_immediate(self.__extension.import_path, True)
# The extension manager needs an opportunity to scan the directory again before the extension can be
# enabled so use a coroutine to wait for the next update to do so.
ext_manager = get_app_interface().get_extension_manager()
self.__subscription_to_enable = ext_manager.get_change_event_stream().create_subscription_to_pop(
lambda _: asyncio.ensure_future(enable_extension_when_ready()), name=self.__extension.import_path
)
assert self.__subscription_to_enable
# ----------------------------------------------------------------------
def build_ui(self):
"""Runs UI commands that implement the extension management interface"""
self.__frame = ui.CollapsableFrame("Extension Management", collapsed=True)
with self.__frame:
with ui.VStack(**VSTACK_ARGS):
with ui.HStack(width=0):
self.__widgets[ID_BTN_POPULATE_EXTENSION] = DestructibleButton(
"Populate Extension",
name=ID_BTN_POPULATE_EXTENSION,
tooltip=TOOLTIPS[ID_BTN_POPULATE_EXTENSION],
clicked_fn=self.__on_populate_extension_button,
)
self.__widgets[ID_BTN_CLEAN_EXTENSION] = DestructibleButton(
"Clean Extension",
name=ID_BTN_CLEAN_EXTENSION,
tooltip=TOOLTIPS[ID_BTN_CLEAN_EXTENSION],
clicked_fn=self.__on_clean_extension_button,
style_type_name_override="DangerButton",
)
with name_value_hstack():
name_value_label("Extension Location:")
model = ui.SimpleStringModel(self.__extension.extension_root)
self.__subscriptions[ID_EXTENSION_ROOT] = model.subscribe_end_edit_fn(self.__on_root_changed)
self.__widgets[ID_EXTENSION_ROOT] = ui.StringField(
model=model,
name=ID_EXTENSION_ROOT,
tooltip=TOOLTIPS[ID_EXTENSION_ROOT],
alignment=ui.Alignment.LEFT_BOTTOM,
)
self.__widget_models[ID_EXTENSION_ROOT] = model
self.__widgets[ID_BTN_CHOOSE_ROOT] = DestructibleButton(
width=24,
height=24,
clicked_fn=self.__on_choose_root,
style_type_name_override="FolderImage",
tooltip=TOOLTIPS[ID_BTN_CHOOSE_ROOT],
)
with name_value_hstack():
name_value_label("Extension Name:")
model = ValidatedStringModel(
self.__extension.import_path,
ogt.OmniGraphExtension.validate_import_path,
IMPORT_PATH_EXPLANATION,
)
self.__subscriptions[ID_EXTENSION_IMPORT] = model.subscribe_end_edit_fn(
self.__on_import_path_changed
)
self.__widgets[ID_EXTENSION_IMPORT] = ui.StringField(
model=model, name=ID_EXTENSION_IMPORT, tooltip=TOOLTIPS[ID_EXTENSION_IMPORT]
)
self.__widget_models[ID_EXTENSION_IMPORT] = model
| 13,752 | Python | 48.82971 | 119 | 0.577298 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/main_editor.py | """
Manage the window containing the node description editor. This main class manages several member
classes that handle different parts of the editor.
The general pattern is Model-View-Controller for each section. This file is the "View" for the
editor as a whole. Controller.py and Model.py form the other two parts.
change_management.py is a set of classes to handle notifications when structure or values change.
Icons.py houses utilities to manage icons used in the editor.
style.py contains the editor's style information, including sizing information that is not technically "style"
The editor itself is managed in sections, roughly corresponding to the files in the diagram below
+------------------------------------+
| MenuManager.py |
| FileManager.py |
+====================================+
| [Generator.py] |
+------------------------------------+
| v ExtensionInfoManager.py |
+------------------------------------+
| v node_properties.py |
| MemoryTypeManager.py |
| NodeLanguageManager.py |
| MetadataManager.py |
+------------------------------------+
| v attribute_properties.py |
| AttributeTupleCountManager.py |
| AttributeListManager.py |
| AttributeBaseTypeManager.py |
| MemoryTypeManager.py |
| MetadataManager.py |
+------------------------------------+
| v test_configurations.py |
+------------------------------------+
| v RawOgnManager.py |
+------------------------------------+
"""
import asyncio
import json
import os
from contextlib import suppress
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
import omni.kit
from omni import ui
from omni.kit.widget.prompt import Prompt
from ..metaclass import Singleton # noqa: PLE0402
from ..style import VSTACK_ARGS, get_window_style # noqa: PLE0402
from .attribute_properties import AttributeListView # noqa: PLE0402
from .extension_info_manager import ExtensionInfoManager # noqa: PLE0402
from .file_manager import FileManager # noqa: PLE0402
from .main_controller import Controller # noqa: PLE0402
from .main_model import Model # noqa: PLE0402
from .node_properties import NodePropertiesView # noqa: PLE0402
from .ogn_editor_utils import show_wip # noqa: PLE0402
from .test_configurations import TestListView # noqa: PLE0402
# ======================================================================
# Constants for the layout of the window
EXTENSION_NAME = "OmniGraph Node Description Editor"
EXTENSION_DESC = "Description ui for the .ogn format of OmniGraph nodes"
MENU_PATH = "Window/Visual Scripting/Node Description Editor"
# ======================================================================
# ID values for the dictionary of frames within the window
ID_FRAME_OGN_CONTENTS = "frameOgn"
ID_GENERATED_CPP = "generatedCpp"
ID_GENERATED_USD = "generatedUsd"
ID_GENERATED_DOC = "generatedDocs"
ID_GENERATED_PYTHON = "generatedPython"
ID_GENERATED_TEMPLATE = "generatedTemplate"
ID_GENERATED_TESTS = "generatedTests"
# ======================================================================
# ID values for widgets that are editable or need updating
ID_ATTR_ARRAY_DEPTH = "attributeArrayDepth"
ID_ATTR_DEFAULT = "attributeDefault"
ID_ATTR_DESCRIPTION = "attributeDescription"
ID_ATTR_DESCRIPTION_PROMPT = "attributeDescriptionPrompt"
ID_ATTR_MEMORY_TYPE = "attributeMemoryType"
ID_ATTR_TYPE = "attributeType"
ID_INPUT_NAME = "attributeInputName"
ID_OGN_CONTENTS = "generatedOgn"
ID_OUTPUT_NAME = "attributeOutputName"
# ======================================================================
# ID for dictionary of classes that manage subsections of the editor, named for their class
ID_MGR_ATTR_METADATA = "AttributeMetadataManager"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {
ID_OGN_CONTENTS: "The .ogn file that would result from the current configuration",
ID_ATTR_ARRAY_DEPTH: "Array dimension of the attribute (e.g. 1 = float[], 0 = float)",
ID_ATTR_DEFAULT: "Default value of the attribute when none has been set",
ID_ATTR_DESCRIPTION: "Description of what information the attribute holds",
ID_ATTR_MEMORY_TYPE: "Type of memory in which the attribute's data will reside",
ID_ATTR_TYPE: "Type of data the attribute holds",
ID_INPUT_NAME: "Name of the attribute without the 'inputs:' prefix",
ID_OUTPUT_NAME: "Name of the attribute without the 'outputs:' prefix",
}
# ======================================================================
# Dispatch table for menu items.
# The menus are described as a dictionary of {MENU_NAME: MENU_ITEMS},
# where MENU_ITEMS is a list of tuples (MENU_ITEM_TEXT, MENU_ITEM_FUNCTION, MENU_ITEM_TOOLTIP)
# The MENU_ITEM_FUNCTION is a method on Editor, resolved by introspection.
MENU_DEFINITIONS = {
"File": [
("Open...", "_on_menu_file_open", "Open a .ogn file into the editor"),
("Save...", "_on_menu_file_save", "Save a .ogn file from the editor"),
("Save as...", "_on_menu_file_save_as", "Save to a new .ogn file from the editor"),
("New Node", "_on_menu_file_new", "Create a new empty .ogn file in the editor"),
("Print OGN", "_on_menu_show_ogn", "Print the .ogn file contents to the console"),
("Extension Info", "_on_menu_show_extension", "Show extension information"),
]
}
# This is only for experimenting with different UI elements, not part of the actual editor
if ogt.OGN_UI_DEBUG:
MENU_DEFINITIONS["File"].append(("Test Window", "_on_menu_show_test", "Show test window"))
# ======================================================================
class Editor(metaclass=Singleton):
"""Manager of the window for editing the Node Description values (.ogn file contents)
Internal Properties:
__controller: Helper that handles modifications to the underlying OGN data model
__frame: Main frame of the window
__input_attribute_view: AttributeListView objects controlling the UI for input attributes
__managers: Dictionary of classes that manage various subparts of the editor
__model: Contains the underlying OGN data model
__output_attribute_view: AttributeListView objects controlling the UI for output attributes
__tests_view: TestListView objects controlling the UI for automated test specifications
__widget_models: Dictionary of model classes used by widgets, by ID
__widgets: Dictionary of editable widgets, by ID
__window: Window object containing the editor widgets
"""
# ----------------------------------------------------------------------
@staticmethod
def get_name() -> str:
"""Returns the name of the window extension"""
return EXTENSION_NAME
# ----------------------------------------------------------------------
@staticmethod
def get_description() -> str:
"""Returns a description of the window extension"""
return EXTENSION_DESC
# ----------------------------------------------------------------------
def __init__(self):
"""Sets up the internal state of the window"""
ogt.dbg_ui("Creating the window")
# These elements are built when the main frame rebuilds
self.__input_attribute_view = None
self.__node_view = None
self.__output_attribute_view = None
self.__tests_view = None
self.__widgets = {}
self.__model = Model()
self.__controller = Controller(self.__model, None)
self.__controller.add_change_callback(self.__on_ogn_changed)
self.__file_manager = FileManager(self.__controller)
self.__extension_manager = ExtensionInfoManager(self.__file_manager, self.__controller)
self.__model.extension = self.__extension_manager.extension
self.__model.file_manager = self.__file_manager
self.__window = ui.Window(
EXTENSION_NAME,
flags=ui.WINDOW_FLAGS_MENU_BAR,
menu_path=MENU_PATH,
width=600,
height=800,
visible=False,
visibility_changed_fn=self._visibility_changed_fn,
)
self.__window.frame.set_style(get_window_style())
with self.__window.menu_bar:
for menu_name, menu_info in MENU_DEFINITIONS.items():
with ui.Menu(menu_name):
for (item_name, item_function, item_tooltip) in menu_info:
ui.MenuItem(item_name, tooltip=item_tooltip, triggered_fn=getattr(self, item_function))
self.__window.menu_bar.visible = True
self.__window.frame.set_build_fn(self.__rebuild_window_frame)
self.__window.frame.rebuild()
def destroy(self):
"""
Called by the extension when it is being unloaded. Due to some ambiguities in references to C++ bound
objects endemic to UI calls the explicit destroy must happen to avoid leaks.
"""
ogt.dbg_ui(f"Destroying the OGN editor window {self} and {self.__extension_manager}")
with suppress(AttributeError):
self.__window.visible = False
with suppress(KeyError, AttributeError):
self.__widgets[ID_FRAME_OGN_CONTENTS].set_build_fn(None)
with suppress(AttributeError):
self.__window.frame.set_build_fn(None)
# Ordering is important for ensuring owners destroy references last.
ogt.destroy_property(self, "__widgets")
ogt.destroy_property(self, "__extension_manager")
ogt.destroy_property(self, "__file_manager")
ogt.destroy_property(self, "__node_view")
ogt.destroy_property(self, "__input_attribute_view")
ogt.destroy_property(self, "__output_attribute_view")
ogt.destroy_property(self, "__tests_view")
ogt.destroy_property(self, "__controller")
ogt.destroy_property(self, "__model")
ogt.destroy_property(self, "__window")
Singleton.forget(Editor)
# ----------------------------------------------------------------------
def show_window(self):
"""Show the currently defined window"""
self.__window.visible = True
def hide_window(self):
self.__window.visible = False
def _visibility_changed_fn(self, visible):
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(MENU_PATH, visible)
# ----------------------------------------------------------------------
def is_visible(self):
"""Returns the visibility state of our window"""
return self.__window and self.__window.visible
# ----------------------------------------------------------------------
def __on_node_class_changed(self):
"""Callback executed when the node class name changed as a result of a file operation"""
ogt.dbg_ui("Node class changed")
new_path = self.__file_manager.ogn_path
if new_path is not None:
self.__extension_manager.node_class = os.path.splitext(os.path.basename(new_path))[0]
# ----------------------------------------------------------------------
def _on_menu_file_open(self):
"""Callback executed when there is a request to open a new .ogn file"""
ogt.dbg_ui("Editor._on_menu_file_open")
self.__file_manager.open(on_open_done=lambda: asyncio.ensure_future(self.__file_opened()))
self.__on_node_class_changed()
# ----------------------------------------------------------------------
def _on_menu_file_save(self):
"""Callback executed when there is a request to save a new .ogn file"""
ogt.dbg_ui("Editor._on_menu_file_save")
self.__file_manager.save()
self.__on_node_class_changed()
# ----------------------------------------------------------------------
def _on_menu_file_save_as(self):
"""Callback executed when there is a request to save a new .ogn file"""
ogt.dbg_ui("Editor._on_menu_file_save_as")
self.__file_manager.save(None, True)
self.__on_node_class_changed()
# ----------------------------------------------------------------------
def _on_menu_file_new(self):
"""Callback executed when there is a request to create a new .ogn file"""
ogt.dbg_ui("Editor._on_menu_file_new")
self.__file_manager.new()
self.__window.frame.rebuild()
# ----------------------------------------------------------------------
def _on_menu_show_ogn(self):
"""Callback executed when there is a request to display the current .ogn file"""
ogt.dbg_ui("Editor._on_menu_show_ogn")
print(json.dumps(self.__controller.ogn_data, indent=4), flush=True)
# ----------------------------------------------------------------------
def _on_menu_show_extension(self):
"""Callback executed when the show extension info menu item was selected, for dumping useful information"""
manager = omni.kit.app.get_app().get_extension_manager()
print(json.dumps(manager.get_extensions(), indent=4), flush=True)
# ----------------------------------------------------------------------
def __on_ogn_changed(self, change_message=None):
"""Callback executed whenever any data affecting the .ogn file has changed"""
ogt.dbg_ui("Updating OGN frame")
try:
self.__widgets[ID_OGN_CONTENTS].text = json.dumps(self.__controller.ogn_data, indent=4)
except KeyError:
ogt.dbg_ui("-> OGN frame does not exist")
# ----------------------------------------------------------------------
def __rebuild_ogn_frame(self):
"""Construct the current contents of the .ogn file"""
ogt.dbg_ui("Rebuilding the .ogn frame")
with self.__widgets[ID_FRAME_OGN_CONTENTS]:
self.__widgets[ID_OGN_CONTENTS] = ui.Label("", style_type_name_override="Code")
self.__on_ogn_changed()
# ----------------------------------------------------------------------
def __build_ogn_frame(self):
"""Construct the collapsable frame containing the current contents of the .ogn file"""
ogt.dbg_ui("Building the .ogn frame")
self.__widgets[ID_FRAME_OGN_CONTENTS] = ui.CollapsableFrame(
title="Raw .ogn Data", tooltip=TOOLTIPS[ID_OGN_CONTENTS], collapsed=True
)
self.__widgets[ID_FRAME_OGN_CONTENTS].set_build_fn(self.__rebuild_ogn_frame)
self.__on_ogn_changed()
# ----------------------------------------------------------------------
async def __file_opened(self):
"""Callback that happens after a file has finished opening. Refresh the window if needed."""
ogt.dbg_ui("Callback after file was opened")
self.__on_node_class_changed()
self.__window.frame.rebuild()
# Make sure the file data is synchronized before redrawing the window
await omni.kit.app.get_app().next_update_async()
# ----------------------------------------------------------------------
def __rebuild_window_frame(self):
"""Callback to rebuild the window frame when the contents have changed.
Call self.__window.frame.rebuild() to trigger this rebuild manually.
"""
ogt.dbg_ui("-------------- Rebuilding the window frame --------------")
self.__widgets = {}
try:
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
name="main_frame",
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
):
with ui.VStack(**VSTACK_ARGS, name="main_vertical_stack"):
self.__extension_manager.build_ui()
self.__node_view = NodePropertiesView(self.__controller.node_properties_controller)
self.__input_attribute_view = AttributeListView(self.__controller.input_attribute_controller)
self.__output_attribute_view = AttributeListView(self.__controller.output_attribute_controller)
assert self.__node_view
assert self.__input_attribute_view
assert self.__output_attribute_view
# TODO: This is not quite coordinating properly; add it back later
if show_wip():
self.__tests_view = TestListView(self.__controller.tests_controller)
assert self.__tests_view
self.__build_ogn_frame()
except ogn.ParseError as error:
Prompt("Parse Error", f"Could not populate values due to parse error - {error}", "Okay").show()
# ----------------------------------------------------------------------
@staticmethod
def _on_menu_show_test():
"""Define a new window and show it (for debugging and testing UI features in isolation)"""
test_window = None
def rebuild_test_frame():
with test_window.frame:
with ui.VStack(**VSTACK_ARGS):
with ui.HStack():
ui.Button(width=20, height=20, style_type_name_override="AddElement", tooltip="Add an Element")
ui.CollapsableFrame(
title="Named Frame",
tooltip="This frame has a very long overlapping tooltip",
collapsed=False,
)
test_window = ui.Window("My Test Window", menu_path="Window/OmniGraph/Test Editor...", width=600, height=400)
test_window.frame.set_style(get_window_style())
test_window.frame.set_build_fn(rebuild_test_frame)
test_window.visible = True
| 17,993 | Python | 46.729443 | 119 | 0.56472 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/test_configurations.py | """
Collection of classes managing the Model-View-Controller paradigm for individual tests within the node.
This test information is collected with the node information later to form the combined .ogn file.
The classes are arranged in a hierarchy to manage the lists within lists within lists.
TestList{Model,View,Controller}: Manage the list of tests
TestsValueLists{Model, View, Controller}: Manage the set of inputs and outputs within a single test
TestsValues{Model, View, Controller}: Manage a single list of input or output values
"""
from contextlib import suppress
from typing import Any, Dict, List, Optional
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_warn
from omni import ui
from ..style import VSTACK_ARGS # noqa: PLE0402
from .change_management import ChangeManager, ChangeMessage
from .ogn_editor_utils import DestructibleButton
from .tests_data_manager import TestsDataManager
# ======================================================================
# ID for frames that will dynamically rebuild
ID_FRAME_MAIN = "testFrame"
# ======================================================================
# ID for dictionary of classes that manage subsections of the editor, named for their class
ID_INPUT_VALUES = "testManageInputs"
ID_OUTPUT_VALUES = "testManageOutputs"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {
ID_FRAME_MAIN: "Specifications for generated tests that set input values, compute, "
"then compare results against expected outputs",
ID_INPUT_VALUES: "Define a new input attribute value as part of the test setup",
ID_OUTPUT_VALUES: "Define a new output attribute value expected as the test's compute result",
}
# ======================================================================
# Label information passed as parameters (Title, Tooltip)
LABELS = {
ID_INPUT_VALUES: [
"Setting These Input Values...",
"Subsection containing inputs to be set as initial state for the test",
],
ID_OUTPUT_VALUES: [
"...Should Generate These Output Values",
"Subsection containing expected output values from running the compute with the above inputs",
],
}
# ================================================================================
class TestsValuesModel:
"""
Manager for a set of test data. Handles the data in both the raw and parsed OGN form.
The raw form is used wherever possible for more flexibility in editing, allowing temporarily illegal
data that can have notifications to the user for fixing (e.g. duplicate attribute names)
External Properties:
ogn_data
test_data
Internal Properties:
__data: Raw test data dictionary
__namespace: Namespace for the group to which this value's attribute belongs
__use_nested_parsing: True if the test inputs and outputs are grouped together without namespaces
"""
def __init__(self, test_data: Dict[str, Any], attribute_group: str, use_nested_parsing: bool):
"""
Create an initial test model.
Args:
test_data: Dictionary of test data, in the .ogn format (attribute_name: value)
is_output: True if the attribute values are outputs; guides which prefix to prepend in the OGN data
use_nested_parsing: True if the test inputs and outputs are grouped together without namespaces
"""
self.__data = test_data
self.__namespace = ogn.namespace_of_group(attribute_group)
self.__use_nested_parsing = use_nested_parsing
# ----------------------------------------------------------------------
@property
def ogn_data(self):
"""Returns the raw OGN data for this test's definition - empty data should return an empty dictionary"""
if self.__use_nested_parsing:
return {self.__namespace: {name: value for name, value in self.__data.items() if value}}
return {f"{self.__namespace}:{name}": value for name, value in self.__data.items() if value}
# ----------------------------------------------------------------------
@property
def test_data(self):
"""Return the dictionary of AttributeName:AttributeValue containing all test data in this subset"""
return self.__data
@test_data.setter
def test_data(self, new_data: Dict[str, str]):
"""Sets a new set of attribute/data values for the test"""
ogt.dbg_ui(f"Updating test data model to {new_data}")
self.__data = new_data
# ================================================================================
class TestsValuesController(ChangeManager):
"""Interface between the view and the model, making changes to the model on request
Internal Properties:
__attribute_controller: Controller managing the list of attributes accessed by this controller
__model: The model this class controls
"""
def __init__(self, model: TestsValuesModel, attribute_controller):
"""Initialize the controller with the model it will control
Args:
attribute_controller: Controller managing the list of attributes accessed by this controller
model: Model on which this controller operates
"""
super().__init__()
self.__model = model
self.__attribute_controller = attribute_controller
# ----------------------------------------------------------------------
def on_attribute_list_changed(self, change_message):
"""Callback that executes when the list of attributes changes"""
ogt.dbg_ui(f"Attribute list changed - {change_message}")
# The data does not change here since this is just an aggregator; someone might be listening that needs changes
self.on_change(change_message)
# ----------------------------------------------------------------------
@property
def available_attribute_names(self) -> List[str]:
"""Returns the list of attribute names known to this controller"""
return self.__attribute_controller.all_attribute_names
# ----------------------------------------------------------------------
@property
def test_data(self):
"""Return the dictionary of AttributeName:AttributeValue containing all test data in this subset"""
return self.__model.test_data
@test_data.setter
def test_data(self, new_data: Dict[str, str]):
"""Sets a new set of attribute/data values for the test"""
ogt.dbg_ui(f"Test Values data set to {new_data}")
self.__model.test_data = new_data
self.on_change(ChangeMessage(self))
# ================================================================================
class TestsValuesView:
"""UI for a single test's subset of data applicable to the attributes whose controller is passed in
Internal Properties:
__tooltip_id: ID for the labels and tooltips in this subsection
"""
def __init__(self, controller: TestsValuesController, tooltip_id: str):
"""Initialize the view with the controller it will use to manipulate the model"""
self.__tooltip_id = tooltip_id
self.__manager = TestsDataManager(controller, add_element_tooltip=TOOLTIPS[tooltip_id])
def on_rebuild_ui(self):
"""Callback executed when the frame in which these widgets live is rebuilt"""
with ui.VStack(**VSTACK_ARGS):
ui.Label(
LABELS[self.__tooltip_id][0],
# tooltip=LABELS[self.__tooltip_id][1],
)
self.__manager.on_rebuild_ui()
# ================================================================================
class TestsValueListsModel:
"""
Manager for a set of test data. Handles the data in both the raw and parsed OGN form.
The raw form is used wherever possible for more flexibility in editing, allowing temporarily illegal
data that can have notifications to the user for fixing (e.g. duplicate attribute names)
External Properties:
ogn_data
Internal Properties:
__inputs_model: Model managing the input values in the test
__outputs_model: Model managing the output values in the test
__description: Description of the attribute
__comments: Comments on the test as a whole, uneditable
__gpu_attributes: Attributes forced on the GPU for the test
"""
def __init__(self, test_data: Dict[str, Any]):
"""
Create an initial test model.
Args:
test_data: Dictionary of test data, in the .ogn format (attribute_name: value)
"""
ogt.dbg_ui(f"Initializing TestsValueListsModel with {test_data}")
# TODO: Pull parsing of the test data into a common location in omni.graph.tools that can be used here
# Description exists at the top level, if at all
try:
self.__description = test_data[ogn.TestKeys.DESCRIPTION]
except KeyError:
self.__description = ""
# Top level comments should be preserved
try:
self.__comments = {key: value for key, value in test_data.items() if key[0] == "$"}
except AttributeError:
self.__comments = {}
# Runtime GPU attributes are preserved
# TODO: Implement editing of this
try:
self.__gpu_attributes = test_data[ogn.TestKeys.GPU_ATTRIBUTES]
except KeyError:
self.__gpu_attributes = []
# TODO: It would be in our best interest to only support one type of test configuration
use_nested_parsing = False
# Switch parsing methods based on which type of test data configuration is present
if ogn.TestKeys.INPUTS in test_data or ogn.TestKeys.OUTPUTS in test_data:
use_nested_parsing = True
try:
input_list = test_data[ogn.TestKeys.INPUTS]
input_data = dict(input_list.items())
except KeyError:
input_data = {}
try:
output_list = test_data[ogn.TestKeys.OUTPUTS]
output_data = dict(output_list.items())
except KeyError:
output_data = {}
else:
try:
prefix = f"{ogn.INPUT_NS}:"
input_data = {
f"{key.replace(prefix, '')}": value for key, value in test_data.items() if key.find(prefix) == 0
}
except AttributeError:
input_data = {}
try:
prefix = f"{ogn.OUTPUT_NS}:"
output_data = {
f"{key.replace(prefix, '')}": value for key, value in test_data.items() if key.find(prefix) == 0
}
except AttributeError:
output_data = {}
self.__inputs_model = TestsValuesModel(input_data, ogn.INPUT_GROUP, use_nested_parsing)
self.__outputs_model = TestsValuesModel(output_data, ogn.OUTPUT_GROUP, use_nested_parsing)
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the model is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__inputs_model = None
self.__outputs_model = None
self.__description = None
self.__comments = None
self.__gpu_attributes = None
# ----------------------------------------------------------------------
@property
def ogn_data(self):
"""Returns the raw OGN data for this test's definition - empty data should return an empty dictionary"""
ogt.dbg_ui(f"Generating OGN data for value lists {self.__inputs_model} and {self.__outputs_model}")
data = self.__inputs_model.ogn_data
# Direct update is okay because the returned values were constructed, not members of the class
data.update(self.__outputs_model.ogn_data)
if self.__description:
data[ogn.TestKeys.DESCRIPTION] = self.__description
if self.__comments:
data.update(self.__comments)
if self.__gpu_attributes:
data[ogn.TestKeys.GPU_ATTRIBUTES] = self.__gpu_attributes
return data
# ================================================================================
class TestsValueListsController(ChangeManager):
"""Interface between the view and the model, making changes to the model on request
Internal Properties:
__index: Test index within the parent's list of indexes
__inputs_controller: Controller managing the list of input attributes
__model: The model this class controls
__outputs_controller: Controller managing the list of output attributes
__parent_controller: Controller for the list of properties, for changing membership callbacks
"""
def __init__(
self,
model: TestsValueListsModel,
parent_controller,
index_in_parent: int,
inputs_controller,
outputs_controller,
):
"""Initialize the controller with the model it will control
Args:
inputs_controller: Controller managing the list of input attributes
model: Model on which this controller operates
outputs_controller: Controller managing the list of output attributes
parent_controller: TestListController that aggregates this individual test
index_in_parent: This test's index within the parent's list (used for unique naming)
"""
super().__init__()
self.__model = model
self.__parent_controller = parent_controller
self.__inputs_controller = TestsValuesController(model.inputs_model, inputs_controller)
self.__outputs_controller = TestsValuesController(model.outputs_model, outputs_controller)
self.__inputs_controller.forward_callbacks_to(self)
self.__outputs_controller.forward_callbacks_to(self)
self.__index = index_in_parent
def destroy(self):
"""Called when the controller is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
super().destroy()
ogt.destroy_property(self, "__model")
ogt.destroy_property(self, "__parent_controller")
ogt.destroy_property(self, "__inputs_controller")
ogt.destroy_property(self, "__outputs_controller")
# ----------------------------------------------------------------------
@property
def model(self) -> TestsValueListsModel:
return self.__model
# ----------------------------------------------------------------------
def on_remove_test(self):
"""Callback that executes when the view wants to remove the named test"""
ogt.dbg_ui(f"Removing existing test {self.__index + 1}")
self.__parent_controller.on_remove_test(self)
# ----------------------------------------------------------------------
def on_input_attribute_list_changed(self, change_message):
"""Callback that executes when the list of input attributes changes"""
ogt.dbg_ui(f"Input attribute list changed on test {self.__index} - {change_message}")
self.__inputs_controller.on_attribute_list_changed(change_message)
# ----------------------------------------------------------------------
def on_output_attribute_list_changed(self, change_message):
"""Callback that executes when the list of output attributes changes"""
ogt.dbg_ui(f"Output attribute list changed on test {self.__index} - {change_message}")
self.__outputs_controller.on_attribute_list_changed(change_message)
# ================================================================================
class TestsValueListsView:
"""UI for the list of all tests
Internal Properties:
__controller: The controller used to manipulate the model's data
__frame: Main frame for this test's interface
__input_frame: Subframe containing input attribute values
__output_frame: Subframe containing output attribute values
__widgets: Dictionary of ID:Widget for the components of the test's frame
"""
def __init__(self, controller: TestsValueListsController):
"""Initialize the view with the controller it will use to manipulate the model"""
self.__controller = controller
self.__input_view = TestsValuesView(self.__controller._inputs_controller, ID_INPUT_VALUES)
self.__output_view = TestsValuesView(self.__controller._outputs_controller, ID_OUTPUT_VALUES)
with ui.HStack(spacing=5):
self.__remove_button = DestructibleButton(
width=20,
height=20,
style_type_name_override="RemoveElement",
clicked_fn=self.__controller.on_remove_test,
tooltip="Remove this test",
)
assert self.__remove_button
self.__frame = ui.CollapsableFrame(title=f"Test {self.__controller._index + 1}", collapsed=False)
self.__frame.set_build_fn(self.__rebuild_frame)
self.__input_frame = None
self.__output_frame = None
def destroy(self):
"""Called when the view is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
ogt.destroy_property(self, "__controller")
ogt.destroy_property(self, "__remove_button")
ogt.destroy_property(self, "__widget_models")
ogt.destroy_property(self, "__widgets")
ogt.destroy_property(self, "__managers")
ogt.destroy_property(self, "__input_view")
ogt.destroy_property(self, "__output_view")
with suppress(AttributeError):
self.__frame.set_build_fn(None)
with suppress(AttributeError):
self.__input_frame.set_build_fn(None)
with suppress(AttributeError):
self.__output_frame.set_build_fn(None)
ogt.destroy_property(self, "__frame")
# ----------------------------------------------------------------------
def __rebuild_frame(self):
"""Rebuild the contents underneath the main test frame"""
with ui.VStack(**VSTACK_ARGS):
with ui.ZStack():
ui.Rectangle(name="frame_background")
self.__input_frame = ui.Frame(name="attribute_value_frame")
with ui.ZStack():
ui.Rectangle(name="frame_background")
self.__output_frame = ui.Frame(name="attribute_value_frame")
ui.Spacer(height=2)
self.__input_frame.set_build_fn(self.__input_view.on_rebuild_ui)
self.__output_frame.set_build_fn(self.__output_view.on_rebuild_ui)
# ================================================================================
class TestListModel:
"""
Manager for an entire list of tests. It only manages the list as a whole. Individual tests are all
managed through TestsValueListsModel
External Properties:
models
ogn_data
Internal Properties:
__models: List of TestsValueListsModels for each test in the list
"""
def __init__(self, test_data: Optional[List[Dict]]):
"""
Create an initial test model from the list of tests (empty list if None)
Args:
test_data: Initial list of test dictionaries
"""
self.__models = []
if test_data is not None:
self.__models = [TestsValueListsModel(test_datum) for test_datum in test_data]
# ----------------------------------------------------------------------
def destroy(self):
"""Run when the model is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
ogt.destroy_property(self, "__models")
# ----------------------------------------------------------------------
@property
def ogn_data(self) -> Dict:
"""Return a dictionary representing the list of tests in .ogn format, None if the list is empty"""
ogt.dbg_ui(f"Generating OGN data for {self.__models}")
return [model.ogn_data for model in self.__models] if self.__models else None
# ----------------------------------------------------------------------
@property
def models(self) -> List:
"""Return a list of the models managing the individual tests"""
return self.__models
# ----------------------------------------------------------------------
def add_new_test(self) -> TestsValueListsModel:
"""Create a new empty test and add it to the list
Returns:
Newly created test values model
"""
self.__models.append(TestsValueListsModel({}))
return self.__models[-1]
# ----------------------------------------------------------------------
def remove_test(self, test_model):
"""Remove the test encapsulated in the given model"""
try:
self.__models.remove(test_model)
except ValueError:
log_warn(f"Failed to remove test model for {test_model.name}")
# ================================================================================
class TestListController(ChangeManager):
"""Interface between the view and the model, making changes to the model on request
Internal Properties:
__inputs_controller: Controller managing the list of input attributes
__model: The model this class controls
__outputs_controller: Controller managing the list of output attributes
"""
def __init__(self, model: TestListModel, inputs_controller, outputs_controller):
"""Initialize the controller with the model it will control"""
super().__init__()
self.__model = model
self.__inputs_controller = inputs_controller
self.__outputs_controller = outputs_controller
# The tests need to know if attributes changed in order to update the list of available attributes
# as well as potentially removing references to attributes that no longer exist.
inputs_controller.add_change_callback(self.__on_input_attribute_list_changed)
outputs_controller.add_change_callback(self.__on_output_attribute_list_changed)
inputs_controller.forward_callbacks_to(self)
outputs_controller.forward_callbacks_to(self)
self.__controllers = [
TestsValueListsController(model, self, index, inputs_controller, outputs_controller)
for (index, model) in enumerate(self.__model.models)
]
# Be sure to forward all change callbacks from the children to this parent
for controller in self.__controllers:
controller.forward_callbacks_to(self)
def destroy(self):
"""Called when the controller is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
super().destroy()
ogt.destroy_property(self, "__model")
ogt.destroy_property(self, "__controllers")
ogt.destroy_property(self, "__inputs_controller")
ogt.destroy_property(self, "__outputs_controller")
# ----------------------------------------------------------------------
def on_new_test(self):
"""Callback that executes when the view wants to add a new test
A test model controller and model are added, but no new OGN data will generate until values are set.
"""
ogt.dbg_ui("Adding a new test")
new_model = self.__model.add_new_test()
new_index = len(self.__controllers)
self.__controllers.append(
TestsValueListsController(new_model, self, new_index, self.__inputs_controller, self.__outputs_controller)
)
self.__controllers[-1].forward_callbacks_to(self)
self.on_change()
# ----------------------------------------------------------------------
def on_remove_test(self, test_controller: TestsValueListsController):
"""Callback that executes when the given controller's test was removed"""
ogt.dbg_ui("Removing an existing test")
try:
self.__model.remove_test(test_controller.model)
self.__controllers.remove(test_controller)
except ValueError:
log_warn(f"Failed removal of controller for {test_controller}")
self.on_change()
# ----------------------------------------------------------------------
def __on_input_attribute_list_changed(self, change_message):
"""Callback that executes when the list of input attributes changes"""
ogt.dbg_ui(f"Input attribute list changed on {change_message}")
for controller in self.__controllers:
controller.on_input_attribute_list_changed(change_message)
# ----------------------------------------------------------------------
def __on_output_attribute_list_changed(self, change_message):
"""Callback that executes when the list of output attributes changes"""
ogt.dbg_ui(f"Output attribute list changed on {change_message}")
for controller in self.__controllers:
controller.on_output_attribute_list_changed(change_message)
# ----------------------------------------------------------------------
@property
def all_test_controllers(self) -> List[TestsValueListsController]:
"""Returns the list of all controllers for tests in this list"""
return self.__controllers
# ================================================================================
class TestListView:
"""UI for a list of tests
Internal Properties:
__test_views: Per-test set of views
__controller: The controller used to manipulate the model's data
__frame: Main frame for this test's interface
"""
def __init__(self, controller: TestListController):
"""Initialize the view with the controller it will use to manipulate the model"""
self.__controller = controller
self.__test_views = []
self.__add_button = None
self.__frame = ui.CollapsableFrame(
title="Tests",
# tooltip=TOOLTIPS[ID_FRAME_MAIN],
collapsed=True,
)
self.__frame.set_build_fn(self.__rebuild_frame)
self.__controller.add_change_callback(self.__on_list_change)
def destroy(self):
"""Called when the view is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
ogt.destroy_property(self, "__test_views")
ogt.destroy_property(self, "__add_button")
ogt.destroy_property(self, "__controller")
with suppress(AttributeError):
self.__frame.set_build_fn(None)
ogt.destroy_property(self, "__frame")
# ----------------------------------------------------------------------
def __on_list_change(self, change_message):
"""Callback executed when a member of the list changes.
Args:
change_message: Message with information about the change
"""
ogt.dbg_ui(f"List change called on {self} with {change_message}")
# If the main controller was requesting the change then the frame must be rebuilt, otherwise the
# individual test controllers are responsible for updating just their frame.
if self.__controller == change_message.caller:
self.__frame.rebuild()
# ----------------------------------------------------------------------
def __rebuild_frame(self):
"""Rebuild the contents underneath the main test frame"""
ogt.dbg_ui("Rebuilding the frame tests")
self.__test_views = []
with ui.VStack(**VSTACK_ARGS):
self.__add_button = DestructibleButton(
width=20,
height=20,
style_type_name_override="AddElement",
clicked_fn=self.__controller.on_new_test,
tooltip="Add a new test",
)
assert self.__add_button
# Reconstruct the list of per-test views. Construction instantiates their UI.
self.__test_views = [
TestsValueListsView(controller) for controller in self.__controller.all_test_controllers
]
assert self.__test_views
| 28,260 | Python | 43.020249 | 119 | 0.577707 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/main_generator.py | """
Management for the functions that generate code from the .ogn files.
"""
import os
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
# ================================================================================
class Generator:
"""Class responsible for generating files from the current .ogn model"""
def __init__(self, extension: ogn.OmniGraphExtension):
"""Initialize the model being used for generation
Args:
extension: Container with information needed to configure the parser
"""
self.ogn_file_path = None
self.extension = extension
self.node_interface_wrapper = None
self.configuration = None
# ----------------------------------------------------------------------
def parse(self, ogn_file_path: str):
"""Perform an initial parsing pass on a .ogn file, keeping the parse information locally for later generation
Args:
ogn_file_path: Path to the .ogn file to use for regeneration
Raises:
ParseError: File parsing failed
FileNotFoundError: .ogn file did not exist
"""
ogt.dbg_ui(f"Parsing OGN file {ogn_file_path}")
self.ogn_file_path = ogn_file_path
# Parse the .ogn file
with open(ogn_file_path, "r", encoding="utf-8") as ogn_fd:
self.node_interface_wrapper = ogn.NodeInterfaceWrapper(ogn_fd, self.extension.extension_name)
ogt.dbg_ui(f"Generated a wrapper {self.node_interface_wrapper}")
# Set up the configuration to write into the correct directories
base_name, _ = os.path.splitext(os.path.basename(ogn_file_path))
self.configuration = ogn.GeneratorConfiguration(
ogn_file_path,
self.node_interface_wrapper.node_interface,
self.extension.import_path,
self.extension.import_path,
base_name,
None,
ogn.OGN_PARSE_DEBUG,
og.Settings.generator_settings(),
)
# ----------------------------------------------------------------------
def check_wrapper(self):
"""Check to see if the node_interface_wrapper was successfully parsed
Raises:
NodeGenerationError if a parsed interface was not available
"""
if self.node_interface_wrapper is None:
raise ogn.NodeGenerationError(f"Cannot generate file due to parse error in {self.ogn_file_path}")
# ----------------------------------------------------------------------
def generate_cpp(self):
"""Take the existing OGN model and generate the C++ database interface header file for it
Returns:
True if the file was successfully generated, else False
"""
ogt.dbg_ui("Generator::generate_cpp")
self.check_wrapper()
# Generate the C++ NODEDatabase.h file if this .ogn description allows it
if self.node_interface_wrapper.can_generate("c++"):
self.configuration.destination_directory = self.extension.ogn_include_directory
ogn.generate_cpp(self.configuration)
else:
ogt.dbg_ui("...Skipping -> File cannot generate C++ database")
# ----------------------------------------------------------------------
def generate_python(self):
"""Take the existing OGN model and generate the Python database interface file for it
Returns:
True if the file was successfully generated, else False
"""
ogt.dbg_ui("Generator::generate_python")
self.check_wrapper()
# Generate the Python NODEDatabase.py file if this .ogn description allows it
if self.node_interface_wrapper.can_generate("python"):
self.configuration.destination_directory = self.extension.ogn_python_directory
ogn.generate_python(self.configuration)
else:
ogt.dbg_ui("...Skipping -> File cannot generate Python database")
# ----------------------------------------------------------------------
def generate_documentation(self):
"""Take the existing OGN model and generate the documentation file for it
Returns:
True if the file was successfully generated, else False
"""
ogt.dbg_ui("Generator::generate_documentation")
self.check_wrapper()
# Generate the documentation NODE.rst file if this .ogn description allows it
if self.node_interface_wrapper.can_generate("docs"):
self.configuration.destination_directory = self.extension.ogn_docs_directory
ogn.generate_documentation(self.configuration)
else:
ogt.dbg_ui("...Skipping -> File cannot generate documentation file")
# ----------------------------------------------------------------------
def generate_tests(self):
"""Take the existing OGN model and generate the tests file for it
Returns:
True if the file was successfully generated, else False
"""
ogt.dbg_ui("Generator::generate_tests")
self.check_wrapper()
# Generate the tests TestNODE.py file if this .ogn description allows it
if self.node_interface_wrapper.can_generate("tests"):
self.configuration.destination_directory = self.extension.ogn_tests_directory
ogn.generate_tests(self.configuration)
else:
ogt.dbg_ui("...Skipping -> File cannot generate tests file")
# ----------------------------------------------------------------------
def generate_usd(self):
"""Take the existing OGN model and generate the usd file for it
Returns:
True if the file was successfully generated, else False
"""
ogt.dbg_ui("Generator::generate_usd")
self.check_wrapper()
# Generate the USD NODE_Template.usda file if this .ogn description allows it
if self.node_interface_wrapper.can_generate("usd"):
self.configuration.destination_directory = self.extension.ogn_usd_directory
ogn.generate_usd(self.configuration)
else:
ogt.dbg_ui("...Skipping -> File cannot generate usd file")
# ----------------------------------------------------------------------
def generate_template(self):
"""Take the existing OGN model and generate the template file for it
Returns:
True if the file was successfully generated, else False
"""
ogt.dbg_ui("Generator::generate_template")
self.check_wrapper()
# Generate the template NODE_Template.c++|py file if this .ogn description allows it
if self.node_interface_wrapper.can_generate("template"):
self.configuration.destination_directory = self.extension.ogn_nodes_directory
ogn.generate_template(self.configuration)
else:
ogt.dbg_ui("...Skipping -> File cannot generate template file")
| 6,998 | Python | 40.414201 | 117 | 0.579737 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/attribute_base_type_manager.py | """
Manager class for the attribute base type combo box.
"""
from typing import Callable, Optional
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_warn
from omni import ui
from .ogn_editor_utils import ComboBoxOptions
BaseTypeChangeCallback = Optional[Callable[[str], None]]
# ======================================================================
# ID values for widgets that are editable or need updating
ID_ATTR_BASE_DATA_TYPE = "attributeBaseDataType"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {ID_ATTR_BASE_DATA_TYPE: "Base type of an attribute's data"}
# ======================================================================
class AttributeBaseTypeComboBox(ui.AbstractItemModel):
"""Implementation of a combo box that shows attribute base data types available
Internal Properties:
__controller: Controller managing the type information
__type_changed_callback: Option callback to execute when a new base type is chosen
__current_index: Model for the currently selected value
__subscription: Subscription object for the type change callback
__items: List of models for each legal value in the combobox
"""
OPTIONS = sorted(list(ogn.ALL_ATTRIBUTE_TYPES.keys()) + list(ogn.ATTRIBUTE_UNION_GROUPS.keys()))
OPTION_INDEX = {}
for (index, attribute_type_name) in enumerate(OPTIONS):
OPTION_INDEX[attribute_type_name] = index
def __init__(self, controller, type_changed_callback: BaseTypeChangeCallback = None):
"""Initialize the attribute base type combo box details"""
super().__init__()
self.__controller = controller
self.__current_index = ui.SimpleIntModel()
self.__type_changed_callback = type_changed_callback
try:
self.__current_index.set_value(self.OPTION_INDEX[self.__controller.base_type])
except KeyError:
log_warn(f"Initial attribute type {self.__controller.base_type} not recognized")
self.__subscription = self.__current_index.subscribe_value_changed_fn(self.__on_base_type_changed)
assert self.__subscription
# Using a list comprehension instead of values() guarantees the pre-sorted ordering
self.__items = [ComboBoxOptions(attribute_type_name) for attribute_type_name in self.OPTIONS]
def destroy(self):
"""Called when the widget is being destroyed, to remove callbacks"""
self.__controller = None
self.__subscription = None
self.__type_changed_callback = None
ogt.destroy_property(self, "__current_index")
ogt.destroy_property(self, "__items")
def get_item_children(self, item):
"""Get the model children of this item"""
return self.__items
def get_item_value_model(self, item, column_id: int):
"""Get the model at the specified column_id"""
if item is None:
return self.__current_index
return item.model
def __on_base_type_changed(self, new_value: ui.SimpleIntModel):
"""Callback executed when a new base type was selected"""
self._item_changed(None)
try:
ogt.dbg_ui(f"Set attribute base type to {new_value.as_int}")
new_type_name = self.OPTIONS[new_value.as_int]
ogt.dbg_ui(f"Type name is {new_type_name}")
if self.__type_changed_callback:
self.__type_changed_callback(new_type_name)
except KeyError:
log_warn(f"Base type index change was rejected - {new_value.as_int} not found")
except AttributeError as error:
log_warn(f"base type '{new_value.as_int}' on attribute '{self.__controller.name}' was rejected - {error}")
# ======================================================================
class AttributeBaseTypeManager:
"""Handle the combo box and responses for getting and setting attribute base type values
Internal Properties:
__controller: Controller for the data of the attribute this will modify
__widget: ComboBox widget controlling the base type
__widget_model: Model for the ComboBox value
"""
def __init__(self, controller, type_changed_callback: BaseTypeChangeCallback = None):
"""Set up the initial UI and model
Args:
controller: AttributePropertiesController in charge of the data for the attribute being managed
"""
self.__controller = controller
assert self.__controller
self.__widget_model = AttributeBaseTypeComboBox(controller, type_changed_callback)
self.__widget = ui.ComboBox(
self.__widget_model,
alignment=ui.Alignment.LEFT_CENTER,
width=80,
name=ID_ATTR_BASE_DATA_TYPE,
tooltip=TOOLTIPS[ID_ATTR_BASE_DATA_TYPE],
)
assert self.__widget
def destroy(self):
"""Called to clean up when the widget is being destroyed"""
self.__controller = None
ogt.destroy_property(self, "__widget")
ogt.destroy_property(self, "__widget_model")
| 5,162 | Python | 40.975609 | 118 | 0.625145 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/attribute_tuple_count_manager.py | """
Manager class for the attribute tuple count combo box.
"""
from typing import Callable, Optional
import omni.graph.tools as ogt
from carb import log_warn
from omni import ui
from .ogn_editor_utils import ComboBoxOptions
TupleChangeCallback = Optional[Callable[[int], None]]
# ======================================================================
# ID values for widgets that are editable or need updating
ID_ATTR_TYPE_TUPLE_COUNT = "attributeTypeTupleCount"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {ID_ATTR_TYPE_TUPLE_COUNT: "Fixed number of basic elements, e.g. 3 for a float[3]"}
# ======================================================================
class AttributeTupleComboBox(ui.AbstractItemModel):
"""Implementation of a combo box that shows attribute tuple counts available
Internal Properties:
__controller: Controller for the data of the attribute this will modify
__legal_values: List of tuples the current attribute type supports
__value_index: Dictionary of tuple-value to combobox index for reverse lookup
__count_changed_callback: Option callback to execute when a new tuple count is chosen
__current_index: Model for the currently selected value
__subscription: Subscription object for the tuple count change callback
__items: List of models for each legal value in the combobox
"""
def __init__(self, controller, count_changed_callback: TupleChangeCallback = None):
"""Initialize the attribute tuple count combo box details"""
super().__init__()
self.__controller = controller
self.__legal_values = controller.tuples_supported
self.__value_index = {}
for (index, value) in enumerate(self.__legal_values):
self.__value_index[value] = index
self.__count_changed_callback = count_changed_callback
self.__current_index = ui.SimpleIntModel()
self.__current_index.set_value(self.__value_index[self.__controller.tuple_count])
self.__subscription = self.__current_index.subscribe_value_changed_fn(self.__on_tuple_count_changed)
assert self.__subscription
# Using a list comprehension instead of values() guarantees the ordering
self.__items = [ComboBoxOptions(str(value)) for value in self.__legal_values]
def destroy(self):
"""Cleanup when the combo box is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__count_changed_callback = None
self.__subscription = None
self.__legal_values = None
self.__value_index = None
ogt.destroy_property(self, "__current_index")
ogt.destroy_property(self, "__items")
def get_item_children(self, item):
"""Get the model children of this item"""
return self.__items
def get_item_value_model(self, item, column_id: int):
"""Get the model at the specified column_id"""
if item is None:
return self.__current_index
return item.model
def __on_tuple_count_changed(self, new_value: ui.SimpleIntModel):
"""Callback executed when a new tuple count was selected"""
self._item_changed(None)
new_selection = "Unknown"
try:
# The combo box new_value is the index of the selection within the list of legal values.
# Report the index selected in case there isn't a corresponding selection value, then use the selection
# value to define the new tuple count.
ogt.dbg_ui(f"Set attribute tuple count to {new_value.as_int}")
new_selection = self.__legal_values[new_value.as_int]
if self.__count_changed_callback:
self.__count_changed_callback(new_selection)
except AttributeError as error:
log_warn(f"Tuple count '{new_selection}' on attribute '{self.__controller.name}' was rejected - {error}")
# ======================================================================
class AttributeTupleCountManager:
"""Handle the combo box and responses for getting and setting attribute tuple count values
Properties:
__widget: ComboBox widget controlling the tuple count
__widget_model: Model for the ComboBox value
"""
def __init__(self, controller, count_changed_callback: TupleChangeCallback = None):
"""Set up the initial UI and model
Args:
controller: AttributePropertiesController in charge of the data for the attribute being managed
count_changed_callback: Optional callback to execute when a new tuple count is chosen
"""
self.__widget_model = AttributeTupleComboBox(controller, count_changed_callback)
self.__widget = ui.ComboBox(
self.__widget_model,
alignment=ui.Alignment.LEFT_BOTTOM,
name=ID_ATTR_TYPE_TUPLE_COUNT,
tooltip=TOOLTIPS[ID_ATTR_TYPE_TUPLE_COUNT],
)
assert self.__widget
def destroy(self):
"""Cleanup when the object is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
ogt.destroy_property(self, "__widget_model")
ogt.destroy_property(self, "__widget")
| 5,300 | Python | 43.175 | 117 | 0.626038 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/file_manager.py | """
Support for all file operations initiated by the Editor interface
"""
from __future__ import annotations
import asyncio
import json
import os
from typing import Optional
import omni.graph.tools as ogt
from carb import log_error
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.widget.prompt import Prompt
from omni.kit.window.filepicker import FilePickerDialog
from .ogn_editor_utils import Callback, OptionalCallback, callback_name
# ======================================================================
# Shared set of filters for the open and save dialogs
OGN_FILTERS = [("*.ogn", ".ogn Files (*.ogn)")]
# ======================================================================
class FileManager:
"""Manager of the file interface to .ogn files.
External Properties:
ogn_path: Full path to the .ogn file
ogn_file: File component of ogn_path
ogn_directory: Directory component of ogn_path
Internal Properties:
__controller: Controller class providing write access to the OGN data model
__current_directory: Directory in which the current file lives.
__current_file: Name of the .ogn file as of the last open or save. None if the data does not come from a file.
__open_file_dialog: External window used for opening a new .ogn file
__save_file_dialog: External window used for saving the .ogn file
__unsaved_changes: True if there are changes in the file management that require the file to be saved again
"""
def __init__(self, controller):
"""Set up the default file picker dialogs to be used later"""
ogt.dbg_ui("Initializing the file manager")
self.__current_file = None
self.__current_directory = None
self.__controller = controller
self.__unsaved_changes = controller.is_dirty()
self.__open_file_dialog = None
self.__save_file_dialog = None
# ----------------------------------------------------------------------
def __on_filter_ogn_files(self, item: FileBrowserItem) -> bool:
"""Callback to filter the choices of file names in the open or save dialog"""
if not item or item.is_folder:
return True
ogt.dbg_ui(f"Filtering OGN files on {item.path}")
# Show only files with listed extensions
return os.path.splitext(item.path)[1] == ".ogn" and os.path.basename(item.path).startswith("Ogn")
# ----------------------------------------------------------------------
def __on_file_dialog_error(self, error: str):
"""Callback executed when there is an error in the file dialogs"""
log_error(error)
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the FileManager is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__current_file = None
self.__current_directory = None
self.__controller = None
self.__save_file_dialog = None
# ----------------------------------------------------------------------
@property
def ogn_path(self) -> Optional[str]:
"""Returns the current full path to the .ogn file, None if that path is not fully defined"""
try:
return os.path.join(self.__current_directory, self.__current_file)
except TypeError:
return None
# ----------------------------------------------------------------------
@property
def ogn_file(self) -> Optional[str]:
"""Returns the name of the current .ogn file"""
return self.__current_file
@ogn_file.setter
def ogn_file(self, new_file: str):
"""Sets a new directory in which the .ogn file will reside. The base name of the file is unchanged"""
ogt.dbg_ui(f"Setting new FileManager ogn_file to {new_file}")
if new_file != self.__current_file:
self.__unsaved_changes = True
self.__current_file = new_file
# ----------------------------------------------------------------------
@property
def ogn_directory(self) -> Optional[str]:
"""Returns the current directory in which the .ogn file will reside"""
return self.__current_directory
@ogn_directory.setter
def ogn_directory(self, new_directory: str):
"""Sets a new directory in which the .ogn file will reside. The base name of the file is unchanged"""
ogt.dbg_ui(f"Setting new FileManager ogn_directory to {new_directory}")
if self.__current_directory != new_directory:
self.__current_directory = new_directory
# ----------------------------------------------------------------------
@staticmethod
def __on_remove_ogn_file(file_to_remove: str):
"""Callback executed when removal of the file is requested"""
try:
os.remove(file_to_remove)
except Exception as error: # noqa: PLW0703
log_error(f"Could not remove existing file {file_to_remove} - {error}")
# ----------------------------------------------------------------------
def remove_obsolete_file(self, old_file_path: Optional[str]):
"""Check to see if an obsolete file path exists and request deletion if it does"""
if old_file_path is not None and os.path.isfile(old_file_path):
old_file_name = os.path.basename(old_file_path)
Prompt(
"Remove old file",
f"Delete the existing .ogn file with the old name {old_file_name}?",
ok_button_text="Yes",
cancel_button_text="No",
cancel_button_fn=self.__on_remove_ogn_file(old_file_path),
modal=True,
).show()
# ----------------------------------------------------------------------
def has_unsaved_changes(self) -> bool:
"""Returns True if the file needs to be saved to avoid losing data"""
return self.__controller.is_dirty() or self.__unsaved_changes
# ----------------------------------------------------------------------
def save_failed(self) -> bool:
"""Returns True if the most recent save failed for any reason"""
return self.has_unsaved_changes()
# ----------------------------------------------------------------------
async def __show_prompt_to_save(self, job: Callback):
"""Show a prompt requesting to save the current file.
If yes then save it and run the job.
If no then just run the job.
If cancel then do nothing
"""
ogt.dbg_ui(f"Showing save prompt with callback {job}")
Prompt(
title="Save OGN File",
text="Would you like to save this file?",
ok_button_text="Save",
middle_button_text="Don't Save",
cancel_button_text="Cancel",
ok_button_fn=lambda: self.save(on_save_done=lambda *args: job()),
middle_button_fn=lambda: job() if job is not None else None,
).show()
# ----------------------------------------------------------------------
def __prompt_if_unsaved_data(self, data_is_dirty: bool, job: Callback):
"""Run a job if there is no unsaved OGN data, otherwise first prompt to save the current data."""
ogt.dbg_ui("Checking for unsaved data")
if data_is_dirty:
asyncio.ensure_future(self.__show_prompt_to_save(job))
elif job is not None:
job()
# ----------------------------------------------------------------------
def __on_click_open(self, file_name: str, directory_path: str, on_open_done: OptionalCallback):
"""Callback executed when the user selects a file in the open file dialog
on_open_done() will be executed after the file is opened, if not None
"""
ogn_path = os.path.join(directory_path, file_name)
ogt.dbg_ui(f"Trying to open the file {ogn_path}")
def open_from_ogn():
"""Open the OGN file into the currently managed model.
Posts an informational dialog if the file could not be opened.
"""
ogt.dbg_ui(f"Opening data from OGN file {ogn_path} - {callback_name(on_open_done)}")
try:
self.__controller.set_ogn_data(ogn_path)
(self.__current_directory, self.__current_file) = os.path.split(ogn_path)
if on_open_done is not None:
on_open_done()
except Exception as error: # noqa: PLW0703
Prompt("Open Error", f"File open failed: {error}", "Okay").show()
if self.has_unsaved_changes():
ogt.dbg_ui("...file is dirty, prompting to overwrite")
asyncio.ensure_future(self.__show_prompt_to_save(open_from_ogn))
else:
open_from_ogn()
self.__open_file_dialog.hide()
# ----------------------------------------------------------------------
def open(self, on_open_done: OptionalCallback = None): # noqa: A003
"""Bring up a file picker to choose a USD file to open.
If current data is dirty, a prompt will show to let you save it.
Args:
on_open_done: Function to call after the open is finished
"""
ogt.dbg_ui(f"Opening up file open dialog - {callback_name(on_open_done)}")
def __on_click_cancel(file_name: str, directory_name: str):
"""Callback executed when the user cancels the file open dialog"""
ogt.dbg_ui("Clicked cancel in file open")
self.__open_file_dialog.hide()
if self.__open_file_dialog is None:
self.__open_file_dialog = FilePickerDialog(
"Open .ogn File",
allow_multi_selection=False,
apply_button_label="Open",
click_apply_handler=lambda filename, dirname: self.__on_click_open(filename, dirname, on_open_done),
click_cancel_handler=__on_click_cancel,
file_extension_options=OGN_FILTERS,
item_filter_fn=self.__on_filter_ogn_files,
error_handler=self.__on_file_dialog_error,
)
self.__open_file_dialog.refresh_current_directory()
self.__open_file_dialog.show(path=self.__current_directory)
# ----------------------------------------------------------------------
def reset_ogn_data(self):
"""Initialize the OGN content to an empty node."""
ogt.dbg_ui("Resetting the content")
self.__controller.set_ogn_data(None)
self.__current_file = None
# ----------------------------------------------------------------------
def new(self):
"""Initialize the OGN content to an empty node.
If current data is dirty, a prompt will show to let you save it.
"""
ogt.dbg_ui("Creating a new node")
self.__prompt_if_unsaved_data(self.has_unsaved_changes(), self.reset_ogn_data)
# ----------------------------------------------------------------------
def __save_as_ogn(self, new_ogn_path: str, on_save_done: OptionalCallback):
"""Save the OGN content into the named file.
Posts an informational dialog if the file could not be saved.
"""
ogt.dbg_ui(f"Saving OGN to file {new_ogn_path} - {callback_name(on_save_done)}")
try:
with open(new_ogn_path, "w", encoding="utf-8") as json_fd:
json.dump(self.__controller.ogn_data, json_fd, indent=4)
(self.__current_directory, self.__current_file) = os.path.split(new_ogn_path)
self.__controller.set_clean()
self.__unsaved_changes = False
if on_save_done is not None:
on_save_done()
except Exception as error: # noqa: PLW0703
Prompt("Save Error", f"File save failed: {error}", "Okay").show()
# ----------------------------------------------------------------------
def __on_click_save(self, file_name: str, directory_path: str, on_save_done: OptionalCallback):
"""Save the file, prompting to overwrite if it already exists.
Args:
on_save_done: Function to call after save is complete (None if nothing to do)
"""
(_, ext) = os.path.splitext(file_name)
if ext != ".ogn":
file_name = f"{file_name}.ogn"
new_ogn_path = os.path.join(directory_path, file_name)
ogt.dbg_ui(f"Saving OGN, checking existence first, to file {new_ogn_path} - {callback_name(on_save_done)}")
if os.path.exists(new_ogn_path):
Prompt(
title="Overwrite OGN File",
text=f"File {os.path.basename(new_ogn_path)} already exists, do you want to overwrite it?",
ok_button_text="Yes",
cancel_button_text="No",
ok_button_fn=lambda: self.__save_as_ogn(new_ogn_path, on_save_done),
).show()
else:
self.__save_as_ogn(new_ogn_path, on_save_done)
self.__save_file_dialog.hide()
# ----------------------------------------------------------------------
def save(self, on_save_done: OptionalCallback = None, open_save_dialog: bool = False):
"""Save currently opened OGN data to file. Will call Save As for a newly created file"""
ogt.dbg_ui(f"Opening up file save dialog - {callback_name(on_save_done)}")
# If there are no unsaved changes then confirm the file exists to ensure the file system did not delete it
# and if so then skip the save
if not self.has_unsaved_changes and os.path.isfile(self.ogn_path):
ogt.dbg_ui("... file is clean, no need to save")
return
def __on_click_cancel(file_name: str, directory_name: str):
"""Callback executed when the user cancels the file save dialog"""
ogt.dbg_ui("Clicked cancel in file save")
self.__save_file_dialog.hide()
if self.ogn_path is None or open_save_dialog:
if not os.path.isdir(self.__current_directory):
raise ValueError("Populate extension before saving file")
ogt.dbg_ui("Opening up the save file dialog")
if self.__save_file_dialog is None:
self.__save_file_dialog = FilePickerDialog(
"Save .ogn File",
allow_multi_selection=False,
apply_button_label="Save",
click_apply_handler=lambda filename, dirname: self.__on_click_save(filename, dirname, on_save_done),
click_cancel_handler=__on_click_cancel,
item_filter_fn=self.__on_filter_ogn_files,
error_handler=self.__on_file_dialog_error,
file_extension_options=OGN_FILTERS,
current_file_extension=".ogn",
)
self.__save_file_dialog.refresh_current_directory()
self.__save_file_dialog.show(path=self.__current_directory)
else:
ogt.dbg_ui("Saving the file under the existing name")
self.__save_as_ogn(self.ogn_path, on_save_done)
| 15,171 | Python | 45.82716 | 120 | 0.541494 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/ogn_editor_utils.py | """
Common functions used by all of the OmniGraph Node Editor implementation classes
Exports:
Callback
callback_name
ComboBoxOptions
DestructibleButton
FileCallback
FileCallbackNested
find_unique_name
ghost_int
ghost_text
OptionalCallback
PatternedStringModel
set_widget_visible
show_wip
SubscriptionManager
"""
import asyncio
import os
from typing import Callable, Dict, Optional, Tuple
import omni.graph.tools as ogt
from carb import log_warn
from omni import ui
from omni.kit.app import get_app
from omni.kit.ui import get_custom_glyph_code
from ..style import STYLE_GHOST, name_value_label # noqa: PLE0402
# Imports from other places that look like they are coming from here
from ..utils import DestructibleButton # noqa
# ======================================================================
OGN_WIP = os.getenv("OGN_WIP")
def show_wip() -> bool:
"""Returns True if work in progress should be visible"""
return OGN_WIP
# ======================================================================
# Glyph paths
GLYPH_EXCLAMATION = f'{get_custom_glyph_code("${glyphs}/exclamation.svg")}'
# ======================================================================
# Default values for initializing new data
OGN_NEW_NODE_NAME = "NewNode"
OGN_DEFAULT_CONTENT = {OGN_NEW_NODE_NAME: {"version": 1, "description": "", "language": "Python"}}
# ======================================================================
# Typing information for callback functions
Callback = Callable[[], None]
OptionalCallback = [None, Callable[[], None]]
FileCallback = [None, Callable[[str], None]]
FileCallbackNested = [None, Callable[[str, Optional[Callable]], None]]
# ======================================================================
def callback_name(job: Callable):
"""Return a string representing the possible None callback function"""
return "No callback" if job is None else f"callback - {job.__name__}"
# ======================================================================
def find_unique_name(base_name: str, names_taken: Dict):
"""Returns the base_name with a suffix that guarantees it does not appear as a key in the names_taken
find_unique_name("fred", ["fred": "flintsone", "fred0": "mercury"]) -> "fred1"
"""
if base_name not in names_taken:
return base_name
index = 0
while f"{base_name}{index}" in names_taken:
index += 1
return f"{base_name}{index}"
# =====================================================================
def set_widget_visible(widget: ui.Widget, visible) -> bool:
"""
Utility for using in lambdas, changes the visibility of a widget.
Returns True so that it can be combined with other functions in a lambda:
lambda m: set_widget_visible(widget, not m.as_string) and callback(m.as_string)
"""
widget.visible = visible
return True
# ======================================================================
class GhostedWidgetInfo:
"""Container for the UI information pertaining to text with ghosted prompt text
Attributes:
begin_subscription: Subscription for callback when editing begins
end_subscription: Subscription for callback when editing ends
model: Main editing model
prompt_widget: Widget that is layered above the main one to show the ghosted prompt text
widget: Main editing widget
"""
def __init__(self):
"""Initialize the members"""
self.begin_subscription = None
self.end_subscription = None
self.widget = None
self.prompt_widget = None
self.model = None
# ======================================================================
def ghost_text(
label: str,
tooltip: str,
widget_id: str,
initial_value: str,
ghosted_text: str,
change_callback: Optional[Callable],
validation: Optional[Tuple[Callable, str]] = None,
) -> GhostedWidgetInfo:
"""
Creates a Label/StringField value entry pair with ghost text to prompt the user when the field is empty.
Args:
label: Text for the label of the field
tooltip: Tooltip for the label
widget_id: Base ID for the string entry widget (append "_prompt" for the ghost prompt overlay)
initial_value: Initial value for the string field
ghosted_text: Text to appear when the string is empty
change_callback: Function to call when the string changes
validation: Optional function and string pattern used to check if the entered string is valid
(no validation if None)
Returns:
4-tuple (subscription, model, widget, prompt_widget)
subscription: Subscription object for active callback
model: The model managing the editable string
widget: The widget containing the editable string
prompt_widget: The widget containing the overlay shown when the string is empty
"""
prompt_widget_id = f"{widget_id}_prompt"
name_value_label(label, tooltip)
ghost_info = GhostedWidgetInfo()
if validation is None:
ghost_info.model = ui.SimpleStringModel(initial_value)
else:
ghost_info.model = ValidatedStringModel(initial_value, validation[0], validation[1])
def ghost_edit_begin(model, label_widget):
"""Called to hide the prompt label"""
label_widget.visible = False
def ghost_edit_end(model, label_widget, callback):
"""Called to show the prompt label and process the field edit"""
if not model.as_string:
label_widget.visible = True
if callback is not None:
callback(model.as_string)
with ui.ZStack(height=0):
ghost_info.widget = ui.StringField(model=ghost_info.model, name=widget_id, tooltip=tooltip)
# Add a ghosted input prompt that only shows up when the attribute name is empty
ghost_info.prompt_widget = ui.Label(
ghosted_text, name=prompt_widget_id, style_type_name_override=STYLE_GHOST, visible=not initial_value
)
ghost_info.begin_subscription = ghost_info.model.subscribe_begin_edit_fn(
lambda model, widget=ghost_info.prompt_widget: ghost_edit_begin(model, widget)
)
ghost_info.end_subscription = ghost_info.model.subscribe_end_edit_fn(
lambda model: ghost_edit_end(model, ghost_info.prompt_widget, change_callback)
)
if label:
ghost_info.prompt_widget.visible = False
return ghost_info
# ======================================================================
def ghost_int(
label: str, tooltip: str, widget_id: str, initial_value: int, ghosted_text: str, change_callback: Optional[Callable]
) -> GhostedWidgetInfo:
"""
Creates a Label/IntField value entry pair with ghost text to prompt the user when the field is empty.
Args:
label: Text for the label of the field
tooltip: Tooltip for the label
widget_id: Base ID for the integer entry widget (append "_prompt" for the ghost prompt overlay)
initial_value: Initial value for the integer field
ghosted_text: Text to appear when the integer is empty
change_callback: Function to call when the integer changes
Returns:
4-tuple (subscription, model, widget, prompt_widget)
subscription: Subscription object for active callback
model: The model managing the editable integer
widget: The widget containing the editable integer
prompt_widget: The widget containing the overlay shown when the integer is empty
"""
ghost_info = GhostedWidgetInfo()
prompt_widget_id = f"{widget_id}_prompt"
name_value_label(label, tooltip)
ghost_info.model = ui.SimpleIntModel(initial_value)
def ghost_edit_begin(model, label_widget):
"""Called to hide the prompt label"""
label_widget.visible = False
def ghost_edit_end(model, label_widget, callback):
"""Called to show the prompt label and process the field edit"""
if not model.as_string:
label_widget.visible = True
if callback is not None:
callback(model.as_int)
with ui.ZStack(height=0):
ghost_info.widget = ui.IntField(model=ghost_info.model, name=widget_id, tooltip=tooltip)
# Add a ghosted input prompt that only shows up when the value is empty
ghost_info.prompt_widget = ui.Label(
ghosted_text, name=prompt_widget_id, style_type_name_override=STYLE_GHOST, visible=not initial_value
)
ghost_info.begin_subscription = ghost_info.model.subscribe_begin_edit_fn(
lambda model, widget=ghost_info.prompt_widget: ghost_edit_begin(model, widget)
)
ghost_info.end_subscription = ghost_info.model.subscribe_end_edit_fn(
lambda model: ghost_edit_end(model, ghost_info.prompt_widget, change_callback)
)
return ghost_info
# ======================================================================
class ComboBoxOptions(ui.AbstractItem):
"""Class that provides a conversion from simple text to a StringModel to use in ComboBox options"""
def __init__(self, text: str):
"""Initialize the internal model to the string"""
super().__init__()
self.model = ui.SimpleStringModel(text)
def destroy(self):
"""Called when the combobox option is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.model = None
# ======================================================================
class SubscriptionManager:
"""Class that manages an AbstractValueModel subscription callback, allowing enabling and disabling.
One potential use is to temporarily disable subscriptions when a change is being made in a callback that
might recursively trigger that same callback.
class ChangeMe:
def __init__(self, model):
self.model = model
self.mgr = SubscriptionManager(model, SubscriptionManager.CHANGE, on_change)
def on_change(self, new_value):
if new_value.as_int > 5:
# Resetting the value to clamp it to a range would recursively trigger this callback so shut it off
self.mgr.disable()
self.model.set_value(5)
self.mgr.enable()
"""
# Enumeration of the different types of subscriptions available
CHANGE = 0
BEGIN_EDIT = 1
END_EDIT = 2
# Model functions corresponding to the above subscription types
FUNCTION_NAMES = ["subscribe_value_changed_fn", "subscribe_begin_edit_fn", "subscribe_end_edit_fn"]
# ----------------------------------------------------------------------
def __init__(self, model: ui.AbstractValueModel, subscription_type: int, callback: callable):
"""Create an initial subscription to a model change"""
ogt.dbg_ui(f"Create subscription manager on {model} of type {subscription_type} for callback {callback}")
self.__model = model
self.__subscription_type = subscription_type
self.__callback = callback
self.__subscription = None
# On creation the subscription will be activated
self.enable()
# ----------------------------------------------------------------------
async def __do_enable(self):
"""Turn on the subscription of the given type"""
ogt.dbg_ui("__do_enable")
await get_app().next_update_async()
try:
self.__subscription = getattr(self.__model, self.FUNCTION_NAMES[self.__subscription_type])(self.__callback)
assert self.__subscription
except (KeyError, AttributeError, TypeError) as error:
log_warn(f"Failed to create subscription type {self.__subscription_type} on {self.__model} - {error}")
# ----------------------------------------------------------------------
def enable(self):
"""Turn on the subscription of the given type, syncing first to make sure no pending updates exist"""
ogt.dbg_ui("Enable")
asyncio.ensure_future(self.__do_enable())
# ----------------------------------------------------------------------
def disable(self):
"""Turn off the subscription of the given type"""
ogt.dbg_ui("Disable")
self.__subscription = None
# ======================================================================
class ValidatedStringModel(ui.AbstractValueModel):
"""String model that insists the values entered match a certain pattern"""
def __init__(self, initial_value: str, verify: Callable[[str], bool], explanation: str):
"""Initialize the legal values of the string, and human-readable explanation of the pattern
Args:
initial_value: Initial value of the string, nulled out if it is not legal
verify: Function to call to check for validity of the string
explanation: Human readable explanation of the RegEx
"""
super().__init__()
self.__verify = verify
self.__explanation = explanation
self.__value = ""
self.__initial_value = None
self.set_value(initial_value)
def get_value_as_string(self):
"""Get the internal value that has been filtered"""
ogt.dbg_ui(f"Get value as string = {self.__value}")
return self.__value
def set_value(self, new_value):
"""Implementation of the value setting that filters new values based on the pattern
Args:
new_value: Potential new value of the string
"""
self.__value = str(new_value)
self._value_changed()
def begin_edit(self):
"""Called when the user starts editing."""
self.__initial_value = self.get_value_as_string()
def end_edit(self):
"""Called when the user finishes editing."""
new_value = self.get_value_as_string()
if not self.__verify(new_value):
self.__value = self.__initial_value
self._value_changed()
log_warn(f"'{new_value}' is not legal - {self.__explanation.format(new_value)}")
| 14,153 | Python | 38.426184 | 120 | 0.603688 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/metaclass.py | from .._impl.metaclass import * # noqa: F401,PLW0401,PLW0614
| 62 | Python | 30.499985 | 61 | 0.725806 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/stage_picker_dialog.py | from .._impl.stage_picker_dialog import * # noqa: F401,PLW0401,PLW0614
| 72 | Python | 35.499982 | 71 | 0.736111 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_attribute_base.py | from .._impl.omnigraph_attribute_base import * # noqa: F401,PLW0401,PLW0614
| 77 | Python | 37.999981 | 76 | 0.753247 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/style.py | from .._impl.style import * # noqa: F401,PLW0401,PLW0614
| 58 | Python | 28.499986 | 57 | 0.706897 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_prim_node_templates.py | from .._impl.omnigraph_prim_node_templates import * # noqa: F401,PLW0401,PLW0614
| 82 | Python | 40.49998 | 81 | 0.756098 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/extension.py | from .._impl.extension import * # noqa: F401,PLW0401,PLW0614
| 62 | Python | 30.499985 | 61 | 0.725806 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/compute_node_widget.py | from .._impl.compute_node_widget import * # noqa: F401,PLW0401,PLW0614
| 72 | Python | 35.499982 | 71 | 0.736111 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/__init__.py | """This module is deprecated. Use 'import omni.graph.ui as ogu' to access the OmniGraph UI API"""
import omni.graph.tools as ogt
ogt.DeprecatedImport("Import 'omni.graph.ui as ogu' to access the OmniGraph UI API")
| 215 | Python | 42.199992 | 97 | 0.75814 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_settings_editor.py | from .._impl.omnigraph_settings_editor import * # noqa: F401,PLW0401,PLW0614
| 78 | Python | 38.499981 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_graph_selector.py | from .._impl.omnigraph_graph_selector import * # noqa: F401,PLW0401,PLW0614
| 77 | Python | 37.999981 | 76 | 0.753247 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/utils.py | from .._impl.utils import * # noqa: F401,PLW0401,PLW0614
| 58 | Python | 28.499986 | 57 | 0.706897 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/menu.py | from .._impl.menu import * # noqa: F401,PLW0401,PLW0614
| 57 | Python | 27.999986 | 56 | 0.701754 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/properties_widget.py | from .._impl.properties_widget import * # noqa: F401,PLW0401,PLW0614
| 70 | Python | 34.499983 | 69 | 0.742857 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_attribute_models.py | from .._impl.omnigraph_attribute_models import * # noqa: F401,PLW0401,PLW0614
| 79 | Python | 38.999981 | 78 | 0.759494 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/graph_variable_custom_layout.py | from .._impl.graph_variable_custom_layout import * # noqa: F401,PLW0401,PLW0614
| 81 | Python | 39.99998 | 80 | 0.753086 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_attribute_builder.py | from .._impl.omnigraph_attribute_builder import * # noqa: F401,PLW0401,PLW0614
| 80 | Python | 39.49998 | 79 | 0.7625 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/token_array_edit_widget.py | from .._impl.token_array_edit_widget import * # noqa: F401,PLW0401,PLW0614
| 76 | Python | 37.499981 | 75 | 0.736842 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_migrate_data.py | from ..._impl.omnigraph_toolkit.toolkit_migrate_data import * # noqa: F401,PLW0401,PLW0614
| 92 | Python | 45.499977 | 91 | 0.76087 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_window.py | from ..._impl.omnigraph_toolkit.toolkit_window import * # noqa: F401,PLW0401,PLW0614
| 86 | Python | 42.499979 | 85 | 0.755814 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/__init__.py | from ..._impl.omnigraph_toolkit.__init__ import * # noqa: F401,PLW0401,PLW0614
| 80 | Python | 39.49998 | 79 | 0.7 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_output.py | from ..._impl.omnigraph_toolkit.toolkit_frame_output import * # noqa: F401,PLW0401,PLW0614
| 92 | Python | 45.499977 | 91 | 0.76087 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_inspection.py | from ..._impl.omnigraph_toolkit.toolkit_frame_inspection import * # noqa: F401,PLW0401,PLW0614
| 96 | Python | 47.499976 | 95 | 0.770833 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_scene.py | from ..._impl.omnigraph_toolkit.toolkit_frame_scene import * # noqa: F401,PLW0401,PLW0614
| 91 | Python | 44.999978 | 90 | 0.758242 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_memory.py | from ..._impl.omnigraph_toolkit.toolkit_frame_memory import * # noqa: F401,PLW0401,PLW0614
| 92 | Python | 45.499977 | 91 | 0.76087 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/metadata_manager.py | from ..._impl.omnigraph_node_description_editor.metadata_manager import * # noqa
| 82 | Python | 40.49998 | 81 | 0.768293 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_controller.py | from ..._impl.omnigraph_node_description_editor.main_controller import * # noqa
| 81 | Python | 39.99998 | 80 | 0.765432 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/change_management.py | from ..._impl.omnigraph_node_description_editor.change_management import * # noqa
| 83 | Python | 40.99998 | 82 | 0.771084 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_list_manager.py | from ..._impl.omnigraph_node_description_editor.attribute_list_manager import * # noqa
| 88 | Python | 43.499978 | 87 | 0.772727 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/memory_type_manager.py | from ..._impl.omnigraph_node_description_editor.memory_type_manager import * # noqa
| 85 | Python | 41.999979 | 84 | 0.764706 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/node_language_manager.py | from ..._impl.omnigraph_node_description_editor.node_language_manager import * # noqa
| 87 | Python | 42.999979 | 86 | 0.770115 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_model.py | from ..._impl.omnigraph_node_description_editor.main_model import * # noqa
| 76 | Python | 37.499981 | 75 | 0.75 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/tests_data_manager.py | from ..._impl.omnigraph_node_description_editor.tests_data_manager import * # noqa
| 84 | Python | 41.499979 | 83 | 0.761905 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/node_properties.py | from ..._impl.omnigraph_node_description_editor.node_properties import * # noqa
| 81 | Python | 39.99998 | 80 | 0.765432 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_properties.py | from ..._impl.omnigraph_node_description_editor.attribute_properties import * # noqa
| 86 | Python | 42.499979 | 85 | 0.77907 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_union_type_adder_manager.py | from ..._impl.omnigraph_node_description_editor.attribute_union_type_adder_manager import * # noqa
| 100 | Python | 49.499975 | 99 | 0.78 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/extension_info_manager.py | from ..._impl.omnigraph_node_description_editor.extension_info_manager import * # noqa
| 88 | Python | 43.499978 | 87 | 0.772727 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_editor.py | from ..._impl.omnigraph_node_description_editor.main_editor import * # noqa
| 77 | Python | 37.999981 | 76 | 0.753247 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/test_configurations.py | from ..._impl.omnigraph_node_description_editor.test_configurations import * # noqa
| 85 | Python | 41.999979 | 84 | 0.776471 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_generator.py | from ..._impl.omnigraph_node_description_editor.main_generator import * # noqa
| 80 | Python | 39.49998 | 79 | 0.7625 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_base_type_manager.py | from ..._impl.omnigraph_node_description_editor.attribute_base_type_manager import * # noqa
| 93 | Python | 45.999977 | 92 | 0.774194 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_tuple_count_manager.py | from ..._impl.omnigraph_node_description_editor.attribute_tuple_count_manager import * # noqa
| 95 | Python | 46.999977 | 94 | 0.778947 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/file_manager.py | from ..._impl.omnigraph_node_description_editor.file_manager import * # noqa
| 78 | Python | 38.499981 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/ogn_editor_utils.py | from ..._impl.omnigraph_node_description_editor.ogn_editor_utils import * # noqa
| 82 | Python | 40.49998 | 81 | 0.756098 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_extension_shutdown.py | """Test cases for extension shutdown"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit
# ======================================================================
class TestExtensionShutdown(ogts.OmniGraphTestCase):
"""Testing for extension shutdown"""
# ----------------------------------------------------------------------
async def test_om_43835(self):
"""Verify safe ordering of node state release on extension shutdown.
The test had to be put into this extension so that it could shut down the extension where the test node
lives without unloading the test itself.
"""
manager = omni.kit.app.get_app_interface().get_extension_manager()
test_nodes_extension = "omni.graph.test"
test_node_type = f"{test_nodes_extension}.TestGracefulShutdown"
was_extension_enabled = manager.is_extension_enabled(test_nodes_extension)
try:
manager.set_extension_enabled_immediate(test_nodes_extension, True)
self.assertTrue(manager.is_extension_enabled(test_nodes_extension))
# Make sure that a dependency hasn't been inadvertently been added from the test extension to this one
ext_id = manager.get_enabled_extension_id(test_nodes_extension)
dependencies = manager.get_extension_dict(ext_id).get_dict()["dependencies"]
self.assertTrue("omni.graph.ui" not in dependencies)
# Creating a node is all that it takes to set up the state information required by the test
controller = og.Controller()
(graph, _, _, _) = controller.edit(
"/TestGraph",
{
og.Controller.Keys.CREATE_NODES: ("TestNode", test_node_type),
},
)
await controller.evaluate(graph)
# Unloading the extension triggers the state release, which will test the necessary conditions
manager.set_extension_enabled_immediate(test_nodes_extension, False)
self.assertEqual(0, og.test_failure_count(), "Test failure was reported by the node state")
finally:
manager.set_extension_enabled_immediate(test_nodes_extension, was_extension_enabled)
| 2,264 | Python | 47.191488 | 114 | 0.615724 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_api.py | """Testing the stability of the API in this module"""
import omni.graph.core.tests as ogts
import omni.graph.ui as ogu
from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents
# ======================================================================
class _TestOmniGraphUiApi(ogts.OmniGraphTestCase):
_UNPUBLISHED = ["bindings", "ogn", "tests", "omni"]
async def test_api(self):
_check_module_api_consistency(ogu, self._UNPUBLISHED) # noqa: PLW0212
_check_module_api_consistency(ogu.tests, is_test_module=True) # noqa: PLW0212
async def test_api_features(self):
"""Test that the known public API features continue to exist"""
_check_public_api_contents( # noqa: PLW0212
ogu,
[
"add_create_menu_type",
"build_port_type_convert_menu",
"ComputeNodeWidget",
"find_prop",
"GraphVariableCustomLayout",
"OmniGraphAttributeModel",
"OmniGraphTfTokenAttributeModel",
"OmniGraphBase",
"OmniGraphPropertiesWidgetBuilder",
"PrimAttributeCustomLayoutBase",
"PrimPathCustomLayoutBase",
"RandomNodeCustomLayoutBase",
"ReadPrimsCustomLayoutBase",
"remove_create_menu_type",
"SETTING_PAGE_NAME",
],
self._UNPUBLISHED,
only_expected_allowed=True,
)
_check_public_api_contents(ogu.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
| 1,638 | Python | 39.974999 | 107 | 0.567155 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/__init__.py | """There is no public API to this module."""
__all__ = []
scan_for_test_modules = True
"""The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
| 201 | Python | 32.666661 | 112 | 0.716418 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_view.py | """
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
"""
import omni.kit.test
class OmniGraphViewTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello(self):
self.assertEqual(10, 10)
| 744 | Python | 31.391303 | 82 | 0.740591 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_widgets.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import pathlib
from typing import List
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading
from omni.ui.tests.test_base import OmniUiTest
class TestOmniWidgets(OmniUiTest):
"""
Test class for testing omnigraph related widgets
"""
async def setUp(self):
await super().setUp()
usd_path = pathlib.Path(get_test_data_path(__name__))
self._golden_img_dir = usd_path.absolute().joinpath("golden_img").absolute()
self._usd_path = usd_path.absolute()
import omni.kit.window.property as p
self._w = p.get_window()
async def tearDown(self):
await super().tearDown()
async def __widget_image_test(
self,
file_path: str,
prims_to_select: List[str],
golden_img_name: str,
width=450,
height=500,
):
"""Helper to do generate a widget comparison test on a property panel"""
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window, # noqa: PLE0211,PLW0212
width=width,
height=height,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
test_file_path = self._usd_path.joinpath(file_path).absolute()
await usd_context.open_stage_async(str(test_file_path))
await wait_stage_loading()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(prims_to_select, True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name, threshold=0.15)
# Close the stage to avoid dangling references to the graph. (OM-84680)
await omni.usd.get_context().close_stage_async()
async def test_compound_node_type_widget_ui(self):
"""Tests the compound node type property pane matches the expected image"""
await self.__widget_image_test(
file_path="compound_node_test.usda",
prims_to_select=["/World/Compounds/TestCompound"],
golden_img_name="test_compound_widget.png",
height=600,
)
async def test_graph_with_variables_widget(self):
"""Tests the variable property pane on a graph prim"""
await self.__widget_image_test(
file_path="test_variables.usda",
prims_to_select=["/World/ActionGraph"],
golden_img_name="test_graph_variables.png",
height=300,
)
async def test_instance_with_variables_widget(self):
"""Tests the variable property pane on an instance prim"""
await self.__widget_image_test(
file_path="test_variables.usda",
prims_to_select=["/World/Instance"],
golden_img_name="test_instance_variables.png",
height=450,
)
| 3,577 | Python | 34.78 | 118 | 0.649427 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_property_widget.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import tempfile
from pathlib import Path
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
import omni.graph.ui._impl.omnigraph_attribute_base as ogab
import omni.graph.ui._impl.omnigraph_attribute_models as ogam
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
import omni.usd
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from pxr import Sdf, Usd
_MATRIX_DIMENSIONS = {4: 2, 9: 3, 16: 4}
# ----------------------------------------------------------------------
class TestOmniGraphWidget(OmniUiTest):
"""
Tests for OmniGraphBase and associated models in this module, the custom widget for the kit property panel uses
these models which are customized for OmniGraphNode prims.
"""
TEST_GRAPH_PATH = "/World/TestGraph"
# Before running each test
async def setUp(self):
await super().setUp()
# Ensure we have a clean stage for the test
await omni.usd.get_context().new_stage_async()
# Give OG a chance to set up on the first stage update
await omni.kit.app.get_app().next_update_async()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
extension_root_folder = Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
self._golden_img_dir = extension_root_folder.joinpath("data/tests/golden_img")
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
# Close the stage to avoid dangling references to the graph. (OM-84680)
await omni.usd.get_context().close_stage_async()
await super().tearDown()
def __attribute_type_to_name(self, attribute_type: og.Type) -> str:
"""Converts an attribute type into the canonical attribute name used by the test nodes.
The rules are:
- prefix of a_
- followed by name of attribute base type
- followed by optional _N if the component count N is > 1
- followed by optional '_array' if the type is an array
Args:
type: OGN attribute type to deconstruct
Returns:
Canonical attribute name for the attribute with the given type
"""
attribute_name = f"a_{og.Type(attribute_type.base_type, 1, 0, attribute_type.role).get_ogn_type_name()}"
attribute_name = attribute_name.replace("prim", "bundle")
if attribute_type.tuple_count > 1:
if attribute_type.role in [og.AttributeRole.TRANSFORM, og.AttributeRole.FRAME, og.AttributeRole.MATRIX]:
attribute_name += f"_{_MATRIX_DIMENSIONS[attribute_type.tuple_count]}"
else:
attribute_name += f"_{attribute_type.tuple_count}"
array_depth = attribute_type.array_depth
while array_depth > 0 and attribute_type.role not in [og.AttributeRole.TEXT, og.AttributeRole.PATH]:
attribute_name += "_array"
array_depth -= 1
return attribute_name
async def test_target_attribute(self):
"""
Exercise the target-attribute customizations for Property Panel. The related code is in
omnigraph_attribute_builder.py and targets.py
"""
usd_context = omni.usd.get_context()
keys = og.Controller.Keys
controller = og.Controller()
(_, (get_parent_prims,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("GetParentPrims", "omni.graph.nodes.GetParentPrims"),
],
},
)
# The OG attribute-base UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# Select the node.
usd_context.get_selection().set_selected_prim_paths([get_parent_prims.get_prim_path()], True)
# Wait for property panel to converge
await ui_test.human_delay(5)
# Click the Add-Relationship button
attr_name = "inputs:prims"
await ui_test.find(
f"Property//Frame/**/Button[*].identifier=='sdf_relationship_array_{attr_name}.add_relationships'"
).click()
# Wait for dialog to show up
await ui_test.human_delay(5)
# push the select-graph-target button and wait for dialog to close
await ui_test.find("Select Targets//Frame/**/Button[*].identifier=='select_graph_target'").click()
await ui_test.human_delay(5)
# Resize to fit the property panel, and take a snapshot
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
await ui_test.human_delay(5)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute.png")
# ----------------------------------------------------------------------
async def test_target_attribute_browse(self):
"""
Test the changing an existing selection via the dialog works
"""
usd_context = omni.usd.get_context()
keys = og.Controller.Keys
controller = og.Controller()
prim_paths = ["/World/Prim"]
(_, (read_prims_node,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ReadPrims", "omni.graph.nodes.ReadPrimsV2"),
],
keys.CREATE_PRIMS: [(prim_path, {}) for prim_path in prim_paths],
},
)
attr_name = "inputs:prims"
usd_context.get_stage().GetPrimAtPath(read_prims_node.get_prim_path()).GetRelationship(attr_name).AddTarget(
prim_paths[0]
)
# The OG attribute-base UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# Select the node.
usd_context.get_selection().set_selected_prim_paths([read_prims_node.get_prim_path()], True)
# Wait for property panel to converge
await ui_test.human_delay(5)
# Click the Browse button
model_index = 0
await ui_test.find(
f"Property//Frame/**/Button[*].identifier=='sdf_browse_relationship_{attr_name}[{model_index}]'"
).click()
# Wait for dialog to show up
await ui_test.human_delay(5)
# push the select-graph-target button and wait for dialog to close
await ui_test.find("Select Targets//Frame/**/Button[*].identifier=='select_graph_target'").click()
await ui_test.human_delay(5)
# Resize to fit the property panel, and take a snapshot
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
await ui_test.human_delay(5)
try:
await self.capture_and_compare(
golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute_browse.png"
)
# Now edit the path to verify it displays as expected
test_path = f"{og.INSTANCING_GRAPH_TARGET_PATH}/foo"
# FIXME: This input call doesn't work - set with USD instead
# await ui_test.find(
# f"Property//Frame/**/StringField[*].identifier=='sdf_relationship_{attr_name}[{model_index}]'"
# ).input(test_path)
usd_context.get_stage().GetPrimAtPath(read_prims_node.get_prim_path()).GetRelationship(
attr_name
).SetTargets([Sdf.Path(f"{read_prims_node.get_prim_path()}/{test_path}")])
await ui_test.human_delay(5)
# Check the USD path has the token after the prim path, before the relative path
self.assertEqual(
usd_context.get_stage()
.GetPrimAtPath(read_prims_node.get_prim_path())
.GetRelationship(attr_name)
.GetTargets()[0],
Sdf.Path(f"{read_prims_node.get_prim_path()}/{test_path}"),
)
# Check that the composed path from OG is relative to the graph path
self.assertEqual(
str(og.Controller.get(f"{read_prims_node.get_prim_path()}.{attr_name}")[0]),
f"{self.TEST_GRAPH_PATH}/foo",
)
# Verify the widget display
await self.capture_and_compare(
golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute_edit.png"
)
finally:
await self.finalize_test_no_image()
# ----------------------------------------------------------------------
async def test_prim_node_template(self):
"""
Tests the prim node template under different variations of selected
prims to validate the the user does not get into a state
where the attribute name cannot be edited
"""
usd_context = omni.usd.get_context()
keys = og.Controller.Keys
controller = og.Controller()
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ReadPrim_Path_ValidTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Path_InvalidTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Path_Connected", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Prim_ValidTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Prim_InvalidTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Prim_Connected", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Prim_OGTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ConstPrims", "omni.graph.nodes.ConstantPrims"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "ReadPrim_Path_Connected.inputs:primPath"),
("ConstPrims.inputs:value", "ReadPrim_Prim_Connected.inputs:prim"),
],
keys.SET_VALUES: [
("ConstToken.inputs:value", "/World/Target"),
("ReadPrim_Path_ValidTarget.inputs:usePath", True),
("ReadPrim_Path_ValidTarget.inputs:primPath", "/World/Target"),
("ReadPrim_Path_ValidTarget.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Path_InvalidTarget.inputs:usePath", True),
("ReadPrim_Path_InvalidTarget.inputs:primPath", "/World/MissingTarget"),
("ReadPrim_Path_InvalidTarget.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Path_Connected.inputs:usePath", True),
("ReadPrim_Path_Connected.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Prim_ValidTarget.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Prim_InvalidTarget.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Prim_Connected.inputs:name", "size"),
("ReadPrim_Prim_OGTarget.inputs:name", "fileFormatVersion"),
],
keys.CREATE_PRIMS: [
("/World/Target", "Xform"),
("/World/Cube", "Cube"),
("/World/MissingTarget", "Xform"),
],
},
)
# Change the pipeline stage to On demand to prevent the graph from running and producing errors
og.cmds.ChangePipelineStage(graph=graph, new_pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND)
# The OG attribute-base UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# add relationships to all
graph_path = self.TEST_GRAPH_PATH
stage = omni.usd.get_context().get_stage()
rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_ValidTarget.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Target")
rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_OGTarget.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=og.INSTANCING_GRAPH_TARGET_PATH)
rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_InvalidTarget.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/MissingTarget")
rel = stage.GetPropertyAtPath(f"{graph_path}/ConstPrims.inputs:value")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Target")
# avoids an error by removing the invalid prim after the graph is created
omni.kit.commands.execute("DeletePrims", paths=["/World/MissingTarget"])
# Go through all the ReadPrim variations and validate that the image is expected.
# In the case of a valid target the widget for the attribute should be a dropdown
# Otherwise it should be a text field
for node in nodes:
node_name = node.get_prim_path().split("/")[-1]
if not node_name.startswith("ReadPrim"):
continue
with self.subTest(node_name=node_name):
test_img_name = f"test_{node_name.lower()}.png"
# Select the node.
usd_context.get_selection().set_selected_prim_paths([node.get_prim_path()], True)
# Wait for property panel to converge
await ui_test.human_delay(5)
# Resize to fit the property panel, and take a snapshot
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=test_img_name)
# ----------------------------------------------------------------------
async def test_extended_attributes(self):
"""
Exercise the OG properties widget with extended attributes
"""
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
keys = og.Controller.Keys
controller = og.Controller()
# OGN Types that we will test resolving the inputs:value to
supported_types = [
"half",
"timecode",
"half[]",
"timecode[]",
"double[2]",
"double[3]",
"double[4]",
"double[2][]",
"double[3][]",
"double[4][]",
"float[2]",
"float[3]",
"float[4]",
"float[2][]",
"float[3][]",
"float[4][]",
"half[2]",
"half[3]",
"half[4]",
"half[2][]",
"half[3][]",
"half[4][]",
"int[2]",
"int[3]",
"int[4]",
"int[2][]",
"int[3][]",
"int[4][]",
"matrixd[2]",
"matrixd[3]",
"matrixd[4]",
"matrixd[2][]",
"matrixd[3][]",
"matrixd[4][]",
"double",
"double[]",
"frame[4]",
"frame[4][]",
"quatd[4]",
"quatf[4]",
"quath[4]",
"quatd[4][]",
"quatf[4][]",
"quath[4][]",
"colord[3]",
"colord[3][]",
"colorf[3]",
"colorf[3][]",
"colorh[3]",
"colorh[3][]",
"colord[4]",
"colord[4][]",
"colorf[4]",
"colorf[4][]",
"colorh[4]",
"colorh[4][]",
"normald[3]",
"normald[3][]",
"normalf[3]",
"normalf[3][]",
"normalh[3]",
"normalh[3][]",
"pointd[3]",
"pointd[3][]",
"pointf[3]",
"pointf[3][]",
"pointh[3]",
"pointh[3][]",
"vectord[3]",
"vectord[3][]",
"vectorf[3]",
"vectorf[3][]",
"vectorh[3]",
"vectorh[3][]",
"texcoordd[2]",
"texcoordd[2][]",
"texcoordf[2]",
"texcoordf[2][]",
"texcoordh[2]",
"texcoordh[2][]",
"texcoordd[3]",
"texcoordd[3][]",
"texcoordf[3]",
"texcoordf[3][]",
"texcoordh[3]",
"texcoordh[3][]",
"string",
"token[]",
"token",
]
attribute_names = [
self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name))
for type_name in supported_types
]
expected_values = [
ogn.get_attribute_manager_type(type_name).sample_values()[0:2] for type_name in supported_types
]
(graph, (_, write_node,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_PRIMS: [
(
"/World/Prim",
{
attrib_name: (usd_type, expected_value[0])
for attrib_name, usd_type, expected_value in zip(
attribute_names, supported_types, expected_values
)
},
)
],
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Write", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Write.inputs:execIn"),
],
keys.SET_VALUES: [
("Write.inputs:name", "acc"),
("Write.inputs:primPath", "/World/Prim"),
("Write.inputs:usePath", True),
],
},
)
await controller.evaluate(graph)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths([write_node.get_prim_path()], True)
# The UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# Test for attrib types that use OmniGraphAttributeValueModel
async def test_numeric(name, value1, value2):
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]})
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(2)
for base in ogab.OmniGraphBase._instances: # noqa: PLW0212
if base._object_paths[0].name == "inputs:value" and ( # noqa: PLW0212
isinstance(base, (ogam.OmniGraphGfVecAttributeSingleChannelModel, ogam.OmniGraphAttributeModel))
):
base.begin_edit()
base.set_value(value1)
await ui_test.human_delay(1)
base.set_value(value2)
await ui_test.human_delay(1)
base.end_edit()
await ui_test.human_delay(1)
break
# Test for attrib types that use ui.AbstractItemModel
async def test_item(name, value1, value2):
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]})
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(2)
for base in ogab.OmniGraphBase._instances: # noqa: PLW0212
if base._object_paths[0].name == "inputs:value": # noqa: PLW0212
base.begin_edit()
base.set_value(value1)
await ui_test.human_delay(1)
base.set_value(value2)
await ui_test.human_delay(1)
base.end_edit()
await ui_test.human_delay(1)
break
# Test for read-only array value - just run the code, no need to verify anything
async def test_array(name, val):
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]})
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(2)
for attrib_name, test_values in zip(attribute_names, expected_values):
if attrib_name.endswith("_array"):
await test_array(attrib_name, test_values[1])
elif attrib_name in ("string", "token"):
await test_item(attrib_name, test_values[1], test_values[0])
else:
# The set_value for some types take a component, others take the whole vector/matrix
if isinstance(test_values[0], tuple) and not (
attrib_name.startswith("a_matrix")
or attrib_name.startswith("a_frame")
or attrib_name.startswith("a_quat")
):
await test_numeric(attrib_name, test_values[1][0], test_values[0][0])
else:
await test_numeric(attrib_name, test_values[1], test_values[0])
# Sanity check the final widget state display
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_extended_attributes.png")
async def test_extended_output_attributes(self):
"""
Exercise the OG properties widget with extended attributes on read nodes
"""
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
keys = og.Controller.Keys
controller = og.Controller()
(graph, (_, read_node, _,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_PRIMS: [(("/World/Prim", {"a_token": ("token", "Ahsoka")}))],
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Read", "omni.graph.nodes.ReadPrimAttribute"),
("Write", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Write.inputs:execIn"),
("Read.outputs:value", "Write.inputs:value"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Read.inputs:name", "a_token"),
("Read.inputs:primPath", "/World/Prim"),
("Read.inputs:usePath", True),
("Write.inputs:name", "a_token"),
("Write.inputs:primPath", "/World/Prim"),
("Write.inputs:usePath", True),
],
},
)
await controller.evaluate(graph)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths([read_node.get_prim_path()], True)
await ui_test.human_delay(5)
# The UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# Sanity check the final widget state display
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="test_extended_output_attributes.png"
)
async def test_layer_identifier_resolver(self):
"""
Test layer identifier resolver using WritePrimsV2 node
/root.usda
/sub/sublayer.usda (as a sublayer of root.usda)
The OG graph will be created on /sub/sublayer.usda with layer identifier set to "./sublayer.usda"
Then open /root.usda to test the relative path is successfully resolved relative to root.usda instead
"""
with tempfile.TemporaryDirectory() as tmpdirname:
usd_context = omni.usd.get_context()
controller = og.Controller()
keys = og.Controller.Keys
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
sub_dir = os.path.join(tmpdirname, "sub")
sublayer_fn = os.path.join(sub_dir, "sublayer.usda")
sublayer = Sdf.Layer.CreateNew(sublayer_fn)
sublayer.Save()
root_fn = os.path.join(tmpdirname, "root.usda")
root_layer = Sdf.Layer.CreateNew(root_fn)
root_layer.subLayerPaths.append("./sub/sublayer.usda")
root_layer.Save()
success, error = await usd_context.open_stage_async(str(root_fn))
self.assertTrue(success, error)
stage = usd_context.get_stage()
# put the graph on sublayer
# only need WritePrimsV2 node for UI tests
with Usd.EditContext(stage, sublayer):
(_, [write_prims_node], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write.inputs:layerIdentifier", "./sublayer.usda"),
],
},
)
# exit the "with" and switch edit target back to root layer
usd_context.get_selection().set_selected_prim_paths([write_prims_node.get_prim_path()], True)
await ui_test.human_delay(5)
# Check the final widget state display
# The "Layer Identifier" section should show "./sub/sublayer.usda" without any "<Invalid Layer>"" tag
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="test_layer_identifier_resolver.png"
)
| 27,911 | Python | 39.926686 | 120 | 0.54294 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_action.py | """
Tests that verify action UI-dependent nodes
"""
import unittest
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from omni.kit.test.teamcity import is_running_in_teamcity
from omni.kit.viewport.utility import get_active_viewport
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf
# ======================================================================
class TestOmniGraphAction(ogts.OmniGraphTestCase):
"""Encapsulate simple sanity tests"""
# ----------------------------------------------------------------------
@unittest.skipIf(is_running_in_teamcity(), "Crashes on TC / Linux")
async def test_camera_nodes(self):
"""Test camera-related node basic functionality"""
keys = og.Controller.Keys
controller = og.Controller()
viewport_api = get_active_viewport()
active_cam = viewport_api.camera_path
persp_cam = "/OmniverseKit_Persp"
self.assertEqual(active_cam.pathString, persp_cam)
(graph, _, _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("SetCam", "omni.graph.ui.SetActiveViewportCamera"),
],
keys.SET_VALUES: [
("SetCam.inputs:primPath", "/OmniverseKit_Top"),
],
keys.CONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")],
},
)
await controller.evaluate()
active_cam = viewport_api.camera_path
self.assertEqual(active_cam.pathString, "/OmniverseKit_Top")
# be nice - set it back
viewport_api.camera_path = persp_cam
# Tests moving the camera and camera target
controller.edit(
graph,
{
keys.DISCONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")],
},
)
await controller.evaluate()
(graph, (_, _, get_pos, get_target), _, _) = controller.edit(
graph,
{
keys.CREATE_NODES: [
("SetPos", "omni.graph.ui.SetCameraPosition"),
("SetTarget", "omni.graph.ui.SetCameraTarget"),
("GetPos", "omni.graph.ui.GetCameraPosition"),
("GetTarget", "omni.graph.ui.GetCameraTarget"),
],
keys.SET_VALUES: [
("SetPos.inputs:primPath", persp_cam),
("SetPos.inputs:position", Gf.Vec3d(1.0, 2.0, 3.0)),
# Target should be different than position
("SetTarget.inputs:target", Gf.Vec3d(-1.0, -2.0, -3.0)),
("SetTarget.inputs:primPath", persp_cam),
("GetPos.inputs:primPath", persp_cam),
("GetTarget.inputs:primPath", persp_cam),
],
keys.CONNECT: [
("OnTick.outputs:tick", "SetPos.inputs:execIn"),
("SetPos.outputs:execOut", "SetTarget.inputs:execIn"),
],
},
)
await controller.evaluate()
# XXX: May need to force these calls through legacy_viewport as C++ nodes call through to that interface.
camera_state = ViewportCameraState(persp_cam) # , viewport=viewport_api, force_legacy_api=True)
x, y, z = camera_state.position_world
for a, b in zip([x, y, z], [1.0, 2.0, 3.0]):
self.assertAlmostEqual(a, b, places=5)
x, y, z = camera_state.target_world
for a, b in zip([x, y, z], [-1.0, -2.0, -3.0]):
self.assertAlmostEqual(a, b, places=5)
# evaluate again, because push-evaluator may not have scheduled the getters after the setters
await controller.evaluate()
get_pos = og.Controller.get(controller.attribute(("outputs:position", get_pos)))
for a, b in zip(get_pos, [1.0, 2.0, 3.0]):
self.assertAlmostEqual(a, b, places=5)
get_target = og.Controller.get(controller.attribute(("outputs:target", get_target)))
for a, b in zip(get_target, [-1.0, -2.0, -3.0]):
self.assertAlmostEqual(a, b, places=5)
# ----------------------------------------------------------------------
@unittest.skipIf(is_running_in_teamcity(), "Flaky - needs investigation")
async def test_on_new_frame(self):
"""Test OnNewFrame node"""
keys = og.Controller.Keys
controller = og.Controller()
# Check that the NewFrame node is getting updated when frames are being generated
(_, (new_frame_node,), _, _) = controller.edit(
"/TestGraph", {keys.CREATE_NODES: [("NewFrame", "omni.graph.ui.OnNewFrame")]}
)
attr = controller.attribute(("outputs:frameNumber", new_frame_node))
await og.Controller.evaluate()
frame_num = og.Controller.get(attr)
# Need to tick Kit before evaluation in order to update
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await og.Controller.evaluate()
self.assertLess(frame_num, og.Controller.get(attr))
| 5,247 | Python | 43.10084 | 113 | 0.545836 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_ui_sanity.py | """
Tests that do basic sanity checks on the OmniGraph UI
"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools as ogt
import omni.kit.test
import omni.usd
from carb import log_warn
from .._impl.menu import MENU_WINDOWS, Menu
from .._impl.omnigraph_node_description_editor.main_editor import Editor
# Data-driven information to allow creation of all windows without specifics.
# This assumes every class has a static get_name() method so that prior existence can be checked,
# and a show_window() or show() method which displays the window.
#
# Dictionary key is the attribute name in the test class under which this window is stored.
# Value is a list of [class, args] where:
# ui_class: Class type that instantiates the window
# args: Arguments to be passed to the window's constructor
#
ALL_WINDOW_INFO = {"_ogn_editor_window": [Editor, []]}
# ======================================================================
class TestOmniGraphUiSanity(ogts.OmniGraphTestCase):
"""Encapsulate simple sanity tests"""
# ----------------------------------------------------------------------
async def test_open_and_close_all_omnigraph_ui(self):
"""Open and close all of the OmniGraph UI windows as a basic sanity check
In order for this test to work all of the UI management classes must support these methods:
show(): Build and display the window contents
destroy(): Close the window and destroy the window elements
And the classes must derive from (metaclass=Singleton) to avoid multiple instantiations
"""
class AllWindows:
"""Encapsulate all of the windows to be tested in an object for easier destruction"""
def __init__(self):
"""Open and remember all of the windows (closing first if they were already open)"""
# The graph window needs to be passed a graph.
graph_path = "/World/TestGraph"
og.Controller.edit({"graph_path": graph_path, "evaluator_name": "push"})
for (member, (ui_class, args)) in ALL_WINDOW_INFO.items():
setattr(self, member, ui_class(*args))
async def show_all(self):
"""Find all of the OmniGraph UI windows and show them"""
for (member, (ui_class, _)) in ALL_WINDOW_INFO.items():
window = getattr(self, member)
show_fn = getattr(window, "show_window", getattr(window, "show", None))
if show_fn:
show_fn()
# Wait for an update to ensure the window has been opened
await omni.kit.app.get_app().next_update_async()
else:
log_warn(f"Not testing type {ui_class.__name__} - no show_window() or show() method")
def destroy(self):
"""Destroy the members, which cleanly destroys the windows"""
for member in ALL_WINDOW_INFO:
ogt.destroy_property(self, member)
all_windows = AllWindows()
await all_windows.show_all()
await omni.kit.app.get_app().next_update_async()
all_windows.destroy()
all_windows = None
# ----------------------------------------------------------------------
async def test_omnigraph_ui_menu(self):
"""Verify that the menu operations all work"""
menu = Menu()
for menu_path in MENU_WINDOWS:
menu.set_window_state(menu_path, True)
await omni.kit.app.get_app().next_update_async()
menu.set_window_state(menu_path, False)
async def test_omnigraph_ui_node_creation(self):
"""Check that all of the registered omni.graph.ui nodes can be created without error."""
graph_path = "/World/TestGraph"
(graph, *_) = og.Controller.edit({"graph_path": graph_path, "evaluator_name": "push"})
# Add one of every type of omni.graph.ui node to the graph.
node_types = [t for t in og.get_registered_nodes() if t.startswith("omni.graph.ui")]
prefix_len = len("omni.graph.ui_nodes.")
node_names = [name[prefix_len:] for name in node_types]
(_, nodes, _, _) = og.Controller.edit(
graph, {og.Controller.Keys.CREATE_NODES: list(zip(node_names, node_types))}
)
self.assertEqual(len(nodes), len(node_types), "Check that all nodes were created.")
for i, node in enumerate(nodes):
self.assertEqual(
node.get_prim_path(), graph_path + "/" + node_names[i], f"Check node type '{node_types[i]}'"
)
| 4,694 | Python | 43.292452 | 109 | 0.585854 |
omniverse-code/kit/exts/omni.graph.ui/docs/prettycons-LICENSE.md | # prettycons License
Icons made by prettycons from "https://www.flaticon.com/"
| 79 | Markdown | 25.666658 | 57 | 0.772152 |
omniverse-code/kit/exts/omni.graph.ui/docs/Pixel_perfect-LICENSE.md | # PixelPerfect License
Icons made by Pixel perfect from "https://www.flaticon.com/"
| 84 | Markdown | 27.333324 | 60 | 0.77381 |
omniverse-code/kit/exts/omni.graph.ui/docs/CHANGELOG.md | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.24.2] - 2023-02-06
- Fix for test failure
## [1.24.1] - 2022-12-08
### Fixed
- Make sure variable colour widgets use AbstractItemModel
- Fixed tab not working on variable vector fields
- Fixed UI update issues with graph variable widgets
## [1.24.0] - 2022-11-10
### Added
- Display initial and runtime values of graph variables
## [1.23.1] - 2022-10-28
### Fixed
- Undo on node attributes
## [1.23.0] - 2022-09-29
### Changed
- Added OmniGraphAttributeModel to public API
## [1.22.0] - 2022-09-27
### Added
- Widget for reporting timing information related to extension processing by OmniGraph
## [1.21.4] - 2022-09-14
### Added
- Instance variable properties remove underlying attribute when reset to default
## [1.21.3] - 2022-09-10
### Added
- Use id paramteter for Viewport picking request so a node will only generate request.
## [1.21.2] - 2022-08-25
### Fixed
- Modified the import path acceptance pattern to adhere to PEP8 guidelines
- Fixed hot reload for the editors by correctly destroying menu items
- Added FIXME comments recommended in a prior review
### Added
- Button for Save-As to support being able to add multiple nodes in a single session
## [1.21.1] - 2022-08-25
### Changed
- Refactored scene frame to be widget-based instead of monolithic
## [1.21.0] - 2022-08-25
### Added
- UI for controlling new setting that turns deprecations into errors
## [1.20.0] - 2022-08-17
### Added
- Toolkit button for dumping out the extension information for OmniGraph users
### Removed
- Obsolete migration buttons
### Changed
- Refactored toolkit inspection frame to be widget-based instead of monolithic
## [1.19.0] - 2022-08-11
### Added
- ReadWindowSize node
- 'widgetPath' inputs to ReadWidgetProperty, WriteWidgetProperty and WriteWidgetStyle nodes.
### Changed
- WriteWidgetStyle now reports the full details of style sytax errors.
## [1.18.1] - 2022-08-10
### Fixed
- Applied formatting to all of the Python files
## [1.18.0] - 2022-08-09
### Changed
- Removed unused graph editor modules
- Removed omni.kit.widget.graph and omni.kit.widget.fast_search dependencies
## [1.17.1] - 2022-08-06
### Changed
- OmniGraph(API) references changed to 'Visual Scripting'
## [1.17.0] - 2022-08-05
### Added
- Mouse press gestures to picking nodes
## [1.16.4] - 2022-08-05
### Changed
- Fixed bug related to parameter-tagged properties
## [1.16.3] - 2022-08-03
### Fixed
- All of the lint errors reported on the Python files in this extension
## [1.16.2] - 2022-07-28
### Fixed
- Spurious error messages about 'Node compute request is ignored because XXX is not request-driven'
## [1.16.1] - 2022-07-28
### Changed
- Fixes for OG property panel
- compute_node_widget no longer flushes prim to FC
## [1.16.0] - 2022-07-25
### Added
- Viewport mouse event nodes for click, press/release, hover, and scroll
### Changed
- Behavior of drag and picking nodes to be consistent
## [1.15.3] - 2022-07-22
### Changed
- Moving where custom metadata is set on the usd property so custom templates have access to it
## [1.15.2] - 2022-07-15
### Added
- test_omnigraph_ui_node_creation()
### Fixed
- Missing graph context in test_open_and_close_all_omnigraph_ui()
### Changed
- Set all of the old Action Graph Window code to be omitted from pyCoverage
## [1.15.1] - 2022-07-13
- OM-55771: File browser button
## [1.15.0] - 2022-07-12
### Added
- OnViewportDragged and ReadViewportDragState nodes
### Changed
- OnPicked and ReadPickState, most importantly how OnPicked handles an empty picking event
## [1.14.0] - 2022-07-08
### Fixed
- ReadMouseState not working with display scaling or multiple workspace windows
### Changed
- Added 'useRelativeCoordinates' input and 'window' output to ReadMouseState
## [1.13.0] - 2022-07-08
### Changed
- Refactored imports from omni.graph.tools to get the new locations
### Added
- Added test for public API consistency
## [1.12.0] - 2022-07-07
### Changed
- Overhaul of SetViewportMode
- Changed default viewport for OnPicked/ReadPickState to 'Viewport'
- Allow templates in omni.graph.ui to be loaded
## [1.11.0] - 2022-07-04
### Added
- OgnSetViewportMode.widgetPath attribute
### Changed
- OgnSetViewportMode does not enable execOut if there's an error
## [1.10.1] - 2022-06-28
### Changed
- Change default viewport for SetViewportMode/OnPicked/ReadPickState to 'Viewport Next'
## [1.10.0] - 2022-06-27
### Changed
- Move ReadMouseState into omni.graph.ui
- Make ReadMouseState coords output window-relative
## [1.9.0] - 2022-06-24
### Added
- Added PickingManipulator for prim picking nodes controlled from SetViewportMode
- Added OnPicked and ReadPickState nodes for prim picking
## [1.8.5] - 2022-06-17
### Added
- Added instancing ui elements
## [1.8.4] - 2022-06-07
### Changed
- Updated imports to remove explicit imports
- Added explicit generator settings
## [1.8.3] - 2022-05-24
### Added
- Remove dependency on Viewport for Camera Get/Set operations
- Run tests with omni.hydra.pxr/Storm instead of RTX
## [1.8.2] - 2022-05-23
### Added
- Use omni.kit.viewport.utility for Viewport nodes and testing.
## [1.8.1] - 2022-05-20
### Fixed
- Change cls.default_model_table to correctly set model_cls in _create_color_or_drag_per_channel
for vec2d, vec2f, vec2h, and vec2i omnigraph attributes
- Infer default values from type for OG attributes when not provided in metadata
## [1.8.0] - 2022-05-05
### Added
- Support for enableLegacyPrimConnections setting, used by DS but deprecated
### Fixed
- Tooltips and descriptions for settings that are interdependent
## [1.7.1] - 2022-04-29
### Changed
- Made tests derive from OmniGraphTestCase
## [1.7.0] - 2022-04-26
### Added
- GraphVariableCustomLayout property panel widget moved from omni.graph.instancing
## [1.6.1] - 2022-04-21
### Fixed
- Some broken and out of date tests.
## [1.6.0] - 2022-04-18
### Changed
- Property Panel widget for OG nodes now reads attribute values from Fabric backing instead of USD.
## [1.5.0] - 2022-03-17
### Added
- Added _add\_create\_menu\_type_ and _remove\_create\_menu\_type_ functions to allow kit-graph extensions to add their corresponding create graph menu item
### Changed
- _Menu.create\_graph_ now return the wrapper node, and will no longer pops up windows
- _Menu_ no longer creates the three menu items _Create\Visual Sciprting\Action Graph_, _Create\Visual Sciprting\Push Graph_, _Create\Visual Sciprting\Lazy Graph_ at extension start up
- Creating a graph now will directly create a graph with default title and open it
## [1.4.4] - 2022-03-11
### Added
- Added glyph icons for menu items _Create/Visual Scripting/_ and items under this submenu
- Added Create Graph context menu for viewport and stage windows.
## [1.4.3] - 2022-03-11
### Fixed
- Node is written to backing store when the custom widget is reset to ensure that view is up to date with FC.
## [1.4.2] - 2022-03-07
### Changed
- Add spliter for items in submenu _Window/Visual Scripting_
- Renamed menu item _Create/Graph_ to _Create/Visual Scripting_
- Changed glyph icon for _Create/Visual Scripting_ and added glyph icons for all sub menu items under
## [1.4.1] - 2022-02-22
### Changed
- Change _Window/Utilities/Attribute Connection_, _Window/Visual Scripting/Node Description Editor_ and _Window/Visual Scripting/Toolkit_ into toggle buttons
- Added OmniGraph.svg glyph for _Create/Graph_
## [1.4.0] - 2022-02-16
### Changes
- Decompose the original OmniGraph menu in toolbar into several small menu items under correct categories
## [1.3.0] - 2022-02-10
### Added
- Toolkit access to the setting that uses schema prims in graphs, and a migration tool for same
## [1.2.2] - 2022-01-28
### Fixed
- Potential crash when handling menu or stage changes
## [1.2.1] - 2022-01-21
### Fixed
- ReadPrimAttribute/WritePrimAttribute property panel when usePath is true
## [1.2.0] - 2022-01-06
### Fixed
- Property window was generating exceptions when a property is added to an OG prim.
## [1.1.0] - 2021-12-02
### Changes
- Fixed compute node widget bug with duplicate graphs
## [1.0.2] - 2021-11-24
### Changes
- Fixed compute node widget to work with scoped graphs
## [1.0.1] - 2021-02-10
### Changes
- Updated StyleUI handling
## [1.0.0] - 2021-02-01
### Initial Version
- Started changelog with initial released version of the OmniGraph core
| 8,560 | Markdown | 29.575 | 184 | 0.725234 |
omniverse-code/kit/exts/omni.graph.ui/docs/OmniGraphSettingsEditor.rst | .. _omnigraph_settings_editor:
OmniGraph Settings Editor
=========================
The settings editor provides a method of modifying settings which affect the OmniGraph appearance and evaluation.
| 199 | reStructuredText | 27.571425 | 113 | 0.718593 |
omniverse-code/kit/exts/omni.graph.ui/docs/README.md | # OmniGraph UI [omni.graph.ui]
OmniGraph is a graph system that provides a compute framework for Omniverse through the use of nodes and graphs.
This extension contains some supporting UI-related components and nodes for OmniGraph.
| 232 | Markdown | 45.599991 | 112 | 0.814655 |
omniverse-code/kit/exts/omni.graph.ui/docs/index.rst | OmniGraph User Interfaces
#########################
.. tabularcolumns:: |L|R|
.. csv-table::
:width: 100%
**Extension**: omni.graph.ui,**Documentation Generated**: |today|
While other UI elements allow indirect interaction with the OmniGraph, the ones listed here provide
direct manipulation of OmniGraph nodes, attributes, and connections.
.. toctree::
:maxdepth: 1
:glob:
*
| 404 | reStructuredText | 20.315788 | 99 | 0.653465 |
omniverse-code/kit/exts/omni.graph.ui/docs/OmniGraphNodeDescriptionEditor.rst | .. _omnigraph_node_description_editor:
OmniGraph Node Description Editor
=================================
The node description editor is the user interface to create and edit the code that implements OmniGraph Nodes, as well
as providing a method for creating a minimal extension that can be used to bring them into Kit.
Follow along with the tutorials `here <https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.graph.core/docs/nodes.html>`
to see how this editor can be used to create an OmniGraph node in Python.
| 531 | reStructuredText | 47.363632 | 131 | 0.749529 |
omniverse-code/kit/exts/omni.graph.ui/docs/Overview.md | # OmniGraph User Interfaces
```{csv-table}
**Extension**: omni.graph.ui,**Documentation Generated**: {sub-ref}`today`
```
While other UI elements allow indirect interaction with the OmniGraph, the ones listed here provide
direct manipulation of OmniGraph nodes, attributes, and connections. | 292 | Markdown | 35.624996 | 99 | 0.773973 |
omniverse-code/kit/exts/omni.kit.menu.aov/PACKAGE-LICENSES/omni.kit.menu.aov-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.menu.aov/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.1.3"
category = "Internal"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "AOV Menu"
description="Implementation of AOV Menu."
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "ui", "menu", "aov"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog = "docs/CHANGELOG.md"
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
[dependencies]
"omni.usd" = {}
"omni.kit.menu.utils" = {}
"omni.kit.context_menu" = {}
"omni.kit.commands" = {}
"omni.kit.widget.layers" = {}
"omni.kit.actions.core" = {}
[[python.module]]
name = "omni.kit.menu.aov"
[setting]
exts."omni.kit.menu.create".original_svg_color = false
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/file/ignoreUnsavedStage=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window",
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
]
stdoutFailPatterns.exclude = [
"*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop
"*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available
]
| 1,924 | TOML | 28.166666 | 122 | 0.694387 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/__init__.py | from .scripts import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/aov_actions.py | import omni.kit.actions.core
def register_actions(extension_id, cls):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "AOV Menu Actions"
# actions
action_registry.register_action(
"omni.kit.menu.aov",
"create_single_aov",
cls._on_create_single_aov,
display_name="Create->AOV",
description="Create AOV",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 598 | Python | 26.227272 | 70 | 0.673913 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/aov.py | import omni.ext
import omni.kit.menu.utils
import omni.kit.context_menu
import omni.kit.commands
from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder
from pxr import Sdf, Usd, UsdUtils, Gf
from .aov_actions import register_actions, deregister_actions
class AOVMenuExtension(omni.ext.IExt):
def __init__(self):
self._aov_menu_list = []
def on_startup(self, ext_id):
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name, AOVMenuExtension)
self._register_menu()
self._register_context_menu()
def on_shutdown(self):
deregister_actions(self._ext_name)
omni.kit.menu.utils.remove_menu_items(self._aov_menu_list, "Create")
self._aov_menu_list = None
self._context_menu = None
def _register_menu(self):
self._aov_menu_list = [
MenuItemDescription(name="AOV", glyph="AOV_dark.svg", appear_after=[MenuItemOrder.LAST], onclick_action=("omni.kit.menu.aov", "create_single_aov"))
]
omni.kit.menu.utils.add_menu_items(self._aov_menu_list, "Create")
def _register_context_menu(self):
menu_dict = {
'glyph': "AOV_dark.svg",
'name': 'AOV',
'show_fn': [],
'onclick_fn': AOVMenuExtension._on_create_single_aov
}
self._context_menu = omni.kit.context_menu.add_menu(menu_dict, "CREATE")
@staticmethod
def _create_render_prim(prim_type, prim_path):
import omni.usd
from omni.kit.widget.layers import LayerUtils
stage = omni.usd.get_context().get_stage()
session_layer = stage.GetSessionLayer()
current_edit_layer = Sdf.Find(LayerUtils.get_edit_target(stage))
swap_edit_targets = current_edit_layer != session_layer
rendervar_list = [ ("ldrColor", {"sourceName": "LdrColor"}),
("hdrColor", {"sourceName": "HdrColor"}),
("PtDirectIllumation", {"sourceName": "PtDirectIllumation"}),
("PtGlobalIllumination", {"sourceName": "PtGlobalIllumination"}),
("PtReflections", {"sourceName": "PtReflections"}),
("PtRefractions", {"sourceName": "PtRefractions"}),
("PtSelfIllumination", {"sourceName": "PtSelfIllumination"}),
("PtBackground", {"sourceName": "PtBackground"}),
("PtWorldNormal", {"sourceName": "PtWorldNormal"}),
("PtWorldPos", {"sourceName": "PtWorldPos"}),
("PtZDepth", {"sourceName": "PtZDepth"}),
("PtVolumes", {"sourceName": "PtVolumes"}),
("PtMultiMatte0", {"sourceName": "PtMultiMatte0"}),
("PtMultiMatte1", {"sourceName": "PtMultiMatte1"}),
("PtMultiMatte2", {"sourceName": "PtMultiMatte2"}),
("PtMultiMatte3", {"sourceName": "PtMultiMatte3"}),
("PtMultiMatte4", {"sourceName": "PtMultiMatte4"}),
("PtMultiMatte5", {"sourceName": "PtMultiMatte5"}),
("PtMultiMatte6", {"sourceName": "PtMultiMatte6"}),
("PtMultiMatte7", {"sourceName": "PtMultiMatte7"}),
]
## create prim. /Render is on session layer but need new prims in currrent layer
try:
if not current_edit_layer.GetPrimAtPath('/Render'):
omni.kit.commands.execute("CreatePrim", prim_path="/Render", prim_type="Scope", attributes={}, select_new_prim=False)
if not current_edit_layer.GetPrimAtPath('/Render/Vars'):
omni.kit.commands.execute("CreatePrim", prim_path="/Render/Vars", prim_type="Scope", attributes={}, select_new_prim=False)
omni.kit.commands.execute("CreatePrim", prim_path=prim_path, prim_type="RenderProduct", attributes={}, select_new_prim=False)
for var_name, attributes in rendervar_list:
if not current_edit_layer.GetPrimAtPath(f"/Render/Vars/{var_name}"):
omni.kit.commands.execute("CreatePrim", prim_path=f"/Render/Vars/{var_name}", prim_type="RenderVar", attributes=attributes, select_new_prim=False)
if swap_edit_targets:
LayerUtils.set_edit_target(stage, session_layer.identifier)
# set /Render visible & non-deletable in stage window...
render_prim = stage.GetPrimAtPath("/Render")
omni.usd.editor.set_hide_in_stage_window(render_prim, False)
omni.usd.editor.set_no_delete(render_prim, True)
# set /Render/Vars visible & non-deletable in stage window...
vars_prim = stage.GetPrimAtPath("/Render/Vars")
omni.usd.editor.set_hide_in_stage_window(vars_prim, False)
omni.usd.editor.set_no_delete(vars_prim, True)
finally:
if swap_edit_targets:
LayerUtils.set_edit_target(stage, current_edit_layer.identifier)
prim = stage.GetPrimAtPath(prim_path)
if prim:
for var_name, attributes in rendervar_list:
omni.kit.commands.execute("AddRelationshipTarget", relationship=prim.GetRelationship('orderedVars'), target=f"/Render/Vars/{var_name}")
prim.CreateAttribute("resolution", Sdf.ValueTypeNames.Int2, False).Set(Gf.Vec2i(1280, 720))
@staticmethod
def _on_create_single_aov(objects=None):
with omni.kit.undo.group():
stage = omni.usd.get_context().get_stage()
prim_path = Sdf.Path(omni.usd.get_stage_next_free_path(stage, "/Render/RenderView", False))
AOVMenuExtension._create_render_prim("RenderProduct", prim_path)
| 5,872 | Python | 48.352941 | 166 | 0.585831 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/__init__.py | from .aov import *
| 19 | Python | 8.999996 | 18 | 0.68421 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/tests/aov_tests.py | import sys
import re
import asyncio
import unittest
import carb
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
class WindowStub():
"""stub window class for use with WidgetRef & """
def undock(_):
pass
def focus(_):
pass
window_stub = WindowStub()
class TestMenuAOVs(omni.kit.test.AsyncTestCase):
async def setUp(self):
import omni.kit.material.library
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
await ui_test.human_delay()
async def tearDown(self):
pass
def get_menubar(self) -> ui_test.WidgetRef:
from omni.kit.mainwindow import get_main_window
window = get_main_window()
return ui_test.WidgetRef(widget=window._ui_main_window.main_menu_bar, path="MainWindow//Frame/MenuBar")
def find_menu(self, menubar: ui_test.WidgetRef, path: str) -> ui_test.WidgetRef:
for widget in menubar.find_all("**/"):
if isinstance(widget.widget, ui.Menu) or isinstance(widget.widget, ui.MenuItem):
if widget.widget.text.encode('ascii', 'ignore').decode().strip() == path:
return ui_test.WidgetRef(widget.widget, path="xxx", window=window_stub)
return None
async def test_aov_menus(self):
from omni.kit.menu.aov import AOVMenuExtension
# get root menu
menubar = self.get_menubar()
# new stage
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# verify one prim
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']]
self.assertTrue(prim_list == ['/Sphere'])
# use menu Create/AOV
create_widget = self.find_menu(menubar, "Create")
await create_widget.click(pos=create_widget.position+ui_test.Vec2(0, 5))
aov_widget = self.find_menu(create_widget, "AOV")
await aov_widget.click(pos=aov_widget.position+ui_test.Vec2(50, 5))
# verify multiple prims
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']]
self.assertFalse(prim_list == ['/Sphere'])
# undo changes
omni.kit.undo.undo()
# verify one prim
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']]
self.assertTrue(prim_list == ['/Sphere'])
# new stage to prevent layout dialogs
await omni.usd.get_context().new_stage_async()
| 2,868 | Python | 34.419753 | 143 | 0.643305 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/tests/__init__.py | from .aov_tests import *
| 25 | Python | 11.999994 | 24 | 0.72 |
omniverse-code/kit/exts/omni.kit.usda_edit/PACKAGE-LICENSES/omni.kit.usda_edit-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.usda_edit/config/extension.toml | [package]
title = "USDA Editor"
description = "Context menu to edit USD layers as USDA files"
authors = ["NVIDIA"]
version = "1.1.10"
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
readme = "docs/README.md"
icon = "data/icon.png"
category = "Internal"
feature = true
[[python.module]]
name = "omni.kit.usda_edit"
[dependencies]
"omni.kit.pip_archive" = {}
"omni.ui" = {}
"omni.usd" = {}
"omni.usd.libs" = {}
# Additional python module with tests, to make them discoverable by test system.
[[python.module]]
name = "omni.kit.usda_edit.tests"
| 564 | TOML | 20.730768 | 80 | 0.689716 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/content_browser_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.usd
from . import editor
from .layer_watch import LayerWatch
from .usda_edit_utils import is_extension_loaded
import os
def content_browser_available() -> bool:
"""Returns True if the extension "omni.kit.widget.content_browser" is loaded"""
return is_extension_loaded("omni.kit.window.content_browser")
class ContentBrowserMenu:
"""
When this object is alive, Layers 2.0 has the additional context menu
with the items that allow to edit the layer in the external editor.
"""
def __init__(self):
import omni.kit.window.content_browser as content
self._content_window = content.get_content_window()
self.__start_name = self._content_window.add_context_menu(
"Edit...", "menu_rename.svg", ContentBrowserMenu.start_editing, ContentBrowserMenu.is_not_editing
)
self.__end_name = self._content_window.add_context_menu(
"Finish editing", "menu_delete.svg", ContentBrowserMenu.stop_editing, ContentBrowserMenu.is_editing
)
def destroy(self):
"""Stop all watchers and remove the menu from Layers 2.0"""
if content_browser_available():
self._content_window.delete_context_menu(self.__start_name)
self._content_window.delete_context_menu(self.__end_name)
self.__start_name = None
self.__end_name = None
self._content_window = None
LayerWatch().stop_all()
@staticmethod
def start_editing(menu: str, content_url: str):
"""Start watching for the layer and run the editor"""
usda_filename = LayerWatch().start_watch(content_url)
editor.run_editor(usda_filename)
@staticmethod
def stop_editing(menu: str, content_url: str):
"""Stop watching for the layer and remove the temporary files"""
LayerWatch().stop_watch(content_url)
@staticmethod
def is_editing(content_url: str) -> bool:
"""Returns true if the layer is already watched"""
return LayerWatch().has_watch(content_url)
@staticmethod
def is_not_editing(content_url: str) -> bool:
"""Returns true if the layer is not watched"""
return omni.usd.is_usd_writable_filetype(content_url) and not ContentBrowserMenu.is_editing(content_url)
| 2,709 | Python | 38.275362 | 112 | 0.689184 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/extension_usda.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .layers_menu import layers_available
from .layers_menu import LayersMenu
from .content_menu import ContentMenu
from .content_browser_menu import content_browser_available
from .content_browser_menu import ContentBrowserMenu
import omni.ext
import omni.kit.app
class UsdaEditExtension(omni.ext.IExt):
def on_startup(self, ext_id):
# Setup a callback for the event
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
self.__extensions_subscription = ext_manager.get_change_event_stream().create_subscription_to_pop(
self._on_event, name="omni.kit.usda_edit"
)
self.__layers_menu = None
self.__content_menu = None
self.__content_browser_menu = None
self._on_event(None)
# When kit exits we won't get a change event for content_browser unloading so we need to resort to
# an explicit subscription to its enable/disable events.
#
# If content_browser is already enabled then we will immediately get a callback for it, so we want
# to do this last.
self.__content_browser_hook = ext_manager.subscribe_to_extension_enable(
self._on_browser_enabled, self._on_browser_disabled, 'omni.kit.window.content_browser')
def _on_browser_enabled(self, ext_id: str):
if not self.__content_browser_menu:
self.__content_browser_menu = ContentBrowserMenu()
def _on_browser_disabled(self, ext_id: str):
if self.__content_browser_menu:
self.__content_browser_menu.destroy()
self.__content_browser_menu = None
def _on_event(self, event):
# Create/destroy the menu in the Layers window
if self.__layers_menu:
if not layers_available():
self.__layers_menu.destroy()
self.__layers_menu = None
else:
if layers_available():
self.__layers_menu = LayersMenu()
# TODO: Create/destroy the menu in the Content Browser
if self.__content_menu:
self.__content_menu.destroy()
self.__content_menu = None
def on_shutdown(self):
self.__extensions_subscription = None
self.__content_browser_hook = None
if self.__layers_menu:
self.__layers_menu.destroy()
self.__layers_menu = None
if self.__content_menu:
self.__content_menu.destroy()
self.__content_menu = None
if self.__content_browser_menu:
self.__content_browser_menu.destroy()
self.__content_browser_menu = None
| 3,068 | Python | 37.3625 | 106 | 0.648305 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/layer_watch.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
from pxr import Sdf
from pxr import Tf
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import asyncio
import carb
import functools
import omni.kit.app
import os.path
import random
import string
import tempfile
import traceback
def handle_exception(func):
"""
Decorator to print exception in async functions
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
# We always cancel the task. It's not a problem.
pass
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
def Singleton(class_):
"""
A singleton decorator.
TODO: It's also available in omni.kit.widget.stage. We need a utility
extension where we can put the utilities like this.
"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@Singleton
class LayerWatch:
"""
Singleton object that contains all the layer watchers. When the watcher
is removed, the tmp file and directory are also removed.
"""
def __init__(self):
self.__items = {}
def start_watch(self, identifier):
"""
Create a temporary usda file and watch it. When this file is changed,
the layer with the given identifier will be updated.
"""
watch_item = self.__items.get(identifier, None)
if not watch_item:
watch_item = LayerWatchItem(identifier)
self.__items[identifier] = watch_item
return watch_item.file_name
def stop_watch(self, identifier):
"""
Stop watching to the temporary file created to the layer with the
given identifier. It will remove the temporary file.
"""
if identifier in self.__items:
self.__items[identifier].destroy()
del self.__items[identifier]
def has_watch(self, identifier):
"""
Return true if the layer with the given identifier is watched.
"""
return identifier in self.__items
def stop_all(self):
"""
Stop watching for all the layers.
"""
for _, watch in self.__items.items():
watch.destroy()
self.__items = {}
@handle_exception
async def wait_import_async(self, identifier):
"""
Wait for the importing of the layer. It happens when the layer is
changed.
"""
if identifier in self.__items:
await self.__items[identifier].wait_import_async()
class LayerWatchItem(FileSystemEventHandler):
def __init__(self, identifier):
super().__init__()
# SdfLayer
self.__layer = Sdf.Layer.FindOrOpen(identifier)
# Generate random name for temp directory
while True:
letters = string.ascii_lowercase
dir_name = "kit_usda_" + "".join(random.choice(letters) for i in range(8))
tmp_path = Path(tempfile.gettempdir()).joinpath(dir_name)
if not tmp_path.exists():
break
# Create temporary directory
tmp_path.mkdir()
# Create temporary usda file
tmp_file_path = tmp_path.joinpath(Tf.MakeValidIdentifier(Path(identifier).stem) + ".usda")
self.__file_name = tmp_file_path.resolve().__str__()
self.__layer.Export(self.__file_name)
# Save the timestamp
self.__last_mtime = os.path.getmtime(self.__file_name)
self.__build_task = None
self.__loop = asyncio.get_event_loop()
# Watch the file
self.__observer = Observer()
self.__observer.schedule(self, path=tmp_path, recursive=False)
self.__observer.start()
# This event is set when the layer is re-imported.
self.__imported_event = asyncio.Event()
@property
def file_name(self):
"""Return the temporary file name"""
return self.__file_name
def on_modified(self, event):
"""Called by watchdog when the temporary file is changed"""
# Check it's the file we are watching.
if event.src_path != self.file_name:
return
# Check the modification time.
mtime = os.path.getmtime(self.file_name)
if self.__last_mtime == mtime:
return
self.__last_mtime = mtime
# Watchdog calls callback from different thread and USD doesn't like
# it. We need to import USDA from the main thread.
if self.__build_task:
self.__build_task.cancel()
self.__build_task = asyncio.ensure_future(self.__import(), loop=self.__loop)
@handle_exception
async def __import(self):
"""Import temporary file to the USD layer"""
# Wait one frame on the case there was multiple events at the same time
await omni.kit.app.get_app().next_update_async()
file_name = self.file_name
# The file extension. For anonymous layers it's ".sdf"
format_id = f".{self.__layer.GetFileFormat().formatId}"
if format_id == ".omni_usd" or format_id == ".usd_omni_wrapper":
# The layer is on the omni server
# Import is not implemented in the Omniverse file format. So we
# clear it and transfer the content to the layer on the server.
usda = Sdf.Layer.FindOrOpen(file_name)
self.__layer.Clear()
self.__layer.TransferContent(usda)
else:
# USD can't do cross-format Import, but it can do cross-format
# export.
if Path(file_name).suffix != format_id:
# Export usda to the format of the layer.
usda = Sdf.Layer.FindOrOpen(file_name)
file_name = file_name + format_id
usda.Export(file_name)
# Import
self.__layer.Import(file_name)
if not self.__layer.anonymous:
# Save if it's not an anonymous layer. So the edit goes directly to
# the server or to the filesystem.
self.__layer.Save()
self.__imported_event.set()
self.__imported_event.clear()
@handle_exception
async def wait_import_async(self):
"""
Wait for the importing of the layer. It happens when the layer is
changed.
"""
await self.__imported_event.wait()
def destroy(self):
"""Stop watching. Delete the temporary file and the temporary directory."""
if self.__observer:
self.__observer.stop()
# Wait when it stops.
# TODO: We need to stop all of them and then join all of them.
self.__observer.join()
self.__observer = None
if self.__layer:
self.__layer = None
# Remove tmp file and tmp folder
if os.path.exists(self.__file_name):
tmp_path = Path(self.__file_name).parent
for f in tmp_path.iterdir():
if f.is_file():
f.unlink()
tmp_path.rmdir()
self.__imported_event.set()
def __del__(self):
self.destroy()
| 7,901 | Python | 30.73494 | 98 | 0.599291 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension_usda import UsdaEditExtension
| 480 | Python | 42.727269 | 76 | 0.8125 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/layers_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from . import editor
from .layer_watch import LayerWatch
from .usda_edit_utils import is_extension_loaded
def layers_available() -> bool:
"""Returns True if the extension "omni.kit.widget.layers" is loaded"""
return is_extension_loaded("omni.kit.widget.layers")
class LayersMenu:
"""
When this object is alive, Layers 2.0 has the additional context menu
with the items that allow to edit the layer in the external editor.
"""
def __init__(self):
import omni.kit.widget.layers as layers
self.__menu_subscription = layers.ContextMenu.add_menu(
[
{"name": ""},
{
"name": "Edit...",
"glyph": "menu_rename.svg",
"show_fn": [
layers.ContextMenu.is_layer_item,
layers.ContextMenu.is_not_missing_layer,
layers.ContextMenu.is_layer_writable,
layers.ContextMenu.is_layer_not_locked_by_other,
layers.ContextMenu.is_layer_and_parent_unmuted,
LayersMenu.is_not_editing,
],
"onclick_fn": LayersMenu.start_editing,
},
{
"name": "Finish editing",
"glyph": "menu_delete.svg",
"show_fn": [layers.ContextMenu.is_layer_item, LayersMenu.is_editing],
"onclick_fn": LayersMenu.stop_editing,
},
]
)
def destroy(self):
"""Stop all watchers and remove the menu from Layers 2.0"""
self.__menu_subscription = None
LayerWatch().stop_all()
@staticmethod
def start_editing(objects):
"""Start watching for the layer and run the editor"""
item = objects["item"]
identifier = item().identifier
usda_filename = LayerWatch().start_watch(identifier)
editor.run_editor(usda_filename)
@staticmethod
def stop_editing(objects):
"""Stop watching for the layer and remove the temporary files"""
item = objects["item"]
identifier = item().identifier
LayerWatch().stop_watch(identifier)
@staticmethod
def is_editing(objects):
"""Returns true if the layer is already watched"""
item = objects["item"]
identifier = item().identifier
return LayerWatch().has_watch(identifier)
@staticmethod
def is_not_editing(objects):
"""Returns true if the layer is not watched"""
return not LayersMenu.is_editing(objects)
| 3,067 | Python | 34.264367 | 89 | 0.592762 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/usda_edit_utils.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.kit.app
def is_extension_loaded(extansion_name: str) -> bool:
"""
Returns True if the extension with the given name is loaded.
"""
def is_ext(id: str, extension_name: str) -> bool:
id_name = id.split("-")[0]
return id_name == extension_name
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
extensions = ext_manager.get_extensions()
loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None)
return not not loaded
| 994 | Python | 34.535713 | 108 | 0.715292 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/editor.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Optional
import carb.settings
import os
import shutil
import subprocess
def _is_exe(path):
"""Return true if the path is executable"""
return os.path.isfile(path) and os.access(path, os.X_OK)
def run_editor(usda_filename: str):
"""Open text editor with usda_filename in it"""
settings = carb.settings.get_settings()
# Find out which editor it's necessary to use
# Check the settings
editor: Optional[str] = settings.get("/app/editor")
if not editor:
# If settings doesn't have it, check the environment variable EDITOR.
# It's the standard way to set the editor in Linux.
editor = os.environ.get("EDITOR", None)
if not editor:
# VSCode is the default editor
editor = "code"
# Remove quotes because it's a common way for windows to specify paths
if editor[0] == '"' and editor[-1] == '"':
editor = editor[1:-1]
if not _is_exe(editor):
try:
# Check if we can run the editor
editor = shutil.which(editor)
except shutil.Error:
editor = None
if not editor:
if os.name == "nt":
# All Windows have notepad
editor = "notepad"
else:
# Most Linux systems have gedit
editor = "gedit"
if os.name == "nt":
# Using cmd on the case the editor is bat or cmd file
call_command = ["cmd", "/c"]
else:
call_command = []
call_command.append(editor)
call_command.append(usda_filename)
# Non blocking call
subprocess.Popen(call_command)
| 2,054 | Python | 29.671641 | 77 | 0.642648 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/content_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from . import editor
from .layer_watch import LayerWatch
from .usda_edit_utils import is_extension_loaded
from omni.kit.ui import get_custom_glyph_code
from pathlib import Path
class ContentMenu:
"""
When this object is alive, Content Browser has the additional context menu
with the items that allow to edit the USD files in the external editor.
"""
def __init__(self):
import omni.kit.content as content
self._content_window = content.get_content_window()
edit_menu_name = f'{get_custom_glyph_code("${glyphs}/menu_rename.svg")} Edit...'
self.__edit_menu_subscription = self._content_window.add_icon_menu(
edit_menu_name, self._on_start_editing, self._is_edit_visible
)
stop_menu_name = f'{get_custom_glyph_code("${glyphs}/menu_delete.svg")} Finish editing'
self.__stop_menu_subscription = self._content_window.add_icon_menu(
stop_menu_name, self._on_stop_editing, self._is_stop_visible
)
def _is_edit_visible(self, content_url):
'''True if we can show the menu item "Edit"'''
for ext in ["usd", "usda", "usdc"]:
if content_url.endswith(f".{ext}"):
return not LayerWatch().has_watch(content_url)
def _on_start_editing(self, menu, value):
"""Start watching for the layer and run the editor"""
file_path = self._content_window.get_selected_icon_path()
usda_filename = LayerWatch().start_watch(file_path)
editor.run_editor(usda_filename)
def _is_stop_visible(self, content_url):
"""Returns true if the layer is already watched"""
return LayerWatch().has_watch(content_url)
def _on_stop_editing(self, menu, value):
"""Stop watching for the layer and remove the temporary files"""
file_path = self._content_window.get_selected_icon_path()
LayerWatch().stop_watch(file_path)
def destroy(self):
"""Stop all watchers and remove the menu from the content browser"""
del self.__edit_menu_subscription
self.__edit_menu_subscription = None
del self.__stop_menu_subscription
self.__stop_menu_subscription = None
self._content_window = None
LayerWatch().stop_all()
| 2,699 | Python | 39.298507 | 96 | 0.669507 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/tests/__init__.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .usda_test import TestUsdaEdit
| 464 | Python | 45.499995 | 76 | 0.810345 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/tests/usda_test.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from ..layer_watch import LayerWatch
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from pxr import Usd
from pxr import UsdGeom
import omni.client
import omni.kit
import omni.usd
import os
import time
import unittest
OMNI_SERVER = "omniverse://kit.nucleus.ov-ci.nvidia.com"
OMNI_USER = "omniverse"
OMNI_PASS = "omniverse"
class TestUsdaEdit(OmniUiTest):
def __set_omni_credentials(self):
# Save the environment to be able to restore it
self.__OMNI_USER = os.environ.get("OMNI_USER", None)
self.__OMNI_PASS = os.environ.get("OMNI_PASS", None)
# Set the credentials
os.environ["OMNI_USER"] = OMNI_USER
os.environ["OMNI_PASS"] = OMNI_PASS
def __restore_omni_credentials(self):
if self.__OMNI_USER is not None:
os.environ["OMNI_USER"] = self.__OMNI_USER
else:
os.environ.pop("OMNI_USER")
if self.__OMNI_PASS is not None:
os.environ["OMNI_PASS"] = self.__OMNI_PASS
else:
os.environ.pop("OMNI_PASS")
async def test_open_file(self):
# New stage with a sphere
await omni.usd.get_context().new_stage_async()
omni.kit.commands.execute("CreatePrim", prim_path="/Sphere", prim_type="Sphere", select_new_prim=False)
stage = omni.usd.get_context().get_stage()
# Create USDA
usda_filename = LayerWatch().start_watch(stage.GetRootLayer().identifier)
# Check it's a valid stage
duplicate = Usd.Stage.Open(usda_filename)
self.assertTrue(duplicate)
# Check it has the sphere
sphere = duplicate.GetPrimAtPath("/Sphere")
self.assertTrue(sphere)
UsdGeom.Cylinder.Define(duplicate, '/Cylinder')
duplicate.Save()
await omni.kit.app.get_app().next_update_async()
# Check cylinder is created
cylinder = duplicate.GetPrimAtPath("/Cylinder")
self.assertTrue(cylinder)
# Remove USDA
LayerWatch().stop_watch(stage.GetRootLayer().identifier)
# Check the file is removed
self.assertFalse(Path(usda_filename).exists())
await omni.kit.app.get_app().next_update_async()
@unittest.skip("Works locally, but fails on TC for server connection in linux -> flaky")
async def test_edit_file_on_nucleus(self):
self.__set_omni_credentials()
# Create a new stage on server
temp_usd_folder = f"{OMNI_SERVER}/Users/test_usda_edit_{str(time.time())}"
temp_usd_file_path = f"{temp_usd_folder}/test_edit_file_on_nucleus.usd"
# cleanup first
await omni.client.delete_async(temp_usd_folder)
# create the folder
result = await omni.client.create_folder_async(temp_usd_folder)
self.assertEqual(result, omni.client.Result.OK)
stage = Usd.Stage.CreateNew(temp_usd_file_path)
await omni.kit.app.get_app().next_update_async()
UsdGeom.Xform.Define(stage, '/xform')
UsdGeom.Sphere.Define(stage, '/xform/sphere')
await omni.kit.app.get_app().next_update_async()
stage.Save()
# Start watching and edit the temp stage
usda_filename = LayerWatch().start_watch(stage.GetRootLayer().identifier)
temp_stage = Usd.Stage.Open(usda_filename)
# Create another sphere
UsdGeom.Sphere.Define(temp_stage, '/xform/sphere1')
# Save the stage
temp_stage.Save()
# UsdStage saves the temorary file and renames it to usda, so we need
# to touch it to let LayerWatch know it's changed.
Path(usda_filename).touch()
# Small delay because watchdog in LayerWatch doesn't call the callback
# right away. So we need to give it some time.
await LayerWatch().wait_import_async(stage.GetRootLayer().identifier)
# Remove USDA
LayerWatch().stop_watch(stage.GetRootLayer().identifier)
stage.Reload()
# Check the second sphere is there
sphere = stage.GetPrimAtPath("/xform/sphere1")
self.assertTrue(sphere)
# Remove the temp folder
result = await omni.client.delete_async(temp_usd_folder)
self.assertEqual(result, omni.client.Result.OK)
self.__restore_omni_credentials()
| 4,700 | Python | 34.885496 | 111 | 0.657021 |
omniverse-code/kit/exts/omni.kit.usda_edit/docs/CHANGELOG.md | # Changelog
This document records all notable changes to ``omni.kit.usda_edit``
extension.
## [1.1.10] - 2022-02-02
### Changed
- Removed explicit pip dependency requirement on `watchdog`. It's now pre-bundled with Kit SDK.
## [1.1.9] - 2021-12-22
### Fixed
- content_browser context menu is now destroyed when content_browser unloaded first during kit exit
## [1.1.8] - 2021-02-23
### Changed
- The test waits for import instead of 15 frames
## [1.1.7] - 2021-02-17
### Added
- Support for the file format `usd_omni_wrapper` which is from Nucleus
### Changed
- The call of the editor is not blocking
### Fixed
- The path to editor can contain quotation marks
## [1.1.6] - 2020-12-08
### Added
- Preview image and description
## [1.1.5] - 2020-12-03
### Added
- Dependency on watchdog
## [1.1.4] - 2020-11-12
### Changed
- Fixed exception in Create
## [1.1.3] - 2020-11-11
### Changed
- Fixed the bug when the USD file destroyed when it's on the server and has the asset metadata
### Added
- Menu to `omni.kit.window.content_browser`
## [1.1.2] - 2020-07-09
### Changed
- Join the observer before destroy it. It should fix the exception when
exiting Kit.
## [1.1.1] - 2020-07-08
### Added
- Added dependency to `omni.kit.pipapi`
## [1.1.0] - 2020-07-06
### Added
- The editor executable is set using settings `/app/editor` or `EDITOR`
environment variable.
## [1.0.0] - 2020-07-06
### Added
- CHANGELOG.rst
- Added the context menu to Content Browser window to edit USDA files
## [0.1.0] - 2020-06-29
### Added
- Ability to edit USD layers as USDA files
- Added the context menu to Layers window to edit USDA files
| 1,628 | Markdown | 23.681818 | 99 | 0.689189 |
omniverse-code/kit/exts/omni.kit.usda_edit/docs/README.md | # USDA Editor [omni.kit.usda_edit]
The tool to view end edit USD layers in a text editor.
Convert a USD file to the USD ASCII format in a temporary location and run an
editor on it. After saving the editor, the edited file will be converted back
to the original format and reload the corresponding layer in Kit, invoking
the stage's update.
The context menu to edit layer appears in Layers and Content windows.
The editor can be configured with a setting `/app/editor` or environment
variable `EDITOR`. By default, the editor is either `code` or
`notepad`/`gedit`, depending on the availability.
| 601 | Markdown | 36.624998 | 77 | 0.777038 |
omniverse-code/kit/exts/omni.usd.config/omni/usd_config/extension.py | import os
from glob import glob
from pathlib import Path
import carb
import carb.dictionary
import carb.settings
import omni.ext
import omni.kit.app
from omni.mtlx import get_mtlx_stdlib_search_path
ENABLE_NESTED_GPRIMS_SETTINGS_PATH = "/usd/enableNestedGprims"
DISABLE_CAMERA_ADAPTER_SETTINGS_PATH = "/usd/disableCameraAdapter"
MDL_SEARCH_PATHS_REQUIRED = "/renderer/mdl/searchPaths/required"
MDL_SEARCH_PATHS_TEMPLATES = "/renderer/mdl/searchPaths/templates"
class Extension(omni.ext.IExt):
def __init__(self):
super().__init__()
pass
def on_startup(self):
self._app = omni.kit.app.get_app()
self._settings = carb.settings.acquire_settings_interface()
self._settings.set_default_bool(ENABLE_NESTED_GPRIMS_SETTINGS_PATH, True)
self._usd_enable_nested_gprims = self._settings.get(ENABLE_NESTED_GPRIMS_SETTINGS_PATH)
self._settings.set_default_bool(DISABLE_CAMERA_ADAPTER_SETTINGS_PATH, False)
self._usd_disable_camera_adapter = self._settings.get(DISABLE_CAMERA_ADAPTER_SETTINGS_PATH)
self._setup_usd_env_settings()
self._setup_usd_material_env_settings()
def on_shutdown(self):
self._settings = None
self._app = None
# This must be invoked before USD's TfRegistry for env settings gets initialized.
# See https://gitlab-master.nvidia.com/carbon/Graphene/merge_requests/3115#note_5019170
def _setup_usd_env_settings(self):
is_release_build = not self._app.is_debug_build()
if is_release_build:
# Disable TfEnvSetting banners (alerting users to local environment overriding Usd defaults) in release builds.
os.environ["TF_ENV_SETTING_ALERTS_ENABLED"] = "0"
# Preferring translucent over additive shaders for opacity mapped preview shaders in HdStorm.
os.environ["HDST_USE_TRANSLUCENT_MATERIAL_TAG"] = "1"
if self._usd_disable_camera_adapter:
# Disable UsdImaging camera support.
os.environ["USDIMAGING_DISABLE_CAMERA_ADAPTER"] = "1"
# Experiment with sparse light updates.
# https://github.com/PixarAnimationStudios/USD/commit/1a82d34b1144caa85909b417d18148197fba551c
# Remove this when nv-usd 20.11+ is enabled in the build.
os.environ["USDIMAGING_ENABLE_SPARSE_LIGHT_UPDATES"] = "1"
if self._usd_enable_nested_gprims:
# Enable imaging refresh for nested gprims (needed for light gizmos).
# https://nvidia-omniverse.atlassian.net/browse/OM-9446
os.environ["USDIMAGING_ENABLE_NESTED_GPRIMS"] = "1"
# Enable support for querying doubles in XformCommonAPI::GetXformVectors
os.environ["USDGEOM_XFORMCOMMONAPI_ALLOW_DOUBLES"] = "1"
# Allow material networks to be defined under IDs which are not known to SdrRegistry until we have a registration
# mechnism for mdl.
os.environ["USDIMAGING_ALLOW_UNREGISTERED_SHADER_IDS"] = "1"
# Continue supporting old mdl schema in UsdShade for now.
os.environ["USDSHADE_OLD_MDL_SCHEMA_SUPPORT"] = "1"
# Disable primvar invalidation in UsdImagingGprimAdapter so that Kit's scene delegate can perform its own primvar
# analysis.
os.environ["USDIMAGING_GPRIMADAPTER_PRIMVAR_INVALIDATION"] = "0"
# OM-18759
# Disable auto-scaling of time samples from layers whose timeCodesPerSecond do not match that of
# the stage's root layer.
# Eventually Pixar will retire this runtime switch; we'll need tooling to find and fix all
# non-compliant assets to maintain their original animated intent.
# OM-28725
# Enable auto-scaling because more and more animation content, e.g. Machinima contents, need
# this feature. Kit now has property window to adjust timeCodePerSecond for each layer so it won't
# be a big issue if animator brings in two layers with different timeCodePerSecond. Need a validator
# to notify the authors such info though.
os.environ["PCP_DISABLE_TIME_SCALING_BY_LAYER_TCPS"] = "0"
# OM-18814
# Temporarily disable notification when setting interpolation mode.
# This needs to be investigated further after Ampere demos are delivered.
os.environ["USDSTAGE_DISABLE_INTERP_NOTICE"] = "1"
# Properties which are unknown to UsdImagingGprimAdapter do not invalidate the rprim (disabled for now-
# see OM-9049. Use whitelist, blacklist, and carb logging in
# omni::usd::hydra::SceneDelegate::ProcessNonAdapterBasedPropertyChange to help contribute to re-enabling it).
# os.environ["USDIMAGING_UNKNOWN_PROPERTIES_ARE_CLEAN] = "1"
# OM-38943
# Enable parallel sync for non-material sprims (i.e., lights).
os.environ["HD_ENABLE_MULTITHREADED_NON_MATERIAL_SPRIM_SYNC"] = "1"
# OM-39636
# Disable scene index emulation until we have integated it with our HdMaterialNode changes for MDL support.
os.environ["HD_ENABLE_SCENE_INDEX_EMULATION"] = "0"
# OM-47199
# Disable the MDL Builtin Bypass for omni_usd_resolver
os.environ["OMNI_USD_RESOLVER_MDL_BUILTIN_BYPASS"] = "1"
# OM-62080
# Use NV-specific maps for optimized Hydra change tracking
os.environ["HD_CHANGETRACKER_USE_CONTIGUOUS_VALUES_MAP"] = "1"
# OM-93197
# Suppress warning spew about material bindings until assets are addressed
os.environ["USD_SHADE_MATERIAL_BINDING_API_CHECK"] = "allowMissingAPI"
def _setup_usd_material_env_settings(self):
def gather_mdl_modules(path, prefix=""):
try:
if not path.exists():
return
except:
return
for child in path.iterdir():
if child.is_file() and (child.suffix == ".mdl"):
mdl_modules.add(prefix + child.name)
elif child.is_dir():
gather_mdl_modules(child, prefix + child.stem + "/")
def process_mdl_search_path(settings_path):
paths = self._settings.get(settings_path)
if not paths:
carb.log_warn(f"Unable to query '{settings_path}' from carb.settings.")
return
paths = [Path(p.strip()) for p in paths.split(";") if p.strip()]
for p in paths:
gather_mdl_modules(p)
# use a set to avoid dupliate module names
# if Neuray finds multiple modules with the same name only the first is loaded into the database
mdl_modules = set()
process_mdl_search_path(MDL_SEARCH_PATHS_REQUIRED)
process_mdl_search_path(MDL_SEARCH_PATHS_TEMPLATES)
os.environ["OMNI_USD_RESOLVER_MDL_BUILTIN_PATHS"] = ",".join(mdl_modules)
# OM-19420, OM-88291
# Set the MaterialX library path in order to add mtlx nodes to the NDR
mtlx_library_path = get_mtlx_stdlib_search_path()
if "PXR_MTLX_STDLIB_SEARCH_PATHS" in os.environ:
os.environ["PXR_MTLX_STDLIB_SEARCH_PATHS"] += os.pathsep + mtlx_library_path
else:
os.environ["PXR_MTLX_STDLIB_SEARCH_PATHS"] = mtlx_library_path
| 7,242 | Python | 42.113095 | 123 | 0.660039 |
omniverse-code/kit/exts/omni.usd.config/omni/usd_config/__init__.py | from .extension import * | 24 | Python | 23.999976 | 24 | 0.791667 |
omniverse-code/kit/exts/omni.mdl.usd_converter/PACKAGE-LICENSES/omni.mdl.usd_converter-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.mdl.usd_converter/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "MDL to USD converter"
description="MDL to USD converter extension."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Services"
# Keywords for the extension
keywords = ["kit", "mdl", "Python bindings"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
# preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
# icon = "data/icon.png"
# Dependencies for this extension:
[dependencies]
"omni.usd" = {}
"omni.mdl.neuraylib" = {}
"omni.mdl" = {}
# Main python module this extension provides, it will be publicly available as "import omni.mdl.usd_converter".
[[python.module]]
name = "omni.mdl.usd_converter"
# Extension test settings
[[test]]
args = []
dependencies = []
stdoutFailPatterns.include = []
stdoutFailPatterns.exclude = []
| 1,654 | TOML | 30.826922 | 118 | 0.737606 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/__init__.py | from .usd_converter import *
| 29 | Python | 13.999993 | 28 | 0.758621 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/usd_converter.py | # *****************************************************************************
# Copyright 2021 NVIDIA Corporation. All rights reserved.
# *****************************************************************************
import omni.ext
import carb
import os
import shutil
import tempfile
import carb.settings
from omni.mdl import pymdlsdk
from omni.mdl import pymdl
import omni.mdl.neuraylib
from . import mdl_usd
import asyncio
from pxr import Usd
from pxr import UsdShade
MDL_AUTOGEN_PATH = "${data}/shadergraphs/mdl_usd"
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def add_search_path_to_system_path(searchPath: str):
if not searchPath == None and not searchPath == "":
MDL_SYSTEM_PATH = "/app/mdl/additionalSystemPaths"
settings = carb.settings.get_settings()
mdl_custom_paths: List[str] = settings.get(MDL_SYSTEM_PATH) or []
mdl_custom_paths.append(searchPath)
mdl_custom_paths = list(set(mdl_custom_paths))
settings.set_string_array(MDL_SYSTEM_PATH, mdl_custom_paths)
# Functions and vars are available to other extension as usual in python: `omni.mdl.usd_converter.mdl_to_usd(x)`
#
# mdl_to_usd(moduleName, targetFolder, targetFilename)
# moduleName: module to convert (example: "nvidia/core_definitions.mdl")
# searchPath: MDL search path to be able to load MDL modules referenced by moduleName
# targetFolder: Destination folder for USD stage (default = "${data}/shadergraphs/mdl_usd")
# targetFilename: Destination stage filename (default is module name, example: "core_definitions.usda")
# output: What to output:
# a shader: omni.mdl.usd_converter.mdl_usd.OutputType.SHADER
# a material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL
# geometry and material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY
# nestedShaders: Do we want nested shaders or flat (default = False)
#
def mdl_to_usd(
moduleName: str,
searchPath: str = None,
targetFolder: str = MDL_AUTOGEN_PATH,
targetFilename: str = None,
output: mdl_usd.OutputType = mdl_usd.OutputType.SHADER,
nestedShaders: bool = False):
print(f"[omni.mdl.usd_converter] mdl_to_usd was called with {moduleName}")
# acquire neuray instance from OV
ovNeurayLib = omni.mdl.neuraylib.get_neuraylib()
ovNeurayLibHandle = ovNeurayLib.getNeurayAPI()
# feed the neuray instance into the python binding
neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle)
neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status()
print(f"Neuray Status: {neurayStatus}")
# Set carb.settings with new MDL search path
add_search_path_to_system_path(searchPath)
# Select a view on the database used for the rtx renderer for.
# It should be fine to use this one always. Hydra will deal with applying the changes to the
# other renderer. It would be possible to use an own space entirely but this would double module loading.
# In the long, we want to load modules only into one scope.
dbScopeName = "rtx_scope"
# we need to load modules to OV using the omni.mdl.neuraylib
# on the c++ side this is async, here it is blocking!
print(f"createMdlModule called with: {moduleName}")
ovModule = ovNeurayLib.createMdlModule(moduleName)
print(f"CoreDefinitions: {ovModule.valid()}")
if ovModule.valid():
print(f" dbScopeName: {ovModule.dbScopeName}")
print(f" dbName: {ovModule.dbName}")
print(f" qualifiedName: {ovModule.qualifiedName}")
else:
print(f" createMdlModule failed : {moduleName}")
# after the module is loaded we create a new transaction that can see the loaded module
ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName)
trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle)
print(f"Transaction Open: {trans.is_open()}")
# try out the high level binding
module = pymdl.Module._fetchFromDb(trans, ovModule.dbName)
if module:
print(f"MDL Qualified Name: {module.mdlName}")
print(f"MDL Simple Name: {module.mdlSimpleName}")
print(f"MDL DB Name: {module.dbName}")
print(f"MDL Module filename: {module.filename}")
else:
print("MDL Module: None")
print(f"Failed to convert: {moduleName}")
return False
try:
stage = mdl_usd.Usd.Stage.CreateInMemory()
except:
trans.abort()
trans = None
return False
stage.SetMetadata('comment', 'MDL to USD conversion')
# create context for the conversion of the scene
context = mdl_usd.ConverterContext()
context.set_neuray(neuray)
context.set_transaction(trans)
context.set_stage(stage)
context.mdl_to_usd_output = output
context.mdl_to_usd_output_material_nested_shaders = nestedShaders
context.ov_neuray = ovNeurayLib
mdl_usd.module_to_stage(context, module)
# Workaround the issue creating stage under "${data}/shadergraphs/mdl_usd"
# by creating the stage in a temp folder and copying it to dest folder
with TemporaryDirectory() as temp_dir:
unmangle_helper = mdl_usd.Unmangle(context)
# Demangle instance name
(unmangled_flag, simple_name) = unmangle_helper.unmangle_mdl_identifier(module.dbName)
simple_name = simple_name.replace("::", "_")
filename = os.path.join(temp_dir, simple_name + ".usda")
if targetFilename is not None:
if targetFilename[-4:] == ".usd" or targetFilename[-5:] == ".usda":
filename = os.path.join(temp_dir, targetFilename)
else:
filename = os.path.join(temp_dir, targetFilename + ".usda")
stage.GetRootLayer().Export(filename)
# Copy file to destination folder
path = targetFolder
token = carb.tokens.get_tokens_interface()
mdlUSDPath = token.resolve(path)
dest = os.path.abspath(mdlUSDPath)
# Create folder if it does not exist
if not os.path.exists(dest):
os.makedirs(dest)
try:
shutil.copy2(filename, dest)
print(f"Stage saved as: {os.path.join(dest, os.path.basename(filename))}")
except:
print(f"Failed to save stage as: {os.path.join(dest, os.path.basename(filename))}")
pass
try:
omni.kit.window.material_graph.GraphExtension.refresh_compounds()
except:
pass
ovNeurayLib.destroyMdlModule(ovModule)
# since we have been reading only, abort
trans.abort()
trans = None
return True
def test_mdl_prim_to_usd(primPath: str):
stage = omni.usd.get_context().get_stage()
if stage:
prim = stage.GetPrimAtPath(primPath)
if prim:
mdl_prim_to_usd(stage, prim)
def mdl_prim_to_usd(stage: Usd.Stage, prim: Usd.Prim):
# Only handle material for the time beeing
if not UsdShade.Material(prim):
return
# acquire neuray instance from OV
ovNeurayLib = omni.mdl.neuraylib.get_neuraylib()
ovNeurayLibHandle = ovNeurayLib.getNeurayAPI()
# feed the neuray instance into the python binding
neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle)
neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status()
print(f"Neuray Status: {neurayStatus}")
# after the module is loaded we create a new transaction that can see the loaded module
dbScopeName = "rtx_scope"
ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName)
trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle)
print(f"Transaction Open: {trans.is_open()}")
# create context for the conversion of the scene
context = mdl_usd.ConverterContext()
context.set_neuray(neuray)
context.set_transaction(trans)
context.set_stage(stage)
context.mdl_to_usd_output = mdl_usd.OutputType = mdl_usd.OutputType.MATERIAL
context.mdl_to_usd_output_material_nested_shaders = False
context.ov_neuray = ovNeurayLib
mdl_usd.mdl_prim_to_usd(context, stage, prim)
# since we have been reading only, abort
trans.abort()
trans = None
return True
# usd_prim_to_mdl(usdStage, usdPrim, searchPath)
# usdStage: Input stage containing the Prim to convert
# usdPrim: Prim to convert (default = not set, use stage default Prim)
# searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set)
# forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False)
#
async def usd_prim_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None, forceNotOV: bool = False):
print(f"[omni.mdl.usd_converter] usd_prim_to_mdl was called with {usdStage} / {usdPrim} / {searchPath} / {forceNotOV}")
rtncode = True
# acquire neuray instance from OV
ovNeurayLib = omni.mdl.neuraylib.get_neuraylib()
ovNeurayLibHandle = ovNeurayLib.getNeurayAPI()
# feed the neuray instance into the python binding
neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle)
neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status()
print(f"Neuray Status: {neurayStatus}")
# Set carb.settings with new MDL search path
add_search_path_to_system_path(searchPath)
# Select a view on the database used for the rtx renderer for.
# It should be fine to use this one always. Hydra will deal with applying the changes to the
# other renderer. It would be possible to use an own space entirely but this would double module loading.
# In the long, we want to load modules only into one scope.
dbScopeName = "rtx_scope"
# create a new transaction
ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName)
trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle)
print(f"Transaction Open: {trans.is_open()}")
try:
stage = mdl_usd.Usd.Stage.Open(usdStage)
except:
rtncode = False
if rtncode:
if usdPrim == None:
try:
# Determine default Prim
usdPrim = stage.GetDefaultPrim().GetPath()
except:
pass
if usdPrim == None:
print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage")
rtncode = False
if rtncode:
# create context for the conversion of the scene
context = mdl_usd.ConverterContext()
context.set_neuray(neuray)
context.set_transaction(trans)
context.set_stage(stage)
if not forceNotOV:
context.ov_neuray = ovNeurayLib
inst_name = await mdl_usd.convert_usd_to_mdl(context, usdPrim, None)
rtncode = (inst_name is not None)
# transaction might have changed internally
trans = context.transaction
if not rtncode:
print(f"[omni.mdl.usd_converter] error: Conversion failure")
trans.abort()
trans = None
return rtncode
# test_export_to_mdl(usdStage, usdPrim, searchPath)
# usdStage: Input stage containing the Prim to convert
# usdPrim: Prim to convert (default = not set, use stage default Prim)
# searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set)
#
async def test_export_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None): # pragma: no cover
# Set carb.settings with new MDL search path
add_search_path_to_system_path(searchPath)
stage = None
try:
stage = mdl_usd.Usd.Stage.Open(usdStage)
except:
return False
if usdPrim == None:
try:
# Determine default Prim
usdPrim = stage.GetDefaultPrim().GetPath()
except:
pass
if usdPrim == None:
print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage")
return False
prim = stage.GetPrimAtPath(usdPrim)
path = "c:/temp/new_module.mdl"
return asyncio.ensure_future(export_to_mdl(path, prim))
# export_to_mdl(path, prim)
# path: Output file name
# prim: Prim to convert
#
# Note: The MDL modules referenced by the prim must be in the MDL searchPath
#
async def export_to_mdl(path: str, prim: mdl_usd.Usd.Prim, forceNotOV: bool = False):
if prim == None:
print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage")
return False
# acquire neuray instance from OV
ovNeurayLib = omni.mdl.neuraylib.get_neuraylib()
ovNeurayLibHandle = ovNeurayLib.getNeurayAPI()
# feed the neuray instance into the python binding
neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle)
neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status()
print(f"Neuray Status: {neurayStatus}")
# Select a view on the database used for the rtx renderer for.
# It should be fine to use this one always. Hydra will deal with applying the changes to the
# other renderer. It would be possible to use an own space entirely but this would double module loading.
# In the long, we want to load modules only into one scope.
dbScopeName = "rtx_scope"
# create a new transaction
ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName)
trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle)
print(f"Transaction Open: {trans.is_open()}")
stage = prim.GetStage()
# create context for the conversion of the scene
context = mdl_usd.ConverterContext()
context.set_neuray(neuray)
context.set_transaction(trans)
context.set_stage(stage)
if not forceNotOV:
context.ov_neuray = ovNeurayLib
usd_prim = prim.GetPath()
inst_name = await mdl_usd.convert_usd_to_mdl(context, usd_prim, path)
rtncode = (inst_name is not None)
if rtncode:
print(f"[omni.mdl.usd_converter] Export to MDL success")
else:
print(f"[omni.mdl.usd_converter] Error: Export to MDL failure")
context.transaction.abort()
context.set_transaction(None)
return rtncode
def find_tokens(lines, filter_import_lines = False):
return mdl_usd.find_tokens(lines, filter_import_lines)
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class DiscoveryExtension(omni.ext.IExt): # pragma: no cover
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[omni.mdl.usd_converter] MDL to USD converter startup")
def on_shutdown(self):
print("[omni.mdl.usd_converter] MDL to USD converter shutdown")
| 15,345 | Python | 36.798029 | 123 | 0.676442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.