file_path
stringlengths
22
162
content
stringlengths
19
501k
size
int64
19
501k
lang
stringclasses
1 value
avg_line_length
float64
6.33
100
max_line_length
int64
18
935
alphanum_fraction
float64
0.34
0.93
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/expand_menu_item.py
from typing import Dict, Optional import omni.ui as ui from omni.ui import constant as fl class _ExpandButtonDelegate(ui.MenuDelegate): """Simple button with left arrow""" def __init__(self, expanded: bool, **kwargs): self._expanded = expanded self.__icon: Optional[ui.Widget] = None super().__init__(**kwargs) def build_item(self, item: ui.MenuHelper): icon_type = "Menu.Item.Icon" self.__icon = ui.ImageWithProvider( style_type_name_override=icon_type, name="Expand", checked=self._expanded, width=20, height=30, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, ) @property def checked(self) -> bool: return self._expanded @checked.setter def checked(self, value: bool): self._expanded = value if self.__icon: self.__icon.checked = value class ExpandMenuItem(ui.MenuItem): def __init__(self, expand_model): self.__model = expand_model super().__init__( "Expand", delegate=_ExpandButtonDelegate(self.__model.as_bool), triggered_fn=lambda: self.__model.set_value(not self.__model.as_bool), identifier="viewport.camera.expand", ) @property def checked(self): return self.delegate.checked @checked.setter def checked(self, value: bool): self.delegate.checked = value
1,508
Python
27.471698
86
0.576923
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_api.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. ## __all__ = ['TestAPI'] import omni.kit.test import functools from omni.kit.test import AsyncTestCase from unittest.mock import patch, call from omni.kit.viewport.menubar.camera import get_instance as _get_menubar_extension from omni.kit.viewport.menubar.camera import SingleCameraMenuItem as _SingleCameraMenuItem from omni.kit.viewport.menubar.camera import SingleCameraMenuItemBase as _SingleCameraMenuItemBase from omni.kit.viewport.menubar.camera.camera_menu_container import CameraMenuContainer as _CameraMenuContainer class TestAPI(AsyncTestCase): async def test_get_instance(self): extension = _get_menubar_extension() self.assertIsNotNone(extension) async def test_register_custom_menu_item_type(self): def _single_camera_menu_item(*args, **kwargs): class SingleCameraMenuItem(_SingleCameraMenuItemBase): pass return SingleCameraMenuItem(*args, **kwargs) extension = _get_menubar_extension() self.assertIsNotNone(extension) try: with patch.object(_CameraMenuContainer, "set_menu_item_type") as set_menu_item_type_mock: fn = functools.partial(_single_camera_menu_item) extension.register_menu_item_type( fn ) self.assertEqual(1, set_menu_item_type_mock.call_count) self.assertEqual(call(fn), set_menu_item_type_mock.call_args) finally: extension.register_menu_item_type(None) async def test_register_regular_menu_item_type(self): def _single_camera_menu_item(*args, **kwargs): return _SingleCameraMenuItem(*args, **kwargs) extension = _get_menubar_extension() self.assertIsNotNone(extension) try: with patch.object(_CameraMenuContainer, "set_menu_item_type") as set_menu_item_type_mock: fn = functools.partial(_single_camera_menu_item) extension.register_menu_item_type( fn ) self.assertEqual(1, set_menu_item_type_mock.call_count) self.assertEqual(call(fn), set_menu_item_type_mock.call_args) finally: extension.register_menu_item_type(None)
2,704
Python
40.615384
110
0.677515
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/__init__.py
from .test_api import * from .test_commands import * from .test_ui import * from .test_focal_distance import *
111
Python
21.399996
34
0.738739
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_ui.py
from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.menubar.camera import get_instance as _get_menubar_extension from omni.kit.viewport.menubar.camera import SingleCameraMenuItemBase from omni.kit.viewport.utility import get_active_viewport, get_active_viewport_window import omni.usd import omni.kit.app import functools import omni.kit.test import omni.appwindow import carb.input from pathlib import Path import omni.ui as ui import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 import unittest from pxr import Sdf, Usd, UsdGeom CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 850, 300 class ToggleExpansionState(): def __init__(self): self.__settings = carb.settings.get_settings() self.__key = "/persistent/exts/omni.kit.viewport.menubar.camera/expand" self.__restore_value = self.__settings.get(self.__key) def set(self, value: bool): self.__settings.set(self.__key, value) def __del__(self): self.__settings.set(self.__key, self.__restore_value) class TestCameraMenuWindow(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def test_general(self): await self.finalize_test(golden_img_name="menubar_camera.png") async def test_lock(self): viewport = get_active_viewport() viewport.camera_path = UsdGeom.Camera.Define(viewport.stage, '/NewCamera').GetPath() path = Sdf.Path(viewport.camera_path).AppendProperty("omni:kit:cameraLock") omni.kit.commands.execute('ChangePropertyCommand', prop_path=path, value=True, prev=False, timecode=Usd.TimeCode.Default(), type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool) try: await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_name="menubar_camera_locked.png") finally: omni.kit.commands.execute('ChangePropertyCommand', prop_path=path, value=False, prev=False, timecode=Usd.TimeCode.Default(), type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool) async def test_collapsed(self): """Test collapse/expand functionality of additional camera properties""" settings = carb.settings.get_settings() expand_state = ToggleExpansionState() try: expand_state.set(False) await self.finalize_test(golden_img_name="menubar_camera_collpased.png") expand_state.set(True) await self.finalize_test(golden_img_name="menubar_camera_expanded.png") finally: del expand_state await self.wait_n_updates() async def test_resize_4_in_1(self): restore_width = self._viewport_window.width expand_state = ToggleExpansionState() expand_state.set(True) await self.wait_n_updates(2) try: # resize 1: contract settings self._viewport_window.width = 200 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_contract_settings.png") # resize 2: contract text self._viewport_window.width = 60 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_contract_text.png") # resize 3 : expand text self._viewport_window.width = 200 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_expand_text.png") # resize 4 : expand settings self._viewport_window.width = restore_width await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_expand_settings.png") finally: del expand_state self._viewport_window.width = restore_width await self.wait_n_updates() async def test_user_menu_item(self): def __create_first(viewport_context, root): ui.MenuItem("This is first custom menu item") def __create_second(viewport_context, root): ui.MenuItem("This is second custom menu item") expand_state = ToggleExpansionState() instance = omni.kit.viewport.menubar.camera.get_instance() try: instance.register_menu_item(__create_second, order=20) instance.register_menu_item(__create_first, order=10) expand_state.set(True) await self.__click_root_menu_item() await self.finalize_test(golden_img_name="menubar_camera_custom.png") await ui_test.emulate_mouse_click() expand_state.set(False) await self.__click_root_menu_item() await self.finalize_test(golden_img_name="menubar_camera_custom_collapsed.png") finally: await ui_test.emulate_mouse_click() instance.deregister_menu_item(__create_first) instance.deregister_menu_item(__create_second) del expand_state await self.wait_n_updates() async def __click_root_menu_item(self): # Enable mouse input app_window = omni.appwindow.get_default_app_window() for device in [carb.input.DeviceType.MOUSE]: app_window.set_input_blocking_state(device, None) await ui_test.emulate_mouse_move(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() async def test_camera_menu_with_custom_type(self): menu_option_clicked = 0 def _single_camera_menu_item(*args, **kwargs): class SingleCameraMenuItem(SingleCameraMenuItemBase): def _option_clicked(self): nonlocal menu_option_clicked menu_option_clicked += 1 return SingleCameraMenuItem(*args, **kwargs) await self.__click_root_menu_item() self.assertEqual(0, menu_option_clicked) await ui_test.emulate_mouse_move(Vec2(140, 110)) await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(0, menu_option_clicked) extension = _get_menubar_extension() try: extension.register_menu_item_type( functools.partial(_single_camera_menu_item) ) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(1, menu_option_clicked) finally: extension.register_menu_item_type(None) # Call it again to hide popup menu window await self.__click_root_menu_item() async def test_external_cam_change(self): # Get the Viewport and change the active camera viewport = get_active_viewport() orig_cam_path = viewport.camera_path new_cam_path = Sdf.Path('/OmniverseKit_Top') self.assertNotEqual(orig_cam_path, new_cam_path) try: viewport.camera_path = new_cam_path # Change should be reflected in UI await self.wait_n_updates(10) await self.finalize_test(golden_img_name="menubar_camera_external_cam_change.png") finally: viewport.camera_path = orig_cam_path class TestCameraMenuHideStageCameras(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showStageCameras", False) # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showStageCameras", True) await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def __click_root_menu_item(self): # Enable mouse input app_window = omni.appwindow.get_default_app_window() for device in [carb.input.DeviceType.MOUSE]: app_window.set_input_blocking_state(device, None) await ui_test.emulate_mouse_move(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() async def test_hide_stage_cameras(self): """Test hide functionality of stage cameras properties""" await self.__click_root_menu_item() try: await self.finalize_test(golden_img_name="menubar_hide_stage_cameras.png") finally: await self.wait_n_updates() await self.__click_root_menu_item() class TestCameraMenuHideManualExposure(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showManualExposure", False) # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showManualExposure", True) await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def test_hide_manual_exposure(self): """Test hiding of manual exposure camera properties""" try: await self.finalize_test(golden_img_name="menubar_hide_manual_exposure.png") finally: await self.wait_n_updates()
11,466
Python
36.230519
113
0.643293
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_focal_distance.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 carb.input from omni.ui.tests.test_base import OmniUiTest import omni.usd from pxr import Gf, UsdGeom import omni.kit.ui_test as ui_test from omni.kit.viewport.utility import get_active_viewport_window from omni.kit.ui_test import Vec2 TEST_WIDTH, TEST_HEIGHT = 850, 300 class TestFocalDistance(OmniUiTest): async def setUp(self): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() self.stage.SetDefaultPrim(UsdGeom.Xform.Define(self.stage, '/World').GetPrim()) await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): self.usd_context = None self.stage = None async def test_cam_sample_focal_distance(self): # create a test camera cam_path = '/World/TestCamera' cam_prim = UsdGeom.Camera.Define(self.stage, cam_path).GetPrim() omni.kit.commands.execute("TransformPrimSRTCommand", path=cam_path, new_translation=Gf.Vec3d(0, 0, 15)) focus_dist_attr = cam_prim.GetAttribute('focusDistance') focus_dist_attr.Set(400) # create a cube as the sample sample_path = '/World/Cube' UsdGeom.Cube.Define(self.stage, sample_path) await self.wait_n_updates(300) # set the test cam to be the viewport cam app_window = omni.appwindow.get_default_app_window() app_window.set_input_blocking_state(carb.input.DeviceType.MOUSE, None) # open camera list await ui_test.emulate_mouse_move(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # cameras await ui_test.emulate_mouse_move(Vec2(40, 75)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # choose test camera await ui_test.emulate_mouse_move(Vec2(200, 75)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # decrease the focal distance by 3 await ui_test.emulate_mouse_move(Vec2(340, 50)) for _ in range(3): await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(focus_dist_attr.Get(), 397) # click focal sample button to enable sample picker await ui_test.emulate_mouse_move(Vec2(370, 40)) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() # click the sample object (cube) to reset the focal distance await ui_test.emulate_mouse_move(Vec2(420, 150)) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates(10) self.assertAlmostEqual(focus_dist_attr.Get(), 14, places=2)
3,524
Python
37.315217
111
0.667423
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_commands.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. ## __all__ = ['TestCommands'] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.usd from pxr import Gf, Sdf, UsdGeom import omni.kit.undo import carb # Test that the Viewport-level commands reach the proper methods class TestViewportAPI: def __init__(self, usd_context_name, cam_path: str = None): self.usd_context_name = usd_context_name self.usd_context = omni.usd.get_context() self.stage = self.usd_context.get_stage() self.__camera_path = cam_path @property def camera_path(self): return self.__camera_path @camera_path.setter def camera_path(self, cam_path): self.__camera_path = cam_path class TestCommands(AsyncTestCase): async def setUp(self): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() self.stage.SetDefaultPrim(UsdGeom.Xform.Define(self.stage, '/World').GetPrim()) async def tearDown(self): self.usd_context = None self.stage = None async def test_duplicate_camera(self): def get_num_xform_ops(cam: UsdGeom.Camera): xform_ops = cam.GetOrderedXformOps() return len(xform_ops) if xform_ops else 0 cam_path = '/World/TestCamera' new_camera = UsdGeom.Camera.Define(self.stage, '/World/TestCamera') # This camera has no xformOps self.assertEqual(0, get_num_xform_ops(new_camera)) omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path) # Should have duplicated to '/World/Camera' dup_camera_path = '/World/Camera' dup_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(dup_camera_path)) # Validate the new camera self.assertIsNotNone(dup_camera) self.assertTrue(bool(dup_camera)) # Should have 3 xformOps, in order to honor the defaut camera roation order self.assertEqual(3, get_num_xform_ops(dup_camera)) # Test duplication of implicit camera omni.kit.commands.execute("DuplicateCameraCommand", camera_path='/OmniverseKit_Persp') # Test both of these meta-data entries are true for an implicit Camera self.assertTrue(omni.usd.editor.is_hide_in_stage_window(self.stage.GetPrimAtPath('/OmniverseKit_Persp'))) self.assertTrue(omni.usd.editor.is_no_delete(self.stage.GetPrimAtPath('/OmniverseKit_Persp'))) num_xfops_1 = get_num_xform_ops(new_camera) # Should have duplicated to '/World/Camera_1' dup_camera_path = '/World/Camera_01' dup_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(cam_path)) # Validate the new camera self.assertIsNotNone(dup_camera) self.assertTrue(bool(dup_camera)) # Should have same number of xformOps now self.assertEqual(num_xfops_1, get_num_xform_ops(dup_camera)) # Test both of these meta-data entries are false after duplicating an implicit Camera self.assertFalse(omni.usd.editor.is_hide_in_stage_window(dup_camera.GetPrim())) self.assertFalse(omni.usd.editor.is_no_delete(dup_camera.GetPrim())) async def test_duplicate_camera_unlocked(self): cam_path = '/World/TestCamera' cam_lock = 'omni:kit:cameraLock' usd_camera = UsdGeom.Camera.Define(self.stage, '/World/TestCamera') prop = usd_camera.GetPrim().CreateAttribute(cam_lock, Sdf.ValueTypeNames.Bool, True) prop.Set(True) # Make sure the lock attribute is present and set to true self.assertTrue(usd_camera.GetPrim().GetAttribute(cam_lock).Get()) omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path) cam_path = '/World/Camera' # Should have duplicated to '/World/Camera' new_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(cam_path)) # Validate the new camera self.assertIsNotNone(new_camera) self.assertTrue(bool(new_camera)) # Make sure the lock attribute wasn't copied over self.assertFalse(new_camera.GetPrim().GetAttribute(cam_lock).IsValid()) # Nothing should have affected the original self.assertTrue(usd_camera.GetPrim().GetAttribute(cam_lock).Get()) async def test_duplicate_camera_with_name(self): cam_path = '/World/TestCamera' UsdGeom.Camera.Define(self.stage, '/World/TestCamera') new_cam_path = '/World/TestDuplicatedCamera' omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path, new_camera_path=new_cam_path) # Should have duplicated to '/World/TestDuplicatedCamera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) # Undo the command omni.kit.undo.undo() # Camera should no longer be valid (its been deleted) self.assertFalse(bool(camera)) async def test_duplicate_viewport_camera(self): cam_path = '/World/TestCamera' UsdGeom.Camera.Define(self.stage, cam_path) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api) # Should have duplicated to '/World/Camera' new_cam_path = '/World/Camera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) self.assertEqual(viewport_api.camera_path, new_cam_path) # Undo the command omni.kit.undo.undo() # Viewport should have been reset self.assertEqual(viewport_api.camera_path, cam_path) # Camera should no longer be valid (its been deleted) self.assertFalse(bool(camera)) async def __test_duplicate_viewport_camera_hierarchy(self, rot_order: str = None): settings = carb.settings.get_settings() try: default_prim = self.stage.GetDefaultPrim() root_path = default_prim.GetPath().pathString if default_prim else '' parent_paths = (f'{root_path}/Xform0', f'{root_path}/Xform0/Xform1') cam_path = f'{parent_paths[1]}/TestCamera' UsdGeom.Xform.Define(self.stage, parent_paths[0]) omni.kit.commands.execute("TransformPrimSRTCommand", path=parent_paths[0], new_translation=Gf.Vec3d(10, 10, 10)) UsdGeom.Xform.Define(self.stage, parent_paths[1]) omni.kit.commands.execute("TransformPrimSRTCommand", path=parent_paths[1], new_translation=Gf.Vec3d(10, 10, 10), new_rotation_euler=Gf.Vec3d(90, 0, 0)) UsdGeom.Camera.Define(self.stage, cam_path) omni.kit.commands.execute("TransformPrimSRTCommand", path=cam_path, new_translation=Gf.Vec3d(10, 10, 10), new_rotation_euler=Gf.Vec3d(90, 0, 0)) # Set the rotation order now to test that moving from an existing order to a new one works if rot_order: settings.set('/persistent/app/primCreation/DefaultCameraRotationOrder', rot_order) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api) # Should have duplicated to '/World/Camera' new_cam_path = f'{root_path}/Camera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) self.assertEqual(viewport_api.camera_path, new_cam_path) src_xform = omni.usd.get_world_transform_matrix(self.stage.GetPrimAtPath(cam_path)) dst_xform = omni.usd.get_world_transform_matrix(self.stage.GetPrimAtPath(new_cam_path)) self.assertTrue(Gf.IsClose(src_xform, dst_xform, 1.0e-5)) if rot_order: self.assertTrue(f'xformOp:rotate{rot_order}' in camera.GetXformOpOrderAttr().Get()) finally: if rot_order: settings.destroy_item('/persistent/app/primCreation/DefaultCameraRotationOrder') async def test_duplicate_viewport_camera_hierarchy(self): await self.__test_duplicate_viewport_camera_hierarchy() async def test_duplicate_viewport_camera_hierarchy_with_order(self): '''Test duplictaing a camera that is nested in a transformed honors default camera rotation order''' await self.__test_duplicate_viewport_camera_hierarchy('XYZ') # Test again with a different order and also without a default prim await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() await self.__test_duplicate_viewport_camera_hierarchy('ZYX') async def test_set_viewport_camera(self): cam_path = '/World/TestCamera' cam_path2 = '/World/TestCamera2' UsdGeom.Camera.Define(self.stage, cam_path) UsdGeom.Camera.Define(self.stage, cam_path) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("SetViewportCameraCommand", camera_path=cam_path2, viewport_api=viewport_api) # Should now be set to cam_path2 self.assertEqual(viewport_api.camera_path, cam_path2) # Undo the command omni.kit.undo.undo() # Should now be set to cam_path self.assertEqual(viewport_api.camera_path, cam_path)
10,059
Python
42.930131
163
0.672134
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/omni/kit/viewport/legacy_gizmos/tests/test_legacy_gizmos.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 import asyncio import carb import omni.kit.app import omni.kit.test import omni.hydratexture import omni.renderer_capture from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric import omni.usd from pxr import Usd, Gf # FIXME: omni.ui.ImageProvider holds the carb.Format conversion routine import omni.ui EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_DIR = EXTENSION_FOLDER_PATH.joinpath('data', 'tests') KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve('${kit}')).parent.parent.parent OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path()) from sys import platform if platform.find('linux') == 0: IMAGE_PLATFORM='linux' elif platform == 'darwin': IMAGE_PLATFORM='macos' elif platform == 'win32': IMAGE_PLATFORM='windows' class TestLegacyGizmos(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.acquire_settings_interface() self._hydra_texture_factory = omni.hydratexture.acquire_hydra_texture_factory_interface() self._render_capture = omni.renderer_capture.acquire_renderer_capture_interface() self._usd_context_name = 'test_context' self._usd_context = omni.usd.create_context(self._usd_context_name) async def tearDown(self): omni.usd.release_all_hydra_engines(self._usd_context) omni.usd.destroy_context(self._usd_context_name) self._hydra_texture_factory = None self._settings = None self._render_capture = None async def _create_hydra_texture_test(self, filename: str = None): wait_iterations = 15 try: if 'rtx' not in self._usd_context.get_attached_hydra_engine_names(): omni.usd.add_hydra_engine('rtx', self._usd_context) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async() if filename: test_usd_asset = TEST_DATA_DIR.joinpath(filename) self._usd_context.open_stage_with_callback(str(test_usd_asset), None) else: self._usd_context.new_stage_with_callback(None) hydra_texture = self._hydra_texture_factory.create_hydra_texture( 'test_viewport', 320, 320, self._usd_context_name, '/OmniverseKit_Persp', 'rtx', is_async=False ) return hydra_texture finally: for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async() async def _capture_hydra_texture(self, hydra_texture, test_name: str, converge: int = 5, platform_image: bool = False): drawable_result = asyncio.Future() if platform_image: global IMAGE_PLATFORM image_name = f'{test_name}_{IMAGE_PLATFORM}.png' else: image_name = f'{test_name}.png' filepath = OUTPUTS_DIR.joinpath(image_name).absolute() def on_drawable_changed(event: carb.events.IEvent): if event.type != omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED: carb.log_error('Wrong event captured for DRAWABLE_CHANGED') return result_handle = event.payload['result_handle'] self.assertIsNotNone(result_handle) ldr_info = hydra_texture.get_aov_info(result_handle, 'LdrColor', include_texture=True) self.assertEqual(len(ldr_info), 1) self.assertEqual(ldr_info[0]['name'], 'LdrColor') ldr_tex = ldr_info[0]['texture'] self.assertIsNotNone(ldr_tex) ldr_rsrc = ldr_tex['rp_resource'] self.assertIsNotNone(ldr_rsrc) nonlocal converge converge = converge - 1 if converge <= 0 and not drawable_result.done(): self._render_capture.capture_next_frame_rp_resource(str(filepath), ldr_rsrc) drawable_result.set_result(True) drawable_change_sub = hydra_texture.get_event_stream().create_subscription_to_push_by_type( omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED, on_drawable_changed, name="_capture_hydra_texture", ) result = await drawable_result drawable_change_sub = None self.assertTrue(result) return image_name async def capture_and_compare(self, image_name: str, threshold: float = 1e-4): # self._render_capture.wait_async_capture() diff = finalize_capture_and_compare(image_name, threshold=threshold, output_img_dir=OUTPUTS_DIR, golden_img_dir=TEST_DATA_DIR, metric=ComparisonMetric.MEAN_ERROR_SQUARED) if diff > threshold: carb.log_error(f'The generated image {image_name} has a difference of {diff}, but max difference is {threshold}') async def test_light_gizmos(self): hydra_texture = await self._create_hydra_texture_test('gizmos.usda') self.assertIsNotNone(hydra_texture) # >> test_sphere_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 1) self._settings.set('/persistent/app/viewport/gizmo/scale', 1) self._usd_context.get_selection().set_selected_prim_paths(['/World/SphereLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_sphere_light', platform_image=True) await self.capture_and_compare(image) # << test_sphere_light # >> test_cylinder_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 2) self._settings.set('/persistent/app/viewport/gizmo/scale', 2) self._usd_context.get_selection().set_selected_prim_paths(['/World/CylinderLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_cylinder_light', platform_image=True) await self.capture_and_compare(image) # << test_cylinder_light # >> test_disk_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 10) self._settings.set('/persistent/app/viewport/gizmo/scale', 10) self._usd_context.get_selection().set_selected_prim_paths(['/World/DiskLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_disk_light', platform_image=True) await self.capture_and_compare(image) # << test_disk_light # >> test_rect_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 20) self._settings.set('/persistent/app/viewport/gizmo/scale', 20) self._usd_context.get_selection().set_selected_prim_paths(['/World/RectLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_rect_light', platform_image=True) await self.capture_and_compare(image) # << test_rect_light async def test_grid_drawing(self): hydra_texture = await self._create_hydra_texture_test('empty.usda') self.assertIsNotNone(hydra_texture) # >> test_grid_drawing self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/persistent/app/viewport/grid/lineWidth', 1) self._settings.set('/persistent/app/viewport/grid/scale', 100) # Need to wait for slightly more frames on Linux to avoid writing black imge / failure image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing', converge=20) await self.capture_and_compare(image) # << test_grid_drawing # >> test_grid_drawing_yz self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'YZ') self._settings.set('/persistent/app/viewport/grid/lineWidth', 10) self._settings.set('/persistent/app/viewport/grid/scale', 150) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_yz') await self.capture_and_compare(image) # << test_grid_drawing_yz # >> test_grid_drawing_xy self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'XY') self._settings.set('/persistent/app/viewport/grid/lineWidth', 4) self._settings.set('/persistent/app/viewport/grid/scale', 200) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_xy') await self.capture_and_compare(image) # << test_grid_drawing_xy # >> test_grid_drawing_xz self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'XZ') self._settings.set('/persistent/app/viewport/grid/lineWidth', 6) self._settings.set('/persistent/app/viewport/grid/scale', 250) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_xz') await self.capture_and_compare(image) # << test_grid_drawing_xz async def test_camera_gizmos(self): hydra_texture = await self._create_hydra_texture_test('cameras.usda') self.assertIsNotNone(hydra_texture) wait_iterations = 5 try: self._settings.set('/app/viewport/show/camera', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', False) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', False) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 10.0) self._settings.set('/persistent/app/viewport/gizmo/scale', 2.0) self._settings.set('/app/viewport/grid/enabled', False) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_0') await self.capture_and_compare(image) stage = self._usd_context.get_stage() camera_prim = stage.GetPrimAtPath('/World/Camera') camera_prim.GetAttribute('xformOp:translate').Set(Gf.Vec3d(0, 0, -250)) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_1') await self.capture_and_compare(image) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 50.0) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', True) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_2') await self.capture_and_compare(image) finally: self._settings.set('/app/viewport/show/camera', False) self._settings.set('/persistent/app/viewport/gizmo/scale', 1.0) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 10.0) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', False)
12,491
Python
45.095941
125
0.650548
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/omni/kit/viewport/legacy_gizmos/tests/__init__.py
from .test_legacy_gizmos import TestLegacyGizmos
49
Python
23.999988
48
0.857143
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/notification_info.py
class NotificationStatus: WARNING = 0 INFO = 1 class NotificationButtonInfo: def __init__(self, text, on_complete=None): """ Constructor for notification button. text (str): The button text. on_complete (Callable[]): The handler to handle button click. """ self._text = text self._on_complete = on_complete @property def text(self): return self._text @property def handler(self): return self._on_complete class NotificationInfo: def __init__( self, text, hide_after_timeout=True, duration=3, status=NotificationStatus.INFO, button_infos=[]): self._text = text self._hide_after_timeout = hide_after_timeout self._duration = duration self._status = status if not button_infos and not hide_after_timeout: button_info = NotificationButtonInfo("Dismiss", None) self._button_infos = [button_info] else: self._button_infos = button_infos @property def text(self): return self._text @property def hide_after_timeout(self): return self._hide_after_timeout @property def duration(self): return self._duration @property def status(self): return self._status @property def button_infos(self): return self._button_infos
1,448
Python
21.640625
69
0.580801
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/extension.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 asyncio import os import weakref import omni.ext from functools import partial from .manager import NotificationManager from .notification_info import NotificationInfo, NotificationStatus _global_instance = None def post_notification( text, hide_after_timeout=True, duration=3, status=NotificationStatus.INFO, button_infos=[] ): """ Post notification. If viewport is visible, it will be docked to the right-button of viewport. Otherwise, it will be docked to main window. Args: text (str): The notification text. hide_after_timeout (bool): If the notification will hide after duration. If it's False, and button_details are not provided, it will display a default dismiss button. duration (int): The duration (in seconds) after which the notification will be hidden. This duration only works if hide_after_timeout is True. status (NotificationStatus): The notification type. button_infos ([NotificationButtonInfo]): Array of buttons. Returns: Notification handler. Examples: >>> import omni.kit.notification_manager as nm >>> >>> ok_button = nm.NotificationButtonInfo("OK", on_complete=None) >>> cancel_button = nm.NotificationButtonInfo("CANCEL", on_complete=None) >>> notification = nm.post_notification( "Notification Example", hide_after_timeout=False, duration=0, status=nm.NotificationStatus.WARNING, button_infos=[ok_button, cancel_button]) """ global _global_instance if _global_instance and _global_instance(): ni = NotificationInfo(text, hide_after_timeout, duration, status, button_infos) return _global_instance().post_notification(ni) return None class NotificationManagerExtension(omni.ext.IExt): def on_startup(self): global _global_instance _global_instance = weakref.ref(self) self._notification_manager = NotificationManager() self._notification_manager.on_startup() def on_shutdown(self): global _global_instance _global_instance = None self._notification_manager.on_shutdown() self._notification_manager = None def post_notification(self, notification_info: NotificationInfo): return self._notification_manager.post_notification(notification_info)
2,929
Python
37.552631
132
0.681803
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/manager.py
import asyncio import carb import omni.kit.app import omni.ui as ui from typing import List from .notification_info import NotificationInfo, NotificationStatus from .prompt import Prompt SETTINGS_DISABLE_NOTIFICATIONS = "/exts/omni.kit.notification_manager/disable_notifications" class Notification: """Handler of notification""" def __init__(self, notification_info: NotificationInfo, notification_manager): """Internal constructor""" self._prompt = None self._notification_info = notification_info self._time_passed = 0 self._notification_mananger = notification_manager self._is_warming = True def destroy(self): self._is_warming = False self._notification_info = None if self._prompt: self._prompt.destroy() self._prompt = None if self._notification_mananger: self._notification_mananger.remove_notification(self) self._notification_mananger = None def _step_and_check(self, dt): if not self._prompt: return True if self._notification_info.hide_after_timeout: if self._time_passed >= self._notification_info.duration: return True self._time_passed += dt return False async def _docking_to(self, window_x, window_y, window_width, window_height, offset_y=0): if self._prompt: await self._prompt.docking_to(window_x, window_y, window_width, window_height, offset_y) def _hide(self): if self._prompt: self._prompt.hide() async def _pre_warming(self): self._prompt = Prompt(self._notification_info) # Set it to a corner pos self._prompt.position_x = 100000 self._prompt.position_y = 100000 # FIXME: After creation, the notification window still # does not have the correct width/height. It needs to # show and wait for the first draw to get correct width/height. # The following code shows it and all notification will # be transparent at the start. After getting correct widht/height, # it will be positioned to correct position later. self._prompt.show() self._is_warming = False async def _warming(): while not self._notification_mananger._shutdown and (self._prompt.width == 0.0 or self._prompt.height == 0.0): await omni.kit.app.get_app().next_update_async() self._hide() if not self._notification_mananger._shutdown: self._notification_mananger._pending_notifications.append(self) await _warming() @property def _dismissed(self): return self._prompt is None or not self._prompt.visible @property def _hovered(self): return self._prompt and self._prompt.hovered @property def info(self): return self._notification_info def dismiss(self): self.destroy() @property def dismissed(self): return not self._is_warming and self._prompt is None class NotificationManager: def on_startup(self): self._max_showed_notifications = 5 self._max_throttle_notifications = self._max_showed_notifications + 2 self._pre_warming_notifications: List[Notification] = [] self._pending_notifications: List[Notification] = [] self._notifications: List[Notification] = [] self._timer_task = None self._shutdown = False self._docking_window_width = 0 self._docking_window_height = 0 self._docking_window_pos_x = 0 self._docking_window_pos_y = 0 async def timer_fn(): while not self._shutdown: """ For each notification, it has 3 stages: 1. When it's created, it will be put in the pre-warming queue. Pre-warming is a WA to calculate the real size of prompt before it's positioning. 2. After pre-warming, it will be put to pending queue and waits to be displayed there. 3. If there is vacancy (determined by _max_showed_notifications), it will be displayed to viewport finally. """ showed_notifications = len(self._pending_notifications) + len(self._notifications) new_notifications = max(self._max_throttle_notifications - showed_notifications, 0) new_notifications = min(len(self._pre_warming_notifications), new_notifications) for _ in range(new_notifications): notification = self._pre_warming_notifications.pop(0) await notification._pre_warming() # To avoid flooding notification queue, all others will be flushed to console. for notification in self._pre_warming_notifications: if notification.info.status == NotificationStatus.INFO: carb.log_info(notification.info.text) else: carb.log_warn(notification.info.text) notification.destroy() self._pre_warming_notifications.clear() changed = self._on_docking_window_changed() pending_to_remove = [] for notification in self._notifications: if ( (notification._step_and_check(0.5) and not notification._hovered) or notification._dismissed ): pending_to_remove.append(notification) if len(pending_to_remove): changed = True for item in pending_to_remove: item.destroy() num_current_notifications = len(self._notifications) if num_current_notifications < self._max_showed_notifications: new_added = self._max_showed_notifications - num_current_notifications else: new_added = 0 num_pending_notifications = len(self._pending_notifications) new_added = min(new_added, num_pending_notifications) for i in range(new_added): notification = self._pending_notifications.pop(0) self._notifications.append(notification) if new_added > 0: changed = True if changed: offset_y = 0 for notification in self._notifications: await notification._docking_to(self._docking_window_pos_x, self._docking_window_pos_y, self._docking_window_width, self._docking_window_height, offset_y) offset_y += notification._prompt.height + 5 # Step 1s await asyncio.sleep(0.5) self._timer_task = asyncio.ensure_future(timer_fn()) def on_shutdown(self): self._shutdown = True if self._timer_task: self._timer_task.cancel() self._timer_task = None for notification in self._notifications: notification.destroy() for notification in self._pending_notifications: notification.destroy() for notification in self._pre_warming_notifications: notification.destroy() self._notifications.clear() self._pending_notifications.clear() self._pre_warming_notifications.clear() def post_notification(self, notification_info: NotificationInfo): notification = Notification(notification_info, self) # OM-87367: options to disable all notifications. settings = carb.settings.get_settings() disable_all_notifications = settings.get(SETTINGS_DISABLE_NOTIFICATIONS) if disable_all_notifications: if notification.info.status == NotificationStatus.INFO: carb.log_info(notification.info.text) else: carb.log_warn(notification.info.text) notification.destroy() else: self._pre_warming_notifications.append(notification) # Still returns the handle of notification. return notification def remove_notification(self, notification: Notification): try: if notification in self._notifications: self._notifications.remove(notification) if notification in self._pending_notifications: self._pending_notifications.remove(notification) if notification in self._pre_warming_notifications: self._pre_warming_notifications.remove(notification) except ValueError: pass def _on_docking_window_changed(self): viewport = ui.Workspace.get_window("Viewport") if viewport and viewport.visible: window_position_x = viewport.position_x window_position_y = viewport.position_y window_width = viewport.width window_height = viewport.height else: window_position_x = 0 window_position_y = 0 window_width = ui.Workspace.get_main_window_width() window_height = ui.Workspace.get_main_window_height() if ((self._docking_window_pos_x != window_position_x) or (self._docking_window_pos_y != window_position_y) or (self._docking_window_width != window_width) or (self._docking_window_height != window_height)): self._docking_window_pos_x = window_position_x self._docking_window_pos_y = window_position_y self._docking_window_width = window_width self._docking_window_height = window_height return True return False
9,827
Python
37.390625
177
0.598962
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/prompt.py
import weakref import omni.ui as ui import omni.kit.app import uuid from .notification_info import NotificationStatus, NotificationButtonInfo, NotificationInfo from .icons import Icons HOVER_AREA_TRANSPARENT_STYLE = { "background_color": 0x0, "background_gradient_color": 0x0, "background_selected_color": 0x0, "border_color": 0x0, "color": 0x0, "selected_color": 0x0, "secondary_color": 0x0, "secondary_selected_color": 0x0, "debug_color": 0x0 } HOVER_AREA_DEFAULT_STYLE = { "Rectangle::hover_area_info": {"background_color": 0xFFE2B170, "border_radius": 10}, "Rectangle::hover_area_warning": {"background_color": 0xFF5EC7E8, "border_radius": 10}, "Label::text": {"font_size": 14, "color": 0xFF000000}, "Image::status_warning": {"image_url": Icons().get("warning"), "color": 0xFF000000}, "Image::status_info": {"image_url": Icons().get("info"), "color": 0xFF000000}, "Button:hovered": {"background_color": 0xFF9E9E9E}, } class Prompt: def __init__(self, notification_info: NotificationInfo): self._notification_info = notification_info self._build_ui( notification_info.text, notification_info.status, notification_info.button_infos ) self._docking_window_x = 0 self._docking_window_y = 0 self._docking_window_width = 0 self._docking_window_height = 0 self._hovered = False def destroy(self): self._notification_info = None self._window.destroy() self._window = None def __enter__(self): self._window.show() return self def __exit__(self, type, value, trace): self._window.hide() def show(self): self._window.visible = True def hide(self): self._window.visible = False @property def hovered(self): return self._hovered @property def visible(self): return self._window.visible @visible.setter def visible(self, value): self._window.visible = value @property def position_x(self): return self._window.position_x @position_x.setter def position_x(self, value): self._window.position_x = value @property def position_y(self): return self._window.position @position_y.setter def position_y(self, value): self._window.position_y = value @property def width(self): return self._window.width @property def height(self): return self._window.height async def docking_to(self, window_x, window_y, window_width, window_height, offset_y=0): self._docking_window_x = window_x self._docking_window_y = window_y self._docking_window_width = window_width self._docking_window_height = window_height self._window.visible = True # FIXME: No idea why this works. It needs to wait for the width/height to be stabalized. await omni.kit.app.get_app().next_update_async() position_x = self._docking_window_x + self._docking_window_width - self._window.width - 16 position_y = self._docking_window_y + self._docking_window_height - self._window.height - 16 - offset_y self._window.position_x = position_x if position_x > 0 else 0 self._window.position_y = position_y if position_y > 0 else 0 if self._notification_info.status == NotificationStatus.INFO: self._window.frame.set_style({"Window": {"background_color": 0xFF75542A, "border_radius": 10}}) else: self._window.frame.set_style({"Window": {"background_color": 0xFF2D5CA1, "border_radius": 10}}) self._layout.set_style(HOVER_AREA_DEFAULT_STYLE) def _build_ui(self, text, status, button_details): self._window = ui.Window(str(uuid.uuid1()), visible=False, height=0, dockPreference=ui.DockPreference.DISABLED) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_CLOSE | ui.WINDOW_FLAGS_NO_FOCUS_ON_APPEARING ) def _button_handler(handler): self.hide() if handler: handler() weak_self = weakref.ref(self) def _on_hovered(hovered): if not weak_self(): return weak_self()._hovered = hovered self._window.frame.style = HOVER_AREA_TRANSPARENT_STYLE with self._window.frame: self._layout = ui.ZStack(style=HOVER_AREA_DEFAULT_STYLE, height=0) with self._layout: if status == NotificationStatus.INFO: hover_area = ui.Rectangle(name="hover_area_info") else: hover_area = ui.Rectangle(name="hover_area_warning") hover_area.set_mouse_hovered_fn(_on_hovered) with ui.VStack(height=0): ui.Spacer(height=5) with ui.HStack(height=0): if status == NotificationStatus.INFO: name = "status_info" else: name = "status_warning" ui.Spacer(width=5) ui.Image(width=20, alignment=ui.Alignment.CENTER, name=name) ui.Spacer(width=10) ui.Label( text, name="text", word_wrap=True, width=self._window.width - 44, height=0, alignment=ui.Alignment.LEFT ) ui.Spacer() if button_details: button_width = 60 if len(button_details) >=3 else 120 ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer() button = ui.Button(button_details[0].text, width=button_width, height=0) button.set_clicked_fn(lambda a=button_details[0].handler: _button_handler(a)) for i in range(len(button_details) - 1): ui.Spacer(width=5) button_info = button_details[i + 1] button = ui.Button(button_info.text, width=button_width, height=0) button.set_clicked_fn(lambda a=button_info.handler: _button_handler(a)) ui.Spacer() ui.Spacer(height=5)
6,796
Python
36.346154
119
0.556651
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/tests/__init__.py
from .test_notification_manager import TestNotificationManagerUI
65
Python
31.999984
64
0.892308
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/tests/test_notification_manager.py
import asyncio import carb.settings import omni.kit.test import omni.ui as ui import omni.kit.notification_manager as nm from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from threading import Thread CURRENT_PATH = Path(__file__).parent.joinpath("../../../../data") class TestNotificationManagerUI(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") self._all_notifications = [] self._settings = carb.settings.get_settings() self._original_value = self._settings.get_as_int("/persistent/app/viewport/displayOptions") self._settings.set_int("/persistent/app/viewport/displayOptions", 0) # Create test area await self.create_test_area(1024, 1024) window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE self._test_window = ui.Window( "Viewport", dockPreference=ui.DockPreference.DISABLED, flags=window_flags, width=1024, height=1024, position_x=0, position_y=0, ) # Override default background self._test_window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}}) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._golden_img_dir = None for notification in self._all_notifications: notification.dismiss() self._all_notifications.clear() # Wait for 1s to make sure all notifications are disappeared. await asyncio.sleep(1) self._test_window = None self._settings.set_int("/persistent/app/viewport/displayOptions", self._original_value) await super().tearDown() async def _wait(self, frames=10): for i in range(frames): await omni.kit.app.get_app().next_update_async() async def test_create_multiple_notifications(self): self._all_notifications.append(nm.post_notification("test", duration=2)) self._all_notifications.append(nm.post_notification("test1", duration=2, status=nm.NotificationStatus.WARNING)) self._all_notifications.append(nm.post_notification("test2", duration=2)) await self._wait() await asyncio.sleep(1.0) # Wait 10 frames for notifications to show up. await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_create_multiple_notifications.png") async def test_auto_hide_notifications(self): self._all_notifications.append(nm.post_notification("test", duration=0.5)) await self._wait() # Watis for 2s for notification to hide await asyncio.sleep(2) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_auto_hide_notifications.png") async def test_multiple_auto_hide_notifications(self): self._all_notifications.append(nm.post_notification("test", duration=0.5)) self._all_notifications.append(nm.post_notification("test1", duration=0.5)) self._all_notifications.append(nm.post_notification("test2", duration=0.5)) await self._wait() # Watis for 2s for notification to hide await asyncio.sleep(2) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_multiple_auto_hide_notifications.png") async def test_create_non_auto_hide_notifications(self): self._all_notifications.append(nm.post_notification("test", duration=0.5, hide_after_timeout=False)) await self._wait() # Watis for 2s for notification and check if it's still shown. await asyncio.sleep(2) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_non_auto_hide_notifications.png") async def test_manual_hide_notifications(self): for i in range(100): self._all_notifications.append(nm.post_notification("test", duration=1)) # Wait and show await self._wait() await asyncio.sleep(2) # Dismiss them manually, after this, all notifications will be dismissed for n in self._all_notifications: n.dismiss() self._all_notifications.clear() # Creates another notification and shows it should work. self._all_notifications.append(nm.post_notification("test100", duration=10)) await self._wait() await asyncio.sleep(2) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_manual_hide_notifications.png") async def test_multithreads_post(self): def run(): nm.post_notification("test multiple threads") t = Thread(target=run) try: t.start() # 2s is enough to show notification await asyncio.sleep(2.0) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_multithreads_post.png") except: pass finally: t.join()
5,253
Python
41.032
130
0.655245
omniverse-code/kit/exts/omni.kit.welcome.learn/omni/kit/welcome/learn/style.py
from pathlib import Path import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") LEARN_PAGE_STYLE = {}
246
Python
21.454544
70
0.752033
omniverse-code/kit/exts/omni.kit.profile_python/omni/kit/profile_python/__init__.py
from .profile_python import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.profile_python/omni/kit/profile_python/profile_python.py
"""Enable automatic profiling of the python code using sys.profile.""" import sys import omni.kit.app import omni.ext import carb import carb.profiler import carb.dictionary import carb.settings _profiler_enabled = False _profile_zone_counter = 0 _python_stack_level = 0 MAX_STACK_LEVEL = 10 EXT_SETTINGS_SECTION = "/exts/omni.kit.profile_python" def set_profiler_enabled(value: bool): global _profile_zone_counter global _python_stack_level global _profiler_enabled global MAX_STACK_LEVEL if value == _profiler_enabled: return MAX_STACK_LEVEL = carb.settings.get_settings().get(EXT_SETTINGS_SECTION + "/maxStackLevel") if value: def profile_calls(frame, event, arg): global _profile_zone_counter global _python_stack_level if event == "call": _python_stack_level += 1 if _python_stack_level > MAX_STACK_LEVEL: return co = frame.f_code filename = co.co_filename if filename[-25:] == r"carb\profiler\__init__.py" or filename[-25:] == "carb/profiler/__init__.py": # Do not profile profiler events return func_name = co.co_name line_no = frame.f_lineno carb.profiler.begin_with_location(1, "Py::" + func_name, func_name, filename, line_no) _profile_zone_counter += 1 return profile_calls elif event == "return": _python_stack_level -= 1 if _python_stack_level >= MAX_STACK_LEVEL: return if _profile_zone_counter == 0: return carb.profiler.end(1) _profile_zone_counter -= 1 return profile_calls _profile_zone_counter = 0 sys.setprofile(profile_calls) else: while _profile_zone_counter > 0: carb.profiler.end(1) _profile_zone_counter -= 1 sys.setprofile(None) _profiler_enabled = value class ProfilePython(omni.ext.IExt): def _on_enable_change(self, item: carb.dictionary.Item, change_event_type: carb.settings.ChangeEventType): self._enabled = self._settings.get(EXT_SETTINGS_SECTION + "/enable") set_profiler_enabled(self._enabled) def on_startup(self): self._dictionary = carb.dictionary.acquire_dictionary_interface() self._settings = carb.settings.get_settings() self._change_subs = self._settings.subscribe_to_node_change_events( EXT_SETTINGS_SECTION + "/enable", self._on_enable_change ) self._enabled = self._settings.get(EXT_SETTINGS_SECTION + "/enable") set_profiler_enabled(self._enabled) def on_shutdown(self): self._settings.unsubscribe_to_change_events(self._change_subs) self._enabled = False set_profiler_enabled(self._enabled) self._change_subs = None self._settings = None self._dictionary = None
3,081
Python
30.131313
115
0.590393
omniverse-code/kit/exts/omni.kit.profile_python/omni/kit/profile_python/tests/__init__.py
from .test_profile_python import *
35
Python
16.999992
34
0.771429
omniverse-code/kit/exts/omni.kit.profile_python/omni/kit/profile_python/tests/test_profile_python.py
import omni.kit.test import gzip import json import os from omni.kit.core.tests import KitLaunchTest PYTHON_EVENT_PREFIX = "Py::" class TestProfilePython(KitLaunchTest): async def test_profile_python(self): FUNC_1 = "some_rare_magical_function_27026930" FUNC_2 = "another_rare_magical_function_120941920" # Call some functions script = f""" def {FUNC_2}(): pass def {FUNC_1}(): {FUNC_2}() {FUNC_1}() """ args = [ # "--/app/quitAfter=10" "--enable", "omni.kit.profile_python", ] trace_file = f"{self._temp_folder}/trace.gz" args += [ "--/plugins/carb.profiler-cpu.plugin/saveProfile=1", "--/plugins/carb.profiler-cpu.plugin/compressProfile=1", "--/app/profileFromStart=1", f"--/plugins/carb.profiler-cpu.plugin/filePath='{trace_file}'", ] # run kit with python profiler and this script await self._run_kit_with_script(script, args=args) self.assertTrue(os.path.exists(trace_file)) # Parse trace and check that they have those functions at least mentioned there events = set() with gzip.open(trace_file, 'rb') as f_in: j = json.loads(f_in.read().decode("utf-8") ) for entry in j: name = entry["name"] if name.startswith(PYTHON_EVENT_PREFIX): events.add(name) self.assertTrue(PYTHON_EVENT_PREFIX + FUNC_1 in events) self.assertTrue(PYTHON_EVENT_PREFIX + FUNC_2 in events)
1,600
Python
26.135593
87
0.5775
omniverse-code/kit/exts/omni.kit.collaboration.telemetry/omni/kit/collaboration/telemetry/__init__.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. """ Provides access to a bindings module to simplify emitting telemetry events for the 'omni.kit.collaboration.*' extensions. """ import omni.core # pragma: no cover from ._telemetry import * # pragma: no cover
658
Python
42.93333
86
0.767477
omniverse-code/kit/exts/omni.kit.collaboration.telemetry/omni/kit/collaboration/telemetry/tests/test_telemetry.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 omni.kit.test import omni.kit.test.teamcity import omni.structuredlog import carb.settings import tempfile import pathlib import time import io import os import sys import json import datetime import psutil import carb import carb.tokens import omni.kit.collaboration.telemetry class TestCollaborationTelemetry(omni.kit.test.AsyncTestCase): # pragma: no cover def setUp(self): self._structured_log_settings = omni.structuredlog.IStructuredLogSettings() self._control = omni.structuredlog.IStructuredLogControl() self._settings = carb.settings.get_settings_interface() self.assertIsNotNone(self._control) self.assertIsNotNone(self._settings) self.assertIsNotNone(self._structured_log_settings) # failed to retrieve the IStructuredLogSettings object => fail if self._structured_log_settings == None or self._control == None or self._settings == None: return # make sure to flush the structured log queue now since we're going to be changing the # log output path and default log name for this test. This will ensure that any pending # events are flushed to their appropriate log files first. self._control.stop() # set the log directory and name. self._temp_dir = tempfile.TemporaryDirectory() self._log_file_name = "omni.kit.collaboration.test.log" self._old_log_name = self._structured_log_settings.log_default_name self._old_log_path = self._structured_log_settings.log_output_path self._structured_log_settings.log_default_name = self._log_file_name self._structured_log_settings.log_output_path = self._temp_dir.name # piece together the expected name of the log file we'll be watching. self._log_path = pathlib.Path(self._temp_dir.name).joinpath(self._log_file_name) self.assertEqual(pathlib.Path(self._structured_log_settings.log_default_name), self._log_path) self.assertEqual(pathlib.Path(self._structured_log_settings.log_output_path), pathlib.Path(self._temp_dir.name)) def tearDown(self): # nothing to clean up => fail. if self._structured_log_settings == None: return; self._structured_log_settings.log_output_path = self._old_log_path self._structured_log_settings.log_default_name = self._old_log_name # explicitly clean up the temporary dir. Note that we need to explicitly clean it up # since it can throw an exception on Windows if a file or folder is still locked. The # support for internally ignoring these exceptions isn't added until `tempfile` v3.10 # and we're using an older version of the package here. try: self._temp_dir.cleanup() except: pass # explicitly clean up all of our objects so we're not relying on the python GC. self._structured_log_settings = None self._control = None self._settings = None self._temp_dir = None self._log_file_name = None self._old_log_name = None self._old_log_path = None self._log_path = None def _read_log_lines(self, filename, expected_types, session = None, time_delta = -1, log_time_range = 900): """ Reads the events from the expected log file location. Each log message line is parsed as a JSON blob. The 'data' property of each message is parsed into a dictionary and a list of these parsed dictionaries are returned. The log's header JSON object will also be parsed and verified. The verification includes checking that the log's creation timestamp is recent. Parameters: filename: The name of the log file to process for events. This may not be `None`. expected_types: A list of event type names that are to be expected in the log file. If an event is found that does not match one of the events in this list, a test will fail. session: An optional session ID string to match to each event. An event will only be included in the output if its session ID matches this one. This may be `None` or "0" to ignore the session ID matching. If this is set to "0", the session ID from each event will be added to each event in the output list so that further filtering can occur. time_delta: An optional time delta in seconds used to further filter events from the log file. Only events that were logged after a point that is this many seconds earlier than the call time will be included in the output. This may be negative to disable filtering out older events. log_time_range: The maximum number of seconds old that the log's creation timestamp in its header may be. This test may be disabled by settings this value to 0. If non-zero, this should be set to an absurd range versus the ideal case so that running on slow machines doesn't cause this test to unexpectedly fail. This defaults to 900s (15m). Returns: A list of parsed events. Each event in the list will be a dictionary of the properties parsed from that event's 'data' property. Note that each returned event in this list will have had its 'type' and 'session' properties copied into it under the property names 'cloudEventsEventType' and 'cloudEventsSessionId'. These can be used by the caller to further filter and categorize the events. """ if not os.path.isfile(filename): print("failed to find the log file '" + str(filename) + "'.") return [] events = [] lines = [] header = {} with open(filename, "r") as f: lines = f.readlines() if time_delta >= 0: timestamp = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds = time_delta) # walk through all the lines in the file except the first one (the log header). for i in range(1, len(lines)): line = lines[i] try: event = json.loads(line) self.assertTrue(event["type"] in expected_types) msg_time = datetime.datetime.strptime(event["time"], "%Y-%m-%dT%H:%M:%S.%f%z") # always add the 'type' and 'session' properties to the output event. Since the # "type" and "session" property names are rather generic and could legitimately # be part of the "data" property, we'll rename them to something less generic # that the caller can consume. event["data"]["cloudEventsEventType"] = event["type"] event["data"]["cloudEventsSessionId"] = event["session"] if (session == None or session == "0" or event["session"] == session) and (time_delta < 0 or msg_time >= timestamp): events.append(event["data"]) except json.decoder.JSONDecodeError as e: print("failed to parse the line '" + line + "' as JSON {reason = '" + str(e) + "'}") pass except Exception as e: print("error processing the line '" + line + "' as JSON {error = '" + str(e) + "'}") raise # ****** parse and verify the header line ****** try: header = json.loads(lines[0]) except json.decoder.JSONDecodeError as e: print("failed to parse the header '" + lines[0] + "' as JSON {reason = '" + str(e) + "'}") self.assertFalse(True) except Exception as e: print("error processing the header '" + lines[0] + "' as JSON {error = '" + str(e) + "'}") self.assertFalse(True) self.assertEqual(header["source"], "omni.structuredlog") self.assertIsNotNone(header["version"]) # make sure the log was created recently. if log_time_range > 0: timestamp = datetime.datetime.strptime(header["time"], "%Y-%m-%dT%H:%M:%S.%f%z") time_diff = datetime.datetime.now(datetime.timezone.utc) - timestamp self.assertLess(time_diff.total_seconds(), log_time_range) return events def _is_event_present(self, events, properties): """ Verifies that all keys in `properties` both exist and have the same values in a single event in `events`. Parameters: events: The set of events that were read from the log file. These are expected to have been parsed into dictionary objects from the original JSON 'data' property of each event. properties: The set of properties to verify are present and match at least one of the events in the log. All properties must match to a single event in order for this to succeed. Returns: `True` if all the requested keys match in a single event. `False` if no event containing all properties is found. """ # go through each event in the log file and check if it has all the required properties. for i in range(len(events)): event = events[i] matches = True # go through each of the required properties and verify they are all present and # have the expected value. for key, value in properties.items(): if not key in event: continue if event[key] != value: matches = False break if matches: return True return False def test_live_edit_events(self): """ Tests sending Schema_omni_kit_collaboration_1_0 events. Note that since this extension is purely a bindings module, no coverage information will be generated unfortunately. This does however test the functionality of the bindings module. """ # get the schema object and create the data object that is required to send the event. self._telemetry = omni.kit.collaboration.telemetry.Schema_omni_kit_collaboration_1_0() event = omni.kit.collaboration.telemetry.Struct_liveEdit_liveEdit() self.assertIsNotNone(self._telemetry) self.assertIsNotNone(event) # send some test events. event.id = "purple monkey dishwasher" event.action = "join" self._telemetry.liveEdit_sendEvent("fudgesicle", event) event.id = "spatula lampshade" event.action = "leave" self._telemetry.liveEdit_sendEvent("peanut butter parfait", event) # make sure all the messages are flushed to disk. self._control.stop() # read the log and verify that all the expected messages are present. events = self._read_log_lines(self._log_path, [ "com.nvidia.omni.kit.collaboration.liveEdit", ]) # verify the ordered parameters events. self.assertTrue(self._is_event_present(events, {"cloud_link_id" : "fudgesicle", "event" : { "id": "purple monkey dishwasher", "action": "join"}, "event": "live-edit"})) self.assertTrue(self._is_event_present(events, {"cloud_link_id" : "peanut butter parfait", "event" : { "id": "spatula lampshade", "action": "leave"}, "event": "live-edit"})) # clean up. self._telemetry = None event = None
12,372
Python
46.588461
181
0.613644
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/__init__.py
"""Initialization for the OmniGraph UI extension""" # Required for proper resolution of ONI wrappers import omni.core from ._impl.compute_node_widget import ComputeNodeWidget from ._impl.extension import _PublicExtension from ._impl.graph_variable_custom_layout import GraphVariableCustomLayout from ._impl.menu import add_create_menu_type, remove_create_menu_type from ._impl.omnigraph_attribute_base import OmniGraphBase from ._impl.omnigraph_attribute_builder import OmniGraphPropertiesWidgetBuilder from ._impl.omnigraph_attribute_models import OmniGraphAttributeModel, OmniGraphTfTokenAttributeModel from ._impl.omnigraph_prim_node_templates import ( PrimAttributeCustomLayoutBase, PrimPathCustomLayoutBase, ReadPrimsCustomLayoutBase, ) from ._impl.omnigraph_random_node_templates import RandomNodeCustomLayoutBase from ._impl.omnigraph_settings_editor import SETTING_PAGE_NAME from ._impl.utils import build_port_type_convert_menu, find_prop __all__ = [ "add_create_menu_type", "build_port_type_convert_menu", "ComputeNodeWidget", "find_prop", "GraphVariableCustomLayout", "OmniGraphAttributeModel", "OmniGraphBase", "OmniGraphPropertiesWidgetBuilder", "OmniGraphTfTokenAttributeModel", "PrimAttributeCustomLayoutBase", "PrimPathCustomLayoutBase", "RandomNodeCustomLayoutBase", "ReadPrimsCustomLayoutBase", "remove_create_menu_type", "SETTING_PAGE_NAME", ]
1,437
Python
36.842104
101
0.78636
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnViewportHoveredDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnViewportHovered Event node which fires when the specified viewport is hovered over. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnViewportHoveredDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnViewportHovered Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.onlyPlayback inputs.viewport Outputs: outputs.began outputs.ended """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for hover events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:began', 'execution', 0, 'Began', 'Enabled when the hover begins', {}, True, None, False, ''), ('outputs:ended', 'execution', 0, 'Ended', 'Enabled when the hover ends', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.began = og.Database.ROLE_EXECUTION role_data.outputs.ended = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"onlyPlayback", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.onlyPlayback, self._attributes.viewport] self._batchedReadValues = [True, "Viewport"] @property def onlyPlayback(self): return self._batchedReadValues[0] @onlyPlayback.setter def onlyPlayback(self, value): self._batchedReadValues[0] = value @property def viewport(self): return self._batchedReadValues[1] @viewport.setter def viewport(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"began", "ended", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def began(self): value = self._batchedWriteValues.get(self._attributes.began) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.began) return data_view.get() @began.setter def began(self, value): self._batchedWriteValues[self._attributes.began] = value @property def ended(self): value = self._batchedWriteValues.get(self._attributes.ended) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.ended) return data_view.get() @ended.setter def ended(self, value): self._batchedWriteValues[self._attributes.ended] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnViewportHoveredDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportHoveredDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportHoveredDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
7,465
Python
48.443708
231
0.644072
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadPickStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadPickState Read the state of the last picking event from the specified viewport. Note that picking events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import carb import numpy class OgnReadPickStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadPickState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.trackedPrimPaths inputs.trackedPrims inputs.usePaths inputs.viewport Outputs: outputs.isTrackedPrimPicked outputs.isValid outputs.pickedPrimPath outputs.pickedWorldPos Predefined Tokens: tokens.LeftMouseClick tokens.RightMouseClick tokens.MiddleMouseClick tokens.LeftMousePress tokens.RightMousePress tokens.MiddleMousePress """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger a picking event', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Click,Right Mouse Click,Middle Mouse Click,Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseClick": "Left Mouse Click", "RightMouseClick": "Right Mouse Click", "MiddleMouseClick": "Middle Mouse Click", "LeftMousePress": "Left Mouse Press", "RightMousePress": "Right Mouse Press", "MiddleMousePress": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Click"'}, True, 'Left Mouse Click', False, ''), ('inputs:trackedPrimPaths', 'token[]', 0, 'Tracked Prim Paths', "Optionally specify a set of prims (by paths) to track whether or not they got picked\n(only affects the value of 'Is Tracked Prim Picked')", {}, False, None, False, ''), ('inputs:trackedPrims', 'bundle', 0, 'Tracked Prims', "Optionally specify a set of prims to track whether or not they got picked\n(only affects the value of 'Is Tracked Prim Picked')", {}, False, None, False, ''), ('inputs:usePaths', 'bool', 0, 'Use Paths', "When true, 'Tracked Prim Paths' is used, otherwise 'Tracked Prims' is used", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for picking events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:isTrackedPrimPicked', 'bool', 0, 'Is Tracked Prim Picked', 'True if a tracked prim got picked in the last picking event,\nor if any prim got picked if no tracked prims are specified', {}, True, None, False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:pickedPrimPath', 'token', 0, 'Picked Prim Path', 'The path of the prim picked in the last picking event, or an empty string if nothing got picked', {}, True, None, False, ''), ('outputs:pickedWorldPos', 'point3d', 0, 'Picked World Position', 'The XYZ-coordinates of the point in world space at which the prim got picked,\nor (0,0,0) if nothing got picked', {}, True, None, False, ''), ]) class tokens: LeftMouseClick = "Left Mouse Click" RightMouseClick = "Right Mouse Click" MiddleMouseClick = "Middle Mouse Click" LeftMousePress = "Left Mouse Press" RightMousePress = "Right Mouse Press" MiddleMousePress = "Middle Mouse Press" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.trackedPrims = og.Database.ROLE_BUNDLE role_data.outputs.pickedWorldPos = og.Database.ROLE_POINT return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "usePaths", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.usePaths, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Click", False, "Viewport"] @property def trackedPrimPaths(self): data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) return data_view.get() @trackedPrimPaths.setter def trackedPrimPaths(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.trackedPrimPaths) data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) data_view.set(value) self.trackedPrimPaths_size = data_view.get_array_size() @property def trackedPrims(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.trackedPrims""" return self.__bundles.trackedPrims @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def usePaths(self): return self._batchedReadValues[1] @usePaths.setter def usePaths(self, value): self._batchedReadValues[1] = value @property def viewport(self): return self._batchedReadValues[2] @viewport.setter def viewport(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isTrackedPrimPicked", "isValid", "pickedPrimPath", "pickedWorldPos", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isTrackedPrimPicked(self): value = self._batchedWriteValues.get(self._attributes.isTrackedPrimPicked) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) return data_view.get() @isTrackedPrimPicked.setter def isTrackedPrimPicked(self, value): self._batchedWriteValues[self._attributes.isTrackedPrimPicked] = value @property def isValid(self): value = self._batchedWriteValues.get(self._attributes.isValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): self._batchedWriteValues[self._attributes.isValid] = value @property def pickedPrimPath(self): value = self._batchedWriteValues.get(self._attributes.pickedPrimPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) return data_view.get() @pickedPrimPath.setter def pickedPrimPath(self, value): self._batchedWriteValues[self._attributes.pickedPrimPath] = value @property def pickedWorldPos(self): value = self._batchedWriteValues.get(self._attributes.pickedWorldPos) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) return data_view.get() @pickedWorldPos.setter def pickedWorldPos(self, value): self._batchedWriteValues[self._attributes.pickedWorldPos] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadPickStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadPickStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadPickStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,988
Python
50.900433
640
0.650567
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnSetViewportMode.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.ui.ogn.OgnSetViewportModeDatabase import OgnSetViewportModeDatabase test_file_name = "OgnSetViewportModeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_ui_SetViewportMode") database = OgnSetViewportModeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:enablePicking")) attribute = test_node.get_attribute("inputs:enablePicking") db_value = database.inputs.enablePicking expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:enableViewportMouseEvents")) attribute = test_node.get_attribute("inputs:enableViewportMouseEvents") db_value = database.inputs.enableViewportMouseEvents expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:execIn")) attribute = test_node.get_attribute("inputs:execIn") db_value = database.inputs.execIn self.assertTrue(test_node.get_attribute_exists("inputs:mode")) attribute = test_node.get_attribute("inputs:mode") db_value = database.inputs.mode expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:viewport")) attribute = test_node.get_attribute("inputs:viewport") db_value = database.inputs.viewport expected_value = "Viewport" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:defaultMode")) attribute = test_node.get_attribute("outputs:defaultMode") db_value = database.outputs.defaultMode self.assertTrue(test_node.get_attribute_exists("outputs:scriptedMode")) attribute = test_node.get_attribute("outputs:scriptedMode") db_value = database.outputs.scriptedMode self.assertTrue(test_node.get_attribute_exists("outputs:widgetPath")) attribute = test_node.get_attribute("outputs:widgetPath") db_value = database.outputs.widgetPath
3,783
Python
49.453333
92
0.690722
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/metaclass.py
""" Management for a singleton metaclass """ import inspect import pprint from gc import get_referrers import omni.graph.tools as ogt # Unique constant that goes in the module's dictionary so that it can be filtered out __SINGLETON_MODULE = True class Singleton(type): """ Helper for defining a singleton class in Python. You define it by starting your class as follows: from Singleton import Singleton class MyClass(metaclass=Singleton): # rest of implementation Then you can do things like this: a = MyClass() a.var = 12 b = MyClass() assert b.var == 12 assert a == b """ _instances = {} def __call__(cls, *args, **kwargs): """Construct the unique instance of the class if necessary, otherwise return the existing one""" if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] @staticmethod def forget(instanced_cls): """Removes the singleton class from the list of allocated singletons""" try: # Caller will usually be the class's destroy() function, invoker has a reference to the object # on which the destroy function is being called (which it will presumably remove after calling) (caller, invoker) = inspect.stack()[1:3] # noqa: PLW0632 referrers = [] # Filter our the class's reference to itself as that is about to be destroyed for referrer in get_referrers(instanced_cls._instances[instanced_cls]): # noqa: PLW0212 try: if referrer.f_back not in (caller.frame, invoker.frame): referrers.append(referrer.f_back) except AttributeError: if isinstance(referrer, dict): if instanced_cls in referrer: continue if "__SINGLETON_MODULE" in referrer: continue referrers.append(referrer) if referrers: referrers = pprint.PrettyPrinter(indent=4).pformat(referrers) ogt.dbg_gc(f"Singleton {instanced_cls.__name__} has dangling references {referrers}") else: ogt.dbg_gc(f"Singleton {instanced_cls.__name__} cleanly forgotten") del instanced_cls._instances[instanced_cls] # noqa: PLW0212 except (AttributeError, KeyError) as error: ogt.dbg_gc(f"Failed trying to destroy singleton type {instanced_cls} - {error}")
2,631
Python
37.705882
107
0.595971
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/stage_picker_dialog.py
import weakref from functools import partial from typing import Callable import omni.ui as ui from omni.kit.property.usd.relationship import SelectionWatch from omni.kit.widget.stage import StageWidget from pxr import Sdf, Usd class StagePickerDialog: def __init__( self, stage, on_select_fn: Callable[[Usd.Prim], None], title=None, select_button_text=None, filter_type_list=None, filter_lambda=None, ): self._weak_stage = weakref.ref(stage) self._on_select_fn = on_select_fn if filter_type_list is None: self._filter_type_list = [] else: self._filter_type_list = filter_type_list self._filter_lambda = filter_lambda self._selected_paths = [] def on_window_visibility_changed(visible): if not visible: self._stage_widget.open_stage(None) else: # Only attach the stage when picker is open. Otherwise the Tf notice listener in StageWidget kills perf self._stage_widget.open_stage(self._weak_stage()) self._window = ui.Window( title if title else "Select Prim", width=600, height=400, visible=False, flags=0, visibility_changed_fn=on_window_visibility_changed, ) with self._window.frame: with ui.VStack(): with ui.Frame(): self._stage_widget = StageWidget(None, columns_enabled=["Type"]) self._selection_watch = SelectionWatch( stage=stage, on_selection_changed_fn=self._on_selection_changed, filter_type_list=filter_type_list, filter_lambda=filter_lambda, ) self._stage_widget.set_selection_watch(self._selection_watch) def on_select(weak_self): weak_self = weak_self() if not weak_self: return selected_prim = None if len(weak_self._selected_paths) > 0: # noqa: PLW0212 selected_prim = stage.GetPrimAtPath(Sdf.Path(weak_self._selected_paths[0])) # noqa: PLW0212 if weak_self._on_select_fn: # noqa: PLW0212 weak_self._on_select_fn(selected_prim) # noqa: PLW0212 weak_self._window.visible = False # noqa: PLW0212 with ui.VStack(height=0, style={"Button.Label:disabled": {"color": 0xFF606060}}): self._label = ui.Label("Selected Path(s):\n\tNone") self._button = ui.Button( select_button_text if select_button_text else "Select", height=10, clicked_fn=partial(on_select, weak_self=weakref.ref(self)), enabled=False, ) def clean(self): self._window.set_visibility_changed_fn(None) self._window.destroy() self._window = None self._selection_watch = None self._stage_widget.open_stage(None) self._stage_widget.destroy() self._stage_widget = None self._filter_type_list = None self._filter_lambda = None self._selected_paths = None self._on_select_fn = None self._weak_stage = None self._label.destroy() self._label = None self._button.destroy() self._button = None def show(self): self._selection_watch.reset(1) self._window.visible = True if self._filter_lambda is not None: self._stage_widget._filter_by_lambda({"relpicker_filter": self._filter_lambda}, True) # noqa: PLW0212 if self._filter_type_list: self._stage_widget._filter_by_type(self._filter_type_list, True) # noqa: PLW0212 self._stage_widget.update_filter_menu_state(self._filter_type_list) def hide(self): self._window.visible = False def _on_selection_changed(self, paths): self._selected_paths = paths if self._button: self._button.enabled = len(self._selected_paths) > 0 if self._label: text = "\n\t".join(self._selected_paths) label_text = "Selected Path" label_text += f":\n\t{text if text else 'None'}" self._label.text = label_text
4,519
Python
36.355372
119
0.545917
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_attribute_base.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 json import weakref from typing import Any, Dict, List, Optional, Set, Tuple, Union import carb import carb.settings import omni.graph.core as og import omni.graph.tools.ogn as ogn import omni.kit from omni.kit.property.usd.control_state_manager import ControlStateManager from omni.kit.property.usd.placeholder_attribute import PlaceholderAttribute from pxr import Sdf, Usd def get_ui_style(): return carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" def get_model_cls(cls, args, key="model_cls"): if args: return args.get(key, cls) return cls AUTO_REFRESH_PERIOD = 0.33 # How frequently to poll for held node compute for refresh BIG_ARRAY_MIN = 17 # The minimum number of elements to be considered a big-array PLAY_COMPUTEGRAPH_SETTING = "/app/player/playComputegraph" # ============================================================================= class PlaceholderOmniGraphAttribute: """Standin when a held Node does not have the given Attribute""" def __init__(self, name: str, node: str): self._name = name self._node = node HELD_ATTRIB = Union[og.Attribute, PlaceholderOmniGraphAttribute] # ============================================================================= class OmniGraphBase: """Mixin base for OmniGraph attribute models""" # Static refresh callback - shared among all instances _update_sub = None _update_counter: float = 0 _instances = weakref.WeakSet() # Set of all OmniGraphBase instances, for update polling _compute_counts: Dict[str, int] = {} # Keep track of last compute count for each node by path. # FIXME: Would be nicer to have an Attribute.get_change_num() to know if it # has actually changed, rather than just if the node computed. @staticmethod def _on_update(event): """Called by kit update event - refreshes OG-based attribute models at a fixed interval.""" # FIXME: In an action graph is probably more efficient to listen for a compute event instead of polling. # likewise in a push graph we should just refresh every N frames. OmniGraphBase._update_counter += event.payload["dt"] # noqa: PLR1702 if OmniGraphBase._update_counter > AUTO_REFRESH_PERIOD: # noqa: PLR1702 OmniGraphBase._update_counter = 0 # If we find one of our nodes has computed since the last check we want to dirty all output and connected # inputs attribute bases dirty_nodes: Set[int] = set() dirty_bases: Set[OmniGraphBase] = set() for base in OmniGraphBase._instances: for attrib in base._get_og_attributes(): # noqa: PLW0212 if isinstance(attrib, og.Attribute): port_type = attrib.get_port_type() if (port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) and ( attrib.get_upstream_connection_count() == 0 ): # Special case - unconnected inputs don't ever have to be polled because they only # change when set externally continue # Check if this attribute's node was computed since last update. If so mark it as dirty so # that we don't have to do the check again in this pass. node = attrib.get_node() node_hash = hash(node) want_dirty = node_hash in dirty_nodes if not want_dirty: node_path = node.get_prim_path() cc = node.get_compute_count() cached_cc = OmniGraphBase._compute_counts.get(node_path, -1) if cached_cc != cc: OmniGraphBase._compute_counts[node_path] = cc dirty_nodes.add(node_hash) want_dirty = True if want_dirty and (base not in dirty_bases): dirty_bases.add(base) for base in dirty_bases: base._set_dirty() # noqa: PLW0212 def __init__( self, stage: Usd.Stage, object_paths: List[Sdf.Path], self_refresh: bool, metadata: dict = None, change_on_edit_end=False, **kwargs, ): self._control_state_mgr = ControlStateManager.get_instance() self._stage = stage self._object_paths = object_paths self._object_paths_set = set(object_paths) self._metadata = metadata if metadata is not None else {} self._change_on_edit_end = change_on_edit_end self._dirty = True self._value = None # The value to be displayed on widget self._has_default_value = False self._default_value = None self._real_values = [] # The actual values in usd, might be different from self._value if ambiguous. self._real_type: og.Type = None self._connections = [] self._is_big_array = False self._prev_value = None self._prev_real_values = [] self._editing = 0 self._ignore_notice = False self._ambiguous = False self._comp_ambiguous = [] self._might_be_time_varying = False # Inaccurate named. It really means if timesamples > 0 self._soft_range_min = None self._soft_range_max = None # get soft_range userdata settings # FIXME: We need an OG equivalent # attributes = self._get_attributes() # if attributes: # attribute = attributes[-1] # if isinstance(attribute, Usd.Attribute): # soft_range = attribute.GetCustomDataByKey("omni:kit:property:usd:soft_range_ui") # if soft_range: # self._soft_range_min = soft_range[0] # self._soft_range_max = soft_range[1] # Hard range for the value. For vector type, range value is a float/int that compares against each component self._min = kwargs.get("min", None) self._max = kwargs.get("max", None) # Override with node-specified # FIXME: minimum/maximum metadata isn't processed # for attrib in self._get_og_attributes(): # if isinstance(attrib, og.Attribute): # self._max = attrib.get_metadata(ogn.MetaDataKeys.MAXIMUM) # self._min = attrib.get_metadata(ogn.MetaDataKeys.MINIMUM) # break # Invalid range if self._min is not None and self._max is not None and self._min >= self._max: self._min = self._max = None # The state of the icon on the right side of the line with widgets self._control_state = 0 # Callback when the control state is changing. We use it to redraw UI self._on_control_state_changed_fn = None # Callback when the value is reset. We use it to redraw UI self._on_set_default_fn = None # True if the attribute has the default value and the current value is not default self._different_from_default: bool = False # Per component different from default self._comp_different_from_default: List[bool] = [] # We want to keep updating when OG is evaluating self._last_compute_count = 0 settings = carb.settings.get_settings() if settings.get(PLAY_COMPUTEGRAPH_SETTING): OmniGraphBase._instances.add(self) if len(OmniGraphBase._instances) == 1 and (OmniGraphBase._update_sub is None): OmniGraphBase._update_sub = ( omni.kit.app.get_app() .get_update_event_stream() .create_subscription_to_pop(OmniGraphBase._on_update, name="OG prop-panel ui update") ) @property def control_state(self): """Returns the current control state, it's the icon on the right side of the line with widgets""" return self._control_state @property def stage(self): return self._stage def update_control_state(self): control_state, force_refresh = self._control_state_mgr.update_control_state(self) # Redraw control state icon when the control state is changed if self._control_state != control_state or force_refresh: self._control_state = control_state if self._on_control_state_changed_fn: self._on_control_state_changed_fn() def set_on_control_state_changed_fn(self, fn): """Callback that is called when control state is changed""" self._on_control_state_changed_fn = fn def set_on_set_default_fn(self, fn): """Callback that is called when value is reset""" self._on_set_default_fn = fn def clean(self): self._stage = None OmniGraphBase._instances.discard(self) if not OmniGraphBase._instances: OmniGraphBase._update_sub = None # unsubscribe from app update stream OmniGraphBase._compute_counts.clear() @carb.profiler.profile def _get_default_value(self, attrib: HELD_ATTRIB) -> Tuple[bool, Any]: if isinstance(attrib, og.Attribute): default_str = attrib.get_metadata(ogn.MetadataKeys.DEFAULT) og_tp = attrib.get_resolved_type() if default_str is not None: py_val = json.loads(default_str) val = og.python_value_as_usd(og_tp, py_val) return True, val # If we still don't find default value, use type's default value val_base = 0 if og_tp.array_depth > 0: # Special case string, path vs uchar[] if (og_tp.base_type == og.BaseDataType.UCHAR) and ( og_tp.role in [og.AttributeRole.TEXT, og.AttributeRole.PATH] ): val_base = "" else: return True, [] elif og_tp.base_type == og.BaseDataType.BOOL: val_base = False elif og_tp.base_type == og.BaseDataType.TOKEN: val_base = "" py_val = val_base if og_tp.tuple_count > 1: if og_tp.role in [og.AttributeRole.FRAME, og.AttributeRole.MATRIX, og.AttributeRole.TRANSFORM]: dim = 2 if og_tp.tuple_count == 4 else 3 if og_tp.tuple_count == 9 else 4 py_val = [[1 if i == j else 0 for j in range(dim)] for i in range(dim)] else: py_val = [val_base] * og_tp.tuple_count val = og.python_value_as_usd(og_tp, py_val) return True, val return False, None def is_different_from_default(self): """Returns True if the attribute has the default value and the current value is not default""" self._update_value() # soft_range has been overridden if self._soft_range_min is not None and self._soft_range_max is not None: return True return self._different_from_default def might_be_time_varying(self): self._update_value() return self._might_be_time_varying def is_ambiguous(self): self._update_value() return self._ambiguous def is_comp_ambiguous(self, index: int): self._update_value() comp_len = len(self._comp_ambiguous) if comp_len == 0 or index < 0: return self.is_ambiguous() if index < comp_len: return self._comp_ambiguous[index] return False def get_value_by_comp(self, comp: int): self._update_value() if comp == -1: return self._value return self._get_value_by_comp(self._value, comp) def _save_real_values_as_prev(self): # It's like copy.deepcopy but not all USD types support pickling (e.g. Gf.Quat*) self._prev_real_values = [type(value)(value) for value in self._real_values] def _get_value_by_comp(self, value, comp: int): if value.__class__.__module__ == "pxr.Gf": if value.__class__.__name__.startswith("Quat"): if comp == 0: return value.real return value.imaginary[comp - 1] if value.__class__.__name__.startswith("Matrix"): dimension = len(value) row = comp // dimension col = comp % dimension # noqa: S001 return value[row, col] if value.__class__.__name__.startswith("Vec"): return value[comp] else: return value[comp] return None def _update_value_by_comp(self, value, comp: int): if self._value.__class__.__module__ == "pxr.Gf": if self._value.__class__.__name__.startswith("Quat"): if comp == 0: value.real = self._value.real else: imaginary = self._value.imaginary imaginary[comp - 1] = self._value.imaginary[comp - 1] value.SetImaginary(imaginary) elif self._value.__class__.__name__.startswith("Matrix"): dimension = len(self._value) row = comp // dimension col = comp % dimension # noqa: S001 value[row, col] = self._value[row, col] elif self._value.__class__.__name__.startswith("Vec"): value[comp] = self._value[comp] else: value[comp] = self._value[comp] return value def _compare_value_by_comp(self, val1, val2, comp: int): return self._get_value_by_comp(val1, comp) == self._get_value_by_comp(val2, comp) def _get_comp_num(self): """Returns the number of components in the value type""" if self._real_type: # For OG scalers have tuple_count == 1, but here we expect 0 return self._real_type.tuple_count if self._real_type.tuple_count > 1 else 0 return 0 def _on_dirty(self): pass def _set_dirty(self): if self._editing > 0: return self._dirty = True self._on_dirty() def _get_type_name(self, obj: Usd.Object): if hasattr(obj, "GetTypeName"): return obj.GetTypeName() if hasattr(obj, "typeName"): return obj.typeName return None def _is_array_type(self, obj: HELD_ATTRIB): if isinstance(obj, og.Attribute): attr_type = obj.get_resolved_type() is_array_type = attr_type.array_depth > 0 and attr_type.role not in [ og.AttributeRole.TEXT, og.AttributeRole.PATH, ] return is_array_type return False def _get_resolved_attribute_path(self, attribute: og.Attribute) -> str: """Return the path to the given attribute, considering resolved extended attributes""" return f"{attribute.get_node().get_prim_path()}.{og.Attribute.resolved_prefix}{attribute.get_name()}" def get_attribute_paths(self) -> List[Sdf.Path]: return self._object_paths def get_property_paths(self) -> List[Sdf.Path]: return self.get_attribute_paths() def get_connections(self): return self._connections def set_default(self, comp=-1): """Set the og.Attribute default value if it exists in metadata""" # FIXME # self.set_soft_range_userdata(None, None) if self.is_different_from_default() is False or self._has_default_value is False: if self._soft_range_min is not None and self._soft_range_max is not None: if self._on_set_default_fn: self._on_set_default_fn() self.update_control_state() return with omni.kit.undo.group(): for attribute in self._get_og_attributes(): if isinstance(attribute, og.Attribute): current_value = self._read_value(attribute) if comp >= 0: default_value = current_value default_value[comp] = self._default_value[comp] else: default_value = self._default_value self._change_property(attribute, default_value, current_value) # We just set all the properties to the same value, it's no longer ambiguous self._ambiguous = False self._comp_ambiguous.clear() self._different_from_default = False self._comp_different_from_default.clear() if self._on_set_default_fn: self._on_set_default_fn() def set_value(self, value, comp=-1): if self._min is not None: if hasattr(value, "__len__"): for i in range(len(value)): # noqa: PLC0200 if value[i] < self._min: value[i] = self._min else: if value < self._min: value = self._min if self._max is not None: if hasattr(value, "__len__"): for i in range(len(value)): # noqa: PLC0200 if value[i] > self._max: value[i] = self._max else: if value > self._max: value = self._max if not self._ambiguous and not any(self._comp_ambiguous) and (value == self._value): return False if self.is_locked(): carb.log_warn("Setting locked attribute is not supported yet") self._update_value(True) # reset value return False if self._might_be_time_varying: carb.log_warn("Setting time varying attribute is not supported yet") self._update_value(True) # reset value return False self._value = value attributes = self._get_og_attributes() if len(attributes) == 0: return False # FIXME: Here we normally harden placeholders into real attributes. For OG we don't do that. # This is because all OG attributes are 'real', IE there are no attributes inherited from a 'type' that # are un-instantiated. However there could be real (dynamic) USD attributes for which there are no # OG attributes. In that case we want to allow editing of those values... # self._create_placeholder_attributes(attributes) if self._editing: for i, attribute in enumerate(attributes): set_value = False self._ignore_notice = True if comp == -1: self._real_values[i] = self._value if not self._change_on_edit_end: set_value = True else: # Only update a single component of the value (for vector type) value = self._real_values[i] self._real_values[i] = self._update_value_by_comp(value, comp) if not self._change_on_edit_end: set_value = True if set_value: # Directly set the value on the attribute, not through a command. # FIXME: Due to the TfNotice issue - we use USD API here. is_extended_attr = ( attribute.get_extended_type() != og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR ) usd_attr = self._stage.GetAttributeAtPath(attribute.get_path()) if is_extended_attr: # But the resolved attrib is not in USD, so we need to set the value using OG, but then # trigger a tfnotice so that the system will know that the attrib has changed og.Controller.set(attribute, value) # The USD attrib is actually a token, so the hack here is to change the token value # so that the node will get the onValueChanged callback. FIXME: Obviously not ideal # to be tokenizing the value usd_attr.Set(str(value)) else: usd_attr.Set(self._value) self._ignore_notice = False else: with omni.kit.undo.group(): for i, attribute in enumerate(attributes): self._ignore_notice = True # begin_edit is not called for certain widget (like Checkbox), issue the command directly if comp == -1: self._change_property(attribute, self._value, None) else: # Only update a single component of the value (for vector type) value = self._real_values[i] self._real_values[i] = self._update_value_by_comp(value, comp) self._change_property(attribute, value, None) self._ignore_notice = False if comp == -1: # We just set all the properties to the same value, it's no longer ambiguous self._ambiguous = False self._comp_ambiguous.clear() else: self._comp_ambiguous[comp] = False self._ambiguous = any(self._comp_ambiguous) if self._has_default_value: self._comp_different_from_default = [False] * self._get_comp_num() if comp == -1: self._different_from_default = value != self._default_value if self._different_from_default: for comp_non_default in range(len(self._comp_different_from_default)): # noqa: PLC0200 self._comp_different_from_default[comp_non_default] = not self._compare_value_by_comp( value, self._default_value, comp_non_default ) else: self._comp_different_from_default[comp] = not self._compare_value_by_comp( value, self._default_value, comp ) self._different_from_default = any(self._comp_different_from_default) else: self._different_from_default = False self._comp_different_from_default.clear() self.update_control_state() return True def _is_prev_same(self): return self._prev_real_values == self._real_values def begin_edit(self): self._editing = self._editing + 1 self._prev_value = self._value self._save_real_values_as_prev() def end_edit(self): self._editing = self._editing - 1 if self._is_prev_same(): return attributes = self._get_og_attributes() omni.kit.undo.begin_group() self._ignore_notice = True for i, attribute in enumerate(attributes): self._change_property(attribute, self._real_values[i], self._prev_real_values[i]) self._ignore_notice = False omni.kit.undo.end_group() # Set flags. It calls _on_control_state_changed_fn when the user finished editing self._update_value(True) def _change_property(self, attribute: og.Attribute, new_value, old_value): """Change the given attribute via a command""" path = Sdf.Path(attribute.get_path()) # Set the value on the attribute, called to "commit" the value # FIXME: Due to the TfNotice issue - we use USD API here. is_extended_attr = attribute.get_extended_type() != og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR if is_extended_attr: # But the resolved attrib is not in USD, so we need to set the value using OG, but then # trigger a tfnotice so that the system will know that the attrib has changed og.Controller.set(attribute, new_value) # The USD attrib is actually a token, so the hack here is to change the token value # so that the node will get the onValueChanged callback. FIXME: Obviously not ideal # to be tokenizing the value + Undo doesn't work omni.kit.commands.execute("ChangeProperty", prop_path=path, value=str(new_value), prev=str(old_value)) else: # FIXME: The UI widgets seem to rely on USD notices (eg color control), so we must set values through # USD until we can refactor things to not require the notices. omni.kit.commands.execute("ChangeProperty", prop_path=path, value=new_value, prev=old_value) def get_value(self): self._update_value() return self._value def get_current_time_code(self): # FIXME: Why are we being asked this return Usd.TimeCode.Default() def _update_value(self, force=False): """Pull the current value of the attributes into this object""" return self._update_value_objects(force, self._get_og_attributes()) def _update_value_objects(self, force: bool, objects: List[HELD_ATTRIB]): if (self._dirty or force) and self._stage: # noqa: PLR1702 carb.profiler.begin(1, "OmniGraphBase._update_value_objects") self._might_be_time_varying = False self._value = None self._has_default_value = False self._default_value = None self._real_values.clear() self._real_type = None self._connections.clear() self._ambiguous = False self._comp_ambiguous.clear() self._different_from_default = False self._comp_different_from_default.clear() for index, attr_object in enumerate(objects): value, tp = self._read_value_and_type(attr_object) self._real_values.append(value) self._real_type = tp # if isinstance(attr_object, og.Attribute): # FIXME: Can OG attributes be 'time varying'? # self._might_be_time_varying = self._might_be_time_varying or attr_object.GetNumTimeSamples() > 0 self._connections.append( [ Sdf.Path(conn.get_node().get_prim_path()).AppendProperty(conn.get_name()) for conn in attr_object.get_upstream_connections() ] ) # only need to check the first prim. All other prims attributes are ostensibly the same if index == 0: self._value = value if ( (self._value is not None) and self._is_array_type(attr_object) and len(self._value) >= BIG_ARRAY_MIN ): self._is_big_array = True comp_num = self._get_comp_num() self._comp_ambiguous = [False] * comp_num self._comp_different_from_default = [False] * comp_num # Loads the default value self._has_default_value, self._default_value = self._get_default_value(attr_object) elif self._value != value: self._value = value self._ambiguous = True comp_num = len(self._comp_ambiguous) if comp_num > 0: for i in range(comp_num): if not self._comp_ambiguous[i]: self._comp_ambiguous[i] = not self._compare_value_by_comp( value, self._real_values[0], i ) if self._has_default_value: comp_num = len(self._comp_different_from_default) if comp_num > 0 and (not self._is_array_type(attr_object)): for i in range(comp_num): if not self._comp_different_from_default[i]: self._comp_different_from_default[i] = not self._compare_value_by_comp( value, self._default_value, i ) self._different_from_default |= any(self._comp_different_from_default) elif not self._is_array_type(attr_object) or value or self._default_value: # empty arrays may compare unequal self._different_from_default |= value != self._default_value self._dirty = False self.update_control_state() carb.profiler.end(1) return True return False def _get_attributes(self): """ Gets the list of managed USD Attributes NOTE: Only returns attributes for which there are corresponding OG Attributes """ attributes = [] if not self._stage: return attributes for path in self._object_paths: prim = self._stage.GetPrimAtPath(path.GetPrimPath()) if prim: attr = prim.GetAttribute(path.name) if attr: # Hidden attributes don't get placeholders if not attr.IsHidden(): try: _ = og.Controller.attribute(path.pathString) except og.OmniGraphError: # No corresponding OG Attribute pass else: attributes.append(attr) else: attr = PlaceholderAttribute(name=path.name, prim=prim, metadata=self._metadata) attributes.append(attr) return attributes def _get_og_attributes(self) -> List[HELD_ATTRIB]: """Returns the held attributes object wrappers""" attributes = [] for path in self._object_paths: attrib = None try: attrib = og.Controller.attribute(path.pathString) attributes.append(attrib) except og.OmniGraphError: # Invalid attribute for whatever reason, put in a placeholder pass if not attrib: attributes.append(PlaceholderOmniGraphAttribute(path.name, path.GetPrimPath().pathString)) return attributes @carb.profiler.profile def _read_value_and_type(self, attr_object: HELD_ATTRIB) -> Tuple[Any, Optional[og.Type]]: """Reads the value and type of the given object Args: attr_object The object to be read Returns: The value The og.Type if the value is read from OG """ val = None if not isinstance(attr_object, PlaceholderOmniGraphAttribute): # The ui expects USD attr_objects, so we must convert data # here. # FIXME: Could optimize by wrapping numpy in compatible shim classes # try: if attr_object.is_valid(): og_val = og.Controller(attr_object).get() og_tp = attr_object.get_resolved_type() # Truncate big arrays to limit copying between numpy/USD types val = og.attribute_value_as_usd(og_tp, og_val, BIG_ARRAY_MIN) return (val, og_tp) except og.OmniGraphError: carb.log_warn(f"Failed to read {attr_object.get_path()}") return (val, None) def _read_value(self, attr_object: HELD_ATTRIB): """Returns the current USD value of the given attribute object""" val, _ = self._read_value_and_type(attr_object) return val def set_locked(self, locked): pass def is_locked(self): return False def has_connections(self): return self._connections[-1]
32,585
Python
42.390146
118
0.555777
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/style.py
"""Contains common information for styling of the OGN node editor and ancillary windows""" import os from pathlib import Path from typing import Dict from omni import ui # These values are not affected by style parameters. Using **kwargs keeps them consistent. VSTACK_ARGS = {"height": 0, "spacing": 8, "margin_height": 4} HSTACK_PROPERTIES = {"spacing": 10} # Style names that can be used for the overrides STYLE_GHOST = "Ghost Prompt" KIT_GREEN = 0xFF8A8777 LABEL_WIDTH = 120 # Styling information for tooltips TOOLTIP_STYLE = { "background_color": 0xFFD1F7FF, "color": 0xFF333333, "margin_width": 3, "margin_height": 2, "border_width": 3, "border_color": 0xFF000000, } # Styling for integer input boxes INT_STYLE = {"Tooltip": TOOLTIP_STYLE} # Styling for the main menubar MENU_STYLE = { "Tooltip": TOOLTIP_STYLE, "background_color": 0xFF555555, "background_selected_color": 0xFF999999, "color": 0xFFFFFFFF, "border_radius": 4, "padding": 8, } # Styling for the metadata subsection METADATA_STYLE = { "Tooltip": TOOLTIP_STYLE, "border_color": 0xFF555555, "background_color": 0xFF000000, "border_width": 1, "margin": 0, "TreeView": {"font_size": 12, "color": 0xFFAAAAAA, "background_color": 0xFF23211F, "secondary_color": 0xFF23211F}, "TreeView::header": { "font_size": 12, "color": 0xFFAAAAAA, "background_color": 0xFF00FFFF, "secondary_color": 0xFF23211F, }, } # Styling for string input boxes STRING_STYLE = {"Tooltip": TOOLTIP_STYLE} # Styling information for vertical stacks. VSTACK_STYLE = {"Tooltip": TOOLTIP_STYLE} # ====================================================================== # General styling for the window as a whole (dark mode) WINDOW_STYLE = { "Window": {"background_color": 0xFF444444}, "Button": {"background_color": 0xFF292929, "margin": 3, "padding": 3, "border_radius": 2}, "Button.Label": {"color": 0xFFCCCCCC}, "Button:hovered": {"background_color": 0xFF9E9E9E}, "Button:pressed": {"background_color": 0xC22A8778}, "VStack::main_v_stack": {"secondary_color": 0x0, "margin_width": 10, "margin_height": 0}, "VStack::frame_v_stack": {"margin_width": 15}, "Rectangle::frame_background": {"background_color": 0xFF343432, "border_radius": 5}, "Field::models": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 4.0}, "Frame": {"background_color": 0xFFAAAAAA}, "Label::transform": {"font_size": 14, "color": 0xFF8A8777}, "Circle::transform": {"background_color": 0x558A8777}, "Field::transform": { "background_color": 0xFF23211F, "border_radius": 3, "corner_flag": ui.CornerFlag.RIGHT, "font_size": 14, }, "Slider::transform": { "background_color": 0xFF23211F, "border_radius": 3, "draw_mode": ui.SliderDrawMode.DRAG, "corner_flag": ui.CornerFlag.RIGHT, "font_size": 14, }, "Label::transform_label": {"font_size": 14, "color": 0xFFDDDDDD}, "Label": {"font_size": 14, "color": 0xFF8A8777}, "Label::label": {"font_size": 14, "color": 0xFF8A8777}, "Label::title": {"font_size": 14, "color": 0xFFAAAAAA}, "Triangle::title": {"background_color": 0xFFAAAAAA}, "ComboBox::path": {"font_size": 12, "secondary_color": 0xFF23211F, "color": 0xFFAAAAAA}, "ComboBox::choices": { "font_size": 12, "color": 0xFFAAAAAA, "background_color": 0xFF23211F, "secondary_color": 0xFF23211F, }, "ComboBox:hovered:choices": {"background_color": 0xFF33312F, "secondary_color": 0xFF33312F}, "Slider::value_less": { "font_size": 14, "color": 0x0, "border_radius": 5, "background_color": 0xFF23211F, "secondary_color": KIT_GREEN, "border_color": 0xFFAAFFFF, "border_width": 0, }, "Slider::value": { "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 5, "background_color": 0xFF23211F, "secondary_color": KIT_GREEN, }, "Rectangle::add": {"background_color": 0xFF23211F}, "Rectangle:hovered:add": {"background_color": 0xFF73414F}, "CheckBox::greenCheck": {"font_size": 12, "background_color": KIT_GREEN, "color": 0xFF23211F}, "CheckBox::whiteCheck": {"font_size": 12, "background_color": 0xFFDDDDDD, "color": 0xFF23211F}, "Slider::colorField": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFF8A8777}, # Frame "CollapsableFrame::standard_collapsable": { "background_color": 0xFF343432, "secondary_color": 0xFF343432, "font_size": 16, "border_radius": 2.0, "border_color": 0x0, "border_width": 0, }, "CollapsableFrame:hovered:standard_collapsable": {"secondary_color": 0xFFFBF1E5}, "CollapsableFrame:pressed:standard_collapsable": {"secondary_color": 0xFFF7E4CC}, } # ====================================================================== # Styling for all of the collapsable frames COLLAPSABLE_FRAME_STYLE = { "CollapsableFrame::standard_collapsable": { "background_color": 0xFF343432, "secondary_color": 0xFF343432, "color": 0xFFAAAAAA, "border_radius": 4.0, "border_color": 0x0, "border_width": 0, "font_size": 14, "padding": 0, "margin_height": 5, "margin_width": 5, }, "HStack::header": {"margin": 5}, "CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A}, "CollapsableFrame:pressed": {"secondary_color": 0xFF343432}, } # ============================================================================================================== class Icons: """A utility that uses the current style to look up the path to icons""" def __init__(self): import carb.settings icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") self.__style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" # Read all the svg files in the directory self.__icons = {icon.stem: icon for icon in icon_path.joinpath(self.__style).glob("*.svg")} def get(self, prim_type, default=None): """Checks the icon cache and returns the icon if exists, None if not""" found = self.__icons.get(prim_type) if not found and default: found = self.__icons.get(default) return str(found) if found else None # ====================================================================== def get_window_style() -> Dict: """Returns a dictionary holding the style information for the OGN editor window""" import carb.settings style_name = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" icons = Icons() if style_name == "NvidiaLight": style = { "AddElement.Image": {"image_url": icons.get("Plus"), "color": 0xFF535354}, "Button": {"background_color": 0xFF296929, "margin": 3, "padding": 3, "border_radius": 4}, "Button.Label": {"color": 0xFFCCCCCC}, "Button:hovered": {"background_color": 0xFF9E9E9E}, "Button:pressed": {"background_color": 0xC22A8778}, "DangerButton": {"background_color": 0xFF292989, "margin": 3, "padding": 3, "border_radius": 4}, "DisabledButton": {"background_color": 0x33296929, "margin": 3, "padding": 3, "border_radius": 4}, "DisabledButton.Label": {"color": 0x33666666}, "Code": {"color": 0xFFACACAC, "margin_width": 4, "font_size": 14, "background_color": 0xFF535354}, "Info": {"color": 0xFF000000, "margin_width": 4, "background_color": 0xFF53E3E3}, "FolderImage.Image": {"image_url": icons.get("folder"), "color": 0xFF535354}, "LabelOverlay": {"background_color": 0xFF535354}, "Rectangle::frame_background": {"background_color": 0xFFC4C4C2, "border_radius": 5}, "RemoveElement.Image": {"image_url": icons.get("trash"), "color": 0xFF535354}, "ScrollingFrame": {"secondary_color": 0xFF444444}, STYLE_GHOST: {"color": 0xFF4C4C4C}, "Tooltip": { "background_color": 0xFFD1F7FF, "color": 0xFF333333, "margin_width": 3, "margin_height": 2, "border_width": 3, "border_color": 0xFF000000, }, "TreeView": { "background_color": 0xFFE0E0E0, "background_selected_color": 0x109D905C, "secondary_color": 0xFFACACAC, }, "TreeView.ScrollingFrame": {"background_color": 0xFFE0E0E0}, "TreeView.Header": {"color": 0xFFCCCCCC}, "TreeView.Header::background": { "background_color": 0xFF535354, "border_color": 0xFF707070, "border_width": 0.5, }, "TreeView.Item": {"color": 0xFF535354, "font_size": 16}, "TreeView.Item:selected": {"color": 0xFF2A2825}, "TreeView:selected": {"background_color": 0x409D905C}, } else: style = { "AddElement.Image": {"image_url": icons.get("Plus"), "color": 0xFF8A8777}, "Button": {"background_color": 0xFF296929, "margin": 3, "padding": 3, "border_radius": 4}, "Button.Label": {"color": 0xFFCCCCCC}, "Button:hovered": {"background_color": 0xFF9E9E9E}, "Button:pressed": {"background_color": 0xC22A8778}, "DangerButton": {"background_color": 0xFF292989, "margin": 3, "padding": 3, "border_radius": 4}, "DisabledButton": {"background_color": 0x33296929, "margin": 3, "padding": 3, "border_radius": 4}, "DisabledButton.Label": {"color": 0x33666666}, "Code": {"color": 0xFF808080, "margin_width": 4, "font_size": 14, "background_color": 0xFF8A8777}, "Info": {"color": 0xFFFFFFFF, "margin_width": 4, "background_color": 0xFF232323}, "FolderImage.Image": {"image_url": icons.get("folder"), "color": 0xFF8A8777}, "RemoveElement.Image": {"image_url": icons.get("trash"), "color": 0xFF8A8777}, STYLE_GHOST: {"color": 0xFF4C4C4C, "margin_width": 4}, "Tooltip": { "background_color": 0xFFD1F7FF, "color": 0xFF333333, "margin_width": 3, "margin_height": 2, "border_width": 3, "border_color": 0xFF000000, }, "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0x664F4D43, "secondary_color": 0xFF403B3B, }, "TreeView.ScrollingFrame": {"background_color": 0xFF23211F}, "TreeView.Header": {"background_color": 0xFF343432, "color": 0xFFCCCCCC, "font_size": 13.0}, "TreeView.Image:disabled": {"color": 0x60FFFFFF}, "TreeView.Item": {"color": 0xFF8A8777}, "TreeView.Item:disabled": {"color": 0x608A8777}, "TreeView.Item:selected": {"color": 0xFF23211F}, "TreeView:selected": {"background_color": 0xFF8A8777}, } # Add the style elements common to both light and dark shared_style = { "ScrollingFrame": {"margin_height": 10}, "Frame::attribute_value_frame": {"margin_height": 5, "margin_width": 5}, "Label::frame_label": {"margin_width": 5}, "CheckBox": {"font_size": 12}, "CollapsableFrame": { "background_color": 0xFF343432, "secondary_color": 0xFF343432, "color": 0xFFAAAAAA, "border_radius": 4.0, "border_color": 0x0, "border_width": 0, "font_size": 16, "padding": 0, "margin_width": 5, }, "CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A}, "CollapsableFrame:pressed": {"secondary_color": 0xFF343432}, # "HStack": {"height": 0, "spacing": 5, "margin_width": 10}, # "HStack::header": {"margin": 5}, # "Label": {"word_wrap": True}, "VStack": {"margin_height": 5}, } # Add some color to hovered widgets for debugging if os.getenv("OGN_DEBUG_EDITOR"): shared_style[":hovered"] = {"debug_color": 0x22FFDDDD} style.update(shared_style) return style # ====================================================================== # Constants for the layout of the window WIDGET_WIDTH = 200 # Standard widget width LINE_HEIGHT = 16 # Height of a single input line NAME_VALUE_WIDTH = 150 # Width of the node property name column BUTTON_WIDTH = 120 # Standard button width # ====================================================================== def name_value_label(property_name: str, tooltip: str = ""): """Emit a UI label for the node property names; allows a common fixed width for the column""" return ui.Label(property_name, width=NAME_VALUE_WIDTH, alignment=ui.Alignment.RIGHT_TOP, tooltip=tooltip) # ====================================================================== def name_value_hstack(): """Emit an HStack widget suitable for the property/value pairs for node properties""" return ui.HStack(**HSTACK_PROPERTIES) # ====================================================================== def icon_directory() -> Path: """Returns a string containing the path to the icon directory for the current style""" import carb.settings style_name = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" return Path(__file__).joinpath("icons").joinpath(style_name)
13,778
Python
41.925234
118
0.573378
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_prim_node_templates.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 functools import partial from typing import List import omni.graph.core as og import omni.ui as ui from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH from pxr import Sdf, Usd # Common functionality for get/set prim attribute templates ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP} def get_use_path(stage: Usd.Stage, node_prim_path: Sdf.Path) -> bool: # Gets the value of the usePath input attribute prim = stage.GetPrimAtPath(node_prim_path) if prim: return prim.GetAttribute("inputs:usePath").Get() return False def is_usable(type_name: Sdf.ValueTypeName) -> bool: # Returns True if the given type can be used by OG return og.AttributeType.type_from_sdf_type_name(str(type_name)).base_type != og.BaseDataType.UNKNOWN def get_filtered_attributes(prim: Usd.Prim) -> List[str]: # Return attributes that should be selectable for the given prim # FIXME: Ideally we only want to show attributes that are useful and can actually be sensibly set. We # will want to add customize logic here to handle pseudo-attributes that can only be manipulated using # USD function sets. return [p.GetName() for p in prim.GetAttributes() if not p.IsHidden() and is_usable(p.GetTypeName())] class TargetPrimAttributeNameModel(TfTokenAttributeModel): """Model for selecting the target attribute for the write/read operation. We modify the list to show attributes which are available on the target prim. """ class AllowedTokenItem(ui.AbstractItem): def __init__(self, item, label): """ Args: item: the attribute name token to be shown label: the label to show in the drop-down """ super().__init__() self.token = item self.model = ui.SimpleStringModel(label) def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict, node_prim_path: Sdf.Path, ): """ Args: stage: The current stage attribute_paths: The list of full attribute paths self_refresh: ignored metadata: pass-through metadata for model node_prim_path: The path of the compute node """ self._stage = stage self._node_prim_path = node_prim_path self._target_prim = None self._max_attrib_name_length = 0 super().__init__(stage, attribute_paths, self_refresh, metadata) def _get_allowed_tokens(self, _): # Override of TfTokenAttributeModel to specialize what tokens are to be shown return self._get_target_attribs_of_interest() def _update_value(self, force=False): # Override of TfTokenAttributeModel to refresh the allowed token cache self._update_allowed_token() super()._update_value(force) def _item_factory(self, item): # Construct the item for the model label = item # FIXME: trying to right-justify type in drop down doesn't work because # font is not fixed widget # if item and self._target_prim: # prop = self._target_prim.GetProperty(item) # if prop: # spacing = 2 + (self._max_attrib_name_length - len(item)) # label = f"{item} {' '*spacing} {str(prop.GetTypeName())})" return TargetPrimAttributeNameModel.AllowedTokenItem(item, label) def _update_allowed_token(self): # Override of TfTokenAttributeModel to specialize the model items super()._update_allowed_token(token_item=self._item_factory) def _get_target_attribs_of_interest(self) -> List[str]: # Returns the attributes we want to let the user select from prim = self._stage.GetPrimAtPath(self._node_prim_path) attribs = [] target = None if prim: if not get_use_path(self._stage, self._node_prim_path): rel = prim.GetRelationship("inputs:prim") if rel.IsValid(): targets = rel.GetTargets() if targets: target = self._stage.GetPrimAtPath(targets[0]) else: prim_path = prim.GetAttribute("inputs:primPath").Get() if prim_path: target = self._stage.GetPrimAtPath(prim_path) if target: attribs = get_filtered_attributes(target) self._target_prim = target self._max_attrib_name_length = max(len(s) for s in attribs) if attribs else 0 name_attr = prim.GetAttribute("inputs:name") if len(attribs) > 0: current_value = name_attr.Get() if (current_value is not None) and (current_value != "") and (current_value not in attribs): attribs.append(current_value) attribs.insert(0, "") else: name_attr.Set("") return attribs class PrimAttributeCustomLayoutBase: """Base class for Read/WritePrimAttribute""" # Set by the derived class to customize the layout _value_is_output = True def __init__(self, compute_node_widget): self.enable = True self.compute_node_widget = compute_node_widget self.attribs = [] self.target_attrib_name_model = None self.prim_path_model = None self.prim_rel_widget = None self.use_path_model = None self._inputs_prim_watcher = None self._inputs_usepath_watcher = None def _name_attrib_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): # Build the Attribute Name widget stage = self.compute_node_widget.stage node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212 if get_use_path(stage, node_prim_path): # Build the simple token input for data-driven attribute name ui_prop.override_display_name("Attribute Name") self.target_attrib_name_model = UsdPropertiesWidgetBuilder._tftoken_builder( # noqa: PLW0212 stage, ui_prop.prop_name, ui_prop.property_type, ui_prop.metadata, [node_prim_path], {"enabled": True, "style": ATTRIB_LABEL_STYLE}, {"enabled": True}, ) return with ui.HStack(spacing=HORIZONTAL_SPACING): ui.Label("Attribute Name", name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH) ui.Spacer(width=HORIZONTAL_SPACING) with ui.ZStack(): attr_path = node_prim_path.AppendProperty("inputs:name") # Build the token-selection widget when prim is known self.target_attrib_name_model = TargetPrimAttributeNameModel( stage, [attr_path], False, {}, node_prim_path ) ui.ComboBox(self.target_attrib_name_model) def _prim_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): # Build the token input prim path widget stage = self.compute_node_widget.stage node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212 use_path = get_use_path(stage, node_prim_path) ui_prop.override_display_name("Prim Path") self.prim_path_model = UsdPropertiesWidgetBuilder._tftoken_builder( # noqa: PLW0212 stage, ui_prop.prop_name, ui_prop.property_type, ui_prop.metadata, [node_prim_path], {"enabled": use_path, "style": ATTRIB_LABEL_STYLE}, {"enabled": use_path}, ) self.prim_path_model.add_value_changed_fn(self._on_target_prim_path_changed) def _prim_rel_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): # Build the relationship input prim widget stage = self.compute_node_widget.stage node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212 use_path = get_use_path(stage, node_prim_path) ui_prop.override_display_name("Prim") self.prim_rel_widget = UsdPropertiesWidgetBuilder._relationship_builder( # noqa: PLW0212 stage, ui_prop.prop_name, ui_prop.metadata, [node_prim_path], {"enabled": not use_path, "style": ATTRIB_LABEL_STYLE}, { "enabled": not use_path, "on_remove_target": self._on_target_prim_rel_changed, "target_picker_on_add_targets": self._on_target_prim_rel_changed, "targets_limit": 1, }, ) def _use_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): # Build the boolean toggle for inputs:usePath stage = self.compute_node_widget.stage node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212 ui_prop.override_display_name("Use Path") self.use_path_model = UsdPropertiesWidgetBuilder._bool_builder( # noqa: PLW0212 stage, ui_prop.prop_name, ui_prop.property_type, ui_prop.metadata, [node_prim_path], {"style": ATTRIB_LABEL_STYLE}, ) self.use_path_model.add_value_changed_fn(self._on_usepath_changed) def _on_target_prim_rel_changed(self, *args): # When the inputs:prim relationship changes # Dirty the attribute name list model because the prim may have changed self.target_attrib_name_model._set_dirty() # noqa: PLW0212 self.prim_rel_widget._set_dirty() # noqa: PLW0212 def _on_target_prim_path_changed(self, *args): # When the inputs:primPath token changes # Dirty the attribute name list model because the prim may have changed self.target_attrib_name_model._set_dirty() # noqa: PLW0212 def _on_usepath_changed(self, _): # When the usePath toggle changes self.prim_rel_widget._set_dirty() # noqa: PLW0212 self.prim_path_model._set_dirty() # noqa: PLW0212 # FIXME: Not sure why _set_dirty doesn't trigger UI change, have to rebuild self.compute_node_widget.request_rebuild() def apply(self, props): # Called by compute_node_widget to apply UI when selection changes def find_prop(name): try: return next((p for p in props if p.prop_name == name)) except StopIteration: return None def build_fn_for_value(prop: UsdPropertyUiEntry): def build_fn(*args): # The resolved attribute is procedural and does not inherit the meta-data of the extended attribute # so we need to manually set the display name prop.override_display_name("Value") self.compute_node_widget.build_property_item( self.compute_node_widget.stage, prop, self.compute_node_widget._payload # noqa: PLW0212 ) return build_fn frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Inputs"): prop = find_prop("inputs:prim") CustomLayoutProperty(None, None, build_fn=partial(self._prim_rel_build_fn, prop)) prop = find_prop("inputs:name") CustomLayoutProperty(None, None, build_fn=partial(self._name_attrib_build_fn, prop)) prop = find_prop("inputs:usePath") CustomLayoutProperty(None, None, build_fn=partial(self._use_path_build_fn, prop)) prop = find_prop("inputs:primPath") CustomLayoutProperty(None, None, build_fn=partial(self._prim_path_build_fn, prop)) # Build the input/output value widget using the compute_node_widget logic so that # we get the automatic handling of extended attribute if not self._value_is_output: prop = find_prop("inputs:value") CustomLayoutProperty(None, None, build_fn=build_fn_for_value(prop)) if self._value_is_output: with CustomLayoutGroup("Outputs"): prop = find_prop("outputs:value") CustomLayoutProperty(None, None, build_fn=build_fn_for_value(prop)) return frame.apply(props)
13,207
Python
42.590759
115
0.6174
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/extension.py
""" Standard file used to manage extension load and unload """ from pathlib import Path import carb import omni.ext import omni.kit from omni.kit.window.extensions import ExtsWindowExtension from .compute_node_widget import ComputeNodeWidget # noqa: PLE0402 from .menu import Menu # noqa: PLE0402 from .metaclass import Singleton # noqa: PLE0402 from .omnigraph_in_extension_window import OmniGraphPage, clear_omnigraph_caches, has_omnigraph_nodes from .properties_widget import OmniGraphProperties # noqa: PLE0402 # ============================================================================================================== class _PublicExtension(omni.ext.IExt): """Standard extension support class, necessary for extension management""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__menu = None self.__widget = None self._properties = None self._hook = None def register_stage_icon(self): """Register the icon used in the stage widget for OmniGraph Prims""" try: import omni.kit.widget.stage # noqa: PLW0621 except ImportError: # No stage widget, no need to register icons return stage_icons = omni.kit.widget.stage.StageIcons() current_path = Path(__file__).parent icon_path = current_path.parent.parent.parent.parent.joinpath("icons") style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" icon_path = icon_path.joinpath(style) for file_name, prim_type in [("OmniGraph.svg", "OmniGraph"), ("OmniGraph.svg", "ComputeGraph")]: file_path = icon_path.joinpath(file_name) stage_icons.set(prim_type, file_path) def on_startup(self): """Callback executed when the extension is starting up. Create the menu that houses the UI functionality""" self.__menu = Menu() self.__widget = ComputeNodeWidget() self._properties = OmniGraphProperties() manager = omni.kit.app.get_app().get_extension_manager() self._hook = manager.subscribe_to_extension_enable( on_enable_fn=lambda _: self.register_stage_icon(), ext_name="omni.kit.widget.stage", hook_name="omni.graph.ui", ) ComputeNodeWidget.get_instance().add_template_path(__file__) ExtsWindowExtension.add_tab_to_info_widget(OmniGraphPage) ExtsWindowExtension.add_searchable_keyword( "@omnigraph", "Uses OmniGraph", has_omnigraph_nodes, clear_omnigraph_caches, ) def on_shutdown(self): """Callback executed when the extension is being shut down. The menu will clean up the dangling editors""" ExtsWindowExtension.remove_searchable_keyword("@omnigraph") ExtsWindowExtension.remove_tab_from_info_widget(OmniGraphPage) self.__menu.on_shutdown() self.__menu = None # Must do this here to avoid the dangling reference Singleton.forget(Menu) self.__widget.on_shutdown() self.__widget = None self._properties.on_shutdown() self._properties = None
3,231
Python
37.939759
115
0.629526
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/compute_node_widget.py
import asyncio import importlib.util import pathlib import weakref from contextlib import suppress from typing import List import omni.graph.core as og import omni.graph.tools.ogn as ogn import omni.kit.window.property as p import omni.ui as ui import omni.usd from omni.kit.property.usd.custom_layout_helper import CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_attribute_widget import UsdAttributeUiEntry, UsdPropertiesWidget, UsdPropertyUiEntry from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH from pxr import Sdf, Usd from .omnigraph_attribute_builder import OmniGraphPropertiesWidgetBuilder # noqa: PLE0402 from .omnigraph_attribute_builder import find_first_node_with_attrib # noqa: PLE0402 _compute_node_widget_instance = None class ComputeNodeWidget(UsdPropertiesWidget): """Creates and registers a widget in the Property Window to display Compute Node contents""" # self.bundles : dict[bundle_name : str, tuple[omni::graph::core::Py_Bundle, list[attrib_name : str]]] BUNDLE_INDEX = 0 ATTRIB_LIST_INDEX = 1 def __init__(self, title="OmniGraph Node", collapsed=False): super().__init__(title=title, collapsed=collapsed) self.context_menu = ui.Menu("ContextMenu") self.bundle_update_sub = None self.bundles = {} self.graph_context: og.GraphContext = None self.graph: og.Graph = None self.node: og.Node = None self.selection = omni.usd.get_context().get_selection() self.stage: Usd.Stage = None self.stage_update_sub = None self.template = None self.template_paths = [] self.time = 0 self.window = None self.window_width_change = False self.window_width_change_fn_set = False self.node_type_name = None self.node_event_sub = None self._payload = None w = p.get_window() w.register_widget("prim", "compute_node", self) global _compute_node_widget_instance _compute_node_widget_instance = weakref.ref(self) OmniGraphPropertiesWidgetBuilder.startup() @staticmethod def get_instance(): return _compute_node_widget_instance() def on_shutdown(self): w = p.get_window() w.unregister_widget("prim", "compute_node") def reset(self): super().reset() window = ui.Workspace.get_window("Property") if self.window != window: self.window_width_change_fn_set = False self.window = window self.window_width_change = False def __on_node_event(self, event): # Called when one of the node event happens self.request_rebuild() def on_new_payload(self, payload: List[Sdf.Path]) -> bool: """ See PropertyWidget.on_new_payload """ if self.bundle_update_sub: self.bundle_update_sub = None if self.stage_update_sub: self.stage_update_sub = None if len(payload) == 0: return False self.stage = omni.usd.get_context().get_stage() self.node = None for path in reversed(payload): node = og.get_node_by_path(path.pathString) if ( node and node.is_valid() and self.stage.GetPrimAtPath(node.get_prim_path()).GetTypeName() in ("ComputeNode", "OmniGraphNode") ): self.node = node self.graph = self.node.get_graph() self.node_event_sub = node.get_event_stream().create_subscription_to_pop( self.__on_node_event, name=f"{path.pathString} Event" ) break if self.node is None: return False self.node_type_name = self.node.get_type_name() self._payload = payload self.graph_context = self.graph.get_default_graph_context() if self.graph.is_valid() else None self.bundles = {} return True def get_additional_kwargs(self, ui_attr: UsdAttributeUiEntry): additional_label_kwargs = {"alignment": ui.Alignment.RIGHT} additional_widget_kwargs = {"no_mixed": True} return additional_label_kwargs, additional_widget_kwargs def get_widget_prim(self): return self.stage.GetPrimAtPath(self._payload[-1]) def add_template_path(self, file_path): """Makes a path from the file_path parameter and adds it to templates paths. So if there is a same kind of structure: /templates template_<ModuleName>.<NameOfComputeNodeType>.py <my_extension>.py then template path can be added by this line in the <my_extension>.py: omni.graph.ui.ComputeNodeWidget.get_instance().add_template_path(__file__) example of template filename: template_omni.particle.system.core.Emitter.py """ template_path = pathlib.Path(file_path).parent.joinpath(pathlib.Path("templates")) if template_path not in self.template_paths: self.template_paths.append(template_path) def get_template_path(self, template_name): for path in self.template_paths: path = path / template_name if path.is_file(): return path return None def load_template(self, props): if not self.node_type_name: return None if self.node_type_name.startswith("omni.graph.ui."): template_name = f"template_{self.node_type_name[14:]}.py" else: template_name = f"template_{self.node_type_name}.py" path = self.get_template_path(template_name) if path is None: return None spec = importlib.util.spec_from_file_location(template_name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) self.template = module.CustomLayout(self) if not self.template.enable: return None return self.template.apply(props) async def __delayed_build_layout(self): await omni.kit.app.get_app().next_update_async() self.window.frame.rebuild() def rebuild_window(self): asyncio.ensure_future(self.__delayed_build_layout()) def _customize_props_layout(self, props): for prop in props: if self.node.get_attribute_exists(prop.prop_name): node_attr = self.node.get_attribute(prop.prop_name) description = node_attr.get_metadata(ogn.MetadataKeys.DESCRIPTION) if description: prop.metadata[Sdf.PropertySpec.DocumentationKey] = description for key in ogn.MetadataKeys.key_names(): prop.add_custom_metadata(key, node_attr.get_metadata(key)) template = self.load_template(props) if template is not None: return template parameter_attrs = [] relationship_attrs = [] hidden_props = [] for prop in props: prop_name = prop.prop_name if prop.property_type == Usd.Relationship: prop.override_display_group("Relationships") relationship_attrs.append(prop) continue if not self.node.get_attribute_exists(prop.prop_name): hidden_props.append(prop) continue is_parameter = False attribute = self.node.get_attribute(prop.prop_name) if attribute.get_metadata("displayGroup") == "parameters": prop.override_display_group("Parameters") parameter_attrs.append(prop) is_parameter = True if attribute.get_metadata(ogn.MetadataKeys.HIDDEN) is not None: hidden_props.append(prop) continue if attribute.get_resolved_type().role == og.AttributeRole.EXECUTION: hidden_props.append(prop) continue if attribute.get_metadata(ogn.MetadataKeys.OBJECT_ID) is not None: hidden_props.append(prop) continue if prop_name.startswith("inputs:"): prop_name = prop_name.replace("inputs:", "") prop.override_display_name(prop_name) if not is_parameter: prop.override_display_group("Inputs") continue elif prop_name.startswith("outputs:"): prop_name = prop_name.replace("outputs:", "") prop.override_display_name(prop_name) if not is_parameter: prop.override_display_group("Outputs") continue elif prop_name.startswith("state:"): prop_name = prop_name.replace("state:", "") prop.override_display_name(prop_name) if not is_parameter: prop.override_display_group("State") continue # Hide everything else if not is_parameter: hidden_props.append(prop) filtered_props = props.copy() for hidden_prop in hidden_props: filtered_props.remove(hidden_prop) self.apply_ogn_metadata_display_names(filtered_props) reordered_attrs = filtered_props self.move_elements_to_beginning(relationship_attrs, reordered_attrs) self.move_elements_to_beginning(parameter_attrs, reordered_attrs) return reordered_attrs def width_changed_subscribe(self): self.window = ui.Workspace.get_window("Property") self.window_width_change = True if not self.window_width_change_fn_set: self.window.set_width_changed_fn(self.width_changed) self.window_width_change_fn_set = True def list_diff(self, list_a, list_b): return [i for i in list_a + list_b if i not in list_a or i not in list_b] def apply_ogn_metadata_display_names(self, attrs): for attr in attrs: if not self.node.get_attribute_exists(attr.attr_name): continue node_attr = self.node.get_attribute(attr.attr_name) if node_attr is None: continue ogn_display_name = node_attr.get_metadata(ogn.MetadataKeys.UI_NAME) if ogn_display_name is not None: attr.override_display_name(ogn_display_name) def move_elements_to_beginning(self, elements_list, target_list): elements_list.reverse() for element in elements_list: target_list.remove(element) for element in elements_list: target_list.insert(0, element) def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]): """Override of base - intercepts all attribute widget building""" with ui.HStack(): # override prim paths to build if UsdPropertyUiEntry specifies one if ui_prop.prim_paths: prim_paths = ui_prop.prim_paths # Use supplied build_fn or our customized builder build_fn = ui_prop.build_fn if ui_prop.build_fn else OmniGraphPropertiesWidgetBuilder.build additional_label_kwargs, additional_widget_kwargs = self.get_additional_kwargs(ui_prop) # Handle extended attributes if ui_prop.property_type is Usd.Attribute: attr_name = ui_prop.attr_name # Find a selected node that actually has this attribute in order to interrogate it node_with_attr = find_first_node_with_attrib(prim_paths, attr_name) if node_with_attr: ogn_attr = node_with_attr.get_attribute(attr_name) is_extended_attribute = ogn_attr.get_extended_type() in ( og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, ) if is_extended_attribute: resolved_type = ogn_attr.get_resolved_type() if resolved_type.base_type == og.BaseDataType.UNKNOWN: # This is an unresolved attribute extended_type = ( "any" if ogn_attr.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY else "union" ) ui_prop.metadata[ OmniGraphPropertiesWidgetBuilder.OVERRIDE_TYPENAME_KEY ] = f"unresolved {extended_type}" ui_prop.metadata[Sdf.PrimSpec.TypeNameKey] = "unknown" else: # Resolved attribute - swap in the resolved type to the ui_prop sdf_type = og.AttributeType.sdf_type_name_from_type(resolved_type) ui_prop.metadata[Sdf.PrimSpec.TypeNameKey] = sdf_type models = build_fn( stage, ui_prop.prop_name, ui_prop.metadata, ui_prop.property_type, prim_paths, additional_label_kwargs, additional_widget_kwargs, ) if models: if not isinstance(models, list): models = [models] for model in models: for prim_path in prim_paths: self._models[prim_path.AppendProperty(ui_prop.prop_name)].append(model) def get_bundles(self): if self.graph_context is None: return inputs_particles_rel = self.stage.GetRelationshipAtPath(self._payload[-1].pathString + ".inputs:particles") if inputs_particles_rel.IsValid(): input_prims = inputs_particles_rel.GetTargets() for input_prim in input_prims: self.bundles[input_prim.GetParentPath().name + ".inputs:particles"] = ( self.graph_context.get_bundle(input_prim.pathString), [], ) self.bundles["outputs:particles"] = ( self.graph_context.get_bundle(self._payload[-1].pathString + "/outputs_particles"), [], ) def bundle_elements_layout_fn(self, **kwargs): with ui.HStack(spacing=HORIZONTAL_SPACING): ui.Label(kwargs["name"], name="label", style={"alignment": ui.Alignment.RIGHT_TOP}, width=LABEL_WIDTH) ui.Spacer(width=HORIZONTAL_SPACING) model = ui.StringField(name="models_readonly", read_only=True, enabled=False).model self.bundles[kwargs["bundle_name"]][self.ATTRIB_LIST_INDEX].append(model) def display_bundles_content(self): self.get_bundles() self.bundle_update_sub = ( omni.kit.app.get_app() .get_update_event_stream() .create_subscription_to_pop(self.on_bundles_update, name="bundles ui update") ) self.stage_update_sub = ( omni.usd.get_context() .get_stage_event_stream() .create_subscription_to_pop(self.on_stage_update, name="bundles ui stage update") ) for bundle_name, bundle_value in self.bundles.items(): names, _ = bundle_value[self.BUNDLE_INDEX].get_attribute_names_and_types() data_count = bundle_value[self.BUNDLE_INDEX].get_attribute_data_count() if data_count == 0: continue with CustomLayoutGroup(bundle_name, collapsed=True): for i in range(0, data_count): attr_name = names[i] def fn(*args, n=attr_name, b=bundle_name): self.bundle_elements_layout_fn(name=n, bundle_name=b) CustomLayoutProperty(None, None, build_fn=fn) def set_bundle_models_values(self): if self.graph_context is None: return for _bundle_name, bundle_value in self.bundles.items(): if not bundle_value[1]: continue _, types = bundle_value[self.BUNDLE_INDEX].get_attribute_names_and_types() data = bundle_value[self.BUNDLE_INDEX].get_attribute_data() for i, d in enumerate(data): with suppress(Exception): attr_type_name = types[i].get_type_name() elem_count = self.graph_context.get_elem_count(d) bundle_value[self.ATTRIB_LIST_INDEX][i].set_value( attr_type_name + " " + str(elem_count) + " elements" ) bundle_value[self.ATTRIB_LIST_INDEX][i]._value_changed() # noqa: PLW0212 def on_bundles_update(self, event): self.time += event.payload["dt"] if self.time > 0.25: self.set_bundle_models_values() self.time = 0 def on_stage_update(self, event): if event.type == int(omni.usd.StageEventType.CLOSING) and self.bundle_update_sub: self.bundle_update_sub = None # unsubscribe from app update stream
17,299
Python
39.705882
116
0.584253
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_settings_editor.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. # import carb.settings import omni.graph.core as og import omni.ui as ui from omni.kit.widget.settings.deprecated import SettingType from omni.kit.window.preferences import PERSISTENT_SETTINGS_PREFIX, PreferenceBuilder SETTING_PAGE_NAME = "Visual Scripting" class OmniGraphSettingsEditor(PreferenceBuilder): def __init__(self): super().__init__(SETTING_PAGE_NAME) self._settings = carb.settings.get_settings() def destroy(self): self._settings = None def build(self): """Updates""" with ui.VStack(height=0): with self.add_frame("Update Settings"): with ui.VStack(): self.create_setting_widget( "Update to USD", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/updateToUsd", SettingType.BOOL, tooltip="When this setting is enabled, copies all OmniGraph node attribute values to USD" " every tick", ) self.create_setting_widget( "Update mesh points to Hydra", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/updateMeshPointsToHydra", SettingType.BOOL, tooltip="When this setting is enabled, mesh points will be not be written back to USD", ) self.create_setting_widget( "Use Realm scheduler", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/realmEnabled", SettingType.BOOL, tooltip="When this setting is enabled, use the Realm scheduler instead of the static scheduler" " with Push evaluator", ) self.create_setting_widget( "Default graph evaluator", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/defaultEvaluator", SettingType.STRING, tooltip="The evaluator to use for new Graphs when not specified", ) self.create_setting_widget( "Use legacy simulation pipeline", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/useLegacySimulationPipeline", SettingType.BOOL, tooltip="(deprecated) - When this setting is enabled , all graphs are run from the simulation" " pipeline stage", ) self.create_setting_widget( "Disable automatic population of prim nodes", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/disablePrimNodes", SettingType.BOOL, tooltip="(deprecated) - When this setting is disabled, prim nodes are populated into Fabric" " for support of direct prim-to-node connections", ) self.create_setting_widget( "Create OmniGraph prims using the schema", og.USE_SCHEMA_PRIMS_SETTING, SettingType.BOOL, tooltip="When this setting is enabled, creates OmniGraph and OmniGraph node prims using the" " schema. Disable the three settings below and enable the one above before enabling" " this.", ) self.create_setting_widget( "Allow global implicit graph", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/allowGlobalImplicitGraph", SettingType.BOOL, tooltip="(deprecated) - When this setting is enabled, allows the global implicit graph" " to exist", ) self.create_setting_widget( "Enable direct connection to prim nodes", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/enableLegacyPrimConnections", SettingType.BOOL, tooltip="(deprecated) - When this setting is enabled, direct connections from OG nodes" " to Prim nodes are allowed", ) self.create_setting_widget( "Enable deprecated OmniGraph prim drop menu", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/createPrimNodes", SettingType.BOOL, tooltip="(deprecated) - When this setting is enabled, adds a menu item on the" " Drop-menu for Prim nodes and allows creation of the omni.graph.core.Prim node type", ) self.create_setting_widget( "Enable deprecated Node.pathChanged callback", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/enablePathChangedCallback", SettingType.BOOL, tooltip="(deprecated) - When this setting is enabled the callback is enabled" " which will affect performance.", ) self.create_setting_widget( "Escalate all deprecation warnings to be errors", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/deprecationsAreErrors", SettingType.BOOL, tooltip="When this setting is enabled any deprecation warnings that a code path" " encounters are escalated to log errors in C++ or raise exceptions in Python. This" " provides a preview of what needs to be fixed when hard deprecation of a code path happens.", ) self.create_setting_widget( "Enable deprecated USD access in pre-render graphs", f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/enableUSDInPreRender", SettingType.BOOL, tooltip="(deprecated) - When this setting is enabled, nodes that read USD data may" " safely be used in a pre-render graph.", )
6,777
Python
54.557377
119
0.539029
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/utils.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 pathlib import Path from typing import Union import carb import omni.graph.core as og import omni.kit.notification_manager as nm import omni.ui as ui from pxr import Sdf # ====================================================================== def get_icons_dir() -> str: """Returns the location of the directory containing the icons used by these windows""" return Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") # ====================================================================== class DestructibleButton(ui.Button): """Class that enhances the standard button with a destroy method that removes callbacks""" def destroy(self): """Called when the button is being destroyed""" self.set_clicked_fn(None) # ====================================================================== class DestructibleImage(ui.Image): """Class that enhances the standard image with a destroy method that removes callbacks""" def destroy(self): """Called when the image is being destroyed""" self.set_mouse_pressed_fn(None) INSTANCE_NODES_WHITELIST = { # Safe to use despite state information in the node "omni.graph.action.OnTick", "omni.graph.core.ReadVariable", "omni.graph.core.WriteVariable", "omni.graph.instancing.ReadGraphVariable", "omni.graph.instancing.WriteGraphVariable", "omni.graph.nodes.FindPrims", "omni.graph.nodes.ReadPrimAttribute", "omni.graph.nodes.WritePrimAttribute", "omni.graph.nodes.ReadPrimBundle", "omni.graph.ui.OnNewFrame", "omni.graph.ui.PrintText", # The following temporal nodes are ignored because there is no way to # set them up with instances at the moment. Any uses of them use explicit paths, # not the graph target node "omni.graph.nodes.MoveToTarget", "omni.graph.nodes.MoveToTransform", "omni.graph.nodes.RotateToOrientation", "omni.graph.nodes.RotateToTarget", "omni.graph.nodes.ScaleToSize", "omni.graph.nodes.TranslateToLocation", "omni.graph.nodes.TranslateToTarget", # visualization nodes are safe - internal state is for caching "omni.graph.visualization.nodes.DrawLine", "omni.graph.visualization.nodes.DrawLabel", "omni.graph.visualization.nodes.DrawScreenSpaceText", } def validate_graph_for_instancing(graph_path: Union[str, Sdf.Path]): """Validate the node types used in a graph are okay to be used with instancing, and post a warning if they are not""" graph = og.get_graph_by_path(str(graph_path)) if not graph: return problematic_nodes = set() nodes = graph.get_nodes() for node in nodes: node_type = node.get_node_type() if node_type and node_type.has_state() and node_type.get_node_type() not in INSTANCE_NODES_WHITELIST: problematic_nodes.add(node_type.get_node_type()) if len(problematic_nodes) == 0: return newline = "\n" node_list = newline.join(sorted(problematic_nodes)) warning_string = ( f"The OmniGraph at path {graph_path} contains nodes that may not execute as" f" expected with multiple instances{newline}{node_list}" ) nm.post_notification(warning_string, status=nm.NotificationStatus.WARNING) carb.log_warn(warning_string) class Prompt: def __init__( self, title, text, ok_button_text="OK", cancel_button_text=None, middle_button_text=None, ok_button_fn=None, cancel_button_fn=None, middle_button_fn=None, modal=False, ): self._title = title self._text = text self._cancel_button_text = cancel_button_text self._cancel_button_fn = cancel_button_fn self._ok_button_fn = ok_button_fn self._ok_button_text = ok_button_text self._middle_button_text = middle_button_text self._middle_button_fn = middle_button_fn self._modal = modal self._build_ui() def __del__(self): self._cancel_button_fn = None self._ok_button_fn = None def __enter__(self): self._window.show() return self def __exit__(self, exit_type, value, trace): self._window.hide() def show(self): self._window.visible = True def hide(self): self._window.visible = False def is_visible(self): return self._window.visible def set_text(self, text): self._text_label.text = text def set_confirm_fn(self, on_ok_button_clicked): self._ok_button_fn = on_ok_button_clicked def set_cancel_fn(self, on_cancel_button_clicked): self._cancel_button_fn = on_cancel_button_clicked def set_middle_button_fn(self, on_middle_button_clicked): self._middle_button_fn = on_middle_button_clicked def _on_ok_button_fn(self): self.hide() if self._ok_button_fn: self._ok_button_fn() def _on_cancel_button_fn(self): self.hide() if self._cancel_button_fn: self._cancel_button_fn() def _on_middle_button_fn(self): self.hide() if self._middle_button_fn: self._middle_button_fn() def _build_ui(self): self._window = ui.Window(self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE ) if self._modal: self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL with self._window.frame: with ui.VStack(height=0): ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer() self._text_label = ui.Label(self._text, word_wrap=True, width=self._window.width - 80, height=0) ui.Spacer() ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer(height=0) if self._ok_button_text: ok_button = ui.Button(self._ok_button_text, width=60, height=0) ok_button.set_clicked_fn(self._on_ok_button_fn) if self._middle_button_text: middle_button = ui.Button(self._middle_button_text, width=60, height=0) middle_button.set_clicked_fn(self._on_middle_button_fn) if self._cancel_button_text: cancel_button = ui.Button(self._cancel_button_text, width=60, height=0) cancel_button.set_clicked_fn(self._on_cancel_button_fn) ui.Spacer(height=0) ui.Spacer(width=0, height=10)
7,319
Python
34.362319
116
0.610739
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_in_extension_window.py
"""Support for adding OmniGraph information to the Kit extensions window""" import json from functools import lru_cache from pathlib import Path from typing import Any, Dict, List import omni.kit.app import omni.ui as ui from omni.kit.window.extensions.common import ExtensionCommonInfo # ============================================================================================================== class OmniGraphTab: def build(self, ext_info): try: ext_name = ext_info["package"]["name"] except KeyError: ext_name = "omni.graph" with ui.VStack(height=0): found_nodes = False node_data = _get_omnigraph_info(ext_info.get("path")) if node_data: node_name_map = { node_name: node_name.replace(f"{ext_name}.", "") for node_name in node_data["nodes"].keys() } for node_name in sorted(node_data["nodes"].keys(), key=lambda name: node_name_map[name]): node_info = node_data["nodes"][node_name] found_nodes = True try: description = node_info["description"] except KeyError: description = "No description provided" with ui.CollapsableFrame(node_name_map[node_name], collapsed=True, tooltip=description): with ui.VStack(): for property_key, property_value in node_info.items(): if property_key == "extension": continue with ui.HStack(): ui.Spacer(width=20) ui.Label( f"{property_key.capitalize()}: ", width=0, style={"color": 0xFF8A8777}, alignment=ui.Alignment.LEFT_TOP, ) ui.Spacer(width=5) ui.Label(str(property_value), word_wrap=True) if not found_nodes: ui.Label( "No OmniGraph nodes are present in this extension", style_type_name_override="ExtensionDescription.Title", ) def destroy(self): pass # ============================================================================================================== class OmniGraphPage: """Wrapper for an OmniGraph tab inside the extension window""" def __init__(self): self.tab = OmniGraphTab() def build_tab(self, ext_info, is_local: bool): self.tab.build(ext_info) def destroy(self): self.tab.destroy() @staticmethod def get_tab_name(): return "OMNIGRAPH" # ============================================================================================================== @lru_cache() def _get_omnigraph_info(ext_path) -> Dict[str, Any]: """Returns the OmniGraph data associated with the extension as a dictionary of path:NodeJsonData The NodeJsonData will be empty if there is no OmniGraph data for the given extension """ node_data = {} path = Path(ext_path) / "ogn" / "nodes.json" if path.is_file(): with open(path, "r", encoding="utf-8") as json_fd: node_data = json.load(json_fd) return node_data # ============================================================================================================== @lru_cache() def _get_omnigraph_user_exts() -> List[Dict[str, Any]]: """Returns the list of all visible extensions that are known to contain OmniGraph nodes. This can be expensive so the results are cached and it is not called until the user explicitly asks for it. TODO: This current method of discovery does not work for extensions that are not installed as there is no information in the .toml file to identify that they have nodes. Once that information is added then it can be checked instead of looking at the extensions on disk as that will be much faster for this quick check. """ found_exts = set() ext_manager = omni.kit.app.get_app().get_extension_manager() for ext_info in ext_manager.get_extensions(): ext_omnigraph_info = _get_omnigraph_info(ext_info.get("path")) if ext_omnigraph_info: found_exts.add(ext_info["name"]) return found_exts # ============================================================================================================== def clear_omnigraph_caches(): """Clear the cached OmniGraph info for extensions. Use only when extensions are modified as this could be costly to call repeatedly as it will force reload of OmniGraph node description files """ _get_omnigraph_info.cache_clear() _get_omnigraph_user_exts.cache_clear() # ============================================================================================================== def has_omnigraph_nodes(extension_info: ExtensionCommonInfo) -> bool: """Check to see if the extension info item refers to an extension that contains OmniGraph nodes.""" return extension_info.fullname in _get_omnigraph_user_exts()
5,376
Python
43.438016
113
0.503534
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/menu.py
""" Support for the menu containing the OmniGraph UI operations. """ import asyncio from functools import partial from typing import List, TypeVar import carb import carb.settings import omni.graph.core as og import omni.graph.tools as ogt import omni.kit.ui import omni.usd from omni import ui from omni.kit.app import get_app_interface from omni.kit.menu.utils import MenuItemDescription from omni.kit.window.preferences import register_page, unregister_page from pxr import Sdf from .metaclass import Singleton # noqa: PLE0402 from .omnigraph_node_description_editor.main_editor import MENU_PATH as MENU_OGN_EDITOR # noqa: PLE0402 from .omnigraph_node_description_editor.main_editor import Editor from .omnigraph_settings_editor import OmniGraphSettingsEditor # noqa: PLE0402 from .omnigraph_toolkit import MENU_PATH as MENU_TOOLKIT # noqa: PLE0402 from .omnigraph_toolkit import Toolkit # Settings # For now we always have an implicit global graph which encompasses the stage. Once that is deprecated we can # disable the workaround code by setting this to False USE_IMPLICIT_GLOBAL_GRAPH = True # ====================================================================== # Menu item names MENU_RELOAD_FROM_STAGE = "deprecated" # ====================================================================== # ============================================================================================================== # Lookup table for operations triggered by the menu items. # They are called with (KEY, ENABLE) values, where KEY is the key in this dictionary and ENABLE is a boolean # where the menu item is triggered when True and "untriggered" when False (i.e. window is opened or closed) MENU_WINDOWS = { MENU_OGN_EDITOR: Editor, } TOOLKIT_WINDOW = Toolkit WindowClassType = TypeVar("WindowClassType", OmniGraphSettingsEditor, Editor, Toolkit) VISUAL_SCRIPTING_MENU_INDEX_OFFSET = 20 MENU_GRAPH = "menu_graph.svg" original_svg_color = carb.settings.get_settings().get("/exts/omni.kit.menu.create/original_svg_color") # ====================================================================== class Menu(metaclass=Singleton): """Manage the menu containing OmniGraph operations Internal Attributes: __menu_items: List of menu trigger subscriptions __toolkit_menu_item: Trigger subscription for the optional toolkit menu item __windows: Dictionary of menu_item/editor_object for editors the menu can open __extension_change_subscription: Subscription to extension changes """ def __init__(self): """Initialize the menu by finding the current context and selection information""" self.__menu_items = [] self.__edit_menu_items = [] self.__create_menu_items = [] self.__create_graph_menu_tuples = [] # noqa: PLW0238 self.__context_menus = [] # noqa: PLW0238 self.__preferences_page = None self.__extension_change_subscription = None self.__toolkit_menu_item = None self.__windows = {} self.on_startup() # -------------------------------------------------------------------------------------------------------------- def set_window_state(self, menu: str, value: bool): """Trigger the visibility state of the given window object. Note: This is not called when the window is manually closed Args: menu: Name of the menu to which the window class is attached value: True means show the window, else hide and destroy Note: It is assumed that the window_class can be destroyed, has is_visible() and is a singleton """ if value: self.__windows[menu].show_window() else: self.__windows[menu].hide_window() def __deferred_set_window_state(self, menu: str, value: bool): # We can't modify UI elements safely from callbacks, so defer that work async def __func(): await omni.kit.app.get_app().next_update_async() self.set_window_state(menu, value) asyncio.ensure_future(__func()) # -------------------------------------------------------------------------------------------------------------- @property def menu_items(self) -> List[ui.MenuItem]: """Returns a list of the menu items owned by this menu class""" return self.__menu_items + self.__edit_menu_items # -------------------------------------------------------------------------------------------------------------- def __on_extension_change(self): """Callback executed when extensions change state""" # Only enable the toolkit debugging window if the inspection extension was enabled since # it supplies the features inspection_enabled = get_app_interface().get_extension_manager().is_extension_enabled("omni.inspect") menu = omni.kit.ui.get_editor_menu() if inspection_enabled: if self.__toolkit_menu_item is None: self.__windows[MENU_TOOLKIT] = TOOLKIT_WINDOW() # Toolkit goes to bottom. There are two graph editors and one node description editor self.__toolkit_menu_item = menu.add_item( MENU_TOOLKIT, self.__deferred_set_window_state, priority=4 + VISUAL_SCRIPTING_MENU_INDEX_OFFSET, toggle=True, value=False, ) else: ogt.destroy_property(self, "__toolkit_menu_item") # -------------------------------------------------------------------------------------------------------------- # Used to be OnClick function for reload from stage menu item # The item is no longer available to external customers but we can keep it alive internally def _on_menu_click(self, menu_item, value): if menu_item == MENU_RELOAD_FROM_STAGE: usd_context = omni.usd.get_context() selection = usd_context.get_selection() selected_prim_paths = selection.get_selected_prim_paths() found_selected_graph = False if selected_prim_paths: all_graphs = og.get_all_graphs() for selected_path in selected_prim_paths: for graph in all_graphs: if graph.get_path_to_graph() == selected_path: found_selected_graph = True carb.log_info(f"reloading graph: '{selected_path}'") graph.reload_from_stage() if not found_selected_graph: current_graph = og.get_current_graph() current_graph_path = current_graph.get_path_to_graph() carb.log_info(f"reloading graph: '{current_graph_path}'") current_graph.reload_from_stage() @classmethod def add_create_menu_type(cls, menu_title: str, evaluator_type: str, prefix: str, glyph_file: str, open_editor_fn): if cls not in cls._instances: # noqa: PLE1101 return instance = cls._instances[cls] # noqa: PLE1101 instance.__create_graph_menu_tuples.append( # noqa: PLW0212,PLW0238 (menu_title, evaluator_type, prefix, glyph_file, open_editor_fn) ) # A wrapper to the create_graph function. Create the graph first and then open that graph def onclick_fn(evaluator_type: str, name_prefix: str, open_editor_fn, menu_arg=None, value=None): node = instance.create_graph(evaluator_type, name_prefix) if open_editor_fn: stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(node.get_wrapped_graph().get_path_to_graph()) open_editor_fn([prim]) def build_context_menu(objects): with omni.ui.Menu(f' {omni.kit.ui.get_custom_glyph_code("${glyphs}/" + MENU_GRAPH)} Visual Scripting'): for ( title, evaluator_type, prefix, glyph_file, _open_editor_fn, ) in instance.__create_graph_menu_tuples: # noqa: PLW0212,E501 omni.ui.MenuItem( f' {omni.kit.ui.get_custom_glyph_code("${glyphs}/" + f"{glyph_file}")} {title}', triggered_fn=partial(onclick_fn, evaluator_type, prefix, _open_editor_fn, objects), ) # First time to add items to create menu, need to create the Visual Scripting submenu if not instance.__context_menus: # noqa: PLW0212 menu_dict = { "name": "Omnigraph Context Create Menu", "glyph": MENU_GRAPH, "populate_fn": build_context_menu, } instance.__context_menus.append( # noqa: PLW0212 omni.kit.context_menu.add_menu(menu_dict, "CREATE", "omni.kit.widget.stage") ) instance.__context_menus.append( # noqa: PLW0212 omni.kit.context_menu.add_menu(menu_dict, "CREATE", "omni.kit.window.viewport") ) if not instance.__create_menu_items: # noqa: PLW0212 instance.__create_menu_items.append( # noqa: PLW0212 MenuItemDescription( name="Visual Scripting", glyph=MENU_GRAPH, appear_after=["Xform"], sub_menu=[ MenuItemDescription( name=title, glyph=glyph_file, onclick_fn=partial(onclick_fn, evaluator_type, prefix, _open_editor_fn), original_svg_color=original_svg_color, ) for ( title, evaluator_type, prefix, glyph_file, _open_editor_fn, ) in instance.__create_graph_menu_tuples # noqa: PLW0212 ], original_svg_color=original_svg_color, ) ) omni.kit.menu.utils.add_menu_items(instance.__create_menu_items, "Create", -9) # noqa: PLW0212 else: instance.__create_menu_items[0].sub_menu.append( # noqa: PLW0212 MenuItemDescription( name=menu_title, glyph=glyph_file, onclick_fn=partial(onclick_fn, evaluator_type, prefix, open_editor_fn), original_svg_color=original_svg_color, ) ) omni.kit.menu.utils.rebuild_menus() @classmethod def remove_create_menu_type(cls, menu_title: str): if cls not in cls._instances: # noqa: PLE1101 return instance = cls._instances[cls] # noqa: PLE1101 instance.__create_graph_menu_tuples = [ # noqa: PLW0212,PLW0238 item for item in instance.__create_graph_menu_tuples if item[0] != menu_title # noqa: PLW0212 ] if not instance.__create_menu_items: # noqa: PLW0212 return if len(instance.__create_graph_menu_tuples) == 0: # noqa: PLW0212 omni.kit.menu.utils.remove_menu_items(instance.__create_menu_items, "Create") # noqa: PLW0212 ogt.destroy_property(instance, "__context_menus") ogt.destroy_property(instance, "__create_menu_items") else: instance.__create_menu_items[0].sub_menu = [ # noqa: PLW0212 item for item in instance.__create_menu_items[0].sub_menu if item.name != menu_title # noqa: PLW0212 ] omni.kit.menu.utils.rebuild_menus() # -------------------------------------------------------------------------------------------------------------- def on_startup(self): """Called when the menu is invoked - build all of the menu entries""" self._settings = carb.settings.get_settings() editor_menu = omni.kit.ui.get_editor_menu() # In a testing environment there may not be an editor, but that's okay if editor_menu is None: return # Add settings page to preference self.__preferences_page = OmniGraphSettingsEditor() register_page(self.__preferences_page) for index, (menu_path, menu_window) in enumerate(MENU_WINDOWS.items()): self.__windows[menu_path] = menu_window() self.__menu_items.append( editor_menu.add_item( menu_path, self.__deferred_set_window_state, priority=index + 1 + VISUAL_SCRIPTING_MENU_INDEX_OFFSET, toggle=True, value=False, ) ) # Set up a subscription to monitor for events that may change whether the toolkit is visible or not change_stream = get_app_interface().get_extension_manager().get_change_event_stream() self.__extension_change_subscription = change_stream.create_subscription_to_pop( lambda _: self.__on_extension_change(), name="OmniGraph Menu Extension Changes" ) assert self.__extension_change_subscription # Ensure the initial state is correct self.__on_extension_change() # -------------------------------------------------------------------------------------------------------------- def on_shutdown(self): """Remove all of the menu objects when the menu is closed""" self.__extension_change_subscription = None if self.__preferences_page: unregister_page(self.__preferences_page) self.__preferences_page = None # Remove all of the menu items from the main menu. Most important when removing callbacks editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: for menu in self.__windows: editor_menu.remove_item(menu) if self.__toolkit_menu_item is not None: editor_menu.remove_item(MENU_TOOLKIT) omni.kit.menu.utils.remove_menu_items(self.__create_menu_items, "Create") ogt.destroy_property(self, "__create_menu_items") ogt.destroy_property(self, "__extension_change_subscription") ogt.destroy_property(self, "__toolkit_menu_item") ogt.destroy_property(self, "__menu_items") ogt.destroy_property(self, "__edit_menu_items") ogt.destroy_property(self, "__context_menus") ogt.destroy_property(self, "__create_graph_menu_tuples") ogt.destroy_property(self, "__windows") # Note that Singleton.forget(Menu) has to be called in the main shutdown since it has a Menu reference # -------------------------------------------------------------------------------------------------------------- def create_graph(self, evaluator_type: str, name_prefix: str, menu_arg=None, value=None) -> og.Node: """Create a new GlobalGraph below the default prim Note: USE_IMPLICIT_GLOBAL_GRAPH forces creation of subgraphs only Args: evaluator_type: the evaluator type to use for the new graph name_prefix: the desired name of the GlobalGraph node. Will be made unique menu_arg: menu info value: menu value Returns: wrapper_node: the node that wraps the new graph """ # FIXME: How to specify USD backing? usd_backing = True usd_context = omni.usd.get_context() stage = usd_context.get_stage() graph_path = Sdf.Path(name_prefix).MakeAbsolutePath(Sdf.Path.absoluteRootPath) graph_path = omni.usd.get_stage_next_free_path(stage, graph_path, True) container_graphs = og.get_global_container_graphs() # FIXME: Just use the first one? We may want a clearer API here. container_graph = container_graphs[0] with omni.kit.undo.group(): _, wrapper_node = og.cmds.CreateGraphAsNode( graph=container_graph, node_name=Sdf.Path(graph_path).name, graph_path=graph_path, evaluator_name=evaluator_type, is_global_graph=True, backed_by_usd=usd_backing, fc_backing_type=og.GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED, pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, ) return wrapper_node def add_create_menu_type(menu_title: str, evaluator_type: str, prefix: str, glyph_file: str, open_editor_fn): """Add a new graph type menu item under Create/Visual Scripting menu which creates a new graph and open the graph. This will create the Visual Scripting menu if menu_title is the first one added Args: menu_title: the display name of this menu item evaluator_type: the evaluator type to use for the new graph prefix: the desired name of the GlobalGraph node. Will be made unique glyph_file: the file name of the svg icon to be displayed. This file must be in the resources package open_editor_fn: the function to open the corresponding graph editor and open the created graph. This is invoked after create_graph """ Menu.add_create_menu_type(menu_title, evaluator_type, prefix, glyph_file, open_editor_fn) def remove_create_menu_type(menu_title: str): """ Remove the menu item named menu_title from Create/Visual Scripting menu. This will remove the entire Visual Scripting menu if menu_title is the last one under it. Args: menu_title: the display name of this menu item """ Menu.remove_create_menu_type(menu_title)
17,858
Python
45.266839
118
0.567589
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/properties_widget.py
import asyncio import types from functools import partial from pathlib import Path from typing import List import carb import omni.graph.core as og import omni.kit.ui import omni.ui as ui import omni.usd from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload from omni.kit.property.usd.usd_attribute_model import FloatModel, IntModel from omni.kit.property.usd.usd_model_base import UsdBase from omni.kit.property.usd.usd_property_widget import ( UsdPropertiesWidget, UsdPropertiesWidgetBuilder, UsdPropertyUiEntry, ) from omni.kit.property.usd.widgets import ICON_PATH from omni.kit.window.property.templates import HORIZONTAL_SPACING from pxr import Gf, OmniGraphSchema, Sdf, Tf, Usd from .stage_picker_dialog import StagePickerDialog # noqa: PLE0402 from .token_array_edit_widget import build_token_array_prop # noqa: PLE0402 from .utils import Prompt # noqa: PLE0402 from .utils import validate_graph_for_instancing # noqa: PLE0402 REMOVE_BUTTON_STYLE = style = {"image_url": str(Path(ICON_PATH).joinpath("remove.svg")), "margin": 0, "padding": 0} AUTO_REFRESH_PERIOD = 0.33 # How frequently to poll for variable refreshes GRAPH_VARIABLE_ATTR_PREFIX = "graph:variable:" OMNIGRAPHS_REL_ATTR = "omniGraphs" COMPUTEGRAPH_TYPE_NAME = ( "OmniGraph" if carb.settings.get_settings().get(og.USE_SCHEMA_PRIMS_SETTING) else "ComputeGraph" ) # Keys for metadata dictionary that the vector variable runtime model will lookup VARIABLE_ATTR = "variable_attr" VARIABLE_GRAPH_PATH = "variable_graph_path" VARIABLE_INSTANCE_PATH = "variable_instance_path" # Used to determine if we need a single channel model builder or not VECTOR_TYPES = { UsdPropertiesWidgetBuilder.tf_gf_vec2i, UsdPropertiesWidgetBuilder.tf_gf_vec2h, UsdPropertiesWidgetBuilder.tf_gf_vec2f, UsdPropertiesWidgetBuilder.tf_gf_vec2d, UsdPropertiesWidgetBuilder.tf_gf_vec3i, UsdPropertiesWidgetBuilder.tf_gf_vec3h, UsdPropertiesWidgetBuilder.tf_gf_vec3f, UsdPropertiesWidgetBuilder.tf_gf_vec3d, UsdPropertiesWidgetBuilder.tf_gf_vec4i, UsdPropertiesWidgetBuilder.tf_gf_vec4h, UsdPropertiesWidgetBuilder.tf_gf_vec4f, UsdPropertiesWidgetBuilder.tf_gf_vec4d, } class OmniGraphProperties: def __init__(self): self._api_widget = None self._variables_widget = None self.on_startup() def on_startup(self): import omni.kit.window.property as p w = p.get_window() if w: self._api_widget = OmniGraphAPIPropertiesWidget("Visual Scripting") w.register_widget("prim", "omni_graph_api", self._api_widget) self._variables_widget = OmniGraphVariablesPropertiesWidget("Variables") w.register_widget("prim", "omni_graph_variables", self._variables_widget) def on_shutdown(self): import omni.kit.window.property as p w = p.get_window() if w: if self._api_widget is not None: w.unregister_widget("prim", "omni_graph_api") self._api_widget.destroy() self._api_widget = None if self._variables_widget is not None: w.unregister_widget("prim", "omni_graph_variables") self._variables_widget.destroy() self._variables_widget = None # ---------------------------------------------------------------------------------------- def is_different_from_default_override(self) -> bool: """Override for USDBase.is_different_from_default""" # Values that are backed by real attributes _always_ override the default value. # Values that are backed by placeholders never override the default value. attributes = self._get_attributes() # noqa: PLW0212 return any(isinstance(attribute, Usd.Attribute) for attribute in attributes) class OmniGraphAPIPropertiesWidget(UsdPropertiesWidget): """Widget for graph instances""" def __init__(self, title: str): super().__init__(title, collapsed=False) self._title = title from omni.kit.property.usd import PrimPathWidget self._add_button_menus = [] self._add_button_menus.append( PrimPathWidget.add_button_menu_entry( "Visual Scripting", show_fn=self._button_show, onclick_fn=self._button_onclick, ) ) self._omnigraph_vars = [] self._omnigraph_vars_props = [] self._graph_targets = set() self._stage_picker = None self._stage_picker_selected_graph = None self._pending_rebuild_task = None def destroy(self): from omni.kit.property.usd import PrimPathWidget for menu in self._add_button_menus: PrimPathWidget.remove_button_menu_entry(menu) self._add_button_menus = [] def _button_show(self, objects: dict): if "prim_list" not in objects or "stage" not in objects: return False stage = objects["stage"] if not stage: return False prim_list = objects["prim_list"] if len(prim_list) < 1: return False for item in prim_list: if isinstance(item, Sdf.Path): prim = stage.GetPrimAtPath(item) elif isinstance(item, Usd.Prim): prim = item type_name = prim.GetTypeName() if "Graph" in type_name or prim.HasAPI(OmniGraphSchema.OmniGraphAPI): return False return True def _on_stage_picker_select_graph(self, selected_prim): for path in self._apply_prim_paths: if not omni.usd.get_context().get_stage().GetPrimAtPath(path).HasAPI(OmniGraphSchema.OmniGraphAPI): validate_graph_for_instancing(selected_prim.GetPath()) omni.kit.commands.execute( "ApplyOmniGraphAPICommand", paths=self._apply_prim_paths, graph_path=selected_prim.GetPath() ) self._refresh_window() return True def __item_added(self, items): """Callback when the target picker adds a graph target""" for (_, path) in items: validate_graph_for_instancing(path) def _button_onclick(self, payload: PrimSelectionPayload): if payload is None: return Sdf.Path.emptyPath if self._stage_picker: self._stage_picker.clean() self._stage_picker = StagePickerDialog( omni.usd.get_context().get_stage(), lambda p: self._on_stage_picker_select_graph(p), # noqa: PLW0108 "Select Graph", "Select", [], lambda p: self._filter_target_lambda(p), # noqa: PLW0108 ) self._stage_picker.show() self._apply_prim_paths = payload.get_paths() # noqa: PLW0201 return self._apply_prim_paths def on_new_payload(self, payload): self._omnigraph_vars.clear() self._omnigraph_vars_props.clear() self._graph_targets.clear() if not super().on_new_payload(payload): return False if not self._payload or len(self._payload) == 0: return False for prim_path in payload: # noqa: PLR1702 prim = self._get_prim(prim_path) if not prim: return False attrs = prim.GetProperties() for attr in attrs: attr_name_str = attr.GetName() if attr_name_str == OMNIGRAPHS_REL_ATTR: targets = attr.GetTargets() for target in targets: self._graph_targets.add(target) target_prim = self._get_prim(target) target_attrs = target_prim.GetAttributes() for target_attr in target_attrs: target_attr_name = target_attr.GetName() if target_attr_name.startswith(GRAPH_VARIABLE_ATTR_PREFIX): self._omnigraph_vars.append(target_attr_name) self._omnigraph_vars_props.append(target_attr) return True return False return False def _filter_props_to_build(self, props): return [ prop for prop in props if prop.GetName().startswith(OMNIGRAPHS_REL_ATTR) or (prop.GetName().startswith(GRAPH_VARIABLE_ATTR_PREFIX) and prop.GetName() in self._omnigraph_vars) ] def _filter_target_lambda(self, target_prim): return target_prim.GetTypeName() == COMPUTEGRAPH_TYPE_NAME def get_additional_kwargs(self, ui_attr): random_prim = Usd.Prim() if self._payload: prim_paths = self._payload.get_paths() for prim_path in prim_paths: prim = self._get_prim(prim_path) if not prim: continue if not random_prim: random_prim = prim elif random_prim.GetTypeName() != prim.GetTypeName(): break if ui_attr.prop_name == OMNIGRAPHS_REL_ATTR: return None, { "target_picker_filter_lambda": self._filter_target_lambda, "target_picker_on_add_targets": self.__item_added, } return None, None def _get_default_value(self, attr_name): """Retreives the default value from the backing attribute""" for graph_prop in self._omnigraph_vars_props: prop_name = graph_prop.GetName() if prop_name == attr_name: if graph_prop.HasValue(): return graph_prop.Get() return graph_prop.GetTypeName().defaultValue return None def _customize_props_layout(self, attrs): variable_group = "Variables" instance_props = set() for attr in attrs: if attr.attr_name == OMNIGRAPHS_REL_ATTR: attr.override_display_group("Graphs") if attr.attr_name in self._omnigraph_vars: instance_props.add(attr.attr_name) var_offset = attr.attr_name.rindex(":") + 1 display_group = variable_group display_name = attr.attr_name[var_offset:] attr.override_display_name(display_name) attr.override_display_group(display_group) attr.add_custom_metadata("default", self._get_default_value(attr.attr_name)) # append the graph properties that don't appear in the list for graph_prop in self._omnigraph_vars_props: prop_name = graph_prop.GetName() if prop_name in instance_props: continue value = graph_prop.GetTypeName().defaultValue if graph_prop.HasValue(): value = graph_prop.Get() ui_prop = UsdPropertyUiEntry( prop_name, variable_group, {Sdf.PrimSpec.TypeNameKey: str(graph_prop.GetTypeName()), "customData": {"default": value}}, Usd.Attribute, ) var_offset = prop_name.rindex(":") + 1 ui_prop.override_display_name(prop_name[var_offset:]) attrs.append(ui_prop) # sort by name to keep the ordering consistent as placeholders are # modified and become actual properies def sort_key(elem): return elem.attr_name attrs.sort(key=sort_key) def build_header(*args): with ui.HStack(spacing=HORIZONTAL_SPACING): ui.Label("Initial", alignment=ui.Alignment.RIGHT) ui.Label("Runtime", alignment=ui.Alignment.RIGHT) header_prop = UsdPropertyUiEntry("header", variable_group, {}, Usd.Property, build_fn=build_header) attrs.insert(0, header_prop) return attrs def _is_placeholder_property(self, ui_prop: UsdPropertyUiEntry) -> bool: """Returns false if this property represents a graph target property that has not been overwritten """ if not ui_prop.attr_name.startswith(GRAPH_VARIABLE_ATTR_PREFIX): return False if self._payload: prim_paths = self._payload.get_paths() for prim_path in prim_paths: prim = self._get_prim(prim_path) if prim and prim.HasAttribute(ui_prop.attr_name): return True return False def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]): metadata = ui_prop.metadata type_name = metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type") sdf_type_name = Sdf.ValueTypeNames.Find(type_name) if sdf_type_name.type == Sdf.ValueTypeNames.TokenArray.type: ui_prop.build_fn = build_token_array_prop elif ui_prop.attr_name.startswith(GRAPH_VARIABLE_ATTR_PREFIX): ui_prop.build_fn = build_variable_prop # override the build function to make modifications to the model build_fn = ui_prop.build_fn if ui_prop.build_fn else UsdPropertiesWidgetBuilder.build ui_prop.build_fn = partial(self.__build_fn_intercept, build_fn) return super().build_property_item(stage, ui_prop, prim_paths) def build_impl(self): if self._collapsable: self._collapsable_frame = ui.CollapsableFrame( # noqa: PLW0201 self._title, build_header_fn=self._build_custom_frame_header, collapsed=self._collapsed ) def on_collapsed_changed(collapsed): self._collapsed = collapsed # noqa: PLW0201 self._collapsable_frame.set_collapsed_changed_fn(on_collapsed_changed) # noqa: PLW0201 else: self._collapsable_frame = ui.Frame(height=10, style={"Frame": {"padding": 5}}) # noqa: PLW0201 self._collapsable_frame.set_build_fn(self._build_frame) def _on_remove_with_prompt(self): def on_remove_omnigraph_api(): selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths() omni.kit.commands.execute("RemoveOmniGraphAPICommand", paths=selected_paths) prompt = Prompt( "Remove Visual Scripting?", "Are you sure you want to remove the 'Visual Scripting' component?", "Yes", "No", ok_button_fn=on_remove_omnigraph_api, modal=True, ) prompt.show() def _build_custom_frame_header(self, collapsed, text): if collapsed: alignment = ui.Alignment.RIGHT_CENTER width = 5 height = 7 else: alignment = ui.Alignment.CENTER_BOTTOM width = 7 height = 5 with ui.HStack(spacing=8): with ui.VStack(width=0): ui.Spacer() ui.Triangle( style_type_name_override="CollapsableFrame.Header", width=width, height=height, alignment=alignment ) ui.Spacer() ui.Label(text, style_type_name_override="CollapsableFrame.Header") with ui.HStack(width=0): ui.Spacer(width=8) with ui.VStack(width=0): ui.Spacer(height=5) ui.Button(style=REMOVE_BUTTON_STYLE, height=16, width=16).set_mouse_pressed_fn( lambda *_: self._on_remove_with_prompt() ) ui.Spacer(width=5) def _on_usd_changed(self, notice, stage): """Overrides the base case USD listener to request a rebuild if the graph target attributes change""" targets = notice.GetChangedInfoOnlyPaths() if any(p.GetPrimPath() in self._graph_targets for p in targets): self._refresh_window() else: super()._on_usd_changed(notice, stage) def _delay_refresh_window(self): self._pending_rebuild_task = asyncio.ensure_future(self._refresh_window()) def _refresh_window(self): """Refreshes the entire property window""" selection = omni.usd.get_context().get_selection() selected_paths = selection.get_selected_prim_paths() window = omni.kit.window.property.get_window()._window # noqa: PLW0212 selection.clear_selected_prim_paths() window.frame.rebuild() selection.set_selected_prim_paths(selected_paths, True) window.frame.rebuild() def __on_set_default_callback(self, paths: List[Sdf.Path], attr_name: str): """ Callback triggered when a model is set to the default value. Instead of reverting to a default value, this will remove the property instead """ stage = omni.usd.get_context().get_stage() for p in paths: prop_path = p.AppendProperty(attr_name) if stage.GetAttributeAtPath(prop_path).IsValid(): omni.kit.commands.execute("RemoveProperty", prop_path=prop_path) def __build_fn_intercept( self, src_build_fn, stage, attr_name, metadata, property_type, prim_paths: List[Sdf.Path], additional_label_kwargs=None, additional_widget_kwargs=None, ): """Build function that leverages an existing build function and sets the model default value callback""" models = src_build_fn( stage, attr_name, metadata, property_type, prim_paths, additional_label_kwargs, additional_widget_kwargs ) # Set a callback when the default is set so that it will do the same operation as remove # Replace the is_different_from_default method to change the behaviour of the reset to default widget if models: if issubclass(type(models), UsdBase): models.set_on_set_default_fn(partial(self.__on_set_default_callback, prim_paths, attr_name)) models.is_different_from_default = types.MethodType(is_different_from_default_override, models) elif hasattr(models, "__iter__"): for model in models: if issubclass(type(model), UsdBase): model.set_on_set_default_fn(partial(self.__on_set_default_callback, prim_paths, attr_name)) model.is_different_from_default = types.MethodType(is_different_from_default_override, model) return models class OmniGraphVariablesPropertiesWidget(UsdPropertiesWidget): """Widget for the graph""" def __init__(self, title: str): super().__init__(title, collapsed=False) self._title = title def destroy(self): pass def on_new_payload(self, payload): if not super().on_new_payload(payload): return False if not self._payload or len(self._payload) == 0: return False for prim_path in payload: prim = self._get_prim(prim_path) if not prim: return False is_graph_type = prim.GetTypeName() == COMPUTEGRAPH_TYPE_NAME attrs = prim.GetProperties() for attr in attrs: attr_name_str = attr.GetName() if is_graph_type and attr_name_str.startswith(GRAPH_VARIABLE_ATTR_PREFIX): return True return False return False def _filter_props_to_build(self, props): return [prop for prop in props if prop.GetName().startswith(GRAPH_VARIABLE_ATTR_PREFIX)] def _filter_target_lambda(self, target_prim): return target_prim.GetTypeName() == COMPUTEGRAPH_TYPE_NAME def get_additional_kwargs(self, ui_attr): random_prim = Usd.Prim() if self._payload: prim_paths = self._payload.get_paths() for prim_path in prim_paths: prim = self._get_prim(prim_path) if not prim: continue if not random_prim: random_prim = prim elif random_prim.GetTypeName() != prim.GetTypeName(): break return None, None def _customize_props_layout(self, attrs): for attr in attrs: if attr.attr_name.startswith(GRAPH_VARIABLE_ATTR_PREFIX): var_offset = attr.attr_name.rindex(":") + 1 display_name = attr.attr_name[var_offset:] attr.override_display_name(display_name) with ui.HStack(spacing=HORIZONTAL_SPACING): ui.Label("Initial", alignment=ui.Alignment.RIGHT) ui.Label("Runtime", alignment=ui.Alignment.RIGHT) return attrs def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]): metadata = ui_prop.metadata type_name = metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type") sdf_type_name = Sdf.ValueTypeNames.Find(type_name) if sdf_type_name.type == Sdf.ValueTypeNames.TokenArray.type: ui_prop.build_fn = build_token_array_prop else: ui_prop.build_fn = build_variable_prop super().build_property_item(stage, ui_prop, prim_paths) class OmniGraphVariableBase: """Mixin base for OmnGraph variable runtime models""" def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict, change_on_edit_end=False, **kwargs, ): self._soft_range_min = None self._soft_range_max = None self._variable = None self._value = None self._context = None self._event_sub = None self._dirty = True graph_path = kwargs.get(VARIABLE_GRAPH_PATH, None) self._graph_path = graph_path.pathString attr = kwargs.get(VARIABLE_ATTR, None) self._variable_name = attr.GetBaseName() self._instance = kwargs.get(VARIABLE_INSTANCE_PATH, None) self._update_counter: float = 0 self._update_sub = ( omni.kit.app.get_app() .get_update_event_stream() .create_subscription_to_pop(self._on_update, name="OmniGraph Variable Runtime Properties") ) def _on_update(self, event): # Ideally, we would have fabric level notifications when a variable has been changed. But for now, just poll at # a fixed interval since variables can be set at any time, not just when a node computes self._update_counter += event.payload["dt"] if self._update_counter > AUTO_REFRESH_PERIOD: self._update_counter = 0 self._on_dirty() def clean(self): self._update_sub = None # unsubscribe from app update stream def get_value(self): return self._value def set_value(self, value): self._value = value def _update_value(self, force=False): if self._dirty or force: if self._variable is None: graph = og.get_graph_by_path(self._graph_path) if graph is not None: self._context = graph.get_default_graph_context() self._variable = graph.find_variable(self._variable_name) if self._variable is not None: self.set_value( self._variable.get(self._context) if self._instance is None else self._variable.get(self._context, self._instance.pathString) ) self._dirty = False def _on_dirty(self): pass def _set_dirty(self): self._dirty = True self._on_dirty() class OmniGraphVariableRuntimeModel(ui.AbstractValueModel, OmniGraphVariableBase): """Model for variable values at runtime""" def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict, change_on_edit_end=False, **kwargs, ): OmniGraphVariableBase.__init__( self, stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs ) ui.AbstractValueModel.__init__(self) def clean(self): OmniGraphVariableBase.clean(self) def get_value(self): return self._value def set_value(self, value): self._value = value def get_value_as_float(self) -> float: self._update_value() return float(self._value) if self._variable is not None else 0.0 def get_value_as_bool(self) -> bool: self._update_value() return bool(self._value) if self._variable is not None else False def get_value_as_int(self) -> int: self._update_value() return int(self._value) if self._variable is not None else 0 def get_value_as_string(self) -> str: self._update_value() return str(self._value) if self._variable is not None else "" def _on_dirty(self): self._value_changed() # tell widget that model value has changed class OmniGraphVectorVariableRuntimeModel(ui.AbstractItemModel, OmniGraphVariableBase): """Model for vector variable values at runtime""" def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], comp_count: int, tf_type: Tf.Type, self_refresh: bool, metadata: dict, **kwargs, ): OmniGraphVariableBase.__init__(self, stage, attribute_paths, self_refresh, metadata, False, **kwargs) ui.AbstractItemModel.__init__(self) self._comp_count = comp_count self._data_type_name = "Vec" + str(self._comp_count) + tf_type.typeName[-1] self._data_type = getattr(Gf, self._data_type_name) class UsdVectorItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # Create three models per component if self._data_type_name.endswith("i"): self._items = [UsdVectorItem(IntModel(self)) for i in range(self._comp_count)] else: self._items = [UsdVectorItem(FloatModel(self)) for i in range(self._comp_count)] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) self._edit_mode_counter = 0 def clean(self): OmniGraphVariableBase.clean(self) def _construct_vector_from_item(self): if self._data_type_name.endswith("i"): data = [item.model.get_value_as_int() for item in self._items] else: data = [item.model.get_value_as_float() for item in self._items] return self._data_type(data) def _on_value_changed(self, item): """Called when the submodel is changed""" if self._edit_mode_counter > 0: vector = self._construct_vector_from_item() index = self._items.index(item) if vector and self.set_value(vector, index): # Read the new value back in case hard range clamped it item.model.set_value(self._value[index]) self._item_changed(item) else: # If failed to update value in model, revert the value in submodel item.model.set_value(self._value[index]) def _update_value(self, force=False): if OmniGraphVariableBase._update_value(self, force): if self._value is None: for i in range(len(self._items)): # noqa: PLC0200 self._items[i].model.set_value(0.0) return for i in range(len(self._items)): # noqa: PLC0200 self._items[i].model.set_value(self._value[i]) def set_value(self, value, comp=-1): pass def _on_dirty(self): self._item_changed(None) def get_item_children(self, item): """Reimplemented from the base class""" self._update_value() return self._items def get_item_value_model(self, item, column_id): """Reimplemented from the base class""" if item is None: return self._root_model return item.model def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls """ Reimplemented from the base class. Called when the user starts editing. """ self._edit_mode_counter += 1 def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls """ Reimplemented from the base class. Called when the user finishes editing. """ self._edit_mode_counter -= 1 class OmniGraphSingleChannelVariableRuntimeModel(OmniGraphVariableRuntimeModel): """Model for per-channel vector variable values at runtime""" def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], channel_index: int, self_refresh: bool, metadata: dict, change_on_edit_end=False, **kwargs, ): self._channel_index = channel_index self._soft_range_min = None self._soft_range_max = None super().__init__(stage, attribute_paths, self_refresh, metadata, False, **kwargs) def set_value(self, value, comp=-1): if comp == -1: super().set_value(value) elif hasattr(self._value, "__len__"): self._value[comp] = value def get_value_as_string(self, **kwargs) -> str: self._update_value() if self._value is None: return "" return str(self._value[self._channel_index]) def get_value_as_float(self) -> float: self._update_value() if self._value is None: return 0.0 if hasattr(self._value, "__len__"): return float(self._value[self._channel_index]) return float(self._value) def get_value_as_bool(self) -> bool: self._update_value() if self._value is None: return False if hasattr(self._value, "__len__"): return bool(self._value[self._channel_index]) return bool(self._value) def get_value_as_int(self) -> int: self._update_value() if self._value is None: return 0 if hasattr(self._value, "__len__"): return int(self._value[self._channel_index]) return int(self._value) def build_variable_prop( stage, attr_name, metadata, property_type, prim_paths: List[Sdf.Path], additional_label_kwargs=None, additional_widget_kwargs=None, ): """Variable widget that displays both initial (USD) and runtime (Fabric) values. This customized widget will be used for both the graph and graph instance on a prim. Make sure we return the models, since the UsdPropertiesWidget will listen for usd notices and update its models accordingly""" # For instanced graph, prim_path is the prim that the instance is on. For non-instanced graphs, prim is the graph # path. See which one we have prims = [stage.GetPrimAtPath(path) for path in prim_paths] attrs = [prim.GetAttribute(attr_name) for prim in prims] models = [] for idx, attr in enumerate(attrs): # if prim is an instance, need to get the graph path from the relationship and verify that a variable with # the given name is on the graph. Also handle the case where multiple graphs have the same variable (this is # not well supported at the moment, but the intention is for it to work) graphs = [] instances = [] if prims[idx].IsA(OmniGraphSchema.OmniGraph): graphs.append(attr.GetPrimPath()) instances.append(None) else: for g in prims[idx].GetProperty(OMNIGRAPHS_REL_ATTR).GetTargets(): graph = og.get_graph_by_path(g.pathString) if graph.find_variable(attr.GetBaseName()): graphs.append(g) instances.append(attr.GetPrimPath()) # TODO: if the graph is instanced, and the evaluation mode is automatic or instanced, then the runtime value # on the graph itself won't update. Only the value on the instance will. So grey out the runtime column for graph, instance in zip(graphs, instances): with ui.HStack(spacing=HORIZONTAL_SPACING): # Build the initial value widget that reads from USD model = UsdPropertiesWidgetBuilder.build( stage, attr_name, metadata, property_type, prim_paths, additional_label_kwargs, additional_widget_kwargs, ) if isinstance(model, list): models = models + model else: models.append(model) # Build runtime value widget which reads from fabric widget_kwargs = {"no_control_state": True} model_kwargs = {VARIABLE_ATTR: attr, VARIABLE_GRAPH_PATH: graph, VARIABLE_INSTANCE_PATH: instance} type_key = metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type") type_name = Sdf.ValueTypeNames.Find(type_key) if type_name.type in VECTOR_TYPES: # type_name.type is the tf_type widget_kwargs["model_cls"] = OmniGraphVectorVariableRuntimeModel widget_kwargs["single_channel_model_cls"] = OmniGraphSingleChannelVariableRuntimeModel else: widget_kwargs["model_cls"] = OmniGraphVariableRuntimeModel widget_kwargs["model_kwargs"] = model_kwargs model = UsdPropertiesWidgetBuilder.build( stage, attr_name, metadata, property_type, prim_paths, {"visible": False}, widget_kwargs ) if isinstance(model, list): models = models + model else: models.append(model) return models
34,283
Python
37.959091
120
0.595806
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_attribute_models.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 copy from typing import List import omni.ui as ui from omni.kit.property.usd.usd_attribute_model import FloatModel, IntModel from pxr import Gf, Sdf, Tf, Usd from .omnigraph_attribute_base import OmniGraphBase # noqa: PLE0402 # ============================================================================= class OmniGraphAttributeModel(ui.AbstractValueModel, OmniGraphBase): """The value model that is reimplemented in Python to watch an OmniGraph attribute path""" def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict, change_on_edit_end=False, **kwargs, ): OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs) ui.AbstractValueModel.__init__(self) def clean(self): OmniGraphBase.clean(self) def begin_edit(self): OmniGraphBase.begin_edit(self) ui.AbstractValueModel.begin_edit(self) def end_edit(self): OmniGraphBase.end_edit(self) ui.AbstractValueModel.end_edit(self) def get_value_as_string(self, elide_big_array=True) -> str: self._update_value() if self._value is None: return "" if self._is_big_array and elide_big_array: return "[...]" return str(self._value) def get_value_as_float(self) -> float: self._update_value() if self._value is None: return 0.0 if hasattr(self._value, "__len__"): return float(self._value[self._channel_index]) return float(self._value) def get_value_as_bool(self) -> bool: self._update_value() if self._value is None: return False if hasattr(self._value, "__len__"): return bool(self._value[self._channel_index]) return bool(self._value) def get_value_as_int(self) -> int: self._update_value() if self._value is None: return 0 if hasattr(self._value, "__len__"): return int(self._value[self._channel_index]) return int(self._value) def set_value(self, value): # noqa: PLW0221 FIXME: reconcile with base class calls if OmniGraphBase.set_value(self, value): self._value_changed() def _on_dirty(self): self._value_changed() # AbstractValueModel # ============================================================================= # OmniGraph Attribute Models need to use OmniGraphBase for their super class state rather than UsdBase # ----------------------------------------------------------------------------- class OmniGraphTfTokenAttributeModel(ui.AbstractItemModel, OmniGraphBase): class AllowedTokenItem(ui.AbstractItem): def __init__(self, item): super().__init__() self.token = item self.model = ui.SimpleStringModel(item) def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict): OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata) ui.AbstractItemModel.__init__(self) self._allowed_tokens = [] self._current_index = ui.SimpleIntModel() self._current_index.add_value_changed_fn(self._current_index_changed) self._updating_value = False self._has_index = False self._update_value() self._has_index = True def clean(self): OmniGraphBase.clean(self) def get_item_children(self, item): self._update_value() return self._allowed_tokens def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls OmniGraphBase.begin_edit(self) def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls OmniGraphBase.end_edit(self) def _current_index_changed(self, model): if not self._has_index: return # if we're updating from USD notice change to UI, don't call set_value if self._updating_value: return index = model.as_int if self.set_value(self._allowed_tokens[index].token): self._item_changed(None) def _get_allowed_tokens(self, attr): return attr.GetMetadata("allowedTokens") def _update_allowed_token(self, token_item=AllowedTokenItem): self._allowed_tokens = [] # For multi prim editing, the allowedTokens should all be the same attributes = self._get_attributes() attr = attributes[0] if len(attributes) > 0 else None if attr: for t in self._get_allowed_tokens(attr): self._allowed_tokens.append(token_item(t)) def _update_value(self, force=False): was_updating_value = self._updating_value self._updating_value = True if OmniGraphBase._update_value(self, force): # TODO don't have to do this every time. Just needed when "allowedTokens" actually changed self._update_allowed_token() index = -1 for i in range(0, len(self._allowed_tokens)): # noqa: PLC0200 if self._allowed_tokens[i].token == self._value: index = i if index not in (-1, self._current_index.as_int): self._current_index.set_value(index) self._item_changed(None) self._updating_value = was_updating_value def _on_dirty(self): self._item_changed(None) def get_value_as_token(self): index = self._current_index.as_int return self._allowed_tokens[index].token def is_allowed_token(self, token): return token in [allowed.token for allowed in self._allowed_tokens] # ----------------------------------------------------------------------------- class OmniGraphGfVecAttributeModel(ui.AbstractItemModel, OmniGraphBase): def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], comp_count: int, tf_type: Tf.Type, self_refresh: bool, metadata: dict, **kwargs, ): OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata, **kwargs) ui.AbstractItemModel.__init__(self) self._comp_count = comp_count self._data_type_name = "Vec" + str(self._comp_count) + tf_type.typeName[-1] self._data_type = getattr(Gf, self._data_type_name) class UsdVectorItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # Create three models per component if self._data_type_name.endswith("i"): self._items = [UsdVectorItem(IntModel(self)) for i in range(self._comp_count)] else: self._items = [UsdVectorItem(FloatModel(self)) for i in range(self._comp_count)] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) self._edit_mode_counter = 0 def clean(self): OmniGraphBase.clean(self) def _construct_vector_from_item(self): if self._data_type_name.endswith("i"): data = [item.model.get_value_as_int() for item in self._items] else: data = [item.model.get_value_as_float() for item in self._items] return self._data_type(data) def _on_value_changed(self, item): """Called when the submodel is changed""" if self._edit_mode_counter > 0: vector = self._construct_vector_from_item() index = self._items.index(item) if vector and self.set_value(vector, index): # Read the new value back in case hard range clamped it item.model.set_value(self._value[index]) self._item_changed(item) else: # If failed to update value in model, revert the value in submodel item.model.set_value(self._value[index]) def _update_value(self, force=False): if OmniGraphBase._update_value(self, force): if self._value is None: for i in range(len(self._items)): # noqa: PLC0200 self._items[i].model.set_value(0.0) return for i in range(len(self._items)): # noqa: PLC0200 self._items[i].model.set_value(self._value[i]) def _on_dirty(self): self._item_changed(None) def get_item_children(self, item): """Reimplemented from the base class""" self._update_value() return self._items def get_item_value_model(self, item, column_id): """Reimplemented from the base class""" if item is None: return self._root_model return item.model def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls """ Reimplemented from the base class. Called when the user starts editing. """ self._edit_mode_counter += 1 OmniGraphBase.begin_edit(self) def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls """ Reimplemented from the base class. Called when the user finishes editing. """ OmniGraphBase.end_edit(self) self._edit_mode_counter -= 1 # ----------------------------------------------------------------------------- class OmniGraphGfVecAttributeSingleChannelModel(OmniGraphAttributeModel): """Specialize version of GfVecAttributeSingleChannelModel""" def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], channel_index: int, self_refresh: bool, metadata: dict, change_on_edit_end=False, **kwargs, ): self._channel_index = channel_index super().__init__(stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs) def get_value_as_string(self, **kwargs) -> str: # noqa: PLW0221 FIXME: reconcile with base class calls self._update_value() if self._value is None: return "" return str(self._value[self._channel_index]) def get_value_as_float(self) -> float: self._update_value() if self._value is None: return 0.0 if hasattr(self._value, "__len__"): return float(self._value[self._channel_index]) return float(self._value) def get_value_as_bool(self) -> bool: self._update_value() if self._value is None: return False if hasattr(self._value, "__len__"): return bool(self._value[self._channel_index]) return bool(self._value) def get_value_as_int(self) -> int: self._update_value() if self._value is None: return 0 if hasattr(self._value, "__len__"): return int(self._value[self._channel_index]) return int(self._value) def set_value(self, value): if self._real_type is None: # FIXME: This Attribute does not have a corresponding OG attribute return vec_value = copy.copy(self._value) vec_value[self._channel_index] = value # Skip over our base class impl, because that is specialized for scaler if OmniGraphBase.set_value(self, vec_value, self._channel_index): self._value_changed() def is_different_from_default(self): """Override to only check channel""" if super().is_different_from_default(): return self._comp_different_from_default[self._channel_index] return False # ----------------------------------------------------------------------------- class OmniGraphGfQuatAttributeModel(ui.AbstractItemModel, OmniGraphBase): def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], tf_type: Tf.Type, self_refresh: bool, metadata: dict ): OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata) ui.AbstractItemModel.__init__(self) data_type_name = "Quat" + tf_type.typeName[-1] self._data_type = getattr(Gf, data_type_name) class UsdQuatItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # Create four models per component self._items = [UsdQuatItem(FloatModel(self)) for i in range(4)] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) self._edit_mode_counter = 0 def clean(self): OmniGraphBase.clean(self) def _on_value_changed(self, item): """Called when the submodel is chaged""" if self._edit_mode_counter > 0: quat = self._construct_quat_from_item() if quat and self.set_value(quat, self._items.index(item)): self._item_changed(item) def _update_value(self, force=False): if OmniGraphBase._update_value(self, force): for i in range(len(self._items)): # noqa: PLC0200 if i == 0: self._items[i].model.set_value(self._value.real) else: self._items[i].model.set_value(self._value.imaginary[i - 1]) def _on_dirty(self): self._item_changed(None) def get_item_children(self, item): """Reimplemented from the base class""" self._update_value() return self._items def get_item_value_model(self, item, column_id): """Reimplemented from the base class""" if item is None: return self._root_model return item.model def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls """ Reimplemented from the base class. Called when the user starts editing. """ self._edit_mode_counter += 1 OmniGraphBase.begin_edit(self) def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls """ Reimplemented from the base class. Called when the user finishes editing. """ OmniGraphBase.end_edit(self) self._edit_mode_counter -= 1 def _construct_quat_from_item(self): data = [item.model.get_value_as_float() for item in self._items] return self._data_type(data[0], data[1], data[2], data[3]) # ----------------------------------------------------------------------------- class OmniGraphGfMatrixAttributeModel(ui.AbstractItemModel, OmniGraphBase): def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], comp_count: int, tf_type: Tf.Type, self_refresh: bool, metadata: dict, ): OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata) ui.AbstractItemModel.__init__(self) self._comp_count = comp_count data_type_name = "Matrix" + str(self._comp_count) + tf_type.typeName[-1] self._data_type = getattr(Gf, data_type_name) class UsdMatrixItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # Create three models per component self._items = [UsdMatrixItem(FloatModel(self)) for i in range(self._comp_count * self._comp_count)] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) self._edit_mode_counter = 0 def clean(self): OmniGraphBase.clean(self) def _on_value_changed(self, item): """Called when the submodel is chaged""" if self._edit_mode_counter > 0: matrix = self._construct_matrix_from_item() if matrix and self.set_value(matrix, self._items.index(item)): self._item_changed(item) def _update_value(self, force=False): if OmniGraphBase._update_value(self, force): for i in range(len(self._items)): # noqa: PLC0200 self._items[i].model.set_value(self._value[i // self._comp_count][i % self._comp_count]) # noqa: S001 def _on_dirty(self): self._item_changed(None) # it's still better to call _value_changed for all child items for child in self._items: child.model._value_changed() # noqa: PLW0212 def get_item_children(self, item): """Reimplemented from the base class.""" self._update_value() return self._items def get_item_value_model(self, item, column_id): """Reimplemented from the base class.""" if item is None: return self._root_model return item.model def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls """ Reimplemented from the base class. Called when the user starts editing. """ self._edit_mode_counter += 1 OmniGraphBase.begin_edit(self) def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls """ Reimplemented from the base class. Called when the user finishes editing. """ OmniGraphBase.end_edit(self) self._edit_mode_counter -= 1 def _construct_matrix_from_item(self): data = [item.model.get_value_as_float() for item in self._items] matrix = [] for i in range(self._comp_count): matrix_row = [] for j in range(self._comp_count): matrix_row.append(data[i * self._comp_count + j]) matrix.append(matrix_row) return self._data_type(matrix) # ----------------------------------------------------------------------------- class OmniGraphSdfTimeCodeModel(OmniGraphAttributeModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._prev_real_values = None def _save_real_values_as_prev(self): # SdfTimeCode cannot be inited from another SdfTimeCode, only from float (double in C++).. self._prev_real_values = [Sdf.TimeCode(float(value)) for value in self._real_values]
19,393
Python
34.134058
118
0.582633
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/graph_variable_custom_layout.py
from functools import partial from typing import List import omni.graph.core as og import omni.ui as ui from carb import settings from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH from pxr import Sdf, Usd ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP} GRAPH_VARIABLE_PREFIX = "graph:variable:" COMPUTEGRAPH_TYPE_NAME = "OmniGraph" if settings.get_settings().get(og.USE_SCHEMA_PRIMS_SETTING) else "ComputeGraph" def is_usable(type_name: Sdf.ValueTypeName) -> bool: # returns if the given type can be used by OG return og.AttributeType.type_from_sdf_type_name(str(type_name)).base_type != og.BaseDataType.UNKNOWN def get_filtered_variables(prim: Usd.Prim) -> List[str]: # return only the USD attributes that start with the graph variable attribute prefix return [ attr.GetName()[len(GRAPH_VARIABLE_PREFIX) :] for attr in prim.GetAttributes() if not attr.IsHidden() and is_usable(attr.GetTypeName()) and attr.GetName().startswith(GRAPH_VARIABLE_PREFIX) ] class VariableNameModel(TfTokenAttributeModel): """Model for selecting the target attribute for the write/read operation. We modify the list to show attributes which are available on the target prim. """ class AllowedTokenItem(ui.AbstractItem): def __init__(self, item, label): """ Args: item: the attribute name token to be shown label: the label to show in the drop-down """ super().__init__() self.token = item self.model = ui.SimpleStringModel(label) def __init__( self, stage: Usd.Stage, variable_paths: List[Sdf.Path], self_refresh: bool, metadata: dict, node_prim_path: Sdf.Path, ): """ Args: stage: The current stage variable_paths: The list of full variable paths self_refresh: ignored metadata: pass-through metadata for model node_prim_path: The path of the compute node """ self._stage = stage self._node_prim_path = node_prim_path self._target_graph = None self._target_prim = None super().__init__(stage, variable_paths, self_refresh, metadata) def _get_allowed_tokens(self, _): # override of TfTokenAttributeModel to specialize what tokens to be shown return self._get_variables_of_interest() def _update_value(self, force=False): # override of TfTokenAttributeModel to refresh the allowed token cache self._update_allowed_token() super()._update_value(force) def _item_factory(self, item): # construct the item for the model label = item return VariableNameModel.AllowedTokenItem(item, label) def _update_allowed_token(self): # override of TfTokenAttributeModel to specialize the model items super()._update_allowed_token(token_item=self._item_factory) def _get_variables_of_interest(self) -> List[str]: # returns the attributes we want to let the user select from prim = self._stage.GetPrimAtPath(self._node_prim_path) variables = [] target = None rel = prim.GetRelationship("inputs:graph") if rel.IsValid(): targets = rel.GetTargets() if targets: target = self._stage.GetPrimAtPath(targets[0]) if target: variables = get_filtered_variables(target) self._target_prim = target # noqa: PLW0212 var_name_attr = prim.GetAttribute("inputs:variableName") if len(variables) > 0: current_value = var_name_attr.Get() if (current_value is not None) and (current_value != "") and (current_value not in variables): variables.append(current_value) variables.insert(0, "") else: var_name_attr.Set("") return variables class GraphVariableCustomLayout: _value_is_output = True def __init__(self, compute_node_widget): self.enable = True self.compute_node_widget = compute_node_widget self.graph_rel_widget = None self.variables = [] self.variable_name_model = None def _variable_name_build_fn(self, *args): # build the variableName widget stage = self.compute_node_widget.stage node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212 with ui.HStack(spacing=HORIZONTAL_SPACING): ui.Label("Variable Name", name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH) ui.Spacer(width=HORIZONTAL_SPACING) with ui.ZStack(): attr_path = node_prim_path.AppendProperty("inputs:variableName") self.variable_name_model = VariableNameModel(stage, [attr_path], False, {}, node_prim_path) ui.ComboBox(self.variable_name_model) def _filter_target_lambda(self, target_prim): return target_prim.GetTypeName() == COMPUTEGRAPH_TYPE_NAME def _graph_rel_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): # build the graph relationship widget stage = self.compute_node_widget.stage node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212 ui_prop.override_display_name("Graph") self.graph_rel_widget = UsdPropertiesWidgetBuilder._relationship_builder( # noqa: PLW0212 stage, ui_prop.prop_name, ui_prop.metadata, [node_prim_path], {"enabled": True, "style": ATTRIB_LABEL_STYLE}, { "enabled": True, "on_remove_target": self._on_graph_rel_changed, "target_picker_on_add_targets": self._on_graph_rel_changed, "targets_limit": 1, "target_picker_filter_lambda": self._filter_target_lambda, }, ) def _on_graph_rel_changed(self, *args): # when the inputs:graph changes, we dirty the variableName list model because the graph may have changed self.variable_name_model._set_dirty() # noqa: PLW0212 self.graph_rel_widget._set_dirty() # noqa: PLW0212 def apply(self, props): # called by compute_node_widget to apply UI when selection changes def find_prop(name): try: return next((p for p in props if p.prop_name == name)) except StopIteration: return None def value_build_fn(prop: UsdPropertyUiEntry): def build_fn(*args): # the resolved attribute is procedural and does not inherit the meta-data of the extended attribute # so we need to manually set the display name prop.override_display_name("Value") self.compute_node_widget.build_property_item( self.compute_node_widget.stage, prop, self.compute_node_widget._payload # noqa: PLW0212 ) return build_fn frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Inputs"): prop = find_prop("inputs:graph") if prop is not None: CustomLayoutProperty(None, None, build_fn=partial(self._graph_rel_build_fn, prop)) CustomLayoutProperty(None, None, build_fn=self._variable_name_build_fn) prop = find_prop("inputs:value") if prop is not None: CustomLayoutProperty(None, None, build_fn=value_build_fn(prop)) prop = find_prop("outputs:value") if prop is not None: with CustomLayoutGroup("Outputs"): CustomLayoutProperty(None, None, build_fn=value_build_fn(prop)) return frame.apply(props)
8,280
Python
40.613065
117
0.62186
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_attribute_builder.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. # from typing import List, Optional import omni.graph.core as og import omni.ui as ui from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH from pxr import Sdf, Tf, Usd from .omnigraph_attribute_base import get_model_cls # noqa: PLE0402 from .omnigraph_attribute_models import OmniGraphAttributeModel # noqa: PLE0402 from .omnigraph_attribute_models import OmniGraphGfVecAttributeModel # noqa: PLE0402 from .omnigraph_attribute_models import OmniGraphGfVecAttributeSingleChannelModel # noqa: PLE0402 from .omnigraph_attribute_models import OmniGraphSdfTimeCodeModel # noqa: PLE0402 from .omnigraph_attribute_models import OmniGraphTfTokenAttributeModel # noqa: PLE0402 # ============================================================================= def find_first_node_with_attrib(prim_paths: List[Sdf.Path], attr_name: str) -> Optional[og.Node]: """Returns the first node in the paths that has the given attrib name""" node_with_attr = None for prim_path in prim_paths: node = og.get_node_by_path(prim_path.pathString) if node and node.get_attribute_exists(attr_name): node_with_attr = node break return node_with_attr # ============================================================================= class OmniGraphPropertiesWidgetBuilder(UsdPropertiesWidgetBuilder): """OmniGraph specialization of USD widget factory based on OG API instead of USD""" OVERRIDE_TYPENAME_KEY = "OGTypeName" UNRESOLVED_TYPENAME = "OGUnresolvedType" tf_gf_matrix2d = Sdf.ValueTypeNames.Matrix2d tf_gf_matrix3d = Sdf.ValueTypeNames.Matrix3d tf_gf_matrix4d = Sdf.ValueTypeNames.Matrix4d @classmethod def init_builder_table(cls): # Make our own list of builder functions because we need `cls` to be us for the # classmethod callstack cls.widget_builder_table = { cls.tf_half: cls._floating_point_builder, cls.tf_float: cls._floating_point_builder, cls.tf_double: cls._floating_point_builder, cls.tf_uchar: cls._integer_builder, cls.tf_uint: cls._integer_builder, cls.tf_int: cls._integer_builder, cls.tf_int64: cls._integer_builder, cls.tf_uint64: cls._integer_builder, cls.tf_bool: cls._bool_builder, cls.tf_string: cls._string_builder, cls.tf_gf_vec2i: cls._vec2_per_channel_builder, cls.tf_gf_vec2h: cls._vec2_per_channel_builder, cls.tf_gf_vec2f: cls._vec2_per_channel_builder, cls.tf_gf_vec2d: cls._vec2_per_channel_builder, cls.tf_gf_vec3i: cls._vec3_per_channel_builder, cls.tf_gf_vec3h: cls._vec3_per_channel_builder, cls.tf_gf_vec3f: cls._vec3_per_channel_builder, cls.tf_gf_vec3d: cls._vec3_per_channel_builder, cls.tf_gf_vec4i: cls._vec4_per_channel_builder, cls.tf_gf_vec4h: cls._vec4_per_channel_builder, cls.tf_gf_vec4f: cls._vec4_per_channel_builder, cls.tf_gf_vec4d: cls._vec4_per_channel_builder, # FIXME: nicer matrix handling cls.tf_gf_matrix2d: cls._floating_point_builder, cls.tf_gf_matrix3d: cls._floating_point_builder, cls.tf_gf_matrix4d: cls._floating_point_builder, cls.tf_tf_token: cls._tftoken_builder, cls.tf_sdf_asset_path: cls._sdf_asset_path_builder, cls.tf_sdf_time_code: cls._time_code_builder, Tf.Type.Unknown: cls._unresolved_builder, } vec_model_dict = { "model_cls": OmniGraphGfVecAttributeModel, "single_channel_model_cls": OmniGraphGfVecAttributeSingleChannelModel, } cls.default_model_table = { # _floating_point_builder cls.tf_half: OmniGraphAttributeModel, cls.tf_float: OmniGraphAttributeModel, cls.tf_double: OmniGraphAttributeModel, # _integer_builder cls.tf_uchar: OmniGraphAttributeModel, cls.tf_uint: OmniGraphAttributeModel, cls.tf_int: OmniGraphAttributeModel, cls.tf_int64: OmniGraphAttributeModel, cls.tf_uint64: OmniGraphAttributeModel, # _bool_builder cls.tf_bool: OmniGraphAttributeModel, # _string_builder cls.tf_string: OmniGraphAttributeModel, # _vec2_per_channel_builder cls.tf_gf_vec2i: vec_model_dict, cls.tf_gf_vec2h: vec_model_dict, cls.tf_gf_vec2f: vec_model_dict, cls.tf_gf_vec2d: vec_model_dict, # _vec3_per_channel_builder cls.tf_gf_vec3i: vec_model_dict, cls.tf_gf_vec3h: vec_model_dict, cls.tf_gf_vec3f: vec_model_dict, cls.tf_gf_vec3d: vec_model_dict, # _vec4_per_channel_builder cls.tf_gf_vec4i: vec_model_dict, cls.tf_gf_vec4h: vec_model_dict, cls.tf_gf_vec4f: vec_model_dict, cls.tf_gf_vec4d: vec_model_dict, # FIXME: matrix models cls.tf_gf_matrix2d: OmniGraphAttributeModel, cls.tf_gf_matrix3d: OmniGraphAttributeModel, cls.tf_gf_matrix4d: OmniGraphAttributeModel, cls.tf_tf_token: { "model_cls": OmniGraphTfTokenAttributeModel, "no_allowed_tokens_model_cls": OmniGraphAttributeModel, }, cls.tf_sdf_time_code: OmniGraphSdfTimeCodeModel, # FIXME: Not converted yet # cls.tf_sdf_asset_path: cls._sdf_asset_path_builder, } @classmethod def startup(cls): cls.init_builder_table() @classmethod def _generate_tooltip_string(cls, attr_name, metadata): """Override tooltip to specialize extended types""" doc_string = metadata.get(Sdf.PropertySpec.DocumentationKey) type_name = metadata.get(OmniGraphPropertiesWidgetBuilder.OVERRIDE_TYPENAME_KEY, cls._get_type_name(metadata)) tooltip = f"{attr_name} ({type_name})" if not doc_string else f"{attr_name} ({type_name})\n\t\t{doc_string}" return tooltip @classmethod def build( cls, stage, attr_name, metadata, property_type, prim_paths: List[Sdf.Path], additional_label_kwargs=None, additional_widget_kwargs=None, ): if property_type == Usd.Attribute: type_name = cls._get_type_name(metadata) tf_type = type_name.type # Lookup the build func build_func = cls.widget_builder_table.get(tf_type, cls._fallback_builder) # Check for override the default attribute model(s) default_model = cls.default_model_table.get(tf_type, None) if isinstance(default_model, dict): additional_widget_kwargs.update(default_model) elif default_model: additional_widget_kwargs["model_cls"] = default_model # Output attributes should be read-only node_with_attr = find_first_node_with_attrib(prim_paths, attr_name) if node_with_attr: ogn_attr = node_with_attr.get_attribute(attr_name) if ogn_attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: additional_widget_kwargs["enabled"] = False return build_func( stage, attr_name, type_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs ) if property_type == Usd.Relationship: return cls._relationship_builder( stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs ) return None # ------------------------------------------------------------------------- # Builder function overrides @classmethod def _unresolved_builder( cls, stage, attr_name, type_name, metadata, prim_paths: List[Sdf.Path], additional_label_kwargs=None, additional_widget_kwargs=None, ): label_txt = attr_name node_with_attr = find_first_node_with_attrib(prim_paths, attr_name) if node_with_attr: ogn_attr = node_with_attr.get_attribute(attr_name) extended_type = ( "any" if ogn_attr.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY else "union" ) label_txt = f"<unresolved {extended_type}>" display_name = metadata.get(Sdf.PropertySpec.DisplayNameKey, attr_name) ui.Label(display_name, name="label", style={"alignment": ui.Alignment.RIGHT_CENTER}, width=LABEL_WIDTH) ui.Spacer(width=16) ui.Label(label_txt, name="label", style={"alignment": ui.Alignment.LEFT_CENTER, "color": 0xFF809095}) ui.Spacer(width=HORIZONTAL_SPACING) ui.Spacer(width=12) return [] @classmethod def _fallback_builder( cls, stage, attr_name, type_name, metadata, prim_paths: List[Sdf.Path], additional_label_kwargs=None, additional_widget_kwargs=None, ): with ui.HStack(spacing=HORIZONTAL_SPACING): model_cls = get_model_cls(OmniGraphAttributeModel, additional_widget_kwargs) model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata) label = cls._create_label(attr_name, metadata, additional_label_kwargs) kwargs = { "name": "models_readonly", "model": model, "enabled": False, "tooltip": model.get_value_as_string(), } if additional_widget_kwargs: kwargs.update(additional_widget_kwargs) with ui.ZStack(): value_widget = ui.StringField(**kwargs) value_widget.identifier = f"fallback_{attr_name}" mixed_overlay = cls._create_mixed_text_overlay() cls._create_control_state(value_widget=value_widget, mixed_overlay=mixed_overlay, **kwargs, label=label) return model
10,772
Python
42.092
118
0.612978
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/token_array_edit_widget.py
import weakref from functools import partial from typing import List import omni.ui as ui from omni.kit.property.usd.usd_attribute_model import UsdAttributeModel from pxr import Sdf, Vt class TokenArrayEditWidget: def __init__(self, stage, attr_name, prim_paths, metadata): self._model = UsdAttributeModel(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata) self._token_array_attrs = [stage.GetPrimAtPath(path).GetAttribute(attr_name) for path in prim_paths] self._frame = ui.Frame() self._frame.set_build_fn(self._build) def clean(self): self._model.clean() self._frame = None def _build(self): shared_tokens = None for attr in self._token_array_attrs: if attr.HasValue(): tokens = list(attr.Get()) else: tokens = [] if shared_tokens is None: shared_tokens = tokens elif shared_tokens != tokens: shared_tokens = None break with ui.VStack(spacing=2): if shared_tokens is not None: for i, token in enumerate(shared_tokens): with ui.HStack(spacing=2): token_model = ui.StringField(name="models").model token_model.set_value(token) def on_edit_element(value_model, weak_self, index): weak_self = weak_self() if weak_self: token_array = list(weak_self._token_array_attrs[0].Get()) # noqa: PLW0212 token_array[index] = value_model.as_string weak_self._model.set_value(Vt.TokenArray(token_array)) # noqa: PLW0212 token_model.add_end_edit_fn(partial(on_edit_element, weak_self=weakref.ref(self), index=i)) def on_remove_element(weak_self, index): weak_self = weak_self() if weak_self: token_array = list(weak_self._token_array_attrs[0].Get()) # noqa: PLW0212 token_array.pop(index) weak_self._model.set_value(Vt.TokenArray(token_array)) # noqa: PLW0212 ui.Button( "-", width=ui.Pixel(14), clicked_fn=partial(on_remove_element, weak_self=weakref.ref(self), index=i), ) def on_add_element(weak_self): weak_self = weak_self() if weak_self: token_array_attr = weak_self._token_array_attrs[0] # noqa: PLW0212 if token_array_attr.HasValue(): token_array = list(token_array_attr.Get()) else: token_array = [] token_array.append("") weak_self._model.set_value(Vt.TokenArray(token_array)) # noqa: PLW0212 ui.Button( "Add Element", width=ui.Pixel(30), clicked_fn=partial(on_add_element, weak_self=weakref.ref(self)) ) else: ui.StringField(name="models", read_only=True).model.set_value("Mixed") def _set_dirty(self): self._frame.rebuild() def build_token_array_prop( stage, attr_name, metadata, property_type, prim_paths: List[Sdf.Path], additional_label_kwargs=None, additional_widget_kwargs=None, ): with ui.HStack(spacing=4): label_kwargs = {"name": "label", "width": 160, "height": 18} ui.Label(attr_name, **label_kwargs) ui.Spacer(width=5) return TokenArrayEditWidget(stage, attr_name, prim_paths, metadata)
3,956
Python
37.048077
120
0.512133
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_window.py
"""Manager for the OmniGraph Toolkit window""" from contextlib import suppress import omni.graph.tools as ogt import omni.kit.ui as kit_ui import omni.ui as ui from ..metaclass import Singleton # noqa: PLE0402 from ..style import VSTACK_ARGS # noqa: PLE0402 from ..style import get_window_style # noqa: PLE0402 from .toolkit_frame_inspection import ToolkitFrameInspection from .toolkit_frame_memory import ToolkitFrameMemory from .toolkit_frame_output import ToolkitFrameOutput from .toolkit_frame_scene import ToolkitFrameScene MENU_PATH = "Window/Visual Scripting/Toolkit" # ====================================================================== class Toolkit(metaclass=Singleton): """Class containing all of the functionality for the OmniGraph Toolkit Window""" @staticmethod def get_name(): """Returns the name of this window extension""" return "OmniGraph Toolkit" # -------------------------------------------------------------------------------------------------------------- @staticmethod def get_description(): """Returns a description of this window extension""" return "Collection of utilities and inspectors to help in working with OmniGraph" # -------------------------------------------------------------------------------------------------------------- @staticmethod def get_menu_path(): """Returns the menu path where this window can be accessed""" return MENU_PATH # -------------------------------------------------------------------------------------------------------------- def __init__(self): """Set up the window elements - use show() for displaying the window""" # The window object self.__window = ui.Window( self.get_name(), width=800, height=500, menu_path=self.get_menu_path(), visible=False, visibility_changed_fn=self._visibility_changed_fn, ) self.__window.frame.set_style(get_window_style()) self.__window.frame.set_build_fn(self.__rebuild_window_frame) self.__window.frame.rebuild() # Manager for the debug output frame of the toolkit self.__frame_output = ToolkitFrameOutput() # Manager for the inspection frame of the toolkit self.__frame_inspection = ToolkitFrameInspection(self.__frame_output.set_debug_output) # Manager for the memory usage frame of the toolkit self.__frame_memory = ToolkitFrameMemory() # Manager for the scene manipulation frame of the toolkit self.__frame_scene = ToolkitFrameScene(self.__frame_output.set_debug_output) # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Destroy the singleton editor, if it exists""" with suppress(AttributeError): self.__window.visible = False with suppress(AttributeError): self.__window.frame.set_build_fn(None) # Ordering is important for ensuring owners destroy references last. ogt.destroy_property(self, "__frame_inspection") ogt.destroy_property(self, "__frame_output") ogt.destroy_property(self, "__frame_memory") ogt.destroy_property(self, "__frame_scene") ogt.destroy_property(self, "__window") self.__window = None Singleton.forget(Toolkit) # -------------------------------------------------------------------------------------------------------------- def show_window(self): """Display the window""" self.__window.visible = True def hide_window(self): self.__window.visible = False def _visibility_changed_fn(self, visible): editor_menu = 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 __rebuild_window_frame(self): """Construct the widgets within the window""" 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.__frame_memory.build() self.__frame_inspection.build() self.__frame_scene.build() self.__frame_output.build()
4,849
Python
41.920354
116
0.528563
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/__init__.py
"""Interface for the OmniGraph toolkit window""" from .toolkit_window import MENU_PATH, Toolkit
96
Python
31.333323
48
0.78125
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_frame_output.py
"""Handler for the debug output frame of the OmniGraph toolkit""" import asyncio import sys from contextlib import suppress from typing import Optional import carb import omni.graph.core as og import omni.graph.tools as ogt import omni.ui as ui from ..style import VSTACK_ARGS # noqa: PLE0402 from ..utils import DestructibleButton # noqa: PLE0402 # ====================================================================== class ToolkitFrameOutput: """Class containing all of the functionality for the debug output frame in the OmniGraph Toolkit Window Public Functions: build() : Construct the frame set_debug_output(output, tooltip): Define the text contents of the frame Layout of the class constants is stacked: Constants Initialize/Destroy Public Functions Build Functions Callback Functions """ # ---------------------------------------------------------------------- # Frame information ID = "FrameOutput" TITLE = "Debug Output" # ---------------------------------------------------------------------- # Maximum number of lines to show in the debug preview pane (limited to avoid overflow crash) DEBUG_PREVIEW_LINE_LIMIT = 10000 # ---------------------------------------------------------------------- # IDs for widgets ID_DEBUG_LABEL = "DebugOutputLabel" ID_DEBUG_CONTENTS = "DebugOutput" ID_TEXT_CLIPPED = "Clipped" # ---------------------------------------------------------------------- # Tooltip for the frame TOOLTIP = "View the output from the debugging functions" # -------------------------------------------------------------------------------------------------------------- def __init__(self): """Set up the frame elements - use build() for constructing the frame""" # Dictionary of widgets in the window self.__widgets = {} # Output text from various functions to show in an auxiliary frame self.__debug_output = "No output available yet" self.__debug_tooltip = self.TOOLTIP # Task for the delayed fade out of the clipboard message self.__delayed_fade_task = None # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Destroy the debug output frame""" with suppress(AttributeError, KeyError): self.__widgets[self.ID].set_build_fn(None) with suppress(AttributeError): self.__delayed_fade_task.cancel() # Ordering is important for ensuring owners destroy references last. ogt.destroy_property(self, "__widgets") # ---------------------------------------------------------------------- def build(self): """Construct the collapsable frame containing the debug output contents""" self.__widgets[self.ID] = ui.CollapsableFrame(title=self.TITLE, collapsed=False) self.__widgets[self.ID].set_build_fn(self.__rebuild_output_display_frame) # ---------------------------------------------------------------------- def set_debug_output(self, new_output: str, new_tooltip: Optional[str]): """Manually set new output data and update it""" self.__debug_output = new_output self.__debug_tooltip = new_tooltip if new_tooltip else self.TOOLTIP self.__on_debug_output_changed() sys.stdout.write(self.__debug_output) # ---------------------------------------------------------------------- def __rebuild_output_display_frame(self): """Construct and populate the display area for output from the serialization functions""" with self.__widgets[self.ID]: with ui.VStack(**VSTACK_ARGS): self.__widgets[self.ID_DEBUG_LABEL] = ui.Label( "Available in the Python variable omni.graph.core.DEBUG_DATA - (RMB to copy contents to clipboard)", style_type_name_override="Info", ) with ui.ZStack(): self.__widgets[self.ID_DEBUG_CONTENTS] = ui.Label( self.ID_DEBUG_CONTENTS, style_type_name_override="Code" ) self.__widgets[self.ID_TEXT_CLIPPED] = DestructibleButton( " ", height=ui.Percent(100), width=ui.Percent(100), alignment=ui.Alignment.CENTER_TOP, style={"background_color": 0x00000000, "color": 0xFF00FFFF}, mouse_pressed_fn=self.__on_copy_debug_output_to_clipboard, ) self.__on_debug_output_changed() # -------------------------------------------------------------------------------------------------------------- def __fade_clip_message(self): """Enable the clipboard message, then set a timer to remove it after 3 seconds.""" async def __delayed_fade(self): await asyncio.sleep(1.0) color = 0xFF00FFFF for _ in range(31): color -= 0x08000000 self.__widgets[self.ID_TEXT_CLIPPED].set_style({"background_color": 0x00000000, "color": color}) await asyncio.sleep(0.02) with suppress(KeyError): self.__widgets[self.ID_TEXT_CLIPPED].set_style({"background_color": 0x00000000, "color": 0xFF00FFFF}) self.__widgets[self.ID_TEXT_CLIPPED].text = " " with suppress(Exception): self.__delayed_fade_task.cancel() carb.log_info("Copied debug output to the clipboard") self.__widgets[self.ID_TEXT_CLIPPED].text = "Debug Output Clipped" self.__delayed_fade_task = asyncio.ensure_future(__delayed_fade(self)) # ---------------------------------------------------------------------- def __on_debug_output_changed(self): """Callback executed whenever any data affecting the debug output has changed""" def find_max_line_end(full_string: str): index = -1 for _ in range(self.DEBUG_PREVIEW_LINE_LIMIT + 1): index = full_string.find("\n", index + 1) if index < 0: break return index with suppress(KeyError): if self.__debug_output and self.__debug_output.count("\n") > self.DEBUG_PREVIEW_LINE_LIMIT: last_line_ends = find_max_line_end(self.__debug_output) if last_line_ends > 0: self.__widgets[self.ID_DEBUG_CONTENTS].text = self.__debug_output[: last_line_ends + 1] + "...\n" else: self.__widgets[self.ID_DEBUG_CONTENTS].text = self.__debug_output og.DEBUG_DATA = self.__debug_output self.__widgets[self.ID_DEBUG_LABEL].set_tooltip(self.__debug_tooltip) # ---------------------------------------------------------------------- def __on_copy_debug_output_to_clipboard(self, x, y, button, modifier): """Callback executed when right-clicking on the output location""" if button != 1: return try: import pyperclip pyperclip.copy(self.__debug_output) self.__fade_clip_message() except ImportError: carb.log_warn("Could not import pyperclip.")
7,387
Python
43.239521
120
0.512387
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_frame_inspection.py
"""Handler for the inspection frame of the OmniGraph toolkit""" from contextlib import suppress from typing import Callable import omni.graph.tools as ogt import omni.ui as ui from ..style import VSTACK_ARGS from .widgets.categories import ToolkitWidgetCategories from .widgets.extension_dependencies import ToolkitWidgetExtensionDependencies from .widgets.extension_timing import ToolkitWidgetExtensionTiming from .widgets.fabric_contents import ToolkitWidgetFabricContents from .widgets.graph_registry import ToolkitWidgetGraphRegistry from .widgets.graph_structure import ToolkitWidgetGraphStructure # ====================================================================== class ToolkitFrameInspection: """Class containing all of the functionality for the inspection frame of the OmniGraph Toolkit Window""" # ---------------------------------------------------------------------- # Frame information ID = "FrameInspection" TITLE = "OmniGraph Object Inspection" # ---------------------------------------------------------------------- # IDs for widgets ID_INSPECTION_LABEL = "Inspection" # -------------------------------------------------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): """Set up the frame elements - use build() for constructing the frame""" # Dictionary of widgets in the window self.__widgets = {} # Dictionary of widget classes in the window self.__widget_classes = [] # Callback to use for reporting new output self.__set_output = set_output_callback # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Destroy the frame""" with suppress(AttributeError, KeyError): self.__widgets[self.ID].set_build_fn(None) # Ordering is important for ensuring owners destroy references last. ogt.destroy_property(self, "__widgets") ogt.destroy_property(self, "__widget_classes") # __widget_models are destroyed when __widgets are destroyed # ---------------------------------------------------------------------- def build(self): """Construct the collapsable frame containing the inspection operations""" self.__widgets[self.ID] = ui.CollapsableFrame(title=self.TITLE, collapsed=False) self.__widgets[self.ID].set_build_fn(self.__rebuild_inspection_frame) # ---------------------------------------------------------------------- def __rebuild_inspection_frame(self): """Construct the widgets for running inspection operations""" self.__widget_classes.append(ToolkitWidgetFabricContents(self.__set_output)) self.__widget_classes.append(ToolkitWidgetGraphStructure(self.__set_output)) self.__widget_classes.append(ToolkitWidgetGraphRegistry(self.__set_output)) self.__widget_classes.append(ToolkitWidgetCategories(self.__set_output)) self.__widget_classes.append(ToolkitWidgetExtensionDependencies(self.__set_output)) self.__widget_classes.append(ToolkitWidgetExtensionTiming(self.__set_output)) with self.__widgets[self.ID]: self.__widgets[self.ID_INSPECTION_LABEL] = ui.Label("", style_type_name_override="Code") with ui.VStack(**VSTACK_ARGS, name="main_vertical_stack"): for widget in self.__widget_classes: with ui.HStack(width=0, spacing=10): widget.build()
3,583
Python
48.09589
116
0.581915
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_utils.py
"""An assortment of utilities shared by various pieces of the toolkit""" import os import omni.ui as ui from ..utils import DestructibleImage, get_icons_dir __all__ = ["help_button"] # ---------------------------------------------------------------------- def help_button(callback) -> ui.Image: """Build the standard help button with a defined callback when the mouse button is pressed""" with ui.HStack(spacing=10): button = DestructibleImage( os.path.join(get_icons_dir(), "help.svg"), width=20, height=20, mouse_pressed_fn=callback, tooltip="Show the help information for the inspector on the object", ) return button
714
Python
30.086955
97
0.578431
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_frame_scene.py
"""Handler for the scene manipulation frame of the OmniGraph toolkit""" from contextlib import suppress from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt import omni.ui as ui from ..style import VSTACK_ARGS from .widgets.extensions_all import ToolkitWidgetExtensionsAll from .widgets.extensions_missing import ToolkitWidgetExtensionsMissing from .widgets.extensions_used import ToolkitWidgetExtensionsUsed from .widgets.ogn_from_node import ToolkitWidgetOgnFromNode # ====================================================================== class ToolkitFrameScene: """Class containing all of the functionality for the scene manipulation frame of the OmniGraph Toolkit Window Public Functions: build() : Construct the frame """ # ---------------------------------------------------------------------- # Frame information ID = "FrameScene" TITLE = "OmniGraph Scene Manipulation" # ---------------------------------------------------------------------- # Layout constants specific to this frame FLAG_COLUMN_WIDTH = 80 # ---------------------------------------------------------------------- # Labels for widgets LABEL_SCENE = "Scene" # -------------------------------------------------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): """Set up the frame elements - use build() for constructing the frame""" # Dictionary of widgets in the window self.__widgets = {} # Dictionary of widget managers in the window self.__widget_managers = [] # Callback to use for reporting new output self.__set_output = set_output_callback # Manager for the per-extension information self.__extension_information = og.ExtensionInformation() # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Destroy the frame""" with suppress(AttributeError, KeyError): self.__widgets[self.ID].set_build_fn(None) # Ordering is important for ensuring owners destroy references last. ogt.destroy_property(self, "__widgets") ogt.destroy_property(self, "__widget_managers") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Construct the collapsable frame containing the inspection operations""" self.__widgets[self.ID] = ui.CollapsableFrame(title=self.TITLE, collapsed=False) self.__widgets[self.ID].set_build_fn(self.__rebuild_scene_frame) # ---------------------------------------------------------------------- def __rebuild_scene_frame(self): """Construct the widgets for running inspection operations""" self.__widget_managers.append(ToolkitWidgetExtensionsUsed(self.__set_output, self.__extension_information)) self.__widget_managers.append(ToolkitWidgetExtensionsMissing(self.__set_output, self.__extension_information)) self.__widget_managers.append(ToolkitWidgetExtensionsAll(self.__set_output, self.__extension_information)) self.__widget_managers.append(ToolkitWidgetOgnFromNode(self.__set_output)) with self.__widgets[self.ID]: self.__widgets[self.LABEL_SCENE] = ui.Label("", style_type_name_override="Code") with ui.VStack(**VSTACK_ARGS, name="main_vertical_stack"): with ui.HStack(width=0, spacing=10): for widget in self.__widget_managers: widget.build()
3,696
Python
44.641975
118
0.559253
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_frame_memory.py
"""Handler for the memory usage frame of the OmniGraph toolkit""" import omni.graph.core as og import omni.graph.tools as ogt import omni.ui as ui from ..style import BUTTON_WIDTH # noqa: PLE0402 from ..style import name_value_hstack # noqa: PLE0402 from ..style import name_value_label # noqa: PLE0402 from ..utils import DestructibleButton # noqa: PLE0402 # ====================================================================== class ToolkitFrameMemory: """Class containing all of the functionality for the memory usage frame in the OmniGraph Toolkit Window Public Functions: build() : Construct the frame Layout of the class constants is stacked: Constants Initialize/Destroy Public Functions Build Functions Callback Functions """ # ---------------------------------------------------------------------- # Frame information ID = "FrameMemory" TITLE = "Memory Usage" # ---------------------------------------------------------------------- # IDs for widgets ID_BTN_UPDATE_MEMORY = "UpdateMemoryUsed" ID_MEMORY_USED = "MemoryUsed" # ---------------------------------------------------------------------- # Tooltips for the editable widgets TOOLTIPS = { ID_MEMORY_USED: "How much memory is currently being used by OmniGraph?", ID_BTN_UPDATE_MEMORY: "Update the memory usage for the current OmniGraph", } # -------------------------------------------------------------------------------------------------------------- def __init__(self): """Set up the frame elements - use build() for constructing the frame""" # Dictionary of widgets in the window self.__widgets = {} # Dictionary of data models belonging to widgets in the window self.__widget_models = {} # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Destroy the memory usage frame""" # Ordering is important for ensuring owners destroy references last. ogt.destroy_property(self, "__widgets") # __widget_models are destroyed when __widgets are destroyed # ---------------------------------------------------------------------- def build(self): """Construct the widgets used in the memory usage section""" with name_value_hstack(): name_value_label("Memory Used By Graph:") model = ui.SimpleIntModel(0) self.__widgets[self.ID_MEMORY_USED] = ui.IntField( model=model, width=100, name=self.ID_MEMORY_USED, tooltip=self.TOOLTIPS[self.ID_MEMORY_USED], alignment=ui.Alignment.LEFT_CENTER, ) self.__widget_models[self.ID_MEMORY_USED] = model self.__widgets[self.ID_BTN_UPDATE_MEMORY] = DestructibleButton( "Update Memory Used", name=self.ID_BTN_UPDATE_MEMORY, width=BUTTON_WIDTH, tooltip=self.TOOLTIPS[self.ID_BTN_UPDATE_MEMORY], clicked_fn=self.__on_update_memory_used_button, ) # -------------------------------------------------------------------------------------------------------------- def __on_update_memory_used_button(self): """Callback executed when the Update Memory Used button is clicked""" ctx = og.get_compute_graph_contexts()[0] self.__widget_models[self.ID_MEMORY_USED].set_value(og.OmniGraphInspector().memory_use(ctx))
3,608
Python
40.965116
116
0.502494
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extension_timing.py
"""Support for the toolkit widget that shows OmniGraph-related timing for all extensions. The output is a dictionary of extension timing information with a legend: .. code-block:: json { "Extension Processing Timing": { "legend": { "Key": "Extension ID", "Value": [ "Registration Of Python Nodes", "Deregistration Of Python Nodes" ] }, "timing": { "omni.graph.examples.python": [ 12345, 12367 ] } } } """ import json from contextlib import suppress from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt from ...style import BUTTON_WIDTH from ...utils import DestructibleButton __all__ = ["ToolkitWidgetExtensionTiming"] # ============================================================================================================== class ToolkitWidgetExtensionTiming: ID = "DumpExtensionTiming" LABEL = "Extension Processing Timing" TOOLTIP = "Dump information on timing of per-extension operations initiated by OmniGraph" RESULTS_TOOLTIP = "Timing information of per-extension operations initiated by OmniGraph - see 'legend' for details" # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): self.__button = None self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the extension information""" self.__button = DestructibleButton( self.LABEL, name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button # -------------------------------------------------------------------------------------------------------------- def __on_click(self): """Callback executed when the Extensions All button is clicked""" try: ext_info = og._PublicExtension # noqa: PLW0212 ext_ids = set(ext_info.REGISTRATION_TIMING.keys()).union(set(ext_info.DEREGISTRATION_TIMING.keys())) extension_timing_information = {} for ext_id in ext_ids: registration_timing = None deregistration_timing = None with suppress(KeyError): registration_timing = ext_info.REGISTRATION_TIMING[ext_id] / 1000000.0 with suppress(KeyError): deregistration_timing = ext_info.DEREGISTRATION_TIMING[ext_id] / 1000000.0 extension_timing_information[ext_id] = [registration_timing, deregistration_timing] text = json.dumps( { self.LABEL: { "legend": { "Key": "Extension ID", "Value": ["Registration Of Python Nodes (ms)", "Deregistration Of Python Nodes (ms)"], }, "timing": extension_timing_information, } }, indent=4, ) except Exception as error: # noqa: PLW0703 text = str(error) self.__set_output(text, self.RESULTS_TOOLTIP)
3,804
Python
37.434343
120
0.492639
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/ogn_from_node.py
"""Support for the widget that dumps the categories OmniGraph knows about.""" import json from typing import Callable import carb import omni.graph.core as og import omni.graph.tools as ogt import omni.usd from ...style import BUTTON_WIDTH from ...utils import DestructibleButton __all__ = ["ToolkitWidgetOgnFromNode"] # ============================================================================================================== class ToolkitWidgetOgnFromNode: ID = "OgnFromNode" LABEL = "Generate .ogn From Selected Node" TOOLTIP = "Generate a .ogn definition that matches the contents of the selected node (one node only)" RESULTS_TOOLTIP = ".ogn file that describes the selected node" # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): self.__button = None self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the list of nodes and their extensions from the scene""" self.__button = DestructibleButton( self.LABEL, name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button # -------------------------------------------------------------------------------------------------------------- def __on_click(self): """Callback executed when the OGN From Node button is clicked""" try: selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths() if not selected_paths: text = "Select a node to generate the .ogn file for it" else: omnigraph_nodes = [] prims = [] graph = og.get_current_graph() for path in selected_paths: node = graph.get_node(path) if node.is_valid(): omnigraph_nodes.append(node) else: prims.append(omni.usd.get_context().get_stage().GetPrimAtPath(path)) if not omnigraph_nodes: # TODO: Most of the .ogn information could be generated from a plain prim as well text = "Select an OmniGraph node to generate the .ogn file for it" else: if len(omnigraph_nodes) > 1: carb.log_warn(f"More than one node selected. Only generating the first one - {selected_paths}") generated_ogn = og.generate_ogn_from_node(omnigraph_nodes[0]) text = json.dumps(generated_ogn, indent=4) except Exception as error: # noqa: PLW0703 text = str(error) self.__set_output(text, self.RESULTS_TOOLTIP)
3,243
Python
42.837837
119
0.50848
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extensions_all.py
"""Support for the widget that dumps the categories OmniGraph knows about.""" import json from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt from ...style import BUTTON_WIDTH from ...utils import DestructibleButton __all__ = ["ToolkitWidgetExtensionsAll"] # ============================================================================================================== class ToolkitWidgetExtensionsAll: ID = "ExtensionsAll" LABEL = "Nodes In All Extensions" TOOLTIP = "List all known extensions containing OmniGraph nodes and the nodes they contain" RESULTS_TOOLTIP = "All known extensions containing OmniGraph nodes and the nodes they contain" # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable, extension_information: og.ExtensionInformation): self.__button = None self.__extension_information = extension_information self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__extension_information") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the list of nodes and their extensions from the scene""" self.__button = DestructibleButton( self.LABEL, name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button # -------------------------------------------------------------------------------------------------------------- def __on_click(self): """Callback executed when the Extensions All button is clicked""" try: enabled_extensions, disabled_extensions = self.__extension_information.get_node_types_by_extension() text = json.dumps({"enabled": enabled_extensions, "disabled": disabled_extensions}, indent=4) except Exception as error: # noqa: PLW0703 text = str(error) self.__set_output(text, self.RESULTS_TOOLTIP)
2,426
Python
43.127272
119
0.54493
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extensions_missing.py
"""Support for the widget that dumps the categories OmniGraph knows about.""" from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt from ...style import BUTTON_WIDTH from ...utils import DestructibleButton __all__ = ["ToolkitWidgetExtensionsMissing"] # ============================================================================================================== class ToolkitWidgetExtensionsMissing: ID = "ExtensionsMissing" LABEL = "Node Extensions Missing" TOOLTIP = "List any extensions required by OmniGraph nodes in the scene that are not currently enabled" RESULTS_TOOLTIP = "Extensions required by OmniGraph nodes in the scene that are not currently enabled" # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable, extension_information: og.ExtensionInformation): self.__button = None self.__extension_information = extension_information self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__extension_information") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the list of nodes and their extensions from the scene""" self.__button = DestructibleButton( self.LABEL, name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button # -------------------------------------------------------------------------------------------------------------- def __on_click(self): """Callback executed when the Extensions Missing button is clicked""" try: _, disabled_node_types = self.__extension_information.get_nodes_by_extension() try: text = str(disabled_node_types) except KeyError: text = "[]" except Exception as error: # noqa: PLW0703 text = str(error) self.__set_output(text, self.RESULTS_TOOLTIP)
2,444
Python
41.894736
119
0.530687
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/graph_registry.py
"""Support for the widget that dumps the categories OmniGraph knows about.""" from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt import omni.ui as ui from ...style import BUTTON_WIDTH from ...utils import DestructibleButton from ..toolkit_utils import help_button from .flag_manager import FlagManager __all__ = ["ToolkitWidgetGraphRegistry"] # ============================================================================================================== class ToolkitWidgetGraphRegistry: ID = "DumpGraphRegistry" TOOLTIP = "Dump the contents of the current OmniGraph registry to the console" FLAGS = { "jsonFlagAttributes": ("attributes", "Show the attributes on registered node types", False), "jsonFlagDetails": ("nodeTypes", "Show the details of the registered node types", False), } # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): self.__button = None self.__flag_managers = {} self.__help_button = None self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__flag_managers") ogt.destroy_property(self, "__help_button") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the graph registry""" self.__button = DestructibleButton( "Dump Registry", name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True)) assert self.__help_button for checkbox_id, (flag, tooltip, default_value) in self.FLAGS.items(): self.__flag_managers[checkbox_id] = FlagManager(checkbox_id, flag, tooltip, default_value) with ui.HStack(spacing=5): self.__flag_managers[checkbox_id].checkbox() # -------------------------------------------------------------------------------------------------------------- def __on_click(self, force_help: bool = False): """Callback executed when the Dump Registry button is clicked""" if force_help: flags = ["help"] else: flags = [flag_manager.name for flag_manager in self.__flag_managers.values() if flag_manager.is_set] tooltip = f"OmniGraph registry contents, filtered with flags {flags}" text = og.OmniGraphInspector().as_json(og.GraphRegistry(), flags=flags) self.__set_output(text, tooltip)
3,007
Python
41.366197
116
0.545727
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/flag_manager.py
"""Helper to manage a checkbox flag from a list that are attached to various widgets""" import omni.graph.tools as ogt import omni.ui as ui # ============================================================================================================== class FlagManager: """Base class to manage values and checkboxes for flags attached to inspection widgets""" FLAG_COLUMN_WIDTH = 80 """Constant width used for flag checkboxes""" def __init__(self, flag_id: str, flag_name: str, flag_tooltip: str, flag_default: bool): self.__id = flag_id self.__name = flag_name self.__tooltip = flag_tooltip self.__value = flag_default self.__default_value = flag_default self.__checkbox = None self.__checkbox_model = None # -------------------------------------------------------------------------------------------------------------- def destroy(self): ogt.destroy_property(self, "__id") ogt.destroy_property(self, "__name") ogt.destroy_property(self, "__tooltip") ogt.destroy_property(self, "__default_value") ogt.destroy_property(self, "__value") ogt.destroy_property(self, "__checkbox_model") ogt.destroy_property(self, "__checkbox") # -------------------------------------------------------------------------------------------------------------- @property def default_value(self) -> str: """Returns the default value of this flag as it will be used by the inspector""" return self.__default_value # -------------------------------------------------------------------------------------------------------------- @property def name(self) -> str: """Returns the name of this flag as it will be used by the inspector""" return self.__name # -------------------------------------------------------------------------------------------------------------- @property def tooltip(self) -> str: """Returns the tooltip of this flag as it will be used by the inspector""" return self.__tooltip # -------------------------------------------------------------------------------------------------------------- @property def is_set(self) -> bool: """Returns True if the flag is currently set to True""" return self.__value # -------------------------------------------------------------------------------------------------------------- def __on_flag_set(self, mouse_x: int, mouse_y: int, mouse_button: int, value: str): """Callback executed when there is a request to change status of one of the inspection flags""" if mouse_button == 0: new_flag_value = not self.__checkbox.model.as_bool self.__value = new_flag_value # -------------------------------------------------------------------------------------------------------------- def checkbox(self): """Define the checkbox that manages this flag's value""" self.__checkbox_model = ui.SimpleIntModel(self.__value) self.__checkbox = ui.CheckBox( model=self.__checkbox_model, alignment=ui.Alignment.RIGHT_BOTTOM, mouse_released_fn=self.__on_flag_set, name=self.__id, width=0, tooltip=self.__tooltip, style_type_name_override="WhiteCheck", ) ui.Label(self.__name, alignment=ui.Alignment.LEFT_TOP, width=self.FLAG_COLUMN_WIDTH, tooltip=self.__tooltip)
3,513
Python
44.636363
116
0.45232
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/graph_structure.py
"""Support for the widget that dumps the categories OmniGraph knows about.""" import json from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt import omni.ui as ui from ...style import BUTTON_WIDTH from ...utils import DestructibleButton from ..toolkit_utils import help_button from .flag_manager import FlagManager __all__ = ["ToolkitWidgetGraphStructure"] # ============================================================================================================== class ToolkitWidgetGraphStructure: ID = "DumpGraphStructure" TOOLTIP = "Dump the contents of all OmniGraphs to the console" FLAGS = { "jsonFlagAttributes": ("attributes", "Show the attributes on nodes in the graph", False), "jsonFlagConnections": ("connections", "Show the connections between nodes in the graph", False), "jsonFlagEvaluation": ("evaluation", "Show the details of the graph evaluator", False), } # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): self.__button = None self.__flag_managers = {} self.__help_button = None self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__flag_managers") ogt.destroy_property(self, "__help_button") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the node type categories""" self.__button = DestructibleButton( "Dump Graph", name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True)) assert self.__help_button for checkbox_id, (flag, tooltip, default_value) in self.FLAGS.items(): self.__flag_managers[checkbox_id] = FlagManager(checkbox_id, flag, tooltip, default_value) with ui.HStack(spacing=5): self.__flag_managers[checkbox_id].checkbox() # -------------------------------------------------------------------------------------------------------------- def __on_click(self, force_help: bool = False): """Callback executed when the Dump Graph button is clicked""" if force_help: flags = ["help"] else: flags = [flag_manager.name for flag_manager in self.__flag_managers.values() if flag_manager.is_set] tooltip = f"OmniGraph contents, filtered with flags {flags}" graph_info = {} json_string = "Could not create output" for graph in og.get_all_graphs(): try: json_string = og.OmniGraphInspector().as_json(graph, flags=flags) graph_info[graph.get_path_to_graph()] = json.loads(json_string) except json.JSONDecodeError as error: self.__set_output(f"Error decoding json for graph {graph.get_path_to_graph()}: {error}\n{json_string}") return text = json.dumps(graph_info, indent=4) self.__set_output(text, tooltip)
3,552
Python
42.329268
119
0.549268
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extension_dependencies.py
"""Support for the toolkit widget that shows OmniGraph downstream dependencies. The output is in a hierarchy showing the dependencies of the various omni.graph extensions. Since these have their own internal dependencies you can find all OmniGraph dependencies just by looking at the list for omni.graph.core """ import asyncio import json from contextlib import suppress from pathlib import Path from typing import Callable, Dict, List, Tuple import carb import omni.graph.tools as ogt import omni.kit import omni.ui as ui from omni.kit.window.extensions.common import build_ext_info from ...style import BUTTON_WIDTH from ...utils import DestructibleButton from ..toolkit_utils import help_button from .flag_manager import FlagManager __all__ = ["ToolkitWidgetExtensionDependencies"] # ============================================================================================================== class ToolkitWidgetExtensionDependencies: ID = "DumpExtensionDependencies" LABEL = "Extensions" TOOLTIP = "Dump information on extension dependencies on OmniGraph" FLAGS = { "flagAll": ("all", "Include dependencies on all omni.graph extensions, not just omni.graph.core", False), "flagVerbose": ("verbose", "Include the list of nodes that are defined inside dependent extensions", False), } # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): self.__button = None self.__ext_information = {} self.__flag_managers = {} self.__help_button = None self.__set_output = set_output_callback self.__dependents_calculated = False self.__dependents_expansions_calculated = False # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__ext_information") ogt.destroy_property(self, "__flag_managers") ogt.destroy_property(self, "__help_button") ogt.destroy_property(self, "__set_output") ogt.destroy_property(self, "__dependents_calculated") ogt.destroy_property(self, "__dependents_expansions_calculated") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the extension information""" self.__button = DestructibleButton( self.LABEL, name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True)) assert self.__help_button for checkbox_id, (flag, tooltip, default_value) in self.FLAGS.items(): self.__flag_managers[checkbox_id] = FlagManager(checkbox_id, flag, tooltip, default_value) with ui.HStack(spacing=5): self.__flag_managers[checkbox_id].checkbox() # -------------------------------------------------------------------------------------------------------------- def __populate_extension_information(self): """Use the extension manager to find out all of the details for known extensions. Populates self.__ext_information as a dictionary where: KEY: Name of the extension (with version information stripped) VALUE: Tuple(ExtensionCommonInfo, Extension Dictionary) """ if self.__ext_information: return manager = omni.kit.app.get_app().get_extension_manager() carb.log_info("Syncing extension registry. May take a minute...") asyncio.ensure_future(omni.kit.app.get_app().next_update_async()) manager.sync_registry() # Make sure all extensions are available known_extensions = manager.fetch_extension_summaries() # Use the utility to convert all of the extension information into a more processing friendly format. # The latest version is used, although if we wanted to be thorough there would be entries for every version # since they could potentially have different dependencies. for extension in known_extensions: latest_version = extension["latest_version"] ext_id = latest_version["id"] ext_name = latest_version["name"] package_id = latest_version["package_id"] self.__ext_information[ext_name] = build_ext_info(ext_id, package_id) # -------------------------------------------------------------------------------------------------------------- def __expand_downstream_extension_dependencies(self, ext_name: str): """Expand the upstream dependencies of the given extension Args: ext_name: Name of the extension being expanded """ (_, ext_info) = self.__ext_information[ext_name] if ext_info.get("full_dependents", None) is not None: return ext_info["full_dependents"] ext_info["full_dependents"] = set() for ext_downstream in ext_info.get("dependents", []): ext_info["full_dependents"].add(ext_downstream) ext_info["full_dependents"].update(self.__expand_downstream_extension_dependencies(ext_downstream)) return ext_info["full_dependents"] # -------------------------------------------------------------------------------------------------------------- def __expand_downstream_dependencies(self): """Take the existing one-step dependencies and expand them into lists of everything upstream of an extension""" # Only do this once if self.__dependents_expansions_calculated: return self.__dependents_expansions_calculated = True for ext_name in self.__ext_information: self.__expand_downstream_extension_dependencies(ext_name) # -------------------------------------------------------------------------------------------------------------- def __create_downstream_dependencies(self): """Take the existing set of downstream dependencies on every extension and compute the equivalent upstream dependencies, adding them to the extension information """ # Only do this once if self.__dependents_calculated: return self.__dependents_calculated = True for ext_name, (_, ext_info) in self.__ext_information.items(): dependencies = ext_info.get("dependencies", {}) for ext_dependency in dependencies: with suppress(KeyError): (_, dependencies_info) = self.__ext_information[ext_dependency] dependencies_info["dependents"] = dependencies_info.get("dependents", []) + [ext_name] # -------------------------------------------------------------------------------------------------------------- def __get_dependent_output(self, ext_name: str) -> Dict[str, List[str]]: """Returns a dictionary of repo_name:extensions_in_repo that are dependents of the 'ext_name' extension""" (_, ext_info) = self.__ext_information[ext_name] dependencies_by_repo = {} for dependent in ext_info.get("full_dependents", []): with suppress(KeyError): repo = self.__ext_information[dependent][0].repository if not repo and self.__ext_information[dependent][0].is_kit_file: repo = "https://gitlab-master.nvidia.com/omniverse/kit" dependencies_by_repo[repo] = dependencies_by_repo.get(repo, set()) dependencies_by_repo[repo].add(dependent) return {repo: list(repo_dependencies) for repo, repo_dependencies in dependencies_by_repo.items()} # -------------------------------------------------------------------------------------------------------------- def __add_nodes_to_extensions( self, output: Dict[str, List[str]] ) -> Tuple[Dict[str, Dict[str, List[str]]], Dict[str, List[str]]]: """Take the dictionary of extension_repo:extension_names[] and add per-extension node information to return (extension_repo:{extension_name:nodes_in_extension},extension_repo:{extension_name[apps_using_extension]}) """ # If showing the nodes then transform the list of extension names to a dictionary of extension:node_list extensions_with_nodes = {} apps_with_nodes = {} for repo, repo_dependencies in output.items(): extensions_with_nodes[repo] = {} for ext_name in repo_dependencies: try: extensions_with_nodes[repo][ext_name] = [] ogn_node_file = Path(self.__ext_information[ext_name][0].path) / "ogn" / "nodes.json" if ogn_node_file.is_file(): with open(ogn_node_file, "r", encoding="utf-8") as nodes_fd: json_nodes = json.load(nodes_fd)["nodes"] extensions_with_nodes[repo][ext_name] = list(json_nodes.keys()) else: raise AttributeError except (AttributeError, KeyError, json.decoder.JSONDecodeError): if str(self.__ext_information[ext_name][0].path).endswith(".kit"): apps_with_nodes[repo] = apps_with_nodes.get(repo, []) + [ext_name] elif self.__ext_information[ext_name][0].is_local: extensions_with_nodes[repo][ext_name] = [] else: extensions_with_nodes[repo][ext_name] = "--- Install Extension To Get Node List ---" return extensions_with_nodes, apps_with_nodes # -------------------------------------------------------------------------------------------------------------- def __on_click(self, force_help: bool = False): """Callback executed when the Dump Graph button is clicked""" if force_help: flags = ["help"] text = ( "Dump the dependencies of other extensions on the OmniGraph extensions.\n" "The following flags are accepted:\n" ) for flag_manager in self.__flag_managers.values(): text += f" {flag_manager.name} ({flag_manager.default_value}): {flag_manager.tooltip}\n" self.__set_output(text, "Help Information") return flags = [flag_manager.name for flag_manager in self.__flag_managers.values() if flag_manager.is_set] tooltip = f"OmniGraph extension dependencies, filtered with flags {flags}" # Clean out the information so that the extensions can be reread each time. There is no callback when extensions # are installed or updated so this is the only way to ensure correct information. self.__ext_information = {} self.__dependents_calculated = False self.__dependents_expansions_calculated = False # Get all of the extension information for analysis self.__populate_extension_information() # If the "all" flag is set then scan the extensions to get the ones starting with omni.graph # Doing this instead of using a hardcoded list future-proofs us. omnigraph_extensions = ["omni.graph.core"] if "all" in flags: omnigraph_extensions = [] for ext_name in self.__ext_information: if ext_name.startswith("omni.graph"): omnigraph_extensions.append(ext_name) include_nodes = "verbose" in flags output = { "flags": { "verbose": include_nodes, "extensions": omnigraph_extensions, }, "paths": {ext: self.__ext_information[ext][0].path for ext in omnigraph_extensions}, "apps": {}, } # Add direct downstream dependencies to the extension info based on the known dependencies self.__create_downstream_dependencies() # Expand the entire downstream tree of dependencies for all extensions based on the computed edges self.__expand_downstream_dependencies() # Populate the per-extension output for each of the requested output extensions for ext_name in omnigraph_extensions: output[ext_name] = self.__get_dependent_output(ext_name) if include_nodes: (output[ext_name], output["apps"][ext_name]) = self.__add_nodes_to_extensions(output[ext_name]) # Pipe the output to the final destination self.__set_output(json.dumps(output, indent=4), tooltip)
12,847
Python
49.384314
120
0.572741
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/categories.py
"""Support for the widget that dumps the categories OmniGraph knows about.""" import json from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt from ...style import BUTTON_WIDTH from ...utils import DestructibleButton from ..toolkit_utils import help_button __all__ = ["ToolkitWidgetCategories"] # ============================================================================================================== class ToolkitWidgetCategories: ID = "DumpCategories" TOOLTIP = "Dump out the list of recognized node type categories" # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): self.__button = None self.__help_button = None self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__help_button") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the node type categories""" self.__button = DestructibleButton( "Dump Categories", name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True)) assert self.__help_button # -------------------------------------------------------------------------------------------------------------- def __on_click(self, force_help: bool = False): """Callback executed when the Dump Categories button is clicked""" if force_help: text = json.dumps({"help": "Dump the current list of recognized node type categories"}, indent=4) else: categories = {} interface = og.get_node_categories_interface() for category_name, category_description in interface.get_all_categories().items(): categories[category_name] = category_description text = json.dumps({"nodeTypeCategories": categories}, indent=4) tooltip = "Node Type Categories" self.__set_output(text, tooltip)
2,529
Python
41.166666
116
0.524318
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extensions_used.py
"""Support for the widget that dumps the categories OmniGraph knows about.""" import json from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt from ...style import BUTTON_WIDTH from ...utils import DestructibleButton __all__ = ["ToolkitWidgetExtensionsUsed"] # ============================================================================================================== class ToolkitWidgetExtensionsUsed: ID = "ExtensionsUsed" LABEL = "Extensions Used By Nodes" TOOLTIP = "List all of the extensions used by OmniGraph nodes in the scene" RESULTS_TOOLTIP = "Extensions used by OmniGraph nodes in the scene" # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable, extension_information: og.ExtensionInformation): self.__button = None self.__extension_information = extension_information self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__extension_information") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the list of nodes and their extensions from the scene""" self.__button = DestructibleButton( self.LABEL, name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button # -------------------------------------------------------------------------------------------------------------- def __on_click(self): """Callback executed when the Extensions Used button is clicked""" try: enabled_node_types, _ = self.__extension_information.get_nodes_by_extension() text = json.dumps(enabled_node_types, indent=4) except Exception as error: # noqa: PLW0703 text = str(error) self.__set_output(text, self.RESULTS_TOOLTIP)
2,319
Python
41.181817
119
0.530401
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/fabric_contents.py
"""Support for the widget that dumps the categories OmniGraph knows about.""" import json from typing import Callable import omni.graph.core as og import omni.graph.tools as ogt import omni.ui as ui from ...style import BUTTON_WIDTH from ...utils import DestructibleButton from ..toolkit_utils import help_button from .flag_manager import FlagManager __all__ = ["ToolkitWidgetFabricContents"] # ============================================================================================================== class ToolkitWidgetFabricContents: ID = "DumpFabricContents" TOOLTIP = "Dump the contents of the OmniGraph Fabric cache" # ---------------------------------------------------------------------- # Checkboxes representing flags for the JSON serialization of the graph context and graph objects # KEY: ID of the checkbox for the flag # VALUE: (Label Text, Tooltip Text, Default Value) FLAGS = { "jsonFlagMaps": ("maps", "Show the context-independent attribute mapping information", False), "jsonFlagDetails": ("noDataDetail", "Hide the detailed attribute data in FlatCache", False), "jsonFlagLimit": ("limit", "Limit the number of output array elements to 100", False), "jsonFlagUnreferenced": ("unreferenced", "Show the connections between nodes in the graph", False), } # ---------------------------------------------------------------------- def __init__(self, set_output_callback: Callable): self.__button = None self.__flag_managers = {} self.__help_button = None self.__set_output = set_output_callback # ---------------------------------------------------------------------- def destroy(self): """Called when the widgets are being deleted to provide clean removal and prevent leaks""" ogt.destroy_property(self, "__button") ogt.destroy_property(self, "__flag_managers") ogt.destroy_property(self, "__help_button") ogt.destroy_property(self, "__set_output") # ---------------------------------------------------------------------- def build(self): """Build the UI section with the functionality to dump the contents of Fabric""" self.__button = DestructibleButton( "Dump Fabric", name=self.ID, width=BUTTON_WIDTH, tooltip=self.TOOLTIP, clicked_fn=self.__on_click, ) assert self.__button self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True)) assert self.__help_button for checkbox_id, (flag, tooltip, default_value) in self.FLAGS.items(): self.__flag_managers[checkbox_id] = FlagManager(checkbox_id, flag, tooltip, default_value) with ui.HStack(spacing=5): self.__flag_managers[checkbox_id].checkbox() # -------------------------------------------------------------------------------------------------------------- def __on_click(self, force_help: bool = False): """Callback executed when the Dump Fabric button is clicked""" result = [] if force_help: flags = ["help"] else: flags = [flag_manager.name for flag_manager in self.__flag_managers.values() if flag_manager.is_set] tooltip = f"Fabric contents, filtered with flags {flags}" for ctx in og.get_compute_graph_contexts(): json_string = "Not generated" try: json_string = og.OmniGraphInspector().as_json(ctx, flags=flags) result.append(json.loads(json_string)) except json.JSONDecodeError as error: self.__set_output(f"Error decoding json for context {ctx}: {error}\n{json_string}", json_string) return self.__set_output(json.dumps(result, indent=4), tooltip)
3,872
Python
44.034883
116
0.551136
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/templates/template_SetViewportMode.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. # from typing import List import omni.graph.core as og import omni.ui as ui from omni.graph.ui import OmniGraphBase from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH from pxr import Sdf, Usd ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP} MODE_NAMES = ["Default", "Scripted"] class ModeAttributeModel(ui.AbstractItemModel, OmniGraphBase): class AllowedTokenItem(ui.AbstractItem): def __init__(self, item, value): super().__init__() self.token = item self.model = ui.SimpleStringModel(value) def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict): OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata) ui.AbstractItemModel.__init__(self) self._allowed_tokens = [ModeAttributeModel.AllowedTokenItem(i, t) for i, t in enumerate(MODE_NAMES)] self._current_index = ui.SimpleIntModel() self._current_index.add_value_changed_fn(self._current_index_changed) self._updating_value = False self._has_index = False self._update_value() self._has_index = True def get_item_children(self, item): return self._allowed_tokens def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model def _current_index_changed(self, model): if not self._has_index: return # if we're updating from USD notice change to UI, don't call set_value if self._updating_value: return index = model.as_int if self.set_value(index): self._item_changed(None) def _update_value(self, force=False): was_updating_value = self._updating_value self._updating_value = True if ( OmniGraphBase._update_value(self, force) and (0 <= self._value < len(self._allowed_tokens)) and (self._value != self._current_index.as_int) ): self._current_index.set_value(self._value) self._item_changed(None) self._updating_value = was_updating_value def _on_dirty(self): self._item_changed(None) class CustomLayout: def __init__(self, compute_node_widget): self.enable = True self.compute_node_widget = compute_node_widget self.controller = og.Controller() self.node_prim_path = self.compute_node_widget._payload[-1] self.node = self.controller.node(self.node_prim_path) self.mode_model = None def _mode_build_fn(self, *args): with ui.HStack(spacing=HORIZONTAL_SPACING): ui.Label("Mode", name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH) ui.Spacer(width=HORIZONTAL_SPACING) with ui.ZStack(): attr_path = self.node_prim_path.AppendProperty("inputs:mode") self.mode_model = ModeAttributeModel(self.compute_node_widget.stage, [attr_path], False, {}) ui.ComboBox(self.mode_model) # Called by compute_node_widget to apply UI when selection changes def apply(self, props): def find_prop(name): return next((p for p in props if p.prop_name == name), None) # Retrieve the input and output attributes that exist on the node all_attributes = self.node.get_attributes() input_attribs = [ attrib.get_name() for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT and attrib.get_name()[:7] == "inputs:" and attrib.get_resolved_type().role != og.AttributeRole.EXECUTION ] output_attribs = [ attrib.get_name() for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and attrib.get_name()[:8] == "outputs:" and attrib.get_resolved_type().role != og.AttributeRole.EXECUTION ] mode_attrib = "inputs:mode" frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Inputs"): # Custom enum-style input for inputs:mode prop = find_prop(mode_attrib) if prop is not None: CustomLayoutProperty(prop.prop_name, mode_attrib[7:], self._mode_build_fn) for input_attrib in input_attribs: prop = find_prop(input_attrib) if prop is not None and input_attrib != mode_attrib: CustomLayoutProperty(prop.prop_name, input_attrib[7:]) with CustomLayoutGroup("Outputs"): for output_attrib in output_attribs: prop = find_prop(output_attrib) if prop is not None: CustomLayoutProperty(prop.prop_name, output_attrib[8:]) return frame.apply(props)
5,591
Python
37.833333
113
0.626185
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/templates/template_Button.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. # from functools import partial import omni.graph.core as og import omni.ui as ui from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder class CustomLayout: def __init__(self, compute_node_widget): self.enable = True self.compute_node_widget = compute_node_widget self.node_prim_path = self.compute_node_widget._payload[-1] self.node = og.Controller.node(self.node_prim_path) self.icon_textbox_widgets = {} self.icon_selector_window = None self.icon_selector_window_previous_directory = None self.icon_attribs = [ "inputs:idleIcon", "inputs:hoverIcon", "inputs:pressedIcon", "inputs:disabledIcon", ] def show_icon_selector_window(self, icon_attrib_name: str): # Create and show the file browser window which is used to select icon try: from omni.kit.window.filepicker import FilePickerDialog except ImportError: # Do nothing if the module cannot be imported return def __on_click_okay(filename: str, dirname: str): # Hardcode a forward slash rather than using os.path.join, # because the dirname will always use forward slash even on Windows machines chosen_file = dirname + "/" + filename self.icon_textbox_widgets[icon_attrib_name].set_value(chosen_file) self.icon_selector_window_previous_directory = self.icon_selector_window.get_current_directory() self.icon_selector_window.hide() def __on_click_cancel(file_name: str, directory_name: str): self.icon_selector_window_previous_directory = self.icon_selector_window.get_current_directory() self.icon_selector_window.hide() self.icon_selector_window = FilePickerDialog( "Select an Icon", click_apply_handler=__on_click_okay, click_cancel_handler=__on_click_cancel, allow_multi_selection=False, ) self.icon_selector_window.show(self.icon_selector_window_previous_directory) def icon_attrib_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): # Build the attribute label, textbox and browse button that's displayed on the property panel icon_attrib_name = ui_prop.prop_name self.icon_textbox_widgets[icon_attrib_name] = UsdPropertiesWidgetBuilder._string_builder( # noqa: PLW0212 self.compute_node_widget.stage, icon_attrib_name, ui_prop.property_type, ui_prop.metadata, [self.node_prim_path], {"style": {"alignment": ui.Alignment.RIGHT_TOP}}, ) ui.Spacer(width=5) ui.Button( "Browse", width=0, clicked_fn=partial(self.show_icon_selector_window, icon_attrib_name), ) def apply(self, props): # Called by compute_node_widget to apply UI when selection changes def find_prop(name): try: return next((p for p in props if p.prop_name == name)) except StopIteration: return None # Retrieve the input and output attributes that exist on the node all_attributes = self.node.get_attributes() input_attribs = [ attrib.get_name() for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT and attrib.get_name()[:7] == "inputs:" ] output_attribs = [ attrib.get_name() for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and attrib.get_name()[:8] == "outputs:" ] frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Inputs"): for input_attrib in input_attribs: prop = find_prop(input_attrib) if prop is not None and input_attrib not in self.icon_attribs: CustomLayoutProperty(prop.prop_name, input_attrib[7:]) for icon_attrib in self.icon_attribs: prop = find_prop(icon_attrib) if prop is not None: build_fn = partial(self.icon_attrib_build_fn, prop) CustomLayoutProperty(prop.prop_name, icon_attrib[7:], build_fn) with CustomLayoutGroup("Outputs"): for output_attrib in output_attribs: prop = find_prop(output_attrib) if prop is not None: CustomLayoutProperty(prop.prop_name, output_attrib[8:]) return frame.apply(props)
5,416
Python
41.653543
114
0.624631
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/metadata_manager.py
""" Classes and functions relating to the handling of both attribute and node metadata in the OgnNodeDescriptionEditor """ from contextlib import suppress from typing import Callable, Dict, Optional import carb import omni.graph.tools as ogt from omni import ui from ..style import name_value_hstack, name_value_label # noqa: PLE0402 from .ogn_editor_utils import DestructibleButton, find_unique_name # ====================================================================== class NameValueTreeManager: """Class that provides a simple interface to ui.TreeView model and delegate management for name/value lists. Class Hierarchy Properties: _model: NameValueModel containing a single name:value element _delegate: EditableDelegate object managing the tree view interaction Usage: def __on_model_changed(new_dictionary): print(f"Model changed to {new_dictionary}) my_dictionary = {"Hello": "Greeting", "World": "Scope"} my_manager = NameValueTreeManager(my_dictionary, __on_model_changed) ui.TreeView(my_manager.model) """ # ---------------------------------------------------------------------- class NameValueModel(ui.AbstractItemModel): """Represents the model for name-value table.""" class NameValueItem(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: str): """Initialize both of the models to the key/value pairs""" super().__init__() self.name_model = ui.SimpleStringModel(key) self.value_model = ui.SimpleStringModel(value) def destroy(self): """Destruction of the underlying models""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") ogt.destroy_property(self, "name_model") ogt.destroy_property(self, "value_model") def __repr__(self): """Return a nice representation of the string pair""" return f'NameValueModel("{self.name_model.as_string} : {self.value_model.as_string}")' # ---------------------------------------------------------------------- def __init__(self, metadata_values: Dict[str, str]): """Initialize the children into sorted tuples from the dictionary""" ogt.dbg_ui(f"NameValueModel({metadata_values}))") super().__init__() self.__children = [] self.__metadata_values = {} self.set_values(metadata_values) def destroy(self): """Cleanup when the model is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.__metadata_values = None ogt.destroy_property(self, "__children") def set_values(self, metadata_values: Dict[str, str]): """Define the children based on the new dictionary of key/value pairs""" ogt.dbg_ui(f"Set values in NameValueModel to {metadata_values}") self.__metadata_values = metadata_values self.__rebuild_children() def __rebuild_children(self): """Set the child string list, either for the initial state or after editing""" ogt.dbg_ui(f"Rebuilding children from {self.__metadata_values}") self.__children = [ self.NameValueItem(key, self.__metadata_values[key]) for key in sorted(self.__metadata_values.keys()) ] # Insert a blank entry at the begining for adding new values self.__children.append(self.NameValueItem("", "")) 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_unique_name("metadataName", self.__metadata_values) self.__metadata_values[suggested_name] = "metadataValue" self.__rebuild_children() def remove_child(self, key_value: str): """Remove the child corresponding to the given item from the list""" ogt.dbg_ui(f"Removing key {key_value}") try: del self.__metadata_values[key_value] except KeyError: carb.log_error(f"Could not find child with key value of {key_value} for removal") self.__rebuild_children() 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. Internal Properties: __add_button: Widget managing the button to add new elements __remove_buttons: Widget list managing the button to remove existing elements __stack_widgets: Widget list managing the editable fields __subscription: Subscription object for the callback on end of an edit __value_change_cb: Function to call when any values change """ def __init__(self, value_change_cb: Callable): """Initialize the state with no subscription on the end edit; it will be used later""" super().__init__() self.__add_button = None self.__remove_buttons = [] self.__subscription = None self.__value_change_cb = value_change_cb self.__stack_widgets = [] def destroy(self): """Release any hanging references""" ogt.destroy_property(self, "__add_button") ogt.destroy_property(self, "__remove_buttons") self.__subscription = None self.__value_change_cb = None with suppress(AttributeError): for stack_widget in self.__stack_widgets: stack_widget.set_mouse_double_clicked_fn(None) self.__stack_widgets = [] def build_branch(self, model, item, column_id: int, level: int, expanded: bool): """Create a branch widget that opens or closes subtree""" def build_header(self, column_id: int): """Set up the header entry at the named column""" ogt.dbg_ui(f"Build header for column {column_id}") header_style = "TreeView.Header" if column_id == 0: ui.Label("", width=20, style_type_name_override=header_style) else: ui.Label("Name" if column_id == 1 else "Value", style_type_name_override=header_style) 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_double_click(self, button, field, label): """Called when the user double-clicked the item in TreeView""" if button != 0: return ogt.dbg_ui(f"Double click on {label}") # 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) ) assert self.__subscription 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 # TODO: Verify that this is not duplicating an existing entry self.__subscription = None if self.__value_change_cb is not None: self.__value_change_cb(model) 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_buttons.append( DestructibleButton( width=20, height=20, style_type_name_override="RemoveElement", clicked_fn=lambda: self.__on_remove_item(model, item), ) ) else: self.__add_button = DestructibleButton( width=20, height=20, style_type_name_override="AddElement", clicked_fn=lambda: self.__on_add_item(model), ) assert self.__add_button else: stack = ui.ZStack(height=20) with stack: value_model = model.get_item_value_model(item, column_id) if not item.name_model.as_string: ui.Label("") else: label = ui.Label(value_model.as_string) 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) ) self.__stack_widgets.append(stack) # ---------------------------------------------------------------------- def __init__(self, value_dictionary: Dict[str, str], value_change_cb: Optional[Callable]): """Initialize the model and delegate information from the dictionary""" self._model = self.NameValueModel(value_dictionary) self._delegate = self.EditableDelegate(value_change_cb) # ---------------------------------------------------------------------- def destroy(self): """Cleanup when the manager is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self._model = None self._delegate.destroy() self._delegate = None # ====================================================================== class MetadataManager(NameValueTreeManager): """Class that handles interaction with the node metadata fields.""" def list_values_changed(self, what): new_metadata = {} for child in self._model.get_item_children(None): if child.name_model.as_string: new_metadata[child.name_model.as_string] = child.value_model.as_string # Edit the metadata based on new values and reset the widget to keep a single blank row self.__controller.filtered_metadata = new_metadata self._model.set_values(new_metadata) def __init__(self, controller): """Initialize the fields inside the given controller and set up the initial frame""" super().__init__(controller.filtered_metadata, self.list_values_changed) self.__controller = controller # 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. with name_value_hstack(): name_value_label("Metadata:", "Name/Value pairs to store as metadata.") self.__metadata_tree = ui.TreeView( self._model, delegate=self._delegate, root_visible=False, header_visible=True, height=0, column_widths=[30], ) assert self.__metadata_tree def destroy(self): """Destroy the widget and cleanup the callbacks""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") super().destroy() ogt.destroy_property(self, "__metadata_tree") self.__controller = None
13,902
Python
45.654362
119
0.555244
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/main_controller.py
""" Controller part of the Model-View-Controller providing editing capabilities to OGN files """ from typing import Dict, Union import omni.graph.tools as ogt from carb import log_warn from .attribute_properties import AttributeListController from .change_management import ChangeManager from .main_model import Model from .node_properties import NodePropertiesController from .ogn_editor_utils import show_wip from .test_configurations import TestListController # TODO: Introduce methods in the node generator to allow translation between attribute type name and component values # TODO: Immediate parsing, with parse errors shown in the "Raw" frame # ====================================================================== class Controller(ChangeManager): """ Class responsible for coordinating changes to the OGN internal model. External Properties: ogn_data: Generated value of the OGN dictionary for the controlled model Internal Properties: __model: The main model being controlled, which encompasses all of the submodels __node_properties_controller: Controller for the section containing node properties __input_attribute_controller: Controller for the section containing input attributes __output_attribute_controller: Controller for the section containing output attributes __tests_controller: Controller for the section containing algorithm tests """ def __init__(self, model: Model, initial_contents: Union[None, str, Dict]): """Initialize the model being controlled""" super().__init__() self.__model = model self.node_properties_controller = None self.input_attribute_controller = None self.output_attribute_controller = None self.tests_controller = None self.set_ogn_data(initial_contents) # ---------------------------------------------------------------------- def destroy(self): """Called when the controller is destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") super().destroy() # The main controller owns all sub-controllers so destroy them here ogt.destroy_property(self, "node_properties_controller") ogt.destroy_property(self, "input_attribute_controller") ogt.destroy_property(self, "output_attribute_controller") ogt.destroy_property(self, "tests_controller") self.__model = None # ---------------------------------------------------------------------- def set_ogn_data(self, new_contents: Union[None, str, Dict]): """Reset the underlying model to new values""" ogt.dbg_ui(f"Controller: set_ogn_data to {new_contents}") try: self.__model.set_ogn_data(new_contents) self.node_properties_controller = NodePropertiesController(self.__model.node_properties_model) self.input_attribute_controller = AttributeListController(self.__model.input_attribute_model) self.output_attribute_controller = AttributeListController(self.__model.output_attribute_model) if show_wip(): self.tests_controller = TestListController( self.__model.tests_model, self.input_attribute_controller, self.output_attribute_controller ) # Change callbacks on the main controller should also be executed by the child controllers when they change self.node_properties_controller.forward_callbacks_to(self) self.input_attribute_controller.forward_callbacks_to(self) self.output_attribute_controller.forward_callbacks_to(self) if show_wip(): self.tests_controller.forward_callbacks_to(self) except Exception as error: # noqa: PLW0703 log_warn(f"Error redefining the OGN data - {error}") # ---------------------------------------------------------------------- @property def ogn_data(self) -> Dict: """Return the current full OGN data content, reassembled from the component pieces""" return self.__model.ogn_data # ---------------------------------------------------------------------- def is_dirty(self) -> bool: """Return True if the contents have been modified since being set clean""" return self.__model.is_dirty # ---------------------------------------------------------------------- def set_clean(self): """Reset the current status of the data to be clean (e.g. after a file save).""" ogt.dbg_ui("Controller: set_clean") self.__model.set_clean()
4,607
Python
47
119
0.619926
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/change_management.py
""" Collection of classes to use for managing reactions to changes to models """ from typing import Callable, List, Optional, Union import omni.graph.tools as ogt # ====================================================================== class ChangeMessage: """Message packet to send when a change is encountered. Created as a class so that other messages can override it and add more information. External Properties: caller: Object that triggered the change """ def __init__(self, caller): """Set up the basic message information""" self.caller = caller def __str__(self) -> str: """Return a string with the contents of the message""" return str(self.caller.__class__.__name__) # ================================================================================ class RenameMessage(ChangeMessage): """Encapsulation of a message sent when an attribute name changes""" def __init__(self, caller, old_name: str, new_name: str): """Set up a message with information needed to indicate a name change""" super().__init__(caller) self.old_name = old_name self.new_name = new_name def __str__(self) -> str: """Returns a human-readable representation of the name change information""" caller_info = super().__str__() return f"Name change {self.old_name} -> {self.new_name} (from {caller_info})" # ====================================================================== class ChangeManager: """Base class to provide the ability to set and react to value changes External Properties: callback_forwarders: List of change manager whose callbacks are also to be executed change_callbacks: List of callbacks to invoke when a change happens """ def __init__(self, change_callbacks: Optional[Union[List, Callable]] = None): """Initialize the callback list""" self.change_callbacks = [] self.callback_forwarders = [] if change_callbacks is not None: self.add_change_callback(change_callbacks) def destroy(self): """Called when the manager is being destroyed, usually from the derived class's destroy""" self.change_callbacks = [] self.callback_forwarders = [] # ---------------------------------------------------------------------- def on_change(self, change_message=None): """Called when the controller has modified some data""" ogt.dbg_ui(f"on_change({change_message})") message = ChangeMessage(self) if change_message is None else change_message # By passing in the caller we facilitate more intelligent responses with callback sharing for callback in self.change_callbacks: callback(message) # Call all of the forwarded change callbacks as well, specifying this manager as the initiator message.caller = self for callback_forwarder in self.callback_forwarders: ogt.dbg_ui(f"...forwarding change to {callback_forwarder.__class__.__name__}") callback_forwarder.on_change(message) # ---------------------------------------------------------------------- def add_change_callback(self, callback: Union[Callable, List[Callable]]): """Add a function to be called when the controller modifies some data""" if isinstance(callback, list): self.change_callbacks = callback elif isinstance(callback, Callable): self.change_callbacks.append(callback) # ---------------------------------------------------------------------- def remove_change_callback(self, callback: Callable): """Remove a function to be called when the controller modifies some data""" try: if isinstance(callback, list): _ = [self.remove_change_callback(child) for child in callback] else: self.change_callbacks.remove(callback) except ValueError: ogt.dbg_ui(f"Tried to remove non-existent callback {callback.name}") # ---------------------------------------------------------------------- def forward_callbacks_to(self, parent_manager): """Set the callbacks on this change manager to include those existing on the parent This is done lazily so that any new callbacks added later will also be handled. Args: parent_manager: ChangeManager whose callbacks are also to be executed by this manager """ self.callback_forwarders.append(parent_manager)
4,570
Python
41.324074
102
0.580744
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/attribute_list_manager.py
""" Manager class for the combo box that lets you select from a list of attribute names. """ from typing import Callable, List import omni.graph.tools as ogt from carb import log_warn from omni import ui from .ogn_editor_utils import ComboBoxOptions # ====================================================================== # ID values for widgets that are editable or need updating ID_ATTR_LIST = "attributeList" # ====================================================================== # Tooltips for the editable widgets TOOLTIPS = {ID_ATTR_LIST: "Attribute name (without namespace)"} # ====================================================================== class AttributeListComboBox(ui.AbstractItemModel): """Implementation of a combo box that shows attribute base data types available""" def __init__(self, initial_value: str, available_attribute_names: List[str]): """Initialize the attribute base type combo box details""" super().__init__() self.__available_attribute_names = available_attribute_names self.__current_index = ui.SimpleIntModel() self.item_selected_callback = None try: self.__current_index.set_value(available_attribute_names.index(initial_value)) except ValueError: log_warn(f"Initial attribute type {initial_value} not recognized") self.__old_value = self.__current_index.as_int self.__current_index.add_value_changed_fn(self.__on_attribute_selected) # Using a list comprehension instead of values() guarantees the sorted ordering self.__items = [ComboBoxOptions(attribute_type_name) for attribute_type_name in available_attribute_names] def destroy(self): """Cleanup when the widget is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.__available_attribute_names = 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 add_child(self, child_name: str): """Callback invoked when a child is added""" self.__items.append(ComboBoxOptions(child_name)) self._item_changed(None) def rename_child(self, old_name: str, new_name: str): """Callback invoked when a child is renamed""" for item in self.__items: if item.model.as_string == old_name: ogt.dbg_ui("Found combo box item to rename") item.model.set_value(new_name) break self._item_changed(None) def remove_child(self, child_name: str): """Callback invoked when a child is removed to adjust for the fact that higher indexes must decrement""" selected = self.__current_index.as_int for (index, item) in enumerate(self.__items): if item.model.as_string == child_name: ogt.dbg_ui(f"Removing combo box item {index} = {child_name}") if selected > index: self.__current_index.set_value(selected - 1) self.__items.pop(index) break index += 1 self._item_changed(None) def __on_attribute_selected(self, new_value: ui.SimpleIntModel): """Callback executed when a new base type was selected""" try: ogt.dbg_ui(f"Set selected attribute to {new_value.as_int} from {self.__current_index.as_int}") new_attribute_name = self.__available_attribute_names[new_value.as_int] ogt.dbg_ui(f"Type name is {new_attribute_name}") if self.item_selected_callback is not None: ogt.dbg_ui(f"...calling into {self.item_selected_callback}") self.item_selected_callback(new_attribute_name) self.__old_value = new_value.as_int except ValueError as error: log_warn(f"Attribute selection rejected - {error}") new_value.set_value(self.__old_value) except KeyError as error: log_warn(f"Attribute selection could not be found - {error}") new_value.set_value(self.__old_value) except IndexError: log_warn(f"Attribute {new_value.as_int} was selected but there is no such attribute") new_value.set_value(self.__old_value) self._item_changed(None) # ====================================================================== class AttributeListManager: """Handle the combo box and responses for getting and setting attribute base type values Internal Properties: __widget: ComboBox widget controlling the base type __widget_model: Model for the ComboBox value """ def __init__(self, initial_value: str, available_attribute_names: List[str], item_selected_callback: Callable): """Set up the initial UI and model Args: initial_value: Initially selected value available_attribute_names: List of potential names """ self.__widget_model = AttributeListComboBox(initial_value, available_attribute_names) self.__widget_model.item_selected_callback = item_selected_callback self.__widget = ui.ComboBox( self.__widget_model, alignment=ui.Alignment.LEFT_BOTTOM, name=ID_ATTR_LIST, tooltip=TOOLTIPS[ID_ATTR_LIST] ) 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") ogt.destroy_property(self, "__widget_model") def on_child_added(self, child_name: str): """Callback invoked when a child is added""" self.__widget_model.add_child(child_name) def on_child_renamed(self, old_name: str, new_name: str): """Callback invoked when a child is renamed""" self.__widget_model.rename_child(old_name, new_name) def on_child_removed(self, child_name: str): """Callback invoked when a child is removed to adjust for the fact that higher indexes must decrement""" self.__widget_model.remove_child(child_name)
6,413
Python
42.931507
118
0.609075
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/memory_type_manager.py
""" Support for the combo box representing the choice of attribute memory types. Shared between the node and attribute properties since both allow that choice. """ 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 name_value_label # noqa: PLE0402 from .ogn_editor_utils import ComboBoxOptions # ====================================================================== # ID values for widgets that are editable or need updating ID_MEMORY_TYPE = "memoryType" # ====================================================================== # Tooltips for the editable widgets TOOLTIPS = {ID_MEMORY_TYPE: "The physical location of attribute data. Attribute values override node values"} # ====================================================================== class MemoryTypeComboBox(ui.AbstractItemModel): """Implementation of a combo box that shows types of memory locations available Internal Properties: __controller: Controller object manipulating the underlying memory model __current_index: Model containing the combo box selection __items: List of options available to choose from in the combo box __subscription: Contains the scoped subscription object for value changes """ OPTION_CPU = "Store Attribute Memory on CPU" OPTION_CUDA = "Store Attribute Memory on GPU (CUDA style)" OPTION_ANY = "Choose Attribute Memory Location at Runtime" OPTIONS = [ogn.MemoryTypeValues.CPU, ogn.MemoryTypeValues.CUDA, ogn.MemoryTypeValues.ANY] OPTION_NAME = { ogn.MemoryTypeValues.CPU: OPTION_CPU, ogn.MemoryTypeValues.CUDA: OPTION_CUDA, ogn.MemoryTypeValues.ANY: OPTION_ANY, } def __init__(self, controller): """Initialize the memory type combo box details""" super().__init__() self.__controller = controller self.__current_index = ui.SimpleIntModel() self.__current_index.set_value(self.OPTIONS.index(self.__controller.memory_type)) self.__subscription = self.__current_index.subscribe_value_changed_fn(self.__on_memory_type_changed) assert self.__subscription # Using a list comprehension instead of values() guarantees the ordering self.__items = [ComboBoxOptions(self.OPTION_NAME[memory_type]) for memory_type in self.OPTIONS] def destroy(self): """Called when the manager is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.__controller = None self.__subscription = 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_memory_type_changed(self, new_value: ui.SimpleIntModel): """Callback executed when a new memory type was selected""" try: new_memory_type = self.OPTION_NAME[self.OPTIONS[new_value.as_int]] ogt.dbg_ui(f"Set memory type to {new_value.as_int} - {new_memory_type}") self.__controller.memory_type = self.OPTIONS[new_value.as_int] self._item_changed(None) except (AttributeError, KeyError) as error: log_warn(f"Node memory type '{new_value.as_int}' was rejected - {error}") # ====================================================================== class MemoryTypeManager: """Handle the combo box and responses for getting and setting the memory type location 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): """Set up the initial UI and model Args: controller: AttributePropertiesController in charge of the data for the attribute being managed """ self.__controller = controller name_value_label("Memory Type:", TOOLTIPS[ID_MEMORY_TYPE]) self.__widget_model = MemoryTypeComboBox(controller) self.__widget = ui.ComboBox( self.__widget_model, alignment=ui.Alignment.LEFT_BOTTOM, name=ID_MEMORY_TYPE, tooltip=TOOLTIPS[ID_MEMORY_TYPE], ) assert self.__widget assert self.__controller def destroy(self): """Called when the manager is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.__controller = None ogt.destroy_property(self, "__widget") ogt.destroy_property(self, "__widget_model")
4,910
Python
40.974359
109
0.625051
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/node_language_manager.py
""" Support for the combo box representing the choice of node languages. """ 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 name_value_label # noqa: PLE0402 from .ogn_editor_utils import ComboBoxOptions # ====================================================================== # ID values for widgets that are editable or need updating ID_NODE_LANGUAGE = "nodeLanguage" # ====================================================================== # Tooltips for the editable widgets TOOLTIPS = {ID_NODE_LANGUAGE: "The language in which the node is implemented, e.g. Python or C++"} # ====================================================================== class NodeLanguageComboBox(ui.AbstractItemModel): """Implementation of a combo box that shows types of implementation languages available Internal Properties: __controller: Controller object manipulating the underlying memory model __current_index: Model containing the combo box selection __items: List of options available to choose from in the combo box __subscription: Contains the scoped subscription object for value changes """ OPTION_CPP = "Node Is Implemented In C++" OPTION_PYTHON = "Node Is Implemented In Python" OPTIONS = [ogn.LanguageTypeValues.CPP, ogn.LanguageTypeValues.PYTHON] OPTION_NAMES = {OPTIONS[0]: OPTION_CPP, OPTIONS[1]: OPTION_PYTHON} def __init__(self, controller): """Initialize the node language combo box details""" super().__init__() self.__controller = controller self.__current_index = ui.SimpleIntModel() self.__current_index.set_value(self.OPTIONS.index(ogn.check_node_language(self.__controller.node_language))) self.__subscription = self.__current_index.subscribe_value_changed_fn(self.__on_language_changed) assert self.__subscription assert self.__controller # Using a list comprehension instead of values() guarantees the ordering self.__items = [ComboBoxOptions(self.OPTION_NAMES[node_language]) for node_language in self.OPTIONS] def destroy(self): """Clean up when the widget is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.__subscription = None self.__controller = 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_language_changed(self, new_value: ui.SimpleIntModel): """Callback executed when a new language was selected""" try: new_node_language = self.OPTION_NAMES[self.OPTIONS[new_value.as_int]] ogt.dbg_ui(f"Set node language to {new_value.as_int} - {new_node_language}") self.__controller.node_language = self.OPTIONS[new_value.as_int] self._item_changed(None) except (AttributeError, KeyError) as error: log_warn(f"Node language '{new_value.as_int}' was rejected - {error}") # ====================================================================== class NodeLanguageManager: """Handle the combo box and responses for getting and setting the node implementation language 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): """Set up the initial UI and model Args: controller: AttributePropertiesController in charge of the data for the attribute being managed """ self.__controller = controller name_value_label("Implementation Language:", TOOLTIPS[ID_NODE_LANGUAGE]) self.__widget_model = NodeLanguageComboBox(controller) self.__widget = ui.ComboBox( self.__widget_model, alignment=ui.Alignment.LEFT_BOTTOM, name=ID_NODE_LANGUAGE, tooltip=TOOLTIPS[ID_NODE_LANGUAGE], ) assert self.__widget assert self.__controller def destroy(self): """Called to clean up when the widget is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.__controller = None ogt.destroy_property(self, "__widget") ogt.destroy_property(self, "__widget_model")
4,740
Python
41.330357
116
0.622363
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_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/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