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.property.usd/omni/kit/property/usd/tests/test_material_widget_refresh_on_binding.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 os import omni.kit.app import omni.usd import omni.kit.commands import omni.kit.undo from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows class MaterialWidgetRefreshOnBinding(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda")) # After running each test async def tearDown(self): await wait_stage_loading() async def test_l1_material_widget_refresh_on_binding(self): widget_name = "Property//Frame/**/StringField[*].identifier=='combo_drop_target'" to_select = "/World/Cylinder" # property window to front await ui_test.find("Property").focus() # select prim await select_prims([to_select]) # wait for material to load & UI to refresh await wait_stage_loading() # verify property_widget is correct self.assertTrue(ui_test.find(widget_name).model.get_value_as_string() == "/World/Looks/OmniPBR") # change material binding omni.kit.commands.execute("BindMaterialCommand", prim_path=to_select, material_path="/World/Looks/OmniGlass", strength=None) # wait for material to load & UI to refresh await wait_stage_loading() # verify widget has been refreshed self.assertTrue(ui_test.find(widget_name).model.get_value_as_string() == "/World/Looks/OmniGlass") # change material binding back omni.kit.undo.undo() # wait for material to load & UI to refresh await wait_stage_loading() # verify widget has been refreshed self.assertTrue(ui_test.find(widget_name).model.get_value_as_string() == "/World/Looks/OmniPBR")
2,376
Python
36.140624
132
0.700337
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_drag_drop_material_property_combobox.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 omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import UsdShade from omni.kit.material.library.test_helper import MaterialLibraryTestHelper from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, delete_prim_path_children, arrange_windows ) from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class DragDropMaterialPropertyComboBox(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 64) await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda")) # After running each test async def tearDown(self): await wait_stage_loading() def _verify_material(self, stage, mtl_name, to_select): # verify material created prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()] self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths) self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths) # verify bound material if to_select: for prim_path in to_select: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{mtl_name}") async def test_l2_drag_drop_material_property_combobox(self): await ui_test.find("Content").focus() await ui_test.find("Stage").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() to_select = "/World/Cylinder" # select prim await select_prims([to_select]) # wait for material to load & UI to refresh await wait_stage_loading() # drag to bottom of stage window # NOTE: Material binding is done on selected prim mdl_list = await omni.kit.material.library.get_mdl_list_async() property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: for mtl_name, mdl_path, submenu in mdl_list: await delete_prim_path_children("/World/Looks") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # use create materialdialog async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_create_material_dialog(mdl_path, mtl_name) # wait for material to load & UI to refresh await wait_stage_loading() # verify self._verify_material(stage, mtl_name, [to_select])
3,517
Python
39.436781
116
0.66079
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_usd_preferences.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 os import carb import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.usd from omni.kit import ui_test from pxr import Vt, Gf from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, wait_for_window, arrange_windows PERSISTENT_SETTINGS_PREFIX = "/persistent" class TestUsdPreferences(AsyncTestCase): def set_defaults(): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/large_selection", 100) carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/raw_widget_multi_selection_limit", 1) # Before running each test async def setUp(self): await arrange_windows() TestUsdPreferences.set_defaults() # After running each test async def tearDown(self): TestUsdPreferences.set_defaults() async def test_l1_usd_preferences_test(self): omni.kit.window.preferences.show_preferences_window() await ui_test.human_delay(50) for page in omni.kit.window.preferences.get_page_list(): if page.get_title() == "Property Widgets": omni.kit.window.preferences.select_page(page) await ui_test.human_delay(50) frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_Property Window'") w = frame.find("**/IntDrag[*].identifier=='large_selection'") await w.click(double=True) await w.input("10") w = frame.find("**/IntDrag[*].identifier=='raw_widget_multi_selection_limit'") await w.click(double=True) await w.input("20") await ui_test.human_delay(50) self.assertEqual(carb.settings.get_settings().get(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/large_selection"), 10) self.assertEqual(carb.settings.get_settings().get(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/raw_widget_multi_selection_limit"), 20) return self.assertTrue(False, "Property Widgets preferences page not found")
2,655
Python
41.15873
163
0.684369
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_shader_goto_UDIM_material_property.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 os import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.usd from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows from omni.kit.window.content_browser import get_content_window from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper from omni.kit.window.file_importer.test_helper import FileImporterTestHelper from omni.kit import ui_test class ShaderGotoUDIMMaterialProperty(AsyncTestCase): # Before running each test async def setUp(self): async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.set_config_menu_settings({'hide_unknown': True, 'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': True}) await arrange_windows("Stage", 128) await open_stage(get_test_data_path(__name__, "usd/locate_file_UDIM_material.usda")) # After running each test async def tearDown(self): from omni.kit.test_suite.helpers import wait_stage_loading await wait_stage_loading() async def test_l1_shader_goto_UDIM_material_property(self): await ui_test.find("Content").focus() stage_window = ui_test.find("Stage") await stage_window.focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniPBR/Shader"]) await wait_stage_loading() # verify corrent prim is selected content_browser = get_content_window() for material_attr, enabled, expected in [ ("sdf_locate_asset_inputs:ao_texture", False, []), # "" ("sdf_locate_asset_inputs:diffuse_texture", True, ["T_Hood_A1_Albedo.<UDIM>.png"]), # T_Hood_A1_1001_Albedo.png ("sdf_locate_asset_inputs:emissive_mask_texture", True, ["T_Hood_A1_Emissive.<UDIM>.png"]), # granite_a_mask.png ("sdf_locate_asset_inputs:opacity_texture", False, []), # http ("sdf_locate_asset_inputs:reflectionroughness_texture", True, [])]: # test content_browser.navigate_to(get_test_data_path(__name__, "")) widget = ui_test.find(f"Property//Frame/**/Button[*].identifier=='{material_attr}'") self.assertEqual(widget.widget.visible, enabled) if enabled: widget.widget.scroll_here_y(0.0) await ui_test.human_delay(10) await widget.click() await ui_test.human_delay(10) selected = [os.path.basename(path) for path in content_browser.get_current_selections()] self.assertEqual(selected, expected) async def test_l1_shader_change_UDIM_material_property(self): await ui_test.find("Content").focus() stage_window = ui_test.find("Stage") await stage_window.focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniPBR/Shader"]) await wait_stage_loading() # verfiy prim asset prim = stage.GetPrimAtPath("/World/Looks/OmniPBR/Shader") attr = prim.GetAttribute("inputs:diffuse_texture") self.assertTrue(attr.Get().resolvedPath.replace("\\", "/").endswith("omni.kit.property.usd/data/tests/usd/textures/T_Hood_A1_Albedo.<UDIM>.png")) # change prim asset content_browser = get_content_window() content_browser.navigate_to(get_test_data_path(__name__, "")) widget = ui_test.find(f"Property//Frame/**/Button[*].identifier=='sdf_browse_asset_inputs:diffuse_texture'") await widget.click() await ui_test.human_delay(50) #grid_view = ui_test.find("Select Asset...//Frame/**/VGrid[*].identifier=='file_importer_grid_view'") #await grid_view.find(f"**/Label[*].text=='granite_a_mask2.png'").click(double=True) url = omni.usd.correct_filename_case(get_test_data_path(__name__, "usd/textures/").replace("\\", "/")) + "/" async with FileImporterTestHelper() as file_import_helper: await file_import_helper.select_items_async(url, names=["granite_a_mask2.png"]) await file_import_helper.click_apply_async(filename_url="granite_a_mask2.png") await ui_test.human_delay(4) # verfiy prim asset self.assertTrue(attr.Get().resolvedPath.replace("\\", "/").endswith("omni.kit.property.usd/data/tests/usd/textures/granite_a_mask2.png"))
5,222
Python
51.229999
165
0.635963
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_shader_drag_drop_mdl.py
import omni.kit.test import omni.kit.ui_test as ui_test from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from omni.kit.test_suite.helpers import open_stage, wait_stage_loading, get_test_data_path, select_prims, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class TestDragDropFileToMaterial(OmniUiTest): # Before running each test async def setUp(self): await arrange_windows("Stage", 200) await open_stage(get_test_data_path(__name__, "usd/locate_file_material.usda")) await wait_stage_loading() # After running each test async def tearDown(self): await wait_stage_loading() async def test_drag_drop_single_mdl_asset_path(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniPBR/Shader"]) await wait_stage_loading() # verify material is correct shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR")) asset = shader.GetSourceAsset("mdl") self.assertTrue(shader.GetPrim().IsValid()) self.assertEqual(asset.path, "OmniPBR.mdl") # drag file from content window property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_info:mdl:sourceAsset'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__, "usd/TESTEXPORT.mdl") await content_browser_helper.drag_and_drop_tree_view(usd_path, drag_target=drag_target) # verify asset shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR")) asset = shader.GetSourceAsset("mdl") self.assertTrue(shader.GetPrim().IsValid()) self.assertTrue(asset.path.endswith("/TESTEXPORT.mdl")) async def test_drag_drop_single_png_asset_path(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniPBR/Shader"]) await wait_stage_loading() # verify material is correct shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR")) asset = shader.GetSourceAsset("mdl") self.assertTrue(shader.GetPrim().IsValid()) self.assertEqual(asset.path, "OmniPBR.mdl") # drag file from content window property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_inputs:ao_texture'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__, "usd/textures/granite_a_mask.png") await content_browser_helper.drag_and_drop_tree_view(usd_path, drag_target=drag_target) # verify asset prim = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"), True) asset_path = prim.GetAttribute("inputs:ao_texture").Get() self.assertTrue(prim.IsValid()) self.assertTrue(asset_path.path.endswith("textures/granite_a_mask.png")) async def test_drag_drop_multi_mdl_asset_path(self): # Test that dropping multiple material files results in no changes usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniPBR/Shader"]) await wait_stage_loading() # verify material is correct shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR")) asset = shader.GetSourceAsset("mdl") self.assertTrue(shader.GetPrim().IsValid()) self.assertEqual(asset.path, "OmniPBR.mdl") # drag file from content window property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_info:mdl:sourceAsset'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__, "usd") await content_browser_helper.drag_and_drop_tree_view( usd_path, names=["TESTEXPORT.mdl", "TESTEXPORT2.mdl"], drag_target=drag_target) # verify material not changed shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR")) asset = shader.GetSourceAsset("mdl") self.assertTrue(shader.GetPrim().IsValid()) self.assertEqual(asset.path, "OmniPBR.mdl") async def test_drag_drop_multi_png_asset_path(self): # Test that dropping multiple texture files results in no changes. usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniPBR/Shader"]) await wait_stage_loading() # verify material is correct shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR")) asset = shader.GetSourceAsset("mdl") self.assertTrue(shader.GetPrim().IsValid()) self.assertEqual(asset.path, "OmniPBR.mdl") # drag file from content window property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_inputs:ao_texture'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__, "usd/textures") await content_browser_helper.drag_and_drop_tree_view( usd_path, names=["granite_a_mask.png", "granite_a_mask2.png"], drag_target=drag_target) # verify asset prim = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"), True) asset_path = prim.GetAttribute("inputs:ao_texture").Get() self.assertTrue(prim.IsValid()) self.assertEqual(asset_path.path, "")
6,031
Python
44.696969
121
0.668048
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_shader_goto_material_property.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 os import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.usd from pxr import Sdf, UsdShade class ShaderGotoMaterialProperty(AsyncTestCase): # Before running each test async def setUp(self): from omni.kit.test_suite.helpers import open_stage, get_test_data_path, arrange_windows await arrange_windows("Stage", 128) await open_stage(get_test_data_path(__name__, "usd/locate_file_material.usda")) # After running each test async def tearDown(self): from omni.kit.test_suite.helpers import wait_stage_loading await wait_stage_loading() async def test_l1_shader_goto_material_property(self): from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path, select_prims, wait_stage_loading from omni.kit.window.content_browser import get_content_window await ui_test.find("Content").focus() stage_window = ui_test.find("Stage") await stage_window.focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniPBR/Shader"]) await wait_stage_loading() # verify corrent prim is selected content_browser = get_content_window() for material_attr, enabled, expected in [ ("sdf_locate_asset_inputs:ao_texture", False, []), # "" ("sdf_locate_asset_inputs:diffuse_texture", True, ["granite_a_mask.png"]), # granite_a_mask.png ("sdf_locate_asset_inputs:emissive_mask_texture", True, ["granite_a_mask.png"]), # granite_a_mask.png ("sdf_locate_asset_inputs:opacity_texture", False, []), # http ("sdf_locate_asset_inputs:reflectionroughness_texture", True, [])]: # test content_browser.navigate_to(get_test_data_path(__name__, "")) widget = ui_test.find(f"Property//Frame/**/Button[*].identifier=='{material_attr}'") self.assertEqual(widget.widget.visible, enabled) if enabled: widget.widget.scroll_here_y(0.0) await ui_test.human_delay(10) await widget.click() await ui_test.human_delay(10) selected = [os.path.basename(path) for path in content_browser.get_current_selections()] self.assertEqual(selected, expected)
3,081
Python
47.156249
148
0.610191
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_references.py
import carb import omni.kit.ui_test as ui_test import omni.usd from pathlib import Path from pxr import Sdf, UsdShade, UsdGeom from omni.ui.tests.test_base import OmniUiTest from omni.kit.test_suite.helpers import open_stage, wait_stage_loading, get_test_data_path, select_prims, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class TestDragDropFileToReference(OmniUiTest): # Before running each test async def setUp(self): carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") await arrange_windows("Stage", 200) await open_stage(get_test_data_path(__name__, "usd/reference_prim.usda")) await wait_stage_loading() # After running each test async def tearDown(self): await wait_stage_loading() async def test_drag_drop_single_usda_to_reference(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/XformReference"]) await wait_stage_loading() # verify refs are correct prim = stage.GetPrimAtPath("/World/XformReference") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertEqual(len(ref_and_layers), 1) self.assertEqual(ref_and_layers[0][0], Sdf.Reference("./cube.usda")) # drag from content window and drop into reference path for w in ui_test.find_all("Property//Frame/**/StringField[*]"): if w.widget.has_drop_fn() and w.model.get_value_as_string() == "./cube.usda": drag_target = w.center break async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__, "usd/sphere.usda") await content_browser_helper.drag_and_drop_tree_view(usd_path, drag_target=drag_target) # verify refs are correct prim = stage.GetPrimAtPath("/World/XformReference") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertEqual(len(ref_and_layers), 1) self.assertEqual(ref_and_layers[0][0], Sdf.Reference("./sphere.usda")) async def test_drag_drop_multi_usda_to_reference(self): # Test that dropping multiple usd files results in no changes. usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/XformReference"]) await wait_stage_loading() # verify refs are correct prim = stage.GetPrimAtPath("/World/XformReference") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertEqual(len(ref_and_layers), 1) self.assertEqual(ref_and_layers[0][0], Sdf.Reference("./cube.usda")) # drag from content window and drop into reference path for w in ui_test.find_all("Property//Frame/**/StringField[*]"): if w.widget.has_drop_fn() and w.model.get_value_as_string() == "./cube.usda": drag_target = w.center break async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__, "usd") await content_browser_helper.drag_and_drop_tree_view( usd_path, names=["sphere.usda", "locate_file_material.usda"], drag_target=drag_target) # verify refs are correct prim = stage.GetPrimAtPath("/World/XformReference") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertEqual(len(ref_and_layers), 1) self.assertEqual(ref_and_layers[0][0], Sdf.Reference("./cube.usda"))
3,684
Python
43.939024
121
0.657709
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_bool_arrays.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.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.kit.undo from omni.ui.tests.test_base import OmniUiTest from pxr import Kind, Sdf, Gf from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, select_prims, arrange_windows class TestBoolType(OmniUiTest): def __init__(self, tests=()): super().__init__(tests) # Before running each test async def setUp(self): await arrange_windows(topleft_window="Property", topleft_height=256, topleft_width=800.0) await open_stage(get_test_data_path(__name__, "usd/bools.usda")) await self._show_raw(False) # After running each test async def tearDown(self): await wait_stage_loading() await self._show_raw(True) async def _show_raw(self, new_state): await select_prims(["/defaultPrim/in_0"]) for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"): if w.widget.title == "Raw USD Properties": w.widget.collapsed = new_state # change prim selection immediately after collapsed state change can result in one bad frame # i.e. selection change event happens before frame UI rebuild, and old widget models are already destroyed. await ui_test.human_delay() await select_prims([]) async def test_l1_bool_test(self): # setup await wait_stage_loading() stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath('/World/Looks/bool_types/Shader') await select_prims(["/World/Looks/bool_types/Shader"]) await ui_test.human_delay() # test bool checkbox attr = prim.GetAttribute("inputs:MyBool") self.assertTrue(attr.Get()) await ui_test.find("Property//Frame/**/.identifier=='bool_inputs:MyBool'").click() self.assertFalse(attr.Get()) await ui_test.find("Property//Frame/**/.identifier=='control_state_inputs:MyBool'").click() self.assertTrue(attr.Get()) # test bool vec2 checkboxes attr = prim.GetAttribute("inputs:MyBool2") self.assertEqual(attr.Get(), (0, 0)) widget = ui_test.find("Property//Frame/**/.identifier=='boolean_per_channel_inputs:MyBool2'") for index, expected in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]): checkwidgets = widget.find_all("**/CheckBox[*]") if index & 1: await checkwidgets[1].click() if index & 2: await checkwidgets[0].click() self.assertEqual(attr.Get(), expected) await ui_test.find("Property//Frame/**/.identifier=='control_state_inputs:MyBool2'").click() self.assertEqual(attr.Get(), (0, 0)) omni.kit.undo.undo() self.assertEqual(attr.Get(), expected) omni.kit.undo.redo() self.assertEqual(attr.Get(), (0, 0)) # test bool vec3 checkboxes attr = prim.GetAttribute("inputs:MyBool3") self.assertEqual(attr.Get(), (0, 0, 0)) widget = ui_test.find("Property//Frame/**/.identifier=='boolean_per_channel_inputs:MyBool3'") for index, expected in enumerate([(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]): checkwidgets = widget.find_all("**/CheckBox[*]") if index & 1: await checkwidgets[2].click() if index & 2: await checkwidgets[1].click() if index & 4: await checkwidgets[0].click() self.assertEqual(attr.Get(), expected) await ui_test.find("Property//Frame/**/.identifier=='control_state_inputs:MyBool3'").click() self.assertEqual(attr.Get(), (0, 0, 0)) omni.kit.undo.undo() self.assertEqual(attr.Get(), expected) omni.kit.undo.redo() self.assertEqual(attr.Get(), (0, 0, 0)) # test bool vec4 checkboxes attr = prim.GetAttribute("inputs:MyBool4") self.assertEqual(attr.Get(), (0, 0, 0, 0)) widget = ui_test.find("Property//Frame/**/.identifier=='boolean_per_channel_inputs:MyBool4'") for index, expected in enumerate([(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]): checkwidgets = widget.find_all("**/CheckBox[*]") if index & 1: await checkwidgets[3].click() if index & 2: await checkwidgets[2].click() if index & 4: await checkwidgets[1].click() if index & 8: await checkwidgets[0].click() self.assertEqual(attr.Get(), expected) await ui_test.find("Property//Frame/**/.identifier=='control_state_inputs:MyBool4'").click() self.assertEqual(attr.Get(), (0, 0, 0, 0)) omni.kit.undo.undo() self.assertEqual(attr.Get(), expected) omni.kit.undo.redo() self.assertEqual(attr.Get(), (0, 0, 0, 0))
6,594
Python
44.482758
121
0.506976
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_variant.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 os import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.usd from omni.kit import ui_test from pxr import Vt, Gf from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows class PrimVariantColorProperty(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() await open_stage(get_test_data_path(__name__, "usd_variants/variant.usda")) # After running each test async def tearDown(self): await wait_stage_loading() async def test_l1_shader_material_subid_property(self): import omni.kit.commands await ui_test.find("Property").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() # select variant prim await select_prims(['/World']) await ui_test.human_delay() # verify displayColor is red prim = stage.GetPrimAtPath('/World/Sphere') attr = prim.GetAttribute('primvars:displayColor') self.assertEqual(attr.Get(), Vt.Vec3fArray(1, (Gf.Vec3f(1.0, 0.0, 0.0)))) # change variant to blue variant_widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Variants'") combo_widget = variant_widget.find("Property//Frame/**/ComboBox[*]") combo_widget.model.set_value("blue") await ui_test.human_delay(100) # verify displayColor is blue self.assertEqual(attr.Get(), Vt.Vec3fArray(1, (Gf.Vec3f(0.0, 0.0, 1.0)))) # NOTE: previous set_value will have refreshed property widget, so old values are not valid # change variant to red variant_widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Variants'") combo_widget = variant_widget.find("Property//Frame/**/ComboBox[*]") combo_widget.model.set_value("red") await ui_test.human_delay(100) # verify displayColor is red self.assertEqual(attr.Get(), Vt.Vec3fArray(1, (Gf.Vec3f(1.0, 0.0, 0.0))))
2,521
Python
37.799999
121
0.679889
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_asset_array_widget.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 pathlib import Path from typing import List import carb.input import carb.settings import omni.kit.app import omni.kit.test import omni.kit.ui_test as ui_test import omni.kit.undo import omni.usd from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper from omni.kit.test_suite.helpers import arrange_windows from omni.kit.window.file_importer.test_helper import FileImporterTestHelper TEST_DATA_PATH = Path( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/tests" ) ASSIGN_PATH_SETTINGS = "/persistent/app/material/dragDropMaterialPath" ADD_ASSET_BUTTON_QUERY = "Property//Frame/**/Button[*].identifier=='sdf_asset_array_asset_array.add_asset'" class TestAssetArray(omni.kit.test.AsyncTestCase): async def setUp(self): self._context = omni.usd.get_context() self._settings = carb.settings.get_settings() self._prev_path_setting = self._settings.get(ASSIGN_PATH_SETTINGS) self._settings.set(ASSIGN_PATH_SETTINGS, "relative") await arrange_windows("Stage", 1) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.set_config_menu_settings({'hide_unknown': False, 'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': False}) async def tearDown(self): self._settings.set(ASSIGN_PATH_SETTINGS, self._prev_path_setting) async def _add_asset(self, asset_names: List[str]): await self._browse_and_select_asset(ADD_ASSET_BUTTON_QUERY, asset_names) async def _browse_and_select_asset(self, browse_button_identifier: str, asset_names: List[str]): browse_button = ui_test.find(browse_button_identifier) await browse_button.click() async with FileImporterTestHelper() as file_importer: await file_importer.wait_for_popup() dir_url = TEST_DATA_PATH.absolute().resolve().joinpath("usd").joinpath("asset_array") await file_importer.select_items_async(str(dir_url), asset_names) await file_importer.click_apply_async(filename_url=None) async def test_asset_array_widget(self): usd_path = TEST_DATA_PATH.absolute().resolve().joinpath("usd").joinpath("asset_array").joinpath("main.usda") success, error = await self._context.open_stage_async(str(usd_path)) self.assertTrue(success, error) self._context.get_selection().set_selected_prim_paths(["/Test"], True) asset_array_attr = self._context.get_stage().GetAttributeAtPath("/Test.asset_array") await ui_test.human_delay() # Expand Raw USD Properties section raw_properties_frame = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'") raw_properties_frame.widget.collapsed = False await ui_test.human_delay() # Add first asset await self._add_asset(["dummy0.txt"]) await ui_test.human_delay() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"]) # Add second asset await self._add_asset(["dummy1.txt"]) await ui_test.human_delay() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy1.txt"]) # Reorder assets reorder_grab = ui_test.find( "Property//Frame/**/HStack[*].identifier=='sdf_asset_array_asset_array[0].reorder_grab'" ) reorder_target_grab = ui_test.find( "Property//Frame/**/HStack[*].identifier=='sdf_asset_array_asset_array[1].reorder_grab'" ) drag_target = reorder_target_grab.position + reorder_target_grab.size await reorder_grab.drag_and_drop(drag_target) self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"]) # Clear the first asset clear_asset = ui_test.find("Property//Frame/**/Button[*].identifier=='sdf_clear_asset_asset_array[0]'") await clear_asset.click() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["", "./dummy0.txt"]) # Readd the first asset from file picker await self._browse_and_select_asset( "Property//Frame/**/Button[*].identifier=='sdf_browse_asset_asset_array[0]'", ["dummy1.txt"] ) await ui_test.human_delay() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"]) # Remove the first asset remove_asset = ui_test.find("Property//Frame/**/Button[*].identifier=='sdf_asset_array_asset_array[0].remove'") await remove_asset.click() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"]) # Add 2 assets from file picker await self._add_asset(["dummy0.txt", "dummy1.txt"]) await ui_test.human_delay() self.assertEqual( [asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy0.txt", "./dummy1.txt"] ) # drag drop 2 assets from content window await ui_test.find("Content").focus() await ui_test.find("Property").focus() async with ContentBrowserTestHelper() as content_browser_helper: # await content_browser_helper.navigate_to_async(str(usd_path.parent)) browse_button = ui_test.find(ADD_ASSET_BUTTON_QUERY) await content_browser_helper.drag_and_drop_tree_view( str(usd_path.parent), ["dummy0.txt", "dummy1.txt"], browse_button.center ) await ui_test.human_delay() self.assertEqual( [asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy0.txt", "./dummy1.txt", "./dummy0.txt", "./dummy1.txt"], ) # Test undo omni.kit.undo.undo() self.assertEqual( [asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy0.txt", "./dummy1.txt"] ) omni.kit.undo.undo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"]) omni.kit.undo.undo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"]) omni.kit.undo.undo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["", "./dummy0.txt"]) omni.kit.undo.undo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"]) omni.kit.undo.undo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy1.txt"]) omni.kit.undo.undo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"]) omni.kit.undo.undo() self.assertEqual(asset_array_attr.Get(), None) # Test redo omni.kit.undo.redo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"]) omni.kit.undo.redo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy1.txt"]) omni.kit.undo.redo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"]) omni.kit.undo.redo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["", "./dummy0.txt"]) omni.kit.undo.redo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"]) omni.kit.undo.redo() self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"]) omni.kit.undo.redo() self.assertEqual( [asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy0.txt", "./dummy1.txt"] ) omni.kit.undo.redo() self.assertEqual( [asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy0.txt", "./dummy1.txt", "./dummy0.txt", "./dummy1.txt"], )
8,762
Python
44.170103
167
0.644488
omniverse-code/kit/exts/omni.kit.welcome.whats_new/omni/kit/welcome/whats_new/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") WHATS_NEW_PAGE_STYLE = {} DOCUMENT_STYLE = { "ScrollingFrame": {"background_color": 0}, "Circle": {"background_color": 0xFF000000}, }
367
Python
23.533332
70
0.713896
omniverse-code/kit/exts/omni.kit.welcome.whats_new/omni/kit/welcome/whats_new/extension.py
import webbrowser import carb.settings import carb.tokens import omni.client import omni.ext import omni.ui as ui from omni.kit.documentation.builder import DocumentationBuilderMd, DocumentationBuilderPage from omni.kit.documentation.builder import get_style as get_doc_style from omni.kit.welcome.window import register_page from omni.ui import constant as fl from .style import ICON_PATH, WHATS_NEW_PAGE_STYLE, DOCUMENT_STYLE _extension_instance = None class WhatsNewPageExtension(omni.ext.IExt): def on_startup(self, ext_id): self.__ext_name = omni.ext.get_extension_name(ext_id) register_page(self.__ext_name, self.build_ui) self.__settings = carb.settings.get_settings() url = self.__settings.get(f"/exts/{self.__ext_name}/url") self._url = carb.tokens.get_tokens_interface().resolve(url) def on_shutdown(self): global _extension_instance _extension_instance = None def build_ui(self) -> None: with ui.ZStack(style=WHATS_NEW_PAGE_STYLE): # Background ui.Rectangle(style_type_name_override="Content") with ui.VStack(): with ui.VStack(height=fl._find("welcome_page_title_height")): ui.Spacer() with ui.HStack(): ui.Spacer() ui.Button( text="VIEW ON THE WEB", width=0, spacing=10, image_url=f"{ICON_PATH}/external_link.svg", clicked_fn=self.__view_on_web, style_type_name_override="Title.Button" ) ui.Spacer() ui.Spacer() with ui.HStack(): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.ZStack(style=get_doc_style()): ui.Rectangle(style_type_name_override="Doc.Background") with ui.ScrollingFrame( style=DOCUMENT_STYLE, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, ): doc_builder = DocumentationBuilderPage(DocumentationBuilderMd(self._url)) doc_builder._dont_scale_images = True ui.Spacer(width=fl._find("welcome_content_padding_x")) ui.Spacer(height=fl._find("welcome_content_padding_y")) def __view_on_web(self): web_url = self.__settings.get(f"/exts/{self.__ext_name}/web_url") if not web_url: web_url = self._url webbrowser.open(web_url)
2,858
Python
39.842857
102
0.551435
omniverse-code/kit/exts/omni.hsscclient/omni/hsscclient/tests/load_usd.py
import argparse import asyncio import json import time from pathlib import Path import carb import carb.events import omni.kit import omni.renderer_capture import omni.stats import omni.usd from omni.hydra.engine.stats import get_device_info, get_mem_stats class StageLoader: def __init__(self) -> None: self._current_url = "" self._stage_event_sub = ( omni.usd.get_context() .get_stage_event_stream() .create_subscription_to_pop(self.on_stage_event, name="Stage Load Timer Subscription") ) self._loading = False self._future_usd_loaded = asyncio.Future() self._start_ts = 0 self._duration = 0 def duration(self): return self._duration async def wait(self): await self._future_usd_loaded def result(self): return self._future_usd_loaded.result() def load(self, url: str) -> None: if self._loading: carb.log_error("*** Cannot load a new stage while one is loading") return # enable the flag, track the current url being loaded self._loading = True self._current_url = url omni.usd.get_context().open_stage(self._current_url) return def on_stage_event(self, e: carb.events.IEvent): event = omni.usd.StageEventType(e.type) payload: dict = e.payload carb.log_info(f"***Stage Event: {event} {payload}") if event == omni.usd.StageEventType.OPENING: url = payload.get("val", None) if self._loading and url and url in self._current_url: self._start_ts = time.time() elif event == omni.usd.StageEventType.ASSETS_LOADED: if self._loading: self._loading = False self._duration = time.time() - self._start_ts carb.log_warn(f"{self._current_url} is loaded in {self._duration}s.") self._future_usd_loaded.set_result(True) elif event == omni.usd.StageEventType.OPEN_FAILED and self._loading: self._loading = False carb.log_error(f"{self._current_url} failed to load.") self._future_usd_loaded.set_result(False) usd_loader = StageLoader() def get_omni_stats(): stats_value = {} _stats = omni.stats.get_stats_interface() scopes = _stats.get_scopes() for scope in scopes: scope_name = scope["name"] # print(scope_name) stats_value[scope_name] = {} stat_nodes = _stats.get_stats(scope["scopeId"]) for stat in stat_nodes: stat_item = { "name": stat["name"], "value": stat["value"], "description": stat["description"], } stats_value[scope_name][stat["name"]] = stat_item return stats_value async def wait_stage_loading(wait_frames: int = 2): """ Waits for the USD stage in the given USD Context to load. Args: wait_frames (int): How many frames to wait after loading the stage if given (2 by default) """ usd_context = omni.usd.get_context() frame_count = 0 while True: _, files_loaded, total_files = usd_context.get_stage_loading_status() if files_loaded or total_files: await omni.kit.app.get_app().next_update_async() continue if frame_count != wait_frames: await omni.kit.app.get_app().next_update_async() frame_count += 1 continue break async def main(largs): try: app = omni.kit.app.get_app() settings_interface = carb.settings.get_settings() except AttributeError: app = omni.kit.app.get_app_interface() settings_interface = omni.kit.settings.get_settings_interface() usd_context = omni.usd.get_context() await usd_context.new_stage_async() carb.log_warn("NEW STAGE ASYNC") await wait_stage_loading(120) carb.log_warn("WAIT STAGE LOADING") output_path = Path(largs.output_folder) # load the scene usd_loader.load(largs.stage) carb.log_warn("Start loading") await usd_loader.wait() carb.log_warn("End loading") if not usd_loader.result(): app.post_quit() return # set renderer mode if largs.renderer == "rt": settings_interface.set_string("/rtx/rendermode", "RaytracedLighting") elif largs.renderer == "pt": settings_interface.set_string("/rtx/rendermode", "PathTracing") settings_interface.set_float("/rtx/pathtracing/totalSpp", 0) from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() resolution = viewport_window.viewport_api.resolution await asyncio.sleep(largs.screenshot_pause) if largs.fps: # measure FPS carb.log_warn("Start FPS measuring") frame_info = viewport_window.viewport_api.frame_info multiplier = frame_info.get("subframe_count", 1) fps = viewport_window.viewport_api.fps * multiplier carb.log_warn(f"End FPS measuring: {fps}") else: fps = None renderer = omni.renderer_capture.acquire_renderer_capture_interface() renderer.capture_next_frame_swapchain(str(output_path / largs.screenshot_file)) carb.log_warn("PRE-CAPTURE") await app.next_update_async() renderer.wait_async_capture() carb.log_warn("POST-CAPTURE") stats_file = output_path / "stats.json" stats = { "load_time": usd_loader.duration(), "fps": fps, "resolution": resolution, "omni.hydra.engine.stats.get_device_info()": get_device_info(), "omni.hydra.engine.stats.get_mem_stats()": get_mem_stats(detailed=False), "omni.stats.get_stats_interface()": get_omni_stats(), } stats_file.write_text(json.dumps(stats, indent=4)) carb.log_warn(f"Stats are saved to: {stats_file}") if largs.keep_running: carb.log_warn("You can quit Kit manually.") else: app.post_quit() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--stage", help="Full path to USD stage to render", required=True) parser.add_argument("--output_folder", help="Full path to the Output Folder", required=True) parser.add_argument("--renderer", help="Renderer mode, rt or pt", default="rt") parser.add_argument("--screenshot_file", help="Name of screenshot file to dump", default="screenshot.png") parser.add_argument("--screenshot_pause", help="Seconds to wait before taking screenshot", default=5, type=int) parser.add_argument("--fps", help="Collect FPS", default=False) parser.add_argument( "--keep_running", help="Whether to keep Kit running after benchmark is complete.", action="store_true" ) args, unknown = parser.parse_known_args() asyncio.ensure_future(main(args))
6,903
Python
32.192308
115
0.623207
omniverse-code/kit/exts/omni.hsscclient/omni/hsscclient/tests/__init__.py
from .test_hssc_integration import *
37
Python
17.999991
36
0.783784
omniverse-code/kit/exts/omni.hsscclient/omni/hsscclient/tests/test_hssc_integration.py
import csv import json import os import pathlib import shutil import socket import subprocess import time from collections import abc import carb import omni.kit.test import toml from omni.kit.core.tests.test_base import KitLaunchTest from omni.ui.tests.compare_utils import CompareMetric, compare def deep_update(sdict, udict): """Update nested-dict sdict with also-nested-dict udict, only where udict has keys set""" for k, v in udict.items(): if isinstance(v, abc.Mapping) and v: sdict[k] = deep_update(sdict.get(k, {}), v) else: sdict[k] = udict[k] return sdict def keychain(default, dictionary, keys): """Take iterable `keys` and dictionary-of-dictionaries, and keep resolving until you run out of keys. If we fail to look up, return default. Otherwise, return final value""" try: for k in keys: dictionary = dictionary[k] return dictionary except KeyError: return default class Memcached: """Class to manage memcached server shard TODO: Add multi-platform support.""" def __init__(self, objsize, poolsize, threads): """Ensure memcached is installed, then start with: - `objsize`: maximum allowed object size - `poolsize`: total memory pool size - `threads`: # of threads This will try to pick port 11211 and probe for a for a failed one.""" self.objsize = objsize self.poolsize = poolsize self.threads = threads self.ip = "127.0.0.1" tokens = carb.tokens.get_tokens_interface() thisdir = pathlib.Path(__file__).resolve().parents[7] testlibs = thisdir.joinpath(tokens.resolve("${platform}/${config}/testlibs/")) self.binpath = os.path.realpath(testlibs.joinpath(tokens.resolve("memcached/${platform}/${config}/memcached"))) self.start() def binary(self): """Memcached binary.""" return self.binpath def start(self): """Start memcached, probing for free port. Will give up after 50 tries.""" code = 71 # code 71 is "port was busy" tries = 0 port = 11211 while code == 71: args = [self.binary(), "-p", str(port), "-I", self.objsize, "-m", self.poolsize, "-t", str(self.threads)] proc = subprocess.Popen(args) # noqa: PLR1732 time.sleep(1) code = proc.poll() if code != 71: break tries += 1 port += 1 if tries > 50: raise RuntimeError("Can't start memcached!") assert proc.poll() is None self.proc = proc # Hang on to process context print(f"Started memcached @ port {port}") self.port = port # hand on to successful port @staticmethod def flush(ip, port): """This sends a `flush_all` to the memcached server at ip:port""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) s.send(bytes("flush_all\r\n", "ascii")) reply = "" dat = s.recv(4096) reply = str(dat, "utf-8") assert reply == "OK\r\n" s.close() def flush_this(self): """Member version of above""" Memcached.flush(self.ip, self.port) def stop(self): """Kills memcached process.""" self.proc.kill() @staticmethod def format_uris(uris): """Format URIs in list-of (ip, port) tuples to pass to kit.""" return ",".join((f"memcache://{ip}:{port}" for (ip, port) in uris)) def get_hssc_log(logfile): """Read CSV file at `logfile`, returning dict of columns (lists)""" with open(logfile, mode="r", encoding="utf-8") as fp: reader = csv.reader(fp, delimiter=",") items = [(s.strip(), []) for s in next(reader)] for li in reader: for idx, it in enumerate(li): items[idx][1].append(it) return {field[0]: field[1] for field in items} scenes = [ ("testtex", pathlib.Path(__file__).resolve().parents[0].joinpath("data/testtex/testtex.usda")), ] async def compare_images(golden_path: str, capture_path: str, diff_path: str, threshold: float): """Compare golden image with test image and provide diff image MSE match status.""" mse = compare( pathlib.Path(golden_path), pathlib.Path(capture_path), pathlib.Path(diff_path), cmp_metric=CompareMetric.MEAN_ERROR_SQUARED, ) matches_golden_image = mse <= threshold if matches_golden_image: carb.log_info(f"MSE of ref {golden_path} with capture {capture_path} is {mse} (PASSES {threshold})") else: carb.log_info( f"MSE of ref {golden_path} with capture {capture_path} is {mse} (FAILS {threshold}, diff image in {diff_path})" ) return mse, matches_golden_image class TestHSSCIntegration(KitLaunchTest): # pragma: no cover """Main test harness for HSS$. Starts up memcached shards and runs series of tests""" async def setUp(self): """Initialize shards""" self.shards = [Memcached("1024m", "101024", 16)] await super().setUp() async def tearDown(self): """Take down shards""" await super().tearDown() for s in self.shards: s.stop() def flush_all(self): """Clear shard states""" for s in self.shards: s.flush_this() async def runkit(self, config): """Start kit with given args, with particular knobs in `config` Returns a dict with information about output directories & logs.""" base_args = [ "--no-audio", "--enable", "omni.kit.uiapp", "--enable", "omni.hydra.rtx", "--enable", "omni.usd", "--enable", "omni.kit.window.extensions", "--enable", "omni.kit.viewport.utility", "--enable", "omni.kit.viewport.bundle", "--enable", "omni.kit.viewport.rtx", "--enable", "omni.kit.renderer.capture", "--enable", "omni.mdl", "--enable", "omni.mdl.neuraylib", "--enable", "omni.hydra.engine.stats", "--/crashreporter/skipOldDumpUpload=true", "--/crashreporter/gatherUserStory=0", # don't pop up the GUI on crash "--/app/skipOldDumpUpload=true", "--/app/renderer/sleepMsOutOfFocus=0", "--/rtx/ecoMode/enabled=false", "--/app/asyncRendering=false", "--/app/fastShutdown=true", "--/foundation/verifyOsVersion/enabled=false", "--/rtx/verifyDriverVersion/enabled=false", "--/persistent/renderer/startupMessageDisplayed=true", "--no-window", "--/app/window/hideUi=true", "--/app/docks/disabled=true", "--/app/viewport/forceHideFps=true", "--/persistent/app/viewport/displayOptions=1024", "--/app/viewport/show/lights=false", "--/app/viewport/show/audio=false", "--/app/viewport/show/camera=false", "--/app/viewport/grid/enabled=false", "--/app/window/scaleToMonitor=false", "--/app/window/dpiScaleOverride=1.0", "--/rtx-transient/dlssg/enabled=false", # OM-97205: Disable DLSS-G for now globally, so L40 tests will all pass. DLSS-G tests will have to enable it ] # Create directory, (delete if already exists) output_dir = config["test"]["resdir"] try: os.makedirs(output_dir) except FileExistsError: shutil.rmtree(output_dir) os.makedirs(output_dir) run_res = {} args = base_args[:] args += [ f"--/app/renderer/resolution/width={config['kit']['resolution'][0]}", f"--/app/renderer/resolution/height={config['kit']['resolution'][1]}", ] run_res["kit_log"] = os.path.join(output_dir, "kit.log") args += [f"--/log/file={run_res['kit_log']}"] if "hssc_config" in config: args += [ "--enable", "omni.hsscclient", f"--/rtx-transient/resourcemanager/hsscUri={Memcached.format_uris(config['hssc_config']['uris'])}", "--/rtx-transient/resourcemanager/UJITSO/enabled=true", ] if "log" in config["hssc_config"]: run_res["hssc_log"] = os.path.join(output_dir, config["hssc_config"]["log"]) args += [f"--/rtx-transient/resourcemanager/hsscLogFile={run_res['hssc_log']}"] if keychain(False, config, ("hssc_config", "preflush")): for s in config["hssc_config"]["uris"]: Memcached.flush(*s) geometry = keychain(False, config, ("ujitso", "geometry")) textures = keychain(False, config, ("ujitso", "textures")) remote = keychain(False, config, ("ujitso", "remote")) args += [f"--/rtx-transient/resourcemanager/UJITSO/geometry={str(geometry).lower()}"] args += [f"--/rtx-transient/resourcemanager/UJITSO/textures={str(textures).lower()}"] args += [f"--/rtx-transient/resourcemanager/useRemoteCache={str(remote).lower()}"] run_res["load_usd_output"] = output_dir extra_args = ["load_usd.py", f'--stage {config["test"]["usd_url"]}', "--output_folder", f"{output_dir}"] root = pathlib.Path(__file__).resolve().parent path = os.path.join(root, "load_usd.py") with open(path, mode="r", encoding="utf-8") as fp: script = fp.read() await self._run_kit_with_script(script, args=args, script_extra_args=" " + " ".join(extra_args), timeout=600) return run_res def default_config(self): """Default params for tests""" config = """[kit] resolution = [ 1280, 720] [hssc_config] log = "hssclog.csv" preflush = false [ujitso] textures = true geometry = true remote = true [test] """ return toml.loads(config) @staticmethod def get_load_time(resdict): """Return load time from json file indicated by dict""" with open(os.path.join(resdict["load_usd_output"], "stats.json"), mode="r", encoding="utf-8") as fp: stats = json.load(fp) return stats["load_time"] async def run_warm_cold(self, name, usd, overrides=None, imagecomp=False, checkwarmfaster=False): """Load `usd` twice; the expectation is that the caches are 'cold' to start with, and then 'warm' the second time.""" if overrides is None: overrides = {} self.flush_all() config = self.default_config() config = deep_update(config, overrides) config["test"]["usd_url"] = usd config["hssc_config"]["uris"] = [(s.ip, s.port) for s in self.shards] if imagecomp: hssc_config = config["hssc_config"] ujitso_config = config["ujitso"] del config["hssc_config"] del config["ujitso"] config["test"]["resdir"] = os.path.join(omni.kit.test.get_test_output_path(), f"ref_{name}") res = await self.runkit(config) ref_image = os.path.join(config["test"]["resdir"], "screenshot.png") # _ref_load = self.get_load_time(res) config["hssc_config"] = hssc_config config["ujitso"] = ujitso_config with self.subTest(f"cold {name}"): config["test"]["resdir"] = os.path.join(omni.kit.test.get_test_output_path(), f"cold_{name}") res = await self.runkit(config) if imagecomp: cold_image = os.path.join(config["test"]["resdir"], "screenshot.png") _mse, matches = await compare_images( ref_image, cold_image, os.path.join(config["test"]["resdir"], "refdiff.png"), 0.01 ) self.assertTrue(matches) log = get_hssc_log(res["hssc_log"]) self.assertGreater( len(log["id"]), 5 ) # This is a punt; we should do more detailed investation. For now, anything in the log indicates that we are talking to the HSS$ cold_load = self.get_load_time(res) with self.subTest(f"warm {name}"): config["test"]["resdir"] = os.path.join(omni.kit.test.get_test_output_path(), f"warm_{name}") res = await self.runkit(config) if imagecomp: warm_image = os.path.join(config["test"]["resdir"], "screenshot.png") _mse, matches = await compare_images( ref_image, warm_image, os.path.join(config["test"]["resdir"], "refdiff.png"), 0.01 ) self.assertTrue(matches) log = get_hssc_log(res["hssc_log"]) self.assertGreater( len(log["id"]), 5 ) # This is a punt; we should do more detailed investation. For now, anything in the log indicates that we are talking to the HSS$ warm_load = self.get_load_time(res) if checkwarmfaster: # Ideally, we could mark this as a "not critical" test, since it could be noisy. self.assertGreater(cold_load, warm_load) async def test_tex_remote(self): odict = { "ujitso": { "geometry": False, "textures": True, "remote": True, } } for name, usd in scenes: name = f"{name}_tex" with self.subTest(name): await self.run_warm_cold(name, usd, odict, imagecomp=False) async def test_tex_remote_image(self): odict = { "ujitso": { "geometry": False, "textures": True, "remote": True, } } for name, usd in scenes: name = f"{name}_tex" with self.subTest(name): await self.run_warm_cold(name, usd, odict, imagecomp=True)
14,137
Python
35.913838
177
0.56101
omniverse-code/kit/exts/omni.kit.commands/omni/kit/undo/undo.py
from datetime import datetime from collections import namedtuple, deque from functools import partial import traceback from contextlib import contextmanager import carb import omni.kit.commands from typing import Any, Tuple from .history import add_history, change_history, get_history, get_history_item from ..commands.command import _call_callbacks as call_callbacks # register undo/redo commands on system startup def register_undo_commands(): omni.kit.commands.register_all_commands_in_module(__name__) Entry = namedtuple("Entry", ["command", "name", "level", "history_key", "time"]) _undo_stack = deque() _redo_stack = deque() _on_change = set() _on_change_detailed = set() _level = 0 _group_entry = None _group_count = 0 _disabled_count = 0 _in_redo_command = False _in_repeat_command = False def _incr_command_level(): global _level _level = _level + 1 def _decr_command_level(): global _level if _level <= 0: carb.log_error(f"Can't decrement command level. Incr/decr mismatch. {_level}") return False _level = _level - 1 def _get_command_level(): return _level def _create_entry(command, name, level, history_key): global _redo_stack global _undo_stack global _in_redo_command entry = Entry(command, name, level, history_key, datetime.now()) # Reset the redo stack if the command being executed is a root level command # and we are not in the middle of a redo command. Leave the stack alone in that # case since we re-execute the commands as a fresh copy to tie in with the history system # but don't want to lose the ability to redo the remaining commands if level == 0 and not _in_redo_command: _redo_stack.clear() _undo_stack.append(entry) return entry def execute(command, name, kwargs) -> Tuple[bool, Any]: level = _get_command_level() history_key = add_history(name, kwargs, level) _incr_command_level() global _group_entry try: # If command has "undo()" method it is executed using Undo System, # unless undo functionality has been disabled using "begin_disabled()" # Otherwise just call "do()". if _disabled_count == 0 and callable(getattr(command, "undo", None)): result = _execute(command, name, level, history_key) else: call_callbacks(command, name, kwargs, omni.kit.commands.PRE_DO_CALLBACK) result = command.do() call_callbacks(command, name, kwargs, omni.kit.commands.POST_DO_CALLBACK) except Exception as e: # update the history to flag it as having an error so we can render it different change_history(history_key, error=True) # if there is an active group being created, flag it as being in error state as well if _group_entry: change_history(_group_entry.history_key, error=True) omni.kit.commands._log_error(f"Failed to execute a command: {name}.\n{omni.kit.undo.format_exception(e)}") return (False, None) finally: # always decrement the group level so we don't end up with a mismatch due to an error being raised _decr_command_level() # History changed -> dispatch change event omni.kit.commands._dispatch_changed() return (True, result) def subscribe_on_change(on_change): global _on_change _on_change.add(on_change) def unsubscribe_on_change(on_change): global _on_change _on_change.discard(on_change) def subscribe_on_change_detailed(on_change): global _on_change_detailed _on_change_detailed.add(on_change) def unsubscribe_on_change_detailed(on_change): global _on_change_detailed _on_change_detailed.discard(on_change) def can_undo(): return len(_undo_stack) > 0 def can_redo(): return len(_redo_stack) > 0 def can_repeat(): return len(_undo_stack) > 0 def clear_stack(): _undo_stack.clear() _redo_stack.clear() def get_undo_stack(): return _undo_stack def get_redo_stack(): return _redo_stack # implement these as bare commands so they integrate properly with the history part of the system class Undo(omni.kit.commands.Command): def __init__(self): super().__init__() def do(self): global _redo_stack if not can_undo(): return False keep_going = True cmds = [] history_entries = [] while keep_going and len(_undo_stack) > 0: entry = _undo_stack.pop() if entry.level == 0: _redo_stack.append(entry) keep_going = False try: history_entry = get_history_item(entry.history_key) kwargs = history_entry.kwargs if history_entry else dict() call_callbacks(entry.command, entry.name, kwargs, omni.kit.commands.PRE_UNDO_CALLBACK) entry.command.undo() call_callbacks(entry.command, entry.name, kwargs, omni.kit.commands.POST_UNDO_CALLBACK) cmds.append(entry.name) if history_entry: history_entries.append(history_entry) except Exception as e: carb.log_error(f"Failed to undo a command: {entry.name}.\n{format_exception(e)}") # take care of alerting the undo set of listeners here # the command side will be handled in the calling code # # Note: The on_change events sent when undoing a command are identical to the # ones generated when the command was originally executed or is then redone, # except when a command group is undone in which case all commands that are # part of the group will be sent as a list to a single call of the callback. # # I don't think this makes sense, firstly because when commands are executed # individually (as opposed to part of a group), there is no way to determine # whether the command is being executed, undone, or redone. Secondly, groups # of commands will generate individual callbacks when originally executed or # redone, but only a single callback for the entire group when it is undone. # # Another confusing aspect of these on_change callbacks is that there is an # identically named API exposed via the 'omni.kit.commands' module which is # used to notify subscribers when a command is registered, deregistered, or # added to the command history (which is distinct from the undo/redo stack). # # Ideally we should clean up both of these APIs, but there is existing code # that depends on the existing behaviour. There have been discussions about # deprecating this entire 'omni.kit.undo' module in favour of new APIs that # are exposed through 'omni.kit.commands' instead, which may be a good time # to address this. _dispatch_changed(cmds) _dispatch_changed_detailed(history_entries) return True class Redo(omni.kit.commands.Command): def __init__(self): super().__init__() def do(self): global _redo_stack global _in_redo_command if not can_redo(): return False # we have to play with the command level to make it look like redo isn't in the stack # the entry that is executed should be at the root level, not redo _decr_command_level() try: # treat this as a group of 1 entry = _redo_stack.pop() _in_redo_command = True return _execute_group_entries([entry]) finally: _in_redo_command = False _incr_command_level() class Repeat(omni.kit.commands.Command): def __init__(self): super().__init__() def do(self): global _undo_stack global _in_repeat_command if not can_repeat(): return False # we have to play with the command level to make it look like repeat isn't in the stack # the entry that is executed should be at the root level, not repeat _decr_command_level() try: # find the last base level command and treat it as a group of 1 for entry in reversed(_undo_stack): if entry.level == 0: _in_repeat_command = True return _execute_group_entries([entry]) finally: _in_repeat_command = False _incr_command_level() def undo(): (success, ret_val) = omni.kit.commands.execute("Undo") return success and ret_val def redo(): (success, ret_val) = omni.kit.commands.execute("Redo") return success and ret_val def repeat(): (success, ret_val) = omni.kit.commands.execute("Repeat") return success and ret_val # helper used to execute commands in the group scope when 'redo' or 'repeat' is called on the group def _execute_group_entries(entries): history = get_history() for e in entries: kwargs = history[e.history_key].kwargs if e.history_key in history else {} command = e.command if _in_repeat_command: # If we're repeating the command, we must create a new instance, # and if it's a group command we must also copy the 'do' function. command = e.command.__class__(**kwargs) if isinstance(command, GroupCommand): command.do = e.command.do (success, _) = execute(command, e.name, kwargs) if not success: raise Exception("Failed to redo or repeat commands") return True class GroupCommand(object): def __init__(self): super().__init__() # this is set once all the children run and the group is closed # it will capture all of the children (and their descendants) so we can redo them later self.do = lambda *_: carb.log_error("Descendants for group not set") # there is never anythign to do 'undo' for a group command # all the undo work is handled by the children of the group def undo(self): pass def begin_group(): """Begin group of **Commands**.""" global _group_entry global _group_count _group_count = _group_count + 1 if _group_count == 1: level = _get_command_level() _incr_command_level() # this should only be called if an undo entry is created history_key = add_history("Group", {}, level) _group_entry = _create_entry(GroupCommand(), "Group", level, history_key) def end_group(): """End group of **Commands**.""" global _group_entry global _group_count global _undo_stack _group_count = _group_count - 1 if _group_count == 0 and _group_entry is not None: _decr_command_level() try: # create a real do function now that we have the full list of entries associated with the group # grab all entries after the group until the end of the list and capture that list in a partial # function for processing if 'redo' is called on the group group_index = _undo_stack.index(_group_entry) group_entries = list(filter(lambda entry: entry.level == 1, list(_undo_stack)[group_index + 1 :])) if group_entries: _group_entry.command.do = partial(_execute_group_entries, group_entries) finally: # have to manually call the listeners since groups don't go through higher level command code _dispatch_changed([_group_entry.name]) history_entry = get_history_item(_group_entry.history_key) if history_entry: _dispatch_changed_detailed([history_entry]) omni.kit.commands._dispatch_changed() # whether there was anything to capture or not, this group is closed, so clear out the entry _group_entry = None @contextmanager def group(): """Group multiple commands in one. This function is a context manager. Example: .. code-block:: python with omni.kit.undo.group(): omni.kit.commands.execute("Foo1") omni.kit.commands.execute("Foo2") """ begin_group() try: yield finally: end_group() def begin_disabled(): """ Begin preventing **Commands** being added to the undo stack. Must be paired with a subsequent call to end_disabled() """ global _disabled_count _disabled_count = _disabled_count + 1 def end_disabled(): """ Stop preventing **Commands** being added to the undo stack. Must be paired with a prior call to begin_disabled() """ global _disabled_count if _disabled_count > 0: _disabled_count = _disabled_count - 1 else: carb.log_error(f"undo.end_disabled() called without matching prior call to undo.begin_disabled()") @contextmanager def disabled(): """Prevent commands being added to the undo stack. This function is a context manager. Example: .. code-block:: python with omni.kit.undo.disabled(): omni.kit.commands.execute("Foo1") omni.kit.commands.execute("Foo2") """ begin_disabled() try: yield finally: end_disabled() def _execute(command, name, level, history_key): try: # create an undo entry on the stack and execute its do function entry = _create_entry(command, name, level, history_key) # We want the callbacks to execute within the same undo group as the command # so that any commands they execute will be undone at the same time as this. history_entry = get_history_item(history_key) kwargs = history_entry.kwargs if history_entry else dict() call_callbacks(command, name, kwargs, omni.kit.commands.PRE_DO_CALLBACK) result = command.do() call_callbacks(command, name, kwargs, omni.kit.commands.POST_DO_CALLBACK) except Exception as error: # If the current command fails we need to unwind anything that came from it. # Undo entries on the stack until we get back to the current entry. # Any commands after this one in the stack were spawned by this command. cmd_names = [] history_entries = [] while True: last_entry = _undo_stack.pop() # run undo on the command so we don't leave things in a half complete state # trap any errors individually so each command has a chance to run try: last_entry.command.undo() # make sure to alert the system of changes to all involved commands # only add to the list if the undo command completed successfully cmd_names.append(last_entry.name) history_entry = get_history_item(last_entry.history_key) if history_entry: history_entries.append(history_entry) except Exception as e: carb.log_error(f"Failed to undo a command: {last_entry.name}.\n{format_exception(e)}") if last_entry == entry: # add it to the redo stack if it is a base level command if level == 0: _redo_stack.append(entry) # when we get back to the current command we are done break # pump the callbacks with all commands that changed _dispatch_changed(cmd_names) _dispatch_changed_detailed(history_entries) # re-raise the original error so the command system can handle it # only need to manage the undo stack here, command system will take care of the rest raise error if name: _dispatch_changed([name]) history_entry = get_history_item(history_key) if history_entry: _dispatch_changed_detailed([history_entry]) return result def _dispatch_changed(cmd_names=[]): for f in _on_change: f(cmd_names) def _dispatch_changed_detailed(cmd_entries=[]): for f in _on_change_detailed: f(cmd_entries) def format_exception(e: Exception, remove_n_last_frames: int = 2) -> str: """Pretty format exception. Include exception info, call stack of exception itself and this function callstack. This function is meant to be used in ``except`` clause. Args: e: Exception. remove_n_last_frames: Number of last call stack frames to be removed. Usually this function and few above are meaningless to the user. Returns: Formatted string. """ stack = traceback.format_list(traceback.extract_stack()[:-remove_n_last_frames]) stack.extend(["[...skipped...]\n"]) stack.extend(traceback.format_list(traceback.extract_tb(e.__traceback__))) return "".join(stack) + f"\n {e.__class__} {e}"
16,807
Python
32.955555
142
0.631463
omniverse-code/kit/exts/omni.kit.commands/omni/kit/undo/history.py
import carb.settings from collections import namedtuple, OrderedDict from functools import lru_cache from itertools import islice # implementing the history as an OrderedDict so we can cap the max size # while keeping consistent indices that outside systems can hold on to # doing it as a deque would let us cap the size, but the indices change # when the cap is hit and it slides the oldest item off # this way outside code can keep the index as well as iterate over it and things stay in the proper order MAX_HISTORY_SIZE = 1000000 _history = OrderedDict() _history_index = 0 HistoryEntry = namedtuple("HistoryEntry", ["name", "kwargs", "level", "error"]) @lru_cache() def _get_crash_report_history_count(): return carb.settings.get_settings().get("/exts/omni.kit.commands/crashReportHistoryCount") # Only convert to string primitive types, others may lead to crash (UsdStage was one of them). PRIMITIVE_TYPES = {"<class 'str'>", "<class 'int'>", "<class 'float'>", "<class 'bool'>", "<class 'pxr.Sdf.Path'>"} def _format_history_entry(history: HistoryEntry): s = "" for k, v in history.kwargs.items(): s += "(" if not s else "," value = str(v) if str(type(v)) in PRIMITIVE_TYPES else "?" s += f"{k}={value}" if s: s += ")" return history.name + s def add_history(name: str, kwargs: dict, level: int): """Add a **Command** execution to the history. Takes: (Command name, Arguments, Groupping level). Return: index that can be used to modify it later""" global _history_index _history_index = _history_index + 1 _history[_history_index] = HistoryEntry(name, kwargs, level, False) # now make sure we have <= MAX_HISTORY_SIZE elements in the history while True: # if the head of the history is a root command and we are under the size limit, we are done # otherwise we need to remove the entire group so we don't end up with children at the front of the history key = next(iter(_history)) if len(_history) else None if not key or (_history[key].level == 0 and len(_history) < MAX_HISTORY_SIZE): break # pop the entry from the front of the list and move on _history.popitem(last=False) # store last N commands for crash report (if we crash later) n = _get_crash_report_history_count() if n > 0: # join last N elements of history into comma separted string lastCommands = [_format_history_entry(x) for x in islice(reversed(_history.values()), n)] settings = carb.settings.get_settings() settings.set("/crashreporter/data/lastCommands", ",".join(reversed(lastCommands))) settings.set("/crashreporter/data/lastCommand", next(iter(lastCommands), "")) return _history_index def change_history(key: int, **kwargs): """Update the history entry for **key**. key: Index of the history entry to modify. kwargs: any of the properties of HistoryEntry.""" if key in _history: _history[key] = _history[key]._replace(**kwargs) def get_history(): """Get **Command** execution history. Returns a list of tuples: HistoryEntry(Command name, Arguments, Groupping level, Error status).""" return _history def get_history_item(history_key: int) -> HistoryEntry: try: return _history[history_key] # if the key is missing return None, any other erros should flow through to the caller except KeyError: return None def clear_history(): """Clear **Command** execution history.""" _history.clear()
3,568
Python
35.050505
115
0.672926
omniverse-code/kit/exts/omni.kit.commands/omni/kit/undo/__init__.py
from .history import clear_history, get_history from .undo import ( execute, begin_group, end_group, begin_disabled, end_disabled, disabled, format_exception, get_redo_stack, get_undo_stack, clear_stack, group, redo, undo, repeat, can_undo, can_redo, can_repeat, subscribe_on_change, unsubscribe_on_change, register_undo_commands, subscribe_on_change_detailed, unsubscribe_on_change_detailed, ) # register undo/redo commands on system startup register_undo_commands()
557
Python
18.241379
47
0.660682
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/command_actions.py
import omni.kit.actions.core def register_actions(extension_id): import omni.kit.undo action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Command Actions" action_registry.register_action( extension_id, "undo", omni.kit.undo.undo, display_name="Command->Undo", description="Undo the last command that was executed.", tag=actions_tag, ) action_registry.register_action( extension_id, "redo", omni.kit.undo.redo, display_name="Command->Redo", description="Redo the last command that was undone.", tag=actions_tag, ) action_registry.register_action( extension_id, "repeat", omni.kit.undo.repeat, display_name="Command->Repeat", description="Repeat the last command that was executed or redone.", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
1,097
Python
27.153845
75
0.642662
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/__init__.py
"""Commands for Omniverse Kit. :mod:`omni.kit.commands` module is used to register and execute **Commands**. It is built on top of :mod:`omni.kit.undo` module to enable undo/redo operations with **Commands**. **Command** is any class with ``do()`` method and optionally ``undo()`` method. If **Command** has ``undo()`` method it is put on the undo stack when executed. It must be inherited from :class:`Command` class for type checking. Example of creating your command, registering it, passing arguments and undoing. .. code-block:: python class MyOrange(omni.kit.commands.Command): def __init__(self, bar: list): self._bar = bar def do(self): self._bar.append('orange') def undo(self): del self._bar[-1] >>> import omni.kit.commands >>> omni.kit.commands.register(MyOrangeCommand) >>> my_list = [] >>> omni.kit.commands.execute("MyOrange", bar=my_list) >>> my_list ['orange'] >>> import omni.kit.undo >>> omni.kit.undo.undo() >>> my_list [] >>> omni.kit.undo.redo() >>> my_list ['orange'] """ __all__ = [ "Command", "create", "register", "register_all_commands_in_module", "unregister_module_commands", "unregister", "PRE_DO_CALLBACK", "POST_DO_CALLBACK", "PRE_UNDO_CALLBACK", "POST_UNDO_CALLBACK", "register_callback", "unregister_callback", "get_command_class", "get_command_class_signature", "get_command_doc", "get_command_parameters", "get_commands", "get_commands_list", "execute", "execute_argv", "get_argument_parser_from_function", "set_logging_enabled", ] from .command import ( Command, create, register, register_all_commands_in_module, unregister_module_commands, unregister, PRE_DO_CALLBACK, POST_DO_CALLBACK, PRE_UNDO_CALLBACK, POST_UNDO_CALLBACK, register_callback, unregister_callback, get_command_class, get_command_class_signature, get_command_doc, get_command_parameters, get_commands, get_commands_list, execute, execute_argv, get_argument_parser_from_function, _log_error, set_logging_enabled, ) from .command_actions import register_actions, deregister_actions from .command_bridge import CommandBridge from .on_change import subscribe_on_change, unsubscribe_on_change, _dispatch_changed import omni.ext import omni.kit.app # this is needed for physx.ui # once it properly imports its own dependencies, it can be removed from typing import Any class CommandExt(omni.ext.IExt): """Monitor for new extensions and register all commands in python modules of those extensions, along with setting up a bridge that allows commands to be registered and executed from C++, and registration of actions that wrap some basic command functionality like undo and redo. """ def on_startup(self, ext_id): # Setup the command bridge self._command_bridge = CommandBridge() self._command_bridge.on_startup() # Register command related actions self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name) # Monitor for commands in new or reloaded extensions manager = omni.kit.app.get_app().get_extension_manager() def on_change(e): if e.type == omni.ext.EXTENSION_EVENT_SCRIPT_CHANGED: def register_subclasses(cls): register(cls) for subcls in cls.__subclasses__(): register_subclasses(subcls) register_subclasses(Command) self._change_script_sub = manager.get_change_event_stream().create_subscription_to_pop( on_change, name="kit.commands ExtensionChange" ) def on_shutdown(self): # Stop monitoring for commands in new or reloaded extensions self._change_script_sub = None # Deregister command related actions deregister_actions(self._ext_name) # Shutdown the command bridge self._command_bridge.on_shutdown() self._command_bridge = None
4,133
Python
28.319149
177
0.651585
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/on_change.py
_on_change = set() def subscribe_on_change(on_change): """Subscribe to module change events. Triggered when commands added, executed.""" global _on_change _on_change.add(on_change) def unsubscribe_on_change(on_change): """Unsubscribe to module change events.""" global _on_change _on_change.discard(on_change) def _dispatch_changed(): for f in _on_change: f()
402
Python
20.210525
85
0.661692
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/command_bridge.py
import carb from ._kit_commands import * from .command import ( Command, execute, register, unregister, get_command_class, ) class CommandBridge: def on_startup(self): self._command_bridge = acquire_command_bridge() def register_cpp_command( extension_id: str, command_name: str, default_kwargs: dict, optional_kwargs: dict, required_kwargs: dict ): def constructor(self, **kwargs): # Check whether all the required keyword arguments specified from C++ have been provided. for required_kwarg in self._required_kwargs: if not required_kwarg in kwargs: carb.log_error( f"Required keyword argument '{required_kwarg}' not found when executing C++ command '{self.__class__.__name__}'." ) # Check whether all the provided keyword arguments were specified as expected from C++. for supplied_key, supplied_value in kwargs.items(): expected_value = self._all_kwargs.get(supplied_key, None) if expected_value is None: carb.log_warn( f"Unexpected keyword argument '{supplied_key}' encountered when executing C++ command '{self.__class__.__name__}'." ) # Merge the provided keyword arguments with the defaults specified from C++. kwargs_with_defaults = {} kwargs_with_defaults.update(self._default_kwargs) kwargs_with_defaults.update(kwargs) # Create the underlying C++ command object that can later be 'done' and 'undone. self._cpp_command_object = self._command_bridge.create_cpp_command_object( self.__class__.__module__, self.__class__.__name__, **kwargs_with_defaults ) def do(self): return self._cpp_command_object.do() def undo(self): self._cpp_command_object.undo() new_cpp_command_class = type( command_name, (omni.kit.commands.Command,), { "__module__": extension_id, "__init__": constructor, "_default_kwargs": default_kwargs, "_optional_kwargs": optional_kwargs, "_required_kwargs": required_kwargs, "_all_kwargs": {**default_kwargs, **optional_kwargs, **required_kwargs}, "_command_bridge": self._command_bridge, "do": do, "undo": undo, }, ) omni.kit.commands.register(new_cpp_command_class) def get_qualified_command_name(extension_id: str, command_name: str): return extension_id + "." + command_name if extension_id else command_name def deregister_cpp_command(extension_id: str, command_name: str): qualified_command_name = get_qualified_command_name(extension_id, command_name) command_class = omni.kit.commands.get_command_class(qualified_command_name) if command_class: omni.kit.commands.unregister(command_class) command_class._command_bridge = None def execute_command_from_cpp(extension_id: str, command_name: str, **kwargs): qualified_command_name = get_qualified_command_name(extension_id, command_name) return omni.kit.commands.execute(qualified_command_name, **kwargs) import omni.kit.undo self._command_bridge.enable( register_cpp_command, deregister_cpp_command, execute_command_from_cpp, omni.kit.undo.undo, omni.kit.undo.redo, omni.kit.undo.repeat, omni.kit.undo.begin_group, omni.kit.undo.end_group, omni.kit.undo.begin_disabled, omni.kit.undo.end_disabled, ) def on_shutdown(self): self._command_bridge.disable() release_command_bridge(self._command_bridge) self._command_bridge = None
4,240
Python
40.174757
143
0.554245
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/command.py
import argparse import carb from collections import defaultdict import inspect import re import sys from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Tuple, Type from .on_change import _dispatch_changed _commands = defaultdict(dict) LOGGING_ENABLED = True # Callback types PRE_DO_CALLBACK = 'pre_do' POST_DO_CALLBACK = 'post_do' PRE_UNDO_CALLBACK = 'pre_undo' POST_UNDO_CALLBACK = 'post_undo' # Callback dictionary: # Keys: tuple(command class name minus any trailing 'Command', module name), callback type. # Value: list of callables. _callbacks: Dict[Tuple[str, str], Dict[str, List[Callable]]] = defaultdict(lambda: defaultdict(list)) # Callback ID object. We don't expose this publicly to prevent users from relying on its internal representation. class CallbackID: def __init__(self, command_name, module_name, callback_type, callback): self.__command_name = command_name self.__module_name = module_name self.__cb_type = callback_type self.__callable = callback def get(self): return (self.__command_name, self.__module_name, self.__cb_type, self.__callable) class Command(ABC): """Base class for all **Commands**.""" @abstractmethod def do(self): pass def modify_callback_info(self, cb_type: str, args: Dict[str, Any]) -> Dict[str, Any]: """Returns a dictionary of information to be passed to callbacks of the given type. By default callbacks are passed a copy of the arguments which were passed to **execute()** when the command was invoked. This method can be overridden to modify that information for specific callback types. Args: cb_type: Type of callback the information will be passed to. args: A dictionary containing a copy of the arguments with which the command was invoked. This is a shallow copy so implementations may add, remove or replace dictionary elements but should not modify any of the objects contained within it. Returns: A dictionary of information to be passed to callbacks of the specified type. """ return args def _log_error(message: str): if LOGGING_ENABLED: carb.log_error(message) def set_logging_enabled(enabled: bool): global LOGGING_ENABLED LOGGING_ENABLED = enabled def _get_module_and_class(name: str) -> Tuple[str, str]: x = name.rsplit(".", 1) if len(x) > 1: return x[0], x[1] return "", x[0] def _get_module_and_stripped_class(name: str) -> Tuple[str, str]: if name.endswith('Command'): name = name[:-7] return _get_module_and_class(name) def create(name, **kwargs): """Create **Command** object. Args: name: **Command** name. **kwargs: Arbitrary keyword arguments to be passed into into **Command** constructor. Returns: **Command** object if succeeded. `None` if failed. """ command_class = get_command_class(name) if not command_class: return None return command_class(**kwargs) def register(command_class: Type[Command]): """Register a **Command**. Args: command_class: **Command** class. """ if not issubclass(command_class, Command): _log_error(f"Can't register command: {command_class} it is not a subclass of a Command.") return global _commands name = command_class.__name__ module = command_class.__module__ if module in _commands[name]: carb.log_verbose('Command: "{}" is already registered. Overwriting it.'.format(name)) # If the class contains the "Command" suffix, register it without the suffix if name.endswith("Command"): name = name[:-7] _commands[name][module] = command_class _dispatch_changed() def register_all_commands_in_module(module): """Register all **Commands** found in specified module. Register all classes in module which inherit :class:`omni.kit.commands.Command`. Args: module: Module name or module object. Returns: An accessor object that contains a function for every command to execute it. e.g. if you register the commands "Run" and "Hide" then the accessor behaves like: .. code-block:: python class Accessor: @staticmethod def Run(**kwargs): execute("Run", **kwargs) @staticmethod def Hide(**kwargs): execute("Hide", **kwargs) This gives you a nicer syntax for running your commands: .. code-block:: python cmds = register_all_commands_in_module(module) cmds.Run(3.14) cmds.Hide("Behind the tree") """ class CommandInterface: class Immediate: pass def add_command(cls, name: str, command: Command): def execute_command(cls, **kwargs): return execute(command.__name__, **kwargs) def execute_command_immediate(cls, **kwargs): return command.do_immediate(**kwargs) execute_command.__doc__ = command.__doc__ execute_command.__name__ = name setattr(cls, name, execute_command) # If the command has an immediate mode add that to the command interface too if hasattr(command, "do_immediate"): if not hasattr(cls, "imm"): setattr(cls, "imm", CommandInterface.Immediate()) execute_command_immediate.__doc__ = command.do_immediate.__doc__ execute_command_immediate.__name__ = name setattr(cls.imm, name, command.do_immediate) if isinstance(module, str) and module in sys.modules: module = sys.modules[module] for name in dir(module): obj = getattr(module, name) if isinstance(obj, type) and issubclass(obj, Command) and obj is not Command: register(obj) # Strip the redundant "Command" suffix if it exists on the command, so you can run "CreateNodeCommand" # by calling command_interface.CreateNode() if obj.__name__.endswith("Command"): add_command(CommandInterface, obj.__name__[:-7], obj) else: add_command(CommandInterface, obj.__name__, obj) return CommandInterface() def unregister_module_commands(command_interface): """Unregister the list of commands registered by register_all_commands_in_module Args: command_interface: An object whose only members are command classes that were registered """ if command_interface is None: return for command_name in dir(command_interface): command_class = get_command_class(command_name) if command_class is not None: unregister(command_class) def unregister(command_class: Type[Command]): """Unregister a **Command**. Args: command_class: **Command** class. """ if not issubclass(command_class, Command): _log_error(f"Can't unregister command: {command_class} it is not a subclass of a Command.") return global _commands, _callbacks name = command_class.__name__ # If the class contains the "Command" suffix, unregister it without the suffix if name.endswith("Command"): name = name[:-7] module = command_class.__module__ _commands[name].pop(module, None) _callbacks.pop((name, module), None) _dispatch_changed() def get_command_class(name: str) -> Type[Command]: """Get **Command** class(type) by name. Args: name: **Command** name. It may include a module name to be more specific and avoid conflicts. Returns: **Command** class if succeeded. `None` if can't find a command with this name. """ module_name, class_name = _get_module_and_class(name) cmds = _commands[class_name] if len(cmds) == 0: # Backward compatibility - allow commands to be invoked with "Command" suffix in their name if name.endswith("Command"): stripped_name = name[:-7] module_name, class_name = _get_module_and_class(stripped_name) cmds = _commands[class_name] if not cmds: return None else: return None if len(cmds) == 1: return next(iter(cmds.values())) else: if module_name == "": _log_error(f"There are multiple commands with {name}. Pass full command name including module name.") return None return cmds.get(module_name, None) def get_command_class_signature(name: str): """Get the init signature for a **Command**. Args: name: **Command** name. It may include a module name to be more specific and avoid conflicts. Returns: __init__ signature """ command_class = get_command_class(name) if command_class is None: return None function = command_class.__init__ return inspect.signature(function) def get_command_doc(name: str) -> str: """Get **Command** docstring by name. Args: name: **Command** name. It may include a module name to be more specific and avoid conflicts. Returns: Python docstring (__doc__) from a command type. """ command_class = get_command_class(name) return inspect.getdoc(command_class) if command_class else "" def register_callback(name: str, cb_type: str, callback: Callable[[Dict[str, Any]], None]) -> CallbackID: """Register a callback for a command. Args: name: **Command** name. It may include a module name to be more specific and avoid conflicts. cb_type: Type of callback. Currently supported types are: PRE_DO_CALLBACK - called before the command is executed POST_DO_CALLBACK - called after the command is executed PRE_UNDO_CALLBACK - called before the command is undone POST_UNDO_CALLBACK - called after the command is undone callback: Callable to be called. Will be passed a dictionary of information specific to that command invocation. By default the dictionary will contain the parameters passed to execute(), but this may be overridden by individual commands so check their documentation. Many command parameters are optional so it is important that callbacks check for their presence before attempting to access them. The callback must not make any changes to the dictionary passed to it. Returns: An ID that can be passed to **unregister_callback**. """ global _callbacks module_name, class_name = _get_module_and_stripped_class(name) _callbacks[(class_name, module_name)][cb_type] += [callback] return CallbackID(class_name, module_name, cb_type, callback) def unregister_callback(id: CallbackID): """Unregister a command callback previously registered through **register_callback**. Args: id: The ID returned by **register_callback** when the callback was registered. """ global _callbacks if isinstance(id, CallbackID): class_name, module_name, cb_type, callback = id.get() cbs = _callbacks[(class_name, module_name)][cb_type] try: cbs.remove(callback) return except: pass carb.log_error(f'Attempt to unregister a {cb_type} callback on {module_name}.{class_name} which was not registered.') else: carb.log_error('Invalid callback id') class CommandParameter: """Parameter details from inspect.Parameter with documentation if present""" def __init__(self, param: inspect.Parameter, doc): self._param = param self._doc = doc @property def name(self) -> str: if self._param.kind == inspect.Parameter.VAR_POSITIONAL: return "*" + self._param.name elif self._param.kind == inspect.Parameter.VAR_KEYWORD: return "**" + self._param.name return self._param.name @property def type(self): if self._param.annotation is inspect._empty: return None return self._param.annotation @property def type_str(self) -> str: if self._param.annotation is inspect._empty: return "" return inspect.formatannotation(self._param.annotation) @property def default(self): if self._param.default is inspect._empty: return None return self._param.default @property def default_str(self) -> str: if self._param.default is inspect._empty: return "" return str(self._param.default) @property def doc(self) -> str: return self._doc def get_command_parameters(name: str) -> List[Type[CommandParameter]]: """Get all parameters for a **Commands**. Args: name: **Command** name. It may include a module name to be more specific and avoid conflicts. Returns: A list of **CommandParameter** (except 'self' parameter) """ command_class = get_command_class(name) if command_class is None: return [] result = [] function = command_class.__init__ vardata = _get_argument_doc(function.__doc__ or command_class.__doc__) sig = inspect.signature(function) for param in sig.parameters.values(): if param.name == "self": continue var_help = "" if param.name in vardata and "doc" in vardata[param.name]: var_help = vardata[param.name]["doc"] result.append(CommandParameter(param, var_help)) return result def get_commands(): """Get all registered **Commands**.""" return _commands def get_commands_list() -> List[Type[Command]]: """Return list of all **Command** classes registered.""" return [c for m in _commands.values() for c in m.values()] def _get_callback_info(cb_type:str, command: Command, cmd_args: Dict[str, Any]) -> Dict[str, Any]: cmd_args = cmd_args.copy() info = command.modify_callback_info(cb_type, cmd_args) if isinstance(info, dict): return info return cmd_args def _call_callbacks(command: Command, name: str, kwargs: Dict[str, Any], cb_type: str): module_name, class_name = _get_module_and_stripped_class(name) callbacks = _callbacks[(class_name, module_name)][cb_type] if callbacks: info = _get_callback_info(cb_type, command, kwargs) for cb in callbacks: cb(info) def execute(name, **kwargs) -> Tuple[bool, Any]: """Execute **Command**. Args: name: **Command** name. Can be class name (e.g. "My") or full name including module (e.g. "foo.bar.MyCommand") **kwargs: Arbitrary keyword arguments to be passed into into **Command** constructor. """ # Create command using passed params command = create(name, **kwargs) # Check command is valid if not command: _log_error("Can't execute command: \"{}\", it wasn't registered or ambigious.".format(name)) return (False, None) if not callable(getattr(command, "do", None)): _log_error("Can't execute command: \"{}\", it doesn't have do() method.".format(name)) return (False, None) import omni.kit.undo # Prevent a circular dependency which breaks the doc-gen # Execute the command. result = omni.kit.undo.execute(command, name, kwargs) return result def execute_argv(name, argv: list) -> Tuple[bool, Any]: """Execute **Command** using argument list.. Attempts to convert argument list into **Command**'s kwargs. If a **Command** has *get_argument_parser* method defined, it will be called to get :class:`argparse.ArgumentParser` instance to use for parsing. Otherwise command docstring is used to extract argument information. Args: name: **Command** name. argv: Argument list. """ command_class = get_command_class(name) if not command_class: return (False, None) kwargs = {} cmd_argparse = None if hasattr(command_class, "get_argument_parser"): cmd_argparse = command_class.get_argument_parser() else: cmd_argparse = get_argument_parser_from_function(command_class.__init__) try: parsed_args = cmd_argparse.parse_known_args(argv) kwargs = vars(parsed_args[0]) except SystemExit: pass return execute(name, **kwargs) def _get_argument_doc(doc): if doc is None: return {} vardata = {} param_name = None for line in doc.splitlines(): stripped = line.strip() if stripped: m = re.match(r"\s*(?P<param>\w+)(?P<type>.*): (?P<doc>.*)", line) if m is not None: param_name = m.group("param") vardata[param_name] = {} vardata[param_name]["doc"] = m.group("doc") elif param_name is not None: # group multiline doc with previous param vardata[param_name]["doc"] += " " + stripped else: param_name = None return vardata def get_argument_parser_from_function(function): fn_argparse = argparse.ArgumentParser() # Note: should probably be replaced with `vardata = _get_argument_doc(function)` param_regex = re.compile(r":param (?P<param>\w+)[\[\s\[]*(?P<meta>[\w\s\,]*)[\]\]*]*: (?P<doc>.*)") vardata = {} for var_match in re.finditer(param_regex, function.__doc__): param_name = var_match.group("param") vardata[param_name] = {} vardata[param_name]["doc"] = var_match.group("doc") vardata[param_name]["meta"] = var_match.group("meta") varnames = function.__code__.co_varnames for var_name in varnames: if var_name == "self": continue var_help = "" is_required = True nargs = None if var_name in vardata: var_help = vardata[var_name]["doc"] if "optional" in vardata[var_name]["meta"]: is_required = False if "list" in vardata[var_name]["meta"]: nargs = "*" if nargs is not None: fn_argparse.add_argument( "--" + var_name, nargs=nargs, metavar=var_name, help=var_help, required=is_required ) else: fn_argparse.add_argument("--" + var_name, metavar=var_name, help=var_help, required=is_required) return fn_argparse
18,541
Python
32.529837
210
0.621434
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/builtin/__init__.py
from .settings_commands import *
33
Python
15.999992
32
0.787879
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/builtin/settings_commands.py
import carb.settings import omni.kit.commands class ChangeSettingCommand(omni.kit.commands.Command): """ Change setting **Command**. Args: path: Path to the setting to change. value: New value to change to. prev: Previous value to for undo operation. If `None` current value would be saved as previous. """ def __init__(self, path, value, prev=None): super().__init__() self._value = value self._prev = prev self._path = path self._settings = carb.settings.get_settings() def do(self): if self._prev is None: self._prev = self._settings.get(self._path) self._settings.set(self._path, self._value) def undo(self): self._settings.set(self._path, self._prev) class ChangeDraggableSettingCommand(omni.kit.commands.Command): """ Change draggable setting **Command**. Args: path: Path to the setting to change. value: New value to change to. """ def __init__(self, path, value): super().__init__() self._value = value self._path = path self._settings = carb.settings.get_settings() def do(self): self._settings.set(self._path, self._value)
1,253
Python
25.124999
103
0.596169
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/tests/test_commands.py
import carb.settings import omni.kit.test import omni.kit.commands import omni.kit.undo from functools import partial from ._kit_command_tests import * _result = [] _command_tests = None def setUpModule(): global _command_tests _command_tests = acquire_command_tests() def tearDownModule(): global _command_tests release_command_tests(_command_tests) _command_tests = None class TestAppendCommand(omni.kit.commands.Command): def __init__(self, x, y): self._x = x self._y = y def do(self): global _result _result.append(self._x) _result.append(self._y) def undo(self): global _result del _result[-1] del _result[-1] def modify_callback_info(self, cb_type, cmd_args): if cb_type == omni.kit.commands.PRE_DO_CALLBACK: cmd_args['pre_do'] = 1 elif cb_type == omni.kit.commands.POST_DO_CALLBACK: cmd_args['post_do'] = 2 elif cb_type == omni.kit.commands.PRE_UNDO_CALLBACK: cmd_args['pre_undo'] = 3 elif cb_type == omni.kit.commands.POST_UNDO_CALLBACK: cmd_args['post_undo'] = 4 else: cmd_args['other'] = 5 return cmd_args class TestAppendNoUndoCommand(omni.kit.commands.Command): def __init__(self, x, y): self._x = x self._y = y def do(self): global _result _result.append(self._x) _result.append(self._y) class TestRaiseException(omni.kit.commands.Command): def __init__(self, x, y): self._x = x self._y = y def do(self): raise Exception("testing an error happening") global _result _result.append(self._x) _result.append(self._y) class TestNoBaseCommand: def __init__(self, x, y): self._x = x self._y = y def do(self): global _result _result.append(self._x) _result.append(self._y) class TestMissingDoMethod(omni.kit.commands.Command): def __init__(self, x, y): global _result _result.append(x) _result.append(y) class TestCommandParameters(omni.kit.commands.Command): """ TestCommandParameters **Command**. Args: x: x argument doc yy: int: yy argument doc slightly longer zzz: zzz argument doc but on 2 lines More info here. """ def __init__(self, x, yy: int, zzz="some default value"): self._x = x self._y = yy self._z = zzz def do(self): pass def undo(self): pass class TestCommands(omni.kit.test.AsyncTestCase): async def setUp(self): # Cache the command tests interface. global _command_tests self.command_tests = _command_tests # Disable logging for the time of tests to avoid spewing errors omni.kit.commands.set_logging_enabled(False) # make sure we are starting from a clean state omni.kit.undo.clear_stack() # Register all commands omni.kit.commands.register(TestAppendCommand) omni.kit.commands.register(TestAppendNoUndoCommand) omni.kit.commands.register(TestRaiseException) omni.kit.commands.register(TestNoBaseCommand) omni.kit.commands.register(TestMissingDoMethod) omni.kit.commands.register(TestCommandParameters) async def tearDown(self): # Unregister all commands omni.kit.commands.unregister(TestAppendCommand) omni.kit.commands.unregister(TestAppendNoUndoCommand) omni.kit.commands.unregister(TestRaiseException) omni.kit.commands.unregister(TestNoBaseCommand) omni.kit.commands.unregister(TestMissingDoMethod) omni.kit.commands.unregister(TestCommandParameters) omni.kit.commands.set_logging_enabled(True) # Clear the command tests interface. self.command_tests = None async def test_commands(self): global _result # Execute and undo _result = [] omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(_result, [1, 2]) omni.kit.undo.undo() self.assertListEqual(_result, []) # Execute and undo command with undo _result = [] undo_stack_len = len(omni.kit.undo.get_undo_stack()) omni.kit.commands.execute("TestAppendNoUndo", x=1, y=2) self.assertListEqual(_result, [1, 2]) self.assertEqual(undo_stack_len, len(omni.kit.undo.get_undo_stack())) # Execute command without base, it should not be registered _result = [] omni.kit.commands.execute("TestNoBase", x=1, y=2) self.assertListEqual(_result, []) # Unregister -> execution does nothing omni.kit.commands.unregister(TestAppendCommand) omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(_result, []) # Register twice works fine omni.kit.commands.register(TestAppendCommand) omni.kit.commands.register(TestAppendCommand) omni.kit.commands.execute("omni.kit.builtin.tests.core.test_commands.TestAppendCommand", x=1, y=2) self.assertListEqual(_result, [1, 2]) # Automatically register command from a module _result = [] omni.kit.commands.unregister(TestAppendCommand) omni.kit.commands.register_all_commands_in_module(__name__) omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2]) omni.kit.undo.undo() self.assertListEqual(_result, []) _result = [] omni.kit.commands.execute("TestAppendNoUndo", x=1, y=2) self.assertListEqual(_result, [1, 2]) _result = [] omni.kit.commands.execute("TestNoBase", x=1, y=2) self.assertListEqual(_result, []) async def test_multiple_calls(self): global _result # make sure that Undo/Redo work properly when called on multiple commands _result = [] omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(_result, [1, 2]) omni.kit.commands.execute("TestAppend", x=3, y=4) self.assertListEqual(_result, [1, 2, 3, 4]) # first call should do actual work and return True res = omni.kit.undo.undo() self.assertListEqual(_result, [1, 2]) self.assertTrue(res) # same for second since 2 commands were run res = omni.kit.undo.undo() self.assertListEqual(_result, []) self.assertTrue(res) # third call should do nothing and return False res = omni.kit.undo.undo() self.assertListEqual(_result, []) self.assertFalse(res) # now do the same for Redo # first call should do actual work and return True res = omni.kit.undo.redo() self.assertListEqual(_result, [1, 2]) self.assertTrue(res) # test undo while there are still commands on the redo stack res = omni.kit.undo.undo() self.assertListEqual(_result, []) self.assertTrue(res) # now redo both of the original commands res = omni.kit.undo.redo() self.assertListEqual(_result, [1, 2]) self.assertTrue(res) res = omni.kit.undo.redo() self.assertListEqual(_result, [1, 2, 3, 4]) self.assertTrue(res) # third call should do nothing and return False res = omni.kit.undo.redo() self.assertListEqual(_result, [1, 2, 3, 4]) self.assertFalse(res) def test_group(self): global _result # Group multiple commands _result = [] omni.kit.undo.begin_group() omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) omni.kit.undo.end_group() self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.undo.undo() self.assertListEqual(_result, []) # Context manager version _result = [] with omni.kit.undo.group(): omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.undo.undo() self.assertListEqual(_result, []) # Nested groups do nothing different: _result = [] omni.kit.undo.begin_group() omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) omni.kit.undo.begin_group() omni.kit.commands.execute("TestAppend", x=5, y=6) omni.kit.commands.execute("TestAppend", x=7, y=8) omni.kit.undo.end_group() omni.kit.undo.end_group() self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8]) omni.kit.undo.undo() self.assertListEqual(_result, []) # test redo/undo multiple times with groups omni.kit.undo.redo() self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8]) omni.kit.undo.undo() self.assertListEqual(_result, []) omni.kit.undo.redo() self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8]) omni.kit.undo.undo() self.assertListEqual(_result, []) # Group multiple commands from C++ _result = [] self.command_tests.test_begin_undo_group_from_cpp() omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) self.command_tests.test_end_undo_group_from_cpp() self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.undo.undo() self.assertListEqual(_result, []) def test_disabled(self): global _result # Disable undo _result = [] omni.kit.undo.begin_disabled() omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) omni.kit.undo.end_disabled() self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) # Context manager version _result = [] with omni.kit.undo.disabled(): omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.commands.execute("TestAppend", x=5, y=6) omni.kit.commands.execute("TestAppend", x=7, y=8) omni.kit.undo.undo() omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) # Disable undo then enable _result = [] omni.kit.undo.begin_disabled() omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) omni.kit.undo.end_disabled() omni.kit.commands.execute("TestAppend", x=5, y=6) omni.kit.commands.execute("TestAppend", x=7, y=8) self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4, 5, 6]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) # Nested calls to disable undo _result = [] omni.kit.undo.begin_disabled() omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) omni.kit.undo.begin_disabled() omni.kit.commands.execute("TestAppend", x=5, y=6) omni.kit.commands.execute("TestAppend", x=7, y=8) omni.kit.undo.end_disabled() omni.kit.undo.end_disabled() self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8]) # Disable undo then enable from C++ _result = [] self.command_tests.test_begin_undo_disabled_from_cpp() omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) self.command_tests.test_end_undo_disabled_from_cpp() omni.kit.commands.execute("TestAppend", x=5, y=6) omni.kit.commands.execute("TestAppend", x=7, y=8) self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4, 5, 6]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) async def test_error(self): global _result # test command raising and exception during `do()` _result = [] res = omni.kit.commands.execute("TestRaiseException", x=1, y=2) self.assertEqual(res, (False, None)) self.assertListEqual(_result, []) # test command TypeError exception because `do()` is missing _result = [1, 2] try: omni.kit.commands.execute("TestMissingDoMethod", x=3, y=4) except TypeError: _result = [] self.assertListEqual(_result, []) async def test_command_parameters(self): params = omni.kit.commands.get_command_parameters("TestCommandParameters") # test parameters self.assertEqual(len(params), 3) self.assertEqual(params[0].name, "x") self.assertEqual(params[1].name, "yy") self.assertEqual(params[2].name, "zzz") self.assertEqual(params[0].type_str, "") self.assertEqual(params[1].type_str, "int") self.assertEqual(params[2].type_str, "") self.assertEqual(params[0].default_str, "") self.assertEqual(params[1].default_str, "") self.assertEqual(params[2].default_str, "some default value") # test documentation in parameters self.assertEqual(params[0].doc, "x argument doc") self.assertEqual(params[1].doc, "yy argument doc slightly longer") self.assertEqual(params[2].doc, "zzz argument doc but on 2 lines") async def test_callbacks(self): self.x = None self.y = None self.pre_do_count = 0 self.post_do_count = 0 self.pre_undo_count = 0 self.post_undo_count = 0 self.cmd_specific_pre_do_count = 0 self.cmd_specific_post_do_count = 0 self.cmd_specific_pre_undo_count = 0 self.cmd_specific_post_undo_count = 0 self.cmd_specific_other_count = 0 def pre_do_callback(self, info): self.pre_do_count += 1 self.x = info.get('x', None) if info.get('pre_do', None): self.cmd_specific_pre_do_count += 1 if info.get('post_do', None): self.cmd_specific_post_do_count += 1 if info.get('pre_undo', None): self.cmd_specific_pre_undo_count += 1 if info.get('post_undo', None): self.cmd_specific_post_undo_count += 1 if info.get('other', None): self.cmd_specific_other_count += 1 def post_do_callback(self, info): self.post_do_count += 1 self.y = info.get('y', None) if info.get('pre_do', None): self.cmd_specific_pre_do_count += 1 if info.get('post_do', None): self.cmd_specific_post_do_count += 1 if info.get('pre_undo', None): self.cmd_specific_pre_undo_count += 1 if info.get('post_undo', None): self.cmd_specific_post_undo_count += 1 if info.get('other', None): self.cmd_specific_other_count += 1 def pre_undo_callback(self, info): self.pre_undo_count += 1 self.x = info.get('x', None) if info.get('pre_do', None): self.cmd_specific_pre_undo_count += 1 if info.get('post_do', None): self.cmd_specific_post_undo_count += 1 if info.get('pre_undo', None): self.cmd_specific_pre_undo_count += 1 if info.get('post_undo', None): self.cmd_specific_post_undo_count += 1 if info.get('other', None): self.cmd_specific_other_count += 1 def post_undo_callback(self, info): self.post_undo_count += 1 self.y = info.get('y', None) if info.get('pre_do', None): self.cmd_specific_pre_undo_count += 1 if info.get('post_do', None): self.cmd_specific_post_undo_count += 1 if info.get('pre_undo', None): self.cmd_specific_pre_undo_count += 1 if info.get('post_undo', None): self.cmd_specific_post_undo_count += 1 if info.get('other', None): self.cmd_specific_other_count += 1 # With no callbacks registered, nothing should change. omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertEqual(self.x, None) self.assertEqual(self.y, None) self.assertEqual(self.pre_do_count, 0) self.assertEqual(self.post_do_count, 0) self.assertEqual(self.cmd_specific_pre_do_count, 0) self.assertEqual(self.cmd_specific_post_do_count, 0) self.assertEqual(self.pre_undo_count, 0) self.assertEqual(self.post_undo_count, 0) self.assertEqual(self.cmd_specific_pre_undo_count, 0) self.assertEqual(self.cmd_specific_post_undo_count, 0) self.assertEqual(self.cmd_specific_other_count, 0) # With only the pre- callback registered only x, pre_do_count and cmd_specific_pre_do_count should # change. pre_do_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.PRE_DO_CALLBACK, partial(pre_do_callback, self)) omni.kit.commands.execute("TestAppend", x=3, y=4) self.assertEqual(self.x, 3) self.assertEqual(self.y, None) self.assertEqual(self.pre_do_count, 1) self.assertEqual(self.post_do_count, 0) self.assertEqual(self.cmd_specific_pre_do_count, 1) self.assertEqual(self.cmd_specific_post_do_count, 0) self.assertEqual(self.pre_undo_count, 0) self.assertEqual(self.post_undo_count, 0) self.assertEqual(self.cmd_specific_pre_undo_count, 0) self.assertEqual(self.cmd_specific_post_undo_count, 0) self.assertEqual(self.cmd_specific_other_count, 0) # With both callbacks registered, everything except cmd_specific_other_count and various *_undo_counts should change. post_do_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.POST_DO_CALLBACK, partial(post_do_callback, self)) omni.kit.commands.execute("TestAppend", x=5, y=6) self.assertEqual(self.x, 5) self.assertEqual(self.y, 6) self.assertEqual(self.pre_do_count, 2) self.assertEqual(self.post_do_count, 1) self.assertEqual(self.cmd_specific_pre_do_count, 2) self.assertEqual(self.cmd_specific_post_do_count, 1) self.assertEqual(self.pre_undo_count, 0) self.assertEqual(self.post_undo_count, 0) self.assertEqual(self.cmd_specific_pre_undo_count, 0) self.assertEqual(self.cmd_specific_post_undo_count, 0) self.assertEqual(self.cmd_specific_other_count, 0) # With callbacks removed, nothing should change. omni.kit.commands.unregister_callback(pre_do_cb) omni.kit.commands.unregister_callback(post_do_cb) omni.kit.commands.execute("TestAppend", x=7, y=8) self.assertEqual(self.x, 5) self.assertEqual(self.y, 6) self.assertEqual(self.pre_do_count, 2) self.assertEqual(self.post_do_count, 1) self.assertEqual(self.cmd_specific_pre_do_count, 2) self.assertEqual(self.cmd_specific_post_do_count, 1) self.assertEqual(self.pre_undo_count, 0) self.assertEqual(self.post_undo_count, 0) self.assertEqual(self.cmd_specific_pre_undo_count, 0) self.assertEqual(self.cmd_specific_post_undo_count, 0) self.assertEqual(self.cmd_specific_other_count, 0) # TestAppendNoUndoCommand doesn't provide any special callback info # so none of the 'specific' data counts should change. pre_do_cb = omni.kit.commands.register_callback("TestAppendNoUndoCommand", omni.kit.commands.PRE_DO_CALLBACK, partial(pre_do_callback, self)) post_do_cb = omni.kit.commands.register_callback("TestAppendNoUndoCommand", omni.kit.commands.POST_DO_CALLBACK, partial(post_do_callback, self)) omni.kit.commands.execute("TestAppendNoUndoCommand", x=9, y=10) self.assertEqual(self.x, 9) self.assertEqual(self.y, 10) self.assertEqual(self.pre_do_count, 3) self.assertEqual(self.post_do_count, 2) self.assertEqual(self.cmd_specific_pre_do_count, 2) self.assertEqual(self.cmd_specific_post_do_count, 1) self.assertEqual(self.pre_undo_count, 0) self.assertEqual(self.post_undo_count, 0) self.assertEqual(self.cmd_specific_pre_undo_count, 0) self.assertEqual(self.cmd_specific_post_undo_count, 0) self.assertEqual(self.cmd_specific_other_count, 0) omni.kit.commands.unregister_callback(pre_do_cb) omni.kit.commands.unregister_callback(post_do_cb) # With no undo callbacks registered, nothing should change. omni.kit.undo.undo() self.assertEqual(self.x, 9) self.assertEqual(self.y, 10) self.assertEqual(self.pre_do_count, 3) self.assertEqual(self.post_do_count, 2) self.assertEqual(self.cmd_specific_pre_do_count, 2) self.assertEqual(self.cmd_specific_post_do_count, 1) self.assertEqual(self.pre_undo_count, 0) self.assertEqual(self.post_undo_count, 0) self.assertEqual(self.cmd_specific_pre_undo_count, 0) self.assertEqual(self.cmd_specific_post_undo_count, 0) self.assertEqual(self.cmd_specific_other_count, 0) # With only the pre-undo callback registered only x, pre_undo_count and cmd_specific_pre_undo_count should change. pre_undo_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.PRE_UNDO_CALLBACK, partial(pre_undo_callback, self)) omni.kit.undo.undo() self.assertEqual(self.x, 5) self.assertEqual(self.y, 10) self.assertEqual(self.pre_do_count, 3) self.assertEqual(self.post_do_count, 2) self.assertEqual(self.cmd_specific_pre_do_count, 2) self.assertEqual(self.cmd_specific_post_do_count, 1) self.assertEqual(self.pre_undo_count, 1) self.assertEqual(self.post_undo_count, 0) self.assertEqual(self.cmd_specific_pre_undo_count, 1) self.assertEqual(self.cmd_specific_post_undo_count, 0) self.assertEqual(self.cmd_specific_other_count, 0) # With both callbacks registered, everything except cmd_specific_other_count and various *_do_counts should change. post_undo_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.POST_UNDO_CALLBACK, partial(post_undo_callback, self)) omni.kit.undo.undo() self.assertEqual(self.x, 3) self.assertEqual(self.y, 4) self.assertEqual(self.pre_do_count, 3) self.assertEqual(self.post_do_count, 2) self.assertEqual(self.cmd_specific_pre_do_count, 2) self.assertEqual(self.cmd_specific_post_do_count, 1) self.assertEqual(self.pre_undo_count, 2) self.assertEqual(self.post_undo_count, 1) self.assertEqual(self.cmd_specific_pre_undo_count, 2) self.assertEqual(self.cmd_specific_post_undo_count, 1) self.assertEqual(self.cmd_specific_other_count, 0) # With callbacks removed, nothing should change. omni.kit.commands.unregister_callback(pre_undo_cb) omni.kit.commands.unregister_callback(post_undo_cb) omni.kit.undo.undo() self.assertEqual(self.x, 3) self.assertEqual(self.y, 4) self.assertEqual(self.pre_do_count, 3) self.assertEqual(self.post_do_count, 2) self.assertEqual(self.cmd_specific_pre_do_count, 2) self.assertEqual(self.cmd_specific_post_do_count, 1) self.assertEqual(self.pre_undo_count, 2) self.assertEqual(self.post_undo_count, 1) self.assertEqual(self.cmd_specific_pre_undo_count, 2) self.assertEqual(self.cmd_specific_post_undo_count, 1) self.assertEqual(self.cmd_specific_other_count, 0) # With callbacks registered again but nothing left to undo, nothing should change. pre_undo_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.PRE_UNDO_CALLBACK, partial(pre_undo_callback, self)) post_undo_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.POST_UNDO_CALLBACK, partial(post_undo_callback, self)) omni.kit.undo.undo() self.assertEqual(self.x, 3) self.assertEqual(self.y, 4) self.assertEqual(self.pre_do_count, 3) self.assertEqual(self.post_do_count, 2) self.assertEqual(self.cmd_specific_pre_do_count, 2) self.assertEqual(self.cmd_specific_post_do_count, 1) self.assertEqual(self.pre_undo_count, 2) self.assertEqual(self.post_undo_count, 1) self.assertEqual(self.cmd_specific_pre_undo_count, 2) self.assertEqual(self.cmd_specific_post_undo_count, 1) self.assertEqual(self.cmd_specific_other_count, 0) async def test_subscribe_on_undo_stack_change(self): self.command_names = [] self.command_entries = [] def on_undo_stack_change(command_names): self.command_names += command_names def on_undo_stack_change_detailed(command_entries): self.command_entries += command_entries # Execute a command before subscribing to on_change callbacks. omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(self.command_names, []) self.assertListEqual(self.command_entries, []) # Subscribe to on_change callbacks. omni.kit.undo.subscribe_on_change(on_undo_stack_change) omni.kit.undo.subscribe_on_change_detailed(on_undo_stack_change_detailed) # Execute a command. omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(self.command_names, ["TestAppend"]) self.assertEqual(len(self.command_entries), 1) self.assertEqual(self.command_entries[0].name, "TestAppend") self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2}) self.assertEqual(self.command_entries[0].level, 0) self.assertEqual(self.command_entries[0].error, False) # Undo the command. self.command_names = [] self.command_entries = [] omni.kit.undo.undo() self.assertListEqual(self.command_names, ["TestAppend"]) self.assertEqual(len(self.command_entries), 1) self.assertEqual(self.command_entries[0].name, "TestAppend") self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2}) self.assertEqual(self.command_entries[0].level, 0) self.assertEqual(self.command_entries[0].error, False) # Redo the command. self.command_names = [] self.command_entries = [] omni.kit.undo.redo() self.assertListEqual(self.command_names, ["TestAppend"]) self.assertEqual(len(self.command_entries), 1) self.assertEqual(self.command_entries[0].name, "TestAppend") self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2}) self.assertEqual(self.command_entries[0].level, 0) self.assertEqual(self.command_entries[0].error, False) # Group multiple commands omni.kit.undo.begin_group() self.command_names = [] self.command_entries = [] omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(self.command_names, ["TestAppend"]) self.assertEqual(len(self.command_entries), 1) self.assertEqual(self.command_entries[0].name, "TestAppend") self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2}) self.assertEqual(self.command_entries[0].level, 1) self.assertEqual(self.command_entries[0].error, False) self.command_names = [] self.command_entries = [] omni.kit.commands.execute("TestAppend", x=3, y=4) self.assertListEqual(self.command_names, ["TestAppend"]) self.assertEqual(len(self.command_entries), 1) self.assertEqual(self.command_entries[0].name, "TestAppend") self.assertDictEqual(self.command_entries[0].kwargs, {"x":3, "y":4}) self.assertEqual(self.command_entries[0].level, 1) self.assertEqual(self.command_entries[0].error, False) self.command_names = [] self.command_entries = [] omni.kit.undo.end_group() self.assertListEqual(self.command_names, ["Group"]) self.assertEqual(len(self.command_entries), 1) self.assertEqual(self.command_entries[0].name, "Group") self.assertDictEqual(self.command_entries[0].kwargs, {}) self.assertEqual(self.command_entries[0].level, 0) self.assertEqual(self.command_entries[0].error, False) # Undo the grouped commands (the callback will only be invoked once for the whole group). self.command_names = [] self.command_entries = [] omni.kit.undo.undo() self.assertListEqual(self.command_names, ["TestAppend", "TestAppend", "Group"]) self.assertEqual(len(self.command_entries), 3) self.assertEqual(self.command_entries[0].name, "TestAppend") self.assertDictEqual(self.command_entries[0].kwargs, {"x":3, "y":4}) self.assertEqual(self.command_entries[0].level, 1) self.assertEqual(self.command_entries[0].error, False) self.assertEqual(self.command_entries[1].name, "TestAppend") self.assertDictEqual(self.command_entries[1].kwargs, {"x":1, "y":2}) self.assertEqual(self.command_entries[1].level, 1) self.assertEqual(self.command_entries[1].error, False) self.assertEqual(self.command_entries[2].name, "Group") self.assertDictEqual(self.command_entries[2].kwargs, {}) self.assertEqual(self.command_entries[2].level, 0) self.assertEqual(self.command_entries[2].error, False) # Redo the grouped commands (the callback will be invoked once for each command being redone). self.command_names = [] self.command_entries = [] omni.kit.undo.redo() self.assertListEqual(self.command_names, ["TestAppend", "TestAppend", "Group"]) self.assertEqual(len(self.command_entries), 3) self.assertEqual(self.command_entries[0].name, "TestAppend") self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2}) self.assertEqual(self.command_entries[0].level, 1) self.assertEqual(self.command_entries[0].error, False) self.assertEqual(self.command_entries[1].name, "TestAppend") self.assertDictEqual(self.command_entries[1].kwargs, {"x":3, "y":4}) self.assertEqual(self.command_entries[1].level, 1) self.assertEqual(self.command_entries[1].error, False) self.assertEqual(self.command_entries[2].name, "Group") self.assertDictEqual(self.command_entries[2].kwargs, {}) self.assertEqual(self.command_entries[2].level, 0) self.assertEqual(self.command_entries[2].error, False) # Unsubscribe from on_change callbacks. omni.kit.undo.unsubscribe_on_change_detailed(on_undo_stack_change_detailed) omni.kit.undo.unsubscribe_on_change(on_undo_stack_change) async def test_cpp_commands(self): global _result _result = [] # Give the C++ test code access to the global test result list self.command_tests.set_test_result_list(_result) # Register a new command type from C++ self.command_tests.test_register_cpp_command("omni.kit.command_tests", "TestCppAppendCommand") # Execute the C++ command from Python res = omni.kit.commands.execute("TestCppAppend", x=7, y=9) self.assertListEqual(_result, [7, 9]) self.assertEqual(res, (True, None)) # Undo the C++ command from C++ res = self.command_tests.test_undo_command_from_cpp() self.assertListEqual(_result, []) self.assertTrue(res) # Redo the C++ command from Python res = omni.kit.undo.redo() self.assertListEqual(_result, [7, 9]) self.assertTrue(res) # Execute the C++ command from C++ res = self.command_tests.test_execute_command_from_cpp("TestCppAppend", x=99, y=0) self.assertListEqual(_result, [7, 9, 99, 0]) self.assertTrue(res) # Undo the C++ command from Python res = omni.kit.undo.undo() self.assertListEqual(_result, [7,9]) self.assertTrue(res) # Execute the C++ command from C++ with a default argument res = self.command_tests.test_execute_command_from_cpp("TestCppAppend", x=99) self.assertListEqual(_result, [7, 9, 99, -1]) self.assertTrue(res) # Execute the C++ command from Python with a default argument res = omni.kit.commands.execute("TestCppAppend", y=-9) self.assertListEqual(_result, [7, 9, 99, -1, 9, -9]) self.assertEqual(res, (True, None)) # Undo the C++ command from C++ res = self.command_tests.test_undo_command_from_cpp() self.assertListEqual(_result, [7, 9, 99, -1]) self.assertTrue(res) # Undo the C++ command from Python res = omni.kit.undo.undo() self.assertListEqual(_result, [7,9]) self.assertTrue(res) # Execute an existng Python command from C++ res = self.command_tests.test_execute_command_from_cpp("TestAppend", x=1, y=2) self.assertListEqual(_result, [7, 9, 1, 2]) self.assertTrue(res) # Undo the Python command from C++ res = self.command_tests.test_undo_command_from_cpp() self.assertListEqual(_result, [7,9]) self.assertTrue(res) # Redo the Python command from C++ res = self.command_tests.test_redo_command_from_cpp() self.assertListEqual(_result, [7,9, 1, 2]) self.assertTrue(res) # Undo the Python command from Python res = omni.kit.undo.undo() self.assertListEqual(_result, [7,9]) self.assertTrue(res) # Deregister the C++ command from C++ self.command_tests.test_deregister_cpp_command("omni.kit.command_tests", "TestCppAppendCommand") # Undo the C++ command from Python after it has been deregistered res = omni.kit.undo.undo() self.assertListEqual(_result, []) self.assertTrue(res) # Execute the C++ command from C++ after it has been deregistered (does nothing) res = self.command_tests.test_execute_command_from_cpp("TestCppAppend", x=10, y=20) self.assertListEqual(_result, []) self.assertFalse(res) # Execute the C++ command from Python after it has been deregistered (does nothing) res = omni.kit.commands.execute("TestCppAppend", x=10, y=20) self.assertListEqual(_result, []) self.assertEqual(res, (False, None)) # Redo the C++ command from C++ after it has been deregistered res = self.command_tests.test_redo_command_from_cpp() self.assertListEqual(_result, [7, 9]) self.assertTrue(res) # Undo the C++ command from C++ after it has been deregistered res = self.command_tests.test_undo_command_from_cpp() self.assertListEqual(_result, []) self.assertTrue(res) # Release the C++ reference to the global test result list self.command_tests.clear_test_result_list() def test_repeat(self): global _result _result = [] # Execute a command res = omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(_result, [1, 2]) self.assertEqual(res, (True, None)) # Repeat the command res = omni.kit.undo.repeat() self.assertListEqual(_result, [1, 2, 1, 2]) self.assertTrue(res) # Undo the repeated command res = omni.kit.undo.undo() self.assertListEqual(_result, [1, 2]) self.assertTrue(res) # Redo the repeated command res = omni.kit.undo.redo() self.assertListEqual(_result, [1, 2, 1, 2]) self.assertTrue(res) # Repeat the command from C++ res = self.command_tests.test_repeat_command_from_cpp() self.assertListEqual(_result, [1, 2, 1, 2, 1, 2]) self.assertTrue(res) # Undo the repeated and original commands res = omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 1, 2]) self.assertTrue(res) res = omni.kit.undo.undo() self.assertListEqual(_result, [1, 2]) self.assertTrue(res) res = omni.kit.undo.undo() self.assertListEqual(_result, []) self.assertTrue(res) # Group multiple commands omni.kit.undo.begin_group() omni.kit.commands.execute("TestAppend", x=1, y=2) omni.kit.commands.execute("TestAppend", x=3, y=4) omni.kit.undo.end_group() self.assertListEqual(_result, [1, 2, 3, 4]) # Repeat the grouped commands res = omni.kit.undo.repeat() self.assertListEqual(_result, [1, 2, 3, 4, 1, 2, 3, 4]) self.assertTrue(res) # Undo the repeated grouped commands res = omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) self.assertTrue(res) # Redo the repeated grouped commands res = omni.kit.undo.redo() self.assertListEqual(_result, [1, 2, 3, 4, 1, 2, 3, 4]) self.assertTrue(res) # Repeat the grouped commands from C++ res = self.command_tests.test_repeat_command_from_cpp() self.assertListEqual(_result, [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]) self.assertTrue(res) # Undo the repeated and original grouped commands res = omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4, 1, 2, 3, 4]) self.assertTrue(res) res = omni.kit.undo.undo() self.assertListEqual(_result, [1, 2, 3, 4]) self.assertTrue(res) res = omni.kit.undo.undo() self.assertListEqual(_result, []) self.assertTrue(res) def test_change_setting_command(self): # Set the default value of our draggable setting test_setting_default_value = -1 test_setting_path = "/test/some/setting" settings = carb.settings.get_settings() settings.set_default(test_setting_path, test_setting_default_value) self.assertEqual(settings.get(test_setting_path), test_setting_default_value) # Execute a change setting command test_setting_new_value = 9 res = omni.kit.commands.execute("ChangeSetting", path=test_setting_path, value=test_setting_new_value) self.assertEqual(settings.get(test_setting_path), test_setting_new_value) # Verify that undoing the change setting command resets the setting to the default value omni.kit.undo.undo() self.assertEqual(settings.get(test_setting_path), test_setting_default_value) def test_change_draggable_setting_command(self): # Set the default value of our draggable setting test_draggable_setting_default_value = -1 test_draggable_setting_path = "/test/draggable/setting" settings = carb.settings.get_settings() settings.set_default(test_draggable_setting_path, test_draggable_setting_default_value) self.assertEqual(settings.get(test_draggable_setting_path), test_draggable_setting_default_value) # Execute a change draggable setting command test_draggable_setting_new_value = 9 res = omni.kit.commands.execute("ChangeDraggableSetting", path=test_draggable_setting_path, value=test_draggable_setting_new_value) self.assertEqual(settings.get(test_draggable_setting_path), test_draggable_setting_new_value) # Verify that undoing the change draggable setting command does nothing omni.kit.undo.undo() self.assertEqual(settings.get(test_draggable_setting_path), test_draggable_setting_new_value) def test_last_command(self): # Set the current and default values of a test setting test_setting_default_value = -1 test_setting_path = "/test/some/setting" settings = carb.settings.get_settings() settings.set(test_setting_path, test_setting_default_value) settings.set_default(test_setting_path, test_setting_default_value) self.assertEqual(settings.get(test_setting_path), test_setting_default_value) # Execute a change draggable setting command test_setting_new_value = 9 res = omni.kit.commands.execute("ChangeDraggableSetting", path=test_setting_path, value=test_setting_new_value) self.assertEqual(settings.get(test_setting_path), test_setting_new_value) # Verify that the 'last command' was set last_command_setting_path = "/crashreporter/data/lastCommand" last_command = settings.get(last_command_setting_path) self.assertEqual(last_command, "ChangeDraggableSetting(path=/test/some/setting,value=9)") # Execute a change setting command test_setting_new_value = 99 res = omni.kit.commands.execute("ChangeSetting", path=test_setting_path, value=test_setting_new_value) self.assertEqual(settings.get(test_setting_path), test_setting_new_value) # Verify that the 'last command' was set last_command = settings.get(last_command_setting_path) self.assertEqual(last_command, "ChangeSetting(path=/test/some/setting,value=99)")
42,395
Python
40.081395
152
0.625593
omniverse-code/kit/exts/omni.kit.widget.filebrowser/scripts/demo_filebrowser.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 sys import omni.ui as ui import asyncio import omni.client from omni.kit.mainwindow import get_main_window from omni.kit.widget.filebrowser import * from functools import partial class FileBrowserView: SERVER_TYPE_FILESYSTEM = "fileSystem" SERVER_TYPE_NUCLEUS = "nucleus" def __init__(self, title: str, **kwargs): self._title = title self._filebrowser = None self._item_menu = None self._server_menu = None self._style = self._init_style() self._layout = kwargs.get("layout", LAYOUT_DEFAULT) self._tooltip = kwargs.get("tooltip", False) self._allow_multi_selection = kwargs.get("allow_multi_selection", True) def build_ui(self): """ """ main_window = get_main_window() self._menu_bar = main_window.get_main_menu_bar() self._menu_bar.set_style(self._style["MenuBar"]) self._menu_bar.visible = True options = [ ("Split Panes", LAYOUT_SPLIT_PANES, False), ("Single Pane Slim", LAYOUT_SINGLE_PANE_SLIM, False), ("Single Pane Wide", LAYOUT_SINGLE_PANE_WIDE, False), ("Grid View", LAYOUT_SPLIT_PANES, True), ] with ui.VStack(spacing=10): with ui.HStack(height=30): collection = ui.RadioCollection() for option in options: button = ui.RadioButton(text=option[0], radio_collection=collection, width=120) button.set_clicked_fn(partial(self._build_filebrowser, option[1], option[2])) ui.Spacer() self._frame = ui.Frame() self._build_filebrowser(LAYOUT_DEFAULT) asyncio.ensure_future(self._dock_window(self._title, ui.DockPosition.SAME)) def _build_filebrowser(self, layout: int, show_grid: bool = False): if self._filebrowser: self._filebrowser.destroy() with self._frame: self._filebrowser = FileBrowserWidget( "Omniverse", layout=layout, tooltip=self._tooltip, allow_multi_selection=self._allow_multi_selection, show_grid_view=show_grid, mouse_pressed_fn=lambda b, item: self._on_mouse_pressed(b, item), ) # Initialize interface with this default list of connections self.add_connection("C:", "C:") self.add_connection("ov-content", "omniverse://ov-content") def add_connection(self, name: str, path: str): asyncio.ensure_future(self._add_connection(name, path)) def _init_style(self) -> dict: style = { "MenuBar": { "background_color": 0xFF23211F, "background_selected_color": 0x664F4D43, "color": 0xFFAAAAAA, "border_width": 0.5, "border_color": 0xFF8A8777, "padding": 8, } } return style def _on_mouse_pressed(self, button: ui.Button, item: FileBrowserItem): if button == 1: if self._filebrowser.is_root_of_model(item): self._show_server_menu(item) else: self._show_item_menu(item) def _show_server_menu(self, item: FileBrowserItem): if not self._server_menu: self._server_menu = ui.Menu("server-menu") self._server_menu.clear() with self._server_menu: ui.MenuItem("Connection Menu") self._server_menu.show() def _show_item_menu(self, item: FileBrowserItem): if not self._item_menu: self._item_menu = ui.Menu("item-menu") self._item_menu.clear() with self._item_menu: ui.MenuItem("Item Info") ui.Separator() ui.MenuItem(item.name) ui.MenuItem(item.path) self._item_menu.show() def _refresh_ui(self, item: FileBrowserItem = None): if self._filebrowser: self._filebrowser.refresh_ui(item) # ---------------------------------------------- Event Handlers ---------------------------------------------- async def _dock_window(self, window_title: str, position: ui.DockPosition, ratio: float = 1.0): frames = 3 while frames > 0: if ui.Workspace.get_window(window_title): break frames = frames - 1 await omni.kit.app.get_app().next_update_async() window = ui.Workspace.get_window(window_title) dockspace = ui.Workspace.get_window("DockSpace") if window and dockspace: window.dock_in(dockspace, position, ratio=ratio) window.dock_tab_bar_visible = False async def _add_connection(self, name: str, path: str): try: await self._stat_path(path) except Exception as e: self._warn(f"{e}\n") else: if path.startswith("omniverse://"): model_creator = NucleusModel else: model_creator = FileSystemModel # Append the new model of desired server type server = model_creator(name, path) self._filebrowser.add_model_as_subtree(server) self._refresh_ui() async def _stat_path(self, path: str, timeout: int = 3.0) -> omni.client.ListEntry: """ Returns stats for path if valid """ if not path: return False, None path = path.replace("\\", "/") try: result, stats = await asyncio.wait_for(omni.client.stat_async(path), timeout=timeout) except asyncio.TimeoutError: raise RuntimeWarning(f"Error unable to stat '{path}': Timed out after {timeout} secs.") except Exception as e: raise RuntimeWarning(f"Error unable to stat '{path}': {e}") if result != omni.client.Result.OK: raise RuntimeWarning(f"Error unable to stat '{path}': {result}") return stats if __name__ == "__main__": window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR window = ui.Window("DemoFileBrowser", width=1000, height=500, flags=window_flags) with window.frame: view = FileBrowserView("DemoFileBrowser") view.build_ui()
6,656
Python
35.779005
114
0.581731
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/zoom_bar.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. # __all__ = ["ZoomBar"] import carb.settings import omni.ui as ui from .style import UI_STYLES, ICON_PATH # key is scale level and value is the actual scale value SCALE_MAP = {0: 0.25, 1: 0.5, 2: 0.75, 3: 1, 4: 1.5, 5: 2.0} class ZoomBar: def __init__(self, **kwargs): self._show_grid_view = kwargs.get("show_grid_view", True) self._grid_view_scale = kwargs.get("grid_view_scale", 2) self._on_toggle_grid_view_fn = kwargs.get("on_toggle_grid_view_fn", None) self._on_scale_grid_view_fn = kwargs.get("on_scale_grid_view_fn", None) settings = carb.settings.get_settings() theme = settings.get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" self._theme = theme self._style = UI_STYLES[theme] self._slider = None self._layout_button = None self._build_ui() # Notify any potential listeners registered through the "_on_toggle_grid_view_fn" argument that the view has # been enabled in the initial state depicted by the resolved `self._show_grid_view` property: self._toggle_grid_view(self._show_grid_view) def destroy(self): self._on_toggle_grid_view_fn = None self._on_scale_grid_view_fn = None self._slider = None self._layout_button = None def _build_ui(self): with ui.HStack(height=0, style=self._style): ui.Spacer() with ui.ZStack(width=0, style=self._style, content_clipping=True): ui.Rectangle(height=20, style_type_name_override="ZoomBar") with ui.HStack(): ui.Spacer(width=6) self._slider = ui.IntSlider(min=0, max=5, width=150, style=self._style["ZoomBar.Slider"]) self._slider.model.add_value_changed_fn(self._scale_grid_view) self._layout_button = ui.Button( image_url=self._get_layout_icon(not self._show_grid_view), width=16, style_type_name_override="ZoomBar.Button", clicked_fn=lambda: self._toggle_grid_view(not self._show_grid_view), ) ui.Spacer(width=6) ui.Spacer(width=16) def _get_layout_icon(self, grid_view: bool) -> str: if grid_view: return f"{ICON_PATH}/{self._theme}/thumbnail.svg" else: return f"{ICON_PATH}/{self._theme}/list.svg" def _scale_grid_view(self, model: ui.SimpleIntModel): scale_level = model.get_value_as_int() scale = SCALE_MAP.get(scale_level, 2) if self._on_scale_grid_view_fn: self._on_scale_grid_view_fn(scale) # If currently displaying the "Grid" View, remember the scale level so it can be rehabilitated later when # toggling back from the "List" View, for which the scale level is set to `0`: if self._show_grid_view: self._grid_view_scale = scale_level def _toggle_grid_view(self, show_grid_view: bool): self._layout_button.image_url = self._get_layout_icon(not show_grid_view) self._show_grid_view = show_grid_view # If showing the "Grid" View, restore the scale level previously set. Showing the "List" View otherwise sets the # scale level to `0`: if show_grid_view: self._slider.model.set_value(self._grid_view_scale) else: self._slider.model.set_value(0) if self._on_toggle_grid_view_fn: self._on_toggle_grid_view_fn(show_grid_view)
4,001
Python
42.5
120
0.615346
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/date_format_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["DatetimeFormatMenu"] import omni.ui as ui import carb.settings import omni.kit.app from typing import Callable from functools import partial DATETIME_FORMAT_SETTING = "/persistent/app/datetime/format" DATETIME_FORMATS = [ "MM/DD/YYYY", "DD.MM.YYYY", "DD-MM-YYYY", "YYYY-MM-DD", "YYYY/MM/DD", "YYYY.MM.DD" ] class DatetimeFormatMenu: def __init__( self, value_changed_fn: Callable=None, ): self._menu = ui.Menu() self._menu_items = {} self._value_changed_fn = value_changed_fn self._update_setting = omni.kit.app.SettingChangeSubscription( DATETIME_FORMAT_SETTING, self._on_datetime_format_changed, ) with self._menu: self._build_dateformat_items() def _on_datetime_format_changed(self, item, event_type): if event_type == carb.settings.ChangeEventType.CHANGED: format = carb.settings.get_settings().get(DATETIME_FORMAT_SETTING) menu_item = self._menu_items.get(format, None) if menu_item: for item in self._menu_items.values(): item.checked = False menu_item.checked = True if self._value_changed_fn: self._value_changed_fn() def _build_dateformat_items(self): def set_datetime_format(owner, format, menu_item): for item in owner._menu_items.values(): if item != menu_item: item.checked = False if menu_item.checked: if format != carb.settings.get_settings().get(DATETIME_FORMAT_SETTING): carb.settings.get_settings().set(DATETIME_FORMAT_SETTING, format) for format in DATETIME_FORMATS: menu_item = ui.MenuItem( format, checkable=True, checked=False, direction=ui.Direction.RIGHT_TO_LEFT ) menu_item.set_triggered_fn(partial(set_datetime_format, self, format, menu_item)) if format == carb.settings.get_settings().get(DATETIME_FORMAT_SETTING): menu_item.checked = True self._menu_items[format] = menu_item @property def visible(self): return self._menu.visible @visible.setter def visible(self, value: bool): self._menu.visible = value def show_at(self, x, y): self._menu.show_at(x, y) def destroy(self): """Destructor""" self._menu = None self._menu_items = None self._update_setting = None self._value_changed_fn = None def get_datetime_format(): format = carb.settings.get_settings().get(DATETIME_FORMAT_SETTING) if format not in DATETIME_FORMATS: # if not valid format, using current system format return "%x" return format.replace("MM", "%m").replace("DD", "%d").replace("YYYY", "%Y")
3,491
Python
32.902912
93
0.590662
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/view.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. # """ An abstract View class, subclassed by TreeView and GridView """ import asyncio import threading import omni.kit.app from typing import Callable from abc import abstractmethod from .model import FileBrowserItem, FileBrowserModel __all__ = ["FileBrowserView"] class FileBrowserView: def __init__(self, model: FileBrowserModel): self._widget = None self._visible = True self._futures = [] # Setting the property to setup the subscription self.model = model self._loop = asyncio.get_event_loop() # Enables thread-safe reads/writes to shared data self._mutex_lock: threading.Lock = threading.Lock() self._refresh_pending = False @abstractmethod def build_ui(self): pass @property def model(self): return self._model @model.setter def model(self, model): self._model = model if self._model: self._model_subscription = self._model.subscribe_item_changed_fn(self._on_item_changed) else: self._model_subscription = None self._on_model_changed(self._model) @property def visible(self): return self._visible @visible.setter def visible(self, visible: bool): if self._widget: self._widget.visible = visible self._visible = visible def set_root(self, item: FileBrowserItem): if self._model: self._model.root = item @abstractmethod def refresh_ui(self, item: FileBrowserItem = None): pass def _throttled_refresh_ui(self, item: FileBrowserItem = None, callback: Callable = None, throttle_frames: int = 1): """ Refreshes the view. Delays the redraw to a later frame so that multiple calls to this function are queued up and handled in one go. For example, when multiple files are copied to the current directory, it will trigger a refresh for each file. If there are many of them, it could swamp the render queue with unnecessary redraws. By queueing up these tasks, we can limit the redraws to once per frame. """ if not self._visible: return self._futures = list(filter(lambda f: not f.done(), self._futures)) if threading.current_thread() is threading.main_thread(): future = asyncio.ensure_future( self._throttled_refresh_ui_async(item, callback, throttle_frames)) else: future = asyncio.run_coroutine_threadsafe( self._throttled_refresh_ui_async(item, callback, throttle_frames), self._loop) self._futures.append(future) async def _throttled_refresh_ui_async(self, item: FileBrowserItem, callback: Callable, throttle_frames: int = 1): # If there's already a pending redraw, then skip. with self._mutex_lock: if self._refresh_pending: return else: self._refresh_pending = True # NOTE: Wait a beat to absorb adjacent redraw events so that we build the grid only once. for _ in range(throttle_frames): await omni.kit.app.get_app().next_update_async() if callback: callback(item) with self._mutex_lock: self._refresh_pending = False @abstractmethod def select_and_center(self, item: FileBrowserItem): pass @abstractmethod def _on_selection_changed(self, selections: [FileBrowserItem]): pass @abstractmethod def destroy(self): for future in self._futures: future.cancel() self._futures.clear() self._loop = None self._mutex_lock = None self._refresh_pending = False def _on_item_changed(self, model, item): """Called by the model when something is changed""" pass def _on_model_changed(self, model): """Called by the model when something is changed""" pass
4,409
Python
32.157894
119
0.641415
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/filesystem_model.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. # __all__ = ["FileSystemItem", "FileSystemItemFactory", "FileSystemModel"] import os import stat import asyncio import omni.client from datetime import datetime from typing import Callable, Any from omni import ui from .model import FileBrowserItem, FileBrowserItemFields, FileBrowserModel from .style import ICON_PATH from carb import log_warn class FileSystemItem(FileBrowserItem): def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = False): super().__init__(path, fields, is_folder=is_folder) async def populate_async(self, callback_async: Callable, timeout: float = 10.0) -> Any: """ Populates current item asynchronously if not already. Overrides base method. Args: callback_async (Callable): Function signature is void callback(result, children: [FileBrowserItem]), where result is an Exception type upon error. timeout (float): Time out duration on failed server connections. Default 10.0. Returns: Any: Result of executing callback. """ result = None if not self.populated: if self.is_folder: try: with os.scandir(self.path) as it: self.children.clear() entries = {entry.name: entry for entry in it} for name in sorted(entries): entry = entries[name] if not FileSystemItem.keep_entry(entry): continue self.add_child(FileSystemItemFactory.create_entry_item(entry)) except asyncio.CancelledError: # NOTE: Return early if operation cancelled, without marking as 'populated'. return None except PermissionError as e: log_warn(f"Can't list files. Permission denied for {self.path}") result = e except Exception as e: result = e # NOTE: Mark this item populated even when there's an error so we don't repeatedly try. self.populated = True if callback_async: try: return await callback_async(result, self.children) except asyncio.CancelledError: return None else: return result def on_list_change_event(self, event: omni.client.ListEvent, entry: omni.client.ListEntry) -> bool: """ Handles ListEvent changes, should update this item's children list with the corresponding ListEntry. Args: event (:obj:`omni.client.ListEvent`): One of of {UNKNOWN, CREATED, UPDATED, DELETED, METADATA, LOCKED, UNLOCKED}. entry (:obj:`omni.client.ListEntry`): Updated entry as defined by omni.client. """ if not entry: return False item_changed = False child_name = entry.relative_path child_name = child_name[:-1] if child_name.endswith("/") else child_name full_path = f"{self.path}/{entry.relative_path}" if event == omni.client.ListEvent.CREATED: if not child_name in self.children: item_changed = True self.add_child(FileSystemItemFactory.create_omni_entry_item(entry, full_path)) elif event == omni.client.ListEvent.DELETED: self.del_child(child_name) item_changed = True elif event == omni.client.ListEvent.UPDATED: child = self.children.get(child_name) if child: # Update file size size_model = child.get_subitem_model(2) size_model.set_value(FileBrowserItem.size_as_string(entry.size)) return item_changed @staticmethod def keep_entry(entry: os.DirEntry) -> bool: if os.name == "nt": # On Windows, test for hidden directories & files try: file_attrs = entry.stat().st_file_attributes except: return False if file_attrs & stat.FILE_ATTRIBUTE_SYSTEM: return False elif os.name == "posix": if entry.is_symlink(): try: entry.stat() except: # NOTE: What accounts for the return value here? return False return True @property def readable(self) -> bool: return (self._fields.permissions & omni.client.AccessFlags.READ) > 0 @property def writeable(self) -> bool: return (self._fields.permissions & omni.client.AccessFlags.WRITE) > 0 class FileSystemItemFactory: @staticmethod def create_group_item(name: str, path: str) -> FileSystemItem: if not name: return None access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE fields = FileBrowserItemFields(name, datetime.now(), 0, access) item = FileSystemItem(path, fields, is_folder=True) item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel("")) return item @staticmethod def create_entry_item(entry: os.DirEntry) -> FileSystemItem: if not entry: return None modified_time = datetime.fromtimestamp(entry.stat().st_mtime) stats = entry.stat() # OM-73238 Translate system access flags to omni.client flags access = 0 if entry.stat().st_mode & stat.S_IRUSR: access |= omni.client.AccessFlags.READ if entry.stat().st_mode & stat.S_IWUSR: access |= omni.client.AccessFlags.WRITE fields = FileBrowserItemFields(entry.name, modified_time, stats.st_size, access) item = FileSystemItem(entry.path, fields, is_folder=entry.is_dir()) size_model = ui.SimpleStringModel(FileBrowserItem.size_as_string(entry.stat().st_size)) item._models = (ui.SimpleStringModel(item.name), modified_time, size_model) return item @staticmethod def create_omni_entry_item(entry: omni.client.ListEntry, path: str) -> FileSystemItem: if not entry: return None name = entry.relative_path name = name[:-1] if name.endswith("/") else name modified_time = entry.modified_time fields = FileBrowserItemFields(name, modified_time, entry.size, entry.access) is_folder = (entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN) > 0 item = FileSystemItem(path, fields, is_folder=is_folder) size_model = ui.SimpleStringModel(FileBrowserItem.size_as_string(entry.size)) item._models = (ui.SimpleStringModel(item.name), modified_time, size_model) return item class FileSystemModel(FileBrowserModel): """ A Filebrowser model class for navigating a the local filesystem in a tree view. Sub-classed from :obj:`FileBrowserModel`. Args: name (str): Name of root item.. root_path (str): Root path. If None, then create empty model. Default "C:". Keyword Args: drop_fn (Callable): Function called to handle drag-n-drops. Function signature: void drop_fn(dst_item: :obj:`FileBrowserItem`, src_item: :obj:`FileBrowserItem`) filter_fn (Callable): This handler should return True if the given tree view item is visible, False otherwise. Function signature: bool filter_fn(item: :obj:`FileBrowserItem`) sort_by_field (str): Name of column by which to sort items in the same folder. Default "name". sort_ascending (bool): Sort in ascending order. Default True. """ def __init__(self, name: str, root_path: str = "C:", **kwargs): import carb.settings super().__init__(**kwargs) if not root_path: return if not root_path.endswith("/"): root_path += "/" self._root = FileSystemItemFactory.create_group_item(name, root_path) theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" self._root.icon = f"{ICON_PATH}/{theme}/hdd.svg"
8,628
Python
40.68599
125
0.617177
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/style.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from pathlib import Path CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") THUMBNAIL_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("thumbnails") UI_STYLES = {} UI_STYLES["NvidiaLight"] = { "Rectangle::Splitter": {"background_color": 0xFFE0E0E0, "margin_width": 2}, "Rectangle::Splitter:hovered": {"background_color": 0xFFB0703B}, "Rectangle::Splitter:pressed": {"background_color": 0xFFB0703B}, "Splitter": {"background_color": 0xFFE0E0E0, "margin_width": 2}, "TreeView": { "background_color": 0xFF535354, "background_selected_color": 0xFF6E6E6E, "secondary_color": 0xFFACACAC, }, "TreeView:hovered": {"background_color": 0xFF6E6E6E}, "TreeView:selected": {"background_color": 0xFFBEBBAE}, "TreeView.Column": {"background_color": 0x0, "color": 0xFFD6D6D6, "margin": 0}, "TreeView.Header": { "background_color": 0xFF535354, "color": 0xFFD6D6D6, "border_color": 0xFF707070, "border_width": 0.5, }, "TreeView.Header::name": {"margin": 3, "alignment": ui.Alignment.LEFT}, "TreeView.Header::date": {"margin": 3, "alignment": ui.Alignment.CENTER}, "TreeView.Header::size": {"margin": 3, "alignment": ui.Alignment.RIGHT}, "TreeView.Icon:selected": {"color": 0xFF535354}, "TreeView.Header.Icon": {"color": 0xFF8A8777}, "TreeView.Icon::default": {"color": 0xFF8A8777}, "TreeView.Icon::file": {"color": 0xFF8A8777}, "TreeView.Item": {"color": 0xFFD6D6D6}, "TreeView.Item:selected": {"color": 0xFF2A2825}, "TreeView.ScrollingFrame": {"background_color": 0xFF535354, "secondary_color": 0xFFE0E0E0}, "GridView.ScrollingFrame": {"background_color": 0xFF535354, "secondary_color": 0xFFE0E0E0}, "GridView.Grid": {"background_color": 0x0, "margin_width": 10}, "Card": {"background_color": 0x0, "margin": 8}, "Card:hovered": {"background_color": 0xFF6E6E6E, "border_color": 0xFF3A3A3A, "border_width": 0}, "Card:pressed": {"background_color": 0xFF6E6E6E, "border_color": 0xFF3A3A3A, "border_width": 0}, "Card:selected": {"background_color": 0xFFBEBBAE, "border_color": 0xFF8A8777, "border_width": 0}, "Card.Image": { "background_color": 0xFFC9C9C9, "color": 0xFFFFFFFF, "corner_flag": ui.CornerFlag.TOP, "alignment": ui.Alignment.CENTER, "margin": 8, }, "Card.Badge": {"background_color": 0xFFC9C9C9, "color": 0xFFFFFFFF}, "Card.Badge::shadow": {"background_color": 0xFFC9C9C9, "color": 0xDD444444}, "Card.Label": { "background_color": 0xFFC9C9C9, "color": 0xFFD6D6D6, "font_size": 12, "alignment": ui.Alignment.CENTER_TOP, "margin_width": 8, "margin_height": 2, }, "Card.Label:checked": {"color": 0xFF23211F}, "ZoomBar": {"background_color": 0x0, "border_radius": 2}, "ZoomBar.Slider": { "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": 0xFF23211F, "secondary_color": 0xFF9D9D9D, "color": 0x0, "alignment": ui.Alignment.CENTER, "padding": 0, "margin": 5, "font_size": 8, }, "ZoomBar.Button": {"background_color": 0x0, "margin": 0, "padding": 0}, "ZoomBar.Button.Image": {"color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "Recycle.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "Recycle.Button.Image": {"image_url": "resources/glyphs/trash.svg", "background_color": 0xFF535354, "alignment": ui.Alignment.CENTER}, "Recycle.Button:hovered": {"background_color": 0xFF3A3A3A}, "RecycleFrame.Button": {"background_color": 0xFF23211F, "margin": 0, "padding": 0}, "RecycleFrame.Button:hovered": {"background_color": 0xFF3A3A3A}, "RecycleFrame.Button:checked": {"background_color": 0xFF3A3A3A}, } UI_STYLES["NvidiaDark"] = { "Splitter": {"background_color": 0x0, "margin_width": 0}, "Splitter:hovered": {"background_color": 0xFFB0703B}, "Splitter:pressed": {"background_color": 0xFFB0703B}, "TreeView.ScrollingFrame": {"background_color": 0xFF23211F}, "TreeView": {"background_color": 0xFF23211F, "background_selected_color": 0x663A3A3A}, "TreeView:selected": {"background_color": 0xFF8A8777}, "TreeView.Column": {"background_color": 0x0, "color": 0xFFADAC9F, "margin": 0}, "TreeView.Header": {"background_color": 0xFF343432, "color": 0xFF9E9E9E}, "TreeView.Icon": {"color": 0xFFFFFFFF, "padding": 0}, "TreeView.Icon::Cut": {"background_color": 0x0, "color": 0x88FFFFFF}, "TreeView.Icon::Cut:selected": {"background_color": 0x0, "color": 0x88FFFFFF}, "TreeView.Icon::shadow": {"background_color": 0x0, "color": 0xDD444444}, "TreeView.Icon::expand": {"color": 0xFFFFFFFF}, "TreeView.Icon:selected": {"color": 0xFFFFFFFF}, "TreeView.Item": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "TreeView.Item:selected": {"color": 0xFF2A2825}, "TreeView.Item::Cut": {"color": 0x889E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "TreeView.Item::Cut:selected": {"color": 0x882A2825}, "GridView.ScrollingFrame": {"background_color": 0xFF23211F}, "GridView.Grid": {"background_color": 0x0, "margin_width": 10}, "Card": {"background_color": 0x0, "margin": 8}, "Card:hovered": {"background_color": 0xFF3A3A3A, "border_color": 0xFF3A3A3A, "border_width": 2}, "Card:pressed": {"background_color": 0xFF3A3A3A, "border_color": 0xFF42413F, "border_width": 2}, "Card:selected": {"background_color": 0xFF8A8777, "border_color": 0xFF8A8777, "border_width": 2}, "Card.Image": { "background_color": 0x0, "color": 0xFFFFFFFF, "corner_flag": ui.CornerFlag.TOP, "alignment": ui.Alignment.CENTER, "margin": 8, }, "Card.Image::Cut": {"color": 0x88FFFFFF}, "Card.Badge": {"background_color": 0x0, "color": 0xFFFFFFFF}, "Card.Badge::shadow": {"background_color": 0x0, "color": 0xDD444444}, "Card.Label": { "background_color": 0x0, "color": 0xFF9E9E9E, "alignment": ui.Alignment.CENTER_TOP, "margin_width": 8, "margin_height": 2, }, "Card.Label::Cut": {"color": 0x889E9E9E}, "Card.Label:checked": {"color": 0xFF23211F}, "Card.Label::Cut:checked": {"color": 0x8823211F}, "ZoomBar": {"background_color": 0xFF454545, "border_radius": 2}, "ZoomBar.Slider": { "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": 0xDD23211F, "secondary_color": 0xFF9E9E9E, "color": 0x0, "alignment": ui.Alignment.CENTER, "padding": 0, "margin": 3, }, "ZoomBar.Button": {"background_color": 0x0, "margin": 0, "padding": 0}, "ZoomBar.Button.Image": {"color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "Recycle.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "Recycle.Button": {"background_color": 0x0, "margin": 0, "padding": 0}, "Recycle.Button.Image": {"image_url": "resources/glyphs/trash.svg","background_color": 0x0, "color": 0xFF9E9E9E, "alignment": ui.Alignment.CENTER}, "Recycle.Button.Image:hovered": {"background_color": 0x0,"color": 0xFFFFFFFF}, "Recycle.Button.Image:checked": {"background_color": 0x0,"color": 0xFFFFFFFF}, "Recycle.Rectangle": {"background_color": 0xFF23211F, "margin": 0, "padding": 0}, "RecycleFrame.Button": {"background_color": 0x0, "margin": 0, "padding": 0}, "RecycleFrame.Button:hovered": {"background_color": 0xFF3A3A3A}, "RecycleFrame.Button:checked": {"background_color": 0xFF3A3A3A}, "RecycleFrame.Button.Label": {"alignment": ui.Alignment.LEFT}, "RecycleView.Frame": {"background_color": 0x0}, }
8,234
Python
50.149068
151
0.651202
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tree_view.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. # """ A generic Tree View Widget for File Systems """ import asyncio import carb from omni import ui from typing import List from typing import Tuple from functools import partial from datetime import datetime from carb import log_warn from .view import FileBrowserView from .model import FileBrowserItem, FileBrowserItemFields, FileBrowserModel from .style import UI_STYLES, ICON_PATH from .abstract_column_delegate import ColumnItem from .column_delegate_registry import ColumnDelegateRegistry from .date_format_menu import DatetimeFormatMenu from . import ALERT_WARNING, ALERT_ERROR from .clipboard import is_path_cut __all__ = ["AwaitWithFrame", "FileBrowserTreeView", "FileBrowserTreeViewDelegate"] class AwaitWithFrame: """ A future-like object that runs the given future and makes sure it's always in the given frame's scope. It allows for creating widgets asynchronously. """ def __init__(self, frame: ui.Frame, future: asyncio.Future): self._frame = frame self._future = future def __await__(self): # create an iterator object from that iterable iter_obj = iter(self._future.__await__()) # infinite loop while True: try: with self._frame: yield next(iter_obj) except StopIteration: break except Exception as e: log_warn(f"Error rendering frame: {str(e)}") break self._frame = None self._future = None class FileBrowserTreeView(FileBrowserView): def __init__(self, model: FileBrowserModel, **kwargs): import carb.settings self._tree_view = None self._delegate = None super().__init__(model) self._headers = FileBrowserItemFields._fields theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False if use_default_style: self._style = {} else: self._style = UI_STYLES[theme] self._root_visible = kwargs.get("root_visible", True) self._header_visible = kwargs.get("header_visible", True) self._allow_multi_selection = kwargs.get("allow_multi_selection", True) self._selection_changed_fn = kwargs.get("selection_changed_fn", None) self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None) self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None) self._treeview_identifier = kwargs.get('treeview_identifier', None) # Callback when the tag registry is changed self._column_delegate_sub = ColumnDelegateRegistry().subscribe_delegate_changed( self._on_column_delegate_changed ) kwargs["mouse_pressed_fn"] = self._on_mouse_pressed kwargs["mouse_double_clicked_fn"] = self._on_mouse_double_clicked kwargs["column_clicked_fn"] = lambda column_id: self._on_column_clicked(column_id) kwargs["datetime_format_changed_fn"] = self._on_datetime_format_changed kwargs["sort_by_column"] = self._headers.index(self._model.sort_by_field) kwargs["sort_ascending"] = self._model.sort_ascending kwargs["builtin_column_count"] = self._model.builtin_column_count self._delegate = FileBrowserTreeViewDelegate(self._headers, theme, **kwargs) self._widget = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, mouse_pressed_fn=partial(self._on_mouse_pressed, None), mouse_double_clicked_fn=partial(self._on_mouse_double_clicked, None), style_type_name_override="TreeView.ScrollingFrame", ) def build_ui(self): # Tree View with self._widget: selection_changed_fn = lambda selections: self._on_selection_changed(selections) self._tree_view = ui.TreeView( self._model, delegate=self._delegate, root_visible=self._root_visible, header_visible=self._header_visible, selection_changed_fn=selection_changed_fn, columns_resizable=True, ) if self._treeview_identifier: self._tree_view.identifier = self._treeview_identifier # It should set the column widths and pass tag delegated to the main delegate self._on_column_delegate_changed() @property def tree_view(self): return self._tree_view @property def selections(self): if self._tree_view: return self._tree_view.selection return [] def refresh_ui(self, item: FileBrowserItem = None): """Throttle the refreshes so that the UI can keep up with multiple refresh directives in succession.""" def update_view(item: FileBrowserItem): if self._tree_view: self._tree_view.dirty_widgets() if self._model: # NOTE: The following action is not publicized but is required for a proper redraw self._model._item_changed(item) self._throttled_refresh_ui(item=item, callback=update_view, throttle_frames=2) def is_expanded(self, item: FileBrowserItem) -> bool: if self._tree_view and item: return self._tree_view.is_expanded(item) return False def set_expanded(self, item: FileBrowserItem, expanded: bool, recursive: bool = False): """ Sets the expansion state of the given item. Args: item (:obj:`FileBrowserItem`): The item to effect. expanded (bool): True to expand, False to collapse. recursive (bool): Apply state recursively to descendent nodes. Default False. """ if self._tree_view and item: self._tree_view.set_expanded(item, expanded, recursive) def select_and_center(self, item: FileBrowserItem): if not self._visible: return item = item or self._model.root if not item: return def set_expanded_recursive(item: FileBrowserItem): if not item: return set_expanded_recursive(item.parent) self.set_expanded(item, True) set_expanded_recursive(item) self._tree_view.selection = [item] self.refresh_ui() def _on_mouse_pressed(self, item: FileBrowserItem, x, y, button, key_mod): if self._mouse_pressed_fn: self._mouse_pressed_fn(button, key_mod, item, x=x, y=y) def _on_mouse_double_clicked(self, item: FileBrowserItem, x, y, button, key_mod): if self._mouse_double_clicked_fn: self._mouse_double_clicked_fn(button, key_mod, item, x=x, y=y) def _on_selection_changed(self, selections: [FileBrowserItem]): if not self._allow_multi_selection: if selections: selections = selections[-1:] self._tree_view.selection = selections if self._model: self._model.drag_mime_data = [sel.path for sel in selections] if self._selection_changed_fn: self._selection_changed_fn(selections) def _on_column_clicked(self, column_id: int): column_id = min(column_id, len(FileBrowserItemFields._fields) - 1) if column_id == self._delegate.sort_by_column: self._delegate.sort_ascending = not self._delegate.sort_ascending else: self._delegate.sort_by_column = column_id if self._model: self._model.sort_by_field = self._headers[column_id] self._model.sort_ascending = self._delegate.sort_ascending self.refresh_ui() def _on_datetime_format_changed(self): self.refresh_ui() def _on_item_changed(self, model, item): """Called by the model when something is changed""" if self._delegate and item is None: self._delegate.clear_futures() def _on_model_changed(self, model): """Called by super when the model is changed""" if model and self._tree_view: self._tree_view.model = model if self._delegate: self._delegate.clear_futures() def _on_column_delegate_changed(self): """Called by ColumnDelegateRegistry""" # Single column should fill all available space if not self._model.single_column: column_delegate_names = ColumnDelegateRegistry().get_column_delegate_names() column_delegate_types = [ColumnDelegateRegistry().get_column_delegate(name) for name in column_delegate_names] # Create the tag delegates column_delegates = [delegate_type() for delegate_type in column_delegate_types] self._delegate.set_column_delegates(column_delegates) # Set column widths # OM-30768: Make file-name dominant and push with left list view separator self._tree_view.column_widths = [ui.Fraction(.75), ui.Fraction(0.15), ui.Fraction(0.1)] + [ d.initial_width for d in column_delegates ] else: self._tree_view.column_widths = [ui.Fraction(1)] # Update the widget self._model._item_changed(None) def scroll_top(self): """Scrolls the widget to top""" if self._widget: # Scroll to top upon refresh self._widget.scroll_y = 0.0 def destroy(self): super().destroy() if self._model: self._model.destroy() self._model = None if self._tree_view: self._tree_view.destroy() self._tree_view = None if self._widget: self._widget.destroy() self._widget = None if self._delegate: self._delegate.destroy() self._delegate = None self._headers = None self._style = None self._selection_changed_fn = None self._mouse_pressed_fn = None self._mouse_double_clicked_fn = None self._column_delegate_sub = None class FileBrowserTreeViewDelegate(ui.AbstractItemDelegate): def __init__(self, headers: Tuple, theme: str, **kwargs): super().__init__() self._headers = headers self._theme = theme use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False if use_default_style: self._style = {} else: self._style = UI_STYLES[theme] self._hide_files = not kwargs.get("files_visible", True) self._tooltip = kwargs.get("tooltip", False) self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None) self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None) self._column_clicked_fn = kwargs.get("column_clicked_fn", None) self._datetime_format_changed_fn = kwargs.get("datetime_format_changed_fn", None) self._sort_by_column = kwargs.get("sort_by_column", 0) self._sort_ascending = kwargs.get("sort_ascending", True) self._builtin_column_count = kwargs.get("builtin_column_count", 1) self._column_delegates = [] self._icon_provider = kwargs.get("icon_provider", None) # The futures that are created by column delegates. We need to store # them to cancel when the model is changed. self._column_futures: List["Future"] = [] self._date_format_menu = None def destroy(self): self.clear_futures() self._headers = None self._style = None self._mouse_pressed_fn = None self._mouse_double_clicked_fn = None self._column_clicked_fn = None self._column_delegates = None self._icon_provider = None if self._date_format_menu: self._date_format_menu.destroy() self._date_format_menu = None def clear_futures(self): """Stop and destroy all working futures""" for future in self._column_futures: if not future.done(): future.cancel() self._column_futures = [] @property def sort_by_column(self) -> int: return self._sort_by_column @sort_by_column.setter def sort_by_column(self, column_id: int): self._sort_by_column = column_id @property def sort_ascending(self) -> bool: return self._sort_ascending @sort_ascending.setter def sort_ascending(self, value: bool): self._sort_ascending = value def _on_date_format_clicked(self): if not self._date_format_menu: self._date_format_menu = DatetimeFormatMenu(self._datetime_format_changed_fn) self._date_format_menu.visible = True self._date_format_menu.show_at( self._date_format_button.screen_position_x, self._date_format_button.screen_position_y+30 ) def build_header(self, column_id: int): if column_id >= self._builtin_column_count: # Additional columns from the extensions. self._column_delegates[column_id - self._builtin_column_count].build_header() return def on_column_clicked(column_id): if self._column_clicked_fn: self._column_clicked_fn(column_id) with ui.ZStack(style=self._style): with ui.HStack(): ui.Spacer(width=4) ui.Label(self._headers[column_id].capitalize(), height=20, style_type_name_override="TreeView.Header") # Invisible click area fills entire header frame if self._headers[column_id] == "date": with ui.HStack(): button = ui.Button(" ", height=20, style_type_name_override="TreeView.Column") self._date_format_button = ui.Button(" ", width=30, height=20, style_type_name_override="TreeView.Column") self._date_format_button.set_clicked_fn(lambda: self._on_date_format_clicked()) else: button = ui.Button(" ", height=20, style_type_name_override="TreeView.Column") if column_id == self._sort_by_column: with ui.HStack(): ui.Spacer() icon = ( f"{ICON_PATH}/{self._theme}/arrow_up.svg" if self._sort_ascending else f"{ICON_PATH}/{self._theme}/arrow_down.svg" ) ui.ImageWithProvider(icon, width=30, style_type_name_override="TreeView.Column") if self._headers[column_id] == "date": icon_date = ( f"{ICON_PATH}/{self._theme}/date_format.svg" ) ui.ImageWithProvider(icon_date, width=30, style_type_name_override="TreeView.Column") elif self._headers[column_id] == "date": with ui.HStack(): ui.Spacer() icon_date = ( f"{ICON_PATH}/{self._theme}/date_format.svg" ) ui.ImageWithProvider(icon_date, width=30, style_type_name_override="TreeView.Column") button.set_clicked_fn(lambda: on_column_clicked(column_id)) def build_branch(self, model: FileBrowserModel, item: FileBrowserItem, column_id: int, level: int, expanded: bool): """Create a branch widget that opens or closes subtree""" def get_branch_icon(item: FileBrowserItem, expanded: bool) -> Tuple[str, str]: icon = "minus.svg" if expanded else "plus.svg" tooltip = "" if item.alert: sev, tooltip = item.alert if sev == ALERT_WARNING: icon = "warn.svg" elif sev == ALERT_ERROR: icon = "error.svg" else: icon = "info.svg" return f"{ICON_PATH}/{self._theme}/{icon}", tooltip item_or_root = item or model.root if not item_or_root or not isinstance(item_or_root, FileBrowserItem): # Makes sure item has expected type, else may crash the process (See OM-34661). return if column_id == 0: with ui.HStack(width=20 * (level + 1), height=0): ui.Spacer() # don't create branch icon for unexpandable items if item_or_root.is_folder and item_or_root.expandable: # Draw the +/- icon icon, tooltip = get_branch_icon(item_or_root, expanded) ui.ImageWithProvider( icon, tooltip=tooltip, name="expand", width=10, height=10, style_type_name_override="TreeView.Icon" ) def build_widget(self, model: FileBrowserModel, item: FileBrowserItem, column_id: int, level: int, expanded: bool): """Create a widget per item""" item_or_root = item or model.root if not item_or_root or not isinstance(item_or_root, FileBrowserItem): # Makes sure item has expected type, else may crash the process (See OM-34661). return if column_id >= self._builtin_column_count: # Additional columns from the extensions. # Async run the delegate. The widget can be created later. future = self._column_delegates[column_id - self._builtin_column_count].build_widget( ColumnItem(item_or_root.path) ) self._column_futures.append(asyncio.ensure_future(AwaitWithFrame(ui.Frame(), future))) return if self._hide_files and not item_or_root.is_folder and item_or_root.hideable: # Don't show file items return value_model = model.get_item_value_model(item_or_root, column_id) if not value_model: return style_variant = self._get_style_variant(item_or_root) # File Name Column if column_id == 0: def mouse_pressed_fn(item: FileBrowserItem, *args): if self._mouse_pressed_fn: self._mouse_pressed_fn(item, *args) def mouse_double_clicked_fn(item: FileBrowserItem, *args): if self._mouse_double_clicked_fn: self._mouse_double_clicked_fn(item, *args) with ui.HStack(height=20, mouse_pressed_fn=partial(mouse_pressed_fn, item_or_root), mouse_double_clicked_fn=partial(mouse_double_clicked_fn, item_or_root)): ui.Spacer(width=2) self._draw_item_icon(item_or_root, expanded) ui.Spacer(width=5) ui.Label( value_model.get_value_as_string(), tooltip=item_or_root.path if self._tooltip else "", tooltip_offset=22, style_type_name_override="TreeView.Item", name=style_variant, ) # Date Column elif column_id == 1: with ui.HStack(): ui.Spacer(width=4) if isinstance(value_model, datetime): ui.Label( FileBrowserItem.datetime_as_string(value_model), style_type_name_override="TreeView.Item", name=style_variant) elif isinstance(value_model, str): ui.Label(value_model.get_value_as_string(), style_type_name_override="TreeView.Item", name=style_variant) # Size Column elif column_id == 2: if not item_or_root.is_folder: with ui.HStack(): ui.Spacer(width=4) ui.Label(value_model.get_value_as_string(), style_type_name_override="TreeView.Item", name=style_variant) def set_column_delegates(self, delegates): """Add custom columns""" self._column_delegates = delegates def _get_style_variant(self, item: FileBrowserItem): return "Cut" if is_path_cut(item.path) else "" def _draw_item_icon(self, item: FileBrowserItem, expanded: bool): if not item: return style_variant = self._get_style_variant(item) icon = item.icon if not icon and self._icon_provider: icon = self._icon_provider(item, expanded) if not icon: if item and not item.is_folder: icon = f"{ICON_PATH}/{self._theme}/file.svg" else: icon = ( f"{ICON_PATH}/{self._theme}/folder_open.svg" if expanded else f"{ICON_PATH}/{self._theme}/folder.svg" ) with ui.ZStack(width=0): if icon: # Draw the icon with ui.HStack(): ui.Spacer(width=4) ui.ImageWithProvider(icon, width=18, height=18, style_type_name_override="TreeView.Icon", name=style_variant) if not item.writeable: # Draw the lock lock_icon = f"{ICON_PATH}/{self._theme}/lock.svg" with ui.Placer(stable_size=True, offset_x=-1, offset_y=1): with ui.HStack(): ui.ImageWithProvider(lock_icon, width=17, height=17, style_type_name_override="TreeView.Icon", name="shadow") ui.Spacer() with ui.Placer(stable_size=True, offset_x=-2, offset_y=1): with ui.HStack(): ui.ImageWithProvider(lock_icon, width=17, height=17, style_type_name_override="TreeView.Icon", name=style_variant) ui.Spacer()
22,351
Python
40.623836
138
0.588296
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/grid_view.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. # """ A generic GridView Widget for File Systems """ __all__ = ["FileBrowserGridView", "FileBrowserGridViewDelegate"] import asyncio import carb import omni.kit.app from typing import Dict, List, Optional, Callable from functools import partial from omni import ui from carb import events, log_warn from carb.input import KEYBOARD_MODIFIER_FLAG_CONTROL, KEYBOARD_MODIFIER_FLAG_SHIFT from .view import FileBrowserView from .model import FileBrowserItem, FileBrowserModel, FileBrowserUdimItem from .style import UI_STYLES from .card import FileBrowserItemCard from .thumbnails import find_thumbnails_for_files_async from . import THUMBNAILS_GENERATED_EVENT from .clipboard import is_path_cut class FileBrowserGridView(FileBrowserView): def __init__(self, model: FileBrowserModel, **kwargs): self._delegate = None super().__init__(model) theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False if use_default_style: self._style = {} else: self._style = UI_STYLES[theme] self._allow_multi_selection = kwargs.get("allow_multi_selection", True) self._selection_changed_fn = kwargs.get("selection_changed_fn", None) self._widget = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="GridView.ScrollingFrame", ) self._delegate = FileBrowserGridViewDelegate(self._widget, theme, **kwargs) self.build_ui() @property def selections(self): if self._delegate: return self._delegate.selections return [] @selections.setter def selections(self, selections): if self._delegate: self._delegate.selections = selections or [] def build_ui(self, restore_selections: Optional[List[FileBrowserItem]] = None): if self._delegate: self._delegate.build_grid(self.model) self.refresh_ui(selections=restore_selections) def scale_view(self, scale: float): if self._delegate: self._delegate.scale = scale def refresh_ui(self, item: Optional[FileBrowserItem] = None, selections: Optional[List[FileBrowserItem]] = None): """Throttle the refreshes so that the UI can keep up with multiple refresh directives in succession.""" if not self._delegate: return def apply_selections(selections): self.selections = selections def refresh_ui_callback(selections): self._delegate.update_grid(self.model) # OM-70157: Switching between List/different Grid View sizes shouldn't reset user selections if selections: self.select_and_center(selections[0], callback=lambda _: apply_selections(selections)) self._throttled_refresh_ui( item=item, callback=lambda _: refresh_ui_callback(selections), throttle_frames=2) def select_and_center(self, item: FileBrowserItem, callback: Optional[Callable[[FileBrowserItem], None]] = None): if not self._visible or not item: return self.selections = [item] # OM-70154: add the ability to center the selected item in file browser grid view # calculate the scroll ratio by item index items = self.model.get_item_children(None) # This should not happen, but add it here as a fail-safe if item not in items: carb.log_warn(f"Failed to select and center item [ {item.path} ] in file browser grid view.") return item_index = items.index(item) scroll_ratio = float((item_index + 1) / len(items)) asyncio.ensure_future( self._delegate.center_selection_async( item, scroll_frame=self._widget, scroll_ratio=scroll_ratio, refresh_interval=3, callback=callback)) def _on_selection_changed(self, selections: List[FileBrowserItem]): if not self._allow_multi_selection: if selections: selections = selections[-1:] self._widget.selection = selections if self._selection_changed_fn: self._selection_changed_fn(selections) def _on_item_changed(self, model, _): self.refresh_ui() def _on_model_changed(self, model): """Called by super when the model is changed""" self.build_ui() def scroll_top(self): """Scrolls the widget to top""" # Scroll to top upon refresh self._widget.scroll_y = 0.0 def destroy(self): super().destroy() if self._delegate: self._delegate.destroy() self._delegate = None if self._widget: self._widget.destroy() self._widget = None self._style = None self._selection_changed_fn = None class FileBrowserGridViewDelegate: def __init__(self, widget: ui.Widget, theme: str, **kwargs): self._widget: ui.Widget = widget self._grid: ui.VGrid = None self._cards: Dict[str, FileBrowserItemCard] = {} self._card_paths: List[str] = [] self._custom_thumbnails: Dict[str, str] = {} self._selections = [] self._pending_selections = [] self._style = UI_STYLES[theme] self._tooltip = kwargs.get("tooltip", False) self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None) self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None) self._selection_changed_fn = kwargs.get("selection_changed_fn", None) self._drop_fn = kwargs.get("drop_fn", None) self._thumbnail_provider = kwargs.get("thumbnail_provider", None) self._badges_provider = kwargs.get("badges_provider", None) self._treeview_identifier = kwargs.get("treeview_identifier", None) self._testing = kwargs.get("testing", False) self._card_width = 120 self._card_height = 120 self._scale = 1 self._update_grid_future = None self._thumbnails_generated_subscription = None self._was_dragging = False # Monitor for new thumbnails being generated event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._thumbnails_generated_subscription = event_stream.create_subscription_to_pop_by_type( THUMBNAILS_GENERATED_EVENT, self.update_cards_on_thumbnails_generated, name="filebrowser grid_view") @property def scale(self) -> float: return self._scale @scale.setter def scale(self, scale: float): self._scale = scale @property def selections(self) -> List[FileBrowserItem]: return [card.item for card in self._selections] @selections.setter def selections(self, selections: List[FileBrowserItem]): self._pending_selections = [] if self._cards: # grid been build, set selection cards = [self._cards[item.path] for item in selections if item.path in self._cards] self.clear_selections() self.extend_selections(cards) else: # grid has not been build yet, set pending_selection self._pending_selections = selections def build_grid(self, model: FileBrowserModel): self.clear_selections() for _, card in self._cards.items(): card.destroy() self._cards.clear() self._card_paths.clear() with self._widget: with ui.ZStack(): with ui.VStack(): if self._grid: self._grid = None self._grid = ui.VGrid( column_width=self._scale * self._card_width, row_height=self._scale * self._card_height + 20, mouse_pressed_fn=partial(self._on_mouse_pressed, model, None), mouse_double_clicked_fn=partial(self._on_mouse_double_clicked, None), style_type_name_override="GridView.Grid", content_clipping=True, ) if self._treeview_identifier: self._grid.identifier = self._treeview_identifier ui.Spacer(height=30) # OM-70157: Since we cannot clip the mouse event for the button in Zoombar for the VGrid, we have to add a invisibleButton here, whose clicked_fn # will not be triggered if the ZoomBar switch layout button is on top of it; this way it will not clear out the selections when the user click # on the layout switch button when it is on top of the VGrid. def grid_clicked(*args, **kwargs): self._on_mouse_released(model, None, None, None, 0, 0) ui.InvisibleButton(clicked_fn=grid_clicked) def update_grid(self, model: FileBrowserModel): """Generates a grid of cards and renders them with custom thumbnails""" if not self._grid: return if model: children = model.get_item_children(None) else: return # make sure the grid not rebuild more than once rebuilt_grid = False for path in self._cards: # If items got deleted then re-build the grid if path not in [c.path for c in children]: self.build_grid(model) rebuilt_grid = True break # update card style if path in cut clipboard if is_path_cut(path): self._cards[path].apply_cut_style() else: self._cards[path].remove_cut_style() for item in children: # Add cards for any new children if item.item_changed : item.item_changed = False if not rebuilt_grid: self.build_grid(model) rebuilt_grid = True with self._grid: for item in children: # Add cards for any new children # OM-91073: check paths to prevent build card more than once in sometimes # not use the self._cards because it not create immediately in frame's build_fn # so we need store and check the card path directly if item.path in self._card_paths: continue def __build_card(file_item): self._cards[file_item.path] = self.build_card(model, file_item) self._card_paths.append(item.path) if self._testing: # In testing mode, forces cards to immediately be built and made available with ui.Frame(): self._cards[item.path] = self.build_card(model, item) else: # OM-63433: Use content_clipping to speed up item display in file picker ui.Frame(content_clipping=True, build_fn=lambda i=item: __build_card(i)) async def refresh_thumbnails(model: FileBrowserModel): # Get custom thumbnails for parent folder and synchronously render them if they exist if model and model.root: self._custom_thumbnails = await model.root.get_custom_thumbnails_for_folder_async() try: await self.refresh_thumbnails_async(list(self._cards)) except asyncio.CancelledError: return # selections was set before cards created, update now if self._pending_selections: cards = [self._cards[item.path] for item in self._pending_selections if item.path in self._cards] self._pending_selections = [] self.clear_selections() self.extend_selections(cards) # Store away future so that it can be cancelled, e.g. when switching directories if self._update_grid_future and not self._update_grid_future.done(): self._update_grid_future.cancel() self._update_grid_future = asyncio.ensure_future(refresh_thumbnails(model)) def update_cards_on_thumbnails_generated(self, event: events.IEvent): """When new thumbnails are generated, re-renders associated cards""" if event.type != THUMBNAILS_GENERATED_EVENT: return try: payload = event.payload.get_dict() urls = payload.get('paths', []) except Exception as e: log_warn(f"Failed to retrieve payload from generated thumbnails event: {str(e)}") return async def refresh_thumbnails(urls: str): # Get custom thumbnails for given urls. Don't try to generate (again) if not found. self._custom_thumbnails.update(await find_thumbnails_for_files_async(urls, generate_missing=False)) try: await self.refresh_thumbnails_async(urls) except asyncio.CancelledError: return refresh_urls = [url for url in urls if url in self._cards] if refresh_urls: # Execute and forget asyncio.ensure_future(refresh_thumbnails(refresh_urls)) def build_card(self, model: FileBrowserModel, item: FileBrowserItem) -> FileBrowserItemCard: """Create a widget per item""" if not item: return if isinstance(item, FileBrowserUdimItem): custom_thumbnail = self._custom_thumbnails.get(item.repr_path) else: custom_thumbnail = self._custom_thumbnails.get(item.path) card = FileBrowserItemCard( item, width=self._scale * self._card_width, height=self._scale * self._card_height, mouse_pressed_fn=partial(self._on_mouse_pressed, model), mouse_released_fn=partial(self._on_mouse_released, model), mouse_double_clicked_fn=self._on_mouse_double_clicked, drag_fn=self._on_drag, drop_fn=self._drop_fn, get_thumbnail_fn=self._thumbnail_provider, get_badges_fn=self._badges_provider, custom_thumbnail=custom_thumbnail, timeout=model._timeout if model else 10.0, ) return card async def refresh_thumbnails_async(self, urls: str): if not self._custom_thumbnails: return tasks = [] for url in urls: card = self._cards.get(url, None) item = card.item if isinstance(item, FileBrowserUdimItem): custom_thumbnail = self._custom_thumbnails.get(item.repr_path) else: custom_thumbnail = self._custom_thumbnails.get(item.path) if card and custom_thumbnail: tasks.append(card.refresh_thumbnail_async(custom_thumbnail)) if tasks: try: await asyncio.gather(*tasks, return_exceptions=True) except Exception as e: carb.log_error(f"Failed to refresh thumbnails: {e}") except asyncio.CancelledError: return def _on_mouse_pressed(self, model: FileBrowserModel, card: FileBrowserItemCard, x, y, b, key_mod): if self._mouse_pressed_fn: self._mouse_pressed_fn(b, key_mod, card.item if card else None, x=x, y=y) def _on_mouse_released(self, model: FileBrowserModel, card: FileBrowserItemCard, x, y, b, key_mod): # Don't cancel selections # FIXME: mouse release event will be triggered for both card and grid. It # needs to check card to make sure mouse release event from grid will not influence selections. if self._was_dragging: if card: self._was_dragging = False return if b == 0: # Update selection list on left mouse clicks if key_mod & KEYBOARD_MODIFIER_FLAG_CONTROL: if card in self._selections: self.remove_selection(card) else: self.add_selection(card) elif key_mod & KEYBOARD_MODIFIER_FLAG_SHIFT: if not self._selections: self.add_selection(card) elif card: last_selection = self._selections[-1].item current_selection = card.item children = model.get_item_children(None) # Note: Search items may re-generate frame to frame, so find by path rather than by object ref last_selection_index = next((i for i, item in enumerate(children) if item.path == last_selection.path), -1) current_selection_index = next((i for i, item in enumerate(children) if item.path == current_selection.path), -1) if last_selection_index >= 0 and current_selection_index >=0: first_index = min(last_selection_index, current_selection_index) last_index = max(last_selection_index, current_selection_index) self.clear_selections() selection_indices = range(first_index, last_index+1) # OM-72965: only add selection in reverse order if current selection is after last selection, so # that the last element in selection remains the oldest (similar to file explorer) if current_selection_index > last_selection_index: selection_indices = reversed(selection_indices) for i in selection_indices: card = self._cards.get(children[i].path) self.add_selection(card) else: self.clear_selections() self.add_selection(card) if self._selection_changed_fn: self._selection_changed_fn(self.selections) def _on_mouse_double_clicked(self, card: FileBrowserItemCard, x, y, b, key_mod): if self._mouse_double_clicked_fn: self._mouse_double_clicked_fn(b, key_mod, card.item if card else None, x=x, y=y) def _on_drag(self, card: FileBrowserItemCard, thumbnail: str): self._was_dragging = True result: List[str] = [] if card not in self._selections: return card.on_drag() with ui.VStack(): for card in self._selections: result.append(card.on_drag()) return "\n".join(result) def clear_selections(self): for selection in self._selections: selection.selected = False self._selections.clear() def extend_selections(self, cards: List[FileBrowserItemCard]): for card in cards: self.add_selection(card) def add_selection(self, card: FileBrowserItemCard): if card and card not in self._selections: card.selected = True self._selections.append(card) def remove_selection(self, card: FileBrowserItemCard): if card and card in self._selections: card.selected = False self._selections.remove(card) async def center_selection_async( self, selection : FileBrowserItem, scroll_frame=None, scroll_ratio=0.0, refresh_interval=2, callback: Optional[Callable[[FileBrowserItem], None]] = None ): # OM-70154: add the ability to center the selected item in file browser grid view async def _wait_for_ui_build(refresh_interval=refresh_interval): for _ in range(refresh_interval): await omni.kit.app.get_app().next_update_async() await _wait_for_ui_build() cards = list(self._cards.values()) if not cards: return card_height = cards[0]._widget.computed_content_height card = self._cards.get(selection.path) if not scroll_frame and not card: return # card is not built yet, need to scroll to the y position in the scrolling frame to trigger card build if not card: # scroll one line to trigger calculation for scroll_y_max scroll_frame.scroll_y = card_height await _wait_for_ui_build() # scroll to the card by using the item index ratio if scroll_ratio > 0: scroll_frame.scroll_y = scroll_ratio * scroll_frame.scroll_y_max - card_height * 0.5 await _wait_for_ui_build() card = self._cards.get(selection.path) if card: card._widget.scroll_here() self.add_selection(card) if callback: callback(selection) def destroy(self): self._grid = None self._cards.clear() self._card_paths.clear() self._custom_thumbnails.clear() self._selections.clear() if self._update_grid_future and not self._update_grid_future.done(): self._update_grid_future.cancel() self._update_grid_future = None self._thumbnails_generated_subscription = None self._style = None self._mouse_pressed_fn = None self._mouse_double_clicked_fn = None self._selection_changed_fn = None self._drop_fn = None self._thumbnail_provider = None self._badges_provider = None
22,038
Python
41.301343
161
0.600554
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """ The basic UI widget and set of supporting classes for navigating the filesystem through a tree view. The filesystem can either be from your local machine or the Omniverse server. Example: .. code-block:: python With just a few lines of code, you can create a powerful, flexible tree view widget that you can embed into your view. filebrowser = FileBrowserWidget( "Omniverse", layout=SPLIT_PANES, mouse_pressed_fn=on_mouse_pressed, selection_changed_fn=on_selection_changed, drop_fn=drop_handler, filter_fn=item_filter_fn, ) Module Constants: layout: {LAYOUT_SINGLE_PANE_SLIM, LAYOUT_SINGLE_PANE_WIDE, LAYOUT_SPLIT_PANES, LAYOUT_DEFAULT} """ LAYOUT_SINGLE_PANE_SLIM = 1 LAYOUT_SINGLE_PANE_WIDE = 2 LAYOUT_SPLIT_PANES = 3 LAYOUT_SINGLE_PANE_LIST = 4 LAYOUT_DEFAULT = 3 TREEVIEW_PANE = 1 LISTVIEW_PANE = 2 import carb.events CONNECTION_ERROR_EVENT: int = carb.events.type_from_string("omni.kit.widget.filebrowser.CONNECTION_ERROR") MISSING_IMAGE_THUMBNAILS_EVENT: int = carb.events.type_from_string("omni.services.thumbnails.MISSING_IMAGE_THUMBNAILS") THUMBNAILS_GENERATED_EVENT: int = carb.events.type_from_string("omni.services.thumbnails.THUMBNAILS_GENERATED") ALERT_INFO = 1 ALERT_WARNING = 2 ALERT_ERROR = 3 from .widget import FileBrowserWidget from .card import FileBrowserItemCard from .model import FileBrowserModel, FileBrowserItem, FileBrowserUdimItem, FileBrowserItemFactory from .filesystem_model import FileSystemModel, FileSystemItem from .nucleus_model import NucleusModel, NucleusItem, NucleusConnectionItem from .column_delegate_registry import ColumnDelegateRegistry from .abstract_column_delegate import ColumnItem from .abstract_column_delegate import AbstractColumnDelegate from .thumbnails import find_thumbnails_for_files_async, list_thumbnails_for_folder_async from .clipboard import save_items_to_clipboard, get_clipboard_items, is_clipboard_cut, is_path_cut, clear_clipboard
2,447
Python
38.48387
119
0.7736
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/card.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. # """ Base Model classes for the filebrowser entity. """ __all__ = ["FileBrowserItemCard"] import carb from typing import Optional from functools import partial from omni import ui from .clipboard import is_path_cut from .model import FileBrowserItem from .style import UI_STYLES, THUMBNAIL_PATH, ICON_PATH from . import ALERT_WARNING, ALERT_ERROR class FileBrowserItemCard(ui.Widget): def __init__(self, item: FileBrowserItem, **kwargs): import carb.settings self._item = item self._widget = None self._rectangle = None self._image_frame = None self._image_buffer = None self._image_buffer_thumbnail = None self._overlay_frame = None self._back_buffer = None self._back_buffer_thumbnail = None self._label = None self._selected = False self._theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False if use_default_style: self._style = {} else: self._style = kwargs.get("style", UI_STYLES[self._theme]) self._width = kwargs.get("width", 60) self._height = kwargs.get("height", 60) self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None) self._mouse_released_fn = kwargs.get("mouse_released_fn", None) self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None) self._drop_fn = kwargs.get("drop_fn", None) self._get_thumbnail_fn = kwargs.get("get_thumbnail_fn", None) self._get_badges_fn = kwargs.get("get_badges_fn", None) self._custom_thumbnail = kwargs.get("custom_thumbnail", None) self._timeout = kwargs.get("timeout", 10.0) super().__init__() self._drag_fn = kwargs.get("drag_fn", None) if self._drag_fn: self._drag_fn = partial(self._drag_fn, self) else: # If nothing is set, use the default one self._drag_fn = self.on_drag self._tooltip = f"Path: {item.path}\n" self._tooltip += f"Size: {FileBrowserItem.size_as_string(item.fields.size)}\n" self._tooltip += f"Modified: {FileBrowserItem.datetime_as_string(item.fields.date)}" self._cached_thumbnail: Optional[str] = None self._build_ui() @property def item(self) -> FileBrowserItem: return self._item @property def selected(self) -> bool: return self._selected @selected.setter def selected(self, value: bool): self._rectangle.selected = value self._label.checked = value self._selected = value def apply_cut_style(self): for widget in (self._back_buffer_thumbnail, self._image_buffer_thumbnail, self._label): if widget: widget.name = "Cut" def remove_cut_style(self): for widget in (self._back_buffer_thumbnail, self._image_buffer_thumbnail, self._label): if widget: widget.name = "" def _build_ui(self): if not self._item: return def on_mouse_pressed(card: "FileBrowserItemCard", *args): if self._mouse_pressed_fn: self._mouse_pressed_fn(card, *args) def on_mouse_released(card: "FileBrowserItemCard", *args): if self._mouse_released_fn: self._mouse_released_fn(card, *args) def on_mouse_double_clicked(card: "FileBrowserItemCard", *args): if self._mouse_double_clicked_fn: self._mouse_double_clicked_fn(card, *args) def mouse_hovered_fn(hovered: bool): self._label.selected = hovered self._widget = ui.ZStack(width=0, height=0, style=self._style) with self._widget: self._rectangle = ui.Rectangle( mouse_pressed_fn=partial(on_mouse_pressed, self), mouse_released_fn=partial(on_mouse_released, self), mouse_double_clicked_fn=partial(on_mouse_double_clicked, self), style_type_name_override="Card", ) self._rectangle.set_mouse_hovered_fn(mouse_hovered_fn) with ui.VStack(spacing=0): with ui.ZStack(): thumbnail = self._custom_thumbnail or self._get_thumbnail(self._item) self._image_frame = ui.Frame( width=self._width, height=self._height, drag_fn=lambda: self.on_drag(thumbnail), accept_drop_fn=lambda url: self._item.is_folder, drop_fn=lambda event: self._on_drop(event), ) self._overlay_frame = ui.Frame( width=self._width, height=self._height, ) self.draw_thumbnail(self._custom_thumbnail) self.draw_badges() with ui.HStack(height=40): # Note: This Placer nudges the label closer to the image. The inherent # margin would otherwise create a less pleasing separation. with ui.Placer(stable_size=True, offset_x=0, offset_y=-8): self._label = ui.Label( self._item.name, style_type_name_override="Card.Label", word_wrap=True, elided_text=True if self._theme == "NvidiaDark" else False, tooltip=self._tooltip, ) ui.Spacer() # add cut style if path is in cut clipboard on build if is_path_cut(self._item.path): self.apply_cut_style() def _get_thumbnail(self, item: FileBrowserItem) -> str: thumbnail = None if self._get_thumbnail_fn: thumbnail = self._get_thumbnail_fn(item) if not thumbnail: # Set to default thumbnails if self._item.is_folder: thumbnail = f"{THUMBNAIL_PATH}/folder_256.png" else: thumbnail = f"{THUMBNAIL_PATH}/file_256.png" return thumbnail def on_drag(self, thumbnail: Optional[str] = None): with ui.VStack(): if not thumbnail and self._cached_thumbnail: thumbnail = self._cached_thumbnail elif not thumbnail: if self._item.is_folder: thumbnail = f"{THUMBNAIL_PATH}/folder_256.png" else: thumbnail = f"{THUMBNAIL_PATH}/file_256.png" ui.Image(thumbnail, width=32, height=32) ui.Label(self._item.path) return self._item.path def _on_drop(self, event: ui.WidgetMouseDropEvent): if self._drop_fn: self._drop_fn(self._item, event.mime_data) async def draw_thumbnail_async(self, thumbnail: str): self.draw_thumbnail(thumbnail) if is_path_cut(self._item.path): self.apply_cut_style() def draw_thumbnail(self, thumbnail: str): """Asynchronously redraws thumbnail with the given file""" def on_image_progress(frame: ui.Frame, thumbnail_image: ui.Image, progress: float): """Called when the image loading progress is changed.""" if progress != 1.0: # We only need to catch the moment when the image is loaded. return # Hide the icon on the background. if frame: frame.visible = False # Remove the callback to avoid circular references. thumbnail_image.set_progress_changed_fn(None) if thumbnail: self._cached_thumbnail = thumbnail with self._image_frame: if not self._image_buffer: self._image_buffer = ui.ZStack() with self._image_buffer: self._back_buffer = ui.Frame() with self._back_buffer: default_thumbnail = self._get_thumbnail(self._item) self._back_buffer_thumbnail = ui.ImageWithProvider( default_thumbnail, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style_type_name_override="Card.Image", ) self._image_frame.set_drag_fn(lambda: self._drag_fn(default_thumbnail)) if not thumbnail: return with self._image_buffer: front_buffer = ui.Frame() with front_buffer: # NOTE: Ideally, we could use ui.ImageProvider here for consistency. However, if that # method doesn't allow loading images from "omniverse://". thumbnail_image = ui.Image( thumbnail, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, style_type_name_override="Card.Image", ) thumbnail_image.set_progress_changed_fn(partial(on_image_progress, self._back_buffer, thumbnail_image)) self._image_buffer_thumbnail = thumbnail_image self._image_frame.set_drag_fn(lambda: self._drag_fn(thumbnail)) self._back_buffer = None def draw_badges(self): if not self._item or not self._get_badges_fn: return badges = self._get_badges_fn(self._item) if self._item.alert: sev, msg = self._item.alert if sev == ALERT_WARNING: badges.append((f"{ICON_PATH}/{self._theme}/warn.svg", msg)) elif sev == ALERT_ERROR: badges.append((f"{ICON_PATH}/{self._theme}/error.svg", msg)) else: badges.append((f"{ICON_PATH}/{self._theme}/info.svg", msg)) if not badges: return size = 14 margin_width = 6 margin_height = 8 shadow_offset = 1 with self._overlay_frame: # First, the shadows with ui.ZStack(): with ui.VStack(): ui.Spacer() with ui.HStack(height=size, spacing=2): ui.Spacer() for badge in badges: icon, _ = badge ui.ImageWithProvider( icon, width=size, name="shadow", fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style_type_name_override="Card.Badge", ) ui.Spacer(width=margin_width - shadow_offset) ui.Spacer(height=margin_height - shadow_offset) # Then, the image itself with ui.VStack(): ui.Spacer() with ui.HStack(height=size, spacing=2): ui.Spacer() for badge in badges: icon, tooltip = badge ui.ImageWithProvider( icon, tooltip=tooltip, width=size, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style_type_name_override="Card.Badge", ) ui.Spacer(width=margin_width) ui.Spacer(height=margin_height) async def refresh_thumbnail_async(self, thumbnail: str): try: await self.draw_thumbnail_async(thumbnail) except Exception as exc: carb.log_error(f"Failed to redraw thumbnail {exc}") def destroy(self): self._item = None self._label = None self._image_frame = None self._overlay_frame = None self._image_buffer = None self._image_buffer_thumbnail = None self._back_buffer = None self._back_buffer_thumbnail = None self._rectangle = None self._widget = None
12,874
Python
39.109034
123
0.536197
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/model.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. # __all__ = ["FileBrowserItem", "FileBrowserItemFactory", "FileBrowserModel"] import os import asyncio import omni.client import omni.kit.app import threading from typing import List, Dict, Tuple, Union, Callable, Any from datetime import datetime from collections import OrderedDict from omni import ui from carb import log_warn from omni.kit.helper.file_utils import asset_types from .thumbnails import list_thumbnails_for_folder_async from .column_delegate_registry import ColumnDelegateRegistry from .date_format_menu import get_datetime_format from . import CONNECTION_ERROR_EVENT from collections import namedtuple FileBrowserItemFields = namedtuple("FileBrowserItemFields", "name date size permissions") compiled_regex = None # A hacky way to get the number of fields in FileBrowserItemFields. Otherwise we need to set hardcoded "3". BUILTIN_COLUMNS = len(dir(FileBrowserItemFields)) - len(dir(namedtuple("_", ""))) class NoLock(object): def __init__(self): pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass class FileBrowserItem(ui.AbstractItem): """ Base class for the Filebrowser tree view Item. Should be sub-classed to implement specific filesystem behavior. The Constructor should not be called directly. Instead there are factory methods available for creating instances when needed. """ # flags for item display expandable = True # whether this type of FileBrowserItem is expandable hideable = True # whether this type of FileBrowserItem is hideable def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = False, is_deleted: bool = False): super().__init__() self._path = path.replace("\\", "/") self._fields = fields # Raw field values self._models = () # Formatted values for display self._parent = None self._children = OrderedDict() self._is_folder = is_folder self._is_deleted = is_deleted self._populated = False self._is_udim_file = False self._populate_func = None self._populate_future = None self._enable_sorting = True # Enables children to be sorted self._icon = None self._alert: Tuple[int, str] = None self._item_changed = False # Enables thread-safe reads/writes to shared data, e.g. children dict self._mutex_lock: threading.Lock = threading.Lock() if is_folder else NoLock() @property def name(self) -> str: """str: Item name.""" return getattr(self._fields, "name", "") @property def path(self) -> str: """str: Full path name.""" return self._path @property def fields(self) -> FileBrowserItemFields: """:obj:`FileBrowserItemFields`: A subset of the item's stats stored as a string tuple.""" return self._fields @property def models(self) -> Tuple: """Tuple[:obj:`ui.AbstractValueModel`]: The columns of this item.""" return self._models @property def parent(self) -> object: """:obj:`FileBrowserItem`: Parent of this item.""" return self._parent @property def children(self) -> OrderedDict: """dict[:obj:`FileBrowserItem`]: Children of this item. Does not populate the item if not already populated.""" children = {} with self._mutex_lock: for name, child in self._children.items(): children[name] = child return children @property def is_folder(self) -> bool: """bool: True if this item is a folder.""" return self._is_folder @property def item_changed (self) -> bool: """bool: True if this item is has been restore/delete aready.""" return self._item_changed @item_changed .setter def item_changed (self, value: bool): self._item_changed = value @property def is_deleted(self) -> bool: """bool: True if this item is a deleted folder/file.""" return self._is_deleted @is_deleted.setter def is_deleted(self, value: bool): self._is_deleted = value @property def populated(self) -> bool: """bool: Gets/Sets item populated state.""" return self._populated @populated.setter def populated(self, value: bool): self._populated = value @property def is_udim_file(self) -> bool: """bool: Gets/Sets item udim_file state.""" return self._is_udim_file @is_udim_file.setter def is_udim_file(self, value: bool): self._is_udim_file = value @property def enable_sorting(self) -> bool: """bool: True if item's children are sortable.""" return self._enable_sorting @property def icon(self) -> str: """str: Gets/sets path to icon file.""" return self._icon @icon.setter def icon(self, icon: str): self._icon = icon @property def readable(self) -> bool: return True @property def writeable(self) -> bool: return True @property def alert(self) -> Tuple[int, str]: return self._alert @alert.setter def alert(self, alert: Tuple[int, str]): self._alert = alert @property def expandable(self) -> bool: """whether this FileBrowserItem is expandable. Override to change behavior""" return True @property def hideable(self) -> bool: """whether this FileBrowserItem is hideable. Override to change behavior""" return True async def on_populated_async(self, result=None, children=None, callback=None): if isinstance(result, Exception) and not isinstance(result, asyncio.CancelledError): log_warn(f"Error populating '{self.path}': {str(result)}") else: # add udim placeholders FileBrowserUdimItem.populate_udim(self) if callback: callback(children) def get_subitem_model(self, index: int) -> object: """ Returns ith column of this item. Returns: :obj:`AbstractValueModel` """ if self._models and index < len(self._models): return self._models[index] return None def populate_with_callback(self, callback: Callable, timeout: float = 10.0): """ Populates this item if not already populated. When done, executes callback. Args: callback (Callable): Function signature is void callback(children: [FileBrowserItem]). timeout (float): Time out duration on failed server connections. Default 10.0. """ if self._populate_future and not self._populate_future.done(): # If there is an ongoing task for populating this folder # Just add the call back instead of cancel it. # populate_with_callback is only called by get_item_children # the callback only need one place holder parameter, so could use here. # simply cancel the furture cause the expand invalid, see OM-35385 self._populate_future.add_done_callback(callback) else: self._populate_future = asyncio.ensure_future(self.populate_async(lambda result, children: self.on_populated_async(result, children, callback), timeout=timeout)) async def populate_async(self, callback_async: Callable = None, timeout: float = 10.0) -> Any: """ Populates current item asynchronously if not already. Override this method to customize for specific file systems. Args: callback_async (Callable): Function signature is void callback(result, children: [FileBrowserItem]), where result is an Exception type upon error. timeout (float): Time out duration on failed server connections. Default 10.0. Returns: Any: Result of executing callback. """ if not self._populated: for _, child in self._children.items(): child._parent = self self._populated = True result = None if callback_async: return await callback_async(result, self.children) else: return result def on_list_change_event(self, event: omni.client.ListEvent, entry: omni.client.ListEntry) -> bool: """ Virtual method to be implemented by sub-class. When called with a ListEvent, should update this item's children list with the corresponding ListEntry. Args: event (:obj:`omni.client.ListEvent`): One of of {UNKNOWN, CREATED, UPDATED, DELETED, METADATA, LOCKED, UNLOCKED}. entry (:obj:`omni.client.ListEntry`): Updated entry as defined by omni.client. """ return True def add_child(self, item: object): """ Adds item as child. Args: item (:obj:`FileBrowserItem`): Child item. """ with self._mutex_lock: if item: self._children[item.name] = item item._parent = self def del_child(self, item_name: str): """ Deletes child item by name. Args: item_name (str): Name of child item. """ with self._mutex_lock: if item_name in self._children: # Note: Pop (instead of del) item here so as not to destory it. Let garbage collection clean it up when # all references are released. Otherwise may result in a race condition (See OM-34661). self._children.pop(item_name) async def get_custom_thumbnails_for_folder_async(self) -> Dict: """ Returns the thumbnail dictionary for this (folder) item. Returns: Dict: With children url's as keys, and url's to thumbnail files as values. """ # If item is 'None' them interpret as root node if self.is_folder: return await list_thumbnails_for_folder_async(self.path) return {} @staticmethod def size_as_string(value: int) -> str: one_kb = 1024.0 one_mb = 1024.0 * one_kb one_gb = 1024.0 * one_mb return ( f"{value/one_gb:.2f} GB" if value > one_gb else ( f"{value/one_mb:.2f} MB" if value > one_mb else f"{value/one_kb:.2f} KB" ) ) @staticmethod def datetime_as_string(value: datetime) -> str: return value.strftime(f"{get_datetime_format()} %I:%M%p") class FileBrowserUdimItem(FileBrowserItem): def __init__(self, path: str, fields: FileBrowserItemFields, range_start: int, range_end: int, repr_frame: int = None): super().__init__(path, fields, is_folder=False) self._range_start = range_start self._range_end = range_end self._repr_frame = repr_frame @property def repr_path(self) -> str: """str: Full thumbnail path name.""" url_parts = self._path.split(".<UDIM>.") if self._repr_frame and len(url_parts) == 2: return f"{url_parts[0]}.{self._repr_frame}.{url_parts[1]}" else: return self._path @staticmethod def populate_udim(parent: FileBrowserItem): udim_added_items = {} for _, item in parent._children.items(): if not item.is_folder and asset_types.is_asset_type(item.path, asset_types.ASSET_TYPE_IMAGE): udim_full_path, udim_index = FileBrowserUdimItem.get_udim_sequence(item.path) if udim_full_path: if not udim_full_path in udim_added_items: udim_added_items[udim_full_path] = {"placeholder": udim_full_path, "range": [udim_index], "items": [item]} else: udim_added_items[udim_full_path]["range"].append(udim_index) udim_added_items[udim_full_path]["items"].append(item) for udim in udim_added_items: range = udim_added_items[udim]["range"] udim_full_path = udim_added_items[udim]["placeholder"] udim_name = os.path.basename(udim_full_path) for item in udim_added_items[udim]["items"]: item.is_udim_file = True # get 1st udim item to use for thumbnail item = FileBrowserItemFactory.create_udim_item(udim_name, udim_full_path, range[0], range[-1], range[0]) parent.add_child(item) @staticmethod def get_udim_sequence(full_path: str): import re global compiled_regex if compiled_regex == None: types = '|'.join([t[1:] for t in asset_types.asset_type_exts(asset_types.ASSET_TYPE_IMAGE)]) numbers = "[0-9][0-9][0-9][0-9]" compiled_regex = re.compile(r'([\w.-]+)(.)('+numbers+')\.('+types+')$') udim_name = compiled_regex.sub(r"\1\2<UDIM>.\4", full_path) if udim_name and udim_name != full_path: udim_index = compiled_regex.sub(r"\3", os.path.basename(full_path)) return udim_name, udim_index return None, None class FileBrowserItemFactory: @staticmethod def create_group_item(name: str, path: str) -> FileBrowserItem: if not name: return None fields = FileBrowserItemFields(name, datetime.now(), 0, 0) item = FileBrowserItem(path, fields, is_folder=True) item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel("")) item._enable_sorting = False return item @staticmethod def create_dummy_item(name: str, path: str) -> FileBrowserItem: if not name: return None fields = FileBrowserItemFields(name, datetime.now(), 0, 0) item = FileBrowserItem(path, fields, is_folder=False) item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel("")) return item @staticmethod def create_udim_item(name: str, path: str, range_start: int, range_end: int, repr_frame: int): modified_time = datetime.now() fields = FileBrowserItemFields(name, modified_time, 0, omni.client.AccessFlags.READ) item = FileBrowserUdimItem(path, fields, range_start, range_end, repr_frame=repr_frame) item._models = (ui.SimpleStringModel(f"{name} [{range_start}-{range_end}]"), modified_time, ui.SimpleStringModel("N/A")) return item class FileBrowserModel(ui.AbstractItemModel): """ Base class for the Filebrowser tree view Model. Should be sub-classed to implement specific filesystem behavior. Args: name (str): Name of root item. If None given, then create an initally empty model. Keyword Args: drop_fn (Callable): Function called to handle drag-n-drops. Function signature: void drop_fn(dst_item: :obj:`FileBrowserItem`, src_item: :obj:`FileBrowserItem`) filter_fn (Callable): This handler should return True if the given tree view item is visible, False otherwise. Function signature: bool filter_fn(item: :obj:`FileBrowserItem`) sort_by_field (str): Name of column by which to sort items in the same folder. Default "name". sort_ascending (bool): Sort in ascending order. Default True. """ _main_loop = asyncio.get_event_loop() def __init__(self, name: str = None, root_path: str = "", **kwargs): super().__init__() if name: self._root = FileBrowserItemFactory.create_group_item(name, root_path) else: self._root = None # By default, display these number of columns self._single_column = False self._show_udim_sequence = False self._drop_fn = kwargs.get("drop_fn", None) self._filter_fn = kwargs.get("filter_fn", None) self._sort_by_field = kwargs.get("sort_by_field", "name") self._sort_ascending = kwargs.get("sort_ascending", True) self._timeout = kwargs.get("timeout", 10.0) self._list_change_subscription = None self._loop = self._main_loop # Enables thread-safe reads/writes to shared data self._pending_item_changed: List = [] self._mutex_lock: threading.Lock = threading.Lock() self._drag_mime_data = None self._pending_drop_items: List = [] @property def show_udim_sequence(self): return self._show_udim_sequence @show_udim_sequence.setter def show_udim_sequence(self, value: bool): self._show_udim_sequence = value @property def root(self) -> FileBrowserItem: """:obj:`FileBrowserItem`: Gets/sets the root item of this model.""" return self._root @root.setter def root(self, item: FileBrowserItem): self._root = item self._item_changed(None) @property def sort_by_field(self) -> str: """:obj:`FileBrowserItem`: Gets/sets the sort-by field name.""" return self._sort_by_field @sort_by_field.setter def sort_by_field(self, field: str): self._sort_by_field = field @property def sort_ascending(self) -> bool: """:obj:`FileBrowserItem`: Gets/sets the sort ascending state.""" return self._sort_ascending @sort_ascending.setter def sort_ascending(self, value: bool): self._sort_ascending = value def set_filter_fn(self, filter_fn: Callable[[str], bool]): self._filter_fn = filter_fn def copy_presets(self, model: 'FileBrowserModel'): # By default, display these number of columns if self._drop_fn is None: self._drop_fn = model._drop_fn if self._filter_fn is None: self._filter_fn = model._filter_fn self._single_column = model._single_column self._sort_by_field = model._sort_by_field self._sort_ascending = model._sort_ascending def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]: """ Returns the list of items that are nested to the given parent item. Args: item (:obj:`FileBrowserItem`): Parent item. Returns: list[:obj:`FileBrowserItem`] """ # If item is 'None' them interpret as root node item_or_root = item or self._root if not item_or_root or not item_or_root.is_folder: return [] if item_or_root.children: children = list(item_or_root.children.values()) if item_or_root.enable_sorting and self._sort_by_field in FileBrowserItemFields._fields: # Skip root level but otherwise, sort by specified field def get_value(item: FileBrowserItem): value = getattr(item.fields, self._sort_by_field) return value.lower() if isinstance(value, str) else value children = sorted(children, key=get_value, reverse=not self._sort_ascending) # List folders before files children = [ item for item, is_folder in [(c, f) for f in [True, False] for c in children] if item.is_folder == is_folder ] if self._filter_fn: children = self.filter_items(children) else: children = [] if not item_or_root.populated: # If item not yet populated, then do it asynchronously. Force redraw when done. Note: When notifying # the TreeView with item_changed events, it's important to pass 'None' for the root node. item_or_root.populate_with_callback(lambda _: self._delayed_item_changed(item), timeout=self._timeout) return children def filter_items(self, items: List[FileBrowserItem]) -> List[FileBrowserItem]: results = [] for item in items: if item.is_folder == False: if (self._show_udim_sequence and item.is_udim_file) or \ (not self._show_udim_sequence and isinstance(item, FileBrowserUdimItem)): continue if self._filter_fn and self._filter_fn(item): results.append(item) return results def get_item_value_model_count(self, item: FileBrowserItem) -> int: """ Returns the number of columns this model item contains. Args: item (:obj:`FileBrowserItem`): The item in question. Returns: int """ if self._single_column: return 1 if item is None: return self.builtin_column_count + len(ColumnDelegateRegistry().get_column_delegate_names()) return len(item._models) def get_item_value_model(self, item: FileBrowserItem, index: int) -> object: """ Get the value model associated with this item. Args: item (:obj:`FileBrowserItem`): The item in question. Returns: :obj:`AbstractValueModel` """ if not item: item = self._root if item: return item.get_subitem_model(index) else: return None def auto_refresh_item(self, item: FileBrowserItem, throttle_frames: int = 4): """ Watches the given folder and updates the children list as soon as its contents are changed. Args: item (:obj:`FileBrowserItem`): The folder item to watch. throttle_frames: Number of frames to throttle the UI refresh. """ # If item is 'None' them interpret as root node item_or_root = item or self._root if not item_or_root or not item_or_root.is_folder: return self._list_change_subscription = omni.client.list_subscribe_with_callback( item_or_root.path, None, lambda result, event, entry: self.on_list_change_event(item_or_root, result, event, entry, throttle_frames=throttle_frames)) def sync_up_item_changes(self, item: FileBrowserItem): """ Scans given folder for missed changes; processes any changes found. Args: item (:obj:`FileBrowserItem`): The folder item to watch. """ item_or_root = item or self._root if not item_or_root or not item_or_root.is_folder: return async def sync_up_item_changes_async(item: FileBrowserItem): if not item.is_folder: return entries = [] try: include_deleted_option = omni.client.ListIncludeOption.INCLUDE_DELETED_FILES result, entries = await asyncio.wait_for(omni.client.list_async(item.path, include_deleted_option=include_deleted_option), timeout=self._timeout) except Exception as e: log_warn(f"Can't list directory '{item.path}': {str(e)}") return else: if result != omni.client.Result.OK: result = RuntimeWarning(f"Error listing directory '{item.path}': {result}") # Emit notification event event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream.push(CONNECTION_ERROR_EVENT, payload={"url": item.path, "exception": result}) return children = item.children for entry in entries: if entry.relative_path not in children: # Entry was added self.on_list_change_event(item, result, omni.client.ListEvent.CREATED, entry) entry_names = [entry.relative_path for entry in entries] for name in children: if name not in entry_names: if asset_types.is_udim_sequence(name): continue # Entry was deleted MockListEntry = namedtuple("MockListEntry", "relative_path") entry = MockListEntry(name) self.on_list_change_event(item, result, omni.client.ListEvent.DELETED, entry) asyncio.ensure_future(sync_up_item_changes_async(item_or_root)) def on_list_change_event(self, item: FileBrowserItem, result: omni.client.Result, event: omni.client.ListEvent, entry: omni.client.ListEntry, throttle_frames: int = 4): """ Processes change events for the given folder. Args: item (:obj:`FileBrowserItem`): The folder item. result (omni.client.Result): Set by omni.client upon listing the folder. event (omni.client.ListEvent): Event type. throttle_frames: Number of frames to throttle the UI refresh. """ if item and result == omni.client.Result.OK: item_changed = item.on_list_change_event(event, entry) # Limit item changed to these events (See OM-29866: Kit crashes during live sync due to auto refresh) if item_changed: # There may be many change events issued at once. To scale properly, we queue up the changes over a # few frames before triggering a single redraw of the UI. self._delayed_item_changed(item, throttle_frames=throttle_frames) def _delayed_item_changed(self, item: FileBrowserItem, throttle_frames: int = 1): """ Produces item changed event after skipping a beat. This is necessary for guaranteeing that async updates are properly recognized and generate their own redraws. Args: item (:obj:`FileBrowserItem`): The item in question. """ async def item_changed_async(item: FileBrowserItem, throttle_frames: int): with self._mutex_lock: if item in self._pending_item_changed: return else: self._pending_item_changed.append(item) # NOTE: Wait a few beats to absorb nearby change events so that we process the changes in one chunk. for _ in range(throttle_frames): await omni.kit.app.get_app().next_update_async() self._item_changed(item) with self._mutex_lock: try: self._pending_item_changed.remove(item) except Exception: pass if threading.current_thread() is threading.main_thread(): asyncio.ensure_future(item_changed_async(item, throttle_frames)) else: asyncio.run_coroutine_threadsafe(item_changed_async(item, throttle_frames), self._loop) @property def single_column(self): """The panel on the left side works in one-column mode""" return self._single_column @single_column.setter def single_column(self, value: bool): """Set the one-column mode""" self._single_column = not not value self._item_changed(None) @property def builtin_column_count(self): """Return the number of available columns without tag delegates""" return 3 @property def drag_mime_data(self): return self._drag_mime_data @drag_mime_data.setter def drag_mime_data(self, data: Union[str, List[str]]): if isinstance(data, List): self._drag_mime_data = "\n".join(data) else: self._drag_mime_data = data def get_drag_mime_data(self, item: FileBrowserItem): """Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere""" if self._drag_mime_data: return self._drag_mime_data return (item or self._root).path def drop_accepted(self, dst_item: FileBrowserItem, src_item: FileBrowserItem) -> bool: """ Reimplemented from AbstractItemModel. Called to highlight target when drag and drop. Returns True if destination item is able to accept a drop. This function can be overriden to implement a different behavior. Args: dst_item (:obj:`FileBrowserItem`): Target item. src_item (:obj:`FileBrowserItem`): Source item. Returns: bool """ if dst_item and dst_item.is_folder: # Returns True if item is a folder. return True return False def drop(self, dst_item: FileBrowserItem, source: Union[str, FileBrowserItem]): """ Invokes user-supplied function to handle dropping source onto destination item. Args: dst_item (:obj:`FileBrowserItem`): Target item. src_item (:obj:`FileBrowserItem`): Source item. """ if self._drop_fn and source: # OM-87075: Delay a frame and batch process source items, if the source arg passed in is a FileBrowserItem # FIXME: The reason for adding this delay is that, when the drop happens between within the same treeview # (eg. selected multiple items and drop to another item in the same tree view the the list view panel) # this ``drop`` is called once per selected item, this causes hang if in `_drop_fn` there's UI related # operation; Thus, here we have to cache pending items and delay a frame; # Ideally, ``omni.ui.TreeView`` might adjust the drop trigger to batch items instead of calling once per # selected item. if isinstance(source, FileBrowserItem): with self._mutex_lock: self._pending_drop_items.append(source) else: self._drop_fn(dst_item, source) return async def delay_drop(): await omni.kit.app.get_app().next_update_async() if self._pending_drop_items: self._drop_fn(dst_item, '\n'.join([item.path for item in self._pending_drop_items])) self._pending_drop_items = [] if threading.current_thread() is threading.main_thread(): asyncio.ensure_future(delay_drop()) else: asyncio.run_coroutine_threadsafe(delay_drop(), self._loop) def destroy(self): self._root = None self._drop_fn = None self._filter_fn = None self._list_change_subscription = None self._loop = None self._pending_item_changed: List = [] self._pending_drop_items.clear()
30,905
Python
36.968059
173
0.605824
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/thumbnails.py
__all__ = ["MissingThumbnailError", "find_thumbnails_for_files_async", "list_thumbnails_for_folder_async", "generate_missing_thumbnails_async"] import os import asyncio import omni.client import omni.kit.app from typing import List, Dict, Set from carb import log_warn from omni.kit.helper.file_utils import asset_types from . import MISSING_IMAGE_THUMBNAILS_EVENT # Module globals _thumbnails_dir: str = ".thumbs/256x256" _missing_thumbnails_cache: Set = set() class MissingThumbnailError(Exception): """ Raised when Moebius server error """ def __init__(self, msg: str = '', url: str = None): super().__init__(msg) self.url = url async def find_thumbnails_for_files_async(urls: List[str], generate_missing: bool = True) -> Dict: """ Returns a dictionary of thumbnails for the given files. Args: urls (List[str]): List of file Urls. generate_missing (bool): When True, emits a carb event for the missing thumbnails. Set to False to disable this behavior. Returns: Dict: Dict of all found thumbnails, with file Url as key, and thumbnail Url as value. """ tasks = [_find_thumbnail_async(url, auto=False) for url in urls if url] results = await asyncio.gather(*tasks, return_exceptions=True) thumbnail_dict = {} missing_thumbnails = [] for result in results: if isinstance(result, MissingThumbnailError): missing_thumbnails.append(result.url) else: url, thumbnail_url = result if url and thumbnail_url: thumbnail_dict[url] = thumbnail_url # Generate any missing thumbnails if missing_thumbnails and generate_missing: await generate_missing_thumbnails_async(missing_thumbnails) return thumbnail_dict async def _find_thumbnail_async(url: str, auto=False): if not url: return None broken_url = omni.client.break_url(url) if _thumbnails_dir in broken_url.path: return None parent_path = os.path.dirname(broken_url.path) filename = os.path.basename(broken_url.path) thumbnail_path = f"{parent_path.rstrip('/')}/{_thumbnails_dir}/{filename}" + (".auto.png" if auto else ".png") thumbnail_url = omni.client.make_url(scheme=broken_url.scheme, host=broken_url.host, port=broken_url.port, path=thumbnail_path) result = None try: result, stats = await omni.client.stat_async(thumbnail_url) except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e: result = omni.client.Result.ERROR_NOT_FOUND if result == omni.client.Result.OK: return (url, thumbnail_url) elif not auto: return await _find_thumbnail_async(url, auto=True) else: raise MissingThumbnailError(url=url) async def list_thumbnails_for_folder_async(url: str, timeout: float = 30.0, generate_missing: bool = True) -> Dict: """ Returns a dictionary of thumbnails for the files in the given folder. Args: url (str): Folder Url. generate_missing (bool): When True, emits a carb event for the missing thumbnails. Set to False to disable this behavior. Returns: Dict: Dict of all found thumbnails, with file Url as key, and thumbnail Url as value. """ thumbnail_dict = {} if not url or _thumbnails_dir in url: return {} url = url.rstrip('/') try: result, stats = await omni.client.stat_async(url) except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e: result = omni.client.Result.ERROR_NOT_FOUND else: if stats and result == omni.client.Result.OK: if not (stats.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN): # Not a folder return await find_thumbnails_for_files_async([url]) else: log_warn(f"Failed to stat url {url}") return {} # 1. List the given folder and populate keys of thumbnail_dict result, entries = None, {} try: result, entries = await asyncio.wait_for(omni.client.list_async(url), timeout=timeout) except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e: log_warn(f"Failed to list the folder at {url}: {str(e)}") return {} if result == omni.client.Result.OK: for entry in entries: thumbnail_dict[f"{url}/{entry.relative_path}"] = None # 2. List thumbnail folder and match up thumbnail Url's thumbnail_folder_url = f"{url}/{_thumbnails_dir}" result = entries = None, {} try: result, entries = await asyncio.wait_for(omni.client.list_async(thumbnail_folder_url), timeout=timeout) except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e: result = omni.client.Result.ERROR_NOT_FOUND if result == omni.client.Result.OK: for entry in entries: if entry.relative_path.endswith(".auto.png"): asset_name = entry.relative_path[:-len(".auto.png")] auto = True elif entry.relative_path.endswith(".png"): asset_name = entry.relative_path[:-len(".png")] auto = False else: continue asset_url = f"{url}/{asset_name}" if not auto or (auto and thumbnail_dict.get(asset_url) is None): # Take manual thumbnails over auto thumbnails thumbnail_dict[asset_url] = f"{thumbnail_folder_url}/{entry.relative_path}" # 3. Separate haves and have nots. Missing thumbnails have thumbnail Url == None missing_thumbnails = [k for k, v in thumbnail_dict.items() if v == None] thumbnail_dict = {k: v for k, v in thumbnail_dict.items() if v != None} # 4. Generate any missing thumbnails if missing_thumbnails and generate_missing: asyncio.ensure_future(generate_missing_thumbnails_async(missing_thumbnails)) return thumbnail_dict async def generate_missing_thumbnails_async(missing_thumbnails: List[str]): """ When missing thumbnails are discovered, send an event to have them generated. The generator service is a separate process. Once generated, a reciprocal event is sent to update the UI. The flow is diagramed below:: +-------------------------------+ +------------------------------+ | Filebrowser | | | | +-------------------------+ | Missing thumbnails | | | | | | event | | | | update_grid +---------------------------> Thumbnail generator | | | | | | service | | +-------------------------+ | | | | +-------------------------+ | Thumbnails | | | | | | generated event | | | | update_cards_on <---------------------------+ | | | thumbnails_generated | | | | | +-------------------------+ | | | | | | | +-------------------------------+ +------------------------------+ """ image_urls = [] for url in missing_thumbnails: if asset_types.is_asset_type(url, asset_types.ASSET_TYPE_IMAGE) and (url not in _missing_thumbnails_cache): # Check that this file is an image type and not already submitted image_urls.append(url) if image_urls: event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream.push(MISSING_IMAGE_THUMBNAILS_EVENT, payload={"urls": image_urls}) _missing_thumbnails_cache.update(set(image_urls))
8,168
Python
40.892307
143
0.557786
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/nucleus_model.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. # __all__ = ["NucleusItem", "NucleusItemFactory", "NucleusModel", "NucleusConnectionItem"] import asyncio from datetime import datetime from typing import Callable, Any import omni.client import omni.kit.app from omni import ui from .model import FileBrowserItem, FileBrowserItemFields, FileBrowserModel from .style import ICON_PATH from . import CONNECTION_ERROR_EVENT class NucleusItem(FileBrowserItem): def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = True, is_deleted: bool = False): super().__init__(path, fields, is_folder=is_folder, is_deleted=is_deleted) async def populate_async(self, callback_async: Callable = None, timeout: float = 10.0) -> Any: """ Populates current item asynchronously if not already. Overrides base method. Args: callback_async (Callable): Function signature is void callback(result, children: [FileBrowserItem]), where result is an Exception type upon error. timeout (float): Time out duration on failed server connections. Default 10.0. Returns: Any: Result of executing callback. """ result = omni.client.Result.OK if not self.populated: entries = [] try: result, entries = await asyncio.wait_for(omni.client.list_async(self.path), timeout=timeout) except asyncio.CancelledError: # NOTE: Return early if operation cancelled, without marking as 'populated'. return omni.client.Result.OK except (asyncio.TimeoutError, Exception) as e: result = omni.client.Result.ERROR finally: if result == omni.client.Result.OK: self.children.clear() else: result = RuntimeWarning(f"Error listing directory '{self.path}': {result}") # Emit connection error event event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream.push(CONNECTION_ERROR_EVENT, payload={"url": self.path, "exception": result}) for entry in entries: full_path = f"{self.path}/{entry.relative_path}" self.add_child(NucleusItemFactory.create_entry_item(entry, full_path)) # NOTE: Mark this item populated even when there's an error so we don't repeatedly try. self.populated = True if callback_async: try: return await callback_async(result, self.children) except asyncio.CancelledError: return omni.client.Result.OK else: return result def on_list_change_event(self, event: omni.client.ListEvent, entry: omni.client.ListEntry) -> bool: """ Handles ListEvent changes, should update this item's children list with the corresponding ListEntry. Args: event (:obj:`omni.client.ListEvent`): One of of {UNKNOWN, CREATED, UPDATED, DELETED, METADATA, LOCKED, UNLOCKED}. entry (:obj:`omni.client.ListEntry`): Updated entry as defined by omni.client. """ if not entry: return False item_changed = False child_name = entry.relative_path child_name = child_name[:-1] if child_name.endswith("/") else child_name full_path = f"{self.path}/{entry.relative_path}" if event == omni.client.ListEvent.CREATED: if not child_name in self.children: self.add_child(NucleusItemFactory.create_entry_item(entry, full_path)) else: item = self.children[child_name] if item.is_deleted: item.is_deleted = False item.item_changed = True item_changed = True elif event == omni.client.ListEvent.DELETED: if child_name in self.children: item = self.children[child_name] item.is_deleted = True item.item_changed = True item_changed = True elif event == omni.client.ListEvent.OBLITERATED: self.del_child(child_name) item_changed = True elif event == omni.client.ListEvent.UPDATED: child = self.children.get(child_name) if child: # Update file size size_model = child.get_subitem_model(2) size_model.set_value(FileBrowserItem.size_as_string(entry.size)) return item_changed @property def readable(self) -> bool: return (self._fields.permissions & omni.client.AccessFlags.READ) > 0 @property def writeable(self) -> bool: return (self._fields.permissions & omni.client.AccessFlags.WRITE) > 0 class NucleusConnectionItem(NucleusItem): """NucleusItem that represents a nucleus connection.""" def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = True): super().__init__(path, fields, is_folder=is_folder) self._signed_in = False @property def signed_in(self): return self._signed_in @signed_in.setter def signed_in(self, value): self._signed_in = value class NucleusItemFactory: @staticmethod def create_group_item(name: str, path: str) -> NucleusItem: if not name: return None access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE fields = FileBrowserItemFields(name, datetime.now(), 0, access) item = NucleusConnectionItem(path, fields) item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel("")) return item @staticmethod def create_entry_item(entry: omni.client.ListEntry, path: str) -> NucleusItem: if not entry: return None name = entry.relative_path.rstrip("/") modified_time = entry.modified_time fields = FileBrowserItemFields(name, modified_time, entry.size, entry.access) is_folder = (entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN) > 0 is_deleted = (entry.flags & omni.client.ItemFlags.IS_DELETED) > 0 item = NucleusItem(path, fields, is_folder=is_folder, is_deleted=is_deleted) size_model = ui.SimpleStringModel(FileBrowserItem.size_as_string(entry.size)) item._models = (ui.SimpleStringModel(item.name), modified_time, size_model) return item class NucleusModel(FileBrowserModel): """ A Filebrowser model class for navigating a Nucleus server in a tree view. Sub-classed from :obj:`FileBrowserModel`. Args: name (str): Name of root item.. root_path (str): Root path. If None, then create empty model. Example: "omniverse://ov-content". Keyword Args: drop_fn (Callable): Function called to handle drag-n-drops. Function signature: void drop_fn(dst_item: :obj:`FileBrowserItem`, src_item: :obj:`FileBrowserItem`) filter_fn (Callable): This handler should return True if the given tree view item is visible, False otherwise. Function signature: bool filter_fn(item: :obj:`FileBrowserItem`) sort_by_field (str): Name of column by which to sort items in the same folder. Default "name". sort_ascending (bool): Sort in ascending order. Default True. """ def __init__(self, name: str, root_path: str, **kwargs): import carb.settings super().__init__(**kwargs) if not root_path: return self._root = NucleusItemFactory.create_group_item(name, root_path) theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" self._root.icon = f"{ICON_PATH}/{theme}/hdd.svg"
8,244
Python
41.282051
125
0.634522
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/column_delegate_registry.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. # __all__ = ["ColumnDelegateRegistry"] from .singleton import Singleton import carb @Singleton class ColumnDelegateRegistry: """ Singleton that keeps all the column delegated. It's used to put custom columns to the content browser. """ class _Event(list): """ A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. """ def __call__(self, *args, **kwargs): """Called when the instance is “called” as a function""" # Call all the saved functions for f in self: f(*args, **kwargs) def __repr__(self): """ Called by the repr() built-in function to compute the “official” string representation of an object. """ return f"Event({list.__repr__(self)})" class _EventSubscription: """ Event subscription. _Event has callback while this object exists. """ def __init__(self, event, fn): """ Save the function, the event, and add the function to the event. """ self._fn = fn self._event = event event.append(self._fn) def __del__(self): """Called by GC.""" self._event.remove(self._fn) class _ColumnDelegateSubscription: """ Event subscription. _Event has callback while this object exists. """ def __init__(self, name, delegate): """ Save name and type to the list. """ self._name = name ColumnDelegateRegistry()._delegates[self._name] = delegate ColumnDelegateRegistry()._on_delegates_changed() def __del__(self): """Called by GC.""" del ColumnDelegateRegistry()._delegates[self._name] ColumnDelegateRegistry()._on_delegates_changed() def __init__(self): self._delegates = {} self._names = [] self._on_delegates_changed = self._Event() self.__delegate_changed_sub = self.subscribe_delegate_changed(self.__delegate_changed) def register_column_delegate(self, name, delegate): """ Add a new engine to the registry. name: the name of the engine as it appears in the menu. delegate: the type derived from AbstractColumnDelegate. Content browser will create an object of this type to build widgets for the custom column. """ if name in self._delegates: carb.log_warn("Unknown column delegate: {}".format(name)) return return self._ColumnDelegateSubscription(name, delegate) def get_column_delegate_names(self): """Returns all the column delegate names""" return self._names def get_column_delegate(self, name): """Returns the type of derived from AbstractColumnDelegate for the given name""" return self._delegates.get(name, None) def subscribe_delegate_changed(self, fn): """ Return the object that will automatically unsubscribe when destroyed. """ return self._EventSubscription(self._on_delegates_changed, fn) def __delegate_changed(self): self._names = list(sorted(self._delegates.keys()))
3,838
Python
32.094827
94
0.600834
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/clipboard.py
# Copyright (c) 2018-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. # from typing import List from .model import FileBrowserItem _clipboard_items: List = [] _is_clipboard_cut = False def save_items_to_clipboard(items: List[FileBrowserItem], is_cut: bool = False): global _clipboard_items _clipboard_items.clear() if isinstance(items, list): _clipboard_items = items elif isinstance(items, FileBrowserItem): _clipboard_items = [items] if _clipboard_items: global _is_clipboard_cut _is_clipboard_cut = is_cut def get_clipboard_items() -> List[FileBrowserItem]: return _clipboard_items def is_clipboard_cut() -> bool: return _is_clipboard_cut def is_path_cut(path: str) -> bool: if _is_clipboard_cut: return any(path == item.path for item in _clipboard_items) return False def clear_clipboard(): # used when cut items are pasted, we need to clear the clipboard and cut status. global _clipboard_items _clipboard_items.clear() global _is_clipboard_cut _is_clipboard_cut = False
1,446
Python
27.939999
84
0.716459
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/widget.py
# Copyright (c) 2018-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. # __all__ = ["FileBrowserWidget"] from queue import Empty import omni.kit.app import carb import omni.ui as ui from carb import log_error, log_warn from typing import Callable, List, Optional from functools import partial from . import LAYOUT_SINGLE_PANE_SLIM, LAYOUT_SINGLE_PANE_WIDE, LAYOUT_SPLIT_PANES, LAYOUT_DEFAULT, LAYOUT_SINGLE_PANE_LIST from . import TREEVIEW_PANE, LISTVIEW_PANE from . import ALERT_INFO, ALERT_WARNING, ALERT_ERROR from .model import FileBrowserModel, FileBrowserItem, FileBrowserItemFactory from .tree_view import FileBrowserTreeView from .grid_view import FileBrowserGridView from .zoom_bar import ZoomBar, SCALE_MAP from .date_format_menu import DATETIME_FORMAT_SETTING from .style import UI_STYLES, ICON_PATH from .clipboard import get_clipboard_items, is_clipboard_cut class FileBrowserWidget: """ The basic UI widget for navigating a filesystem as a tree view. The filesystem can either be from your local machine or the Omniverse server. Args: title (str): Widget title. Default None. Keyword Args: layout (int): The overall layout of the window, one of: {LAYOUT_SPLIT_PANES, LAYOUT_SINGLE_PANE_SLIM, LAYOUT_SINGLE_PANE_WIDE, LAYOUT_DEFAULT}. Default LAYOUT_SPLIT_PANES. splitter_offset (int): Position of vertical splitter bar. Default 300. tooltip (bool): Display tooltips when hovering over items. Default False. allow_multi_selection (bool): Allow multiple items to be selected at once. Default True. mouse_pressed_fn (Callable): Function called on mouse press. Function signature: void mouse_pressed_fn(pane: int, button: int, key_mode: int, item: :obj:`FileBrowserItem`) mouse_double_clicked_fn (Callable): Function called on mouse double click. Function signature: void mouse_double_clicked_fn(pane: int, button: int, key_mode: int, item: :obj:`FileBrowserItem`) selection_changed_fn (Callable): Function called when selection changed. Function signature: void selection_changed_fn(pane: int, selections: list[:obj:`FileBrowserItem`]) drop_fn (Callable): Function called to handle drag-n-drops. Function signature: void drop_fn(dst_item: :obj:`FileBrowserItem`, src_path: str) filter_fn (Callable): This user function should return True if the given tree view item is visible, False otherwise. Function signature: bool filter_fn(item: :obj:`FileBrowserItem`) show_grid_view (bool): If True, initializes the folder view to display icons. Default False. show_recycle_widget (bool): If True, show recycle view in the left bottom corner. Default False. grid_view_scale (int): Scales grid view, ranges from 0-5. Default 2. on_toggle_grid_view_fn (Callable): Callback after toggle grid view is executed. Default None. on_scale_grid_view_fn (Callable): Callback after scale grid view is executed. Default None. icon_provider (Callable): This callback provides an icon to replace the default one in the tree view. Signature: str icon_provider(item: :obj:`FileBrowserItem`, expanded: bool). thumbnail_provider (Callable): This callback returns the path to the item's thumbnail. If not specified, then a default thumbnail is used. Signature: str thumbnail_provider(item: :obj:`FileBrowserItem`). badges_provider (Callable): This callback provides the list of badges to layer atop the thumbnail in the grid view. Callback signature: [str] badges_provider(item: :obj:`FileBrowserItem`) treeview_identifier (str): widget identifier for treeview, only used by tests. enable_zoombar (bool): Enables/disables zoombar. Default True. """ def __init__(self, title: str, **kwargs): import carb.settings self._tree_view = None self._grid_view = None self._table_view = None self._zoom_bar = None self._theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" self._drop_fn = kwargs.get("drop_fn", None) self._filter_fn = kwargs.get("filter_fn", None) # Create model to group other models, used by the tree view self._models = FileBrowserModel(name=title, drop_fn=self._drop_fn, filter_fn=self._filter_fn) self._models.root.icon = f"{ICON_PATH}/{self._theme}/cloud.svg" # Create the model for the list view self._listview_model = FileBrowserModel(drop_fn=self._drop_fn, filter_fn=self._filter_fn) # OM-70157: Added this selections for listview here, because we cannot aggregate and re-apply selection from # grid view/list view if the switch grid view scale and toggle happened within one frame (i.e. if the user # is dragging the zoombar from one end to another within one frame), because the grid view items are built # one frame delay, the selection will be lost from the scale and switch; thus this is recorded at a higher # level on this widget, as a source of truth for selections for both list view and grid view; self._listview_selections = [] self._currently_visible_model = None self._style = UI_STYLES[self._theme] self._layout = kwargs.get("layout", LAYOUT_DEFAULT) self._splitter_offset = kwargs.get("splitter_offset", 300) self._tooltip = kwargs.get("tooltip", False) self._tree_root_visible = kwargs.get("tree_root_visible", True) self._allow_multi_selection = kwargs.get("allow_multi_selection", True) self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None) self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None) self._selection_changed_fn = kwargs.get("selection_changed_fn", None) self._show_grid_view = kwargs.get("show_grid_view", False) self._grid_view_scale = kwargs.get("grid_view_scale", 2) # OM-66270: Add callback to record show grid view settings in between sessions self._on_toggle_grid_view_fn = kwargs.get("on_toggle_grid_view_fn", None) self._on_scale_grid_view_fn = kwargs.get("on_scale_grid_view_fn", None) self._icon_provider = kwargs.get("icon_provider", None) self._thumbnail_provider = kwargs.get("thumbnail_provider", None) self._badges_provider = kwargs.get("badges_provider", None) self._treeview_identifier = kwargs.get('treeview_identifier', None) self._enable_zoombar = kwargs.get("enable_zoombar", True) self._datetime_format_updated_subscription = None self._build_ui() @property def show_udim_sequence(self): return self._listview_model.show_udim_sequence @show_udim_sequence.setter def show_udim_sequence(self, value: bool): self._listview_model.show_udim_sequence = value def _build_ui(self): if self._layout in [LAYOUT_SPLIT_PANES, LAYOUT_SINGLE_PANE_LIST, LAYOUT_DEFAULT]: self._tree_view = self._build_split_panes_view() else: slim_view = self._layout == LAYOUT_SINGLE_PANE_SLIM self._tree_view = self._build_tree_view( self._models, slim_view=slim_view, selection_changed_fn=partial(self._on_selection_changed, TREEVIEW_PANE), ) def on_datetime_format_changed(_: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: self.refresh_ui(listview_only=True) self._datetime_format_updated_subscription = omni.kit.app.SettingChangeSubscription( DATETIME_FORMAT_SETTING, on_datetime_format_changed) def _build_split_panes_view(self) -> FileBrowserTreeView: show_grid_view = self._show_grid_view use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False if use_default_style: self._style = {} with ui.HStack(style=self._style): with ui.ZStack(width=0, visible=self._layout != LAYOUT_SINGLE_PANE_LIST): # Create navigation view as side pane self._models.single_column = True with ui.HStack(): with ui.VStack(): tree_view = self._build_tree_view( self._models, header_visible=False, files_visible=False, slim_view=True, selection_changed_fn=partial(self._on_selection_changed, TREEVIEW_PANE), ) ui.Spacer(width=2) with ui.Placer(offset_x=self._splitter_offset, draggable=True, drag_axis=ui.Axis.X): ui.Rectangle(width=4, style_type_name_override="Splitter") with ui.ZStack(): self._grid_view = self._build_grid_view(self._listview_model) self._table_view = self._build_table_view(self._listview_model) if self._enable_zoombar: with ui.VStack(): ui.Spacer() self._zoom_bar = ZoomBar( show_grid_view=self._show_grid_view, grid_view_scale=self._grid_view_scale, on_toggle_grid_view_fn=self.toggle_grid_view, on_scale_grid_view_fn=self.scale_grid_view ) ui.Spacer(height=2) # OM-49484: Add a notification frame to list view stack, that could be used for showing notification self._notification_frame = ui.Frame() self.toggle_grid_view(show_grid_view) return tree_view def _build_tree_view( self, model: FileBrowserModel, header_visible: bool = True, files_visible: bool = True, slim_view: bool = True, selection_changed_fn: Callable = None, ) -> FileBrowserTreeView: if slim_view: model._single_column = True with ui.ZStack(style=self._style): ui.Rectangle(style_type_name_override="TreeView") view = FileBrowserTreeView( model, header_visible=header_visible, files_visible=files_visible, tooltip=self._tooltip, root_visible=self._tree_root_visible, allow_multi_selection=self._allow_multi_selection, mouse_pressed_fn=partial(self._on_mouse_pressed, TREEVIEW_PANE), mouse_double_clicked_fn=partial(self._on_mouse_double_clicked, TREEVIEW_PANE), selection_changed_fn=selection_changed_fn, icon_provider=self._icon_provider, treeview_identifier=f"{self._treeview_identifier}_folder_view", ) view.build_ui() return view def _build_table_view(self, model: FileBrowserModel) -> FileBrowserTreeView: # Create detail view as table view view = FileBrowserTreeView( model, root_visible=False, tooltip=self._tooltip, allow_multi_selection=self._allow_multi_selection, mouse_pressed_fn=partial(self._on_mouse_pressed, LISTVIEW_PANE), mouse_double_clicked_fn=partial(self._on_mouse_double_clicked, LISTVIEW_PANE), selection_changed_fn=partial(self._on_selection_changed, LISTVIEW_PANE), icon_provider=self._icon_provider, treeview_identifier=self._treeview_identifier, ) view.build_ui() return view def _build_grid_view(self, model: FileBrowserModel) -> FileBrowserGridView: # Create detail view as table view view = FileBrowserGridView( model, root_visible=False, tooltip=self._tooltip, allow_multi_selection=self._allow_multi_selection, mouse_pressed_fn=partial(self._on_mouse_pressed, LISTVIEW_PANE), mouse_double_clicked_fn=partial(self._on_mouse_double_clicked, LISTVIEW_PANE), selection_changed_fn=partial(self._on_selection_changed, LISTVIEW_PANE), drop_fn=self._drop_fn, thumbnail_provider=self._thumbnail_provider, badges_provider=self._badges_provider, treeview_identifier=f"{self._treeview_identifier}_grid_view", ) view.build_ui() return view def _on_mouse_pressed(self, pane: int, button: int, key_mod: int, item: FileBrowserItem, x: float = 0, y: float = 0): if self._mouse_pressed_fn: self._mouse_pressed_fn(pane, button, key_mod, item, x=x, y=y) def _on_mouse_double_clicked(self, pane: int, button: int, key_mod: int, item: FileBrowserItem, x: float = 0, y: float = 0): if self._mouse_double_clicked_fn: self._mouse_double_clicked_fn(pane, button, key_mod, item, x=x, y=y) if item and item.is_folder: self._tree_view.select_and_center(item) def _on_selection_changed(self, pane: int, selected: List[FileBrowserItem]): if self._selection_changed_fn: self._selection_changed_fn(pane, selected) if pane == TREEVIEW_PANE and selected: item = selected[-1] if item.populated: # If entering an already populated folder, sync up to any folder changes that may # have been missed. self._models.sync_up_item_changes(item) # Refresh the folder in the list view self._listview_model.root = item self.show_model(self._listview_model) # Clear out list view selections self._listview_selections = [] # Finally, set folder to auto-refresh self._auto_refresh_folder(item) if pane == LISTVIEW_PANE: # update list view selection on list view model self._listview_selections = selected def _auto_refresh_folder(self, item: FileBrowserItem): if item: self._models.auto_refresh_item(item) self._models.add_item_changed_fn(lambda model, item: self.refresh_ui(item, listview_only=True)) def get_root(self, pane: int = None) -> FileBrowserItem: if not pane: return self._models.root elif pane == TREEVIEW_PANE: return self._tree_view.model.root elif pane == LISTVIEW_PANE: return self._listview_model.root return None def toggle_grid_view(self, show_grid_view: bool): current_selections = self.get_selections(pane=LISTVIEW_PANE) if not (self._grid_view and self._table_view): return if show_grid_view: self._grid_view.visible = True self._table_view.visible = False else: self._grid_view.visible = False self._table_view.visible = True # OM-70157: maintain current selection when toggling between grid view and list view self.set_selections(current_selections, pane=LISTVIEW_PANE) # OM-86768: refresh UI if cut clipboard is not empty to maintain the cut style if is_clipboard_cut() and get_clipboard_items(): self.refresh_ui(listview_only=True) self._show_grid_view = show_grid_view # OM-66270: Record show grid view settings in between sessions if self._on_toggle_grid_view_fn: self._on_toggle_grid_view_fn(show_grid_view) def hide_notification(self): self._notification_frame.visible = False self._grid_view.visible = self.show_grid_view self._table_view.visible = not self.show_grid_view def show_notification(self): self._notification_frame.visible = True self._grid_view.visible = False self._table_view.visible = False @property def show_grid_view(self): return self._show_grid_view def scale_grid_view(self, scale: float): if not self._grid_view: return if scale < 0.5: self.toggle_grid_view(False) else: self.toggle_grid_view(True) self._grid_view.scale_view(scale) self._grid_view.build_ui(restore_selections=self._listview_selections) # OM-66270: Record grid view scale settings in between sessions if self._on_scale_grid_view_fn: scale_level = None # infer scale level from SCALE_MAP if scale in SCALE_MAP.values(): scale_level = list(SCALE_MAP.keys())[list(SCALE_MAP.values()).index(scale)] self._on_scale_grid_view_fn(scale_level) def create_grouping_item(self, name: str, path: str, parent: FileBrowserItem = None) -> FileBrowserItem: child = FileBrowserItemFactory.create_group_item(name, path) if child: item = parent or self._models.root item.add_child(child) self._models._item_changed(parent) return child def add_model_as_subtree(self, model: FileBrowserModel, parent: FileBrowserItem = None): if model: parent = parent or self._models.root parent.add_child(model.root) # TODO: Remove it self.refresh_ui() def delete_child_by_name(self, item_name: str, parent: FileBrowserItem = None): if item_name: parent = parent or self._models.root parent.del_child(item_name) # TODO: Remove it self.refresh_ui() def delete_child(self, item: FileBrowserItem, parent: FileBrowserItem = None): if item: self.delete_child_by_name(item.name, parent) def link_views(self, src_widget: object): """ Links this widget to the given widget, i.e. the 2 widgets will therafter display the same models but not necessarily share the same view. Args: src_widget (:obj:`FilePickerWidget`): The source widget. """ if self._tree_view and src_widget._tree_view: src_model = src_widget._tree_view.model if src_model: self._tree_view.set_root(src_model.root) def set_item_alert(self, item: FileBrowserItem, alert_level: int, msg: str): if item: item.alert = (alert_level, msg) self.refresh_ui(item) def set_item_info(self, item: FileBrowserItem, msg: str): self.set_item_alert(item, ALERT_INFO, msg) def set_item_warning(self, item: FileBrowserItem, msg: str): self.set_item_alert(item, ALERT_WARNING, msg) def set_item_error(self, item: FileBrowserItem, msg: str): self.set_item_alert(item, ALERT_ERROR, msg) def clear_item_alert(self, item: FileBrowserItem): if item: item.alert = None self.refresh_ui(item) def refresh_ui(self, item: FileBrowserItem = None, listview_only: bool = False): """ Redraws the subtree rooted at the given item. If item is None, then redraws entire tree. Args: item (:obj:`FileBrowserItem`): Root of subtree to redraw. Default None, i.e. root. """ if not listview_only: if self._tree_view: self._tree_view.refresh_ui(item) if self._grid_view: self._grid_view.refresh_ui(item) if self._table_view: self._table_view.refresh_ui() def set_selections(self, selections: [FileBrowserItem], pane: int = TREEVIEW_PANE): """ Selected given items in given pane. ARGS: selections (list[:obj:`FileBrowserItem`]): list of selections. pane (int): One of TREEVIEW_PANE, LISTVIEW_PANE, or None for both. Default None. """ if not pane or pane == TREEVIEW_PANE: if selections: self._tree_view.tree_view.selection = selections else: # Note: OM-23294 - Segfaults when selections cleared # self._tree_view.tree_view.clear_selection() pass if not pane or pane == LISTVIEW_PANE: if selections: self._table_view.tree_view.selection = selections else: # Note: OM-23294 - Segfaults when selections cleared self._table_view.tree_view.clear_selection() pass if self._grid_view: self._grid_view.selections = selections self._listview_selections = selections def get_selected_item(self, pane: int = TREEVIEW_PANE) -> FileBrowserItem: """ Returns last of selected item from the specified pane. ARGS: pane (int): One of TREEVIEW_PANE, LISTVIEW_PANE. Returns the union if None is specified. Returns: `FileBrowserItem` or None """ selections = self.get_selections(pane) return selections[-1] if len(selections) > 0 else None def get_selections(self, pane: int = TREEVIEW_PANE) -> [FileBrowserItem]: """ Returns list of selected items from the specified pane. ARGS: pane (int): One of TREEVIEW_PANE, LISTVIEW_PANE. Returns the union if None is specified. Returns: list[:obj:`FileBrowserItem`] """ if not pane or pane == TREEVIEW_PANE: selections = self._tree_view.selections else: selections = [] if not pane or pane == LISTVIEW_PANE: selections.extend(self._listview_selections) # Ensure selections are unique return list(set(selections)) def select_and_center(self, selection: FileBrowserItem, pane: int = TREEVIEW_PANE): """ Selects and centers the tree view on the given item, expanding the tree if needed. Args: selection (:obj:`FileBrowserItem`): The selected item. pane (int): One of TREEVIEW_PANE, LISTVIEW_PANE. """ if not pane or pane == TREEVIEW_PANE: self._tree_view.select_and_center(selection) if self._grid_view: self._grid_view.scroll_top() if self._table_view: self._table_view.scroll_top() # clear out listview model selections when selecting treeview items self._listview_selections = [] if not pane or pane == LISTVIEW_PANE: if self._grid_view.visible: self._grid_view.select_and_center(selection) if self._table_view.visible: self._table_view.select_and_center(selection) self._listview_selections = [selection] def set_expanded(self, item: FileBrowserItem, expanded: bool, recursive: bool = False): """ Sets the expansion state of the given item. Args: item (:obj:`FileBrowserItem`): The item to effect. expanded (bool): True to expand, False to collapse. recursive (bool): Apply state recursively to descendent nodes. Default False. """ if self._tree_view: self._tree_view.set_expanded(item, expanded, recursive) def show_model(self, model: FileBrowserModel): if model: new_model = model new_model.copy_presets(self._listview_model) else: new_model = self._listview_model if new_model != self._currently_visible_model: # Hack to remove model to avoid memory leaks # TODO: Find out how to create a model with no circular dependencies if self._currently_visible_model and self._currently_visible_model != self._listview_model: self._currently_visible_model.destroy() self._currently_visible_model = new_model if self._grid_view: self._grid_view.model = self._currently_visible_model if self._table_view: self._table_view.model = self._currently_visible_model def destroy(self): """ Destructor. Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ if self._tree_view: self._tree_view.destroy() self._tree_view = None if self._grid_view: self._grid_view.destroy() self._grid_view = None if self._table_view: self._table_view.destroy() self._table_view = None if self._listview_model: self._listview_model.destroy() self._listview_model = None self._listview_selections.clear() if self._notification_frame: self._notification_frame = None if self._zoom_bar: self._zoom_bar.destroy() self._zoom_bar = None if self._models: self._models.destroy() self._models = None self._currently_visible_model = None self._style = None self._drop_fn = None self._filter_fn = None self._mouse_pressed_fn = None self._mouse_double_clicked_fn = None self._selection_changed_fn = None self._icon_provider = None self._thumbnail_provider = None self._badges_provider = None self._datetime_format_updated_subscription = None
25,916
Python
43.8391
128
0.617919
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/abstract_column_delegate.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. # __all__ = ["ColumnItem", "AbstractColumnDelegate"] import omni.ui as ui import abc class ColumnItem: """ It's not clear which data we need to pass to build_widget. It's path, but there are potentially other interesting information the column has. To keep API unchanged over the time, we pass data in a struct. It also allow to pass custom data with deriving from this class. """ def __init__(self, path): self._path = path @property def path(self): return self._path class AbstractColumnDelegate(metaclass=abc.ABCMeta): """ An abstract object that is used to put the widget to the file browser asynchronously. """ @property def initial_width(self): """The width of the column""" return ui.Fraction(1) def build_header(self): """Build the header""" pass @abc.abstractmethod async def build_widget(self, item: ColumnItem): """ Build the widget for the given path. Works inside Frame in async mode. Once the widget is created, it will replace the content of the frame. It allow to await something for a while and create the widget when the result is available. """ pass
1,686
Python
29.672727
77
0.685647
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/test_zoom_bar.py
## Copyright (c) 2018-2019, 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.app from unittest.mock import patch from ..widget import FileBrowserWidget from ..grid_view import FileBrowserGridViewDelegate class TestZoomBar(omni.kit.test.AsyncTestCase): """Testing FileBrowserGridViewDelegate.update_grid""" async def setUp(self): self._throttle_frames = 2 async def tearDown(self): pass async def _after_redraw_async(self): for _ in range(self._throttle_frames + 1): await omni.kit.app.get_app().next_update_async() async def test_zoom_switches_to_table_view(self): """Testing FileBrowserWidget.scale_grid_view changes to treeview for small scale factors""" under_test = FileBrowserWidget("test", show_grid_view=True) self.assertFalse(under_test._table_view.visible) self.assertTrue(under_test._grid_view.visible) under_test.scale_grid_view(0.25) self.assertTrue(under_test._table_view.visible) self.assertFalse(under_test._grid_view.visible) under_test.scale_grid_view(0.5) self.assertFalse(under_test._table_view.visible) self.assertTrue(under_test._grid_view.visible) under_test.scale_grid_view(2.0) self.assertFalse(under_test._table_view.visible) self.assertTrue(under_test._grid_view.visible) under_test.destroy() under_test = None async def test_zoom_rebuilds_grid_view(self): """Testing FileBrowserWidget.scale_grid_view re-builds the grid view""" with patch.object(FileBrowserGridViewDelegate, "build_grid") as mock_build_grid,\ patch.object(FileBrowserGridViewDelegate, "update_grid") as mock_update_grid: test_scale = 1.75 under_test = FileBrowserWidget("test", show_grid_view=True) mock_build_grid.reset_mock() mock_update_grid.reset_mock() under_test.scale_grid_view(test_scale) await self._after_redraw_async() self.assertEqual(under_test._grid_view._delegate.scale, test_scale) mock_build_grid.assert_called_once() mock_update_grid.assert_called_once()
2,599
Python
38.393939
99
0.689496
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/test_thumbnails.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import os import asyncio import omni.kit.test import omni.kit.app import omni.client import omni.ui as ui from unittest.mock import patch, Mock from typing import List, Dict from functools import partial from ..grid_view import FileBrowserGridViewDelegate from ..card import FileBrowserItemCard from ..model import FileBrowserModel, FileBrowserItem, FileBrowserItemFactory from ..thumbnails import find_thumbnails_for_files_async, list_thumbnails_for_folder_async from .. import MISSING_IMAGE_THUMBNAILS_EVENT, THUMBNAILS_GENERATED_EVENT from . import AsyncMock class TestRefreshThumbnails(omni.kit.test.AsyncTestCase): """Testing FileBrowserGridViewDelegate rendering thumbnails""" async def setUp(self): self.test_dir = "omniverse://ov-test" self.test_thumbnail_dict = { f"{self.test_dir}/foo.tif": f"{self.test_dir}/.thumbs/foo.tif.png", f"{self.test_dir}/bar.png": f"{self.test_dir}/.thumbs/bar.png.png", } async def tearDown(self): pass def _build_test_model(self, paths: List[str]) -> FileBrowserModel: model = FileBrowserModel("ov-test", self.test_dir) for path in paths: model.root.add_child( FileBrowserItemFactory.create_dummy_item(os.path.basename(path), path)) return model async def _mock_get_folder_thumbnails_impl(self) -> Dict: return self.test_thumbnail_dict async def _mock_get_folder_thumbnails_empty(self) -> Dict: return {} async def _mock_find_thumbnails_impl(self, paths: str, generate_missing: bool = False) -> Dict: return {path: self.test_thumbnail_dict.get(path) for path in paths} async def test_update_grid_succeeds(self): """Testing FileBrowserGridViewDelegate.update_grid successfully renders custom thumbnails""" with patch.object(FileBrowserItem, "get_custom_thumbnails_for_folder_async", side_effect=self._mock_get_folder_thumbnails_impl),\ patch.object(FileBrowserItemCard, "refresh_thumbnail_async", new_callable=AsyncMock) as mock_refresh_thumbnail: paths = list(self.test_thumbnail_dict) model = self._build_test_model(paths) under_test = FileBrowserGridViewDelegate(ui.Frame(), "NvidiaDark", testing=True) under_test.build_grid(model) under_test.update_grid(model) await omni.kit.app.get_app().next_update_async() # Confirm that cards with existing thumbnails redraw themselves self.assertEqual(mock_refresh_thumbnail.call_count, len(paths)) async def test_thumbnails_not_found(self): """Testing FileBrowserGridViewDelegate.update_grid correctly handles no thumbnails""" with patch.object(FileBrowserItem, "get_custom_thumbnails_for_folder_async", side_effect=self._mock_get_folder_thumbnails_empty),\ patch.object(FileBrowserItemCard, "refresh_thumbnail_async", new_callable=AsyncMock) as mock_refresh_thumbnail: paths = list(self.test_thumbnail_dict) model = self._build_test_model(paths) under_test = FileBrowserGridViewDelegate(ui.Frame(), "NvidiaDark", testing=True) under_test.build_grid(model) under_test.update_grid(model) await omni.kit.app.get_app().next_update_async() # Confirm that no matching thumbnails were found mock_refresh_thumbnail.assert_not_called() async def test_update_cards_on_thumbnails_generated(self): """Testing FileBrowserGridViewDelegate.update_cards_on_thumbnails_generated correctly handles new thumbnails""" with patch.object(FileBrowserItem, "get_custom_thumbnails_for_folder_async", side_effect=self._mock_get_folder_thumbnails_empty),\ patch.object(FileBrowserItemCard, "refresh_thumbnail_async", new_callable=AsyncMock) as mock_refresh_thumbnail,\ patch("omni.kit.widget.filebrowser.grid_view.find_thumbnails_for_files_async", side_effect=self._mock_find_thumbnails_impl): paths = list(self.test_thumbnail_dict) model = self._build_test_model(paths) under_test = FileBrowserGridViewDelegate(ui.Frame(), "NvidiaDark", testing=True) under_test.build_grid(model) under_test.update_grid(model) await omni.kit.app.get_app().next_update_async() # Listen for connection error events event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream.push(THUMBNAILS_GENERATED_EVENT, payload={'paths': [paths[0]]}) for _ in range(2): await omni.kit.app.get_app().next_update_async() mock_refresh_thumbnail.assert_called_with(self.test_thumbnail_dict.get(paths[0])) event_stream.push(THUMBNAILS_GENERATED_EVENT, payload={'paths': [paths[1]]}) for _ in range(2): await omni.kit.app.get_app().next_update_async() mock_refresh_thumbnail.assert_called_with(self.test_thumbnail_dict.get(paths[1])) class TestFindThumbnailsForFiles(omni.kit.test.AsyncTestCase): """Testing find_thumbnails_for_files_async api func""" async def setUp(self): pass async def tearDown(self): pass async def test_find_thumbnails_succeeds(self): """Testing find_thumbnails_for_files_async returns expected thumbnails in dict""" async def mock_stat_async_impl(path: str): return omni.client.Result.OK, None with patch("omni.client.stat_async", side_effect=mock_stat_async_impl): test_urls = ["omniverse://ov-foo/foo.usd", "omniverse://ov-bar/bar.usd", "omniverse://ov-baz/baz.usd" ] results = await find_thumbnails_for_files_async(test_urls) # Confirm thumbnail files found self.assertEqual(len(test_urls), len(results)) for url, thumbnail_url in results.items(): parent_dir = os.path.dirname(url) filename = os.path.basename(url) expected = f"{parent_dir}/.thumbs/256x256/{filename}.png" self.assertEqual(thumbnail_url, expected) async def test_find_thumbnails_returns_auto_files(self): """Testing find_thumbnails_for_files_async returns auto thumbnails when those are available""" async def mock_stat_async_auto(path: str): return (omni.client.Result.OK, None) if ".auto." in path else (omni.client.Result.ERROR_NOT_FOUND, None) with patch("omni.client.stat_async", side_effect=mock_stat_async_auto): test_urls = ["omniverse://ov-foo/foo.usd", "omniverse://ov-bar/bar.usd", "omniverse://ov-baz/baz.usd" ] results = await find_thumbnails_for_files_async(test_urls) # Confirm thumbnail files found self.assertEqual(len(test_urls), len(results)) for url, thumbnail_url in results.items(): parent_dir = os.path.dirname(url) filename = os.path.basename(url) expected = f"{parent_dir}/.thumbs/256x256/{filename}.auto.png" self.assertEqual(thumbnail_url, expected) async def test_find_thumbnails_generates_missing_when_not_found(self): """Testing find_thumbnails_for_files_async submits missing thumbnails for generation""" async def mock_stat_async_not_found(path: str): return omni.client.Result.ERROR_NOT_FOUND, None with patch("omni.client.stat_async", side_effect=mock_stat_async_not_found): test_image_urls = ["omniverse://ov-foo/foo.png", "omniverse://ov-baz/baz.jpg"] test_urls = test_image_urls + ["omniverse://ov-bar/bar.usd"] mock_sub_callback = Mock() event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream_sub = event_stream.create_subscription_to_pop_by_type(MISSING_IMAGE_THUMBNAILS_EVENT, mock_sub_callback) results = await find_thumbnails_for_files_async(test_urls) # Check that subscription callback was triggered, and that only image files are submitted for # thumbnail generation. self.assertEqual(len(results), 0) await omni.kit.app.get_app().next_update_async() mock_sub_callback.assert_called_once() event = mock_sub_callback.call_args[0][0] self.assertTrue(event.payload.get_dict() == {'urls': tuple(test_image_urls)}) # Call again with additional inputs test_more_image_urls = ["omniverse://ov-cow/cow.tif"] test_urls += test_more_image_urls mock_sub_callback.reset_mock() results = await find_thumbnails_for_files_async(test_urls) # This time, assert that only the new files are submitted for thumbnail generation. I.e. we don't # want the same files to be submitted more than once. self.assertEqual(len(results), 0) await omni.kit.app.get_app().next_update_async() mock_sub_callback.assert_called_once() event = mock_sub_callback.call_args[0][0] self.assertTrue(event.payload.get_dict() == {'urls': tuple(test_more_image_urls)}) class TestListThumbnailsForFolder(omni.kit.test.AsyncTestCase): """Testing list_thumbnails_for_folder_async api func""" async def setUp(self): self.test_folder = "omniverse://ov-test/folder" self.test_files = ["foo.usd", "bar.jpg", "baz.png" ] self.test_urls = [f"{self.test_folder}/{f}" for f in self.test_files] self.test_thumbnails = [f"{self.test_folder}/.thumbs/256x256/{f}.png" for f in self.test_files] self.test_auto_thumbnails = [f"{self.test_folder}/.thumbs/256x256/{f}.auto.png" for f in self.test_files] async def tearDown(self): pass class MockStats: def __init__(self, is_folder: bool = False): self.flags = 0 if is_folder: self.flags |= omni.client.ItemFlags.CAN_HAVE_CHILDREN class MockListEntry: def __init__(self, url: str): self.relative_path = os.path.basename(url) async def _mock_stat_async_impl(self, url: str): if os.path.basename(url) == "folder": return omni.client.Result.OK, self.MockStats(is_folder=True) return omni.client.Result.OK, self.MockStats(is_folder=False) async def _mock_list_async_impl(self, url: str): if url.endswith(".thumbs/256x256"): return omni.client.Result.OK, [self.MockListEntry(url) for url in self.test_thumbnails] else: return omni.client.Result.OK, [self.MockListEntry(url) for url in self.test_urls] async def _mock_list_async_impl_auto(self, url: str): if url.endswith(".thumbs/256x256"): return omni.client.Result.OK, [self.MockListEntry(url) for url in self.test_auto_thumbnails] else: return omni.client.Result.OK, [self.MockListEntry(url) for url in self.test_urls] async def _mock_list_async_timeout(self, url: str): raise asyncio.TimeoutError async def test_list_thumbnails_succeeds(self): """Testing list_thumbnails_for_folder_async returns expected thumbnails in dict""" with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.list_async", side_effect=self._mock_list_async_impl): results = await list_thumbnails_for_folder_async(self.test_folder) # Confirm thumbnail files found self.assertEqual(len(self.test_urls), len(results)) for url, thumbnail_url in results.items(): parent_dir = os.path.dirname(url) filename = os.path.basename(url) expected = f"{parent_dir}/.thumbs/256x256/{filename}.png" self.assertEqual(thumbnail_url, expected) async def test_list_thumbnails_auto(self): """Testing list_thumbnails_for_folder_async returns auto thumbnails in dict""" with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.list_async", side_effect=self._mock_list_async_impl_auto): results = await list_thumbnails_for_folder_async(self.test_folder) # Confirm auto thumbnail files found self.assertEqual(len(self.test_urls), len(results)) for url, thumbnail_url in results.items(): parent_dir = os.path.dirname(url) filename = os.path.basename(url) expected = f"{parent_dir}/.thumbs/256x256/{filename}.auto.png" self.assertEqual(thumbnail_url, expected) async def test_list_thumbnails_auto_precedence(self): """Testing that when list_thumbnails_for_folder_async returns multiple thumbnails, the non-auto one takes precedence""" test_file = "foo.usd" test_url = f"{self.test_folder}/{test_file}" async def mock_list_async_impl(url: str): if url.endswith(".thumbs/256x256"): thumbnail_folder = f"{self.test_folder}/.thumbs/256x256" # Return both auto and non-auto thumbnails return omni.client.Result.OK, [self.MockListEntry(f"{thumbnail_folder}/{test_file}.auto.png"), self.MockListEntry(f"{thumbnail_folder}/{test_file}.png")] else: return omni.client.Result.OK, [self.MockListEntry(test_url)] with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.list_async", side_effect=mock_list_async_impl): results = await list_thumbnails_for_folder_async(self.test_folder) # Confirm non-auto thumbnail precedes auto thumbnail expected = f"{self.test_folder}/.thumbs/256x256/{test_file}.png" self.assertEqual(results.get(test_url), expected) async def test_get_thumbnails_timeout(self): """Testing list_thumbnails_for_folder_async times out""" with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.list_async", side_effect=self._mock_list_async_timeout): results = await list_thumbnails_for_folder_async(self.test_folder) self.assertEqual(results, {}) async def test_get_thumbnails_generates_missing_when_not_found(self): """Testing list_thumbnails_for_folder_async submits missing thumbnails for generation""" test_image_files = ["bar.jpg", "baz.png" ] test_image_urls = [f"{self.test_folder}/{f}" for f in test_image_files] test_urls = test_image_urls + [f"{self.test_folder}/foo.usd"] async def mock_list_async_impl(url: str): if url.endswith(".thumbs/256x256"): # Thumbnails not found return omni.client.Result.OK, [] else: return omni.client.Result.OK, [self.MockListEntry(url) for url in test_urls] with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.list_async", side_effect=mock_list_async_impl): mock_sub_callback = Mock() event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream_sub = event_stream.create_subscription_to_pop_by_type(MISSING_IMAGE_THUMBNAILS_EVENT, mock_sub_callback) results = await list_thumbnails_for_folder_async(self.test_folder) # Check that subscription callback was triggered, and that only image files are submitted for # thumbnail generation. self.assertEqual(len(results), 0) await omni.kit.app.get_app().next_update_async() mock_sub_callback.assert_called_once() event = mock_sub_callback.call_args[0][0] self.assertEqual(event.payload.get_dict(), {'urls': tuple(test_image_urls)}) # Call again with additional inputs test_more_image_urls = [f"{self.test_folder}/cow.tif"] test_urls += test_more_image_urls mock_sub_callback.reset_mock() results = await list_thumbnails_for_folder_async(self.test_folder) # This time, assert that only the new files are submitted for thumbnail generation. I.e. we don't # want the same files to be submitted more than once. self.assertEqual(len(results), 0) await omni.kit.app.get_app().next_update_async() mock_sub_callback.assert_called_once() event = mock_sub_callback.call_args[0][0] self.assertTrue(event.payload.get_dict() == {'urls': tuple(test_more_image_urls)})
17,144
Python
51.753846
169
0.650782
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/test_datetime_format.py
## Copyright (c) 2018-2019, 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.app import carb.settings from functools import partial from ..date_format_menu import DatetimeFormatMenu, DATETIME_FORMAT_SETTING, get_datetime_format class TestDatetimeFormat(omni.kit.test.AsyncTestCase): """Testing DatetimeFormatMenu""" async def setUp(self): pass async def tearDown(self): pass async def _after_redraw_async(self): for _ in range(2): await omni.kit.app.get_app().next_update_async() async def test_datetime_format_change(self): """ Test datetime format setting changes""" self._datetime_format = "MM/DD/YYYY" self._format_changed = False def format_change_callback(owner): owner._format_changed = True datetime_menu = DatetimeFormatMenu(partial(format_change_callback, self)) datetime_menu.visible = True # test datetime format value carb.settings.get_settings().set(DATETIME_FORMAT_SETTING, self._datetime_format) await self._after_redraw_async() self.assertEqual(get_datetime_format(), "%m/%d/%Y") carb.settings.get_settings().set(DATETIME_FORMAT_SETTING, "DD-MM-YYYY") await self._after_redraw_async() self.assertEqual(get_datetime_format(), "%d-%m-%Y") # test datetime format setting change callback is work as expected carb.settings.get_settings().set(DATETIME_FORMAT_SETTING, "DD/MM/YYYY") await self._after_redraw_async() self.assertEqual(get_datetime_format(), "%x") self.assertTrue(self._format_changed)
2,033
Python
37.377358
95
0.694048
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/test_widget.py
## Copyright (c) 2018-2019, 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.client import omni.kit.app from unittest.mock import patch from ..model import FileBrowserModel, FileBrowserItemFactory from ..widget import FileBrowserWidget async def after_redraw_async(frames=1): for _ in range(frames + 1): await omni.kit.app.get_app().next_update_async() class TestWidget(omni.kit.test.AsyncTestCase): """Testing FileBrowserWidget basic fuction""" async def setUp(self): self._throttle_frames = 4 async def tearDown(self): # Wait a few frames for delayed item changed events to clear the system await after_redraw_async(self._throttle_frames) async def test_widget_refreshes_views(self): """Testing FileBrowserWidget._auto_refresh_item updates views""" from .. import TREEVIEW_PANE, LISTVIEW_PANE import omni.ui as ui window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_DOCKING self._window = ui.Window("test_window", width=1200, height=900, flags=window_flags) with self._window.frame: test_url = "C://watched" test_url2 = "C://watched2" udim_url = "C://texture_1001.jpg" udim_url2 = "C://texture_1002.jpg" model = FileBrowserModel("C:", "C:") watched = FileBrowserItemFactory.create_group_item("watched", test_url) udim_item = FileBrowserItemFactory.create_udim_item("udim", udim_url, 0,1,1) udim_item2 = FileBrowserItemFactory.create_udim_item("udim2", udim_url2,1,2,1) udim_item.populate_udim(model.root) model.root.add_child(watched) model.root.add_child(udim_item) model.root.add_child(udim_item2) under_test = FileBrowserWidget("test") under_test.add_model_as_subtree(model) under_test._on_selection_changed(TREEVIEW_PANE, [watched]) # teat some widget's attribute and method under_test.show_udim_sequence=True self.assertTrue(under_test.show_udim_sequence) self.assertEqual(under_test.get_root(), under_test._models.root) self.assertEqual(under_test.get_root(TREEVIEW_PANE), under_test._tree_view.model.root) self.assertEqual(under_test.get_root(LISTVIEW_PANE), under_test._listview_model.root) # test notification and toggle under_test.show_notification() self.assertTrue(under_test._notification_frame.visible) under_test.hide_notification() self.assertFalse(under_test._notification_frame.visible) under_test.toggle_grid_view(True) self.assertTrue(under_test.show_grid_view) # test create item item_create_from_widget = under_test.create_grouping_item("watched2", test_url2) self.assertEqual(item_create_from_widget.name, "watched2") # test set item info under_test.set_item_info(item_create_from_widget, "info") self.assertEqual(item_create_from_widget.alert[1], "info") under_test.set_item_warning(item_create_from_widget, "warning") self.assertEqual(item_create_from_widget.alert[1], "warning") await after_redraw_async(self._throttle_frames) under_test.set_item_error(item_create_from_widget, "error") self.assertEqual(item_create_from_widget.alert[1], "error") await after_redraw_async(self._throttle_frames) under_test.clear_item_alert(item_create_from_widget) self.assertEqual(item_create_from_widget.alert, None) await after_redraw_async(self._throttle_frames) # test tree view select under_test.set_selections([item_create_from_widget], TREEVIEW_PANE) self.assertEqual(under_test.get_selected_item(), item_create_from_widget) await after_redraw_async(self._throttle_frames) under_test.select_and_center(item_create_from_widget, TREEVIEW_PANE) under_test.set_expanded(item_create_from_widget, True, True) self.assertEqual(under_test.get_selected_item(), item_create_from_widget) await after_redraw_async(self._throttle_frames) # test listview select under_test.select_and_center(watched, LISTVIEW_PANE) under_test.toggle_grid_view(False) self.assertFalse(under_test.show_grid_view) under_test.select_and_center(item_create_from_widget, LISTVIEW_PANE) under_test._on_selection_changed(LISTVIEW_PANE, [item_create_from_widget]) self.assertEqual(under_test.get_selected_item(), item_create_from_widget) await after_redraw_async(self._throttle_frames) under_test.delete_child(item_create_from_widget) await after_redraw_async(self._throttle_frames)
5,317
Python
49.647619
98
0.661651
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/__init__.py
## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from unittest.mock import Mock class AsyncMock(Mock): """Async equivalent of Mock class""" def __call__(self, *args, **kwargs): sup = super(AsyncMock, self) async def coro(): return sup.__call__(*args, **kwargs) return coro() def __await__(self): return self().__await__() from .test_widget import * from .test_populate import * from .test_thumbnails import * from .test_auto_refresh import * from .test_grid_view import * from .test_zoom_bar import * from .test_datetime_format import * from .test_drop import *
1,014
Python
31.741934
77
0.704142
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/test_populate.py
## Copyright (c) 2018-2019, 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 asyncio import omni.client import omni.kit.app from typing import List, Callable from functools import partial from datetime import datetime from unittest.mock import Mock, patch, ANY from carb.events import IEventStream from ..model import FileBrowserModel, FileBrowserItemFactory, FileBrowserItem from ..nucleus_model import NucleusItemFactory, NucleusItem from ..filesystem_model import FileSystemItemFactory, FileSystemItem from .. import CONNECTION_ERROR_EVENT from . import AsyncMock class TestNucleusPopulate(omni.kit.test.AsyncTestCase): """Testing omni.kit.widget.filebrowser.NucleusItem""" async def setUp(self): self.test_listings = {"omniverse://ov-test": ["Lib", "NVIDIA", "Projects", "Users"]} async def tearDown(self): pass class MockListEntry: def __init__(self, path, size=0, access=0, flags=omni.client.ItemFlags.CAN_HAVE_CHILDREN): self.relative_path = path self.size = size self.access = access self.flags = flags self.modified_time = datetime.now() async def _mock_list_async_impl(self, url: str): if url in self.test_listings: entries = [self.MockListEntry(subdir) for subdir in self.test_listings[url]] result = omni.client.Result.OK else: entries, result = [], omni.client.Result.ERROR_NOT_FOUND return result, entries async def _mock_list_async_exception(self, url: str): raise RuntimeError("Runtime error") async def _mock_list_async_error(self, url: str): return omni.client.Result.ERROR, [] async def _mock_list_async_timeout(self, url: str, timeout = 1.0): await asyncio.sleep(timeout+1) async def test_listing_succeeds(self): """Testing NucleusItem.populate_async should succeed""" with patch("omni.client.list_async") as mock_list_async: mock_list_async.side_effect = self._mock_list_async_impl mock_callback = AsyncMock(return_value=123) test_path = "omniverse://ov-test" item = NucleusItemFactory.create_group_item(test_path, test_path) return_value = await item.populate_async(mock_callback) # Check that item has been populated self.assertTrue(item.populated) # Check that the callback was invoked and that we received its return value mock_callback.assert_called_once_with(omni.client.Result.OK, item.children) self.assertEqual(return_value, 123) async def test_listing_raises_exception(self): """Testing NucleusItem.populate_async should catch Exception""" with patch("omni.client.list_async") as mock_list_async: mock_list_async.side_effect = self._mock_list_async_exception mock_callback = AsyncMock() mock_sub_callback = Mock() test_path = "omniverse://ov-test" item = NucleusItemFactory.create_group_item(test_path, test_path) # Listen for connection error events event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream_sub = event_stream.create_subscription_to_pop_by_type(CONNECTION_ERROR_EVENT, mock_sub_callback) await item.populate_async(mock_callback) # Check that the callback was invoked with Exception result. result, _ = mock_callback.call_args[0] assert isinstance(result, Exception) # Check that item is nevertheless marked as populated self.assertFalse(bool(item.children)) self.assertTrue(item.populated) # Confirm that an error event was sent to the subscribed callback await omni.kit.app.get_app().next_update_async() mock_sub_callback.assert_called_once() event = mock_sub_callback.call_args[0][0] self.assertTrue(event.payload.get_dict() == {'url': test_path}) async def test_listing_returns_error(self): """Testing NucleusItem.populate_async should return error""" with patch("omni.client.list_async") as mock_list_async: mock_list_async.side_effect = self._mock_list_async_error mock_callback = AsyncMock() mock_sub_callback = Mock() test_path = "omniverse://ov-test" item = NucleusItemFactory.create_group_item(test_path, test_path) # Listen for connection error events event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream_sub = event_stream.create_subscription_to_pop_by_type(CONNECTION_ERROR_EVENT, mock_sub_callback) await item.populate_async(mock_callback) # Check that the callback was invoked with Exception result. result, _ = mock_callback.call_args[0] assert isinstance(result, RuntimeWarning) # Check that item is nevertheless marked as populated self.assertFalse(bool(item.children)) self.assertTrue(item.populated) # Check that an error event was sent to the subscribed callback await omni.kit.app.get_app().next_update_async() mock_sub_callback.assert_called_once() event = mock_sub_callback.call_args[0][0] self.assertTrue(event.payload.get_dict() == {'url': test_path}) async def test_listing_times_out(self): """Testing NucleusItem.populate_async times out""" with patch("omni.client.list_async") as mock_list_async: timeout = 1.0 mock_list_async.side_effect = self._mock_list_async_timeout mock_callback = AsyncMock() mock_sub_callback = Mock() test_path = "omniverse://ov-test" item = NucleusItemFactory.create_group_item(test_path, test_path) # Listen for connection error events event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream_sub = event_stream.create_subscription_to_pop_by_type(CONNECTION_ERROR_EVENT, mock_sub_callback) await item.populate_async(mock_callback, timeout=timeout) # Check that the callback was invoked with Exception result. result, _ = mock_callback.call_args[0] assert isinstance(result, RuntimeWarning) # Check that item is nevertheless marked as populated self.assertFalse(bool(item.children)) self.assertTrue(item.populated) # Check that an error event was sent to the subscribed callback await omni.kit.app.get_app().next_update_async() mock_sub_callback.assert_called_once() event = mock_sub_callback.call_args[0][0] self.assertTrue(event.payload.get_dict() == {'url': test_path}) async def test_listing_called_just_once(self): """Testing NucleusItem.populate_async should not populate item if already populated""" with patch("omni.client.list_async") as mock_list_async: mock_list_async.side_effect = self._mock_list_async_impl test_path = "omniverse://ov-test" item = NucleusItemFactory.create_group_item(test_path, test_path) await item.populate_async(None) # Check that item has been populated self.assertTrue(bool(item.children) and item.populated) # Populate again and again await item.populate_async(None) await item.populate_async(None) # Check that the call to list_async ran only the first time self.assertEqual(mock_list_async.call_count, 1) class TestFileSystemPopulate(omni.kit.test.AsyncTestCase): """Testing omni.kit.widget.filebrowser.FileSystemItem""" async def setUp(self): self.test_listings = {"C:": ["Program Files", "ProgramData", "temp", "Users", "Windows"]} async def tearDown(self): pass class MockDirEntry: def __init__(self, path: str, file_attrs: int = 0, symlink: bool = False): self.name = path self.path = path self._file_attrs = file_attrs self._symlink = symlink def stat(self): from collections import namedtuple MockStat = namedtuple("MockStat", "st_file_attributes st_size, st_mode, st_mtime") return MockStat(self._file_attrs, 0, 0, 0) def is_dir(self): True def is_symlink(self): return self._symlink class MockDirEntryIterator: def __init__(self, subdirs = List[str]): self._subdirs = subdirs self._current = 0 def __iter__(self): return self def __next__(self): if self._current < len(self._subdirs): entry = TestFileSystemPopulate.MockDirEntry(self._subdirs[self._current]) self._current += 1 return entry else: raise StopIteration def __enter__(self): return self.__iter__() def __exit__(self, e_type, e_val, e_traceback): return False def _mock_os_scandir_impl(self, path: str): if path in self.test_listings: subdirs = self.test_listings[path] else: subdirs = [] return self.MockDirEntryIterator(subdirs) async def test_listing_succeeds(self): """Testing FileSystemItem.populate_async should succeed""" with patch("os.scandir") as mock_os_scandir: with patch("omni.kit.widget.filebrowser.FileSystemItem.keep_entry") as mock_keep_entry: mock_os_scandir.side_effect = self._mock_os_scandir_impl mock_keep_entry.return_value = True mock_callback = AsyncMock(return_value=123) test_path = "C:" item = FileSystemItemFactory.create_group_item(test_path, test_path) return_value = await item.populate_async(mock_callback) # Check that item has been populated self.assertTrue(item.populated) # Check that the callback was invoked and that we received its return value mock_callback.assert_called_once_with(None, item.children) self.assertEqual(return_value, 123) async def test_listing_returns_empty(self): """Testing FileSystemItem.populate_async returns empty""" with patch("os.scandir") as mock_os_scandir: with patch("omni.kit.widget.filebrowser.FileSystemItem.keep_entry") as mock_keep_entry: mock_os_scandir.side_effect = self._mock_os_scandir_impl mock_keep_entry.return_value = True mock_callback = AsyncMock(return_value=123) test_path = "O:" item = FileSystemItemFactory.create_group_item(test_path, test_path) return_value = await item.populate_async(mock_callback) # Check that item has not been populated self.assertFalse(bool(item.children) and item.populated) # Check that the callback was invoked and that we received its return value mock_callback.assert_called_once_with(None, ANY) self.assertEqual(return_value, 123) async def test_keep_entry(self): """Testing FileSystemItem.keep_entry returns True for valid entries""" import stat with patch("os.name", "nt"): self.assertTrue( FileSystemItem.keep_entry(self.MockDirEntry("Desktop"))) self.assertTrue( FileSystemItem.keep_entry(self.MockDirEntry(".thumbs", file_attrs=stat.FILE_ATTRIBUTE_HIDDEN))) self.assertFalse( FileSystemItem.keep_entry(self.MockDirEntry("System", file_attrs=stat.FILE_ATTRIBUTE_SYSTEM))) with patch("os.name", "posix"): self.assertTrue( FileSystemItem.keep_entry(self.MockDirEntry("home"))) self.assertTrue( FileSystemItem.keep_entry(self.MockDirEntry("link@", symlink=True))) class TestFileBrowserPopulate(omni.kit.test.AsyncTestCase): """Testing omni.kit.widget.filebrowser.FileBrowserItem""" async def setUp(self): self.test_listings = {"omniverse://ov-test": ["Lib", "NVIDIA", "Projects", "Users"]} self._timeout = 1.0 async def tearDown(self): pass async def _mock_populate_async_impl(self, item: FileBrowserItem, callback_async: Callable, timeout: float = 1.0): if not item.populated: if item.path in self.test_listings: subdirs = self.test_listings[item.path] else: subdirs = [] for subdir in subdirs: item.add_child(FileBrowserItemFactory.create_group_item(subdir, f"{item.path}/{subdir}")) item.populated = True return await callback_async(None, item.children) async def _mock_populate_async_timeout(self, item: FileBrowserItem, callback_async: Callable, timeout: float = 1.0): return await callback_async(asyncio.TimeoutError(), None) async def test_populate_with_callback_succeeds(self): """Testing FileBrowserItem.populate_with_callback should invoke callback""" with patch.object(FileBrowserItem, "populate_async", autospec=True) as mock_populate_async: mock_populate_async.side_effect = self._mock_populate_async_impl mock_callback = Mock() test_path = "omniverse://ov-test" item = FileBrowserItemFactory.create_group_item(test_path, test_path) item.populate_with_callback(mock_callback, timeout=self._timeout) # Wait for the thread to finish, then check that callback was invoked await omni.kit.app.get_app().next_update_async() mock_callback.assert_called_once_with(item.children) async def test_populate_with_callback_times_out(self): """Testing FileBrowserItem.populate_with_callback times out""" with patch.object(FileBrowserItem, "populate_async", autospec=True) as mock_populate_async: mock_populate_async.side_effect = self._mock_populate_async_timeout mock_callback = Mock() test_path = "omniverse://ov-test" item = FileBrowserItemFactory.create_group_item(test_path, test_path) item.populate_with_callback(mock_callback, timeout=self._timeout) # Wait for the thread to finish, then check that callback was not invoked await omni.kit.app.get_app().next_update_async() mock_callback.assert_not_called() async def test_get_item_children_succeeds(self): """Testing FileBrowserModel.get_item_children should populate asynchronously""" with patch.object(FileBrowserItem, "populate_async", autospec=True) as mock_populate_async: mock_populate_async.side_effect = self._mock_populate_async_impl mock_item_changed_callback = Mock() test_path = "omniverse://ov-test" model = FileBrowserModel(test_path, test_path, timeout=self._timeout) model.add_item_changed_fn(mock_item_changed_callback) item = model.root self.assertFalse(item.populated) # Check that the call immediately returns but with initially empty children list children = model.get_item_children(item) self.assertEqual(children, []) # Wait til populate_async fulfills its task await omni.kit.app.get_app().next_update_async() # Check again and confirm item is now populated with expected children self.assertTrue(item.populated) children = model.get_item_children(item) self.assertEqual([c.name for c in children], self.test_listings.get(test_path)) # Confirm item changed was called await omni.kit.app.get_app().next_update_async() mock_item_changed_callback.assert_called_once_with(model, item)
16,583
Python
42.98939
121
0.635711
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/test_auto_refresh.py
## Copyright (c) 2018-2019, 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.client import omni.kit.app from datetime import datetime from typing import Callable from unittest.mock import patch from ..model import FileBrowserModel, FileBrowserItemFactory from ..nucleus_model import NucleusItemFactory from ..filesystem_model import FileSystemItemFactory from ..widget import FileBrowserWidget from ..tree_view import FileBrowserTreeView from ..grid_view import FileBrowserGridView, FileBrowserGridViewDelegate class MockListEntry: def __init__(self, path, size=0, access=0, flags=omni.client.ItemFlags.CAN_HAVE_CHILDREN): self.relative_path = path self.size = size self.access = access self.flags = flags self.modified_time = datetime.now() self.deleted = False class MockListSubscription: def __init__(self, url, list_cb, list_change_cb): self._url = url self._list_cb = list_cb self._list_change_cb = list_change_cb self._events = [] self._cur_event = 0 def queue_event(self, result: omni.client.Result, event: omni.client.ListEvent, entry: MockListEntry): self._events.append((result, event, entry)) def next_event(self, url: str) -> omni.client.ListEvent: if url == self._url and self._cur_event < len(self._events): result, event, entry = self._events[self._cur_event] if self._list_change_cb: self._list_change_cb(result, event, entry) self._cur_event += 1 return event else: return None async def after_redraw_async(frames=1): for _ in range(frames + 1): await omni.kit.app.get_app().next_update_async() class TestAutoRefresh(omni.kit.test.AsyncTestCase): """Testing FileSystemItem.content_changed_async""" async def setUp(self): self.test_list_subscription = None self._throttle_frames = 4 async def tearDown(self): # Wait a few frames for delayed item changed events to clear the system await after_redraw_async(self._throttle_frames) def _mock_list_subscribe_impl(self, url: str, list_cb: Callable, list_change_cb: Callable): self.test_list_subscription = MockListSubscription(url, list_cb, list_change_cb) async def test_auto_refresh_nucleus_folder(self): """Testing FileBrowserModel.auto_refresh_item monitors Nucleus folder for changes""" with patch.object(omni.client, "list_subscribe_with_callback", side_effect=self._mock_list_subscribe_impl),\ patch.object(FileBrowserModel, "_item_changed") as mock_item_changed: test_url = "omniverse://ov-test/watched" model = FileBrowserModel("ov-test", "omniverse://ov-test") watched = NucleusItemFactory.create_group_item("watched", test_url) model.root.add_child(watched) # Queue up events model.auto_refresh_item(watched, throttle_frames=self._throttle_frames) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.CREATED, MockListEntry("foo.usd")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.CREATED, MockListEntry("bar.mdl")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.DELETED, MockListEntry("foo.usd")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.DELETED, MockListEntry("bar.mdl")) # Created foo.usd self.assertEqual(len(watched.children), 0) self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 1) self.assertTrue("foo.usd" in watched.children) # Created bar.mdl self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 2) self.assertTrue("bar.mdl" in watched.children) # Deleted foo.usd self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 2) # To implement soft deleted feature, we don't real delete the item, set it's delete flag instead self.assertTrue(watched.children["foo.usd"].is_deleted) self.assertTrue(not watched.children["bar.mdl"].is_deleted) # Deleted bar.mdl self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 2) self.assertTrue(watched.children["bar.mdl"].is_deleted) # Confirm item changes queued up and triggered only once after next frame await after_redraw_async(self._throttle_frames) mock_item_changed.assert_called_once_with(watched) async def test_auto_refresh_filesystem_folder(self): """Testing FileBrowserModel.auto_refresh_item monitors Filesystem folder for changes""" with patch("omni.client.list_subscribe_with_callback", side_effect=self._mock_list_subscribe_impl),\ patch.object(FileBrowserModel, "_item_changed") as mock_item_changed: test_url = "C://watched" model = FileBrowserModel("C:", "C:") watched = FileSystemItemFactory.create_group_item("watched", test_url) model.root.add_child(watched) # Queue up events model.auto_refresh_item(watched, throttle_frames=self._throttle_frames) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.CREATED, MockListEntry("foo.usd")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.CREATED, MockListEntry("bar.mdl")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.DELETED, MockListEntry("foo.usd")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.DELETED, MockListEntry("bar.mdl")) # Created foo.usd self.assertEqual(len(watched.children), 0) self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 1) self.assertTrue("foo.usd" in watched.children) # Created bar.mdl self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 2) self.assertTrue("bar.mdl" in watched.children) # Deleted foo.usd self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 1) # To implement soft deleted feature, we don't real delete the item, set it's delete flag instead self.assertTrue(not "foo.usd" in watched.children) self.assertTrue("bar.mdl" in watched.children) # Deleted bar.mdl self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 0) self.assertTrue(not "bar.mdl" in watched.children) # Confirm item changes queued up and triggered only once await after_redraw_async(self._throttle_frames) mock_item_changed.assert_called_once_with(watched) async def test_auto_refresh_ignores_update_events(self): """Testing FileBrowserModel.auto_refresh_item responds to only CREATED and DELETED events (OM-29866)""" with patch("omni.client.list_subscribe_with_callback", side_effect=self._mock_list_subscribe_impl),\ patch.object(FileBrowserModel, "_item_changed") as mock_item_changed: test_url = "omniverse://ov-test/watched" model = FileBrowserModel("ov-test", "omniverse://ov-test") watched = NucleusItemFactory.create_group_item("watched", test_url) model.root.add_child(watched) model.auto_refresh_item(watched, throttle_frames=self._throttle_frames) self.assertEqual(len(watched.children), 0) # CREATED event mock_item_changed.reset_mock() self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.CREATED, MockListEntry("foo.usd")) self.test_list_subscription.next_event(watched.path) self.assertEqual(len(watched.children), 1) self.assertTrue("foo.usd" in watched.children) await after_redraw_async(self._throttle_frames) mock_item_changed.assert_called_once_with(watched) # UPDATED, etc. events self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.UPDATED, MockListEntry("foo.usd")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.LOCKED, MockListEntry("foo.usd")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.UNLOCKED, MockListEntry("foo.usd")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.METADATA, MockListEntry("foo.usd")) self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.UNKNOWN, MockListEntry("foo.usd")) mock_item_changed.reset_mock() while True: # UPDATED event event = self.test_list_subscription.next_event(watched.path) if event: await after_redraw_async(self._throttle_frames) self.assertTrue(event not in [omni.client.ListEvent.CREATED, omni.client.ListEvent.DELETED]) mock_item_changed.assert_not_called() else: break # DELETED event mock_item_changed.reset_mock() self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.DELETED, MockListEntry("foo.usd")) self.test_list_subscription.next_event(watched.path) # To implement soft deleted feature, we don't real delete the item, set it's delete flag instead for child_name in watched.children: item = watched.children[child_name] item.is_deleted = True self.assertEqual(item.is_deleted, True) # Confirm item changes queued up and triggered only once await after_redraw_async(self._throttle_frames) mock_item_changed.assert_called_once_with(watched) async def test_widget_refreshes_views(self): """Testing FileBrowserWidget._auto_refresh_item updates views""" from .. import TREEVIEW_PANE with patch("omni.client.list_subscribe_with_callback", side_effect=self._mock_list_subscribe_impl),\ patch.object(FileBrowserTreeView, "refresh_ui") as mock_refresh_tree_view,\ patch.object(FileBrowserGridView, "refresh_ui") as mock_refresh_grid_view: test_url = "C://watched" model = FileBrowserModel("C:", "C:") watched = FileBrowserItemFactory.create_group_item("watched", test_url) model.root.add_child(watched) # Make watched directory the current one under_test = FileBrowserWidget("test") under_test.add_model_as_subtree(model) under_test._on_selection_changed(TREEVIEW_PANE, [watched]) # Queue up events self.test_list_subscription.queue_event(omni.client.Result.OK, omni.client.ListEvent.CREATED, MockListEntry("foo.usd")) # Confirm change event triggers UI refresh mock_refresh_tree_view.reset_mock() mock_refresh_grid_view.reset_mock() self.test_list_subscription.next_event(watched.path) await after_redraw_async(self._throttle_frames) mock_refresh_tree_view.assert_called() mock_refresh_grid_view.assert_called() async def test_gridview_redraws_only_once(self): """Testing FileBrowserGridView.refresh_ui updates grid view only once when refreshed many times""" with patch.object(FileBrowserGridViewDelegate, "build_grid") as mock_delegate_build_grid,\ patch.object(FileBrowserGridViewDelegate, "update_grid") as mock_delegate_update_grid: model = FileBrowserModel("ov-test", "omniverse://ov-test") under_test = FileBrowserGridView(model) mock_delegate_build_grid.assert_called_once_with(model) # OM-78400 Clear out all refreshes from setting up the view before testing for additional ones await after_redraw_async(self._throttle_frames) mock_delegate_update_grid.reset_mock() # Call refresh multiple times under_test.refresh_ui() under_test.refresh_ui() under_test.refresh_ui() # Confirm that refresh doesn't immediately rebuild the grid view. Instead, after some delay, # builds the view only once. mock_delegate_update_grid.assert_not_called() await after_redraw_async(self._throttle_frames) mock_delegate_update_grid.assert_called_once_with(model) class TestSyncItemChanges(omni.kit.test.AsyncTestCase): """Testing omni.kit.widget.filebrowser.FileBrowserModel""" async def setUp(self): self.test_frame = 0 self.test_listings_by_frame = [["A", "B", "C"], ["B", "C", "D"]] self._throttle_frames = 4 async def tearDown(self): # Wait a few frames for delayed item changed events to clear the system await after_redraw_async(self._throttle_frames) async def _mock_list_async_impl(self, url: str, include_deleted_option=omni.client.ListIncludeOption.INCLUDE_DELETED_FILES): subdirs = [] if self.test_frame < len(self.test_listings_by_frame): subdirs = self.test_listings_by_frame[self.test_frame] self.test_frame += 1 entries = [MockListEntry(subdir) for subdir in subdirs] result = omni.client.Result.OK return result, entries async def test_syncing_item_changes_succeeds(self): """Testing FileBrowserModel.sync_up_item_changes updates given folder""" with patch("omni.client.list_async") as mock_list_async: mock_list_async.side_effect = self._mock_list_async_impl test_url = "C://watched" watched = FileSystemItemFactory.create_group_item("watched", test_url) under_test = FileBrowserModel("C:", "C:") under_test.root.add_child(watched) under_test.sync_up_item_changes(watched) await omni.kit.app.get_app().next_update_async() test_subdirs_0 = self.test_listings_by_frame[0] self.assertEqual(test_subdirs_0, [name for name in watched.children]) under_test.sync_up_item_changes(watched) await omni.kit.app.get_app().next_update_async() test_subdirs_1 = self.test_listings_by_frame[1] self.assertEqual(test_subdirs_1, [name for name in watched.children])
15,506
Python
49.02258
132
0.658326
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/test_drop.py
## Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.client import omni.kit.app from unittest.mock import Mock from ..model import FileBrowserModel, FileBrowserItemFactory class TestDrop(omni.kit.test.AsyncTestCase): """Testing FileSystemItem.content_changed_async""" async def setUp(self): pass async def tearDown(self): pass async def test_drop_handler(self): """Test drop handler behaves as expected.""" from .. import TREEVIEW_PANE mock_drop = Mock() model = FileBrowserModel("C:", "C:", drop_fn=mock_drop) src_paths = [] for i in range(100): src_paths.append("C://foo_" + str(i +1)) src_items = [] for src in src_paths: src_items.append(FileBrowserItemFactory.create_group_item(src.lstrip("C://"), src)) dst_item = FileBrowserItemFactory.create_group_item("dst", "C://dst") # test drop_fn only called once when multiple items are triggering drop handler at the same time for src_item in src_items: model.drop(dst_item, src_item) for _ in range(2): await omni.kit.app.get_app().next_update_async() mock_drop.assert_called_once_with(dst_item, "\n".join(src_paths)) mock_drop.reset_mock() # test drop_fn called correctly when passing in string as source src_paths_str = "C://foo\nC://bar\nC://baz" model.drop(dst_item, src_paths_str) mock_drop.assert_called_once_with(dst_item, src_paths_str)
1,961
Python
37.470588
104
0.661397
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tests/test_grid_view.py
## Copyright (c) 2018-2019, 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.client import omni.kit.app import omni.ui as ui from unittest.mock import patch from ..model import FileBrowserModel, FileBrowserItemFactory, FileBrowserItem from ..grid_view import FileBrowserGridView, FileBrowserGridViewDelegate class TestUpdateGridView(omni.kit.test.AsyncTestCase): """Testing FileBrowserGridViewDelegate.update_grid""" async def setUp(self): self._throttle_frames = 2 async def tearDown(self): pass async def _after_redraw_async(self): for _ in range(self._throttle_frames + 1): await omni.kit.app.get_app().next_update_async() async def _mock_refresh_thumbnails_async(self, model: FileBrowserModel): pass def _get_badges(self, item: FileBrowserItem): return [] async def test_update_grid_adds_new_items(self): """Testing FileBrowserGridView.update_grid updates the grid view successfully""" with patch.object(FileBrowserGridViewDelegate, "refresh_thumbnails_async", side_effect=self._mock_refresh_thumbnails_async): model = FileBrowserModel("ov-test", "omniverse://ov-test") test_items = ["foo.usd", "bar.usd"] test_items_path = [] for name in test_items: model.root.add_child(FileBrowserItemFactory.create_dummy_item(name, f"{model.root.path}/{name}")) test_items_path.append(f"{model.root.path}/{name}") # Assert grid initially empty under_test = FileBrowserGridView(model, testing=True) delegate = under_test._delegate self.assertTrue(delegate._grid is not None) self.assertEqual(0, len(ui.Inspector.get_children(delegate._grid))) self.assertEqual(0, len(delegate._cards)) # Grid is populated after redraw under_test.refresh_ui() await self._after_redraw_async() test_card = delegate._cards[test_items_path[0]] test_card._get_badges_fn = self._get_badges thumbnail = test_card._get_thumbnail(test_card._item) self.assertIsNotNone(thumbnail) test_card._item.alert = (1, "Info") test_card.draw_badges() self.assertEqual(len(test_items), len(ui.Inspector.get_children(delegate._grid))) self.assertEqual(len(test_items), len(delegate._cards)) # Adding a file updates the grid model.root.add_child(FileBrowserItemFactory.create_dummy_item("baz.usd", f"{model.root.path}/baz.usd")) under_test.refresh_ui() await self._after_redraw_async() self.assertEqual(len(test_items)+1, len(ui.Inspector.get_children(delegate._grid))) self.assertEqual(len(test_items)+1, len(delegate._cards)) # Assert deleting orignal files leaves only the added file in place for name in test_items: model.root.del_child(name) under_test.refresh_ui() await self._after_redraw_async() self.assertEqual(1, len(ui.Inspector.get_children(delegate._grid))) self.assertEqual(1, len(delegate._cards)) self.assertTrue(f"{model.root.path}/baz.usd" in delegate._cards) async def test_cut_items_style_reflected(self): """Testing that items in cut clipboard are applied cut style.""" from ..clipboard import save_items_to_clipboard, is_path_cut with patch.object(FileBrowserGridViewDelegate, "refresh_thumbnails_async", side_effect=self._mock_refresh_thumbnails_async): model = FileBrowserModel("ov-test", "omniverse://ov-test") test_names = ["foo.usd", "bar.usd", "baz.usd"] for name in test_names: model.root.add_child(FileBrowserItemFactory.create_dummy_item(name, f"{model.root.path}/{name}")) # Assert grid initially empty under_test = FileBrowserGridView(model, testing=True) delegate = under_test._delegate under_test.refresh_ui() await self._after_redraw_async() # with empty clipboard every item should be with normal name for path, item in delegate._cards.items(): self.assertFalse(is_path_cut(path)) self.assertEqual(item._back_buffer_thumbnail.name, "") item.draw_badges() # put item in clipboard items = model.get_item_children(model.root) cut_path = items[0].path save_items_to_clipboard(items[0], is_cut=True) await self._after_redraw_async() under_test.refresh_ui() # item in clipboard should be applied Cut style name for path, item in delegate._cards.items(): if path == cut_path: self.assertTrue(is_path_cut(path)) self.assertEqual(item._back_buffer_thumbnail.name, "Cut") else: self.assertFalse(is_path_cut(path)) self.assertEqual(item._back_buffer_thumbnail.name, "")
5,534
Python
45.512605
132
0.634261
omniverse-code/kit/exts/omni.index.compute/omni/index/compute/ogn/OgnIndexDistributedComputeTechniqueDatabase.py
"""Support for simplified access to data on nodes of type omni.index.compute.indexDistributedComputeTechnique Integration with NVIDIA IndeX distributed compute technique """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnIndexDistributedComputeTechniqueDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.index.compute.indexDistributedComputeTechnique Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.active inputs.buffers inputs.threading inputs.timestep inputs.verbose """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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:active', 'bool', 0, 'Active', 'If false then disable the node operation', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:buffers', 'uint64[]', 0, 'Compute buffers', 'Input compute buffers', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''), ('inputs:threading', 'bool', 0, 'Multithreading', 'Use multithreading', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:timestep', 'int', 0, 'Timestep', 'Active timestep', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('inputs:verbose', 'int', 0, 'Verbose', 'Log verbose output', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def active(self): data_view = og.AttributeValueHelper(self._attributes.active) return data_view.get() @active.setter def active(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.active) data_view = og.AttributeValueHelper(self._attributes.active) data_view.set(value) @property def buffers(self): data_view = og.AttributeValueHelper(self._attributes.buffers) return data_view.get() @buffers.setter def buffers(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.buffers) data_view = og.AttributeValueHelper(self._attributes.buffers) data_view.set(value) self.buffers_size = data_view.get_array_size() @property def threading(self): data_view = og.AttributeValueHelper(self._attributes.threading) return data_view.get() @threading.setter def threading(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.threading) data_view = og.AttributeValueHelper(self._attributes.threading) data_view.set(value) @property def timestep(self): data_view = og.AttributeValueHelper(self._attributes.timestep) return data_view.get() @timestep.setter def timestep(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.timestep) data_view = og.AttributeValueHelper(self._attributes.timestep) data_view.set(value) @property def verbose(self): data_view = og.AttributeValueHelper(self._attributes.verbose) return data_view.get() @verbose.setter def verbose(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.verbose) data_view = og.AttributeValueHelper(self._attributes.verbose) data_view.set(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 = { } """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 = { } 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 = OgnIndexDistributedComputeTechniqueDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnIndexDistributedComputeTechniqueDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnIndexDistributedComputeTechniqueDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
7,131
Python
45.311688
150
0.65685
omniverse-code/kit/exts/omni.index.compute/omni/index/compute/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.index.compute as ogidx from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphIndexApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests"] async def test_api(self): _check_module_api_consistency(ogidx, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogidx.tests, is_test_module=True) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents(ogidx, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212 _check_public_api_contents(ogidx.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
935
Python
48.263155
109
0.657754
omniverse-code/kit/exts/omni.kit.manipulator.selector/omni/kit/manipulator/selector/manipulator_order_manager.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 Callable, Dict import carb.settings MANIPULATOR_ORDERS_SETTING_PATH = "/persistent/exts/omni.kit.manipulator.selector/orders" class ManipulatorOrderManager: def __init__(self): self._on_orders_changed_fns_id = 0 self._on_orders_changed_fns: Dict[Callable] = {} self._settings = carb.settings.get_settings() self._sub = self._settings.subscribe_to_tree_change_events( MANIPULATOR_ORDERS_SETTING_PATH, self._on_setting_changed ) self._orders_dict: Dict[str, int] = {} self._refresh_orders() def destroy(self): if self._sub: self._settings.unsubscribe_to_change_events(self._sub) self._sub = None def __del__(self): self.destroy() @property def orders_dict(self) -> Dict[str, int]: return self._orders_dict def subscribe_to_orders_changed(self, fn: Callable) -> int: self._on_orders_changed_fns_id += 1 self._on_orders_changed_fns[self._on_orders_changed_fns_id] = fn return self._on_orders_changed_fns_id def unsubscribe_to_orders_changed(self, id: int): self._on_orders_changed_fns.pop(id, None) def _on_setting_changed(self, tree_item, changed_item, event_type): self._refresh_orders() def _refresh_orders(self): self._orders_dict = self._settings.get_settings_dictionary(MANIPULATOR_ORDERS_SETTING_PATH) for fn in self._on_orders_changed_fns.values(): fn()
1,938
Python
33.624999
99
0.672859
omniverse-code/kit/exts/omni.kit.manipulator.selector/omni/kit/manipulator/selector/extension.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 Dict import omni.ext from .manipulator_order_manager import ManipulatorOrderManager from .manipulator_selector import ManipulatorSelector _selectors: Dict[str, ManipulatorSelector] = {} _order_manager: ManipulatorOrderManager = None # Each UsdContext has a ManipulatorSelector to subscribe to selection event def get_manipulator_selector(usd_context_name: str) -> ManipulatorSelector: global _selectors global _order_manager if usd_context_name not in _selectors: selector = ManipulatorSelector(_order_manager, usd_context_name) _selectors[usd_context_name] = selector return selector return _selectors[usd_context_name] class ManipulatorPrim(omni.ext.IExt): def on_startup(self, ext_id): global _order_manager assert _order_manager is None _order_manager = ManipulatorOrderManager() def on_shutdown(self): global _selectors global _order_manager for selector in _selectors.values(): selector.destroy() _selectors.clear() if _order_manager: _order_manager.destroy() _order_manager = None
1,594
Python
31.55102
76
0.725847
omniverse-code/kit/exts/omni.kit.manipulator.selector/omni/kit/manipulator/selector/manipulator_selector.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 __future__ import annotations from typing import TYPE_CHECKING, Dict, Set import carb.events import carb.settings import omni.usd from pxr import Sdf if TYPE_CHECKING: from .manipulator_base import ManipulatorBase, ManipulatorOrderManager class ManipulatorSelector: def __init__(self, order_manager: ManipulatorOrderManager, usd_context_name: str): self._order_manager = order_manager self._usd_context_name = usd_context_name self._manipulators: Dict[str, Set[ManipulatorBase]] = {} self._usd_context = omni.usd.get_context(usd_context_name) self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop_by_type( int(omni.usd.StageEventType.SELECTION_CHANGED), self._on_stage_selection_event, name="ManipulatorSelector stage event", ) self._order_sub = self._order_manager.subscribe_to_orders_changed(self._on_orders_changed) self._refresh() def destroy(self): self._stage_event_sub = None if self._order_sub: self._order_manager.unsubscribe_to_orders_changed(self._order_sub) self._order_sub = None def __del__(self): self.destroy() def register_manipulator_instance(self, name: str, manipulator: ManipulatorBase): needs_sort = False if name not in self._manipulators: self._manipulators[name] = set() needs_sort = True self._manipulators[name].add(manipulator) if needs_sort: self._sort() self._refresh() def unregister_manipulator_instance(self, name: str, manipulator: ManipulatorBase): manipulator_set = self._manipulators.get(name, set()) manipulator_set.remove(manipulator) self._refresh() def _sort(self) -> bool: orders_dict = self._order_manager.orders_dict # sort by order sorted_manipulators = dict(sorted(self._manipulators.items(), key=lambda item: orders_dict.get(item[0], 0))) # compare keys to check order difference (direct dicts compare are equal if their content is same but in # different order) if sorted_manipulators != self._manipulators or list(sorted_manipulators.keys()) != list( self._manipulators.keys() ): self._manipulators = sorted_manipulators return True return False def _refresh(self): if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_selection_changed() def _on_stage_selection_event(self, event: carb.events.IEvent): self._on_selection_changed() def _on_selection_changed(self): selection = self._usd_context.get_selection().get_selected_prim_paths() selection_sdf = [Sdf.Path(path) for path in selection] for _, manipulators in self._manipulators.items(): handled = False for manipulator in manipulators: if manipulator.on_selection_changed(self._usd_context.get_stage(), selection_sdf): manipulator.enabled = True handled = True else: manipulator.enabled = False if handled: # Set selection_sdf to None to signal subsequent manipulator the selection has been handled # This is different from being empty [] selection_sdf = None def _on_orders_changed(self): if self._sort(): self._refresh()
3,991
Python
35.623853
116
0.646204
omniverse-code/kit/exts/omni.kit.manipulator.selector/omni/kit/manipulator/selector/__init__.py
from .extension import * from .manipulator_base import ManipulatorBase
71
Python
22.999992
45
0.830986
omniverse-code/kit/exts/omni.kit.manipulator.selector/omni/kit/manipulator/selector/manipulator_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 asyncio from abc import ABC, abstractmethod from typing import List, Union from pxr import Sdf, Usd from .extension import get_manipulator_selector class ManipulatorBase(ABC): """ Base class for prim manipulator that works with ManipulatorSelector. Instead of subscribing to UsdStageEvent for selection change, manipulator should inherit this class and implements all abstractmethods to support choosing between multiple types of prim manipulators based on their order and enable criterions. The order of the manipulator is specified at carb.settings path `/persistent/exts/omni.kit.manipulator.selector/orders/<name>"` """ def __init__(self, name: str, usd_context_name: str): """ Constructor. Args: name (str): name of the manipulator. It must match the <name> in the setting path specifies order. usd_context_name (str): name of the UsdContext this manipulator operates on. """ self._name = name self._selector = get_manipulator_selector(usd_context_name) self._register_task = None self._registered = None # do an async registration so that the child class __init__ has a chance to finish first. self._delayed_register() def destroy(self): if self._register_task and not self._register_task.done(): self._register_task.cancel() self._register_task = None if self._registered: self._selector.unregister_manipulator_instance(self._name, self) self._registered = False def __del__(self): self.destroy() @abstractmethod def on_selection_changed(self, stage: Usd.Stage, selection: Union[List[Sdf.Path], None], *args, **kwargs) -> bool: """ Function called when selection changes or types of prim manipulators are added or removed. Args: stage (Usd.Stage): the usd stage of which the selection change happens. It is the same as the stage of the UsdContext this manipulator works on. selection (Union[List[Sdf.Path], None]): the list of selected prim paths. If it is None (different from []), it means another manipulator with higher priority has handled the selection and this manipulator should yield. Return: True if selected prim paths can be handled by this manipulator and subsequent manipulator with higher order should yield. False if selected prim paths can not be handled. Function should always return False if `selection` is None. """ raise NotImplementedError("Derived class must implement on_selection_changed") return False @property @abstractmethod def enabled(self) -> bool: """ Returns if this manipulator is enabled. """ raise NotImplementedError('Derived class must implement "enabled" getter') return False @enabled.setter @abstractmethod def enabled(self, value: bool): """ Sets if this manipulator is enabled. A disabled manipulator should hide itself. """ raise NotImplementedError('Derived class must implement "enabled" setter') def _delayed_register(self): async def register_manipulator(): self._selector.register_manipulator_instance(self._name, self) self._registered = True self._register_task = asyncio.ensure_future(register_manipulator())
4,038
Python
38.990099
131
0.662704
omniverse-code/kit/exts/omni.kit.manipulator.selector/omni/kit/manipulator/selector/tests/test_manipulator.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, Union from omni.kit.manipulator.prim.prim_transform_manipulator import PrimTransformManipulator from omni.kit.manipulator.transform import get_default_style from omni.kit.manipulator.transform.settings_constants import c from omni.kit.viewport.registry import RegisterScene from pxr import Sdf, Usd, UsdGeom # Creates a test manipulator that is white and half in size when selecting a mesh class PrimTransformManipulatorMeshTest(PrimTransformManipulator): def __init__(self, usd_context_name: str = "", viewport_api=None): super().__init__( usd_context_name=usd_context_name, viewport_api=viewport_api, name="omni.kit.manipulator.test_mesh_prim", size=0.5, ) def _create_local_global_styles(self): super()._create_local_global_styles() global_style = get_default_style() global_style["Translate.Axis::x"]["color"] = 0xFFFFFFFF global_style["Translate.Axis::y"]["color"] = 0xFFFFFFFF global_style["Translate.Axis::z"]["color"] = 0xFFFFFFFF self._styles[c.TRANSFORM_MODE_GLOBAL] = global_style def on_selection_changed(self, stage: Usd.Stage, selection: Union[List[Sdf.Path], None], *args, **kwargs) -> bool: if selection is None: self.model.on_selection_changed([]) return False self.model.on_selection_changed(selection) for path in selection: prim = stage.GetPrimAtPath(path) if prim.IsA(UsdGeom.Mesh): return True return False class PrimTransformManipulatorScene: def __init__(self, desc: dict): usd_context_name = desc.get("usd_context_name") self.__transform_manip_override = PrimTransformManipulatorMeshTest( usd_context_name=usd_context_name, viewport_api=desc.get("viewport_api") ) def destroy(self): if self.__transform_manip_override: self.__transform_manip_override.destroy() self.__transform_manip_override = None # PrimTransformManipulator & TransformManipulator don't have their own visibility @property def visible(self): return True @visible.setter def visible(self, value): pass @property def categories(self): return ("manipulator",) @property def name(self): return "Test Mesh Prim Transform" class TransformManipulatorRegistry: def __init__(self): self._scene = RegisterScene(PrimTransformManipulatorScene, "omni.kit.manipulator.test_mesh_prim") def __del__(self): self.destroy() def destroy(self): self._scene = None
3,111
Python
32.826087
118
0.677274
omniverse-code/kit/exts/omni.kit.manipulator.selector/omni/kit/manipulator/selector/tests/test_manipulator_selector.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 inspect import logging import os from pathlib import Path from omni.kit.test.teamcity import is_running_in_teamcity import sys import unittest import carb import carb.input import carb.settings import omni.kit.commands import omni.kit.ui_test as ui_test import omni.kit.undo import omni.kit.viewport.utility import omni.usd from omni.kit.manipulator.prim.settings_constants import Constants as prim_c from omni.kit.manipulator.transform.settings_constants import c from omni.kit.test_helpers_gfx.compare_utils import ComparisonMetric, capture_and_compare from omni.kit.ui_test import Vec2 from omni.ui.tests.test_base import OmniUiTest CURRENT_PATH = Path(f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data") OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()).resolve().absolute() logger = logging.getLogger(__name__) class TestSelector(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._context = omni.usd.get_context() self._selection = self._context.get_selection() self._settings = carb.settings.get_settings() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests").joinpath("golden") self._usd_scene_dir = CURRENT_PATH.absolute().resolve().joinpath("tests").joinpath("usd") await self._setup() # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def _snapshot(self, golden_img_name: str = "", threshold: float = 2e-4): await ui_test.human_delay() test_fn_name = "" for frame_info in inspect.stack(): if os.path.samefile(frame_info[1], __file__): test_fn_name = frame_info[3] golden_img_name = f"{test_fn_name}.{golden_img_name}.png" # Because we're testing RTX renderered pixels, use a better threshold filter for differences diff = await capture_and_compare( golden_img_name, threshold=threshold, output_img_dir=OUTPUTS_DIR, golden_img_dir=self._golden_img_dir, metric=ComparisonMetric.MEAN_ERROR_SQUARED, ) self.assertLessEqual( diff, threshold, f"The generated image {golden_img_name} has a difference of {diff}, but max difference is {threshold}", ) async def _setup( self, scene_file: str = "test_scene.usda", enable_toolbar: bool = False, ): usd_path = self._usd_scene_dir.joinpath(scene_file) success, error = await self._context.open_stage_async(str(usd_path)) self.assertTrue(success, error) # move the mouse out of the way await ui_test.emulate_mouse_move(Vec2(0, 0)) await ui_test.human_delay() self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT) self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL) self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL) self._settings.set(c.TRANSFORM_OP_SETTING, c.TRANSFORM_OP_MOVE) self._settings.set("/app/viewport/snapEnabled", False) self._settings.set("/persistent/app/viewport/snapToSurface", False) self._settings.set("/exts/omni.kit.manipulator.prim/tools/enabled", enable_toolbar) @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_multi_manipulator_selector(self): from .test_manipulator import PrimTransformManipulatorMeshTest, TransformManipulatorRegistry # Select the /Cube, should show default manipulator self._selection.set_selected_prim_paths(["/Cube"], True) await ui_test.human_delay() await self._snapshot("default_mesh") # Select the /Xform, should show default manipulator self._selection.set_selected_prim_paths(["/World"], True) await ui_test.human_delay() await self._snapshot("default_xform") # Register the test manipulator that is specialized for Mesh active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() if hasattr(active_vp_window, "legacy_window"): test_manipulator = PrimTransformManipulatorMeshTest() else: test_manipulator = TransformManipulatorRegistry() await ui_test.human_delay() # Select the /Cube, should show overridden manipulator self._selection.set_selected_prim_paths(["/Cube"], True) await ui_test.human_delay() await self._snapshot("overridden_mesh") # Select the /Xform, should still show default manipulator as it's not a mesh self._selection.set_selected_prim_paths(["/World"], True) await ui_test.human_delay() await self._snapshot("default_xform") # Remove the overridden manipulator test_manipulator.destroy() test_manipulator = None # Select the /Cube, should revert back to default manipulator self._selection.set_selected_prim_paths(["/Cube"], True) await ui_test.human_delay() await self._snapshot("default_mesh")
5,734
Python
38.826389
116
0.679456
omniverse-code/kit/exts/omni.usd.schema.semantics/pxr/Semantics/__init__.py
# #==== # Copyright (c) 2018, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys import platform py38 = (3,8) current_version = sys.version_info if platform.system() == "Windows" and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _semanticAPI from pxr import Tf Tf.PrepareModule(_semanticAPI, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
1,693
Python
28.719298
100
0.710573
omniverse-code/kit/exts/omni.rtx.index_composite/omni/rtx/index_composite/tests/nvindex_rtx_composite_render_test.py
#!/usr/bin/env python3 import carb import omni.kit.commands import omni.kit.test import omni.usd from omni.rtx.tests import RtxTest, testSettings, postLoadTestSettings from omni.rtx.tests.test_common import set_transform_helper, wait_for_update from omni.kit.test_helpers_gfx.compare_utils import ComparisonMetric from pxr import Sdf, Gf, UsdVol from pathlib import Path EXTENSION_DIR = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TESTS_DIR = EXTENSION_DIR.joinpath('data', 'tests') USD_DIR = TESTS_DIR.joinpath('usd') GOLDEN_IMAGES_DIR = TESTS_DIR.joinpath('golden') VOLUMES_DIR = TESTS_DIR.joinpath('volumes') OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) # This class is auto-discoverable by omni.kit.test class IndexRtxCompositeRenderTest(RtxTest): WINDOW_SIZE = (512, 512) THRESHOLD = 1e-6 async def setUp(self): await super().setUp() self.set_settings(testSettings) self.ctx.new_stage() self.add_dir_light() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) # Overridden with custom paths async def capture_and_compare(self, img_subdir: Path = "", golden_img_name=None, threshold=THRESHOLD, metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED): golden_img_dir = GOLDEN_IMAGES_DIR.joinpath(img_subdir) output_img_dir = OUTPUTS_DIR.joinpath(img_subdir) if not golden_img_name: golden_img_name = f"{self.__test_name}.png" return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric) # Overridden with custom paths def open_usd(self, usdSubpath: Path): path = USD_DIR.joinpath(usdSubpath) self.ctx.open_stage(str(path)) async def run_imge_test(self, usd_file: str, image_name: str, fn = None, threshold=THRESHOLD): if usd_file: self.open_usd(usd_file) if fn: fn() await wait_for_update() await self.capture_and_compare(golden_img_name=image_name, threshold=threshold) # # The tests # async def test_render_torus_volume_with_geometry(self): self.open_usd('torus-volume-with-geometry.usda') settings = carb.settings.get_settings() for depth_mode in [0, 1, 2, 3]: settings.set("/rtx/index/compositeDepthMode", depth_mode) await wait_for_update() # Non-stable depth mode is more noisy threshold = (1e-2 if depth_mode == 2 else IndexRtxCompositeRenderTest.THRESHOLD) await self.run_imge_test(None, f"nvindex-torus-composite-depth-mode-{depth_mode}.png", threshold=threshold)
2,775
Python
35.051948
119
0.672793
omniverse-code/kit/exts/omni.rtx.index_composite/omni/rtx/index_composite/tests/__init__.py
from .nvindex_rtx_composite_render_test import *
49
Python
23.999988
48
0.795918
omniverse-code/kit/exts/omni.kit.usd_undo/omni/kit/usd_undo/__init__.py
from .layer_undo import *
26
Python
12.499994
25
0.730769
omniverse-code/kit/exts/omni.kit.usd_undo/omni/kit/usd_undo/layer_undo.py
from pxr import Sdf, Usd class UsdLayerUndo: class Key: def __init__(self, path, info): self.path = path self.info = info def __init__(self, layer: Sdf.Layer): self._layer = layer self.reset() def reserve(self, path: Sdf.Path, info=None): # Check if it's included by any added paths path = Sdf.Path(path) for added_key in self._paths: if path.HasPrefix(added_key.path) and added_key.info is None: return # Check if it includes any added paths if info is None: for added_key in self._paths: if added_key.path.HasPrefix(path): self._paths.pop(added_key) # If it doesn't exist, it's new spec. No need to reserve anything. key = self.Key(path, info) if not self._layer.GetObjectAtPath(path): self._paths[key] = True return else: self._paths[key] = False # Reserve existing data if info is None: Sdf.CreatePrimInLayer(self._reserve_layer, path.GetParentPath()) Sdf.CopySpec(self._layer, path, self._reserve_layer, path) else: # We must know attribute type to create it in layer. So we don't handle it here. if path.IsPropertyPath(): raise Exception("Property info is not supported.") spec = self._layer.GetObjectAtPath(path) Sdf.CreatePrimInLayer(self._reserve_layer, path) reserve_spec = self._reserve_layer.GetObjectAtPath(path) reserve_spec.SetInfo(info, spec.GetInfo(info)) def undo(self): batch_edit = Sdf.BatchNamespaceEdit() for key, new_spec in self._paths.items(): spec = self._layer.GetObjectAtPath(key.path) reserve_spec = self._reserve_layer.GetObjectAtPath(key.path) if new_spec: # Remove new added spec if spec: batch_edit.Add(Sdf.NamespaceEdit.Remove(key.path)) elif key.info is None: # Restore spec Sdf.CopySpec(self._reserve_layer, key.path, self._layer, key.path) else: # Restore spec info spec.SetInfo(key.info, reserve_spec.GetInfo(key.info)) self._layer.Apply(batch_edit) def reset(self): self._reserve_layer = Sdf.Layer.CreateAnonymous() self._paths = {} class UsdEditTargetUndo: def __init__(self, edit_target: Usd.EditTarget): self._edit_target = edit_target self._layer_undo = UsdLayerUndo(self._edit_target.GetLayer()) def reserve(self, path: Sdf.Path, info=None): self._layer_undo.reserve(path, info) def undo(self): self._layer_undo.undo() def reset(self): self._layer_undo.reset()
2,883
Python
32.149425
92
0.571627
omniverse-code/kit/exts/omni.kit.usd_undo/omni/kit/usd_undo/tests/__init__.py
from .test import *
20
Python
9.499995
19
0.7
omniverse-code/kit/exts/omni.kit.usd_undo/omni/kit/usd_undo/tests/test.py
import omni.kit.test from ..layer_undo import * from pxr import Sdf, Usd, UsdGeom, Kind, Gf class TestUsdUndo(omni.kit.test.AsyncTestCase): async def test_layer_undo(self): stage = Usd.Stage.CreateInMemory() usd_undo = UsdEditTargetUndo(stage.GetEditTarget()) mesh = UsdGeom.Mesh.Define(stage, "/root") mesh.CreateNormalsAttr().Set([Gf.Vec3f(1, 0, 0)]) mesh.SetNormalsInterpolation("constant") model = Usd.ModelAPI(mesh) model.SetKind(Kind.Tokens.group) org_stage_str = stage.ExportToString() print("Original stage:") print(org_stage_str) usd_undo.reserve("/root.normals") mesh.GetNormalsAttr().Set([Gf.Vec3f(0, 1, 0)]) mesh.SetNormalsInterpolation("faceVarying") usd_undo.reserve("/root", "kind") model.SetKind(Kind.Tokens.component) usd_undo.reserve("/root/newPrim") stage.DefinePrim("/root/newPrim") modified_stage_str = stage.ExportToString() print("Modified stage:") print(modified_stage_str) assert org_stage_str != modified_stage_str usd_undo.undo() undone_stage_str = stage.ExportToString() print("Undone stage:") print(undone_stage_str) assert org_stage_str == undone_stage_str
1,311
Python
28.818181
59
0.630816
omniverse-code/kit/exts/omni.kit.manipulator.selection/omni/kit/manipulator/selection/__init__.py
# Expose these for easier import via from omni.kit.manipulator.selection import XXX from .manipulator import SelectionManipulator, SelectionMode
145
Python
47.666651
83
0.848276
omniverse-code/kit/exts/omni.kit.manipulator.selection/omni/kit/manipulator/selection/model.py
# Copyright (c) 2021-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 omni.ui import scene as sc from typing import List, Sequence, Union class SelectionShapeModel(sc.AbstractManipulatorModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__items = { "ndc_start": (sc.AbstractManipulatorItem(), 2), "ndc_current": (sc.AbstractManipulatorItem(), 2), "ndc_rect": (sc.AbstractManipulatorItem(), 4), "mode": (sc.AbstractManipulatorItem(), 1), "live_update": (sc.AbstractManipulatorItem(), 1) } self.__ndc_ret_item = self.__items.get('ndc_rect')[0] self.__values = {item: [] for item, _ in self.__items.values()} def __validate_arguments(self, name: Union[str, sc.AbstractManipulatorItem], values: Sequence[Union[int, float]] = None) -> sc.AbstractManipulatorItem: if isinstance(name, sc.AbstractManipulatorItem): return name item, expected_len = self.__items.get(name, (None, None)) if item is None: raise KeyError(f"SelectionShapeModel doesn't understand values of {name}") if values and len(values) != expected_len: raise ValueError(f"SelectionShapeModel {name} takes {expected_len} values, got {len(values)}") return item def get_item(self, name: str) -> sc.AbstractManipulatorItem(): return self.__items.get(name, (None, None))[0] def set_ints(self, name: str, values: Sequence[int]): item = self.__validate_arguments(name, values) self.__values[item] = values def set_floats(self, name: str, values: Sequence[int]): item = self.__validate_arguments(name, values) self.__values[item] = values def get_as_ints(self, name: str) -> List[int]: item = self.__validate_arguments(name) return self.__values[item] def get_as_floats(self, name: str) -> List[float]: item = self.__validate_arguments(name) if item == self.__ndc_ret_item: ndc_start, ndc_end = self.__values[self.get_item('ndc_start')], self.__values[self.get_item('ndc_current')] if not ndc_start: return [] if not ndc_end: ndc_end = ndc_start min_x = min(ndc_start[0], ndc_end[0]) max_x = max(ndc_start[0], ndc_end[0]) min_y = min(ndc_start[1], ndc_end[1]) max_y = max(ndc_start[1], ndc_end[1]) return [min_x, min_y, max_x, max_y] return self.__values[item]
2,936
Python
42.83582
155
0.620232
omniverse-code/kit/exts/omni.kit.manipulator.selection/omni/kit/manipulator/selection/manipulator.py
# Copyright (c) 2021-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__ = ['SelectionManipulator', 'SelectionMode'] import carb.input from omni.ui import scene as sc from .model import SelectionShapeModel from pxr import Gf from typing import List import weakref class SelectionMode: REPLACE = 0 APPEND = 1 REMOVE = 2 def _optional_bool(model: sc.AbstractManipulatorModel, item: str, default_value: bool = False): values = model.get_as_ints(item) return values[0] if values else default_value class _KeyDown: def __init__(self): self.__input = carb.input.acquire_input_interface() def test(self, key_a, key_b): if self.__input.get_keyboard_button_flags(None, key_a) & carb.input.BUTTON_FLAG_DOWN: return True if self.__input.get_keyboard_button_flags(None, key_b) & carb.input.BUTTON_FLAG_DOWN: return True return False class _SelectionPreventer(sc.GestureManager): '''Class to explicitly block selection in favor of alt-orbit when alt-dragging''' def can_be_prevented(self, gesture): alt_down = _KeyDown().test(carb.input.KeyboardInput.LEFT_ALT, carb.input.KeyboardInput.RIGHT_ALT) if alt_down: if getattr(gesture, 'name', None) == "SelectionDrag": return True # Never prevent in the middle or at the end of drag return ( gesture.state != sc.GestureState.CHANGED and gesture.state != sc.GestureState.ENDED and gesture.state != sc.GestureState.CANCELED ) def should_prevent(self, gesture, preventer): alt_down = _KeyDown().test(carb.input.KeyboardInput.LEFT_ALT, carb.input.KeyboardInput.RIGHT_ALT) if alt_down: name = getattr(gesture, 'name', None) if name == "TumbleGesture": return False if name == "SelectionDrag": return True return super().should_prevent(gesture, preventer) class _SelectionGesture: @classmethod def __get_selection_mode(self): key_down = _KeyDown() shift_down = key_down.test(carb.input.KeyboardInput.LEFT_SHIFT, carb.input.KeyboardInput.RIGHT_SHIFT) if shift_down: return SelectionMode.APPEND ctrl_down = key_down.test(carb.input.KeyboardInput.LEFT_CONTROL, carb.input.KeyboardInput.RIGHT_CONTROL) if ctrl_down: return SelectionMode.REMOVE # alt_down = key_down.test(carb.input.KeyboardInput.LEFT_ALT, carb.input.KeyboardInput.RIGHT_ALT) return SelectionMode.REPLACE @classmethod def _set_mouse(self, model: sc.AbstractManipulatorModel, ndc_mouse: List[float], is_start: bool = False): if is_start: model.set_floats('ndc_start', ndc_mouse) model.set_ints('mode', [self.__get_selection_mode()]) elif _optional_bool(model, 'live_update'): model.set_ints('mode', [self.__get_selection_mode()]) model.set_floats('ndc_current', ndc_mouse) @classmethod def _on_ended(self, manipulator: sc.Manipulator): # This is needed to not fight with alt+left-mouse camera orbit when not blocking alt explicitly # manipulator.invalidate() model = manipulator.model model.set_floats('ndc_start', []) model.set_floats('ndc_current', []) model.set_ints('mode', []) model._item_changed(model.get_item('ndc_rect')) class _DragGesture(sc.DragGesture): def __init__(self, manipulator: sc.Manipulator, *args, **kwargs): super().__init__(*args, **kwargs) self.__manipulator = manipulator def on_began(self): _SelectionGesture._set_mouse(self.__manipulator.model, self.sender.gesture_payload.mouse, True) def on_changed(self): model = self.__manipulator.model _SelectionGesture._set_mouse(model, self.sender.gesture_payload.mouse) model._item_changed(model.get_item('ndc_rect')) def on_ended(self): # Track whether on_changed has been called. # When it has: this drag is a drag. # When it hasn't: this drag is actually a click. if self.state != sc.GestureState.ENDED: return _SelectionGesture._on_ended(self.__manipulator) class _ClickGesture(sc.ClickGesture): def __init__(self, manipulator: sc.Manipulator, *args, **kwargs): super().__init__(*args, **kwargs) self.__manipulator = manipulator def on_ended(self): model = self.__manipulator.model _SelectionGesture._set_mouse(model, self.sender.gesture_payload.mouse, True) model._item_changed(model.get_item('ndc_rect')) _SelectionGesture._on_ended(self.__manipulator) class SelectionManipulator(sc.Manipulator): def __init__(self, style: dict = None, *args, **kwargs): applied_style = { 'as_rect': True, 'thickness': 2.0, 'color': (1.0, 1.0, 1.0, 0.2), 'inner_color': (1.0, 1.0, 1.0, 0.2) } if style: applied_style.update(style) super().__init__(*args, **kwargs) self.__as_rect = applied_style['as_rect'] self.__outline_color = applied_style['color'] self.__inner_color = applied_style['inner_color'] self.__thickness = applied_style['thickness'] self.__polygons, self.__transform = [], None # Provide some defaults if not self.model: self.model = SelectionShapeModel() self.gestures = [] def on_build(self): if self.__transform: self.__transform.clear() self.__polygons = [] sc.Screen(gestures=self.gestures or [ _DragGesture(weakref.proxy(self), manager=_SelectionPreventer(), name='SelectionDrag'), _ClickGesture(weakref.proxy(self), name='SelectionClick'), ]) self.__transform = sc.Transform(look_at=sc.Transform.LookAt.CAMERA) def __draw_shape(self, start, end, as_rect): if as_rect: avg_z = (start[2] + end[2]) * 0.5 points = ((start[0], start[1], avg_z), (end[0], start[1], avg_z), (end[0], end[1], avg_z), (start[0], end[1], avg_z)) else: if self.__polygons: points = self.__polygons[0].positions + [end] else: points = start, end # FIXME: scene.ui needs a full rebuild on this case self.__transform.clear() self.__polygons = [] npoints = len(points) visible = npoints >= 3 if not self.__polygons: with self.__transform: faces = [x for x in range(npoints)] # TODO: omni.ui.scene Shouldn't requires redundant color & thickness for constant color if self.__inner_color: self.__polygons.append( sc.PolygonMesh(points, [self.__inner_color]*npoints, [npoints], faces, wireframe=False, visible=visible) ) if self.__thickness and self.__outline_color: self.__polygons.append( sc.PolygonMesh(points, [self.__outline_color]*npoints, [npoints], faces, wireframe=True, thicknesses=[self.__thickness]*npoints, visible=visible) ) else: for poly in self.__polygons: poly.positions = points poly.visible = visible def on_model_updated(self, item): model = self.model if item != model.get_item('ndc_rect'): return ndc_rect = model.get_as_floats('ndc_rect') if ndc_rect: ndc_depth = 1 start = self.__transform.transform_space(sc.Space.NDC, sc.Space.OBJECT, (ndc_rect[0], ndc_rect[1], ndc_depth)) end = self.__transform.transform_space(sc.Space.NDC, sc.Space.OBJECT, (ndc_rect[2], ndc_rect[3], ndc_depth)) self.__draw_shape(start, end, self.__as_rect) else: self.__transform.clear() self.__polygons = []
8,490
Python
38.129032
169
0.601649
omniverse-code/kit/exts/omni.kit.manipulator.selection/omni/kit/manipulator/selection/tests/test_selection_manipulator.py
## Copyright (c) top_left[0]22, 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__ = ['TestSelectionManipulator'] import omni.kit.test from ..manipulator import SelectionManipulator from .test_scene_ui_base import TestOmniUiScene from omni.ui import scene as sc class TestSelectionManipulator(TestOmniUiScene): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__ndc_rects = [] self.__last_rect = None def on_item_changed(self, model, item): # ndc_rect should be part of the model, always ndc_rect_item = model.get_item('ndc_rect') self.assertIsNotNone(ndc_rect_item) # Ignore other signals if item != ndc_rect_item: return # Get the values ndc_rect = model.get_as_floats(ndc_rect_item) self.assertIsNotNone(ndc_rect) # NDC rect cannot be none, but it can be empty (on mouse-up) if ndc_rect != []: # ndc_rect should be totally ordered: top-left, bottom-right self.assertLess(ndc_rect[0], ndc_rect[2]) self.assertLess(ndc_rect[1], ndc_rect[3]) # Save the lat mouse for a test later self.__last_rect = ndc_rect def ndc_rects_match(self): self.assertIsNotNone(self.__last_rect) self.__ndc_rects.append(self.__last_rect) self.__last_rect = None if len(self.__ndc_rects) > 1: self.assertEqual(self.__ndc_rects[0], self.__ndc_rects[-1]) async def test_ortho_selection(self): window, scene_view = await self.create_ortho_scene_view('test_ortho_selection') with scene_view.scene: manipulator = SelectionManipulator() sc.Arc(radius=25, wireframe=True, tesselation = 36 * 3, thickness = 2) manip_sub = manipulator.model.subscribe_item_changed_fn(self.on_item_changed) top_left = (20, 40) bottom_right = (window.width-top_left[0], window.height-60) # Test dragging top-left to bottom-right await self.wait_frames() await self.mouse_dragging_test('test_ortho_selection', (top_left[0], top_left[1]), (bottom_right[0], bottom_right[1])) await self.wait_frames() # Ortho and Perspective should stil have same selection box self.ndc_rects_match() # Test dragging bottom-right to top-left await self.wait_frames() await self.mouse_dragging_test('test_ortho_selection', (bottom_right[0], bottom_right[1]), (top_left[0], top_left[1])) await self.wait_frames() # Ortho and Perspective should stil have same selection box self.ndc_rects_match() # Test dragging top-right to bottom-left await self.wait_frames() await self.mouse_dragging_test('test_ortho_selection', (bottom_right[0], top_left[1]), (top_left[0], bottom_right[1])) await self.wait_frames() # Should stil have same selection box self.ndc_rects_match() # Test dragging bottom-left to top-right await self.wait_frames() await self.mouse_dragging_test('test_ortho_selection', (top_left[0], bottom_right[1]), (bottom_right[0], top_left[1])) await self.wait_frames() async def test_persepctive_selection(self): window, scene_view = await self.create_perspective_scene_view('test_persepctive_selection') with scene_view.scene: manipulator = SelectionManipulator({ 'thickness': 5.0, 'color': (0.2, 0.2, 0.8, 0.8), 'inner_color': (0.2, 0.6, 0.8, 0.4) }) sc.Arc(radius=25, wireframe=True, tesselation = 36 * 3, thickness = 2) manip_sub = manipulator.model.subscribe_item_changed_fn(self.on_item_changed) top_left = (20, 40) bottom_right = (window.width-top_left[0], window.height-60) # Test dragging bottom-left to top-right await self.wait_frames() await self.mouse_dragging_test('test_persepctive_selection', (top_left[0], bottom_right[1]), (bottom_right[0], top_left[1])) await self.wait_frames() # Should stil have same selection box self.ndc_rects_match() # Test dragging top-right to bottom-left await self.wait_frames() await self.mouse_dragging_test('test_persepctive_selection', (bottom_right[0], top_left[1]), (top_left[0], bottom_right[1])) await self.wait_frames() # Should stil have same selection box self.ndc_rects_match() # Test dragging bottom-right to top-left await self.wait_frames() await self.mouse_dragging_test('test_persepctive_selection', (bottom_right[0], bottom_right[1]), (top_left[0], top_left[1])) await self.wait_frames() # Ortho and Perspective should stil have same selection box self.ndc_rects_match() # Test dragging top-left to bottom-right await self.wait_frames() await self.mouse_dragging_test('test_persepctive_selection', (top_left[0], top_left[1]), (bottom_right[0], bottom_right[1])) await self.wait_frames() # Ortho and Perspective should stil have same selection box self.ndc_rects_match()
5,588
Python
40.708955
132
0.635648
omniverse-code/kit/exts/omni.kit.manipulator.selection/omni/kit/manipulator/selection/tests/__init__.py
from .test_selection_model import TestSelectionModel from .test_selection_manipulator import TestSelectionManipulator
118
Python
38.666654
64
0.881356
omniverse-code/kit/exts/omni.kit.manipulator.selection/omni/kit/manipulator/selection/tests/test_scene_ui_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. ## from omni.ui.tests.test_base import OmniUiTest from omni.ui.tests.compare_utils import capture_and_compare from omni.kit.ui_test.input import emulate_mouse, emulate_mouse_slow_move, human_delay from omni.kit.ui_test import Vec2 from omni.ui import scene as sc import omni.ui as ui import omni.appwindow import omni.kit.app import carb from carb.input import MouseEventType from pxr import Gf from pathlib import Path async def emulate_mouse_drag_and_drop(start_pos, end_pos, right_click=False, human_delay_speed: int = 4, end_with_up: bool = True): """Emulate Mouse Drag & Drop. Click at start position and slowly move to end position.""" await emulate_mouse(MouseEventType.MOVE, start_pos) await emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN if right_click else MouseEventType.LEFT_BUTTON_DOWN) await human_delay(human_delay_speed) await emulate_mouse_slow_move(start_pos, end_pos, human_delay_speed=human_delay_speed) if end_with_up: await emulate_mouse(MouseEventType.RIGHT_BUTTON_UP if right_click else MouseEventType.LEFT_BUTTON_UP) await human_delay(human_delay_speed) def _flatten_matrix(matrix: Gf.Matrix4d): return [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]] class TestOmniUiScene(OmniUiTest): DATA_PATH = None async def setUp(self, ext_id: str = None): await super().setUp() self.__width, self.__height = None, None # If no extension-id, assume standard xxx.xxx.xxx.tests.current_test if ext_id is None: ext_id = '.'.join(self.__module__.split('.')[0:-2]) TestOmniUiScene.DATA_PATH = Path(carb.tokens.get_tokens_interface().resolve("${" + ext_id + "}")).absolute().resolve() self.__golden_img_dir = TestOmniUiScene.DATA_PATH.joinpath("data", "tests") # After running each test async def tearDown(self): self.__golden_img_dir = None await super().tearDown() async def setup_test_area_and_input(self, title: str, width: int = 256, height: int = 256): self.__width, self.__height = width, height await self.create_test_area(width=width, height=height) app_window = omni.appwindow.get_default_app_window() app_window.set_input_blocking_state(carb.input.DeviceType.MOUSE, False) return ui.Window(title=title, width=width, height=height, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE) async def create_ortho_scene_view(self, title='test', width = 256, height = 256, ortho_size = 100, z_pos = -5): window = await self.setup_test_area_and_input(title, width, height) with window.frame: # Camera matrices projection = self.ortho_projection() view = sc.Matrix44.get_translation_matrix(0, 0, z_pos) scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH, model=sc.CameraModel(projection, view)) return window, scene_view async def create_perspective_scene_view(self, title='test', width = 256, height = 256, field_of_view = 25, distance = 100): window = await self.setup_test_area_and_input(title, width, height) with window.frame: # Camera matrices projection = self.perspective_projection(field_of_view) eye = Gf.Vec3d(distance, distance, distance) target = Gf.Vec3d(0, 0, 0) forward = (target - eye).GetNormalized() up = Gf.Vec3d(0, 0, 1).GetComplement(forward) view = _flatten_matrix(Gf.Matrix4d().SetLookAt(eye, target, up)) scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH, model=sc.CameraModel(projection, view)) return window, scene_view async def finish_scene_ui_test(self, wait_frames = 15): for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() return await self.finalize_test(golden_img_dir=self.__golden_img_dir) def ortho_projection(self, ortho_size: float = 100, aspect_ratio: float = None, near: float = 0.001, far: float = 10000): if aspect_ratio is None: aspect_ratio = self.__width / self.__height if aspect_ratio > 1: ortho_half_height = ortho_size * 0.5 ortho_half_width = ortho_half_height * aspect_ratio else: ortho_half_width = ortho_size * 0.5 ortho_half_height = ortho_half_width * aspect_ratio frustum = Gf.Frustum() frustum.SetOrthographic(-ortho_half_width, ortho_half_width, -ortho_half_height, ortho_half_height, near, far) return _flatten_matrix(frustum.ComputeProjectionMatrix()) def perspective_projection(self, field_of_view: float = 20, aspect_ratio: float = None, near: float = 0.001, far: float = 10000): if aspect_ratio is None: aspect_ratio = self.__width / self.__height frustum = Gf.Frustum() frustum.SetPerspective(field_of_view / aspect_ratio, aspect_ratio, near, far) return _flatten_matrix(frustum.ComputeProjectionMatrix()) @property def golden_img_dir(self): return self.__golden_img_dir @property def human_delay(self): return 4 async def wait_frames(self, frames: int = 15): for _ in range(10): await omni.kit.app.get_app().next_update_async() async def end_mouse(self): await emulate_mouse(MouseEventType.LEFT_BUTTON_UP) await human_delay(self.human_delay) async def mouse_dragging_test(self, test_name, start_pos, end_pos): threshold = 10 start_pos = Vec2(start_pos[0], start_pos[1]) end_pos = Vec2(end_pos[0], end_pos[1]) # Do a drag operation await emulate_mouse_drag_and_drop(start_pos, end_pos, human_delay_speed = self.human_delay, end_with_up=False) # Capture while mouse is down diff1 = await capture_and_compare(f'{test_name}_drag.png', threshold, self.golden_img_dir) # End the drag await self.end_mouse() # And cature again with mouse up diff2 = await capture_and_compare(f'{test_name}_done.png', threshold, self.golden_img_dir) if diff1 != 0: carb.log_warn(f"[{test_name}_drag.png] the generated image has difference {diff1}") if diff2 != 0: carb.log_warn(f"[{test_name}_done.png] the generated image has difference {diff2}") self.assertTrue( (diff1 is not None and diff1 < threshold), msg=f"The image for test '{test_name}_drag.png' doesn't match the golden one. Difference of {diff1} is is not less than threshold of {threshold}.", ) self.assertTrue( (diff2 is not None and diff2 < threshold), msg=f"The image for test '{test_name}_done.png' doesn't match the golden one. Difference of {diff2} is is not less than threshold of {threshold}.", )
7,634
Python
44.177515
159
0.653262
omniverse-code/kit/exts/omni.kit.manipulator.selection/omni/kit/manipulator/selection/tests/test_selection_model.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__ = ['TestSelectionModel'] import omni.kit.test from ..model import SelectionShapeModel class TestSelectionModel(omni.kit.test.AsyncTestCase): async def test_ortho_selection(self): model = SelectionShapeModel() # Standard item should exist ndc_start_item = model.get_item('ndc_start') self.assertIsNotNone(ndc_start_item) # Standard item should exist ndc_current_item = model.get_item('ndc_current') self.assertIsNotNone(ndc_current_item) # Standard item should exist ndc_rect_item = model.get_item('ndc_rect') self.assertIsNotNone(ndc_rect_item) # Test setting only a start result in no rect model.set_floats(ndc_start_item, [1, 2]) ndc_rect = model.get_as_floats(ndc_rect_item) self.assertEqual(ndc_rect, [1, 2, 1, 2]) # Test setting a start and current results in a rect model.set_floats(ndc_start_item, [1, 2]) model.set_floats(ndc_current_item, [3, 4]) ndc_rect = model.get_as_floats(ndc_rect_item) self.assertEqual(ndc_rect, [1, 2, 3, 4]) # Changing the order should result in the same sorted top-left, bottom-right rect model.set_floats(ndc_start_item, [3, 4]) model.set_floats(ndc_current_item, [1, 2]) ndc_rect = model.get_as_floats(ndc_rect_item) self.assertEqual(ndc_rect, [1, 2, 3, 4])
1,847
Python
36.714285
89
0.674066
omniverse-code/kit/exts/omni.kit.filebrowser_column.tags/omni/kit/filebrowser_column/tags/__init__.py
from .tags_extension import TagsExtension
42
Python
20.49999
41
0.857143
omniverse-code/kit/exts/omni.kit.filebrowser_column.tags/omni/kit/filebrowser_column/tags/tags_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. # from .tags_delegate import TagsDelegate from omni.kit.widget.filebrowser import ColumnDelegateRegistry import omni.ext import carb class TagsExtension(omni.ext.IExt): def on_startup(self, ext_id): self._subscription = ColumnDelegateRegistry().register_column_delegate("Tags", TagsDelegate) def on_shutdown(self): self._subscription = None
799
Python
37.095236
100
0.783479
omniverse-code/kit/exts/omni.kit.filebrowser_column.tags/omni/kit/filebrowser_column/tags/tags_delegate.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.tagging import OmniKitTaggingDelegate, get_tagging_instance from omni.kit.widget.filebrowser import ColumnItem from omni.kit.widget.filebrowser import AbstractColumnDelegate import asyncio import carb import functools import omni.client import omni.ui as ui import traceback def handle_exception(func): """ Decorator to print exception in async functions """ @functools.wraps(func) async def wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except asyncio.CancelledError: pass except Exception as e: carb.log_error(f"Exception when async '{func}'") carb.log_error(f"{e}") carb.log_error(f"{traceback.format_exc()}") return wrapper class TagsDelegate(AbstractColumnDelegate): """ The object that adds the new column "Access" to fileblowser. The columns displays access flags. """ @property def initial_width(self): """The width of the column""" return ui.Pixel(40) def build_header(self): """Build the header""" ui.Label("Tags", style_type_name_override="TreeView.Header") @handle_exception async def build_widget(self, item: ColumnItem): """ Build the widget for the given item. Works inside Frame in async mode. Once the widget is created, it will replace the content of the frame. It allow to await something for a while and create the widget when the result is available. """ tagging = get_tagging_instance() if tagging is None: carb.log_warn("Tagging client not found") return # sanitize relative item paths path = item.path.replace("/./", "/") results = await tagging.get_tags_async([path]) if results is None: results = [] ordered_tags = tagging.ordered_tag_list(results) tag_string = ", ".join(ordered_tags) tooltip_string = "\n".join(ordered_tags) ui.Label(tag_string, style_type_name_override="TreeView.Item", tooltip=tooltip_string)
2,560
Python
31.417721
94
0.666797
omniverse-code/kit/exts/omni.kit.property.layer/omni/kit/property/layer/layer_property_models.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import omni.kit.commands import omni.timeline import omni.ui as ui import omni.usd import weakref import omni.kit.widget.layers from pxr import Usd, Sdf, UsdGeom, UsdPhysics from omni.kit.widget.layers import LayerUtils from .types import LayerMetaType class LayerPathModel(ui.SimpleStringModel): def __init__(self, layer_item: weakref): super().__init__() self._layer_item = layer_item if self._layer_item and self._layer_item(): self._identifier = self._layer_item().identifier else: self._identifier = None def get_value_as_string(self): return self._identifier def set_value(self, value): if value != self._identifier: self._identifier = value self._value_changed() def begin_edit(self): pass def end_edit(self): if not self._layer_item or not self._layer_item(): return value = self.get_value_as_string() layer_item = self._layer_item() if not layer_item.reserved: sublayer_position = LayerUtils.get_sublayer_position_in_parent( layer_item.parent.identifier, layer_item.identifier ) omni.kit.commands.execute( "ReplaceSublayer", layer_identifier=layer_item.parent.identifier, sublayer_position=sublayer_position, new_layer_path=value, ) # OM-76598: Delay frames until layer item is initialized. async def focus_on_layer_item(path): await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() layer_instance = omni.kit.widget.layers.get_instance() layer_instance.set_current_focused_layer_item(path) asyncio.ensure_future(focus_on_layer_item(value)) def replace_layer(self, value): self.set_value(value) self.end_edit() def is_reserved_layer(self): if not self._layer_item or not self._layer_item(): return True return self._layer_item().reserved def anonymous(self): if not self._layer_item or not self._layer_item() or not self._layer_item().layer: return True return self._layer_item().anonymous class LayerWorldAxisItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.model = ui.SimpleStringModel(text) class LayerWorldAxisModel(ui.AbstractItemModel): def __init__(self, layer_item: weakref): super().__init__() self._layer_item = layer_item self._items = [LayerWorldAxisItem(text) for text in [UsdGeom.Tokens.y, UsdGeom.Tokens.z]] self._current_index = ui.SimpleIntModel() self.on_value_changed() self._current_index.add_value_changed_fn(self._current_index_changed) def get_item_children(self, item): return self._items 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._layer_item or not self._layer_item(): return stage = Usd.Stage.Open(self._layer_item().layer) index = model.as_int if index == 0: omni.kit.commands.execute("ModifyStageAxis", stage=stage, axis=UsdGeom.Tokens.y) elif index == 1: omni.kit.commands.execute("ModifyStageAxis", stage=stage, axis=UsdGeom.Tokens.z) UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) self._item_changed(None) def get_usd_token_name(self): return UsdGeom.Tokens.upAxis def on_value_changed(self): if self._layer_item and self._layer_item(): layer = self._layer_item().layer stage = Usd.Stage.Open(layer) up_axis = UsdGeom.GetStageUpAxis(stage) index = 0 if up_axis == UsdGeom.Tokens.y else 1 self._current_index.set_value(index) class LayerMetaModel(ui.AbstractValueModel): def __init__(self, layer_item: weakref, meta_type: LayerMetaType): super().__init__() self._layer_item = layer_item self._meta_type = meta_type self._value = self._get_value_as_string() def get_value_as_string(self): return self._value def _get_value_as_string(self): if not self._layer_item or not self._layer_item(): return None layer = self._layer_item().layer if not layer: return None if self._meta_type == LayerMetaType.COMMENT: return str(layer.comment) elif self._meta_type == LayerMetaType.DOC: return str(layer.documentation) elif self._meta_type == LayerMetaType.START_TIME: return str(layer.startTimeCode) elif self._meta_type == LayerMetaType.END_TIME: return str(layer.endTimeCode) elif self._meta_type == LayerMetaType.TIMECODES_PER_SECOND: return str(layer.timeCodesPerSecond) elif layer.HasFramesPerSecond() and self._meta_type == LayerMetaType.FPS_PER_SECOND: return str(layer.framesPerSecond) elif self._meta_type == LayerMetaType.UNITS: stage = Usd.Stage.Open(layer, None, None, Usd.Stage.LoadNone) meters = UsdGeom.GetStageMetersPerUnit(stage) return str(meters) elif self._meta_type == LayerMetaType.KG_PER_UNIT: stage = Usd.Stage.Open(layer, None, None, Usd.Stage.LoadNone) kilograms = UsdPhysics.GetStageKilogramsPerUnit(stage) return str(kilograms) elif ( self._layer_item().parent and self._meta_type == LayerMetaType.LAYER_OFFSET ): parent = self._layer_item().parent layer_index = LayerUtils.get_sublayer_position_in_parent(parent.identifier, layer.identifier) offset = parent.layer.subLayerOffsets[layer_index] return str(offset.offset) elif self._layer_item().parent and self._meta_type == LayerMetaType.LAYER_SCALE: parent = self._layer_item().parent layer_index = LayerUtils.get_sublayer_position_in_parent(parent.identifier, layer.identifier) offset = parent.layer.subLayerOffsets[layer_index] return str(offset.scale) return None def set_value(self, value): if value != self._value: self._value = value self._value_changed() def end_edit(self): if not self._layer_item or not self._layer_item(): return layer = self._layer_item().layer if not layer: return if self._layer_item().parent: parent_layer_identifier = self._layer_item().parent.identifier else: parent_layer_identifier = None layer_identifier = layer.identifier omni.kit.commands.execute( "ModifyLayerMetadata", layer_identifier=layer_identifier, parent_layer_identifier=parent_layer_identifier, meta_index=self._meta_type, value=self._value, ) def begin_edit(self): pass def get_usd_token_name(self): if self._meta_type == LayerMetaType.COMMENT: return Sdf.Layer.CommentKey elif self._meta_type == LayerMetaType.DOC: return Sdf.Layer.DocumentationKey elif self._meta_type == LayerMetaType.START_TIME: return Sdf.Layer.StartTimeCodeKey elif self._meta_type == LayerMetaType.END_TIME: return Sdf.Layer.EndTimeCodeKey elif self._meta_type == LayerMetaType.TIMECODES_PER_SECOND: return Sdf.Layer.TimeCodesPerSecondKey elif self._meta_type == LayerMetaType.FPS_PER_SECOND: return Sdf.Layer.FramesPerSecondKey elif self._meta_type == LayerMetaType.UNITS: return UsdGeom.Tokens.metersPerUnit elif self._meta_type == LayerMetaType.KG_PER_UNIT: return UsdPhysics.Tokens.kilogramsPerUnit elif self._meta_type == LayerMetaType.LAYER_OFFSET: return "subLayerOffsets_offset" # USD has no python bindings for this key elif self._meta_type == LayerMetaType.LAYER_SCALE: return "subLayerOffsets_scale" # USD has no python bindings for this key return "" def on_value_changed(self): self.set_value(self._get_value_as_string())
8,951
Python
35.390244
105
0.625517
omniverse-code/kit/exts/omni.kit.property.layer/omni/kit/property/layer/widgets.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.ext import omni.kit.app import omni.usd import weakref from pathlib import Path from pxr import Sdf, UsdGeom from typing import List from .layer_property_widgets import LayerPathWidget, LayerMetaWiget ICON_PATH = "" _instance = None def get_instance(): global _instance return _instance class LayerPropertyWidgets(omni.ext.IExt): def __init__(self): self._registered = False self._examples = None self._selection_notifiers = [] super().__init__() def on_startup(self, ext_id): global _instance _instance = self manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) global ICON_PATH ICON_PATH = Path(extension_path).joinpath("data").joinpath("icons") self._selection_notifiers.append(SelectionNotifier()) # default context self._hooks = manager.subscribe_to_extension_enable( lambda _: self._register_widget(), lambda _: self._unregister_widget(), ext_name="omni.kit.window.property", hook_name="omni.kit.property.layer listener", ) def on_shutdown(self): global _instance if _instance: _instance = None for notifier in self._selection_notifiers: notifier.stop() self._selection_notifiers.clear() self._hooks = None if self._registered: self._unregister_widget() def _register_widget(self): try: import omni.kit.window.property as p from .layer_property_widgets import LayerPathWidget, LayerMetaWiget w = p.get_window() self._layer_path_widget = LayerPathWidget(ICON_PATH) self._meta_widget = LayerMetaWiget(ICON_PATH) if w: w.register_widget("layers", "path", self._layer_path_widget) w.register_widget("layers", "metadata", self._meta_widget) for notifier in self._selection_notifiers: notifier.start() # notifier._notify_layer_selection_changed(None) # force a refresh self._registered = True except Exception as exc: carb.log_warn(f"error {exc}") def _unregister_widget(self): try: import omni.kit.window.property as p w = p.get_window() if w: for notifier in self._selection_notifiers: notifier.stop() w.unregister_widget("layers", "metadata") w.unregister_widget("layers", "path") self._registered = False if self._layer_path_widget: self._layer_path_widget.destroy() self._layer_path_widget = None self._meta_widget = None except Exception as e: carb.log_warn(f"Unable to unregister omni.kit.property.layer.widgets: {e}") class SelectionNotifier: def __init__(self, property_window_context_id=""): self._property_window_context_id = property_window_context_id def start(self): layers_widget = self.get_layers_widget() if layers_widget: layers_widget.add_layer_selection_changed_fn(self._notify_layer_selection_changed) def get_layers_widget(self): return omni.kit.widget.layers.get_instance() def stop(self): layers_widget = self.get_layers_widget() if layers_widget: layers_widget.remove_layer_selection_changed_fn(self._notify_layer_selection_changed) def _notify_layer_selection_changed(self, item): import omni.kit.window.property as p # TODO _property_window_context_id w = p.get_window() if w and self.get_layers_widget(): layer_item = self.get_layers_widget().get_current_focused_layer_item() if layer_item: w.notify("layers", weakref.ref(layer_item)) else: w.notify("layers", None)
4,491
Python
32.522388
97
0.616566
omniverse-code/kit/exts/omni.kit.property.layer/omni/kit/property/layer/commands.py
import weakref import carb import omni.kit.commands from pxr import Sdf, Usd, UsdGeom, UsdPhysics from .types import LayerMetaType from omni.kit.widget.layers import LayerUtils class ModifyStageAxisCommand(omni.kit.commands.Command): """Modify stage up axis undoable **Command**.""" def __init__(self, stage, axis): if stage: self._stage = weakref.ref(stage) else: self._stage = None self._new_axis = axis self._old_axis = None def do(self): if self._stage and self._stage(): self._old_axis = UsdGeom.GetStageUpAxis(self._stage()) UsdGeom.SetStageUpAxis(self._stage(), self._new_axis) def undo(self): if self._stage and self._stage() and self._old_axis: UsdGeom.SetStageUpAxis(self._stage(), self._old_axis) class ModifyLayerMetadataCommand(omni.kit.commands.Command): """Modify layer metadata undoable **Command**.""" def __init__(self, layer_identifier, parent_layer_identifier, meta_index, value): """Constructor. Keyword Arguments: layer_identifier (str): Layer identifier to operate. parent_identifier (str): Parent identifier that layer_identifier resides in as sublayer. It's None if it's root layer. meta_index (omni.kit.property.layer.types.LayerMetaType): Metadata type. """ super().__init__() self._layer_identifer = layer_identifier self._parent_layer_identifier = parent_layer_identifier self._meta_index = meta_index self._new_value = value self._old_value = None def _set_value(self, meta_type, value): layer = Sdf.Find(self._layer_identifer) if not layer: return if self._parent_layer_identifier: parent_layer = Sdf.Find(self._parent_layer_identifier) else: parent_layer = None try: if meta_type == LayerMetaType.COMMENT: self._old_value = layer.comment layer.comment = str(value) elif meta_type == LayerMetaType.DOC: self._old_value = layer.documentation layer.documentation = str(value) elif meta_type == LayerMetaType.START_TIME: self._old_value = layer.startTimeCode layer.startTimeCode = float(value) elif meta_type == LayerMetaType.END_TIME: self._old_value = layer.endTimeCode layer.endTimeCode = float(value) elif meta_type == LayerMetaType.TIMECODES_PER_SECOND: self._old_value = layer.timeCodesPerSecond layer.timeCodesPerSecond = float(value) elif meta_type == LayerMetaType.FPS_PER_SECOND: self._old_value = layer.framesPerSecond layer.framesPerSecond = float(value) elif meta_type == LayerMetaType.UNITS: stage = Usd.Stage.Open(layer, None, None, Usd.Stage.LoadNone) meters = UsdGeom.GetStageMetersPerUnit(stage) self._old_value = meters UsdGeom.SetStageMetersPerUnit(stage, float(value)) elif meta_type == LayerMetaType.KG_PER_UNIT: stage = Usd.Stage.Open(layer, None, None, Usd.Stage.LoadNone) kilograms = UsdPhysics.GetStageKilogramsPerUnit(stage) self._old_value = kilograms UsdPhysics.SetStageKilogramsPerUnit(stage, float(value)) elif parent_layer and meta_type == LayerMetaType.LAYER_OFFSET: layer_index = LayerUtils.get_sublayer_position_in_parent( self._parent_layer_identifier, layer.identifier ) offset = parent_layer.subLayerOffsets[layer_index] self._old_value = offset.offset parent_layer.subLayerOffsets[layer_index] = Sdf.LayerOffset(float(value), offset.scale) elif parent_layer and meta_type == LayerMetaType.LAYER_SCALE: layer_index = LayerUtils.get_sublayer_position_in_parent( self._parent_layer_identifier, layer.identifier ) offset = parent_layer.subLayerOffsets[layer_index] self._old_value = offset.scale parent_layer.subLayerOffsets[layer_index] = Sdf.LayerOffset(offset.offset, float(value)) except Exception as e: pass def do(self): self._set_value(self._meta_index, self._new_value) def undo(self): self._set_value(self._meta_index, self._old_value)
4,624
Python
40.294642
104
0.60359
omniverse-code/kit/exts/omni.kit.property.layer/omni/kit/property/layer/layer_property_widgets.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import carb import omni.client import omni.kit.window.content_browser as content import omni.ui as ui import omni.usd from omni.kit.usd.layers import get_layers, LayerEventType, get_layer_event_payload from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_HEIGHT, LABEL_WIDTH, SimplePropertyWidget from .file_picker import FileBrowserSelectionType, FilePicker from .layer_property_models import LayerMetaModel, LayerPathModel, LayerWorldAxisModel from .types import LayerMetaName, LayerMetaType class LayerPathWidget(SimplePropertyWidget): def __init__(self, icon_path): super().__init__(title="Layer Path", collapsed=False) self._icon_path = icon_path self._file_picker = None self._layer_path_field = False self._layer_path_model = None def destroy(self): if self._file_picker: self._file_picker.destroy() def _show_file_picker(self): if not self._file_picker: self._file_picker = FilePicker( "Select File", "Select", FileBrowserSelectionType.FILE_ONLY, [(omni.usd.writable_usd_re(), omni.usd.writable_usd_files_desc())], ) self._file_picker.set_custom_fn(self._on_file_selected, None) if self._layer_path_field: value = self._layer_path_field.model.get_value_as_string() current_dir = os.path.dirname(value) self._file_picker.set_current_directory(current_dir) self._file_picker.show_dialog() def _on_file_selected(self, path): self._layer_path_field.model.replace_layer(path) def on_new_payload(self, payload): if not super().on_new_payload(payload, ignore_large_selection=True): return False return payload is not None def build_items(self): layer_item = self._payload if layer_item and layer_item(): with ui.VStack(height=0, spacing=5): with ui.HStack(): self._layer_path_model = LayerPathModel(layer_item) if self._layer_path_model.is_reserved_layer(): read_only = True else: read_only = False self._layer_path_field = ui.StringField( name="models", model=self._layer_path_model, read_only=read_only ) if layer_item().missing: self._layer_path_field.set_style({"color" : 0xFF6F72FF}) style = {"image_url": str(self._icon_path.joinpath("small_folder.png"))} if not read_only: ui.Spacer(width=3) open_button = ui.Button(style=style, width=20, tooltip="Open") open_button.set_clicked_fn(self._show_file_picker) if not self._layer_path_model.anonymous(): ui.Spacer(width=3) style["image_url"] = str(self._icon_path.joinpath("find.png")) find_button = ui.Button(style=style, width=20, tooltip="Find") def find_button_fn(): path = self._layer_path_field.model.get_value_as_string() # Remove checkpoint and branch so navigate_to works client_url = omni.client.break_url(path) path = omni.client.make_url( scheme=client_url.scheme, user=client_url.user, host=client_url.host, port=client_url.port, path=client_url.path, query=None, fragment=client_url.fragment, ) content.get_content_window().navigate_to(path) find_button.set_clicked_fn(find_button_fn) if not self._layer_path_model.anonymous(): if self._filter.matches("Checkpoint"): self._build_checkpoint_ui(layer_item().identifier) self._any_item_visible = True else: selected_info_name = "(nothing selected)" ui.StringField(name="layer_path", height=LABEL_HEIGHT, enabled=False).model.set_value(selected_info_name) def _build_checkpoint_ui(self, absolute_layer_path): try: # Use checkpoint widget in the drop down menu for more detailed information from omni.kit.widget.versioning.checkpoint_combobox import CheckpointCombobox with ui.HStack(spacing=HORIZONTAL_SPACING): self.add_label("Checkpoint") def on_selection_changed(selection): if selection: self._layer_path_model.replace_layer(selection.get_full_url()) self._checkpoint_combobox = CheckpointCombobox(absolute_layer_path, on_selection_changed) return None except ImportError as e: # If the widget is not available, create a simple combo box instead carb.log_warn(f"Checkpoint widget in Layer Path widget is not availbale due to: {e}") class LayerMetaWiget(SimplePropertyWidget): def __init__(self, icon_path): super().__init__(title="Layer Metadata", collapsed=False) self._icon_path = icon_path self._models = {} self._meta_change_listener = None def on_new_payload(self, payload): if not super().on_new_payload(payload): return False return payload is not None def reset(self): super().reset() self._meta_change_listener = None self._models = {} def _on_meta_changed(self, event: carb.events.IEvent): payload = get_layer_event_payload(event) if payload and payload.event_type == LayerEventType.INFO_CHANGED: layer_item = self._payload if layer_item and layer_item() and layer_item().layer: layer_item = layer_item() if layer_item.identifier in payload.layer_info_data: info_tokens = payload.layer_info_data.get(layer_item.identifier, []) for token in info_tokens: model = self._models.get(token, None) if model: model.on_value_changed() def build_items(self): layer_item = self._payload if layer_item and layer_item() and layer_item().layer: usd_context = layer_item().usd_context layers = get_layers(usd_context) event_stream = layers.get_event_stream() self._meta_change_listener = event_stream.create_subscription_to_pop(self._on_meta_changed, name="Layers Property Window") model = LayerWorldAxisModel(layer_item) self._models[model.get_usd_token_name()] = model if self._filter.matches("World Axis"): with ui.HStack(spacing=HORIZONTAL_SPACING): self.add_label("World Axis") ui.ComboBox(model, name="choices") self._any_item_visible = True for index in range(LayerMetaType.NUM_PROPERTIES): model = LayerMetaModel(layer_item, index) if model.get_value_as_string() is not None: self.add_item_with_model(LayerMetaName[index], model, True) self._models[model.get_usd_token_name()] = model
8,143
Python
42.784946
134
0.571779
omniverse-code/kit/exts/omni.kit.property.layer/omni/kit/property/layer/types.py
class LayerMetaType: START_TIME = 0 END_TIME = 1 TIMECODES_PER_SECOND = 2 FPS_PER_SECOND = 3 UNITS = 4 LAYER_OFFSET = 5 LAYER_SCALE = 6 KG_PER_UNIT = 7 COMMENT = 8 DOC = 9 NUM_PROPERTIES = 10 LayerMetaName = [ "Start Time Code", "End Time Code", "Time Codes Per Second", "Frames Per Second", "Meters Per Unit", "Layer Offset", "Layer Scale", "Kgs Per Unit", "Comment", "Documentation" ]
473
Python
16.555555
28
0.566596
omniverse-code/kit/exts/omni.kit.property.layer/omni/kit/property/layer/tests/test_property_window.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 tempfile import os import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.kit.widget.layers as layers_widget import omni.kit.property.layer as layers_property from omni.kit.property.layer.layer_property_models import LayerMetaModel, LayerWorldAxisModel from omni.kit.property.layer.types import LayerMetaType from omni.ui.tests.test_base import OmniUiTest from pxr import Kind, Sdf, Gf, UsdGeom, UsdPhysics class TestLayerPropertyUI(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() # After running each test async def tearDown(self): await self._usd_context.close_stage_async() await super().tearDown() async def wait_for_update(self, usd_context=omni.usd.get_context(), wait_frames=10): max_loops = 0 while max_loops < wait_frames: _, files_loaded, total_files = usd_context.get_stage_loading_status() await omni.kit.app.get_app().next_update_async() if files_loaded or total_files: continue max_loops = max_loops + 1 async def test_layer_replacement(self): omni.usd.get_context().set_pending_edit(False) stage = self._usd_context.get_stage() root_layer = stage.GetRootLayer() sublayer = Sdf.Layer.CreateAnonymous() sublayer_replace = Sdf.Layer.CreateAnonymous() root_layer.subLayerPaths.append(sublayer.identifier) missing_identifier = "non_existed_sublayer_identifier.usd" root_layer.subLayerPaths.append(missing_identifier) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() layers_widget.get_instance().set_current_focused_layer_item(sublayer.identifier) # Wait several frames to make sure it's focused await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Make sure it's changed focused_item = layers_widget.get_instance().get_current_focused_layer_item() self.assertTrue(focused_item) self.assertEqual(focused_item.identifier, sublayer.identifier) layer_path_widget = layers_property.get_instance()._layer_path_widget layer_path_widget._show_file_picker() await self.wait_for_update() layer_path_widget._on_file_selected(sublayer_replace.identifier) await self.wait_for_update() # Make sure it's replaced self.assertTrue(root_layer.subLayerPaths[0], sublayer_replace.identifier) omni.kit.undo.undo() self.assertTrue(root_layer.subLayerPaths[0], sublayer.identifier) # Focus and replace missing layer layers_widget.get_instance().set_current_focused_layer_item(missing_identifier) # Wait several frames to make sure it's focused await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Make sure it's changed focused_item = layers_widget.get_instance().get_current_focused_layer_item() self.assertTrue(focused_item and focused_item.missing) self.assertEqual(focused_item.identifier, missing_identifier) layer_path_widget = layers_property.get_instance()._layer_path_widget layer_path_widget._show_file_picker() await self.wait_for_update() layer_path_widget._on_file_selected(sublayer_replace.identifier) await self.wait_for_update() # Make sure it's replaced self.assertTrue(root_layer.subLayerPaths[0], sublayer_replace.identifier) async def test_commands(self): test_comment = "test comment" test_doc = "test document" test_start_time = "0.0" test_end_time = "96.0" test_timecodes_per_second = "24.0" test_fps_per_second = "24.0" test_units = "10.0" test_kg_per_units = "10.0" test_layer_offset = "1.0" test_layer_scale = "10.0" omni.usd.get_context().set_pending_edit(False) stage = self._usd_context.get_stage() root_layer = stage.GetRootLayer() layers_widget.get_instance().set_current_focused_layer_item(root_layer.identifier) await self.wait_for_update() meta_models = layers_property.get_instance()._meta_widget._models modified_metadata = {} old_up_index = new_up_index = None for token, model in meta_models.items(): if isinstance(model, LayerMetaModel): new_value = None if model._meta_type == LayerMetaType.COMMENT: new_value = test_comment elif model._meta_type == LayerMetaType.DOC: new_value = test_doc elif model._meta_type == LayerMetaType.START_TIME: new_value = test_start_time elif model._meta_type == LayerMetaType.END_TIME: new_value = test_end_time elif model._meta_type == LayerMetaType.TIMECODES_PER_SECOND: new_value = test_timecodes_per_second elif model._meta_type == LayerMetaType.UNITS: new_value = test_units elif model._meta_type == LayerMetaType.KG_PER_UNIT: new_value = test_kg_per_units elif model._meta_type == LayerMetaType.FPS_PER_SECOND and root_layer.HasFramesPerSecond(): new_value = test_fps_per_second if new_value: model.set_value(new_value) model.end_edit() modified_metadata[model._meta_type] = model elif isinstance(model, LayerWorldAxisModel): old_up_index = model._current_index.get_value_as_int() if old_up_index == 0: # up_axis is UsdGeom.Tokens.y new_up_index = 1 else: # up_axis is UsdGeom.Tokens.z new_up_index = 0 model._current_index.set_value(new_up_index) # Wait several frames to make sure it's focused await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Check if the metadata is set correctly for meta_type, model in modified_metadata.items(): if meta_type == LayerMetaType.COMMENT: self.assertEqual(test_comment, str(root_layer.comment)) elif meta_type == LayerMetaType.DOC: self.assertEqual(test_doc, str(root_layer.documentation)) elif meta_type == LayerMetaType.START_TIME: self.assertEqual(test_start_time, str(root_layer.startTimeCode)) elif meta_type == LayerMetaType.END_TIME: self.assertEqual(test_end_time, str(root_layer.endTimeCode)) elif meta_type == LayerMetaType.TIMECODES_PER_SECOND: self.assertEqual(test_timecodes_per_second, str(root_layer.timeCodesPerSecond)) elif meta_type == LayerMetaType.UNITS: meters = UsdGeom.GetStageMetersPerUnit(stage) self.assertEqual(test_units, str(meters)) elif meta_type == LayerMetaType.KG_PER_UNIT: kilograms = UsdPhysics.GetStageKilogramsPerUnit(stage) self.assertEqual(test_kg_per_units, str(kilograms)) elif meta_type == LayerMetaType.FPS_PER_SECOND and root_layer.HasFramesPerSecond(): self.assertEqual(test_fps_per_second, str(root_layer.framesPerSecond)) if new_up_index is not None: up_axis = UsdGeom.GetStageUpAxis(stage) if new_up_index == 0: self.assertEqual(up_axis, UsdGeom.Tokens.y) elif new_up_index == 1: self.assertEqual(up_axis, UsdGeom.Tokens.z) # Testing metadata for sublayers sublayer = Sdf.Layer.CreateAnonymous() root_layer.subLayerPaths.append(sublayer.identifier) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() layers_widget.get_instance().set_current_focused_layer_item(sublayer.identifier) # Wait several frames to make sure it's focused await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Make sure it's changed focused_item = layers_widget.get_instance().get_current_focused_layer_item() self.assertTrue(focused_item) self.assertEqual(focused_item.identifier, sublayer.identifier) meta_models = layers_property.get_instance()._meta_widget._models modified_metadata = {} for token, model in meta_models.items(): if isinstance(model, LayerMetaModel): new_value = None if model._meta_type == LayerMetaType.LAYER_OFFSET and model._layer_item().parent: new_value = test_layer_offset elif model._meta_type == LayerMetaType.LAYER_SCALE and model._layer_item().parent: new_value = test_layer_scale if new_value: model.set_value(new_value) model.end_edit() modified_metadata[model._meta_type] = model # Check if the metadata is set correctly for meta_type, model in modified_metadata.items(): parent = model._layer_item().parent layer = model._layer_item().layer layer_index = layers_widget.LayerUtils.get_sublayer_position_in_parent(parent.identifier, layer.identifier) offset = parent.layer.subLayerOffsets[layer_index] if meta_type == LayerMetaType.LAYER_OFFSET: self.assertEqual(test_layer_offset, str(offset.offset)) elif meta_type == LayerMetaType.LAYER_SCALE and model._layer_item().parent: self.assertEqual(test_layer_scale, str(offset.scale)) async def test_shut_down(self): manager = omni.kit.app.get_app().get_extension_manager() ext_id = "omni.kit.property.layer" self.assertTrue(ext_id) self.assertTrue(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, False) await self.wait_for_update() self.assertTrue(not manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await self.wait_for_update() self.assertTrue(manager.is_extension_enabled(ext_id))
11,459
Python
44.296443
119
0.632516
omniverse-code/kit/exts/omni.kit.property.layer/omni/kit/property/layer/tests/__init__.py
from .test_property_window import *
35
Python
34.999965
35
0.8
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/__init__.py
"""There is no public API to this module.""" __all__ = []
58
Python
18.66666
44
0.568966
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/ogn/OgnBundleToUSDADatabase.py
"""Support for simplified access to data on nodes of type omni.graph.BundleToUSDA Outputs a represention of the content of a bundle as usda text """ import carb import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnBundleToUSDADatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.BundleToUSDA Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.bundle inputs.outputAncestors inputs.outputValues inputs.usePrimPath inputs.usePrimType inputs.usePrimvarMetadata Outputs: outputs.text """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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:bundle', 'bundle', 0, None, 'The bundle to convert to usda text.', {}, True, None, False, ''), ('inputs:outputAncestors', 'bool', 0, None, 'If usePath is true and this is also true, ancestor "primPath" entries will be output.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:outputValues', 'bool', 0, None, 'If true, the values of attributes will be output, else values will be omitted.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:usePrimPath', 'bool', 0, None, 'Use the attribute named "primPath" for the usda prim path.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:usePrimType', 'bool', 0, None, 'Use the attribute named "primType" for the usda prim type name.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:usePrimvarMetadata', 'bool', 0, None, 'Identify attributes representing metadata like the interpolation type for primvars, and include them as usda metadata in the output text.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:text', 'token', 0, None, 'Output usda text representing the bundle contents.', {}, 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.inputs.bundle = og.AttributeRole.BUNDLE return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def bundle(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.bundle""" return self.__bundles.bundle @property def outputAncestors(self): data_view = og.AttributeValueHelper(self._attributes.outputAncestors) return data_view.get() @outputAncestors.setter def outputAncestors(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.outputAncestors) data_view = og.AttributeValueHelper(self._attributes.outputAncestors) data_view.set(value) @property def outputValues(self): data_view = og.AttributeValueHelper(self._attributes.outputValues) return data_view.get() @outputValues.setter def outputValues(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.outputValues) data_view = og.AttributeValueHelper(self._attributes.outputValues) data_view.set(value) @property def usePrimPath(self): data_view = og.AttributeValueHelper(self._attributes.usePrimPath) return data_view.get() @usePrimPath.setter def usePrimPath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePrimPath) data_view = og.AttributeValueHelper(self._attributes.usePrimPath) data_view.set(value) @property def usePrimType(self): data_view = og.AttributeValueHelper(self._attributes.usePrimType) return data_view.get() @usePrimType.setter def usePrimType(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePrimType) data_view = og.AttributeValueHelper(self._attributes.usePrimType) data_view.set(value) @property def usePrimvarMetadata(self): data_view = og.AttributeValueHelper(self._attributes.usePrimvarMetadata) return data_view.get() @usePrimvarMetadata.setter def usePrimvarMetadata(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePrimvarMetadata) data_view = og.AttributeValueHelper(self._attributes.usePrimvarMetadata) data_view.set(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 = { } """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 text(self): data_view = og.AttributeValueHelper(self._attributes.text) return data_view.get() @text.setter def text(self, value): data_view = og.AttributeValueHelper(self._attributes.text) data_view.set(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 = OgnBundleToUSDADatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnBundleToUSDADatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnBundleToUSDADatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,803
Python
47.373626
285
0.659889
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/ogn/OgnTransformBundleDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.TransformBundle Applies a transform to an input bundle, storing the result in an output bundle """ import carb import numpy import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnTransformBundleDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.TransformBundle Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.input inputs.transform Outputs: outputs.output """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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:input', 'bundle', 0, None, 'Input bundle containing the attributes to be transformed.', {}, True, None, False, ''), ('inputs:transform', 'matrix4d', 0, None, 'The transform to apply to the bundle', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]'}, True, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], False, ''), ('outputs:output', 'bundle', 0, None, 'Output bundle containing all of the transformed attributes', {}, 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.inputs.input = og.AttributeRole.BUNDLE role_data.inputs.transform = og.AttributeRole.MATRIX role_data.outputs.output = og.AttributeRole.BUNDLE return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def input(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.input""" return self.__bundles.input @property def transform(self): data_view = og.AttributeValueHelper(self._attributes.transform) return data_view.get() @transform.setter def transform(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.transform) data_view = og.AttributeValueHelper(self._attributes.transform) data_view.set(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 = { } """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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={}) self._batchedWriteValues = { } @property def output(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute outputs.output""" return self.__bundles.output @output.setter def output(self, bundle: og.BundleContents): """Overwrite the bundle attribute outputs.output with a new bundle""" if not isinstance(bundle, og.BundleContents): carb.log_error("Only bundle attributes can be assigned to another bundle attribute") self.__bundles.output.bundle = bundle 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 = OgnTransformBundleDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnTransformBundleDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnTransformBundleDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
6,555
Python
48.666666
347
0.661937
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/ogn/OgnImportUSDPrimDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ImportUSDPrim Imports data from a USD prim into attributes in an output bundle """ import carb import numpy import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnImportUSDPrimDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ImportUSDPrim Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.applySkelBinding inputs.applyTransform inputs.attrNamesToImport inputs.computeBoundingBox inputs.importAttributes inputs.importPath inputs.importPrimvarMetadata inputs.importTime inputs.importTransform inputs.importType inputs.inputAttrNames inputs.keepPrimsSeparate inputs.outputAttrNames inputs.prim inputs.renameAttributes inputs.timeVaryingAttributes inputs.usdTimecode Outputs: outputs.output State: state.prevApplySkelBinding state.prevApplyTransform state.prevAttrNamesToImport state.prevComputeBoundingBox state.prevImportAttributes state.prevImportPath state.prevImportPrimvarMetadata state.prevImportTime state.prevImportTransform state.prevImportType state.prevInputAttrNames state.prevInvNodeTransform state.prevKeepPrimsSeparate state.prevOnlyImportSpecified state.prevOutputAttrNames state.prevPaths state.prevRenameAttributes state.prevTimeVaryingAttributes state.prevTransforms state.prevUsdTimecode """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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:applySkelBinding', 'bool', 0, None, 'If the input USD prim is a Mesh, and has SkelBindingAPI schema applied, compute skinned points and normals.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:applyTransform', 'bool', 0, None, 'If importAttributes is true, apply the transform necessary to transform any transforming attributes into the space of this node.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:attrNamesToImport', 'token', 0, 'Attributes To Import', 'Comma or space separated text, listing the names of attributes in the input data to be imported \nor empty to import all attributes.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:computeBoundingBox', 'bool', 0, None, 'Compute and store local bounding box of a prim and its children.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:importAttributes', 'bool', 0, None, 'Import attribute data from the USD prim.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:importPath', 'bool', 0, None, 'Record the input USD prim\'s path into the output bundle in an attribute named "primPath".', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:importPrimvarMetadata', 'bool', 0, None, 'Import metadata like the interpolation type for primvars, and store it as attributes in the output bundle.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:importTime', 'bool', 0, None, 'Record the usdTimecode above into the output bundle in an attribute named "primTime".', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:importTransform', 'bool', 0, None, 'Record the transform required to take any attributes of the input USD prim \ninto the space of this node, i.e. the world transform of the input prim times the \ninverse world transform of this node, into the output bundle in an attribute named "transform".', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:importType', 'bool', 0, None, 'Deprecated, prim type is always imported', {ogn.MetadataKeys.HIDDEN: 'true', 'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:inputAttrNames', 'token', 0, 'Attributes To Rename', 'Comma or space separated text, listing the names of attributes in the input data to be renamed', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:keepPrimsSeparate', 'bool', 0, None, 'Prefix output attribute names with "prim" followed by a unique number and a colon, \nto keep the attributes for separate input prims separate. The prim paths will \nbe in the "primPaths" token array attribute.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:outputAttrNames', 'token', 0, 'New Attribute Names', 'Comma or space separated text, listing the new names for the attributes listed in inputAttrNames', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:prim', 'bundle', 0, None, 'The USD prim from which to import data.', {}, False, None, False, ''), ('inputs:renameAttributes', 'bool', 0, None, 'If true, attributes listed in "inputAttrNames" will be imported to attributes with the names specified in "outputAttrNames".', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:timeVaryingAttributes', 'bool', 0, None, 'Check whether the USD attributes are time-varying and if so, import their data at the time "usdTimecode".', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:usdTimecode', 'double', 0, None, 'The time at which to evaluate the transform of the USD prim.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:output', 'bundle', 0, None, 'Output bundle containing all of the imported data.', {}, True, None, False, ''), ('state:prevApplySkelBinding', 'bool', 0, None, 'Value of "applySkelBinding" input from previous run', {}, True, None, False, ''), ('state:prevApplyTransform', 'bool', 0, None, 'Value of "applyTransform" input from previous run', {}, True, None, False, ''), ('state:prevAttrNamesToImport', 'token', 0, None, 'Value of "attrNamesToImport" input from previous run', {}, True, None, False, ''), ('state:prevComputeBoundingBox', 'bool', 0, None, 'Value of "computeBoundingBox" input from previous run', {}, True, None, False, ''), ('state:prevImportAttributes', 'bool', 0, None, 'Value of "importAttributes" input from previous run', {}, True, None, False, ''), ('state:prevImportPath', 'bool', 0, None, 'Value of "importPath" input from previous run', {}, True, None, False, ''), ('state:prevImportPrimvarMetadata', 'bool', 0, None, 'Value of "importPrimvarMetadata" input from previous run', {}, True, None, False, ''), ('state:prevImportTime', 'bool', 0, None, 'Value of "importTime" input from previous run', {}, True, None, False, ''), ('state:prevImportTransform', 'bool', 0, None, 'Value of "importTransform" input from previous run', {}, True, None, False, ''), ('state:prevImportType', 'bool', 0, None, 'Value of "importType" input from previous run', {}, True, None, False, ''), ('state:prevInputAttrNames', 'token', 0, None, 'Value of "inputAttrNames" input from previous run', {}, True, None, False, ''), ('state:prevInvNodeTransform', 'matrix4d', 0, None, 'Inverse transform of the node prim from the previous run.', {}, True, None, False, ''), ('state:prevKeepPrimsSeparate', 'bool', 0, None, 'Value of "keepPrimsSeparate" input from previous run', {}, True, None, False, ''), ('state:prevOnlyImportSpecified', 'bool', 0, None, 'Value of "onlyImportSpecified" input from previous run', {}, True, None, False, ''), ('state:prevOutputAttrNames', 'token', 0, None, 'Value of "outputAttrNames" input from previous run', {}, True, None, False, ''), ('state:prevPaths', 'token[]', 0, None, 'Array of paths from the previous run.', {}, True, None, False, ''), ('state:prevRenameAttributes', 'bool', 0, None, 'Value of "renameAttributes" input from previous run', {}, True, None, False, ''), ('state:prevTimeVaryingAttributes', 'bool', 0, None, 'Value of "timeVaryingAttributes" input from previous run', {}, True, None, False, ''), ('state:prevTransforms', 'matrix4d[]', 0, None, 'Array of transforms from the previous run.', {}, True, None, False, ''), ('state:prevUsdTimecode', 'double', 0, None, 'Value of "usdTimecode" input from previous run', {}, 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.inputs.prim = og.AttributeRole.BUNDLE role_data.outputs.output = og.AttributeRole.BUNDLE role_data.state.prevInvNodeTransform = og.AttributeRole.MATRIX role_data.state.prevTransforms = og.AttributeRole.MATRIX return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def applySkelBinding(self): data_view = og.AttributeValueHelper(self._attributes.applySkelBinding) return data_view.get() @applySkelBinding.setter def applySkelBinding(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.applySkelBinding) data_view = og.AttributeValueHelper(self._attributes.applySkelBinding) data_view.set(value) @property def applyTransform(self): data_view = og.AttributeValueHelper(self._attributes.applyTransform) return data_view.get() @applyTransform.setter def applyTransform(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.applyTransform) data_view = og.AttributeValueHelper(self._attributes.applyTransform) data_view.set(value) @property def attrNamesToImport(self): data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) return data_view.get() @attrNamesToImport.setter def attrNamesToImport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.attrNamesToImport) data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) data_view.set(value) @property def computeBoundingBox(self): data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox) return data_view.get() @computeBoundingBox.setter def computeBoundingBox(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.computeBoundingBox) data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox) data_view.set(value) @property def importAttributes(self): data_view = og.AttributeValueHelper(self._attributes.importAttributes) return data_view.get() @importAttributes.setter def importAttributes(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.importAttributes) data_view = og.AttributeValueHelper(self._attributes.importAttributes) data_view.set(value) @property def importPath(self): data_view = og.AttributeValueHelper(self._attributes.importPath) return data_view.get() @importPath.setter def importPath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.importPath) data_view = og.AttributeValueHelper(self._attributes.importPath) data_view.set(value) @property def importPrimvarMetadata(self): data_view = og.AttributeValueHelper(self._attributes.importPrimvarMetadata) return data_view.get() @importPrimvarMetadata.setter def importPrimvarMetadata(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.importPrimvarMetadata) data_view = og.AttributeValueHelper(self._attributes.importPrimvarMetadata) data_view.set(value) @property def importTime(self): data_view = og.AttributeValueHelper(self._attributes.importTime) return data_view.get() @importTime.setter def importTime(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.importTime) data_view = og.AttributeValueHelper(self._attributes.importTime) data_view.set(value) @property def importTransform(self): data_view = og.AttributeValueHelper(self._attributes.importTransform) return data_view.get() @importTransform.setter def importTransform(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.importTransform) data_view = og.AttributeValueHelper(self._attributes.importTransform) data_view.set(value) @property def importType(self): data_view = og.AttributeValueHelper(self._attributes.importType) return data_view.get() @importType.setter def importType(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.importType) data_view = og.AttributeValueHelper(self._attributes.importType) data_view.set(value) @property def inputAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.inputAttrNames) return data_view.get() @inputAttrNames.setter def inputAttrNames(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.inputAttrNames) data_view = og.AttributeValueHelper(self._attributes.inputAttrNames) data_view.set(value) @property def keepPrimsSeparate(self): data_view = og.AttributeValueHelper(self._attributes.keepPrimsSeparate) return data_view.get() @keepPrimsSeparate.setter def keepPrimsSeparate(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.keepPrimsSeparate) data_view = og.AttributeValueHelper(self._attributes.keepPrimsSeparate) data_view.set(value) @property def outputAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.outputAttrNames) return data_view.get() @outputAttrNames.setter def outputAttrNames(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.outputAttrNames) data_view = og.AttributeValueHelper(self._attributes.outputAttrNames) data_view.set(value) @property def prim(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.prim""" return self.__bundles.prim @property def renameAttributes(self): data_view = og.AttributeValueHelper(self._attributes.renameAttributes) return data_view.get() @renameAttributes.setter def renameAttributes(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renameAttributes) data_view = og.AttributeValueHelper(self._attributes.renameAttributes) data_view.set(value) @property def timeVaryingAttributes(self): data_view = og.AttributeValueHelper(self._attributes.timeVaryingAttributes) return data_view.get() @timeVaryingAttributes.setter def timeVaryingAttributes(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.timeVaryingAttributes) data_view = og.AttributeValueHelper(self._attributes.timeVaryingAttributes) data_view.set(value) @property def usdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) return data_view.get() @usdTimecode.setter def usdTimecode(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usdTimecode) data_view = og.AttributeValueHelper(self._attributes.usdTimecode) data_view.set(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 = { } """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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={}) self._batchedWriteValues = { } @property def output(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute outputs.output""" return self.__bundles.output @output.setter def output(self, bundle: og.BundleContents): """Overwrite the bundle attribute outputs.output with a new bundle""" if not isinstance(bundle, og.BundleContents): carb.log_error("Only bundle attributes can be assigned to another bundle attribute") self.__bundles.output.bundle = bundle 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) self.prevPaths_size = None self.prevTransforms_size = None @property def prevApplySkelBinding(self): data_view = og.AttributeValueHelper(self._attributes.prevApplySkelBinding) return data_view.get() @prevApplySkelBinding.setter def prevApplySkelBinding(self, value): data_view = og.AttributeValueHelper(self._attributes.prevApplySkelBinding) data_view.set(value) @property def prevApplyTransform(self): data_view = og.AttributeValueHelper(self._attributes.prevApplyTransform) return data_view.get() @prevApplyTransform.setter def prevApplyTransform(self, value): data_view = og.AttributeValueHelper(self._attributes.prevApplyTransform) data_view.set(value) @property def prevAttrNamesToImport(self): data_view = og.AttributeValueHelper(self._attributes.prevAttrNamesToImport) return data_view.get() @prevAttrNamesToImport.setter def prevAttrNamesToImport(self, value): data_view = og.AttributeValueHelper(self._attributes.prevAttrNamesToImport) data_view.set(value) @property def prevComputeBoundingBox(self): data_view = og.AttributeValueHelper(self._attributes.prevComputeBoundingBox) return data_view.get() @prevComputeBoundingBox.setter def prevComputeBoundingBox(self, value): data_view = og.AttributeValueHelper(self._attributes.prevComputeBoundingBox) data_view.set(value) @property def prevImportAttributes(self): data_view = og.AttributeValueHelper(self._attributes.prevImportAttributes) return data_view.get() @prevImportAttributes.setter def prevImportAttributes(self, value): data_view = og.AttributeValueHelper(self._attributes.prevImportAttributes) data_view.set(value) @property def prevImportPath(self): data_view = og.AttributeValueHelper(self._attributes.prevImportPath) return data_view.get() @prevImportPath.setter def prevImportPath(self, value): data_view = og.AttributeValueHelper(self._attributes.prevImportPath) data_view.set(value) @property def prevImportPrimvarMetadata(self): data_view = og.AttributeValueHelper(self._attributes.prevImportPrimvarMetadata) return data_view.get() @prevImportPrimvarMetadata.setter def prevImportPrimvarMetadata(self, value): data_view = og.AttributeValueHelper(self._attributes.prevImportPrimvarMetadata) data_view.set(value) @property def prevImportTime(self): data_view = og.AttributeValueHelper(self._attributes.prevImportTime) return data_view.get() @prevImportTime.setter def prevImportTime(self, value): data_view = og.AttributeValueHelper(self._attributes.prevImportTime) data_view.set(value) @property def prevImportTransform(self): data_view = og.AttributeValueHelper(self._attributes.prevImportTransform) return data_view.get() @prevImportTransform.setter def prevImportTransform(self, value): data_view = og.AttributeValueHelper(self._attributes.prevImportTransform) data_view.set(value) @property def prevImportType(self): data_view = og.AttributeValueHelper(self._attributes.prevImportType) return data_view.get() @prevImportType.setter def prevImportType(self, value): data_view = og.AttributeValueHelper(self._attributes.prevImportType) data_view.set(value) @property def prevInputAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.prevInputAttrNames) return data_view.get() @prevInputAttrNames.setter def prevInputAttrNames(self, value): data_view = og.AttributeValueHelper(self._attributes.prevInputAttrNames) data_view.set(value) @property def prevInvNodeTransform(self): data_view = og.AttributeValueHelper(self._attributes.prevInvNodeTransform) return data_view.get() @prevInvNodeTransform.setter def prevInvNodeTransform(self, value): data_view = og.AttributeValueHelper(self._attributes.prevInvNodeTransform) data_view.set(value) @property def prevKeepPrimsSeparate(self): data_view = og.AttributeValueHelper(self._attributes.prevKeepPrimsSeparate) return data_view.get() @prevKeepPrimsSeparate.setter def prevKeepPrimsSeparate(self, value): data_view = og.AttributeValueHelper(self._attributes.prevKeepPrimsSeparate) data_view.set(value) @property def prevOnlyImportSpecified(self): data_view = og.AttributeValueHelper(self._attributes.prevOnlyImportSpecified) return data_view.get() @prevOnlyImportSpecified.setter def prevOnlyImportSpecified(self, value): data_view = og.AttributeValueHelper(self._attributes.prevOnlyImportSpecified) data_view.set(value) @property def prevOutputAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.prevOutputAttrNames) return data_view.get() @prevOutputAttrNames.setter def prevOutputAttrNames(self, value): data_view = og.AttributeValueHelper(self._attributes.prevOutputAttrNames) data_view.set(value) @property def prevPaths(self): data_view = og.AttributeValueHelper(self._attributes.prevPaths) self.prevPaths_size = data_view.get_array_size() return data_view.get() @prevPaths.setter def prevPaths(self, value): data_view = og.AttributeValueHelper(self._attributes.prevPaths) data_view.set(value) self.prevPaths_size = data_view.get_array_size() @property def prevRenameAttributes(self): data_view = og.AttributeValueHelper(self._attributes.prevRenameAttributes) return data_view.get() @prevRenameAttributes.setter def prevRenameAttributes(self, value): data_view = og.AttributeValueHelper(self._attributes.prevRenameAttributes) data_view.set(value) @property def prevTimeVaryingAttributes(self): data_view = og.AttributeValueHelper(self._attributes.prevTimeVaryingAttributes) return data_view.get() @prevTimeVaryingAttributes.setter def prevTimeVaryingAttributes(self, value): data_view = og.AttributeValueHelper(self._attributes.prevTimeVaryingAttributes) data_view.set(value) @property def prevTransforms(self): data_view = og.AttributeValueHelper(self._attributes.prevTransforms) self.prevTransforms_size = data_view.get_array_size() return data_view.get() @prevTransforms.setter def prevTransforms(self, value): data_view = og.AttributeValueHelper(self._attributes.prevTransforms) data_view.set(value) self.prevTransforms_size = data_view.get_array_size() @property def prevUsdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.prevUsdTimecode) return data_view.get() @prevUsdTimecode.setter def prevUsdTimecode(self, value): data_view = og.AttributeValueHelper(self._attributes.prevUsdTimecode) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnImportUSDPrimDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnImportUSDPrimDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnImportUSDPrimDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
29,375
Python
48.78983
401
0.654672
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/ogn/OgnExportUSDPrimDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ExportUSDPrim Exports data from an input bundle into a USD prim """ import carb import numpy import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnExportUSDPrimDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ExportUSDPrim Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.applyTransform inputs.attrNamesToExport inputs.bundle inputs.excludedAttrNames inputs.exportToRootLayer inputs.inputAttrNames inputs.layerName inputs.onlyExportToExisting inputs.outputAttrNames inputs.primPathFromBundle inputs.removeMissingAttrs inputs.renameAttributes inputs.timeVaryingAttributes inputs.usdTimecode Outputs: outputs.prim State: state.prevApplyTransform state.prevAttrNamesToExport state.prevBundleDirtyID state.prevExcludedAttrNames state.prevExportToRootLayer state.prevInputAttrNames state.prevLayerName state.prevOnlyExportToExisting state.prevOutputAttrNames state.prevPrimDirtyIDs state.prevPrimPathFromBundle state.prevRemoveMissingAttrs state.prevRenameAttributes state.prevTimeVaryingAttributes state.prevUsdTimecode Predefined Tokens: tokens.primPath tokens.primType tokens.primTime tokens.primCount tokens.transform """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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:applyTransform', 'bool', 0, None, 'If true, apply the transform necessary to transform any transforming attributes from the space of the node into the space of the specified prim.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:attrNamesToExport', 'token', 0, 'Attributes To Export', 'Comma or space separated text, listing the names of attributes in the input data to be exported \nor empty to import all attributes.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:bundle', 'bundle', 0, None, 'The bundle from which data should be exported.', {}, True, None, False, ''), ('inputs:excludedAttrNames', 'token', 0, 'Attributes To Exclude', 'Attributes to be excluded from being exported', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:exportToRootLayer', 'bool', 0, 'Export to Root Layer', 'If true, prims are exported in the root layer, otherwise the layer specified by "layerName" is used.', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:inputAttrNames', 'token', 0, 'Attributes To Rename', 'Comma or space separated text, listing the names of attributes in the input data to be renamed', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:layerName', 'token', 0, 'Layer Name', 'Identifier of the layer to export to if "exportToRootLayer" is false, or leave this blank to export to the session layer', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:onlyExportToExisting', 'bool', 0, None, 'If true, only attributes that already exist in the specified output prim will have data transferred to them from the input bundle.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:outputAttrNames', 'token', 0, 'New Attribute Names', 'Comma or space separated text, listing the new names for the attributes listed in inputAttrNames', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:primPathFromBundle', 'bool', 0, None, 'When true, if there is a "primPath" token attribute inside the bundle, that will be the path of the USD prim to write to, \nelse the "outputs:prim" attribute below will be used for the USD prim path.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:removeMissingAttrs', 'bool', 0, 'Export to Root Layer', "If true, any attributes on the USD prim(s) being written to, that aren't in the input data, \nwill be removed from the USD prim(s).", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:renameAttributes', 'bool', 0, None, 'If true, attributes listed in "inputAttrNames" will be exported to attributes with the names specified in "outputAttrNames". \nNote: to avoid potential issues with redundant attributes being created while typing, keep this off until after \nspecifying all input and output attribute names.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:timeVaryingAttributes', 'bool', 0, None, 'Check whether the USD attributes should be time-varying and if so, export their data to a time sample at the time "usdTimecode".', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:usdTimecode', 'double', 0, None, 'The time at which to evaluate the transform of the USD prim for applyTransform.', {'displayGroup': 'parameters', ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:prim', 'bundle', 0, None, 'The USD prim(s) to which data should be exported if primPathFromBundle is false or if the bundle doesn\'t have a "primPath" token attribute. \nNote: this is really an input, since the node just receives the path to the prim. The node does not contain the prim.', {ogn.MetadataKeys.HIDDEN: 'true'}, False, None, False, ''), ('state:prevApplyTransform', 'bool', 0, None, 'Value of "applyTransform" input from previous run', {}, True, None, False, ''), ('state:prevAttrNamesToExport', 'token', 0, None, 'Value of "attrNamesToExport" input from previous run', {}, True, None, False, ''), ('state:prevBundleDirtyID', 'uint64', 0, None, 'Dirty ID of input bundle from previous run', {}, True, None, False, ''), ('state:prevExcludedAttrNames', 'token', 0, None, 'Value of "excludedAttrNames" input from previous run', {}, True, None, False, ''), ('state:prevExportToRootLayer', 'bool', 0, None, 'Value of "exportToRootLayer" input from previous run', {}, True, None, False, ''), ('state:prevInputAttrNames', 'token', 0, None, 'Value of "inputAttrNames" input from previous run', {}, True, None, False, ''), ('state:prevLayerName', 'token', 0, None, 'Value of "layerName" input from previous run', {}, True, None, False, ''), ('state:prevOnlyExportToExisting', 'bool', 0, None, 'Value of "onlyExportToExisting" input from previous run', {}, True, None, False, ''), ('state:prevOutputAttrNames', 'token', 0, None, 'Value of "outputAttrNames" input from previous run', {}, True, None, False, ''), ('state:prevPrimDirtyIDs', 'uint64[]', 0, None, 'Dirty IDs of input prims from previous run', {}, True, None, False, ''), ('state:prevPrimPathFromBundle', 'bool', 0, None, 'Value of "primPathFromBundle" input from previous run', {}, True, None, False, ''), ('state:prevRemoveMissingAttrs', 'bool', 0, None, 'Value of "removeMissingAttrs" input from previous run', {}, True, None, False, ''), ('state:prevRenameAttributes', 'bool', 0, None, 'Value of "renameAttributes" input from previous run', {}, True, None, False, ''), ('state:prevTimeVaryingAttributes', 'bool', 0, None, 'Value of "timeVaryingAttributes" input from previous run', {}, True, None, False, ''), ('state:prevUsdTimecode', 'double', 0, None, 'Value of "usdTimecode" input from previous run', {}, True, None, False, ''), ]) class tokens: primPath = "primPath" primType = "primType" primTime = "primTime" primCount = "primCount" transform = "transform" @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.bundle = og.AttributeRole.BUNDLE role_data.outputs.prim = og.AttributeRole.BUNDLE return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def applyTransform(self): data_view = og.AttributeValueHelper(self._attributes.applyTransform) return data_view.get() @applyTransform.setter def applyTransform(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.applyTransform) data_view = og.AttributeValueHelper(self._attributes.applyTransform) data_view.set(value) @property def attrNamesToExport(self): data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport) return data_view.get() @attrNamesToExport.setter def attrNamesToExport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.attrNamesToExport) data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport) data_view.set(value) @property def bundle(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.bundle""" return self.__bundles.bundle @property def excludedAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.excludedAttrNames) return data_view.get() @excludedAttrNames.setter def excludedAttrNames(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.excludedAttrNames) data_view = og.AttributeValueHelper(self._attributes.excludedAttrNames) data_view.set(value) @property def exportToRootLayer(self): data_view = og.AttributeValueHelper(self._attributes.exportToRootLayer) return data_view.get() @exportToRootLayer.setter def exportToRootLayer(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exportToRootLayer) data_view = og.AttributeValueHelper(self._attributes.exportToRootLayer) data_view.set(value) @property def inputAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.inputAttrNames) return data_view.get() @inputAttrNames.setter def inputAttrNames(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.inputAttrNames) data_view = og.AttributeValueHelper(self._attributes.inputAttrNames) data_view.set(value) @property def layerName(self): data_view = og.AttributeValueHelper(self._attributes.layerName) return data_view.get() @layerName.setter def layerName(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.layerName) data_view = og.AttributeValueHelper(self._attributes.layerName) data_view.set(value) @property def onlyExportToExisting(self): data_view = og.AttributeValueHelper(self._attributes.onlyExportToExisting) return data_view.get() @onlyExportToExisting.setter def onlyExportToExisting(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyExportToExisting) data_view = og.AttributeValueHelper(self._attributes.onlyExportToExisting) data_view.set(value) @property def outputAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.outputAttrNames) return data_view.get() @outputAttrNames.setter def outputAttrNames(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.outputAttrNames) data_view = og.AttributeValueHelper(self._attributes.outputAttrNames) data_view.set(value) @property def primPathFromBundle(self): data_view = og.AttributeValueHelper(self._attributes.primPathFromBundle) return data_view.get() @primPathFromBundle.setter def primPathFromBundle(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.primPathFromBundle) data_view = og.AttributeValueHelper(self._attributes.primPathFromBundle) data_view.set(value) @property def removeMissingAttrs(self): data_view = og.AttributeValueHelper(self._attributes.removeMissingAttrs) return data_view.get() @removeMissingAttrs.setter def removeMissingAttrs(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.removeMissingAttrs) data_view = og.AttributeValueHelper(self._attributes.removeMissingAttrs) data_view.set(value) @property def renameAttributes(self): data_view = og.AttributeValueHelper(self._attributes.renameAttributes) return data_view.get() @renameAttributes.setter def renameAttributes(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renameAttributes) data_view = og.AttributeValueHelper(self._attributes.renameAttributes) data_view.set(value) @property def timeVaryingAttributes(self): data_view = og.AttributeValueHelper(self._attributes.timeVaryingAttributes) return data_view.get() @timeVaryingAttributes.setter def timeVaryingAttributes(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.timeVaryingAttributes) data_view = og.AttributeValueHelper(self._attributes.timeVaryingAttributes) data_view.set(value) @property def usdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) return data_view.get() @usdTimecode.setter def usdTimecode(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usdTimecode) data_view = og.AttributeValueHelper(self._attributes.usdTimecode) data_view.set(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 = { } """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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={}) self._batchedWriteValues = { } @property def prim(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute outputs.prim""" return self.__bundles.prim @prim.setter def prim(self, bundle: og.BundleContents): """Overwrite the bundle attribute outputs.prim with a new bundle""" if not isinstance(bundle, og.BundleContents): carb.log_error("Only bundle attributes can be assigned to another bundle attribute") self.__bundles.prim.bundle = bundle 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) self.prevPrimDirtyIDs_size = None @property def prevApplyTransform(self): data_view = og.AttributeValueHelper(self._attributes.prevApplyTransform) return data_view.get() @prevApplyTransform.setter def prevApplyTransform(self, value): data_view = og.AttributeValueHelper(self._attributes.prevApplyTransform) data_view.set(value) @property def prevAttrNamesToExport(self): data_view = og.AttributeValueHelper(self._attributes.prevAttrNamesToExport) return data_view.get() @prevAttrNamesToExport.setter def prevAttrNamesToExport(self, value): data_view = og.AttributeValueHelper(self._attributes.prevAttrNamesToExport) data_view.set(value) @property def prevBundleDirtyID(self): data_view = og.AttributeValueHelper(self._attributes.prevBundleDirtyID) return data_view.get() @prevBundleDirtyID.setter def prevBundleDirtyID(self, value): data_view = og.AttributeValueHelper(self._attributes.prevBundleDirtyID) data_view.set(value) @property def prevExcludedAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.prevExcludedAttrNames) return data_view.get() @prevExcludedAttrNames.setter def prevExcludedAttrNames(self, value): data_view = og.AttributeValueHelper(self._attributes.prevExcludedAttrNames) data_view.set(value) @property def prevExportToRootLayer(self): data_view = og.AttributeValueHelper(self._attributes.prevExportToRootLayer) return data_view.get() @prevExportToRootLayer.setter def prevExportToRootLayer(self, value): data_view = og.AttributeValueHelper(self._attributes.prevExportToRootLayer) data_view.set(value) @property def prevInputAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.prevInputAttrNames) return data_view.get() @prevInputAttrNames.setter def prevInputAttrNames(self, value): data_view = og.AttributeValueHelper(self._attributes.prevInputAttrNames) data_view.set(value) @property def prevLayerName(self): data_view = og.AttributeValueHelper(self._attributes.prevLayerName) return data_view.get() @prevLayerName.setter def prevLayerName(self, value): data_view = og.AttributeValueHelper(self._attributes.prevLayerName) data_view.set(value) @property def prevOnlyExportToExisting(self): data_view = og.AttributeValueHelper(self._attributes.prevOnlyExportToExisting) return data_view.get() @prevOnlyExportToExisting.setter def prevOnlyExportToExisting(self, value): data_view = og.AttributeValueHelper(self._attributes.prevOnlyExportToExisting) data_view.set(value) @property def prevOutputAttrNames(self): data_view = og.AttributeValueHelper(self._attributes.prevOutputAttrNames) return data_view.get() @prevOutputAttrNames.setter def prevOutputAttrNames(self, value): data_view = og.AttributeValueHelper(self._attributes.prevOutputAttrNames) data_view.set(value) @property def prevPrimDirtyIDs(self): data_view = og.AttributeValueHelper(self._attributes.prevPrimDirtyIDs) self.prevPrimDirtyIDs_size = data_view.get_array_size() return data_view.get() @prevPrimDirtyIDs.setter def prevPrimDirtyIDs(self, value): data_view = og.AttributeValueHelper(self._attributes.prevPrimDirtyIDs) data_view.set(value) self.prevPrimDirtyIDs_size = data_view.get_array_size() @property def prevPrimPathFromBundle(self): data_view = og.AttributeValueHelper(self._attributes.prevPrimPathFromBundle) return data_view.get() @prevPrimPathFromBundle.setter def prevPrimPathFromBundle(self, value): data_view = og.AttributeValueHelper(self._attributes.prevPrimPathFromBundle) data_view.set(value) @property def prevRemoveMissingAttrs(self): data_view = og.AttributeValueHelper(self._attributes.prevRemoveMissingAttrs) return data_view.get() @prevRemoveMissingAttrs.setter def prevRemoveMissingAttrs(self, value): data_view = og.AttributeValueHelper(self._attributes.prevRemoveMissingAttrs) data_view.set(value) @property def prevRenameAttributes(self): data_view = og.AttributeValueHelper(self._attributes.prevRenameAttributes) return data_view.get() @prevRenameAttributes.setter def prevRenameAttributes(self, value): data_view = og.AttributeValueHelper(self._attributes.prevRenameAttributes) data_view.set(value) @property def prevTimeVaryingAttributes(self): data_view = og.AttributeValueHelper(self._attributes.prevTimeVaryingAttributes) return data_view.get() @prevTimeVaryingAttributes.setter def prevTimeVaryingAttributes(self, value): data_view = og.AttributeValueHelper(self._attributes.prevTimeVaryingAttributes) data_view.set(value) @property def prevUsdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.prevUsdTimecode) return data_view.get() @prevUsdTimecode.setter def prevUsdTimecode(self, value): data_view = og.AttributeValueHelper(self._attributes.prevUsdTimecode) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnExportUSDPrimDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnExportUSDPrimDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnExportUSDPrimDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
24,954
Python
49.211268
437
0.658852
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/ogn/tests/TestOgnImportUSDPrim.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.io.ogn.OgnImportUSDPrimDatabase import OgnImportUSDPrimDatabase test_file_name = "OgnImportUSDPrimTemplate.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_ImportUSDPrim") database = OgnImportUSDPrimDatabase(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:applySkelBinding")) attribute = test_node.get_attribute("inputs:applySkelBinding") db_value = database.inputs.applySkelBinding expected_value = True 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:applyTransform")) attribute = test_node.get_attribute("inputs:applyTransform") db_value = database.inputs.applyTransform 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:attrNamesToImport")) attribute = test_node.get_attribute("inputs:attrNamesToImport") db_value = database.inputs.attrNamesToImport expected_value = "" 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:computeBoundingBox")) attribute = test_node.get_attribute("inputs:computeBoundingBox") db_value = database.inputs.computeBoundingBox 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:importAttributes")) attribute = test_node.get_attribute("inputs:importAttributes") db_value = database.inputs.importAttributes expected_value = True 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:importPath")) attribute = test_node.get_attribute("inputs:importPath") db_value = database.inputs.importPath expected_value = True 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:importPrimvarMetadata")) attribute = test_node.get_attribute("inputs:importPrimvarMetadata") db_value = database.inputs.importPrimvarMetadata expected_value = True 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:importTime")) attribute = test_node.get_attribute("inputs:importTime") db_value = database.inputs.importTime expected_value = True 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:importTransform")) attribute = test_node.get_attribute("inputs:importTransform") db_value = database.inputs.importTransform expected_value = True 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:importType")) attribute = test_node.get_attribute("inputs:importType") db_value = database.inputs.importType expected_value = True 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:inputAttrNames")) attribute = test_node.get_attribute("inputs:inputAttrNames") db_value = database.inputs.inputAttrNames expected_value = "" 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:keepPrimsSeparate")) attribute = test_node.get_attribute("inputs:keepPrimsSeparate") db_value = database.inputs.keepPrimsSeparate expected_value = True 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:outputAttrNames")) attribute = test_node.get_attribute("inputs:outputAttrNames") db_value = database.inputs.outputAttrNames expected_value = "" 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:renameAttributes")) attribute = test_node.get_attribute("inputs:renameAttributes") db_value = database.inputs.renameAttributes 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:timeVaryingAttributes")) attribute = test_node.get_attribute("inputs:timeVaryingAttributes") db_value = database.inputs.timeVaryingAttributes expected_value = True 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:usdTimecode")) attribute = test_node.get_attribute("inputs:usdTimecode") db_value = database.inputs.usdTimecode 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("outputs_output")) attribute = test_node.get_attribute("outputs_output") db_value = database.outputs.output self.assertTrue(test_node.get_attribute_exists("state:prevApplySkelBinding")) attribute = test_node.get_attribute("state:prevApplySkelBinding") db_value = database.state.prevApplySkelBinding self.assertTrue(test_node.get_attribute_exists("state:prevApplyTransform")) attribute = test_node.get_attribute("state:prevApplyTransform") db_value = database.state.prevApplyTransform self.assertTrue(test_node.get_attribute_exists("state:prevAttrNamesToImport")) attribute = test_node.get_attribute("state:prevAttrNamesToImport") db_value = database.state.prevAttrNamesToImport self.assertTrue(test_node.get_attribute_exists("state:prevComputeBoundingBox")) attribute = test_node.get_attribute("state:prevComputeBoundingBox") db_value = database.state.prevComputeBoundingBox self.assertTrue(test_node.get_attribute_exists("state:prevImportAttributes")) attribute = test_node.get_attribute("state:prevImportAttributes") db_value = database.state.prevImportAttributes self.assertTrue(test_node.get_attribute_exists("state:prevImportPath")) attribute = test_node.get_attribute("state:prevImportPath") db_value = database.state.prevImportPath self.assertTrue(test_node.get_attribute_exists("state:prevImportPrimvarMetadata")) attribute = test_node.get_attribute("state:prevImportPrimvarMetadata") db_value = database.state.prevImportPrimvarMetadata self.assertTrue(test_node.get_attribute_exists("state:prevImportTime")) attribute = test_node.get_attribute("state:prevImportTime") db_value = database.state.prevImportTime self.assertTrue(test_node.get_attribute_exists("state:prevImportTransform")) attribute = test_node.get_attribute("state:prevImportTransform") db_value = database.state.prevImportTransform self.assertTrue(test_node.get_attribute_exists("state:prevImportType")) attribute = test_node.get_attribute("state:prevImportType") db_value = database.state.prevImportType self.assertTrue(test_node.get_attribute_exists("state:prevInputAttrNames")) attribute = test_node.get_attribute("state:prevInputAttrNames") db_value = database.state.prevInputAttrNames self.assertTrue(test_node.get_attribute_exists("state:prevInvNodeTransform")) attribute = test_node.get_attribute("state:prevInvNodeTransform") db_value = database.state.prevInvNodeTransform self.assertTrue(test_node.get_attribute_exists("state:prevKeepPrimsSeparate")) attribute = test_node.get_attribute("state:prevKeepPrimsSeparate") db_value = database.state.prevKeepPrimsSeparate self.assertTrue(test_node.get_attribute_exists("state:prevOnlyImportSpecified")) attribute = test_node.get_attribute("state:prevOnlyImportSpecified") db_value = database.state.prevOnlyImportSpecified self.assertTrue(test_node.get_attribute_exists("state:prevOutputAttrNames")) attribute = test_node.get_attribute("state:prevOutputAttrNames") db_value = database.state.prevOutputAttrNames self.assertTrue(test_node.get_attribute_exists("state:prevPaths")) attribute = test_node.get_attribute("state:prevPaths") db_value = database.state.prevPaths self.assertTrue(test_node.get_attribute_exists("state:prevRenameAttributes")) attribute = test_node.get_attribute("state:prevRenameAttributes") db_value = database.state.prevRenameAttributes self.assertTrue(test_node.get_attribute_exists("state:prevTimeVaryingAttributes")) attribute = test_node.get_attribute("state:prevTimeVaryingAttributes") db_value = database.state.prevTimeVaryingAttributes self.assertTrue(test_node.get_attribute_exists("state:prevTransforms")) attribute = test_node.get_attribute("state:prevTransforms") db_value = database.state.prevTransforms self.assertTrue(test_node.get_attribute_exists("state:prevUsdTimecode")) attribute = test_node.get_attribute("state:prevUsdTimecode") db_value = database.state.prevUsdTimecode
13,220
Python
53.407407
92
0.709834
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/ogn/tests/TestOgnExportUSDPrim.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.io.ogn.OgnExportUSDPrimDatabase import OgnExportUSDPrimDatabase test_file_name = "OgnExportUSDPrimTemplate.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_ExportUSDPrim") database = OgnExportUSDPrimDatabase(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:applyTransform")) attribute = test_node.get_attribute("inputs:applyTransform") db_value = database.inputs.applyTransform 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:attrNamesToExport")) attribute = test_node.get_attribute("inputs:attrNamesToExport") db_value = database.inputs.attrNamesToExport expected_value = "" 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:bundle")) attribute = test_node.get_attribute("inputs:bundle") db_value = database.inputs.bundle self.assertTrue(test_node.get_attribute_exists("inputs:excludedAttrNames")) attribute = test_node.get_attribute("inputs:excludedAttrNames") db_value = database.inputs.excludedAttrNames expected_value = "" 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:exportToRootLayer")) attribute = test_node.get_attribute("inputs:exportToRootLayer") db_value = database.inputs.exportToRootLayer expected_value = True 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:inputAttrNames")) attribute = test_node.get_attribute("inputs:inputAttrNames") db_value = database.inputs.inputAttrNames expected_value = "" 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:layerName")) attribute = test_node.get_attribute("inputs:layerName") db_value = database.inputs.layerName expected_value = "" 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:onlyExportToExisting")) attribute = test_node.get_attribute("inputs:onlyExportToExisting") db_value = database.inputs.onlyExportToExisting 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:outputAttrNames")) attribute = test_node.get_attribute("inputs:outputAttrNames") db_value = database.inputs.outputAttrNames expected_value = "" 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:primPathFromBundle")) attribute = test_node.get_attribute("inputs:primPathFromBundle") db_value = database.inputs.primPathFromBundle 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:removeMissingAttrs")) attribute = test_node.get_attribute("inputs:removeMissingAttrs") db_value = database.inputs.removeMissingAttrs 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:renameAttributes")) attribute = test_node.get_attribute("inputs:renameAttributes") db_value = database.inputs.renameAttributes 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:timeVaryingAttributes")) attribute = test_node.get_attribute("inputs:timeVaryingAttributes") db_value = database.inputs.timeVaryingAttributes 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:usdTimecode")) attribute = test_node.get_attribute("inputs:usdTimecode") db_value = database.inputs.usdTimecode 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("state:prevApplyTransform")) attribute = test_node.get_attribute("state:prevApplyTransform") db_value = database.state.prevApplyTransform self.assertTrue(test_node.get_attribute_exists("state:prevAttrNamesToExport")) attribute = test_node.get_attribute("state:prevAttrNamesToExport") db_value = database.state.prevAttrNamesToExport self.assertTrue(test_node.get_attribute_exists("state:prevBundleDirtyID")) attribute = test_node.get_attribute("state:prevBundleDirtyID") db_value = database.state.prevBundleDirtyID self.assertTrue(test_node.get_attribute_exists("state:prevExcludedAttrNames")) attribute = test_node.get_attribute("state:prevExcludedAttrNames") db_value = database.state.prevExcludedAttrNames self.assertTrue(test_node.get_attribute_exists("state:prevExportToRootLayer")) attribute = test_node.get_attribute("state:prevExportToRootLayer") db_value = database.state.prevExportToRootLayer self.assertTrue(test_node.get_attribute_exists("state:prevInputAttrNames")) attribute = test_node.get_attribute("state:prevInputAttrNames") db_value = database.state.prevInputAttrNames self.assertTrue(test_node.get_attribute_exists("state:prevLayerName")) attribute = test_node.get_attribute("state:prevLayerName") db_value = database.state.prevLayerName self.assertTrue(test_node.get_attribute_exists("state:prevOnlyExportToExisting")) attribute = test_node.get_attribute("state:prevOnlyExportToExisting") db_value = database.state.prevOnlyExportToExisting self.assertTrue(test_node.get_attribute_exists("state:prevOutputAttrNames")) attribute = test_node.get_attribute("state:prevOutputAttrNames") db_value = database.state.prevOutputAttrNames self.assertTrue(test_node.get_attribute_exists("state:prevPrimDirtyIDs")) attribute = test_node.get_attribute("state:prevPrimDirtyIDs") db_value = database.state.prevPrimDirtyIDs self.assertTrue(test_node.get_attribute_exists("state:prevPrimPathFromBundle")) attribute = test_node.get_attribute("state:prevPrimPathFromBundle") db_value = database.state.prevPrimPathFromBundle self.assertTrue(test_node.get_attribute_exists("state:prevRemoveMissingAttrs")) attribute = test_node.get_attribute("state:prevRemoveMissingAttrs") db_value = database.state.prevRemoveMissingAttrs self.assertTrue(test_node.get_attribute_exists("state:prevRenameAttributes")) attribute = test_node.get_attribute("state:prevRenameAttributes") db_value = database.state.prevRenameAttributes self.assertTrue(test_node.get_attribute_exists("state:prevTimeVaryingAttributes")) attribute = test_node.get_attribute("state:prevTimeVaryingAttributes") db_value = database.state.prevTimeVaryingAttributes self.assertTrue(test_node.get_attribute_exists("state:prevUsdTimecode")) attribute = test_node.get_attribute("state:prevUsdTimecode") db_value = database.state.prevUsdTimecode
10,861
Python
53.582914
92
0.710524
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/_impl/extension.py
"""Support required by the Carbonite extension loader""" import omni.ext from ..bindings._omni_graph_io import acquire_interface as _acquire_interface # noqa: PLE0402 from ..bindings._omni_graph_io import release_interface as _release_interface # noqa: PLE0402 class _PublicExtension(omni.ext.IExt): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__interface = None try: import omni.graph.ui as ogu ogu.ComputeNodeWidget.get_instance().add_template_path(__file__) except ImportError: pass def on_startup(self, ext_id): self.__interface = _acquire_interface() def on_shutdown(self): if self.__interface is not None: _release_interface(self.__interface) self.__interface = None
833
Python
31.076922
94
0.631453
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/_impl/templates/template_omni.graph.ImportUSDPrim.py
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty class CustomLayout: def __init__(self, compute_node_widget): # print("\nInside template_omni.genproc.ImportUSDPrim.py, CustomLayout:__init__\n"); # Enable template self.enable = True self.compute_node_widget = compute_node_widget self.compute_node_widget.get_bundles() bundle_items_iter = iter(self.compute_node_widget.bundles.items()) _ = next(bundle_items_iter)[1][0].get_attribute_names_and_types() def apply(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Import Parameters"): CustomLayoutProperty("inputs:prim", "Prim(s) to Import") CustomLayoutProperty("inputs:usdTimecode", "Timecode") CustomLayoutProperty("inputs:keepPrimsSeparate", "Allow Multiple Prims") CustomLayoutProperty("inputs:importTransform", "Import Transforms") CustomLayoutProperty("inputs:computeBoundingBox", "Compute Bounding Boxes") CustomLayoutProperty("inputs:importType", "Import Types") CustomLayoutProperty("inputs:importPath", "Import Paths") CustomLayoutProperty("inputs:importTime", "Import Time") with CustomLayoutGroup("Attributes"): CustomLayoutProperty("inputs:importAttributes", "Import Attributes") CustomLayoutProperty("inputs:attrNamesToImport", "Attributes to Import") CustomLayoutProperty("inputs:renameAttributes", "Rename Attributes") CustomLayoutProperty("inputs:inputAttrNames", "Attributes to Rename") CustomLayoutProperty("inputs:outputAttrNames", "New Attribute Names") CustomLayoutProperty("inputs:applyTransform", "Transform Attributes") CustomLayoutProperty("inputs:timeVaryingAttributes", "Time Varying Attributes") CustomLayoutProperty("inputs:importPrimvarMetadata", "Import Metadata") CustomLayoutProperty("inputs:applySkelBinding", "Apply SkelBinding") return frame.apply(props) # print("\nIn template_omni.graph.ImportUSDPrim.py\n")
2,295
Python
52.395348
113
0.672331
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/_impl/templates/template_omni.graph.ExportUSDPrim.py
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty class CustomLayout: def __init__(self, compute_node_widget): # print("\nInside template_omni.genproc.ExportUSDPrim.py, CustomLayout:__init__\n"); # Enable template self.enable = True self.compute_node_widget = compute_node_widget self.compute_node_widget.get_bundles() bundle_items_iter = iter(self.compute_node_widget.bundles.items()) _ = next(bundle_items_iter)[1][0].get_attribute_names_and_types() def apply(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Export Parameters"): CustomLayoutProperty("outputs:prim", "Prim(s) to Export to") CustomLayoutProperty("inputs:bundle", "Source Data") CustomLayoutProperty("inputs:primPathFromBundle", "Export to primPath from Source") CustomLayoutProperty("inputs:exportToRootLayer", "Export to Root Layer") CustomLayoutProperty("inputs:layerName", "Layer Name") with CustomLayoutGroup("Attributes"): CustomLayoutProperty("inputs:attrNamesToExport", "Attributes to Export") CustomLayoutProperty("inputs:onlyExportToExisting", "Only Export Existing") CustomLayoutProperty("inputs:removeMissingAttrs", "Remove Missing") CustomLayoutProperty("inputs:renameAttributes", "Rename Attributes") CustomLayoutProperty("inputs:inputAttrNames", "Attributes to Rename") CustomLayoutProperty("inputs:outputAttrNames", "New Attribute Names") CustomLayoutProperty("inputs:excludedAttrNames", "Attributes to Exclude") CustomLayoutProperty("inputs:applyTransform", "Transform Attributes") CustomLayoutProperty("inputs:timeVaryingAttributes", "Time-varying Attributes") CustomLayoutProperty("inputs:usdTimecode", "USD Time") return frame.apply(props) # print("\nIn template_omni.graph.ExportUSDPrim.py\n")
2,150
Python
51.463413
113
0.672093
omniverse-code/kit/exts/omni.graph.io/omni/graph/io/tests/test_prim_data_import_export.py
import omni.graph.core as ogc import omni.kit.test class TestPrimDataImportExport(ogc.tests.OmniGraphTestCase): """Run a unit test to validate data flow through bundles.""" TEST_GRAPH_PATH = "/TestGraph" TRANSLATE = (10.0, 20.0, 30.0) ROTATE = (90.0, 180.0, 270.0) SCALE = (400.0, 500.0, 600.0) async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.controller = ogc.Controller() self.graph = self.controller.create_graph(self.TEST_GRAPH_PATH) self.context = self.graph.get_default_graph_context() # Create ImportUSDPrim and ExportUSDPrim and connect them together. (self.graph, (self.importNode, self.exportNode), _, _,) = self.controller.edit( self.TEST_GRAPH_PATH, { ogc.Controller.Keys.CREATE_NODES: [ ("import_usd_prim_data", "omni.graph.ImportUSDPrim"), ("export_usd_prim_data", "omni.graph.ExportUSDPrim"), ], ogc.Controller.Keys.CONNECT: [ ( "import_usd_prim_data.outputs_output", "export_usd_prim_data.inputs:bundle", ) ], }, ) stage = omni.usd.get_context().get_stage() # Create two Xform nodes, one as input, the other as output. self.input_prim = ogc.Controller.create_prim("/input_prim", {}, "Xform") self.output_prim = ogc.Controller.create_prim("/output_prim", {}, "Xform") omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(self.TEST_GRAPH_PATH + "/import_usd_prim_data.inputs:prim"), target=self.input_prim.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(self.TEST_GRAPH_PATH + "/export_usd_prim_data.outputs:prim"), target=self.output_prim.GetPath(), ) async def test_set_attributes(self): """Test whether attribute value changes of the input prim will be synced to the output prim.""" # Assign new TRS values to the input prim. self.input_prim.GetAttribute("xformOp:translate").Set(self.TRANSLATE) self.input_prim.GetAttribute("xformOp:rotateXYZ").Set(self.ROTATE) self.input_prim.GetAttribute("xformOp:scale").Set(self.SCALE) # Before graph evaluation, the output prim is still with its default attribute values. self.assertFalse(self.output_prim.GetAttribute("xformOp:translate").Get() == self.TRANSLATE) self.assertFalse(self.output_prim.GetAttribute("xformOp:rotateXYZ").Get() == self.ROTATE) self.assertFalse(self.output_prim.GetAttribute("xformOp:scale").Get() == self.SCALE) # Trigger graph evaluation and wait for completion. await ogc.Controller.evaluate(self.graph) # After graph evaluation, the output prim has been fed with data from the input prim. self.assertTrue(self.output_prim.GetAttribute("xformOp:translate").Get() == self.TRANSLATE) self.assertTrue(self.output_prim.GetAttribute("xformOp:rotateXYZ").Get() == self.ROTATE) self.assertTrue(self.output_prim.GetAttribute("xformOp:scale").Get() == self.SCALE) async def test_bundle_attributes_and_metadata(self): """Test bundle attributes and metadata""" # Get the bundle from the import node. bundle = self.context.get_output_bundle(self.importNode, "outputs_output") self.assertTrue(bundle.is_valid()) # Attribute names and types before evaluation. attr_names, attr_types = bundle.get_attribute_names_and_types() self.assertTrue(len(attr_names) == 0) self.assertTrue(len(attr_types) == 0) # Assign new TRS values to the input prim. self.input_prim.GetAttribute("xformOp:translate").Set(self.TRANSLATE) self.input_prim.GetAttribute("xformOp:rotateXYZ").Set(self.ROTATE) self.input_prim.GetAttribute("xformOp:scale").Set(self.SCALE) # Trigger graph evaluation and wait for completion. await ogc.Controller.evaluate(self.graph) # Attribute names and types after evaluation. attr_names, attr_types = bundle.get_attribute_names_and_types() self.assertTrue(len(attr_names) != 0) self.assertTrue(len(attr_types) != 0) # Internal attributes shouldn't be exposed. metadata_names = { "interpolation", "source", "bundlePrimIndexOffset", } self.assertTrue(metadata_names.isdisjoint(set(attr_names))) # Convert bundle to IBundle2 for metadata access. factory = ogc.IBundleFactory.create() bundle = factory.get_bundle(self.context, bundle) # Test metadata names. self.assertEqual( set(bundle.get_bundle_metadata_names()), {"bundlePrimIndexOffset"}, ) async def test_bundle_dirty_id(self): """Test whether bundleDirtyID bumps after graph evaluation.""" factory = ogc.IBundleFactory.create() # Get the output bundle from the importer and convert to IBundle2. output_bundle = self.context.get_output_bundle(self.importNode, "outputs_output") output_bundle = factory.get_bundle(self.context, output_bundle) # Get the input bundle from the exporter and convert to IBundle2. input_bundle = self.context.get_input_bundle(self.exportNode, "inputs:bundle") input_bundle = factory.get_bundle(self.context, input_bundle) # Trigger graph evaluation and wait for completion. await ogc.Controller.evaluate(self.graph) dirty_id = ogc._og_unstable.IDirtyID2.create(self.context) # noqa: PLW0212 # Get dirty id. output_dirty_id = dirty_id.get([output_bundle])[0] input_dirty_id = dirty_id.get([input_bundle])[0] # Trigger graph evaluation and wait for completion. await ogc.Controller.evaluate(self.graph) # The dirty id doesn't bump because nothing gets changed. self.assertEqual(output_dirty_id, dirty_id.get([output_bundle])[0]) self.assertEqual(input_dirty_id, dirty_id.get([input_bundle])[0]) # Assign new TRS values to the input prim. self.input_prim.GetAttribute("xformOp:translate").Set(self.TRANSLATE) self.input_prim.GetAttribute("xformOp:rotateXYZ").Set(self.ROTATE) self.input_prim.GetAttribute("xformOp:scale").Set(self.SCALE) # Trigger graph evaluation and wait for completion. await ogc.Controller.evaluate(self.graph) # The dirty id bumps because of TRS value changes. self.assertNotEqual(output_dirty_id, dirty_id.get([output_bundle])[0]) self.assertNotEqual(input_dirty_id, dirty_id.get([input_bundle])[0]) async def test_child_bundle_order(self): """Test whether the order of child bundles extracted from the output bundle is consistent with that of target prims.""" graph_path = "/TestGraph2" cubes = [("/cube_1", 1.0), ("/cube_2", 2.0), ("/cube_3", 3.0), ("/cube_4", 4.0)] attr_name = "size" controller = ogc.Controller() keys = ogc.Controller.Keys (graph, (_, output_node), _, _,) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("import_usd_prim_data", "omni.graph.ImportUSDPrim"), ("bundle_to_usda_text", "omni.graph.BundleToUSDA"), ], keys.CONNECT: [ ("import_usd_prim_data.outputs_output", "bundle_to_usda_text.inputs:bundle"), ], keys.SET_VALUES: ("import_usd_prim_data.inputs:attrNamesToImport", attr_name), }, ) # Create target prims and assign the size attribute with different values. for cube_path, cube_size in cubes: prim = ogc.Controller.create_prim(cube_path, {}, "Cube") prim.GetAttribute(attr_name).Set(cube_size) # Assign the target prims to the import node. stage = omni.usd.get_context().get_stage() omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(graph_path + "/import_usd_prim_data.inputs:prim"), targets=[cube_path for cube_path, _ in cubes], ) await ogc.Controller.evaluate(graph) expected_result = ( 'def Cube "cube_1"\n' "{\n" " double size = 1.00000000000000000e+00\n" ' token sourcePrimPath = "/cube_1"\n' ' token sourcePrimType = "Cube"\n' "}\n" 'def Cube "cube_2"\n' "{\n" " double size = 2.00000000000000000e+00\n" ' token sourcePrimPath = "/cube_2"\n' ' token sourcePrimType = "Cube"\n' "}\n" 'def Cube "cube_3"\n' "{\n" " double size = 3.00000000000000000e+00\n" ' token sourcePrimPath = "/cube_3"\n' ' token sourcePrimType = "Cube"\n' "}\n" 'def Cube "cube_4"\n' "{\n" " double size = 4.00000000000000000e+00\n" ' token sourcePrimPath = "/cube_4"\n' ' token sourcePrimType = "Cube"\n' "}\n" ) # Change timecode to trigger recompute. Run 60 times to eliminate random factor. for timecode in range(60): self.controller.edit( self.TEST_GRAPH_PATH, {ogc.Controller.Keys.SET_VALUES: ("import_usd_prim_data.inputs:usdTimecode", timecode)}, ) await ogc.Controller.evaluate(self.graph) output_attr = output_node.get_attribute("outputs:text") self.assertTrue(output_attr is not None and output_attr.is_valid()) self.assertEqual(output_attr.get(), expected_result)
10,119
Python
41.521008
127
0.605989
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnReadViewportPressStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.ReadViewportPressState Read the state of the last viewport press event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadViewportPressStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.ReadViewportPressState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isPressed outputs.isReleasePositionValid outputs.isValid outputs.pressPosition outputs.releasePosition Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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 viewport press events', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Press", "RightMouseDrag": "Right Mouse Press", "MiddleMouseDrag": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Press"'}, True, "Left Mouse Press", False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for press events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:isPressed', 'bool', 0, 'Is Pressed', 'True if the specified viewport is currently pressed', {}, True, None, False, ''), ('outputs:isReleasePositionValid', 'bool', 0, 'Is Release Position Valid', 'True if the press was released inside of the viewport, and false otherwise', {}, 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:pressPosition', 'double2', 0, 'Press Position', 'The position at which the specified viewport was last pressed', {}, True, None, False, ''), ('outputs:releasePosition', 'double2', 0, 'Release Position', 'The position at which the last press on the specified viewport was released,\nor (0,0) if the press was released outside of the viewport or the viewport is currently pressed', {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Press" RightMouseDrag = "Right Mouse Press" MiddleMouseDrag = "Middle Mouse Press" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def gesture(self): data_view = og.AttributeValueHelper(self._attributes.gesture) return data_view.get() @gesture.setter def gesture(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gesture) data_view = og.AttributeValueHelper(self._attributes.gesture) data_view.set(value) @property def useNormalizedCoords(self): data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) return data_view.get() @useNormalizedCoords.setter def useNormalizedCoords(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.useNormalizedCoords) data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) data_view.set(value) @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(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 = { } """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 isPressed(self): data_view = og.AttributeValueHelper(self._attributes.isPressed) return data_view.get() @isPressed.setter def isPressed(self, value): data_view = og.AttributeValueHelper(self._attributes.isPressed) data_view.set(value) @property def isReleasePositionValid(self): data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) return data_view.get() @isReleasePositionValid.setter def isReleasePositionValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) data_view.set(value) @property def isValid(self): data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isValid) data_view.set(value) @property def pressPosition(self): data_view = og.AttributeValueHelper(self._attributes.pressPosition) return data_view.get() @pressPosition.setter def pressPosition(self, value): data_view = og.AttributeValueHelper(self._attributes.pressPosition) data_view.set(value) @property def releasePosition(self): data_view = og.AttributeValueHelper(self._attributes.releasePosition) return data_view.get() @releasePosition.setter def releasePosition(self, value): data_view = og.AttributeValueHelper(self._attributes.releasePosition) data_view.set(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 = OgnReadViewportPressStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadViewportPressStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadViewportPressStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
9,771
Python
48.604061
469
0.670044
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnOnViewportPressedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.OnViewportPressed Event node which fires when the specified viewport is pressed, and when that press is released. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnViewportPressedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.OnViewportPressed Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.onlyPlayback inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isReleasePositionValid outputs.pressPosition outputs.pressed outputs.releasePosition outputs.released Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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 viewport press events', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Press", "RightMouseDrag": "Right Mouse Press", "MiddleMouseDrag": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Press"'}, True, "Left Mouse Press", False, ''), ('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:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for press events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:isReleasePositionValid', 'bool', 0, 'Is Release Position Valid', 'True if the press was released inside of the viewport, and false otherwise', {}, True, None, False, ''), ('outputs:pressPosition', 'double2', 0, 'Press Position', "The position at which the viewport was pressed (valid when either 'Pressed' or 'Released' is enabled)", {}, True, None, False, ''), ('outputs:pressed', 'execution', 0, 'Pressed', "Enabled when the specified viewport is pressed, populating 'Press Position' with the current mouse position", {}, True, None, False, ''), ('outputs:releasePosition', 'double2', 0, 'Release Position', "The position at which the press was released, or (0,0) if the press was released outside of the viewport\nor the viewport is currently pressed (valid when 'Ended' is enabled and 'Is Release Position Valid' is true)", {}, True, None, False, ''), ('outputs:released', 'execution', 0, 'Released', "Enabled when the press is released, populating 'Release Position' with the current mouse position\nand setting 'Is Release Position Valid' to true if the press is released inside of the viewport.\nIf the press is released outside of the viewport, 'Is Release Position Valid' is set to false\nand 'Release Position' is set to (0,0).", {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Press" RightMouseDrag = "Right Mouse Press" MiddleMouseDrag = "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.outputs.pressed = og.AttributeRole.EXECUTION role_data.outputs.released = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def gesture(self): data_view = og.AttributeValueHelper(self._attributes.gesture) return data_view.get() @gesture.setter def gesture(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gesture) data_view = og.AttributeValueHelper(self._attributes.gesture) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) data_view.set(value) @property def useNormalizedCoords(self): data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) return data_view.get() @useNormalizedCoords.setter def useNormalizedCoords(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.useNormalizedCoords) data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) data_view.set(value) @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(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 = { } """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 isReleasePositionValid(self): data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) return data_view.get() @isReleasePositionValid.setter def isReleasePositionValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) data_view.set(value) @property def pressPosition(self): data_view = og.AttributeValueHelper(self._attributes.pressPosition) return data_view.get() @pressPosition.setter def pressPosition(self, value): data_view = og.AttributeValueHelper(self._attributes.pressPosition) data_view.set(value) @property def pressed(self): data_view = og.AttributeValueHelper(self._attributes.pressed) return data_view.get() @pressed.setter def pressed(self, value): data_view = og.AttributeValueHelper(self._attributes.pressed) data_view.set(value) @property def releasePosition(self): data_view = og.AttributeValueHelper(self._attributes.releasePosition) return data_view.get() @releasePosition.setter def releasePosition(self, value): data_view = og.AttributeValueHelper(self._attributes.releasePosition) data_view.set(value) @property def released(self): data_view = og.AttributeValueHelper(self._attributes.released) return data_view.get() @released.setter def released(self, value): data_view = og.AttributeValueHelper(self._attributes.released) data_view.set(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 = OgnOnViewportPressedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportPressedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportPressedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,292
Python
50.56621
505
0.67136
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnReadPickStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.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 numpy import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadPickStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.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.pickedPrim outputs.pickedPrimPath outputs.pickedWorldPos Predefined Tokens: tokens.LeftMouseClick tokens.RightMouseClick tokens.MiddleMouseClick tokens.LeftMousePress tokens.RightMousePress tokens.MiddleMousePress """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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, True, 'Use the trackedPrims input instead'), ('inputs:trackedPrims', 'target', 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')", {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, False, [], 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:pickedPrim', 'target', 0, 'Picked Prim', 'The picked prim, or an empty target if nothing got picked', {}, True, [], 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, True, 'Use the pickedPrim output instead'), ('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.AttributeRole.TARGET role_data.outputs.pickedPrim = og.AttributeRole.TARGET role_data.outputs.pickedWorldPos = og.AttributeRole.POSITION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def gesture(self): data_view = og.AttributeValueHelper(self._attributes.gesture) return data_view.get() @gesture.setter def gesture(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gesture) data_view = og.AttributeValueHelper(self._attributes.gesture) data_view.set(value) @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): data_view = og.AttributeValueHelper(self._attributes.trackedPrims) return data_view.get() @trackedPrims.setter def trackedPrims(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.trackedPrims) data_view = og.AttributeValueHelper(self._attributes.trackedPrims) data_view.set(value) self.trackedPrims_size = data_view.get_array_size() @property def usePaths(self): data_view = og.AttributeValueHelper(self._attributes.usePaths) return data_view.get() @usePaths.setter def usePaths(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePaths) data_view = og.AttributeValueHelper(self._attributes.usePaths) data_view.set(value) @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(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 = { } """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.pickedPrim_size = None self._batchedWriteValues = { } @property def isTrackedPrimPicked(self): data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) return data_view.get() @isTrackedPrimPicked.setter def isTrackedPrimPicked(self, value): data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) data_view.set(value) @property def isValid(self): data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isValid) data_view.set(value) @property def pickedPrim(self): data_view = og.AttributeValueHelper(self._attributes.pickedPrim) return data_view.get(reserved_element_count=self.pickedPrim_size) @pickedPrim.setter def pickedPrim(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedPrim) data_view.set(value) self.pickedPrim_size = data_view.get_array_size() @property def pickedPrimPath(self): data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) return data_view.get() @pickedPrimPath.setter def pickedPrimPath(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) data_view.set(value) @property def pickedWorldPos(self): data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) return data_view.get() @pickedWorldPos.setter def pickedWorldPos(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) data_view.set(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)
12,176
Python
48.702041
640
0.662861
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnSetViewportFullscreenDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.SetViewportFullscreen Toggles fullscreen on/off for viewport(s) and visibility on/off for all other panes. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSetViewportFullscreenDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.SetViewportFullscreen Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.mode Outputs: outputs.exec Predefined Tokens: tokens.Default tokens.Fullscreen tokens.HideUI """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # 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:exec', 'execution', 0, None, 'The input execution', {}, True, None, False, ''), ('inputs:mode', 'token', 0, 'Mode', 'The mode to toggle fullscreen on/off for viewport(s) and visibility on/off for all other panes:\n\n"Default" - Windowed viewport(s) with all other panes shown.\n"Fullscreen" - Fullscreen viewport(s) with all other panes hidden.\n"Hide UI" - Windowed viewport(s) with all other panes hidden.', {ogn.MetadataKeys.ALLOWED_TOKENS: 'Default,Fullscreen,Hide UI', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"Default": "Default", "Fullscreen": "Fullscreen", "HideUI": "Hide UI"}', ogn.MetadataKeys.DEFAULT: '"Default"'}, True, "Default", False, ''), ('outputs:exec', 'execution', 0, None, 'The output execution', {}, True, None, False, ''), ]) class tokens: Default = "Default" Fullscreen = "Fullscreen" HideUI = "Hide UI" @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.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def mode(self): data_view = og.AttributeValueHelper(self._attributes.mode) return data_view.get() @mode.setter def mode(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.mode) data_view = og.AttributeValueHelper(self._attributes.mode) data_view.set(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 = { } """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 exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(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 = OgnSetViewportFullscreenDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSetViewportFullscreenDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSetViewportFullscreenDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
6,593
Python
45.765957
582
0.664493