file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshTorus.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshTorusDatabase import OgnProceduralMeshTorusDatabase test_file_name = "OgnProceduralMeshTorusTemplate.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_kit_procedural_mesh_CreateMeshTorus") database = OgnProceduralMeshTorusDatabase(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:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 200 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:loopResolution")) attribute = test_node.get_attribute("inputs:loopResolution") db_value = database.inputs.loopResolution expected_value = 10 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:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 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:sectionDiameter")) attribute = test_node.get_attribute("inputs:sectionDiameter") db_value = database.inputs.sectionDiameter expected_value = 50 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:sectionResolution")) attribute = test_node.get_attribute("inputs:sectionResolution") db_value = database.inputs.sectionResolution expected_value = 10 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:sectionTwist")) attribute = test_node.get_attribute("inputs:sectionTwist") db_value = database.inputs.sectionTwist 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:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
5,303
Python
50.495145
110
0.695267
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/__init__.py
"""====== GENERATED BY omni.graph.tools - DO NOT EDIT ======""" import omni.graph.tools as ogt ogt.import_tests_in_directory(__file__, __name__)
145
Python
35.499991
63
0.634483
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshPlane.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshPlaneDatabase import OgnProceduralMeshPlaneDatabase test_file_name = "OgnProceduralMeshPlaneTemplate.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_kit_procedural_mesh_CreateMeshPlane") database = OgnProceduralMeshPlaneDatabase(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:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 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:xLength")) attribute = test_node.get_attribute("inputs:xLength") db_value = database.inputs.xLength expected_value = 100 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:xResolution")) attribute = test_node.get_attribute("inputs:xResolution") db_value = database.inputs.xResolution expected_value = 10 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:zLength")) attribute = test_node.get_attribute("inputs:zLength") db_value = database.inputs.zLength expected_value = 100 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:zResolution")) attribute = test_node.get_attribute("inputs:zResolution") db_value = database.inputs.zResolution expected_value = 10 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:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
4,616
Python
49.736263
110
0.691941
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshCylinder.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshCylinderDatabase import OgnProceduralMeshCylinderDatabase test_file_name = "OgnProceduralMeshCylinderTemplate.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_kit_procedural_mesh_CreateMeshCylinder") database = OgnProceduralMeshCylinderDatabase(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:capResolution")) attribute = test_node.get_attribute("inputs:capResolution") db_value = database.inputs.capResolution expected_value = 10 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:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 100 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:height")) attribute = test_node.get_attribute("inputs:height") db_value = database.inputs.height expected_value = 100 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:latitudeResolution")) attribute = test_node.get_attribute("inputs:latitudeResolution") db_value = database.inputs.latitudeResolution expected_value = 10 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:longitudeResolution")) attribute = test_node.get_attribute("inputs:longitudeResolution") db_value = database.inputs.longitudeResolution expected_value = 10 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:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 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:creaseIndices")) attribute = test_node.get_attribute("outputs:creaseIndices") db_value = database.outputs.creaseIndices self.assertTrue(test_node.get_attribute_exists("outputs:creaseLengths")) attribute = test_node.get_attribute("outputs:creaseLengths") db_value = database.outputs.creaseLengths self.assertTrue(test_node.get_attribute_exists("outputs:creaseSharpnesses")) attribute = test_node.get_attribute("outputs:creaseSharpnesses") db_value = database.outputs.creaseSharpnesses self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:normalIndices")) attribute = test_node.get_attribute("outputs:normalIndices") db_value = database.outputs.normalIndices self.assertTrue(test_node.get_attribute_exists("outputs:normals")) attribute = test_node.get_attribute("outputs:normals") db_value = database.outputs.normals self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
6,313
Python
50.333333
116
0.698875
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshCube.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshCubeDatabase import OgnProceduralMeshCubeDatabase test_file_name = "OgnProceduralMeshCubeTemplate.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_kit_procedural_mesh_CreateMeshCube") database = OgnProceduralMeshCubeDatabase(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:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 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:xLength")) attribute = test_node.get_attribute("inputs:xLength") db_value = database.inputs.xLength expected_value = 100 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:xResolution")) attribute = test_node.get_attribute("inputs:xResolution") db_value = database.inputs.xResolution expected_value = 10 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:yLength")) attribute = test_node.get_attribute("inputs:yLength") db_value = database.inputs.yLength expected_value = 100 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:yResolution")) attribute = test_node.get_attribute("inputs:yResolution") db_value = database.inputs.yResolution expected_value = 10 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:zLength")) attribute = test_node.get_attribute("inputs:zLength") db_value = database.inputs.zLength expected_value = 100 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:zResolution")) attribute = test_node.get_attribute("inputs:zResolution") db_value = database.inputs.zResolution expected_value = 10 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:creaseIndices")) attribute = test_node.get_attribute("outputs:creaseIndices") db_value = database.outputs.creaseIndices self.assertTrue(test_node.get_attribute_exists("outputs:creaseLengths")) attribute = test_node.get_attribute("outputs:creaseLengths") db_value = database.outputs.creaseLengths self.assertTrue(test_node.get_attribute_exists("outputs:creaseSharpnesses")) attribute = test_node.get_attribute("outputs:creaseSharpnesses") db_value = database.outputs.creaseSharpnesses self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:normalIndices")) attribute = test_node.get_attribute("outputs:normalIndices") db_value = database.outputs.normalIndices self.assertTrue(test_node.get_attribute_exists("outputs:normals")) attribute = test_node.get_attribute("outputs:normals") db_value = database.outputs.normals self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
6,674
Python
49.954198
108
0.694636
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshDisk.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshDiskDatabase import OgnProceduralMeshDiskDatabase test_file_name = "OgnProceduralMeshDiskTemplate.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_kit_procedural_mesh_CreateMeshDisk") database = OgnProceduralMeshDiskDatabase(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:capResolution")) attribute = test_node.get_attribute("inputs:capResolution") db_value = database.inputs.capResolution expected_value = 10 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:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 100 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:longitudeResolution")) attribute = test_node.get_attribute("inputs:longitudeResolution") db_value = database.inputs.longitudeResolution expected_value = 10 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:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 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:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
4,212
Python
49.759036
108
0.694919
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/extension.py
import omni.ext from ..bindings._omni_kit_procedural_mesh import * from .menu import * class PublicExtension(omni.ext.IExt): def on_startup(self): self._interface = acquire_interface() self._menu = Menu() def on_shutdown(self): self._menu.on_shutdown() self._menu = None release_interface(self._interface)
357
Python
22.866665
50
0.644258
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/procedural_mesh_omnigraph_utils.py
""" A set of utilities """ import omni.kit.app import omni.usd from pxr import Sdf, UsdGeom import omni.graph.core as og def get_parent(stage, parentPath): if parentPath: parentPrim = stage.GetPrimAtPath(parentPath) if parentPrim: return parentPrim, False # fallback to default behavior (creating a parent xform prim) omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type="Xform", prim_path=omni.usd.get_stage_next_free_path(stage, "/" + "ProceduralMeshXform", True), select_new_prim=True, create_default_xform=False, ) paths = omni.usd.get_context().get_selection().get_selected_prim_paths() for path in paths: parentPrim = stage.GetPrimAtPath(path) return parentPrim, True def create_mesh_computer(stage, prim_name: str, evaluator_name: str, node_type: str, parentPath=None): parentPrim, isParentOwned = get_parent(stage, parentPath) omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type="Mesh", prim_path=omni.usd.get_stage_next_free_path( stage, str(parentPrim.GetPath().AppendElementString(prim_name)), False ), select_new_prim=True, create_default_xform=False, ) paths = omni.usd.get_context().get_selection().get_selected_prim_paths() for path in paths: mesh = stage.GetPrimAtPath(path) helper = og.OmniGraphHelper() computer = helper.create_node(str(mesh.GetPath().AppendElementString(evaluator_name)), node_type) if isParentOwned: return parentPrim, mesh, computer else: return mesh, mesh, computer def init_common_attributes(prim): # parameter check # sschirm parameterCheckAttr = prim.CreateAttribute("proceduralMesh:parameterCheck", Sdf.ValueTypeNames.Int) parameterCheckAttr.Set(0) # basic attributes pointsAttr = prim.GetAttribute("points") faceVertexCountsAttr = prim.GetAttribute("faceVertexCounts") faceVertexIndicesAttr = prim.GetAttribute("faceVertexIndices") # extent extentAttr = prim.GetAttribute("extent") def connect_common_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect parameterCheck attribute as in and output helper.connect(ognPrim, "proceduralMesh:parameterCheck", computer, "inputs:parameterCheck") helper.connect(computer, "outputs:parameterCheck", ognPrim, "proceduralMesh:parameterCheck") # connect basic attributes helper.connect(computer, "outputs:points", ognPrim, "points") helper.connect(computer, "outputs:faceVertexCounts", ognPrim, "faceVertexCounts") helper.connect(computer, "outputs:faceVertexIndices", ognPrim, "faceVertexIndices") # connect to extent helper.connect(computer, "outputs:extent", ognPrim, "extent") def init_crease_attributes(prim): creaseIndicesAttr = prim.GetAttribute("creaseIndices") creaseLengthsAttr = prim.GetAttribute("creaseLengths") creaseSharpnessesAttr = prim.GetAttribute("creaseSharpnesses") def connect_crease_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect smooth group related attributes helper.connect(computer, "outputs:creaseIndices", ognPrim, "creaseIndices") helper.connect(computer, "outputs:creaseLengths", ognPrim, "creaseLengths") helper.connect(computer, "outputs:creaseSharpnesses", ognPrim, "creaseSharpnesses") def init_corner_attributes(prim): cornerIndicesAttr = prim.GetAttribute("cornerIndices") cornerSharpnessesAttr = prim.GetAttribute("cornerSharpnesses") def connect_corner_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect smooth group related attributes helper.connect(computer, "outputs:cornerIndices", ognPrim, "cornerIndices") helper.connect(computer, "outputs:cornerSharpnesses", ognPrim, "cornerSharpnesses") def init_normals_facevarying_attributes(prim): mesh = UsdGeom.Mesh(prim) # authored normals only works when subdivision is none mesh.CreateSubdivisionSchemeAttr("none") normalsVar = mesh.CreatePrimvar("normals", Sdf.ValueTypeNames.Normal3fArray) normalsAttr = prim.GetAttribute("primvars:normals") normalIndicesAttr = prim.CreateAttribute("primvars:normals:indices", Sdf.ValueTypeNames.IntArray, False) normalsVar.SetInterpolation("faceVarying") def connect_normals_facevarying_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect normal related attributes helper.connect(computer, "outputs:normals", ognPrim, "primvars:normals") helper.connect(computer, "outputs:normalIndices", ognPrim, "primvars:normals:indices") def init_texture_coords_facevarying_attributes(prim): mesh = UsdGeom.Mesh(prim) # st related attributes stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying) stsAttr = prim.GetAttribute("primvars:st") stIndicesAttr = prim.CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False) def connect_texture_coords_facevarying_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect st related attributes helper.connect(computer, "outputs:sts", ognPrim, "primvars:st") helper.connect(computer, "outputs:stIndices", ognPrim, "primvars:st:indices") def init_texture_coords_attributes(prim): mesh = UsdGeom.Mesh(prim) # st related attributes stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex) stsAttr = prim.GetAttribute("primvars:st") def connect_texture_coords_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect st related attributes helper.connect(computer, "outputs:sts", ognPrim, "primvars:st") def create_procedural_mesh_cube( stage, parentPath=None, xLength=100, yLength=100, zLength=100, xResolution=10, yResolution=10, zResolution=10 ): root, cube, computer = create_mesh_computer( stage, "ProceduralMeshCube", "CubeEvaluator", "omni.kit.procedural.mesh.CreateMeshCube", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:xLength", xLength], ["inputs:yLength", yLength], ["inputs:zLength", zLength], ["inputs:xResolution", xResolution], ["inputs:yResolution", xResolution], ["inputs:zResolution", zResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cube) init_crease_attributes(cube) init_normals_facevarying_attributes(cube) init_texture_coords_facevarying_attributes(cube) connect_common_attributes(cube, computer) connect_crease_attributes(cube, computer) connect_normals_facevarying_attributes(cube, computer) connect_texture_coords_facevarying_attributes(cube, computer) return root, cube def create_procedural_mesh_sphere(stage, parentPath=None, diameter=100, longitudeResolution=10, latitudeResolution=10): root, sphere, computer = create_mesh_computer( stage, "ProceduralMeshSphere", "SphereEvaluator", "omni.kit.procedural.mesh.CreateMeshSphere", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(sphere) init_texture_coords_facevarying_attributes(sphere) connect_common_attributes(sphere, computer) connect_texture_coords_facevarying_attributes(sphere, computer) return root, sphere def create_procedural_mesh_capsule( stage, parentPath=None, diameter=100, yLength=200, longitudeResolution=10, hemisphereLatitudeResolution=10, middleLatitudeResolution=10, ): root, capsule, computer = create_mesh_computer( stage, "ProceduralMeshCapsule", "CapsuleEvaluator", "omni.kit.procedural.mesh.CreateMeshCapsule", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:yLength", yLength], ["inputs:longitudeResolution", longitudeResolution], ["inputs:hemisphereLatitudeResolution", hemisphereLatitudeResolution], ["inputs:middleLatitudeResolution", middleLatitudeResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(capsule) init_texture_coords_facevarying_attributes(capsule) connect_common_attributes(capsule, computer) connect_texture_coords_facevarying_attributes(capsule, computer) return root, capsule def create_procedural_mesh_cylinder( stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10 ): root, cylinder, computer = create_mesh_computer( stage, "ProceduralMeshCylinder", "CylinderEvaluator", "omni.kit.procedural.mesh.CreateMeshCylinder", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:height", height], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cylinder) init_crease_attributes(cylinder) init_normals_facevarying_attributes(cylinder) init_texture_coords_facevarying_attributes(cylinder) connect_common_attributes(cylinder, computer) connect_crease_attributes(cylinder, computer) connect_normals_facevarying_attributes(cylinder, computer) connect_texture_coords_facevarying_attributes(cylinder, computer) return root, cylinder def create_procedural_mesh_cone( stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10 ): root, cone, computer = create_mesh_computer( stage, "ProceduralMeshCone", "ConeEvaluator", "omni.kit.procedural.mesh.CreateMeshCone", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:height", height], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cone) init_crease_attributes(cone) init_corner_attributes(cone) init_normals_facevarying_attributes(cone) init_texture_coords_facevarying_attributes(cone) connect_common_attributes(cone, computer) connect_crease_attributes(cone, computer) connect_corner_attributes(cone, computer) connect_normals_facevarying_attributes(cone, computer) connect_texture_coords_facevarying_attributes(cone, computer) return root, cone def create_procedural_mesh_torus( stage, parentPath=None, diameter=200, sectionDiameter=50, sectionTwist=0, loopResolution=10, sectionResolution=10 ): root, torus, computer = create_mesh_computer( stage, "ProceduralMeshTorus", "TorusEvaluator", "omni.kit.procedural.mesh.CreateMeshTorus", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:sectionDiameter", sectionDiameter], ["inputs:sectionTwist", sectionTwist], ["inputs:loopResolution", loopResolution], ["inputs:sectionResolution", sectionResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(torus) init_texture_coords_facevarying_attributes(torus) connect_common_attributes(torus, computer) connect_texture_coords_facevarying_attributes(torus, computer) return root, torus def create_procedural_mesh_disk(stage, parentPath=None, diameter=100, longitudeResolution=10, capResolution=10): root, disk, computer = create_mesh_computer( stage, "ProceduralMeshDisk", "DiskEvaluator", "omni.kit.procedural.mesh.CreateMeshDisk", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:longitudeResolution", longitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(disk) init_texture_coords_attributes(disk) connect_common_attributes(disk, computer) connect_texture_coords_attributes(disk, computer) return root, disk def create_procedural_mesh_plane(stage, parentPath=None, xLength=100, zLength=100, xResolution=10, zResolution=10): root, plane, computer = create_mesh_computer( stage, "ProceduralMeshPlane", "PlaneEvaluator", "omni.kit.procedural.mesh.CreateMeshPlane", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:xLength", xLength], ["inputs:zLength", zLength], ["inputs:xResolution", xResolution], ["inputs:zResolution", zResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(plane) init_texture_coords_attributes(plane) connect_common_attributes(plane, computer) connect_texture_coords_attributes(plane, computer) return root, plane
14,417
Python
33.910412
119
0.703614
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/menu.py
import omni.kit.ui import omni.usd # ====================================================================== MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cube' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Sphere' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Capsule' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cylinder' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cone' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Torus' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Plane' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Disk' ) class Menu: def __init__(self): self.on_startup() def on_startup(self): self.menus = [] editor_menu = omni.kit.ui.get_editor_menu() self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK, self._on_menu_click)) def _on_menu_click(self, menu_item, value): if menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE: omni.kit.commands.execute("CreateProceduralMeshCube") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE: omni.kit.commands.execute("CreateProceduralMeshSphere") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE: omni.kit.commands.execute("CreateProceduralMeshCapsule") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER: omni.kit.commands.execute("CreateProceduralMeshCylinder") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE: omni.kit.commands.execute("CreateProceduralMeshCone") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS: omni.kit.commands.execute("CreateProceduralMeshTorus") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE: omni.kit.commands.execute("CreateProceduralMeshPlane") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK: omni.kit.commands.execute("CreateProceduralMeshDisk") def on_shutdown(self): self.menus = []
3,576
Python
50.840579
114
0.694631
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/command.py
import omni from pxr import UsdGeom, Usd, Vt, Kind, Sdf from .procedural_mesh_omnigraph_utils import ( create_procedural_mesh_cube, create_procedural_mesh_sphere, create_procedural_mesh_capsule, create_procedural_mesh_cylinder, create_procedural_mesh_cone, create_procedural_mesh_torus, create_procedural_mesh_plane, create_procedural_mesh_disk, ) class CreateProceduralMeshCommand(omni.kit.commands.Command): def __init__(self): self._create = None self._stage = omni.usd.get_context().get_stage() self._selection = omni.usd.get_context().get_selection() def do(self): xForm, mesh = self._create(self._stage) self._prim_path = xForm.GetPath() # set the new prim as the active selection self._selection.set_prim_path_selected(self._prim_path.pathString, True, False, True, True) return xForm def undo(self): prim = self._stage.GetPrimAtPath(self._prim_path) if prim: self._stage.RemovePrim(self._prim_path) class CreateProceduralMeshCubeCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cube class CreateProceduralMeshSphereCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_sphere class CreateProceduralMeshCapsuleCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_capsule class CreateProceduralMeshCylinderCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cylinder class CreateProceduralMeshConeCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cone class CreateProceduralMeshTorusCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_torus class CreateProceduralMeshPlaneCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_plane class CreateProceduralMeshDiskCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_disk omni.kit.commands.register(CreateProceduralMeshCubeCommand) omni.kit.commands.register(CreateProceduralMeshSphereCommand) omni.kit.commands.register(CreateProceduralMeshCapsuleCommand) omni.kit.commands.register(CreateProceduralMeshCylinderCommand) omni.kit.commands.register(CreateProceduralMeshConeCommand) omni.kit.commands.register(CreateProceduralMeshTorusCommand) omni.kit.commands.register(CreateProceduralMeshPlaneCommand) omni.kit.commands.register(CreateProceduralMeshDiskCommand)
2,939
Python
31.307692
99
0.714869
omniverse-code/kit/exts/omni.kit.gfn/PACKAGE-LICENSES/omni.kit.gfn-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.gfn/config/extension.toml
[package] title = "NVIDIA GFN Integration" category = "Streaming" # Semantic Versioning is used: https://semver.org/ version = "1.1.0" [dependencies] #"omni.usd" = {} [[python.module]] name = "omni.kit.gfn" [[native.plugin]] path = "bin/*.plugin" recursive = false [settings] #exts."omni.kit.gfn".enable = false [[test]] waiver = "Tests are in omni.gfn.autoload"
369
TOML
15.086956
50
0.674797
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/__init__.py
from ._kit_gfn import * # Cached interface instance pointer def get_geforcenow_interface() -> IGeForceNow: """Returns cached :class:`omni.kit.gfn.IGeForceNow` interface""" if not hasattr(get_geforcenow_interface, "geforcenow"): get_geforcenow_interface.geforcenow = acquire_geforcenow_interface() return get_geforcenow_interface.geforcenow
362
Python
35.299996
76
0.745856
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/_kit_gfn.pyi
"""pybind11 omni.kit.gfn bindings""" from __future__ import annotations import omni.kit.gfn._kit_gfn import typing __all__ = [ "IGeForceNow", "acquire_geforcenow_interface", "release_geforcenow_interface" ] class IGeForceNow(): def get_partner_secure_data(self) -> str: ... def shutdown(self) -> None: ... def startup(self, sdk_library_path: str = '') -> None: ... pass def acquire_geforcenow_interface(plugin_name: str = None, library_path: str = None) -> IGeForceNow: pass def release_geforcenow_interface(arg0: IGeForceNow) -> None: pass
580
unknown
25.40909
99
0.668966
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/thumbnail_grid.py
from functools import partial from typing import Callable, Dict, List, Optional import omni.ui as ui from omni.ui import constant as fl from .style import ICON_PATH class ThumbnailItem(ui.AbstractItem): """ Data item for a thumbnail. Args: thumbnail (str): Url to thumbnail. url (str): Url to item. text (str): Display text for this item. Default use file name of url. """ def __init__(self, thumbnail: str, url: str, text: Optional[str] = None): self.thumbnail = thumbnail self.url = url self.text = text if text else url.split("/")[-1] super().__init__() def execute(self): pass class ThumbnailModel(ui.AbstractItemModel): """ Data model for thumbnail items. Args: items (List[ThumbnailItem]): List of thumbnail items """ def __init__(self, items: List[ThumbnailItem]): super().__init__() self._items = items def get_item_children(self, item: Optional[ThumbnailItem] = None) -> List[ThumbnailItem]: return self._items class ThumbnailGrid: """ Widget to show a grid (thumbnail + label). Args: model (ThumbnailModel): Data model. label_height (int): Height for item label. Default 30. thumbnail_width (int): Thumbnail width. Default 128. thumbnail_height (int): Thumbnail height. Default 128. thumbnail_padding_x (int): X padding between different thumbnail items. Default 2. thumbnail_padding_y (int): Y padding between different thumbnail items. Default 4. """ def __init__( self, model: ThumbnailModel, on_selection_changed: Callable[[Optional[ThumbnailItem]], None] = None, label_height:int=fl._find("welcome_open_lable_size"), thumbnail_width: int=fl._find("welcome_open_thumbnail_size"), thumbnail_height: int=fl._find("welcome_open_thumbnail_size"), thumbnail_padding_x: int=2, thumbnail_padding_y: int=4, ): self._model = model self._on_selection_changed = on_selection_changed self._label_height = label_height self._thumbnail_width = thumbnail_width self._thumbnail_height = thumbnail_height self._thumbnail_padding_x = thumbnail_padding_x self._thumbnail_padding_y = thumbnail_padding_y self._column_width = self._thumbnail_width + 2 * self._thumbnail_padding_x self._row_height = self._thumbnail_height + 2 * self._thumbnail_padding_y + self._label_height self.__selected_thumbnail: Optional[ThumbnailItem] = None self.__frames: Dict[ThumbnailItem, ui.Frame] = {} self._build_ui() @property def selected(self) -> Optional[ThumbnailItem]: return self.__selected_thumbnail @selected.setter def selected(self, item: Optional[ThumbnailItem]) -> None: self.select_item(item) def _build_ui(self): self._container = ui.ScrollingFrame( style_type_name_override="ThumbnailGrid.Frame", vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ) self._refresh() self._sub_model = self._model.subscribe_item_changed_fn(lambda m, i: self._refresh()) def _refresh(self): self._container.clear() with self._container: self._grid = ui.VGrid( column_width=self._column_width, row_hegiht=self._row_height, content_clipping=True, ) with self._grid: children = self._model.get_item_children() if not children: return for item in children: with ui.VStack(): ui.Spacer(height=self._thumbnail_padding_y) with ui.HStack(): ui.Spacer(width=self._thumbnail_padding_x) self.__frames[item] = ui.Frame( build_fn=lambda i=item: self._build_thumbnail_item(i), mouse_double_clicked_fn=lambda x, y, a, f, i=item: i.execute(), mouse_pressed_fn=lambda x, y, a, f, i=item: self.select_item(i), ) ui.Spacer(width=self._thumbnail_padding_x) ui.Spacer(height=self._thumbnail_padding_y) self._grid.set_mouse_pressed_fn(lambda x, y, btn, flag: self.select_item(None)) def _build_thumbnail_item(self, item: ThumbnailItem) -> None: with ui.ZStack(): with ui.VStack(): self.build_thumbnail(item) self.build_label(item) ui.Rectangle(style_type_name_override="ThumbnailGrid.Selection") def build_thumbnail(self, item: ThumbnailItem) -> None: def on_image_progress(default_image: ui.Image, 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 default_image at the back. default_image.visible = False # Remove the callback to avoid circular references. thumbnail_image.set_progress_changed_fn(None) with ui.ZStack(width=self._thumbnail_width, height=self._thumbnail_height): # Default image for thumbnail not defined or invalid thumbnail url or download in progress # Hidden when actually thumbnail downloaded default_image = ui.Image(f"{ICON_PATH}/usd_stage_256.png", style_type_name_override="ThumbnailGrid.Image") if item.thumbnail: thumbnail_image = ui.Image(item.thumbnail, style_type_name_override="ThumbnailGrid.Image") thumbnail_image.set_progress_changed_fn(partial(on_image_progress, default_image, thumbnail_image)) def build_label(self, item: ThumbnailItem) -> None: with ui.ZStack(): ui.Rectangle(style_type_name_override="ThumbnailGrid.Item.Background") ui.Label( item.text, height=self._label_height, word_wrap=True, elided_text=True, skip_draw_when_clipped=True, alignment=ui.Alignment.CENTER, style_type_name_override="ThumbnailGrid.Item", ) def select_item(self, item: Optional[ThumbnailItem]) -> None: if self.__selected_thumbnail: self.__frames[self.__selected_thumbnail].selected = False if item: self.__frames[item].selected = True self.__selected_thumbnail = item if self._on_selection_changed: self._on_selection_changed(item) def find_item(self, url: str) -> Optional[ThumbnailItem]: for item in self._model.get_item_children(None): if item.url == url: return item return None def select_url(self, url: str) -> None: if url: item = self.find_item(url) self.select_item(item) else: self.select_item(None)
7,367
Python
38.612903
118
0.586806
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/stage_tab.py
from typing import Optional import carb import omni.ui as ui from omni.ui import constant as fl from omni.kit.welcome.window import show_window as show_welcome_window from .recent_widget import RecentWidget from .template_grid import TemplateGrid from .thumbnail_grid import ThumbnailItem SETTING_SHOW_TEMPLATES = "/exts/omni.kit.welcome.open/show_templates" class StageTab: """ Tab to show stage content. """ def __init__(self): self._checkpoint_combobox = None self._build_ui() def destroy(self): self._recent_widget.destroy() def _build_ui(self): with ui.VStack(): # Templates if carb.settings.get_settings().get_as_bool(SETTING_SHOW_TEMPLATES): with ui.HStack(height=0): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.VStack(): ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator") ui.Label("NEW", height=0, style_type_name_override="ThumbnailGrid.Title") ui.Spacer(height=10) ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.HStack(height=fl._find("welcome_open_thumbnail_size") + fl._find("welcome_open_lable_size") + 60): ui.Spacer(width=8) self._template_grid = TemplateGrid(on_selection_changed=self.__on_template_selected) ui.Spacer(width=8) # Recent files with ui.HStack(height=0): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.VStack(): ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator") with ui.HStack(height=20): ui.Label("RECENT", width=0, style_type_name_override="ThumbnailGrid.Title") ui.Spacer() self._mode_image = ui.Image(name="grid", width=20, style_type_name_override="ThumbnailGrid.Mode", mouse_pressed_fn=lambda x, y, b,a: self.__toggle_thumbnail_model()) ui.Spacer(height=10) ui.Spacer(width=fl._find("welcome_content_padding_x")) self._recent_widget = RecentWidget(self.__on_recent_selected, self.__on_grid_mode) # Open widgets with ui.ZStack(height=26): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(spacing=2): self._checkpoint_blank = ui.Rectangle(style_type_name_override="Stage.Blank") self._checkpoint_frame = ui.Frame(build_fn=self.__build_checkpoints, visible=False) # Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_file()) ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False)) def __toggle_thumbnail_model(self): if self._mode_image.name == "grid": self._mode_image.name = "table" self._recent_widget.show_grid(False) else: self._mode_image.name = "grid" self._recent_widget.show_grid(True) def __build_checkpoints(self): try: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.widget.versioning", True) from omni.kit.widget.versioning import CheckpointCombobox with ui.HStack(spacing=2): with ui.ZStack(content_clipping=True, width=0): ui.Rectangle(style_type_name_override="Stage.Blank") ui.Label("Checkpoints", width=0, style_type_name_override="Stage.Label") self._checkpoint_combobox = CheckpointCombobox( self._recent_widget.selected_url if self._recent_widget.selected_url else "", None, width=ui.Fraction(1), has_pre_spacer=False, popup_width=0, modal=True ) except Exception as e: carb.log_warn(f"Failed to create checkpoint combobox: {e}") self._checkpoint_combobox = None def __on_template_selected(self, item: Optional[ThumbnailItem]): if item: # Clear selection in recents self._recent_widget.selected_url = None # Hide checkpoint combobox self._checkpoint_frame.visible = False self._checkpoint_blank.visible = True def __on_recent_selected(self, item: Optional[ui.AbstractItem]): if item: # Clear selection in templates self._template_grid.selected = None if isinstance(item, ThumbnailItem): # Show checkpoint combobox if selected in recent grid self._checkpoint_frame.visible = bool(item) self._checkpoint_blank.visible = not bool(item) if item and self._checkpoint_combobox: self._checkpoint_combobox.url = item.url def __on_grid_mode(self, grid_mode: bool) -> None: # Show checkpoint combobox in grid mode and recent file selected if grid_mode: show_checkpoint = bool(self._recent_widget.selected_url) self._checkpoint_frame.visible = show_checkpoint self._checkpoint_blank.visible = not show_checkpoint else: self._checkpoint_frame.visible = False self._checkpoint_blank.visible = True def __open_file(self) -> None: selected = self._template_grid.selected if selected: carb.log_info(f"Open template: {selected.url}") selected.execute() else: self._recent_widget.open_selected(self._checkpoint_combobox.url if self._checkpoint_combobox else None)
6,253
Python
44.985294
189
0.58244
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/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") fl.welcome_open_thumbnail_size = 145 fl.welcome_open_lable_size = 30 cl.welcome_open_item_selected = cl.shade(cl("#77878A")) cl.welcome_open_label = cl.shade(cl("#9E9E9E")) OPEN_PAGE_STYLE = { "RadioButton": {"background_color": cl.transparent, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "padding": 0, "margin": 0}, "RadioButton.Label": {"font_size": fl.welcome_title_font_size, "color": cl.welcome_label, "alignment": ui.Alignment.LEFT_CENTER}, "RadioButton.Label:checked": {"color": cl.welcome_label_selected}, "RadioButton:checked": {"background_color": cl.transparent}, "RadioButton:hovered": {"background_color": cl.transparent}, "RadioButton:pressed": {"background_color": cl.transparent}, "RadioButton.Image::STAGE": {"image_url": f"{ICON_PATH}/USD.svg"}, "RadioButton.Image::SAMPLES": {"image_url": f"{ICON_PATH}/image.svg"}, "RadioButton.Image::FILE": {"image_url": f"{ICON_PATH}/hdd.svg"}, "RadioButton.Image": {"color": cl.welcome_label, "alignment": ui.Alignment.RIGHT_CENTER}, "RadioButton.Image:checked": {"color": cl.welcome_label_selected}, "ThumbnailGrid.Separator": {"color": cl.welcome_window_background, "border_width": 1.5}, "ThumbnailGrid.Title": {"color": 0xFFCCCCCC, "font_size": fl.welcome_title_font_size}, "ThumbnailGrid.Mode": {"margin": 2}, "ThumbnailGrid.Mode::grid": {"image_url": f"{ICON_PATH}/thumbnail.svg"}, "ThumbnailGrid.Mode::table": {"image_url": f"{ICON_PATH}/list.svg"}, "ThumbnailGrid.Frame": { "background_color": cl.transparent, "secondary_color": 0xFF808080, "border_radius": 0, "scrollbar_size": 10, }, "ThumbnailGrid.Selection": { "background_color": cl.transparent, }, "ThumbnailGrid.Selection:selected": { "border_width": 1, "border_color": cl.welcome_open_item_selected, "border_radius": 0, }, "ThumbnailGrid.Item.Background": { "background_color": cl.transparent, }, "ThumbnailGrid.Item.Background:selected": { "background_color": 0xFF525252, }, "ThumbnailGrid.Item": { "margin_width": 2, "color": cl.welcome_label, }, "Template.Add": {"color": 0xFFFFFFFF}, "Template.Add:hovered": {"color": cl.welcome_label_selected}, "Template.Add:pressed": {"color": cl.welcome_label_selected}, "Template.Add:selected": {"color": cl.welcome_label_selected}, "Stage.Label": {"color": cl.welcome_open_label, "margin_width": 6}, "Stage.Button": { "background_color": 0xFF23211F, "selected_color": 0xFF8A8777, "color": cl.welcome_open_label, "margin": 0, "padding": 0 }, "Stage.Button:hovered": {"background_color": 0xFF3A3A3A}, "Stage.Button.Label": {"color": cl.welcome_open_label}, "Stage.Button.Label:disabled": {"color": 0xFF3A3A3A}, "Stage.Separator": {"background_color": cl.welcome_window_background}, "Stage.Blank": {"background_color": cl.welcome_content_background}, }
3,242
Python
41.116883
133
0.652067
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/extension.py
from typing import Optional import omni.ext import omni.ui as ui from omni.kit.welcome.window import register_page from .open_widget import OpenWidget class OpenPageExtension(omni.ext.IExt): def on_startup(self, ext_id): self._widget: Optional[OpenWidget] = None self.__ext_name = omni.ext.get_extension_name(ext_id) register_page(self.__ext_name, self.build_ui) def on_shutdown(self): if self._widget: self._widget.destroy() self._widget = None def build_ui(self) -> None: self._widget = OpenWidget()
585
Python
23.416666
61
0.652991
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_widget.py
import asyncio import os from typing import Callable, List, Optional import carb.settings import omni.ui as ui from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel SETTING_RECENT_FILES = "/persistent/app/file/recentFiles" class RecentItem(ThumbnailItem): """ Data item for recent file. """ def __init__(self, url: str): super().__init__(self.__get_thumbnail(url), url) def __get_thumbnail(self, url: str): file_name = os.path.basename(url) path = os.path.dirname(url) # Do not check if thumbnail image exists here, leave it to ThumbnailGrid return f"{path}/.thumbs/256x256/{file_name}.png" def execute(self, url: Optional[str] = None): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", url if url else self.url) class RecentModel(ThumbnailModel): """ Data model for recent files. """ def __init__(self, recent_files: List[str]): super().__init__([]) self.refresh(recent_files) def refresh(self, recent_files: List[str]) -> None: self._items = [RecentItem(recent) for recent in recent_files] if recent_files else [] self._item_changed(None) class RecentWidget: """ Show recents grid and open widgets. """ def __init__(self, on_recent_changed_fn: Callable[[Optional[ui.AbstractItem]], None], on_grid_mode_fn: Callable[[bool], None]): self._settings = carb.settings.get_settings() self.__get_recent_history() self._grid_model = RecentModel(self.__recent_files) self._recent_table: Optional[RecentTable] = None self.__on_recent_selected_fn = on_recent_changed_fn self.__on_grid_mode_fn = on_grid_mode_fn self._build_ui() def destroy(self): self._subscription = None self._event_sub = None @property def selected_url(self) -> str: if self._grid_frame.visible: return self._recent_grid.selected.url if self._recent_grid.selected else "" else: return self._recent_table.selected @selected_url.setter def selected_url(self, url: str) -> None: if self._grid_frame.visible: self._recent_grid.select_url(url) else: self._recent_table.selected = url def clear_selection(self): if self._grid_frame.visible: self._recent_grid.selected = None else: self._recent_table.selected = None def show_grid(self, grid: bool) -> None: self._grid_frame.visible = grid self._table_frame.visible = not grid if grid: # Set grid selection from table if self._recent_table: self._recent_grid.select_url(self._recent_table.selected) else: # Set table selection from grid if self._recent_table: if self._recent_grid.selected: self._recent_table.selected = self._recent_grid.selected.url else: # Wait for widget create and set selection async def __delay_select(): await omni.kit.app.get_app().next_update_async() if self._recent_grid.selected: self._recent_table.selected = self._recent_grid.selected.url asyncio.ensure_future(__delay_select()) self.__on_grid_mode_fn(grid) def open_selected(self, checkpoint_url: Optional[str]) -> None: def __open_file(url): carb.log_info(f"Open recent file: {url}") from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", url) if self.selected_url: if self._grid_frame.visible: __open_file(checkpoint_url or self.selected_url) else: __open_file(self._recent_table.get_filename()) def _build_ui(self): with ui.ZStack(): self._grid_frame = ui.Frame(build_fn=self._build_grid_ui) self._table_frame = ui.Frame(build_fn=self._build_table_ui, visible=False) def _build_table_ui(self): try: from .recent_table import RecentTable self._recent_table = RecentTable(self.__recent_files, on_selection_changed_fn=self.__on_recent_selected_fn) except Exception as e: self._recent_table = None carb.log_error(f"Failed to create recent table: {e}") def _build_grid_ui(self): with ui.VStack(): # Recent grid with ui.HStack(): ui.Spacer(width=8) self._recent_grid = ThumbnailGrid(self._grid_model, on_selection_changed=self.__on_recent_selected_fn) ui.Spacer(width=8) def _on_change(self, item, event_type): if event_type == carb.settings.ChangeEventType.CHANGED: self.__recent_files = self._settings.get(SETTING_RECENT_FILES) self.__rebuild_recents() def __rebuild_recents_from_event(self) -> None: from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD) if self._recent_table: self._recent_table.refresh(self.__recent_files) self._grid_model.refresh(self.__recent_files) def __get_recent_history(self): load_recents_from_event = self._settings.get("/exts/omni.kit.welcome.open/load_recent_from_event") if load_recents_from_event: self.__get_recent_from_event() else: self.__recent_files = self._settings.get(SETTING_RECENT_FILES) # If recent files changed, refresh self._subscription = omni.kit.app.SettingChangeSubscription(SETTING_RECENT_FILES, self._on_change) def __get_recent_from_event(self) -> None: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.helper.file_utils", True) from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED self._max_recent_files = self._settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10 self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD) event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self.__rebuild_recents_from_event())
6,736
Python
39.10119
146
0.614757
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_action.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["run_open_action"] import asyncio def run_open_action(extension_id: str, action_id: str, *args, **kwargs): import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() # Setup the viewport (and UI first) action_registry.execute_action("omni.app.setup", "enable_viewport_rendering") # Finally hide the Welcome window from omni.kit.welcome.window import show_window as show_welcome_window show_welcome_window(visible=False, stage_opened=True) # Run the action which will open or create a Usd.Stage async def __execute_action(): import omni.kit.app # OM-90720: sometimes open stage will popup a prompt to ask if save current stage # But the prompt is a popup window which will hide immediately if the welcome window (modal) still there # As a result, the required stage will not be opened # So here wait a few frames to make sure welcome window is really closed for _ in range(4): await omni.kit.app.get_app().next_update_async() action_registry.execute_action(extension_id, action_id, *args, **kwargs) asyncio.ensure_future(__execute_action())
1,624
Python
45.42857
112
0.723522
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_widget.py
from typing import Dict, Optional import carb import omni.ui as ui from omni.kit.welcome.window import show_window as show_welcome_window from omni.ui import constant as fl from .stage_tab import StageTab from .style import OPEN_PAGE_STYLE class OpenWidget: """ Widget for open page. """ def __init__(self): self.__tabs: Dict[str, callable] = { "STAGE": self.__build_stage, "SAMPLES": self.__build_sample, "FILE": self.__build_file, } self.__tab_frames: Dict[str, ui.Frame] = {} self.__stage_tab: Optional[StageTab] = None self._build_ui() def destroy(self): if self.__stage_tab: self.__stage_tab.destroy() self.__stage_tab = None def _build_ui(self): self._collection = ui.RadioCollection() with ui.ZStack(style=OPEN_PAGE_STYLE): # Background ui.Rectangle(style_type_name_override="Content") with ui.VStack(): # Tab buttons with ui.VStack(height=fl._find("welcome_page_title_height")): ui.Spacer() with ui.HStack(height=0): ui.Spacer() with ui.HStack(spacing=30): for tab in self.__tabs.keys(): ui.RadioButton(text=tab, width=0, spacing=8, image_width=24, image_height=24, name=tab, radio_collection=self._collection, clicked_fn=lambda t=tab: self._show_tab(t)) ui.Spacer() ui.Spacer() # Tab frames with ui.ZStack(): for tab in self.__tabs.keys(): self.__tab_frames[tab] = ui.Frame(build_fn=lambda t=tab: self.__tabs[t](), visible=tab == "STAGE") def _show_tab(self, name: str) -> None: for tab in self.__tabs.keys(): if tab == name: self.__tab_frames[name].visible = True else: self.__tab_frames[tab].visible = False def __build_stage(self): self.__stage_tab = StageTab() def __build_sample(self): try: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.browser.sample", True) from omni.kit.browser.sample import get_instance as get_sample_instance from omni.kit.browser.sample.browser_widget import SampleTreeFolderBrowserWidget from omni.kit.browser.core import BrowserSearchBar # Remove options button class SampleWidget(SampleTreeFolderBrowserWidget): def _build_search_bar(self): self._search_bar = BrowserSearchBar(options_menu=None) # Hack to close welcome window after sample opened def __open_sample(item): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", item.url) model = get_sample_instance().get_model() model.execute = __open_sample # Sample widget with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=2) self.__sample_widget = SampleWidget(model) # Open widgets with ui.ZStack(height=26): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(spacing=2): ui.Rectangle(style_type_name_override="Stage.Blank") # Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_sample()) ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False)) except Exception as e: carb.log_error(f"Failed to import sample browser widget: {e}") def __build_file(self): try: from omni.kit.window.filepicker import FilePickerWidget def __open_file(file_name, dir_name): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", dir_name + file_name) with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(): ui.Spacer(width=2) FilePickerWidget( "Welcome", enable_checkpoints=True, apply_button_label="Open File", cancel_button_label="Close", click_apply_handler=__open_file, click_cancel_handler=lambda f, d: show_welcome_window(visible=False), modal=True, ) except Exception as e: carb.log_error(f"Failed to import file picker widget: {e}") def __open_sample(self): selections = self.__sample_widget.detail_selection if selections: self.__sample_widget._browser_model.execute(selections[0]) show_welcome_window(visible=False)
5,849
Python
42.333333
198
0.526586
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_table.py
import os from typing import List, Optional import omni.client import omni.ui as ui from omni.kit.widget.filebrowser import LAYOUT_SINGLE_PANE_LIST, LISTVIEW_PANE, FileBrowserItem, FileBrowserModel from omni.kit.widget.filebrowser.model import FileBrowserItemFields from omni.kit.window.filepicker import FilePickerWidget class RecentTableModel(FileBrowserModel): def __init__(self, recent_files: List[str]): super().__init__() self.refresh(recent_files) def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]: return self._items def refresh(self, recent_files: List[str]): if recent_files: self._items = [self.__create_file_item(url) for url in recent_files] else: self._items = [] self._item_changed(None) def __create_file_item(self, url: str) -> Optional[FileBrowserItem]: file_name = os.path.basename(url) result, entry = omni.client.stat(url) if result == omni.client.Result.OK: item = FileBrowserItem(url, FileBrowserItemFields(file_name, entry.modified_time, 0, 0), is_folder=False) item._models = (ui.SimpleStringModel(item.name), entry.modified_time, ui.SimpleStringModel("")) return item else: return None class RecentTable: def __init__(self, recent_files: List[str], on_selection_changed_fn: callable): self.__recent_files = recent_files self.__picker: Optional[FilePickerWidget] = None self.__on_selection_changed_fn = on_selection_changed_fn self._build_ui() @property def selected(self) -> str: if self.__picker: selections = self.__picker._view.get_selections(pane=LISTVIEW_PANE) if selections: return selections[0].path else: return "" else: return "" @selected.setter def selected(self, url: str) -> None: if self.__picker: if url: for item in self._model.get_item_children(None): if item.path == url: selections = [item] else: selections = [] self.__picker._view.set_selections(selections, pane=LISTVIEW_PANE) def refresh(self, recent_files: List[str]): self._model.refresh(recent_files) def get_filename(self) -> str: return self.__picker._api.get_filename() if self.__picker else "" def _build_ui(self): with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(): self.__picker = FilePickerWidget( "Welcome", enable_tool_bar=False, layout=LAYOUT_SINGLE_PANE_LIST, show_grid_view=False, save_grid_view=False, enable_checkpoints=True, enable_zoombar=False, enable_file_bar=False, selection_changed_fn=self.__on_selection_changed_fn, ) self._model = RecentTableModel(self.__recent_files) self.__picker._view.show_model(self._model)
3,377
Python
35.717391
117
0.568256
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/render_loading.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["start_render_loading_ui"] def start_render_loading_ui(ext_manager, renderer: str): import carb import time time_begin = time.time() carb.settings.get_settings().set("/exts/omni.kit.viewport.ready/startup/enabled", False) ext_manager.set_extension_enabled_immediate("omni.kit.viewport.ready", True) from omni.kit.viewport.ready.viewport_ready import ViewportReady, ViewportReadyDelegate class TimerDelegate(ViewportReadyDelegate): def __init__(self, time_begin): super().__init__() self.__timer_start = time.time() self.__vp_ready_cost = self.__timer_start - time_begin @property def font_size(self) -> float: return 48 @property def message(self) -> str: rtx_mode = { "RaytracedLighting": "Real-Time", "PathTracing": "Interactive (Path Tracing)", "LightspeedAperture": "Aperture (Game Path Tracer)" }.get(carb.settings.get_settings().get("/rtx/rendermode"), "Real-Time") renderer_label = { "rtx": f"RTX - {rtx_mode}", "iray": "RTX - Accurate (Iray)", "pxr": "Pixar Storm", "index": "RTX - Scientific (IndeX)" }.get(renderer, renderer) return f"Waiting for {renderer_label} to start" def on_complete(self): rtx_load_time = time.time() - self.__timer_start super().on_complete() print(f"Time until pixel: {rtx_load_time}") print(f"ViewportReady cost: {self.__vp_ready_cost}") return ViewportReady(TimerDelegate(time_begin))
2,121
Python
37.581817
92
0.619991
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/template_grid.py
import functools import locale from typing import List import omni.kit.stage_templates import omni.ui as ui from omni.kit.welcome.window import show_window from .style import ICON_PATH from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel import asyncio class TemplateItem(ThumbnailItem): """ Data item for template. """ def __init__(self, template: list): # TODO: how to get template thumbnail? stage_name = template[0] super().__init__("", stage_name) def execute(self): from .open_action import run_open_action run_open_action("omni.kit.stage.templates", self.__get_action_name()) def __get_action_name(self): return "create_new_stage_" + self.url.lower().replace('-', '_').replace(' ', '_') class TemplateModel(ThumbnailModel): """ Data model for templates. """ def __init__(self): stage_templates = omni.kit.stage_templates.get_stage_template_list() template_items: List[ThumbnailItem] = [] def sort_cmp(template1, template2): return locale.strcoll(template1[0], template2[0]) for template_list in stage_templates: for template in sorted(template_list.items(), key=functools.cmp_to_key(sort_cmp)): template_items.append(TemplateItem(template)) super().__init__(template_items) class TemplateGrid(ThumbnailGrid): """ Template grid. """ def __init__(self, **kwargs): self._model = TemplateModel() super().__init__(self._model, **kwargs) def build_thumbnail(self, item: ThumbnailItem): padding = 5 with ui.ZStack(): super().build_thumbnail(item) with ui.VStack(): ui.Spacer() with ui.HStack(height=20): ui.Spacer() ui.Image( f"{ICON_PATH}/add_dark.svg", width=20, style_type_name_override="Template.Add", mouse_pressed_fn=lambda x, y, a, f, i=item: i.execute() ) ui.Spacer(width=padding) ui.Spacer(height=padding)
2,216
Python
29.791666
94
0.576715
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/tests/test_page.py
import asyncio from pathlib import Path import omni.kit.app from omni.ui.tests.test_base import OmniUiTest from ..extension import OpenPageExtension CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") class TestPage(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() # After running each test async def tearDown(self): await super().tearDown() async def test_page(self): window = await self.create_test_window(width=800, height=800) with window.frame: ext = OpenPageExtension() ext.on_startup("omni.kit.welcome.open-1.1.0") ext.build_ui() await omni.kit.app.get_app().next_update_async() # OM-92413: Wait for icons loaded await asyncio.sleep(8) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="page.png")
1,074
Python
29.714285
99
0.667598
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/tests/__init__.py
from .test_page import *
24
Python
23.999976
24
0.75
omniverse-code/kit/exts/omni.kit.welcome.open/docs/index.rst
omni.kit.welcome.open ########################### .. toctree:: :maxdepth: 1 CHANGELOG
94
reStructuredText
10.874999
27
0.457447
omniverse-code/kit/exts/omni.kit.selection/PACKAGE-LICENSES/omni.kit.selection-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.selection/config/extension.toml
[package] version = "0.1.0" category = "Internal" [dependencies] "omni.kit.commands" = {} "omni.ui" = {} "omni.usd" = {} [[python.module]] name = "omni.kit.selection"
169
TOML
13.166666
27
0.621302
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection_actions.py
import omni.kit.actions.core def register_actions(extension_id): import omni.kit.commands action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Selection Actions" action_registry.register_action( extension_id, "all", lambda: omni.kit.commands.execute("SelectAll"), display_name="Select->All", description="Select all prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "none", lambda: omni.kit.commands.execute("SelectNone"), display_name="Select->None", description="Deselect all prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "invert", lambda: omni.kit.commands.execute("SelectInvert"), display_name="Select->Invert", description="Deselect all currently unselected prims, and select all currently unselected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "parent", lambda: omni.kit.commands.execute("SelectParentCommand"), display_name="Select->Parent", description="Select the parents of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "leaf", lambda: omni.kit.commands.execute("SelectLeafCommand"), display_name="Select->Leaf", description="Select the leafs of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "hierarchy", lambda: omni.kit.commands.execute("SelectHierarchyCommand"), display_name="Select->Hierarchy", description="Select the hierachies of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "similar", lambda: omni.kit.commands.execute("SelectSimilarCommand"), display_name="Select->Similar", description="Select prims of the same type as any currently selected prim.", tag=actions_tag, ) action_registry.register_action( extension_id, "HideUnselected", lambda: omni.kit.commands.execute("HideUnselected"), display_name="Select->Hide Unselected", description="Hide Unselected Prims", tag=actions_tag, ) action_registry.register_action( extension_id, "UnhideAllPrims", lambda: omni.kit.commands.execute("UnhideAllPrims"), display_name="Select->Unhide All Prims", description="Unhide All Prims", 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)
2,880
Python
31.370786
106
0.639931
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/__init__.py
from .selection import *
25
Python
11.999994
24
0.76
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection.py
import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, Trace, Kind from .selection_actions import register_actions, deregister_actions class SelectionExtension(omni.ext.IExt): def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name) def on_shutdown(self): deregister_actions(self._ext_name) class SelectAllCommand(omni.kit.commands.Command): """ Select all prims. Args: type (Union[str, None]): Specific type name. If it's None, it will select all prims. If it has type str with value "", it will select all prims without any type. Otherwise, it will select prims with that type. """ def __init__(self, type=None): self._type = type self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() @Trace.TraceFunction def do(self): omni.usd.get_context().get_selection().select_all_prims(self._type) def undo(self): if self._prev_selection: omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) else: omni.usd.get_context().get_selection().clear_selected_prim_paths() class SelectNoneCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): omni.usd.get_context().get_selection().clear_selected_prim_paths() def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectInvertCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() @Trace.TraceFunction def do(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) omni.usd.get_context().get_selection().select_inverted_prims() def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class HideUnselectedCommand(omni.kit.commands.Command): def get_parent_prims(self, stage, prim): parent_prims = set([]) while prim.GetParent(): parent_prims.add(prim.GetParent().GetPath()) prim = prim.GetParent() if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: break return parent_prims def get_all_children(self, prim): children_list = set([]) queue = [prim] while len(queue) > 0: child_prim = queue.pop() for child in child_prim.GetAllChildren(): children_list.add(child.GetPath()) queue.append(child) return children_list def __init__(self): stage = omni.usd.get_context().get_stage() selection = omni.usd.get_context().get_selection().get_selected_prim_paths() # if selected path as children and none of the children are selected, then all the children are selected.. selected_prims = set([]) for prim_path in selection: sdf_prim_path = Sdf.Path(prim_path) prim = stage.GetPrimAtPath(sdf_prim_path) if prim: selected_prims.add(sdf_prim_path) selected_prims.update(self.get_all_children(prim)) ## exclude parent prims as visabillity is inherited all_parent_prims = set([]) for prim_path in selected_prims: prim = stage.GetPrimAtPath(prim_path) if prim: all_parent_prims.update(self.get_parent_prims(stage, prim)) selected_prims.update(all_parent_prims) all_prims = set([]) children_iterator = iter(stage.TraverseAll()) for prim in children_iterator: if omni.usd.is_hidden_type(prim): children_iterator.PruneChildren() continue all_prims.add(prim.GetPath()) self._invert_prims = [item for item in all_prims if item not in selected_prims] self._prev_visabillity = [] for prim_path in self._invert_prims: prim = stage.GetPrimAtPath(prim_path) if prim: if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: self._prev_visabillity.append([prim, imageable.ComputeVisibility()]) @Trace.TraceFunction def do(self): stage = omni.usd.get_context().get_stage() for prim_path in self._invert_prims: prim = stage.GetPrimAtPath(prim_path) if prim: if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: imageable.MakeInvisible() def undo(self): for prim, state in self._prev_visabillity: imageable = UsdGeom.Imageable(prim) if imageable: if state == UsdGeom.Tokens.invisible: imageable.MakeInvisible() else: imageable.MakeVisible() class SelectParentCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): stage = omni.usd.get_context().get_stage() parent_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) if prim and prim.GetParent() is not None: parent_prims.add(prim.GetParent().GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(parent_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectLeafCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def collect_leafs(self, prim, leaf_set): prim_children = prim.GetChildren() if not prim_children: leaf_set.add(prim.GetPath().pathString) else: for child in prim_children: self.collect_leafs(child, leaf_set) def do(self): stage = omni.usd.get_context().get_stage() leaf_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) self.collect_leafs(prim, leaf_prims) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(leaf_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectHierarchyCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def collect_hierarchy(self, prim, hierarchy_set): hierarchy_set.add(prim.GetPath().pathString) prim_children = prim.GetChildren() for child in prim_children: self.collect_hierarchy(child, hierarchy_set) def do(self): stage = omni.usd.get_context().get_stage() heirarchy_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) self.collect_hierarchy(prim, heirarchy_prims) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(heirarchy_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectSimilarCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): stage = omni.usd.get_context().get_stage() similar_prim_types = set() for prim_path in self._prev_selection: prim_type = stage.GetPrimAtPath(prim_path).GetTypeName() similar_prim_types.add(prim_type) omni.usd.get_context().get_selection().select_all_prims(sorted(list(similar_prim_types))) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectListCommand(omni.kit.commands.Command): def __init__(self, **kwargs): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() self._new_selection = [] if 'selection' in kwargs: self._new_selection = kwargs['selection'] def do(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._new_selection, True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectKindCommand(omni.kit.commands.Command): def __init__(self, **kwargs): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() self._kind = "" if 'kind' in kwargs: self._kind = kwargs['kind'] @Trace.TraceFunction def do(self): selection = [] for prim in omni.usd.get_context().get_stage().TraverseAll(): model_api = Usd.ModelAPI(prim) if Kind.Registry.IsA(model_api.GetKind(), self._kind): selection.append(str(prim.GetPath())) omni.usd.get_context().get_selection().set_selected_prim_paths(selection, True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
9,914
Python
36.415094
114
0.620637
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/create_prims.py
import os import carb import carb.settings import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux def create_test_stage(): settings = carb.settings.get_settings() default_prim_name = settings.get("/persistent/app/stage/defaultPrimName") rootname = f"/{default_prim_name}" stage = omni.usd.get_context().get_stage() kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}") omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl") # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False ) # create GroundMat material mtl_name = "GroundMat" mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=mtl_path ) ground_mat_prim = stage.GetPrimAtPath(mtl_path) shader = UsdShade.Material(ground_mat_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "specular_level", 0.25, Sdf.ValueTypeNames.Float) omni.usd.create_material_input( ground_mat_prim, "diffuse_color_constant", Gf.Vec3f(0.08, 0.08, 0.08), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "metallic_constant", 0.0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) # create BackSideMat mtl_name = "BackSideMat" backside_mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=backside_mtl_path ) backside_mtl_prim = stage.GetPrimAtPath(backside_mtl_path) shader = UsdShade.Material(backside_mtl_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input( backside_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0.11814344, 0.118142255, 0.118142255), Sdf.ValueTypeNames.Color3f, ) omni.usd.create_material_input(backside_mtl_prim, "reflection_roughness_constant", 0.27, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(backside_mtl_prim, "specular_level", 0.163, Sdf.ValueTypeNames.Float) # create EmissiveMat mtl_name = "EmissiveMat" emissive_mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=emissive_mtl_path ) emissive_mtl_prim = stage.GetPrimAtPath(emissive_mtl_path) shader = UsdShade.Material(emissive_mtl_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input( emissive_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0, 0, 0), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(emissive_mtl_prim, "reflection_roughness_constant", 1, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(emissive_mtl_prim, "specular_level", 0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(emissive_mtl_prim, "enable_emission", True, Sdf.ValueTypeNames.Bool) omni.usd.create_material_input(emissive_mtl_prim, "emissive_color", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(emissive_mtl_prim, "emissive_intensity", 15000, Sdf.ValueTypeNames.Float) # create studiohemisphere hemisphere_path = omni.usd.get_stage_next_free_path(stage, "{}/studiohemisphere".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_path, prim_type="Xform", select_new_prim=False, attributes={} ) hemisphere_prim = stage.GetPrimAtPath(hemisphere_path) UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) Usd.ModelAPI(hemisphere_prim).SetKind("group") # create sphere hemisphere_sphere_path = omni.usd.get_stage_next_free_path( stage, "{}/studiohemisphere/Sphere".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_sphere_path, prim_type="Sphere", select_new_prim=False, attributes={UsdGeom.Tokens.radius: 100}, ) hemisphere_prim = stage.GetPrimAtPath(hemisphere_sphere_path) Usd.ModelAPI(hemisphere_prim).SetKind("assembly") # set transform hemisphere_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(2500, 2500, 2500)) hemisphere_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=hemisphere_sphere_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create floor hemisphere_floor_path = omni.usd.get_stage_next_free_path( stage, "{}/studiohemisphere/Floor".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_floor_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100}, ) hemisphere_floor_prim = stage.GetPrimAtPath(hemisphere_floor_path) # set transform hemisphere_floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(2500, 0.1, 2500) ) hemisphere_floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) UsdGeom.PrimvarsAPI(hemisphere_floor_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=hemisphere_floor_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create LightPivot_01 light_pivot1_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_01".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot1_prim = stage.GetPrimAtPath(light_pivot1_path) UsdGeom.PrimvarsAPI(light_pivot1_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot1_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot1_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(-30.453436397207547, 16.954190666353664, 9.728788165428536) ) light_pivot1_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0.9999999445969171, 1.000000574567198, 0.9999995086845976) ) light_pivot1_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight light_pivot1_al_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_al_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot1_al_prim = stage.GetPrimAtPath(light_pivot1_al_path) UsdGeom.PrimvarsAPI(light_pivot1_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot1_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 800) ) light_pivot1_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot1_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(4.5, 4.5, 4.5) ) light_pivot1_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight RectLight light_pivot1_alrl_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/RectLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_alrl_path, prim_type="RectLight", select_new_prim=False, attributes={}, ) light_pivot1_alrl_prim = stage.GetPrimAtPath(light_pivot1_alrl_path) # set values # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 # https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4 if hasattr(UsdLux.Tokens, 'inputsIntensity'): light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(15000) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) else: light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(15000) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) # create AreaLight Backside backside_albs_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/Backside".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_albs_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_albs_prim = stage.GetPrimAtPath(backside_albs_path) # set values backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1)) backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_albs_path, material_path=backside_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create AreaLight EmissiveSurface backside_ales_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/EmissiveSurface".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_ales_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_ales_prim = stage.GetPrimAtPath(backside_ales_path) # set values backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 0.002) ) backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_ales_path, material_path=emissive_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create LightPivot_02 light_pivot2_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_02".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot2_prim = stage.GetPrimAtPath(light_pivot2_path) UsdGeom.PrimvarsAPI(light_pivot2_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot2_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot2_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(-149.8694695859529, 35.87684189578612, -18.78499937937383) ) light_pivot2_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0.9999999347425043, 0.9999995656418647, 1.0000001493100235) ) light_pivot2_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight light_pivot2_al_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_al_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot2_al_prim = stage.GetPrimAtPath(light_pivot2_al_path) UsdGeom.PrimvarsAPI(light_pivot2_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot2_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 800) ) light_pivot2_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot2_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(1.5, 1.5, 1.5) ) light_pivot2_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight RectLight light_pivot2_alrl_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/RectLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_alrl_path, prim_type="RectLight", select_new_prim=False, attributes={}, ) light_pivot2_alrl_prim = stage.GetPrimAtPath(light_pivot2_alrl_path) # set values # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 # https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4 if hasattr(UsdLux.Tokens, 'inputsIntensity'): light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(55000) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) else: light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(55000) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) # create AreaLight Backside backside_albs_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/Backside".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_albs_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_albs_prim = stage.GetPrimAtPath(backside_albs_path) # set values backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1)) backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_albs_path, material_path=backside_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create AreaLight EmissiveSurface backside_ales_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/EmissiveSurface".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_ales_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_ales_prim = stage.GetPrimAtPath(backside_ales_path) # set values backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 0.002) ) backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_ales_path, material_path=emissive_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, )
20,064
Python
48.178921
126
0.707835
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/__init__.py
from .test_commands import * from .create_prims import *
57
Python
18.333327
28
0.754386
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/test_commands.py
import random import omni.kit.test import omni.kit.commands import omni.kit.undo from pxr import Usd, UsdGeom, Kind class TestCommands(omni.kit.test.AsyncTestCase): def check_visibillity(self, visible_set, invisible_set): context = omni.usd.get_context() stage = context.get_stage() for prim in stage.TraverseAll(): if prim and not prim.GetMetadata("hide_in_stage_window"): if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: if imageable.ComputeVisibility() == UsdGeom.Tokens.invisible: self.assertTrue((prim.GetPath().pathString in invisible_set)) else: self.assertTrue((prim.GetPath().pathString in visible_set)) def get_parent_prims(self, prim): stage = omni.usd.get_context().get_stage() parent_prims = [] while prim.GetParent(): parent_prims.append(prim.GetParent().GetPath().pathString) prim = prim.GetParent() if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: break return parent_prims def get_all_children(self, prim, child_list): for child in prim.GetAllChildren(): child_list.append(child.GetPath().pathString) self.get_all_children(child, child_list) def get_all_prims(self): all_prims = [] stage = omni.usd.get_context().get_stage() for prim in stage.TraverseAll(): if not prim.GetMetadata("hide_in_stage_window"): all_prims.append(prim.GetPath().pathString) return all_prims async def setUp(self): # Disable logging for the time of tests to avoid spewing errors await omni.usd.get_context().new_stage_async() omni.kit.selection.tests.create_test_stage() async def tearDown(self): pass async def test_command_select_all(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_root_prims = [] all_prims = [] material_prims = [] cube_prims = [] sphere_prims = [] children_iterator = iter(stage.TraverseAll()) for prim in children_iterator: all_root_prims.append(prim.GetPath().pathString) children_iterator.PruneChildren() for prim in stage.TraverseAll(): if prim.GetMetadata("hide_in_stage_window"): continue all_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Material": material_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Cube": cube_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Sphere": sphere_prims.append(prim.GetPath().pathString) subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) # SelectAllCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll") self.assertListEqual(selection.get_selected_prim_paths(), all_root_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Material" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Material") self.assertListEqual(selection.get_selected_prim_paths(), material_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Cube" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Cube") self.assertListEqual(selection.get_selected_prim_paths(), cube_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Sphere" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Sphere") self.assertListEqual(selection.get_selected_prim_paths(), sphere_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectSimilarCommand: "Sphere" and "Cube" prim_paths = [sphere_prims[0], cube_prims[0]] selection.set_selected_prim_paths(prim_paths, True) omni.kit.commands.execute("SelectSimilar") all_prims = sphere_prims.copy() all_prims.extend(cube_prims) self.assertListEqual(selection.get_selected_prim_paths(), all_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), prim_paths) async def test_command_select_none(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) inverse_prims = [item for item in all_prims if item not in subset_prims] # SelectNoneCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectNone") self.assertListEqual(selection.get_selected_prim_paths(), []) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_invert(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = [] for prim in stage.TraverseAll(): if not prim.GetMetadata("hide_in_stage_window") and stage.HasDefaultPrim() and not stage.GetDefaultPrim() == prim: all_prims.append(prim.GetPath().pathString) # if selected path as children and none of the children are selected, then all the children are selected.. subset_count = int(len(all_prims) >> 1) subset_prims = [] for prim_path in sorted(random.sample(all_prims, subset_count), reverse=True): prim = stage.GetPrimAtPath(prim_path) if prim: subset_prims.append(prim_path) child_list = [] self.get_all_children(prim, child_list) if not set(subset_prims).intersection(set(child_list)): subset_prims += child_list # SelectInvertCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectInvert") self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_hide_unselected(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() # if selected path as children and none of the children are selected, then all the children are selected.. subset_prims = set() for prim_path in sorted(random.sample(all_prims, 3), reverse=True): # we need to remove "/World" from the sampled result since it is the parent of all prims if prim_path == '/World': continue prim = stage.GetPrimAtPath(prim_path) if prim: subset_prims.add(prim_path) child_list = [] self.get_all_children(prim, child_list) subset_prims.update(child_list) # HideUnselectedCommand Execute and undo visible_prims = set() for prim_path in subset_prims: prim = stage.GetPrimAtPath(prim_path) if prim: visible_prims.add(prim.GetPath().pathString) visible_prims.update(self.get_parent_prims(prim)) invisible_prims = set([item for item in all_prims if item not in visible_prims]) selection.set_selected_prim_paths(list(subset_prims), True) omni.kit.commands.execute("HideUnselected") self.check_visibillity(visible_prims, invisible_prims) omni.kit.undo.undo() self.check_visibillity(all_prims, []) async def test_command_select_parent(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) parent_prims = set() for prim_path in subset_prims: prim = stage.GetPrimAtPath(prim_path) if prim and prim.GetParent() is not None: parent_prims.add(prim.GetParent().GetPath().pathString) parent_prims = list(parent_prims) selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectParent") self.assertListEqual(selection.get_selected_prim_paths(), sorted(parent_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_kind(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = [] group_prims = [] for prim in stage.TraverseAll(): if Kind.Registry.IsA(Usd.ModelAPI(prim).GetKind(), "group"): group_prims.append(prim.GetPath().pathString) if not prim.GetMetadata("hide_in_stage_window"): all_prims.append(prim.GetPath().pathString) subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectKind", kind="group") self.assertListEqual(selection.get_selected_prim_paths(), sorted(group_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_hierarchy(self): context = omni.usd.get_context() selection = context.get_selection() selection.set_selected_prim_paths(['/World'], True) omni.kit.commands.execute("SelectHierarchy") self.assertListEqual(selection.get_selected_prim_paths(), sorted(self.get_all_prims())) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) async def test_command_select_list(self): context = omni.usd.get_context() selection = context.get_selection() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) selection.set_selected_prim_paths(['/World'], True) self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) # with no kwargs it should clear the selection omni.kit.commands.execute("SelectList") self.assertListEqual(selection.get_selected_prim_paths(), []) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) # with kwarg it should swap the selection to the new list omni.kit.commands.execute("SelectList", selection=subset_prims) self.assertListEqual(sorted(selection.get_selected_prim_paths()), sorted(subset_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) async def test_command_select_leaf(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() selection.set_selected_prim_paths(['/World'], True) omni.kit.commands.execute("SelectLeaf") selected = selection.get_selected_prim_paths() for leaf in selected: self.assertFalse(stage.GetPrimAtPath(leaf).GetChildren()) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
12,583
Python
41.948805
126
0.629739
omniverse-code/kit/exts/omni.kit.selection/docs/index.rst
omni.kit.selection ########################### Commands for selection of prims
80
reStructuredText
15.199997
31
0.5375
omniverse-code/kit/exts/omni.mdl.distill_and_bake/docs/index.rst
omni.mdl.distill_and_bake ########################### .. toctree:: :maxdepth: 1 CHANGELOG
98
reStructuredText
11.374999
27
0.469388
omniverse-code/kit/exts/omni.kit.widget.toolbar/PACKAGE-LICENSES/omni.kit.widget.toolbar-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.widget.toolbar/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.4.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI description = "Extension to create toolbar widget. It also comes with builtin tools for transform manipulation and animation playing." title = "Toolbar Widget Extension" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Internal" # Keywords for the extension keywords = ["kit", "toolbar", "widget"] # Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content # of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.actions.core" = {} "omni.kit.commands" = {} "omni.kit.context_menu" = {} "omni.kit.menu.utils" = {} "omni.timeline" = {} "omni.ui" = {} "omni.usd" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.widget.toolbar" [[test]] args = [ "--/app/window/width=480", "--/app/window/height=480", "--/app/renderer/resolution/width=480", "--/app/renderer/resolution/height=480", "--/app/window/scaleToMonitor=false", "--no-window", ] dependencies = [ "omni.kit.uiapp", "omni.kit.renderer.capture", ] stdoutFailPatterns.exclude = [ "*Failed to acquire interface*while unloading all plugins*", ] [settings] exts."omni.kit.widget.toolbar".Grab.enabled = true exts."omni.kit.widget.toolbar".legacySnapButton.enabled = true exts."omni.kit.widget.toolbar".PlayButton.enabled = true exts."omni.kit.widget.toolbar".SelectionButton.enabled = true exts."omni.kit.widget.toolbar".SelectionButton.SelectMode.enabled = true exts."omni.kit.widget.toolbar".TransformButton.enabled = true
1,975
TOML
30.870967
134
0.730127
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/simple_tool_button.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui import weakref from .hotkey import Hotkey from .widget_group import WidgetGroup class SimpleToolButton(WidgetGroup): """ A helper class to create simple WidgetGroup that contains only one ToolButton. Args: name: Name of the ToolButton. tooltip: Tooltip of the ToolButton. icon_path: The icon to be used when button is not checked. icon_checked_path: The icon to be used when button is checked. hotkey: HotKey to toggle the button (optional). toggled_fn: Callback function when button is toggled. Signature: on_toggled(checked) (optional). model: Model for the ToolButton (optional). additional_style: Additional styling to apply to the ToolButton (optional). """ def __init__( self, name, tooltip, icon_path, icon_checked_path, hotkey=None, toggled_fn=None, model=None, additional_style=None, ): super().__init__() self._name = name self._tooltip = tooltip self._icon_path = icon_path self._icon_checked_path = icon_checked_path self._hotkey = hotkey self._toggled_fn = toggled_fn self._model = model self._additional_style = additional_style self._hotkey = None if hotkey: def on_hotkey_changed(hotkey: str): self._tool_button.tooltip = f"{self._tooltip} ({hotkey})" self._select_hotkey = Hotkey( f"{name}::hotkey", hotkey, lambda: self._on_hotkey(), lambda: self._tool_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey), ) def clean(self): super().clean() self._value_sub = None self._tool_button = None if self._select_hotkey: self._select_hotkey.clean() self._select_hotkey = None def get_style(self): style = { f"Button.Image::{self._name}": {"image_url": self._icon_path}, f"Button.Image::{self._name}:checked": {"image_url": self._icon_checked_path}, } if self._additional_style: style.update(self._additional_style) return style def create(self, default_size): def on_value_changed(model, widget): widget = widget() if widget is not None: if model.get_value_as_bool(): self._acquire_toolbar_context() else: self._release_toolbar_context() widget._toggled_fn(model.get_value_as_bool()) self._tool_button = omni.ui.ToolButton( name=self._name, model=self._model, tooltip=self._tooltip, width=default_size, height=default_size ) if self._toggled_fn is not None: self._value_sub = self._tool_button.model.subscribe_value_changed_fn( lambda model, widget=weakref.ref(self): on_value_changed(model, widget) ) # return a dictionary of name -> widget if you want to expose it to other widget_group return {self._name: self._tool_button} def get_tool_button(self): return self._tool_button def _on_hotkey(self): self._tool_button.model.set_value(not self._tool_button.model.get_value_as_bool())
3,858
Python
34.081818
110
0.604458
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/widget_group.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 from abc import abstractmethod import omni.kit.widget.toolbar import omni.kit.app import omni.ui as ui from .context_menu import ContextMenuEvent class WidgetGroup: """ Base class to create a group of widgets on Toolbar """ def __init__(self): self._context = "" self._context_token = None self._show_menu_task = None self._toolbar_ext_path = ( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar") ) @abstractmethod def clean(self): """ Clean up function to be called before destorying the object. """ if self._context_token: self._release_toolbar_context() self._context_token = None self._context = "" if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None @abstractmethod def get_style(self) -> dict: """ Gets the style of all widgets defined in this Widgets group. """ pass # pragma: no cover (Abstract) @abstractmethod def create(self, default_size): """ Main function to creates widget. If you want to export widgets and allow external code to fetch and manipulate them, return a Dict[str, Widget] mapping from name to instance at the end of the function. """ pass # pragma: no cover (Abstract) def on_toolbar_context_changed(self, context: str): """ Called when toolbar's effective context has changed. Args: context: new toolbar context. """ pass def on_added(self, context): """ Called when widget is added to toolbar when calling Toolbar.add_widget Args: context: the context used to add widget when calling Toolbar.add_widget. """ self._context = context def on_removed(self): """ Called when widget is removed from toolbar when calling Toolbar.remove_widget """ pass def _acquire_toolbar_context(self): """ Request toolbar to switch to current widget's context. """ self._context_token = omni.kit.widget.toolbar.get_instance().acquire_toolbar_context(self._context) def _release_toolbar_context(self): """ Release the ownership of toolbar context and reset to default. If the ownership was preemptively taken by other owner, release does nothing. """ omni.kit.widget.toolbar.get_instance().release_toolbar_context(self._context_token) def _is_in_context(self): """ Checks if the Toolbar is in default context or owned by current widget's context. Override this function if you want to customize the behavior. Returns: True if toolbar is either in default context or owned by current widget. False otherwise. """ toolbar_context = omni.kit.widget.toolbar.get_instance().get_context() return toolbar_context == omni.kit.widget.toolbar.Toolbar.DEFAULT_CONTEXT or self._context == toolbar_context def _invoke_context_menu(self, button_id: str, min_menu_entries: int = 1): """ Function to invoke context menu. Args: button_id: button_id of the context menu to be invoked. min_menu_entries: minimal number of menu entries required for menu to be visible (default 1). """ event = ContextMenuEvent() event.payload["widget_name"] = button_id event.payload["min_menu_entries"] = min_menu_entries omni.kit.widget.toolbar.get_instance().context_menu.on_mouse_event(event) def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 2): """ Function to handle flyout menu. Either with LMB long press or RMB click. Args: button_id: button_id of the context menu to be invoked. min_menu_entries: minimal number of menu entries required for menu to be visible (default 1). """ self._acquire_toolbar_context() if button == 1: # Right click, show immediately self._invoke_context_menu(button_id, min_menu_entries) elif button == 0: # Schedule a task if hold LMB long enough self._show_menu_task = asyncio.ensure_future(self._schedule_show_menu(button_id)) def _on_mouse_released(self, button): if button == 0: if self._show_menu_task: self._show_menu_task.cancel() async def _schedule_show_menu(self, button_id: str, min_menu_entries: int = 2): await asyncio.sleep(0.3) self._invoke_context_menu(button_id, min_menu_entries) self._show_menu_task = None def _build_flyout_indicator( self, width, height, index: str, extension_id: str = "omni.kit.widget.toolbar", padding=7, min_menu_count=2 ): import carb import omni.kit.context_menu indicator_size = 3 with ui.Placer(offset_x=width - indicator_size - padding, offset_y=height - indicator_size - padding): indicator = ui.Image( f"{self._toolbar_ext_path}/data/icon/flyout_indicator_dark.svg", width=indicator_size, height=indicator_size, ) def on_menu_changed(evt: carb.events.IEvent): try: menu_list = omni.kit.context_menu.get_menu_dict(index, extension_id) # because we moved separated the widget from the window extension, we need to still grab the menu from # the window extension menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(index, "omni.kit.window.toolbar") if menu_list_backward_compatible and evt.payload.get("extension_id", None) == "omni.kit.window.toolbar": # pragma: no cover omni.kit.app.log_deprecation( 'Adding menu using "add_menu(menu, index, "omni.kit.window.toolbar")" is deprecated. ' 'Please use "add_menu(menu, index, "omni.kit.widget.toolbar")"' ) # TODO check the actual menu entry visibility with show_fn indicator.visible = len(menu_list + menu_list_backward_compatible) >= min_menu_count except AttributeError as exc: # pragma: no cover carb.log_warn(f"on_menu_changed error {exc}") # Check initial state on_menu_changed(None) event_stream = omni.kit.context_menu.get_menu_event_stream() return event_stream.create_subscription_to_pop(on_menu_changed)
7,173
Python
38.202186
176
0.625401
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/commands.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.timeline import omni.kit.commands class ToolbarPlayButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar play button **Command**. """ def do(self): omni.timeline.get_timeline_interface().play() class ToolbarPauseButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar pause button **Command**. """ def do(self): omni.timeline.get_timeline_interface().pause() class ToolbarStopButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar stop button **Command**. """ def do(self): omni.timeline.get_timeline_interface().stop() class ToolbarPlayFilterCheckedCommand(omni.kit.commands.Command): """ Change settings depending on the status of play filter checkboxes **Command**. Args: path: Path to the setting to change. enabled: New value to change to. """ def __init__(self, setting_path, enabled): self._setting_path = setting_path self._enabled = enabled def do(self): omni.kit.commands.execute("ChangeSetting", path=self._setting_path, value=self._enabled) def undo(self): pass # pragma: no cover class ToolbarPlayFilterSelectAllCommand(omni.kit.commands.Command): # pragma: no cover """ Sets all play filter settings to True **Command**. Args: settings: Paths to the settings. """ def __init__(self, settings): self._settings = settings def do(self): for setting in self._settings: omni.kit.commands.execute("ChangeSetting", path=setting, value=True) def undo(self): pass omni.kit.commands.register_all_commands_in_module(__name__)
2,165
Python
26.075
96
0.684988
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.ext from functools import lru_cache from pathlib import Path from .toolbar import Toolbar _toolbar_instance = None @lru_cache() def get_data_path() -> Path: manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path_by_module("omni.kit.widget.toolbar") return Path(extension_path).joinpath("data") def get_instance(): return _toolbar_instance class WidgetToolBarExtension(omni.ext.IExt): """omni.kit.widget.toolbar ext""" def on_startup(self, ext_id): global _toolbar_instance carb.log_info("[omni.kit.widget.toolbar] Startup") _toolbar_instance = Toolbar() def on_shutdown(self): carb.log_info("[omni.kit.widget.toolbar] Shutdown") global _toolbar_instance if _toolbar_instance: _toolbar_instance.destroy() _toolbar_instance = None
1,338
Python
29.431818
84
0.720478
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/__init__.py
from .extension import * from .toolbar import * from omni.kit.widget.toolbar.simple_tool_button import * # backward compatible from .widget_group import * # backward compatible
179
Python
34.999993
79
0.776536
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/context_menu.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.kit.context_menu from omni import ui class ContextMenuEvent: """The object comatible with ContextMenu""" def __init__(self): self.type = 0 self.payload = {} class ContextMenu: def on_mouse_event(self, event): # check its expected event if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): # pragma: no cover return # get context menu core functionality & check its enabled context_menu = omni.kit.context_menu.get_instance() if context_menu is None: # pragma: no cover carb.log_error("context_menu is disabled!") return # setup objects, this is passed to all functions objects = {} objects.update(event.payload) widget_name = objects.get("widget_name", None) menu_list = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.widget.toolbar") # because we moved separated the widget from the window extension, we need to still grab the menu from # the window extension menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.window.toolbar") for menu_list_backward in menu_list_backward_compatible: # pragma: no cover if menu_list_backward not in menu_list: menu_list.append(menu_list_backward) # For some tool buttons, the context menu only shows if additional (>1) menu entries are added. min_menu_entries = event.payload.get("min_menu_entries", 0) # show menu context_menu.show_context_menu("toolbar", objects, menu_list, min_menu_entries, delegate=ui.MenuDelegate())
2,117
Python
38.962263
115
0.683987
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/toolbar.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 carb import carb.settings import omni.kit.app import omni.ui as ui import omni.usd from omni.ui import color as cl from typing import Callable from .builtin_tools.builtin_tools import BuiltinTools from .commands import * from .context_menu import * from .widget_group import WidgetGroup # backward compatible import typing if typing.TYPE_CHECKING: # pragma: no cover import weakref GRAB_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/Grab/enabled" # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class Toolbar: WINDOW_NAME = "Main ToolBar" DEFAULT_CONTEXT = "" DEFAULT_CONTEXT_TOKEN = 0 DEFAULT_SIZE = 38 # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def __init__(self): self._settings = carb.settings.get_settings() self.__root_frame = None self._toolbar_widget_groups = [] self._toolbar_widgets = {} self._toolbar_dirty = False self._axis = ui.ToolBarAxis.X self._rebuild_task = None self._grab_stack = None self._context_menu = ContextMenu() self._context_token_pool = 1 self._context = Toolbar.DEFAULT_CONTEXT self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN self._context_token_owner_count = 0 self.__init_shades() self._builtin_tools = BuiltinTools(self) def __init_shades(self): """Style colors""" cl.toolbar_button_background = cl.shade(0x0) cl.toolbar_button_background_checked = cl.shade(0xFF1F2123) cl.toolbar_button_background_pressed = cl.shade(0xFF4B4B4B) cl.toolbar_button_background_hovered = cl.shade(0xFF383838) @property def context_menu(self): return self._context_menu def destroy(self): if self._rebuild_task is not None: # pragma: no cover self._rebuild_task.cancel() self._toolbar_widgets = {} if self._builtin_tools: self._builtin_tools.destroy() self._builtin_tools = None self._toolbar_widget_groups = [] def add_widget(self, widget_group: "WidgetGroup", priority: int, context: str = ""): self._toolbar_widget_groups.append((priority, widget_group)) widget_group.on_added(context) self._set_toolbar_dirty() def remove_widget(self, widget_group: "WidgetGroup"): for widget in self._toolbar_widget_groups: if widget[1] == widget_group: self._toolbar_widget_groups.remove(widget) widget_group.on_removed() self._set_toolbar_dirty() break def get_widget(self, name: str): return self._toolbar_widgets.get(name, None) def acquire_toolbar_context(self, context: str): """ Request toolbar to switch to given context. It takes the context preemptively even if previous context owner has not release the context. Args: context (str): Context to switch to. Returns: A token to be used to release_toolbar_context """ if self._context == context: self._context_token_owner_count += 1 return self._context_token # preemptively take current context, regardless of previous owner/count self._context = context if context == Toolbar.DEFAULT_CONTEXT: self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN else: self._context_token_pool += 1 self._context_token = self._context_token_pool self._context_token_owner_count = 1 for widget in self._toolbar_widget_groups: widget[1].on_toolbar_context_changed(context) return self._context_token def release_toolbar_context(self, token: int): """ Request toolbar to release context associated with token. If token is expired (already released or context ownership taken by others), this function does nothing. Args: token (int): Context token to release. """ if token == self._context_token: self._context_token_owner_count -= 1 else: carb.log_info("Releasing expired context token, ignoring") return if self._context_token_owner_count <= 0: self._context = Toolbar.DEFAULT_CONTEXT self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN self._context_token_owner_count = 0 for widget in self._toolbar_widget_groups: widget[1].on_toolbar_context_changed(self._context) def get_context(self): return self._context def _set_toolbar_dirty(self): self._toolbar_dirty = True if self._rebuild_task is None: self._rebuild_task = asyncio.ensure_future(self._delayed_rebuild()) def set_axis(self, axis): self._axis = axis # delay rebuild so widgets added within one frame are rebuilt together @omni.usd.handle_exception async def _delayed_rebuild(self): await omni.kit.app.get_app().next_update_async() if self._toolbar_dirty: self.rebuild_toolbar() self._toolbar_dirty = False self._rebuild_task = None def rebuild_toolbar(self, root_frame=None): if root_frame: self.__root_frame = root_frame if not self.__root_frame: carb.log_warn("No root frame specified. Please specify a root frame for this widget") return axis = self._axis self._toolbar_widgets = {} self._toolbar_widget_groups.sort(key=lambda x: x[0]) # sort by priority with self.__root_frame: stack = None style = { "Button": {"background_color": cl.toolbar_button_background, "border_radius": 4, "margin": 2, "padding": 3}, "Button:checked": {"background_color": cl.toolbar_button_background_checked}, "Button:pressed": {"background_color": cl.toolbar_button_background_pressed}, "Button:hovered": {"background_color": cl.toolbar_button_background_hovered}, "Button.Image::disabled": {"color": 0x608A8777}, "Line::grab": {"color": 0xFF2E2E2E, "border_width": 2, "margin": 2}, "Line::separator": {"color": 0xFF555555}, "Tooltip": { "background_color": 0xFFC7F5FC, "color": 0xFF4B493B, "border_width": 1, "margin_width": 2, "margin_height": 1, "padding": 1, }, } for widget in self._toolbar_widget_groups: style.update(widget[1].get_style()) default_size = self.DEFAULT_SIZE if axis == ui.ToolBarAxis.X: stack = ui.HStack(style=style, height=default_size, width=ui.Percent(100)) else: stack = ui.VStack(style=style, height=ui.Percent(100), width=default_size) with stack: if self._settings.get(GRAB_ENABLED_SETTING_PATH): self._create_grab(axis) ui.Spacer(width=3, height=3) last_priority = None for widget in self._toolbar_widget_groups: this_priority = widget[0] if last_priority is not None and this_priority - last_priority >= 10: self._create_separator(axis) public_widgets = widget[1].create(default_size=default_size) if public_widgets is not None: self._toolbar_widgets.update(public_widgets) last_priority = this_priority def _create_separator(self, axis): if axis == ui.ToolBarAxis.X: ui.Line(width=1, name="separator", alignment=ui.Alignment.LEFT) else: ui.Line(height=1, name="separator", alignment=ui.Alignment.TOP) def subscribe_grab_mouse_pressed(self, function: Callable[[int, "weakref.ref"], None]): if self._grab_stack: self._grab_stack.set_mouse_pressed_fn(function) def _create_grab(self, axis): grab_area_size = 20 if axis == ui.ToolBarAxis.X: self._grab_stack = ui.HStack(width=grab_area_size) else: self._grab_stack = ui.VStack(height=grab_area_size) with self._grab_stack: if axis == ui.ToolBarAxis.X: ui.Spacer(width=5) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Spacer(width=3) else: ui.Spacer(height=5) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Spacer(height=3) def add_custom_select_type(self, entry_name: str, selection_types: list): self._builtin_tools.add_custom_select_type(entry_name, selection_types) def remove_custom_select(self, entry_name): self._builtin_tools.remove_custom_select(entry_name)
10,132
Python
37.973077
124
0.606001
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/hotkey.py
# Copyright (c) 2020-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 Callable import carb.events import carb.input import omni.appwindow import omni.kit.actions.core import omni.kit.app class Hotkey: def __init__( self, action_name: str, hotkey: carb.input.KeyboardInput, on_action_fn: Callable[[], None], hotkey_enabled_fn: Callable[[], None], modifiers: int = 0, on_hotkey_changed_fn: Callable[[str], None] = None, ): self._action_registry = omni.kit.actions.core.get_action_registry() self._settings = carb.settings.get_settings() self._action_name = action_name self._hotkey = hotkey self._modifiers = modifiers self._on_hotkey_changed_fn = on_hotkey_changed_fn self._registered_hotkey = None self._manager = omni.kit.app.get_app().get_extension_manager() self._extension_name = omni.ext.get_extension_name(self._manager.get_extension_id_by_module(__name__)) def action_trigger(): if not hotkey_enabled_fn(): return if on_action_fn: on_action_fn() # Register a test action that invokes a Python function. self._action = self._action_registry.register_action( self._extension_name, action_name, lambda *_: action_trigger(), display_name=action_name, tag="Toolbar", ) self._hooks = self._manager.subscribe_to_extension_enable( lambda _: self._register_hotkey(), lambda _: self._unregister_hotkey(), ext_name="omni.kit.hotkeys.core", hook_name=f"toolbar hotkey {action_name} listener", ) def clean(self): self._unregister_hotkey() self._action_registry.deregister_action(self._action) self._hooks = None self._on_hotkey_changed_fn = None def get_as_string(self, default:str): if self._registered_hotkey: return self._registered_hotkey.key_text return default def _on_hotkey_changed(self, event: carb.events.IEvent): from omni.kit.hotkeys.core import KeyCombination if ( event.payload["hotkey_ext_id"] == self._extension_name and event.payload["action_ext_id"] == self._extension_name and event.payload["action_id"] == self._action_name ): new_key = event.payload["key"] # refresh _registered_hotkey with newly registered key? hotkey_combo = KeyCombination(new_key) self._registered_hotkey = self._hotkey_registry.get_hotkey(self._extension_name, hotkey_combo) if self._on_hotkey_changed_fn: self._on_hotkey_changed_fn(new_key) def _register_hotkey(self): try: from omni.kit.hotkeys.core import HOTKEY_CHANGED_EVENT, KeyCombination, get_hotkey_registry self._hotkey_registry = get_hotkey_registry() hotkey_combo = KeyCombination(self._hotkey, self._modifiers) self._registered_hotkey = self._hotkey_registry.register_hotkey( self._extension_name, hotkey_combo, self._extension_name, self._action_name ) event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._change_event_sub = event_stream.create_subscription_to_pop_by_type( HOTKEY_CHANGED_EVENT, self._on_hotkey_changed ) except ImportError: # pragma: no cover pass def _unregister_hotkey(self): if not self._registered_hotkey or not self._hotkey_registry: return try: self._hotkey_registry.deregister_hotkey(self._registered_hotkey) self._registered_hotkey = None self._change_event_sub = None except Exception: # pragma: no cover pass
4,357
Python
34.430894
110
0.620151
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/play_button_group.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.dictionary import carb.settings import omni.timeline import omni.ui as ui from carb.input import KeyboardInput as Key from omni.kit.commands import execute from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.timeline_model import TimelinePlayPauseModel PLAY_TOOL_NAME = "Play" PAUSE_TOOL_NAME = "Pause" class PlayButtonGroup(WidgetGroup): PLAY_ANIMATIONS_SETTING = "/app/player/playAnimations" PLAY_AUDIO_SETTING = "/app/player/audio/enabled" PLAY_SIMULATIONS_SETTING = "/app/player/playSimulations" PLAY_COMPUTEGRAPH_SETTING = "/app/player/playComputegraph" all_settings_paths = [ PLAY_ANIMATIONS_SETTING, PLAY_AUDIO_SETTING, PLAY_SIMULATIONS_SETTING, PLAY_COMPUTEGRAPH_SETTING, ] def __init__(self): super().__init__() self._play_button = None self._play_hotkey = None self._stop_button = None self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._timeline_play_pause_model = TimelinePlayPauseModel() self._timeline = omni.timeline.get_timeline_interface() self._settings.set_default_bool(self.PLAY_ANIMATIONS_SETTING, True) self._settings.set_default_bool(self.PLAY_AUDIO_SETTING, True) self._settings.set_default_bool(self.PLAY_SIMULATIONS_SETTING, True) self._settings.set_default_bool(self.PLAY_COMPUTEGRAPH_SETTING, True) stream = self._timeline.get_timeline_event_stream() self._sub = stream.create_subscription_to_pop(self._on_timeline_event) self._register_context_menu() self._show_menu_task = None self._visible = True def clean(self): super().clean() self._sub = None if self._timeline_play_pause_model: self._timeline_play_pause_model.clean() self._timeline_play_pause_model = None self._play_button = None self._stop_button = None self._animations_menu = None self._audio_menu = None self._simulations_menu = None self._compute_graph_menu = None self._play_filter_menu = None self._filter_menu = None self._sep_menu = None self._sep_menu2 = None self._select_all_menu = None if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None if self._play_hotkey: self._play_hotkey.clean() self._play_hotkey = None self._visible = True def get_style(self): style = { "Button.Image::play": {"image_url": "${glyphs}/toolbar_play.svg"}, "Button.Image::play:checked": {"image_url": "${glyphs}/toolbar_pause.svg"}, "Button.Image::stop": {"image_url": "${glyphs}/toolbar_stop.svg"}, } return style def create(self, default_size): # Build Play button self._play_button = ui.ToolButton( model=self._timeline_play_pause_model, name="play", tooltip=f"{PLAY_TOOL_NAME} ('Space')", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "play"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=self._timeline_play_pause_model.get_value_as_bool(), ) def on_play_hotkey_changed(hotkey: str): if self._play_button: self._play_button.tooltip = f"{PLAY_TOOL_NAME} ({hotkey})" # Assign Play button Hotkey self._play_hotkey = Hotkey( "toolbar::play", Key.SPACE, lambda: self._timeline_play_pause_model.set_value(not self._timeline_play_pause_model.get_value_as_bool()), lambda: self._play_button is not None and self._play_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_play_hotkey_changed(hotkey), ) self._visible = True def on_stop_clicked(*_): self._acquire_toolbar_context() execute("ToolbarStopButtonClicked") self._stop_button = ui.Button( name="stop", tooltip="Stop", width=default_size, height=default_size, visible=False, clicked_fn=on_stop_clicked, ) return {"play": self._play_button, "stop": self._stop_button} def _on_setting_changed(self, item, event_type, menu_item): # pragma: no cover menu_item.checked = self._dict.get(item) def _on_timeline_event(self, e): if e.type == int(omni.timeline.TimelineEventType.PLAY): if self._play_button: self._play_button.set_tooltip(f"{PAUSE_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if self._stop_button: self._stop_button.visible = self._visible if e.type == int(omni.timeline.TimelineEventType.PAUSE): if self._play_button: self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if e.type == int(omni.timeline.TimelineEventType.STOP): if self._stop_button: self._stop_button.visible = False if self._play_button: self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if hasattr(omni.timeline.TimelineEventType, 'DIRECTOR_CHANGED') and\ e.type == int(omni.timeline.TimelineEventType.DIRECTOR_CHANGED): # pragma: no cover self._visible = not e.payload['hasDirector'] if self._stop_button: self._stop_button.visible = self._visible if self._play_button: self._play_button.visible = self._visible def _on_filter_changed(self, filter_setting, enabled): # pragma: no cover execute("ToolbarPlayFilterChecked", setting_path=filter_setting, enabled=enabled) def _select_all(self): # pragma: no cover execute("ToolbarPlayFilterSelectAll", settings=self.all_settings_paths) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name def create_menu_entry(name, setting_path): menu = { "name": name, "show_fn": [lambda object: is_button(object, "play")], "onclick_fn": lambda object: self._on_filter_changed( setting_path, not self._settings.get(setting_path) ), "checked_fn": lambda object: self._settings.get(setting_path), } return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") def create_seperator(name=""): menu = { "name": name, "show_fn": [lambda object: is_button(object, "play")], } return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") if context_menu: menu = { "name": "Filter", "show_fn": [lambda object: is_button(object, "play")], "enabled_fn": lambda object: False, } self._filter_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") self._sep_menu = create_seperator("sep/") self._animations_menu = create_menu_entry("Animation", self.PLAY_ANIMATIONS_SETTING) self._audio_menu = create_menu_entry("Audio", self.PLAY_AUDIO_SETTING) self._simulations_menu = create_menu_entry("Simulations", self.PLAY_SIMULATIONS_SETTING) self._compute_graph_menu = create_menu_entry("OmniGraph", self.PLAY_COMPUTEGRAPH_SETTING) self._sep_menu2 = create_seperator("sep2/") menu = { "name": "Select All", "show_fn": [lambda object: is_button(object, "play")], "onclick_fn": lambda object: self._select_all(), } self._select_all_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
8,842
Python
40.32243
119
0.604275
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/builtin_tools.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.dictionary import carb.settings from .select_button_group import SelectButtonGroup from .snap_button_group import LegacySnapButtonGroup from .transform_button_group import TransformButtonGroup from .play_button_group import PlayButtonGroup import typing if typing.TYPE_CHECKING: # pragma: no cover from ..toolbar import Toolbar SELECT_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/enabled" TRANSFORM_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/TransformButton/enabled" PLAY_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/PlayButton/enabled" LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW = "/exts/omni.kit.window.toolbar/legacySnapButton/enabled" LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET = "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled" class BuiltinTools: def __init__(self, toolbar: "Toolbar"): self._dict = carb.dictionary.get_dictionary() self._settings = carb.settings.get_settings() self._sub_window = self._settings.subscribe_to_node_change_events( LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, self._on_legacy_snap_setting_changed_window ) self._toolbar = toolbar self._select_button_group = None if self._settings.get(SELECT_BUTTON_ENABLED_SETTING_PATH): self._select_button_group = SelectButtonGroup() toolbar.add_widget(self._select_button_group, 0) self._transform_button_group = None if self._settings.get(TRANSFORM_BUTTON_ENABLED_SETTING_PATH): self._transform_button_group = TransformButtonGroup() toolbar.add_widget(self._transform_button_group, 1) self._snap_button_group = None if self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET): self._add_snap_button() self._play_button_group = None if self._settings.get(PLAY_BUTTON_ENABLED_SETTING_PATH): self._play_button_group = PlayButtonGroup() toolbar.add_widget(self._play_button_group, 21) self._sub_widget = self._settings.subscribe_to_node_change_events( LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, self._on_legacy_snap_setting_changed ) def destroy(self): if self._select_button_group: self._toolbar.remove_widget(self._select_button_group) self._select_button_group.clean() self._select_button_group = None if self._transform_button_group: self._toolbar.remove_widget(self._transform_button_group) self._transform_button_group.clean() self._transform_button_group = None if self._snap_button_group: self._remove_snap_button() if self._play_button_group: self._toolbar.remove_widget(self._play_button_group) self._play_button_group.clean() self._play_button_group = None if self._sub_window: self._settings.unsubscribe_to_change_events(self._sub_window) self._sub_window = None if self._sub_widget: self._settings.unsubscribe_to_change_events(self._sub_widget) self._sub_widget = None def __del__(self): self.destroy() def _add_snap_button(self): self._snap_button_group = LegacySnapButtonGroup() self._toolbar.add_widget(self._snap_button_group, 11) def _remove_snap_button(self): self._toolbar.remove_widget(self._snap_button_group) self._snap_button_group.clean() self._snap_button_group = None def _on_legacy_snap_setting_changed_window(self, *args, **kwargs): """ If the old setting is set, we forward it into the new settings. """ enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW) if enabled_legacy_snap is not None: carb.log_warn( 'Deprecated, please use "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled" setting' ) self._settings.set(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, enabled_legacy_snap) def _on_legacy_snap_setting_changed(self, *args, **kwargs): enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET) if self._snap_button_group is None and enabled_legacy_snap: self._add_snap_button() elif self._snap_button_group is not None and not enabled_legacy_snap: self._remove_snap_button() def add_custom_select_type(self, entry_name: str, selection_types: list): self._select_button_group.add_custom_select_type(entry_name, selection_types) def remove_custom_select(self, entry_name): self._select_button_group.remove_custom_select(entry_name)
5,263
Python
41.796748
105
0.67984
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/transform_button_group.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.input import carb.dictionary import carb.settings import omni.kit.context_menu import omni.ui as ui from carb.input import KeyboardInput as Key from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.transform_mode_model import LocalGlobalTransformModeModel, TransformModeModel MOVE_TOOL_NAME = "Move" ROTATE_TOOL_NAME = "Rotate" SCALE_TOOL_NAME = "Scale" class TransformButtonGroup(WidgetGroup): TRANSFORM_MOVE_MODE_SETTING = "/app/transform/moveMode" TRANSFORM_ROTATE_MODE_SETTING = "/app/transform/rotateMode" def __init__(self): super().__init__() self._input = carb.input.acquire_input_interface() self._settings = carb.settings.get_settings() self._settings.set_default_string(TransformModeModel.TRANSFORM_OP_SETTING, TransformModeModel.TRANSFORM_OP_MOVE) self._settings.set_default_string( self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ) self._settings.set_default_string( self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ) self._move_op_model = LocalGlobalTransformModeModel( op=TransformModeModel.TRANSFORM_OP_MOVE, op_space_setting_path=self.TRANSFORM_MOVE_MODE_SETTING ) self._rotate_op_model = LocalGlobalTransformModeModel( op=TransformModeModel.TRANSFORM_OP_ROTATE, op_space_setting_path=self.TRANSFORM_ROTATE_MODE_SETTING ) self._scale_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SCALE) def on_hotkey_changed(hotkey: str, button, tool_name: str): button.tooltip = f"{tool_name} ({hotkey})" self._move_hotkey = Hotkey( "toolbar::move", Key.W, lambda: self._move_op_model.set_value(not self._move_op_model.get_value_as_bool()), lambda: self._move_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, # when RMB is down, it's possible viewport WASD navigation is going on, and don't trigger it if W is pressed on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._move_button, MOVE_TOOL_NAME), ) self._rotate_hotkey = Hotkey( "toolbar::rotate", Key.E, lambda: self._rotate_op_model.set_value(not self._rotate_op_model.get_value_as_bool()), lambda: self._rotate_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._rotate_button, ROTATE_TOOL_NAME), ) self._scale_hotkey = Hotkey( "toolbar::scale", Key.R, lambda: self._scale_op_model.set_value(True), lambda: self._scale_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._scale_button, SCALE_TOOL_NAME), ) self._register_context_menu() def get_style(self): style = { "Button.Image::move_op_global": {"image_url": "${glyphs}/toolbar_move_global.svg"}, "Button.Image::move_op_local": {"image_url": "${glyphs}/toolbar_move_local.svg"}, "Button.Image::rotate_op_global": {"image_url": "${glyphs}/toolbar_rotate_global.svg"}, "Button.Image::rotate_op_local": {"image_url": "${glyphs}/toolbar_rotate_local.svg"}, "Button.Image::scale_op": {"image_url": "${glyphs}/toolbar_scale.svg"}, } return style def create(self, default_size): self._sub_move, self._move_button = self._create_local_global_button( self._move_op_model, f"{MOVE_TOOL_NAME} ({self._move_hotkey.get_as_string('W')})", "move_op", self.TRANSFORM_MOVE_MODE_SETTING, "move_op_global", "move_op_local", default_size, ) self._sub_rotate, self._rotate_button = self._create_local_global_button( self._rotate_op_model, f"{ROTATE_TOOL_NAME} ({self._rotate_hotkey.get_as_string('E')})", "rotate_op", self.TRANSFORM_ROTATE_MODE_SETTING, "rotate_op_global", "rotate_op_local", default_size, ) self._scale_button = ui.ToolButton( model=self._scale_op_model, name="scale_op", tooltip=f"{SCALE_TOOL_NAME} ({self._scale_hotkey.get_as_string('R')})", width=default_size, height=default_size, mouse_pressed_fn=lambda *_: self._acquire_toolbar_context(), ) return {"move_op": self._move_button, "rotate_op": self._rotate_button, "scale_op": self._scale_button} def clean(self): super().clean() self._move_button = None self._rotate_button = None self._scale_button = None self._sub_move = None self._sub_rotate = None self._move_op_model.clean() self._move_op_model = None self._rotate_op_model.clean() self._rotate_op_model = None self._scale_op_model.clean() self._scale_op_model = None self._move_hotkey.clean() self._move_hotkey = None self._rotate_hotkey.clean() self._rotate_hotkey = None self._scale_hotkey.clean() self._scale_hotkey = None self._move_global_menu_entry = None self._move_local_menu_entry = None self._rotate_global_menu_entry = None self._rotate_local_menu_entry = None def _get_op_button_name(self, model, global_name, local_name): if model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL: return global_name else: # pragma: no cover return local_name def _create_local_global_button( self, op_model, tooltip, button_name, op_setting_path, global_name, local_name, default_size ): op_button = ui.ToolButton( name=self._get_op_button_name(op_model, global_name, local_name), model=op_model, tooltip=tooltip, width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, button_name), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=op_model.get_value_as_bool(), ) def on_op_button_value_change(model): op_button.name = self._get_op_button_name(model, global_name, local_name) return op_model.subscribe_value_changed_fn(on_op_button_value_change), op_button def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name def on_mode(objects: dict, op_setting_path: str, desired_value): # pragma: no cover self._settings.set(op_setting_path, desired_value) def checked(objects: dict, op_setting_path: str, desired_value: str): # pragma: no cover return self._settings.get(op_setting_path) == desired_value if context_menu: menu = { "name": "Global (W)", "show_fn": [lambda object: is_button(object, "move_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), } self._move_global_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar") menu = { "name": "Local (W)", "show_fn": [lambda object: is_button(object, "move_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), } self._move_local_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar") menu = { "name": "Global (E)", "show_fn": [lambda object: is_button(object, "rotate_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), } self._rotate_global_menu_entry = omni.kit.context_menu.add_menu( menu, "rotate_op", "omni.kit.widget.toolbar" ) menu = { "name": "Local (E)", "show_fn": [lambda object: is_button(object, "rotate_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), } self._rotate_local_menu_entry = omni.kit.context_menu.add_menu(menu, "rotate_op", "omni.kit.widget.toolbar")
10,527
Python
43.8
127
0.605016
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/snap_button_group.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.dictionary import carb.settings import omni.kit.context_menu import omni.ui as ui from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.setting_model import BoolSettingModel, FloatSettingModel class LegacySnapButtonGroup(WidgetGroup): SNAP_ENABLED_SETTING = "/app/viewport/snapEnabled" SNAP_MOVE_X_SETTING = "/persistent/app/viewport/stepMove/x" SNAP_MOVE_Y_SETTING = "/persistent/app/viewport/stepMove/y" SNAP_MOVE_Z_SETTING = "/persistent/app/viewport/stepMove/z" SNAP_ROTATE_SETTING = "/persistent/app/viewport/stepRotate" SNAP_SCALE_SETTING = "/persistent/app/viewport/stepScale" SNAP_TO_SURFACE_SETTING = "/persistent/app/viewport/snapToSurface" def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_bool(self.SNAP_ENABLED_SETTING, False) self._settings.set_default_float(self.SNAP_MOVE_X_SETTING, 50.0) self._settings.set_default_float(self.SNAP_MOVE_Y_SETTING, 50.0) self._settings.set_default_float(self.SNAP_MOVE_Z_SETTING, 50.0) self._settings.set_default_float(self.SNAP_ROTATE_SETTING, 1.0) self._settings.set_default_float(self.SNAP_SCALE_SETTING, 1.0) self._dict = carb.dictionary.get_dictionary() self._snap_setting_model = BoolSettingModel(self.SNAP_ENABLED_SETTING, False) self._snap_move_x_settings_model = FloatSettingModel(self.SNAP_MOVE_X_SETTING) self._snap_move_y_settings_model = FloatSettingModel(self.SNAP_MOVE_Y_SETTING) self._snap_move_z_settings_model = FloatSettingModel(self.SNAP_MOVE_Z_SETTING) self._snap_rotate_settings_model = FloatSettingModel(self.SNAP_ROTATE_SETTING) self._snap_scale_settings_model = FloatSettingModel(self.SNAP_SCALE_SETTING) self._create_snap_increment_setting_window() self._register_context_menu() self._show_menu_task = None self._button = None def clean(self): super().clean() self._snap_setting_model.clean() self._snap_setting_model = None # workaround delayed toolbar rebuild after group is destroyed and access null model if self._button: self._button.model = ui.SimpleBoolModel() self._button = None self._snap_move_x_settings_model.clean() self._snap_move_x_settings_model = None self._snap_move_y_settings_model.clean() self._snap_move_y_settings_model = None self._snap_move_z_settings_model.clean() self._snap_move_z_settings_model = None self._snap_rotate_settings_model.clean() self._snap_rotate_settings_model = None self._snap_scale_settings_model.clean() self._snap_scale_settings_model = None self._snap_increment_setting_window = None self._snap_setting_menu = None self._snap_settings = None self._snap_to_increment_menu = None self._snap_to_face_menu = None if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None self._snap_settings_menu_entry = None self._snap_to_increment_menu_entry = None self._snap_to_face_menu_entry = None def get_style(self): style = {"Button.Image::snap": {"image_url": "${glyphs}/toolbar_snap.svg"}} return style def create(self, default_size): self._button = ui.ToolButton( model=self._snap_setting_model, name="snap", tooltip="Snap", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "snap"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=self._snap_setting_model.get_value_as_bool(), ) return {"snap": self._button} def _on_snap_on_off(self, model): # pragma: no cover (Never called anywhere it seems) self._snap_settings.enabled = self._snap_setting_model.get_value_as_bool() def _on_snap_setting_change(self, item, event_type): # pragma: no cover (Never called anywhere it seems) snap_to_face = self._dict.get(item) self._snap_to_increment_menu.checked = not snap_to_face self._snap_to_face_menu.checked = snap_to_face self._snap_settings.enabled = not snap_to_face def _on_snap_setting_menu_clicked(self, snap_to_face): # pragma: no cover self._settings.set(self.SNAP_TO_SURFACE_SETTING, snap_to_face) def _on_show_snap_increment_setting_window(self): # pragma: no cover self._snap_increment_setting_window.visible = True def _create_snap_increment_setting_window(self): self._snap_increment_setting_window = ui.Window( "Snap Increment Settings Menu", width=400, height=0, flags=ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR, visible=False, ) with self._snap_increment_setting_window.frame: with ui.VStack(spacing=8, height=0, name="frame_v_stack"): ui.Label("Snap Settings - Increments", enabled=False) ui.Separator() with ui.HStack(): with ui.HStack(width=120): ui.Label("Position", width=50) ui.Spacer() all_axis = ["X", "Y", "Z"] all_axis_model = { "X": self._snap_move_x_settings_model, "Y": self._snap_move_y_settings_model, "Z": self._snap_move_z_settings_model, } colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F} for axis in all_axis: with ui.HStack(): with ui.ZStack(width=15): ui.Rectangle( width=15, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, alignment=ui.Alignment.CENTER) ui.FloatDrag(model=all_axis_model[axis], min=0, max=1000000, step=0.01) ui.Circle(width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED) with ui.HStack(): with ui.HStack(width=120): ui.Label("Rotation", width=50) ui.Spacer() ui.FloatDrag(model=self._snap_rotate_settings_model, min=0, max=1000000, step=0.01) with ui.HStack(): with ui.HStack(width=120): ui.Label("Scale", width=50) ui.Spacer() ui.FloatDrag(model=self._snap_scale_settings_model, min=0, max=1000000, step=0.01) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name if context_menu: menu = { "name": f"Snap Settings {ui.get_custom_glyph_code('${glyphs}/cog.svg')}", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_show_snap_increment_setting_window(), "enabled_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_settings_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar") menu = { "name": "Snap to Increment", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=False), "checked_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_to_increment_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar") menu = { "name": "Snap to Face", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=True), "checked_fn": lambda object: self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_to_face_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
9,363
Python
47.518134
120
0.583574
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/select_button_group.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.input import omni.kit.context_menu import omni.ui as ui import pathlib from pxr import Kind from carb.input import KeyboardInput as Key from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.select_mode_model import SelectModeModel from .models.select_no_kinds_model import SelectNoKindsModel from .models.select_include_ref_model import SelectIncludeRefModel from .models.transform_mode_model import TransformModeModel SELECT_PRIM_MODE_TOOL_NAME = "Prim" SELECT_MODEL_MODE_TOOL_NAME = "Model" SELECT_TOOL_NAME = "Select" LIGHT_TYPES = "type:CylinderLight;type:DiskLight;type:DistantLight;type:DomeLight;type:GeometryLight;type:Light;type:RectLight;type:SphereLight" EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar") ) SELECT_MODE_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/SelectMode/enabled" class SelectButtonGroup(WidgetGroup): def __init__(self): super().__init__() self._input = carb.input.acquire_input_interface() self._select_mode_model = SelectModeModel() self._select_no_kinds_model = SelectNoKindsModel() self._select_include_ref_model = SelectIncludeRefModel() self._select_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SELECT) self._select_op_menu_entry = None self._custom_types = [] self._settings = carb.settings.get_settings() self._icon_path = str(EXTENSION_FOLDER_PATH / "data" / "icon") self._settings = carb.settings.get_settings() self._select_mode_button = None self._mode_hotkey = None if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): def hotkey_change(): current_mode = self._select_mode_model.get_value_as_string() if current_mode == "models" or current_mode == "kind:model.ALL": self._select_mode_model.set_value("type:ALL") else: self._select_mode_model.set_value("kind:model.ALL") self._update_selection_mode_button() def on_select_mode_hotkey_changed(hotkey: str): self._select_mode_button.tooltip = self._get_select_mode_tooltip() self._mode_hotkey = Hotkey( "toolbar::select_mode", Key.T, hotkey_change, lambda: self._select_mode_button.enabled and self._is_in_context(), on_hotkey_changed_fn=on_select_mode_hotkey_changed, ) # only replace the tooltip part so that "Paint Select" registered from select brush can still have correct label def on_select_hotkey_changed(hotkey: str): self._select_op_button.tooltip = ( self._select_op_button.tooltip.rsplit("(", 1)[0] + f"({self._select_hotkey.get_as_string('Q')})" ) self._select_hotkey = Hotkey( "toolbar::select", Key.Q, lambda: self._select_op_button.model.set_value(True), lambda: self._select_op_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, on_hotkey_changed_fn=lambda hotkey: on_select_hotkey_changed(hotkey), ) self._sub_menu = [] self._register_context_menu() def get_style(self): style = { "Button.Image::select_mode": {"image_url": "${glyphs}/toolbar_select_prim.svg"}, "Button.Image::select_op_models": {"image_url": "${glyphs}/toolbar_select_models.svg"}, "Button.Image::select_op_prims": {"image_url": "${glyphs}/toolbar_select_prims.svg"}, "Button.Image::all_prim_types": {"image_url": f"{self._icon_path}/all_prim_types.svg"}, "Button.Image::meshes": {"image_url": f"{self._icon_path}/meshes.svg"}, "Button.Image::lights": {"image_url": f"{self._icon_path}/lights.svg"}, "Button.Image::cameras": {"image_url": f"{self._icon_path}/cameras.svg"}, "Button.Image::model_kinds": {"image_url": f"{self._icon_path}/model_kinds.svg"}, "Button.Image::assembly": {"image_url": f"{self._icon_path}/assembly.svg"}, "Button.Image::group": {"image_url": f"{self._icon_path}/group.svg"}, "Button.Image::component": {"image_url": f"{self._icon_path}/component.svg"}, "Button.Image::sub_component": {"image_url": f"{self._icon_path}/sub_component.svg"}, "Button.Image::payload_reference": {"image_url": f"{self._icon_path}/payload_reference.svg"}, "Button.Image::custom_kind": {"image_url": f"{self._icon_path}/custom_kind.svg"}, "Button.Image::custom_type": {"image_url": f"{self._icon_path}/custom_type.svg"}, } return style def create(self, default_size): def select_enabled(): # pragma: no cover (Unused, it's commened out below - I am just adding coverage! '^^) return True def on_select_mode_change(model): self._update_selection_mode_button() result = {} if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): self._select_mode_button = ui.ToolButton( model=self._select_mode_model, name="select_mode", tooltip=self._get_select_mode_tooltip(), width=default_size, height=default_size, # checked=select_enabled, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_mode"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), ) self._model_changed_sub = self._select_mode_model.subscribe_value_changed_fn(on_select_mode_change) result["select_mode"] = self._select_mode_button with ui.ZStack(width=0, height=0): self._select_op_button = ui.ToolButton( model=self._select_op_model, name=self._get_select_op_button_name(self._select_mode_model), tooltip=self._get_select_tooltip(), width=default_size, height=default_size, checked=self._select_op_model.get_value_as_bool(), mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_op"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), ) # Follow the pattern here (ZStack + _build_flyout_indicator) for other buttons if they want dynamic flyout indicator self._select_op_menu_sub = self._build_flyout_indicator(default_size, default_size, "select_op") result["select_op"] = self._select_op_button self._update_selection_mode_button() return result def clean(self): super().clean() self._select_mode_button = None self._select_op_button = None self._select_mode_model.clean() self._select_mode_model = None self._select_no_kinds_model.clean() self._select_no_kinds_model = None self._select_include_ref_model.clean() self._select_include_ref_model = None self._select_op_model.clean() self._select_op_model = None self._model_changed_sub = None if self._mode_hotkey: self._mode_hotkey.clean() self._mode_hotkey = None self._select_hotkey.clean() self._select_hotkey = None self._select_mode_menu_entry.release() self._select_mode_menu_entry = None if self._select_op_menu_entry: self._select_op_menu_entry.release() self._select_op_menu_entry = None self._select_op_menu_sub = None for menu in self._sub_menu: menu.release() self._sub_menu = [] def _get_select_op_button_name(self, model): return "select_op_prims" if model.get_value_as_bool() else "select_op_models" def _get_select_tooltip(self): return f"{SELECT_TOOL_NAME} ({self._select_hotkey.get_as_string('Q')})" def _get_select_mode_button_name(self): mode_name = { "type:ALL": "all_prim_types", "type:Mesh": "meshes", LIGHT_TYPES: "lights", "type:Camera": "cameras", "kind:model.ALL": "model_kinds", "kind:assembly": "assembly", "kind:group": "group", "kind:component": "component", "kind:subcomponent": "sub_component", "ref:reference;ref:payload": "custom_type", } mode = self._select_mode_model.get_value_as_string() if mode in mode_name: return mode_name[mode] else: # pragma: no cover if mode[:4] == "kind": return "custom_kind" else: return "custom_type" def _get_select_mode_tooltip(self): mode_data = { "type:ALL": "All Prim Types", "type:Mesh": "Meshes", LIGHT_TYPES: "Lights", "type:Camera": "Camera", "kind:model.ALL": "All Model Kinds", "kind:assembly": "Assembly", "kind:group": "Group", "kind:component": "Component", "kind:subcomponent": "Subcomponent", "ref:reference;ref:payload": "Subcomponent", } mode = self._select_mode_model.get_value_as_string() if mode in mode_data: tooltip = mode_data[mode] else: # pragma: no cover if mode[:4] == "kind": tooltip = "Custom Kind" else: tooltip = "Custom type" return tooltip + f" ({self._mode_hotkey.get_as_string('T')})" def _usd_kinds(self): return ["model", "assembly", "group", "component", "subcomponent"] def _enable_no_kinds_option(self, b): # pragma: no cover mode = self._select_mode_model.get_value_as_string() return mode[:4] == "kind" def _usd_kinds_display(self): # pragma: no cover return self._usd_kinds()[1:] def _plugin_kinds(self): all_kinds = set(Kind.Registry.GetAllKinds()) return all_kinds - set(self._usd_kinds()) def _create_selection_list(self, selections): results = "" delimiter = ";" first_selection = True for s in selections: if not first_selection: # pragma: no cover (This seemingly can never happen, since first_selection is initialized with True oO) first_selection = True else: results += delimiter results += s return results def _update_selection_mode_button(self): if self._select_mode_button: self._select_mode_button.name = self._get_select_mode_button_name() self._select_mode_button.tooltip = self._get_select_mode_tooltip() if self._select_op_button: self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model) def _update_select_menu(self): for menu in self._sub_menu: menu.release() self._sub_menu = [] def create_menu_entry(name, value, add_hotkey=False): menu = { "name": name, "onclick_fn": lambda object: self._select_mode_model.set_value(value), "checked_fn": lambda object, name=name, value=value: self._select_mode_model.get_value_as_string() == value, "additional_kwargs": { "style": {"Menu.Item.CheckMark": {"image_url": omni.kit.context_menu.style.get_radio_mark_url()}} }, } if add_hotkey: menu["hotkey"] = (carb.input.KeyboardInput.T) return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") def create_header(header=""): menu = { "header": header, "name": "", } return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") self._sub_menu.append(create_header(header="Select by Type")) self._sub_menu.append(create_menu_entry("All Prim Types", "type:ALL", True)) self._sub_menu.append(create_menu_entry("Meshes", "type:Mesh")) self._sub_menu.append(create_menu_entry("Lights", LIGHT_TYPES)) self._sub_menu.append(create_menu_entry("Camera", "type:Camera")) if self._custom_types: for name, types in self._custom_types: self._sub_menu.append(create_menu_entry(name, types)) self._sub_menu.append(create_header(header="Select by Model Kind")) self._sub_menu.append(create_menu_entry("All Model Kinds", "kind:model.ALL")) self._sub_menu.append(create_menu_entry("Assembly", "kind:assembly")) self._sub_menu.append(create_menu_entry("Group", "kind:group")) self._sub_menu.append(create_menu_entry("Component", "kind:component")) self._sub_menu.append(create_menu_entry("Subcomponent", "kind:subcomponent")) plugin_kinds = self._plugin_kinds() if (len(plugin_kinds)) > 0: for k in plugin_kinds: # pragma: no cover self._sub_menu.append(create_menu_entry(str(k), str(key).capitalize(), f"kind:{k}")) self._sub_menu.append(create_header(header="")) menu = { "name": "Include Prims with no Kind", "onclick_fn": lambda object: self._select_no_kinds_model.set_value(not self._select_no_kinds_model.get_value_as_bool()), "checked_fn": lambda object: self._select_no_kinds_model.get_value_as_bool(), "enabled_fn": self._enable_no_kinds_option, } self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")) menu = { "name": "Include References and Payloads", "onclick_fn": lambda object: self._select_include_ref_model.set_value(not self._select_include_ref_model.get_value_as_bool()), "checked_fn": lambda object: self._select_include_ref_model.get_value_as_bool(), "enabled_fn": self._enable_no_kinds_option, } self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name if context_menu: def on_clicked_select(): # pragma: no cover self._select_op_model.set_value(True) self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model) self._select_op_button.set_tooltip(self._get_select_tooltip()) self._select_op_button.model = self._select_op_model menu = { "name": "Select", "show_fn": [lambda object: is_button(object, "select_op")], "onclick_fn": lambda object: on_clicked_select(), "checked_fn": lambda object: self._select_op_button.name == "select_op_prims" or self._select_op_button.name == "select_op_models", } self._select_mode_menu_entry = omni.kit.context_menu.add_menu(menu, "select_op", "omni.kit.widget.toolbar") if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): menu = { "name": "Select Mode", "show_fn": [lambda object: is_button(object, "select_mode")], } self._select_op_menu_entry = omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") self._update_select_menu() def add_custom_select_type(self, entry_name: str, selection_types: list): selection = [] for s in selection_types: selection.append(f"type:{s}") selection_string = self._create_selection_list(selection) self._custom_types.append((entry_name, selection_string)) self._update_select_menu() def remove_custom_select(self, entry_name): for index, (entry, selection_string) in enumerate(self._custom_types): if entry == entry_name: del self._custom_types[index] self._update_select_menu() return
17,097
Python
44.473404
144
0.592151
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/transform_mode_model.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import carb import carb.dictionary import carb.settings class TransformModeModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the prim select mode""" TRANSFORM_OP_SETTING = "/app/transform/operation" TRANSFORM_OP_SELECT = "select" TRANSFORM_OP_MOVE = "move" TRANSFORM_OP_ROTATE = "rotate" TRANSFORM_OP_SCALE = "scale" def __init__(self, op): super().__init__() self._op = op self._settings = carb.settings.get_settings() self._settings.set_default_string(self.TRANSFORM_OP_SETTING, self.TRANSFORM_OP_MOVE) self._dict = carb.dictionary.get_dictionary() self._op_sub = self._settings.subscribe_to_node_change_events(self.TRANSFORM_OP_SETTING, self._on_op_change) self._selected_op = self._settings.get(self.TRANSFORM_OP_SETTING) def clean(self): self._settings.unsubscribe_to_change_events(self._op_sub) def _on_op_change(self, item, event_type): self._selected_op = self._dict.get(item) self._value_changed() def _on_op_space_changed(self, item, event_type): # pragma: no cover (Seems to never be used, is overwritten in the inherited model where it is used.) self._op_space = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._selected_op == self._op def set_value(self, value): """Reimplemented set bool""" if value: self._settings.set(self.TRANSFORM_OP_SETTING, self._op) class LocalGlobalTransformModeModel(TransformModeModel): TRANSFORM_MODE_GLOBAL = "global" TRANSFORM_MODE_LOCAL = "local" def __init__(self, op, op_space_setting_path): super().__init__(op=op) self._setting_path = op_space_setting_path self._op_space_sub = self._settings.subscribe_to_node_change_events( self._setting_path, self._on_op_space_changed ) self._op_space = self._settings.get(self._setting_path) def clean(self): self._settings.unsubscribe_to_change_events(self._op_space_sub) super().clean() def _on_op_space_changed(self, item, event_type): self._op_space = self._dict.get(item) self._value_changed() def get_op_space_mode(self): return self._op_space def set_value(self, value): if not value: self._settings.set( self._setting_path, self.TRANSFORM_MODE_LOCAL if self._op_space == self.TRANSFORM_MODE_GLOBAL else self.TRANSFORM_MODE_GLOBAL, ) super().set_value(value)
3,104
Python
33.5
155
0.653351
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/setting_model.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import carb import carb.dictionary import carb.settings class BoolSettingModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch a bool setting path""" def __init__(self, setting_path, inverted): super().__init__() self._setting_path = setting_path self._inverted = inverted self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change) self._value = self._settings.get(self._setting_path) if self._inverted: self._value = not self._value def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._value = self._dict.get(item) if self._inverted: self._value = not self._value self._value_changed() def get_value_as_bool(self): return self._value def set_value(self, value): """Reimplemented set bool""" if self._inverted: value = not value self._settings.set(self._setting_path, value) if self._inverted: self._value = value class FloatSettingModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch a float setting path""" def __init__(self, setting_path): super().__init__() self._setting_path = setting_path self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change) self._value = self._settings.get(self._setting_path) def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._value = self._dict.get(item) self._value_changed() def get_value_as_float(self): return self._value def set_value(self, value): """Reimplemented set float""" self._settings.set(self._setting_path, value)
2,654
Python
34.4
112
0.662773
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/timeline_model.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import carb import omni.timeline from omni.kit.commands import execute class TimelinePlayPauseModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch a bool setting path""" def __init__(self): super().__init__() self._timeline = omni.timeline.get_timeline_interface() self._is_playing = self._timeline.is_playing() self._is_stopped = self._timeline.is_stopped() stream = self._timeline.get_timeline_event_stream() self._sub = stream.create_subscription_to_pop(self._on_timeline_event) def clean(self): self._sub = None def get_value_as_bool(self): return self._is_playing and not self._is_stopped def set_value(self, value): """Reimplemented set bool""" if value: execute("ToolbarPlayButtonClicked") else: execute("ToolbarPauseButtonClicked") def _on_timeline_event(self, e): is_playing = self._timeline.is_playing() is_stopped = self._timeline.is_stopped() if is_playing != self._is_playing or is_stopped != self._is_stopped: self._is_playing = self._timeline.is_playing() self._is_stopped = self._timeline.is_stopped() self._value_changed()
1,732
Python
34.367346
86
0.67552
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_mode_model.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import carb import carb.dictionary import carb.settings class SelectModeModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the prim select mode""" PICKING_MODE_SETTING = "/persistent/app/viewport/pickingMode" PICKING_MODE_MODELS = "kind:model.ALL" PICKING_MODE_PRIMS = "type:ALL" # new default PICKING_MODE_DEFAULT = PICKING_MODE_PRIMS def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_string(self.PICKING_MODE_SETTING, self.PICKING_MODE_DEFAULT) self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_SETTING, self._on_change) self.set_value(self._settings.get(self.PICKING_MODE_SETTING)) def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._mode = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._mode == self.PICKING_MODE_PRIMS def get_value_as_string(self): return self._mode def set_value(self, value): if isinstance(value, bool): if value: self._mode = self.PICKING_MODE_PRIMS else: self._mode = self.PICKING_MODE_MODELS else: self._mode = value self._settings.set(self.PICKING_MODE_SETTING, self._mode)
1,993
Python
32.79661
119
0.67988
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_no_kinds_model.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import carb import carb.dictionary import carb.settings class SelectNoKindsModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the prim select mode""" PICKING_MODE_NO_KINDS_SETTING = "/persistent/app/viewport/pickingModeNoKinds" # new default PICKING_MODE_NO_KINDS_DEFAULT = True def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_bool(self.PICKING_MODE_NO_KINDS_SETTING, self.PICKING_MODE_NO_KINDS_DEFAULT) self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_NO_KINDS_SETTING, self._on_change) self.set_value(self._settings.get(self.PICKING_MODE_NO_KINDS_SETTING)) def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._mode = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._mode def set_value(self, value): self._mode = value self._settings.set(self.PICKING_MODE_NO_KINDS_SETTING, self._mode)
1,680
Python
34.765957
128
0.713095
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_include_ref_model.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import carb import carb.dictionary import carb.settings class SelectIncludeRefModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the prim select mode""" PICKING_MODE_INCLUDE_REF_SETTING = "/persistent/app/viewport/pickingModeIncludeRef" # new default PICKING_MODE_INCLUDE_REF_DEFAULT = True def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_bool(self.PICKING_MODE_INCLUDE_REF_SETTING, self.PICKING_MODE_INCLUDE_REF_DEFAULT) self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_INCLUDE_REF_SETTING, self._on_change) self.set_value(self._settings.get(self.PICKING_MODE_INCLUDE_REF_SETTING)) def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._mode = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._mode def set_value(self, value): self._mode = value self._settings.set(self.PICKING_MODE_INCLUDE_REF_SETTING, self._mode)
1,707
Python
35.340425
131
0.717633
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/helpers.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.settings def reset_toolbar_settings(): settings = carb.settings.get_settings() vals = { "/app/transform/operation": "move", "/persistent/app/viewport/pickingMode": "type:ALL", "/app/viewport/snapEnabled": False, } for key, val in vals.items(): settings.set(key, val)
759
Python
32.043477
76
0.724638
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_api.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 asyncio import carb.settings import omni.appwindow import omni.kit.app import omni.kit.test import omni.timeline import omni.kit.ui_test as ui_test import omni.kit.widget.toolbar import omni.kit.context_menu import omni.kit.hotkeys.core import omni.ui as ui from carb.input import KeyboardInput as Key from carb.input import KEYBOARD_MODIFIER_FLAG_SHIFT from omni.kit.ui_test import Vec2 from omni.kit.widget.toolbar import Hotkey, SimpleToolButton, Toolbar, WidgetGroup, get_instance from .helpers import reset_toolbar_settings test_message_queue = [] class TestSimpleToolButton(SimpleToolButton): """ Test of how to use SimpleToolButton """ def __init__(self, icon_path): def on_toggled(c): test_message_queue.append(f"Test button toggled {c}") super().__init__( name="test_simple_tool_button", tooltip="Test Simple ToolButton", icon_path=f"{icon_path}/plus.svg", icon_checked_path=f"{icon_path}/plus.svg", hotkey=Key.U, toggled_fn=on_toggled, additional_style={"Button": { "color": 0xffffffff }} ) class TestToolButtonGroup(WidgetGroup): """ Test of how to create two ToolButton in one WidgetGroup """ def __init__(self, icon_path): super().__init__() self._icon_path = icon_path def clean(self): self._sub1 = None self._sub2 = None self._hotkey.clean() self._hotkey = None super().clean() def get_style(self): style = { "Button.Image::test1": {"image_url": f"{self._icon_path}/plus.svg"}, "Button.Image::test1:checked": {"image_url": f"{self._icon_path}/minus.svg"}, "Button.Image::test2": {"image_url": f"{self._icon_path}/minus.svg"}, "Button.Image::test2:checked": {"image_url": f"{self._icon_path}/plus.svg"}, } return style def create(self, default_size): def on_value_changed(index, model): if model.get_value_as_bool(): self._acquire_toolbar_context() else: self._release_toolbar_context() test_message_queue.append(f"Group button {index} clicked") self._menu1 = omni.kit.context_menu.add_menu({ "name": "Test 1", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar") self._menu2 = omni.kit.context_menu.add_menu({ "name": "Test 2", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar") button1 = ui.ToolButton( name="test1", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "test1"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), ) self._sub1 = button1.model.subscribe_value_changed_fn(lambda model, index=1: on_value_changed(index, model)) button2 = ui.ToolButton( name="test2", width=default_size, height=default_size, ) self._sub2 = button2.model.subscribe_value_changed_fn(lambda model, index=2: on_value_changed(index, model)) self._hotkey = Hotkey( "toolbar::test2", Key.K, lambda: button2.model.set_value(not button2.model.get_value_as_bool()), lambda: self._is_in_context(), ) # return a dictionary of name -> widget if you want to expose it to other widget_group return {"test1": button1, "test2": button2} _MAIN_WINDOW_INSTANCE = None class ToolbarApiTest(omni.kit.test.AsyncTestCase): WINDOW_NAME = "Main Toolbar Test" async def setUp(self): reset_toolbar_settings() self._icon_path = omni.kit.widget.toolbar.get_data_path().absolute().joinpath("icon").absolute() self._app = omni.kit.app.get_app() test_message_queue.clear() # If the instance doesn't exist, we need to create it for the test # Create a tmp window with the widget inside, Y axis because the tests are in the Y axis global _MAIN_WINDOW_INSTANCE if _MAIN_WINDOW_INSTANCE is None: _MAIN_WINDOW_INSTANCE = ui.ToolBar( self.WINDOW_NAME, noTabBar=False, padding_x=3, padding_y=3, margin=5, axis=ui.ToolBarAxis.Y ) self._widget = get_instance() self._widget.set_axis(ui.ToolBarAxis.Y) self._widget.rebuild_toolbar(root_frame=_MAIN_WINDOW_INSTANCE.frame) await self._app.next_update_async() await self._app.next_update_async() self._main_dockspace = ui.Workspace.get_window("DockSpace") self._toolbar_handle = ui.Workspace.get_window(self.WINDOW_NAME) self._toolbar_handle.undock() await self._app.next_update_async() self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.LEFT) await self._app.next_update_async() async def test_api(self): toolbar: Toolbar = omni.kit.widget.toolbar.get_instance() widget_simple = TestSimpleToolButton(self._icon_path) widget = TestToolButtonGroup(self._icon_path) toolbar.add_widget(widget, -100) toolbar.add_widget(widget_simple, -200) await self._app.next_update_async() self.assertIsNotNone(widget_simple.get_tool_button()) # Check widgets are added and can be fetched self.assertIsNotNone(toolbar.get_widget("test_simple_tool_button")) self.assertIsNotNone(toolbar.get_widget("test1")) self.assertIsNotNone(toolbar.get_widget("test2")) await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() manager = omni.kit.app.get_app().get_extension_manager() extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__)) hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry() hotkey = self._get_hotkey('test_simple_tool_button::hotkey') self.assertIsNotNone(hotkey) hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button") tool_test1_pos = self._get_widget_center(toolbar, "test1") tool_test2_pos = self._get_widget_center(toolbar, "test2") # Test click on first simple button await self._emulate_click(tool_test_simple_pos) await self._app.next_update_async() # Test hot key on first simple button await self._emulate_keyboard_press(Key.U, KEYBOARD_MODIFIER_FLAG_SHIFT) await self._app.next_update_async() # Test click on 1/2 group button await self._emulate_click(tool_test1_pos) await self._app.next_update_async() # Test click on 2/2 group button await self._emulate_click(tool_test2_pos) await self._app.next_update_async() # Test click on 2/2 group button again await self._emulate_click(tool_test2_pos) await self._app.next_update_async() self.assertIsNone(ui.Menu.get_current()) # Test right click on 1/2 group button await self._emulate_click(tool_test1_pos, right_click=True) await self._app.next_update_async() self.assertIsNotNone(ui.Menu.get_current()) # Test left click on 1/2 group button to close the menu await self._emulate_click(tool_test1_pos, right_click=False) await self._app.next_update_async() self.assertIsNone(ui.Menu.get_current()) # Test hold-left-click click on 1/2 group button await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.MOVE, Vec2(*tool_test1_pos)) await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_DOWN) await self._app.next_update_async() await asyncio.sleep(0.4) await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_UP) await self._app.next_update_async() self.assertIsNotNone(ui.Menu.get_current()) # Test left click on 1/2 group button to close the menu await self._emulate_click(tool_test1_pos) await self._app.next_update_async() self.assertIsNone(ui.Menu.get_current()) # Making sure all button are triggered by checking the message queue expected_messages = [ "Test button toggled True", "Test button toggled False", "Group button 1 clicked", "Group button 2 clicked", "Group button 2 clicked", ] self.assertEqual(expected_messages, test_message_queue) test_message_queue.clear() hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=0), None) toolbar.remove_widget(widget) toolbar.remove_widget(widget_simple) widget.clean() widget_simple.clean() await self._app.next_update_async() # Check widgets are cleared self.assertIsNone(toolbar.get_widget("test_simple_tool_button")) self.assertIsNone(toolbar.get_widget("test1")) self.assertIsNone(toolbar.get_widget("test2")) # Change the Hotkey for the Play button play_hotkey = self._get_hotkey('toolbar::play') self.assertIsNotNone(play_hotkey) hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) await self._app.next_update_async() tooltip_after_change = toolbar.get_widget('play').tooltip hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=0), None) await self._app.next_update_async() tooltip_after_revert = toolbar.get_widget('play').tooltip self.assertEqual(tooltip_after_change, "Play (SHIFT + SPACE)") self.assertEqual(tooltip_after_revert, "Play (SPACE)") # Change the Hotkey for the Select Mode button select_mode_hotkey = self._get_hotkey('toolbar::select_mode') self.assertIsNotNone(select_mode_hotkey) hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) await self._app.next_update_async() tooltip_after_change = toolbar.get_widget('select_mode').tooltip hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=0), None) await self._app.next_update_async() tooltip_after_revert = toolbar.get_widget('select_mode').tooltip self.assertEqual(tooltip_after_change, "All Prim Types (SHIFT + T)") self.assertEqual(tooltip_after_revert, "All Prim Types (T)") # Change the Hotkey for the Move button move_op_hotkey = self._get_hotkey('toolbar::move') self.assertIsNotNone(move_op_hotkey) hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) await self._app.next_update_async() tooltip_after_change = toolbar.get_widget('move_op').tooltip hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=0), None) await self._app.next_update_async() tooltip_after_revert = toolbar.get_widget('move_op').tooltip from ..builtin_tools.transform_button_group import MOVE_TOOL_NAME self.assertEqual(tooltip_after_change, f"{MOVE_TOOL_NAME} (SHIFT + W)") self.assertEqual(tooltip_after_revert, f"{MOVE_TOOL_NAME} (W)") # Test the Select Mode hotkey button settings = carb.settings.get_settings() from ..builtin_tools.models.select_mode_model import SelectModeModel self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS) await self._emulate_keyboard_press(Key.T) await self._app.next_update_async() self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_MODELS) await self._emulate_keyboard_press(Key.T) await self._app.next_update_async() self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS) # Test changing the Select hotkey select_hotkey = self._get_hotkey('toolbar::select') self.assertIsNotNone(select_hotkey) hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) await self._app.next_update_async() hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=0), None) await self._app.next_update_async() async def test_context(self): toolbar = omni.kit.widget.toolbar.get_instance() widget_simple = TestSimpleToolButton(self._icon_path) widget = TestToolButtonGroup(self._icon_path) test_context = "test_context" toolbar.add_widget(widget, -100) toolbar.add_widget(widget_simple, -200, test_context) await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button") tool_test1_pos = self._get_widget_center(toolbar, "test1") # Test click on first simple button # Add "Test button toggled True" to queue await self._emulate_click(tool_test_simple_pos) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), test_context) # Test hot key on 2/2 group button # It should have no effect since it's not "in context" # Add nothing to queue await self._emulate_keyboard_press(Key.K) await self._app.next_update_async() # Test click on first simple button again, should exit context # Add "Test button toggled False" to queue await self._emulate_click(tool_test_simple_pos) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT) # Test hot key on 2/2 group button again # It should have effect because it's in default context # Add "Group button 2 clicked" to queue await self._emulate_keyboard_press(Key.K) await self._app.next_update_async() # Test click on first simple button again # Add "Test button toggled True" to queue await self._emulate_click(tool_test_simple_pos) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), test_context) # Test click on 1/2 group button so it takes context by force. # Add "Group button 1 clicked" to queue await self._emulate_click(tool_test1_pos) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT) # Test hot key on first simple button, it should still work on default context. # Releasing an expired context. # Add "Test button toggled False" to queue await self._emulate_keyboard_press(Key.U) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT) # Test hot key on first simple button, it should still work on default context. # Add "Test button toggled True" to queue await self._emulate_keyboard_press(Key.U) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), test_context) expected_messages = [ "Test button toggled True", "Test button toggled False", "Group button 2 clicked", "Test button toggled True", "Group button 1 clicked", "Test button toggled False", "Test button toggled True", ] self.assertEqual(expected_messages, test_message_queue) toolbar.remove_widget(widget) toolbar.remove_widget(widget_simple) widget.clean() widget_simple.clean() await self._app.next_update_async() def _get_widget_center(self, toolbar, id: str): return ( toolbar.get_widget(id).screen_position_x + toolbar.get_widget(id).width / 2, toolbar.get_widget(id).screen_position_y + toolbar.get_widget(id).height / 2, ) def _get_hotkey(self, action_id: str): manager = omni.kit.app.get_app().get_extension_manager() extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__)) hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry() for hotkey in hotkey_registry.get_all_hotkeys_for_extension(extension_name): if hotkey.action_id == action_id: return hotkey async def _emulate_click(self, pos, right_click: bool = False): await ui_test.emulate_mouse_move_and_click(Vec2(*pos), right_click=right_click) async def _emulate_keyboard_press(self, key: Key, modifier: int = 0): await ui_test.emulate_keyboard_press(key, modifier) async def test_custom_select_types(self): toolbar: Toolbar = omni.kit.widget.toolbar.get_instance() entry_name = 'TestType' toolbar.add_custom_select_type(entry_name, ['test_type']) menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar") self.assertIn(entry_name, [item['name'] for item in menu_dict]) toolbar.remove_custom_select(entry_name) menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar") self.assertNotIn(entry_name, [item['name'] for item in menu_dict]) async def test_toolbar_methods(self): from ..context_menu import ContextMenu toolbar: Toolbar = omni.kit.widget.toolbar.get_instance() self.assertIsInstance(toolbar.context_menu, ContextMenu) toolbar.set_axis(ui.ToolBarAxis.X) toolbar.rebuild_toolbar() await ui_test.human_delay() toolbar.set_axis(ui.ToolBarAxis.Y) toolbar.rebuild_toolbar() await ui_test.human_delay() toolbar.subscribe_grab_mouse_pressed(None) async def test_toolbar_play_stop_button(self): toolbar: Toolbar = omni.kit.widget.toolbar.get_instance() timeline = omni.timeline.get_timeline_interface() # Click the stop button toolbar.get_widget("stop").call_clicked_fn() await ui_test.human_delay() self.assertTrue(timeline.is_stopped())
19,485
Python
39.17732
146
0.651014
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/__init__.py
from .test_api import * from .test_models import *
50
Python
24.499988
26
0.74
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_models.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.kit.test import omni.timeline import carb.settings import omni.kit.commands from omni.kit import ui_test class ToolbarTestModels(omni.kit.test.AsyncTestCase): async def test_setting_pass_through(self): from ..builtin_tools.builtin_tools import LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET settings = carb.settings.get_settings() orig_value = settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET) settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, True) self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)) settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, False) self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)) settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, orig_value) async def test_select_include_ref_model(self): from ..builtin_tools.models.select_include_ref_model import SelectIncludeRefModel model = SelectIncludeRefModel() orig_value = model.get_value_as_bool() model.set_value(not orig_value) self.assertEqual(model.get_value_as_bool(), not orig_value) model.set_value(orig_value) async def test_select_mode_model(self): from ..builtin_tools.models.select_mode_model import SelectModeModel model = SelectModeModel() orig_value = model.get_value_as_string() model.set_value(True) self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS) model.set_value(False) self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_MODELS) model.set_value(SelectModeModel.PICKING_MODE_PRIMS) self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS) model.set_value(orig_value) async def test_select_no_kinds_model(self): from ..builtin_tools.models.select_no_kinds_model import SelectNoKindsModel model = SelectNoKindsModel() orig_value = model.get_value_as_bool() model.set_value(not orig_value) self.assertEqual(model.get_value_as_bool(), not orig_value) model.set_value(orig_value) async def test_setting_model(self): from ..builtin_tools.models.setting_model import BoolSettingModel, FloatSettingModel settings = carb.settings.get_settings() bool_setting_path = '/exts/omni.kit.widget.toolbar/test/boolSetting' float_setting_path = '/exts/omni.kit.widget.toolbar/test/floatSetting' bool_model = BoolSettingModel(bool_setting_path, False) bool_model.set_value(True) self.assertEqual(bool_model.get_value_as_bool(), True) self.assertEqual(settings.get(bool_setting_path), True) bool_model.set_value(False) self.assertEqual(bool_model.get_value_as_bool(), False) self.assertEqual(settings.get(bool_setting_path), False) inverted_bool_model = BoolSettingModel(bool_setting_path, True) inverted_bool_model.set_value(True) self.assertEqual(inverted_bool_model.get_value_as_bool(), not True) self.assertEqual(settings.get(bool_setting_path), not True) inverted_bool_model.set_value(False) self.assertEqual(inverted_bool_model.get_value_as_bool(), not False) self.assertEqual(settings.get(bool_setting_path), not False) float_model = FloatSettingModel(float_setting_path) float_model.set_value(42.0) self.assertEqual(float_model.get_value_as_float(), 42.0) self.assertEqual(settings.get(float_setting_path), 42.0) float_model.set_value(21.0) self.assertEqual(float_model.get_value_as_float(), 21.0) self.assertEqual(settings.get(float_setting_path), 21.0) async def test_timeline_model(self): from ..builtin_tools.models.timeline_model import TimelinePlayPauseModel model = TimelinePlayPauseModel() model.set_value(True) await ui_test.human_delay() self.assertTrue(model.get_value_as_bool()) model.set_value(False) await ui_test.human_delay() self.assertFalse(model.get_value_as_bool()) async def test_transform_mode_model(self): from ..builtin_tools.models.transform_mode_model import TransformModeModel, LocalGlobalTransformModeModel model = TransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE) model.set_value(True) self.assertTrue(model.get_value_as_bool()) settings = carb.settings.get_settings() setting_path = '/exts/omni.kit.widget.toolbar/test/localGlobalTransformOp' settings.set(setting_path, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL) model = LocalGlobalTransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE, setting_path) model.set_value(False) self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL) model.set_value(False) self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL) async def test_play_pause_stop_commands(self): timeline = omni.timeline.get_timeline_interface() omni.kit.commands.execute("ToolbarPlayButtonClicked") await ui_test.human_delay() self.assertTrue(timeline.is_playing()) omni.kit.commands.execute("ToolbarPauseButtonClicked") await ui_test.human_delay() self.assertFalse(timeline.is_playing()) omni.kit.commands.execute("ToolbarStopButtonClicked") await ui_test.human_delay() self.assertTrue(timeline.is_stopped()) settings = carb.settings.get_settings() setting_path = '/exts/omni.kit.widget.toolbar/test/playFilter' omni.kit.commands.execute("ToolbarPlayFilterChecked", setting_path=setting_path, enabled=True) self.assertTrue(settings.get(setting_path))
6,629
Python
43.496644
148
0.706291
omniverse-code/kit/exts/omni.kit.widget.toolbar/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.kit.window.toolbar`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [1.4.0] - 2022-11-28 ### Changed - Rename `omni.kit.window.toolbar` into `omni.kit.widget.toolbar` ## [1.3.3] - 2022-09-26 ### Changed - Updated to use `omni.kit.actions.core` and `omni.kit.hotkeys.core` for hotkeys. ## [1.3.2] - 2022-09-01 ### Changed - Context menu without compatibility mode. ## [1.3.1] - 2022-06-23 ### Changed - Change how hotkey `W` is skipped during possible camera manipulation. ## [1.3.0] - 2022-05-17 ### Changed - Changed Snap button to legacy button. New snap button will be registered by extension. ## [1.2.4] - 2022-04-19 ### Fixed - Slienced menu_changed error on create exit ## [1.2.3] - 2022-04-06 ### Fixed - Message "Failed to acquire interface while unloading all plugins" ## [1.2.1] - 2021-06-22 ### Added - Fixed height of increment settings window ## [1.2.0] - 2021-06-04 ### Added - Moved all built-in toolbutton's flyout menu to use omni.kit.context_menu, making it easier to add additional menu items to exiting button from external extension. ## [1.1.0] - 2021-04-16 ### Added - Added "Context" concept to toolbar that can be used to control the effective scope of tool buttons. ## [1.0.0] - 2021-03-04 ### Added - Started tracking changelog. Added tests.
1,381
Markdown
26.639999
164
0.696597
omniverse-code/kit/exts/omni.kit.widget.toolbar/docs/index.rst
omni.kit.widget.toolbar ########################### Omniverse Kit Toolbar extension .. toctree:: :maxdepth: 1 CHANGELOG
129
reStructuredText
11.999999
31
0.565891
omniverse-code/kit/exts/omni.kit.window.file/PACKAGE-LICENSES/omni.kit.window.file-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.window.file/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.3.32" category = "Internal" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "USD File UI" description="Provides utility functions to new/open/save/close USD files" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "usd", "ui"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" [dependencies] "omni.client" = {} "omni.usd" = {} "omni.kit.stage_templates" = {} "omni.ui" = {} "omni.kit.pip_archive" = {} # Pull in pip_archive to make sure psutil is found and not installed "omni.kit.window.file_importer" = {} "omni.kit.window.file_exporter" = {} "omni.kit.widget.versioning" = {} "omni.kit.widget.nucleus_connector" = {} "omni.kit.actions.core" = {} [python.pipapi] requirements = ["psutil"] [[python.module]] name = "omni.kit.window.file" [settings] exts."omni.kit.window.file".enable_versioning = true [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/file/ignoreUnsavedOnExit=true", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", "--no-window" ] dependencies = [ "omni.hydra.pxr", "omni.physx.bundle", "omni.timeline", "omni.kit.mainwindow", "omni.kit.menu.file", "omni.kit.ui_test", "omni.kit.test_suite.helpers", ]
1,741
TOML
25.8
96
0.687536
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/__init__.py
from .scripts import *
23
Python
10.999995
22
0.73913
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/prompt_ui.py
import urllib import carb import carb.settings import omni.ui as ui from typing import List class Prompt: def __init__( self, title: str, text: str, button_text: list, button_fn: list, modal: bool = False, callback_addons: List = [], callback_destroy: List = [], decode_text: bool = True ): self._title = title self._text = urllib.parse.unquote(text) if decode_text else text self._button_list = [] self._modal = modal self._callback_addons = callback_addons self._callback_destroy = callback_destroy self._buttons = [] for name, fn in zip(button_text, button_fn): self._button_list.append((name, fn)) self._build_ui() def destroy(self): self._cancel_button_fn = None self._ok_button_fn = None self._button_list = [] if self._window: self._window.destroy() del self._window self._window = None for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() self._callback_addons = [] for callback in self._callback_destroy: if callback and callable(callback): callback() self._callback_destroy = [] def __del__(self): self.destroy() def __enter__(self): self.show() if self._modal: settings = carb.settings.get_settings() # Only use first word as a reason (e.g. "Creating, Openning"). URL won't work as a setting key. operation = self._text.split(" ")[0].lower() self._hang_detector_disable_key = "/app/hangDetector/disableReasons/{0}".format(operation) settings.set(self._hang_detector_disable_key, "1") settings.set("/crashreporter/data/appState", operation) return self def __exit__(self, type, value, trace): self.hide() if self._modal: settings = carb.settings.get_settings() settings.destroy_item(self._hang_detector_disable_key) settings.set("/crashreporter/data/appState", "started") def show(self): self._window.visible = True def hide(self): self._window.visible = False def is_visible(self): return self._window.visible def set_text(self, text): self._text_label.text = text def _build_ui(self): self._window = ui.Window( self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED, raster_policy=ui.RasterPolicy.NEVER ) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_NO_CLOSE ) if self._modal: self._window.flags |= ui.WINDOW_FLAGS_MODAL with self._window.frame: with ui.VStack(height=0): ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer(widht=10, height=0) self._text_label = ui.Label( self._text, width=ui.Percent(100), height=0, word_wrap=True, alignment=ui.Alignment.CENTER, ) ui.Spacer(widht=10, height=0) ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer(height=0) for name, fn in self._button_list: if name: button = ui.Button(name) if fn: button.set_clicked_fn(lambda on_fn=fn: (self.hide(), on_fn())) else: button.set_clicked_fn(lambda: self.hide()) self._buttons.append(button) ui.Spacer(height=0) ui.Spacer(width=0, height=10) for callback in self._callback_addons: if callback and callable(callback): callback()
4,295
Python
32.302325
128
0.518743
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/share_window.py
import carb import omni.ui as ui class ShareWindow(ui.Window): def __init__(self, copy_button_text="Copy Path to Clipboard", copy_button_fn=None, modal=True, url=None): self._title = "Share Omniverse USD Path" self._copy_button_text = copy_button_text self._copy_button_fn = copy_button_fn self._status_text = "Copy and paste this path to another user to share the location of this USD file." self._stage_url = url self._stage_string_box = None super().__init__(self._title, visible=url is not None, width=600, height=140, dockPreference=ui.DockPreference.DISABLED) self.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE ) if modal: self.flags = self.flags | ui.WINDOW_FLAGS_MODAL self.frame.set_build_fn(self._build_ui) def _build_ui(self): with self.frame: with ui.VStack(): ui.Spacer(height=10) with ui.HStack(height=0): ui.Spacer() self._status_label = ui.Label(self._status_text, width=0) ui.Spacer() ui.Spacer(height=10) with ui.HStack(height=0): ui.Spacer() self._stage_string_box = ui.StringField(width=550) self._stage_string_box.model.set_value(self._stage_url) ui.Spacer() ui.Spacer(height=5) with ui.HStack(height=0): ui.Spacer() copy_button = ui.Button(self._copy_button_text, width=165) copy_button.set_clicked_fn(self._on_copy_button_fn) ui.Spacer() ui.Spacer(height=10) def _on_copy_button_fn(self): self.visible = False if self._stage_string_box: try: import omni.kit.clipboard # type: ignore try: omni.kit.clipboard.copy(self._stage_string_box.model.as_string) except: carb.log_warn("clipboard copy failed") except ImportError: carb.log_warn("Could not import omni.kit.clipboard. Cannot copy scene URL to the clipboard.") @property def url(self): return self._stage_url @url.setter def url(self, value: str) -> None: self._stage_url = value if self._stage_string_box: self._stage_string_box.model.set_value(value) self.visible = True
2,688
Python
37.971014
128
0.541295
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/save_stage_ui.py
import asyncio import weakref import urllib import carb.settings import omni.client import omni.ui from omni.kit.widget.versioning import CheckpointHelper class CheckBoxStatus: def __init__(self, checkbox, layer_identifier, layer_is_writable): self.checkbox = checkbox self.layer_identifier = layer_identifier self.layer_is_writable = layer_is_writable self.is_checking = False class StageSaveDialog: WINDOW_WIDTH = 580 MAX_VISIBLE_LAYER_COUNT = 10 def __init__(self, on_save_fn=None, on_dont_save_fn=None, on_cancel_fn=None, enable_dont_save=False): self._usd_context = omni.usd.get_context() self._save_fn = on_save_fn self._dont_save_fn = on_dont_save_fn self._cancel_fn = on_cancel_fn self._checkboxes_status = [] self._select_all_checkbox_is_checking = False self._selected_layers = [] self._checkpoint_marks = {} flags = ( omni.ui.WINDOW_FLAGS_NO_COLLAPSE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_MODAL ) self._window = omni.ui.Window( "Select Files to Save##file.py", visible=False, width=0, height=0, flags=flags, auto_resize=True, padding_x=10, dockPreference=omni.ui.DockPreference.DISABLED, ) with self._window.frame: with omni.ui.VStack(height=0, width=StageSaveDialog.WINDOW_WIDTH): self._layers_scroll_frame = omni.ui.ScrollingFrame(height=160) omni.ui.Spacer(width=0, height=10) self._checkpoint_comment_frame = omni.ui.Frame() with self._checkpoint_comment_frame: with omni.ui.VStack(height=0, spacing=5): omni.ui.Label("*) File(s) that will be Checkpointed with a comment.") with omni.ui.ZStack(): self._description_field = omni.ui.StringField(multiline=True, height=60) self._description_field_hint_label = omni.ui.Label( " Description", alignment=omni.ui.Alignment.LEFT_TOP, style={"color": 0xFF3F3F3F} ) self._description_begin_edit_sub = self._description_field.model.subscribe_begin_edit_fn( self._on_description_begin_edit ) self._description_end_edit_sub = self._description_field.model.subscribe_end_edit_fn( self._on_description_end_edit ) self._checkpoint_comment_spacer = omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(height=0) self._save_selected_button = omni.ui.Button("Save Selected", width=0, height=0) self._save_selected_button.set_clicked_fn(self._on_save_fn) omni.ui.Spacer(width=5, height=0) if enable_dont_save: self._dont_save_button = omni.ui.Button("Don't Save", width=0, height=0) self._dont_save_button.set_clicked_fn(self._on_dont_save_fn) omni.ui.Spacer(width=5, height=0) self._cancel_button = omni.ui.Button("Cancel", width=0, height=0) self._cancel_button.set_clicked_fn(self._on_cancel_fn) omni.ui.Spacer(height=0) omni.ui.Spacer(height=5) def destroy(self): self._usd_context = None self._save_fn = None self._dont_save_fn = None self._cancel_fn = None self._checkboxes_status = None self._selected_layers = None self._checkpoint_marks = None if self._window: del self._window self._window = None def __del__(self): self.destroy() def _on_save_fn(self): if self._save_fn: self._save_fn( self._selected_layers, comment=self._description_field.model.get_value_as_string() if self._checkpoint_comment_frame.visible else "", ) self._window.visible = False self._selected_layers = [] def _on_dont_save_fn(self): if self._dont_save_fn: self._dont_save_fn(self._description_field.model.get_value_as_string()) self._window.visible = False self._selected_layers = [] def _on_cancel_fn(self): if self._cancel_fn: self._cancel_fn(self._description_field.model.get_value_as_string()) self._window.visible = False self._selected_layers = [] def _on_select_all_fn(self, model): if self._select_all_checkbox_is_checking: return self._select_all_checkbox_is_checking = True if model.get_value_as_bool(): for checkbox_status in self._checkboxes_status: checkbox_status.checkbox.model.set_value(True) else: for checkbox_status in self._checkboxes_status: checkbox_status.checkbox.model.set_value(False) self._select_all_checkbox_is_checking = False def _check_and_select_all(self, select_all_check_box): select_all = True for checkbox_status in self._checkboxes_status: if checkbox_status.layer_is_writable and not checkbox_status.checkbox.model.get_value_as_bool(): select_all = False break if select_all: self._select_all_checkbox_is_checking = True select_all_check_box.model.set_value(True) self._select_all_checkbox_is_checking = False def _on_checkbox_fn(self, model, check_box_index, select_all_check_box): check_box_status = self._checkboxes_status[check_box_index] if check_box_status.is_checking: return check_box_status.is_checking = True if not check_box_status.layer_is_writable: model.set_value(False) elif model.get_value_as_bool(): self._selected_layers.append(check_box_status.layer_identifier) self._check_and_select_all(select_all_check_box) else: self._selected_layers.remove(check_box_status.layer_identifier) self._select_all_checkbox_is_checking = True select_all_check_box.model.set_value(False) self._select_all_checkbox_is_checking = False check_box_status.is_checking = False def show(self, layer_identifiers=None): self._layers_scroll_frame.clear() self._checkpoint_marks.clear() self._checkpoint_comment_frame.visible = False self._checkpoint_comment_spacer.visible = False settings = carb.settings.get_settings() enable_versioning = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False # make a copy self._selected_layers.extend(layer_identifiers) self._checkboxes_status = [] #build layers_scroll_frame self._first_item_stack = None with self._layers_scroll_frame: with omni.ui.VStack(height=0): omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(width=20, height=0) self._select_all_checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16}) self._select_all_checkbox.model.set_value(True) omni.ui.Label("File Name", alignment=omni.ui.Alignment.LEFT) omni.ui.Spacer(width=20, height=0) omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(width=20, height=0) omni.ui.Separator(height=0, style={"color": 0xFF808080}) omni.ui.Spacer(width=20, height=0) omni.ui.Spacer(width=0, height=5) for i in range(len(layer_identifiers)): layer_identifier = layer_identifiers[i] # TODO Move version related code if enable_versioning: # Check if the server support checkpoint self._check_checkpoint_enabled(layer_identifier) style = {} layer_is_writable = omni.usd.is_layer_writable(layer_identifier) layer_is_locked = omni.usd.is_layer_locked(self._usd_context, layer_identifier) if not layer_is_writable or layer_is_locked: self._selected_layers.remove(layer_identifier) style = {"background_color": 0xFF808080, "color": 0xFF808080} label_text = urllib.parse.unquote(layer_identifier).replace("\\", "/") if not layer_is_writable or layer_is_locked: label_text += " (Read-Only)" omni.ui.Spacer(width=0, height=5) stack = omni.ui.HStack(height=0, style=style) if self._first_item_stack is None: self._first_item_stack = stack with stack: omni.ui.Spacer(width=20, height=0) checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16}) checkbox.model.set_value(True) omni.ui.Label(label_text, word_wrap=False, elided_text=True, alignment=omni.ui.Alignment.LEFT) check_point_label = omni.ui.Label("*", width=3, alignment=omni.ui.Alignment.LEFT, visible=False) omni.ui.Spacer(width=20, height=0) self._checkpoint_marks[layer_identifier] = check_point_label checkbox.model.add_value_changed_fn( lambda a, b=i, c=self._select_all_checkbox: self._on_checkbox_fn(a, b, c) ) self._checkboxes_status.append(CheckBoxStatus(checkbox, layer_identifier, layer_is_writable)) self._select_all_checkbox.model.add_value_changed_fn(lambda a: self._on_select_all_fn(a)) self._window.visible = True async def __delay_adjust_window_size(weak_self): await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() __self = weak_self() if not __self: return y0 = __self._layers_scroll_frame.screen_position_y y1 = __self._first_item_stack.screen_position_y fixed_height = y1 - y0 + 5 item_height = __self._first_item_stack.computed_content_height + 5 count = min(StageSaveDialog.MAX_VISIBLE_LAYER_COUNT, len(__self._checkpoint_marks)) scroll_frame_new_height = fixed_height + count * item_height __self._layers_scroll_frame.height = omni.ui.Pixel(scroll_frame_new_height) if len(layer_identifiers) > 0: asyncio.ensure_future(__delay_adjust_window_size(weakref.ref(self))) def is_visible(self): return self._window.visible def _on_description_begin_edit(self, model): self._description_field_hint_label.visible = False def _on_description_end_edit(self, model): if len(model.get_value_as_string()) == 0: self._description_field_hint_label.visible = True def _check_checkpoint_enabled(self, url): async def check_server_support(weak_self, url): _self = weak_self() if not _self: return if await CheckpointHelper.is_checkpoint_enabled_async(url): _self._checkpoint_comment_frame.visible = True _self._checkpoint_comment_spacer.visible = True label = _self._checkpoint_marks.get(url, None) if label: label.visible = True asyncio.ensure_future(check_server_support(weakref.ref(self), url))
12,233
Python
43.813187
120
0.563803
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/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 carb import omni.ui as ui try: THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") except Exception: THEME = None finally: THEME = THEME or "NvidiaDark" def get_style(): if THEME == "NvidiaLight": # pragma: no cover BACKGROUND_COLOR = 0xFF535354 BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E FIELD_BACKGROUND_COLOR = 0xFF1F2124 SECONDARY_COLOR = 0xFFE0E0E0 BORDER_COLOR = 0xFF707070 TITLE_COLOR = 0xFF707070 TEXT_COLOR = 0xFF8D760D TEXT_HINT_COLOR = 0xFFD6D6D6 else: BACKGROUND_COLOR = 0xFF23211F BACKGROUND_SELECTED_COLOR = 0xFF8A8777 BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A SECONDARY_COLOR = 0xFF9E9E9E BORDER_COLOR = 0xFF8A8777 TITLE_COLOR = 0xFFCECECE TEXT_COLOR = 0xFF9E9E9E TEXT_HINT_COLOR = 0xFF7A7A7A style = { "Button": { "background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "margin": 0, "padding": 0 }, "Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR}, "Button.Label": {"color": TEXT_COLOR}, "Field": {"background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER}, "Field.Hint": {"background_color": 0x0, "color": TEXT_HINT_COLOR, "margin_width": 4}, "Label": {"background_color": 0x0, "color": TEXT_COLOR}, "CheckBox": {"alignment": ui.Alignment.CENTER}, } return style
2,126
Python
36.982142
161
0.659454
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/__init__.py
from .file_window import *
27
Python
12.999994
26
0.740741
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_actions.py
import omni.kit.actions.core from .app_ui import AppUI, DialogOptions def register_actions(extension_id): import omni.kit.window.file action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "File Actions" action_registry.register_action( extension_id, "new", omni.kit.window.file.new, display_name="File->New", description="Create a new USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open", omni.kit.window.file.open, display_name="File->Open", description="Open an existing USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open_stage", omni.kit.window.file.open_stage, display_name="File->Open Stage", description="Open an named USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "reopen", omni.kit.window.file.reopen, display_name="File->Reopen", description="Reopen the currently opened USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open_with_new_edit_layer", omni.kit.window.file.open_with_new_edit_layer, display_name="File->Open With New Edit Layer", description="Open an existing USD stage with a new edit layer.", tag=actions_tag, ) action_registry.register_action( extension_id, "share", omni.kit.window.file.share, display_name="File->Share", description="Share the currently open USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "save", lambda: omni.kit.window.file.save(dialog_options=DialogOptions.HIDE), display_name="File->Save", description="Save the currently opened USD stage to file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_with_options", lambda: omni.kit.window.file.save(dialog_options=DialogOptions.NONE), display_name="File->Save With Options", description="Save the currently opened USD stage to file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_as", lambda: omni.kit.window.file.save_as(False), display_name="File->Save As", description="Save the currently opened USD stage to a new file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_as_flattened", lambda: omni.kit.window.file.save_as(True), display_name="File->Save As Flattened", description="Save the currently opened USD stage to a new flattened file.", tag=actions_tag, ) action_registry.register_action( extension_id, "add_reference", lambda: omni.kit.window.file.add_reference(is_payload=False), display_name="File->Add Reference", description="Add a reference to a file.", tag=actions_tag, ) action_registry.register_action( extension_id, "add_payload", lambda: omni.kit.window.file.add_reference(is_payload=True), display_name="File->Add Payload", description="Add a payload to a file.", 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)
3,626
Python
31.383928
83
0.621897
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_window.py
"""USD File interaction for Omniverse Kit. :mod:`omni.kit.window.file` provides util functions to new/open/save/close USD files. It handles file picking dialog and prompt for unsaved stage. """ import os import time import traceback import asyncio from typing import Awaitable, Callable, List import carb import omni.ext import omni.usd import omni.kit.app import omni.kit.helper.file_utils as file_utils from pathlib import Path from functools import partial from omni.kit.helper.file_utils import asset_types import omni.kit.usd.layers as layers from omni.kit.window.file_importer import get_file_importer from omni.kit.window.file_exporter import get_file_exporter from omni.kit.widget.nucleus_connector import get_nucleus_connector from .prompt_ui import Prompt from .read_only_options_window import ReadOnlyOptionsWindow from .share_window import ShareWindow from .app_ui import AppUI, DialogOptions, SaveOptionsDelegate, OpenOptionsDelegate from .file_actions import register_actions, deregister_actions from pxr import Tf, Sdf, Usd, UsdGeom, UsdUtils _extension_instance = None TEST_DATA_PATH = "" IGNORE_UNSAVED_ON_EXIT_PATH = "/app/file/ignoreUnsavedOnExit" IGNORE_UNSAVED_STAGE = "/app/file/ignoreUnsavedStage" LAST_OPENED_DIRECTORY = "/persistent/app/omniverse/lastOpenDirectory" SHOW_UNSAVED_LAYERS_DIALOG = "/persistent/app/file/save/showUnsavedLayersDialog" class _CheckpointCommentContext: def __init__(self, comment: str): self._comment = comment def __enter__(self): try: import omni.usd_resolver omni.usd_resolver.set_checkpoint_message(self._comment) except Exception as e: carb.log_error(f"Failed to import omni.usd_resolver: {str(e)}.") return self def __exit__(self, type, value, trace): try: import omni.usd_resolver omni.usd_resolver.set_checkpoint_message("") except Exception: pass class _CallbackRegistrySubscription: """ Simple subscription. _Event has callback while this object exists. """ def __init__(self, callback_list: List, callback: Callable): """ Save the callback in the given list. """ self.__callback_list: List = callback_list self.__callback = callback callback_list.append(callback) def __del__(self): """Called by GC.""" self.__callback_list.remove(self.__callback) class FileWindowExtension(omni.ext.IExt): def on_startup(self, ext_id): global _extension_instance _extension_instance = self self._open_stage_callbacks: List = [] self._open_stage_complete_callbacks: List = [] self.ui_handler = None self._task = None self._unsaved_stage_prompt = None self._file_existed_prompt = None self._open_readonly_usd_prompt = None self._app = omni.kit.app.get_app() self._settings = carb.settings.get_settings() self._settings.set_default_bool(IGNORE_UNSAVED_ON_EXIT_PATH, False) self.ui_handler = AppUI() self._save_options = None self._open_options = None self._share_window = None manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) global TEST_DATA_PATH TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests") def on_event(e: carb.events.IEvent): if e.type == omni.kit.app.POST_QUIT_EVENT_TYPE: ignore_unsaved_file_on_exit = self._settings.get(IGNORE_UNSAVED_ON_EXIT_PATH) usd_context = omni.usd.get_context() if not ignore_unsaved_file_on_exit and usd_context.can_close_stage() and usd_context.has_pending_edit(): self._app.try_cancel_shutdown("Interrupting shutdown - closing stage first") # OM-52366: fast shutdown will not close stage but post quit directly. fast_shutdown = carb.settings.get_settings().get("/app/fastShutdown") self.close(lambda *args: omni.kit.app.get_app().post_quit(), fast_shutdown=fast_shutdown) self._shutdown_subs = self._app.get_shutdown_event_stream().create_subscription_to_pop( on_event, name="window.file shutdown hook", order=0 ) self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name) def on_shutdown(self): deregister_actions(self._ext_name) self._shutdown_subs = None self._save_options = None self._open_options = None if self._task: self._task.cancel() self._task = None if self._unsaved_stage_prompt: self._unsaved_stage_prompt.destroy() self._unsaved_stage_prompt = None if self._file_existed_prompt: self._file_existed_prompt.destroy() self._file_existed_prompt = None if self._open_readonly_usd_prompt: self._open_readonly_usd_prompt.destroy() self._open_readonly_usd_prompt = None global _extension_instance _extension_instance = None if self.ui_handler: self.ui_handler.destroy() self.ui_handler = None def stop_timeline(self): try: import omni.timeline timeline = omni.timeline.get_timeline_interface() if timeline: timeline.stop() else: carb.log_warn(f"Failed to stop timeline, get_timeline_interface() return None") except ModuleNotFoundError: carb.log_warn(f"Failed to stop timeline, omni.timeline not loaded") def new(self, template=None): """Create a new USD stage. If currently opened stage is dirty, a prompt will show to let you save it.""" self.stop_timeline() async def new_stage_job(): # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Creating new stage...", [], [], True): await self._app.next_update_async() # Making sure prompt shows await omni.kit.stage_templates.new_stage_async(template=template) await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled self.prompt_if_unsaved_stage(lambda *_: self._exclusive_task_wrapper(new_stage_job)) def open(self, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL): """Bring up a file picker to choose a USD file to open. If currently opened stage is dirty, a prompt will show to let you save it.""" self.stop_timeline() def open_handler(loadset: int, filename: str, dirname: str, selections: List[str]): if ':/' in filename or filename.startswith('\\\\'): # Filename is a pasted fullpath. The first test finds paths that start with 'C:/' or 'omniverse://'; # the second finds MS network paths that start like '\\analogfs\VENDORS\...' path = filename else: path = f"{dirname or ''}/{filename}" if not omni.usd.is_usd_readable_filetype(path): FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage") return result, entry = omni.client.stat(path) if result != omni.client.Result.OK: carb.log_warn(f"Failed to stat '{path}', attempting to open in read-only mode.") read_only = True else: # https://nvidia-omniverse.atlassian.net/browse/OM-45124 read_only = entry.access & omni.client.AccessFlags.WRITE == 0 if read_only: def _open_with_edit_layer(): self.open_with_new_edit_layer(path, open_loadset) def _open_original_stage(): self.open_stage(path, open_loadset, open_options=self._open_options) self._show_readonly_usd_prompt(_open_with_edit_layer, _open_original_stage) else: self.open_stage(path, open_loadset=loadset, open_options=self._open_options) file_importer = get_file_importer() if file_importer: file_importer.show_window( title="Open File", import_button_label="Open File", import_handler=partial(open_handler, open_loadset), ) if self._open_options is None: self._open_options = OpenOptionsDelegate() file_importer.add_import_options_frame("Options", self._open_options) def open_stage(self, path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, open_options: OpenOptionsDelegate=None, callback: callable=None): """open stage. If the current stage is dirty, a prompt will show to let you save it.""" if not omni.usd.is_usd_readable_filetype(path): FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage") if callback: callback(False) return self.stop_timeline() ui_handler = self.ui_handler self._settings.set(LAST_OPENED_DIRECTORY, os.path.dirname(path)) checkbox = None if open_options: checkbox = open_options.should_load_payload() if not checkbox: # open with payloads disabled open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE async def open_stage_job(): # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() prompt = Prompt("Please Wait", f"Opening {path}...", [], [], True, self._open_stage_callbacks, self._open_stage_complete_callbacks) prompt._window.width = 415 with prompt: context = omni.usd.get_context() start_time = time.time() result, err = await context.open_stage_async(path, open_loadset) success = True if not result or context.get_stage_state() != omni.usd.StageState.OPENED: success = False carb.log_error(f"Failed to open stage {path}: {err}") ui_handler.show_open_stage_failed_prompt(path) else: stage = context.get_stage() identifier = stage.GetRootLayer().identifier if not stage.GetRootLayer().anonymous: message_bus = omni.kit.app.get_app().get_message_bus_event_stream() message_bus.push(file_utils.FILE_OPENED_EVENT, payload=file_utils.FileEventModel(url=identifier).dict()) open_duration = time.time() - start_time omni.kit.app.send_telemetry_event("omni.kit.window.file@open_stage", duration=open_duration, data1=path, value1=float(success)) if callback: callback(False) async def open_stage_async(): result, _ = await omni.client.stat_async(path) if result == omni.client.Result.OK: FileWindowExtension._exclusive_task_wrapper(open_stage_job) return # Attempt to connect to nucleus server broken_url = omni.client.break_url(path) if broken_url.scheme == 'omniverse': server_url = omni.client.make_url(scheme='omniverse', host=broken_url.host) nucleus_connector = get_nucleus_connector() if nucleus_connector: nucleus_connector.connect(broken_url.host, server_url, on_success_fn=lambda *_: FileWindowExtension._exclusive_task_wrapper(open_stage_job), on_failed_fn=lambda *_: carb.log_error(f"Invalid stage URL: {path}") ) else: carb.log_error(f"Invalid stage URL: {path}") self.prompt_if_unsaved_stage(lambda *_: asyncio.ensure_future(open_stage_async())) def _show_readonly_usd_prompt(self, ok_fn, middle_fn): if self._open_readonly_usd_prompt: self._open_readonly_usd_prompt.destroy() self._open_readonly_usd_prompt = ReadOnlyOptionsWindow(ok_fn, middle_fn) self._open_readonly_usd_prompt.show() def _show_file_existed_prompt(self, path, on_confirm_fn, on_cancel_fn=None): file_name = os.path.basename(path) if self._file_existed_prompt: self._file_existed_prompt.destroy() self._file_existed_prompt = Prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite', f"File {file_name} already exists, do you want to overwrite it?", ["OK", "Cancel"], [on_confirm_fn, None], False, ) self._file_existed_prompt.show() def open_with_new_edit_layer(self, path: str, open_loadset: int = omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback: Callable = None): if not omni.usd.is_usd_readable_filetype(path): FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage") return self.stop_timeline() def create_handler(stage_path: str, callback: Callable, filename: str, dirname: str, extension: str = None, selections: List[str] = []): # Allow incoming directory as /path/to/dir or /path/to/dir/ dirname = dirname.rstrip('/') edit_layer_path = f"{dirname}/{filename}{extension}" self.create_stage(edit_layer_path, stage_path, callback=callback) def create_edit_layer(stage_path: str, callback: Callable): file_exporter = get_file_exporter() if file_exporter: dirname = os.path.dirname(stage_path) if Sdf.Layer.IsAnonymousLayerIdentifier(stage_path): basename = Sdf.Layer.GetDisplayNameFromIdentifier(stage_path) else: basename = os.path.basename(stage_path) edit_layer_path = f"{dirname}/{os.path.splitext(basename)[0]}_edit" file_exporter.show_window( title="Create Edit Layer", export_button_label="Save", export_handler=partial(create_handler, stage_path, callback), filename_url=edit_layer_path, ) self.prompt_if_unsaved_stage(lambda: create_edit_layer(path, callback)) def create_stage(self, edit_layer_path: str, file_path: str, callback: Callable = None): self.stop_timeline() async def create_stage_async(edit_layer_path: str, stage_path: str, callback: Callable): edit_layer = Sdf.Layer.FindOrOpen(edit_layer_path) if edit_layer: edit_layer.Clear() else: edit_layer = Sdf.Layer.CreateNew(edit_layer_path) if not edit_layer: carb.log_error(f"open_with_new_edit_layer: failed to create edit layer {edit_layer_path}") return # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Creating new stage...", [], [], True): await self._app.next_update_async() # Making sure prompt shows root_layer = Sdf.Layer.CreateAnonymous() root_layer.subLayerPaths.insert(0, file_path) root_layer.subLayerPaths.insert(0, edit_layer_path) # Copy all meta base_layer = Sdf.Layer.FindOrOpen(file_path) UsdUtils.CopyLayerMetadata(base_layer, root_layer, True) omni.usd.resolve_paths(base_layer.identifier, root_layer.identifier, False, True) # Set edit target stage = Usd.Stage.Open(root_layer) edit_target = Usd.EditTarget(edit_layer) stage.SetEditTarget(edit_target) await omni.usd.get_context().attach_stage_async(stage) await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled if callback: callback() async def create_stage_prompt_if_exists(edit_layer_path: str, file_path: str, callback: Callable): result, _ = await omni.client.stat_async(edit_layer_path) # File is existed already. if result == omni.client.Result.OK: self._show_file_existed_prompt( edit_layer_path, lambda: FileWindowExtension._exclusive_task_wrapper( create_stage_async, edit_layer_path, file_path, callback ) ) else: await create_stage_async(edit_layer_path, file_path, callback) asyncio.ensure_future(create_stage_prompt_if_exists(edit_layer_path, file_path, callback)) def reopen(self): """Reopen currently opened stage. If the stage is dirty, a prompt will show to let you save it.""" self.stop_timeline() async def reopen_stage_job(): context = omni.usd.get_context() path = context.get_stage_url() # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", f"Reopening {path}...", [], [], True): await self._app.next_update_async() # Making sure prompt shows result, err = await context.reopen_stage_async() await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled if not result or context.get_stage_state() != omni.usd.StageState.OPENED: carb.log_error(f"Failed to reopen stage {path}: {err}") self.ui_handler.show_open_stage_failed_prompt(path) if not (omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED and not omni.usd.get_context().is_new_stage()): FileWindowExtension.post_notification("Cannot Reopen. No valid stage") return self.prompt_if_unsaved_stage(lambda *_: FileWindowExtension._exclusive_task_wrapper(reopen_stage_job)) def share(self): context = omni.usd.get_context() if context.get_stage_url().startswith("omniverse://"): layers_interface = layers.get_layers(context) live_syncing = layers_interface.get_live_syncing() current_session = live_syncing.get_current_live_session() if not current_session: url = context.get_stage_url() else: url = current_session.shared_link self._share_window = ShareWindow(url=url) def save(self, callback: Callable, allow_skip_sublayers: bool = False): """Save currently opened stage to file. Will call Save As for a newly created stage""" # Syncs render settings to stage before save so stage could # get the correct edit state if render settings are changed. if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: FileWindowExtension.post_notification("Cannot Save. No valid stage") return self.stop_timeline() async def save_async(callback: Callable, allow_skip_sublayers: bool): is_new_stage = omni.usd.get_context().is_new_stage() or \ omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED is_writeable = False try: filename_url = omni.usd.get_context().get_stage().GetRootLayer().identifier result, stat = await omni.client.stat_async(filename_url) except Exception: pass else: if result == omni.client.Result.OK: is_writeable = stat.flags & omni.client.ItemFlags.WRITEABLE_FILE # OM-47514 When saving a checkpoint or read-only file, use save_as instead if is_new_stage or not is_writeable: self.save_as(False, callback, allow_skip_sublayers=allow_skip_sublayers) else: stage = omni.usd.get_context().get_stage() dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, True) self.ui_handler.save_root_and_sublayers("", dirty_layer_identifiers, on_save_done=callback, allow_skip_sublayers=allow_skip_sublayers) asyncio.ensure_future(save_async(callback, allow_skip_sublayers)) def save_as(self, flatten: bool, callback: Callable, allow_skip_sublayers: bool = False): """Bring up a file picker to choose a file to save current stage to.""" self.stop_timeline() def save_handler(callback: Callable, flatten: bool, filename: str, dirname: str, extension: str = '', selections: List[str] = []): path = f"{dirname}/{filename}{extension}" self.save_stage(path, callback=callback, flatten=flatten, save_options=self._save_options, allow_skip_sublayers=allow_skip_sublayers) if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: FileWindowExtension.post_notification("Cannot Save As. No valid stage") return file_exporter = get_file_exporter() if file_exporter: # OM-48033: Save as should open to latest opened stage path. Solution also covers ... # OM-58150: Save as should pass in the current file name as default value. filename_url = file_utils.get_last_url_visited(asset_type=asset_types.ASSET_TYPE_USD) if filename_url: # OM-91056: File Save As should not prefill the file name filename_url = os.path.dirname(filename_url) + "/" file_exporter.show_window( title="Save File As...", export_button_label="Save", export_handler=partial(save_handler, callback, flatten), filename_url=filename_url, # OM-64312: Set save-as dialog to validate file names in file exporter should_validate=True, ) if self._save_options is None: self._save_options = SaveOptionsDelegate() file_exporter.add_export_options_frame("Save Options", self._save_options) # OM-55838: Don't show "include sesson layer" for non-flatten save-as. self._save_options.show_include_session_layer_option = flatten def save_stage(self, path: str, callback: Callable = None, flatten: bool=False, save_options: SaveOptionsDelegate=None, allow_skip_sublayers: bool=False): self.stop_timeline() stage = omni.usd.get_context().get_stage() save_comment = "" if save_options: save_comment = save_options.get_comment() include_session_layer = False if save_options and flatten: include_session_layer = save_options.include_session_layer() if flatten: path = path or stage.GetRootLayer().identifier # TODO: Currently, it's implemented differently for export w/o session layer as # flatten is a simple operation and we don't want to break the ABI of omni.usd. if include_session_layer: omni.usd.get_context().export_as_stage_with_callback(path, callback) else: async def flatten_stage_without_session_layer(path, callback): await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Exporting flattened stage...", [], [], True): await self._app.next_update_async() usd_context = omni.usd.get_context() if usd_context.can_save_stage(): stage = usd_context.get_stage() # Creates empty anon layer. anon_layer = Sdf.Layer.CreateAnonymous() temp_stage = Usd.Stage.Open(stage.GetRootLayer(), anon_layer) success = temp_stage.Export(path) if callback: if success: callback(True, "") else: callback(False, f"Error exporting flattened stage to path: {path}.") else: error = "Stage busy or another saving task is in progress!!" CARB_LOG_ERROR(error) if callback: callback(False, error) asyncio.ensure_future(flatten_stage_without_session_layer(path, callback)) else: async def save_stage_async(path: str, callback: Callable): if path == stage.GetRootLayer().identifier: dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, True) self.ui_handler.save_root_and_sublayers( "", dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers) else: path = path or stage.GetRootLayer().identifier dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, False) save_fn = lambda: self.ui_handler.save_root_and_sublayers( path, dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers) cancel_fn = lambda: self.ui_handler.save_root_and_sublayers( "", dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers) result, _ = await omni.client.stat_async(path) if result == omni.client.Result.OK: # Path already exists, prompt to overwrite self._show_file_existed_prompt(path, save_fn, on_cancel_fn=cancel_fn) else: save_fn() asyncio.ensure_future(save_stage_async(path, callback)) def close(self, on_closed, fast_shutdown=False): """Check if current stage is dirty. If it's dirty, it will ask if to save the file, then close stage.""" self.stop_timeline() async def close_stage_job(): if not fast_shutdown: # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Closing stage...", [], [], True): await self._app.next_update_async() # Making sure prompt shows await omni.usd.get_context().close_stage_async() await self._app.next_update_async() # Wait anther frame for StageEvent.CLOSED to be handled else: # Clear dirty state to allow quit fastly. omni.usd.get_context().set_pending_edit(False) if on_closed: on_closed() self.prompt_if_unsaved_stage(lambda *_: self._exclusive_task_wrapper(close_stage_job)) def save_layers(self, new_root_path, dirty_layers, on_save_done, create_checkpoint=True, checkpoint_comment=""): """Save current layers""" # Skips if it has no real layers to be saved. self.stop_timeline() # It's possible that all layers are not dirty but it has pending edits to be saved, # like render settings, which needs to be saved into root layer during save. usd_context = omni.usd.get_context() has_pending_edit = usd_context.has_pending_edit() if not new_root_path and not dirty_layers and not has_pending_edit: if on_save_done: on_save_done(True, "") return try: async def save_layers_job(*_): # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Saving layers...", [], [], True): await self._app.next_update_async() # Making sure prompt shows await self._app.next_update_async() # Need 2 frames since save happens on mainthread with _CheckpointCommentContext(checkpoint_comment): result, err, saved_layers = await usd_context.save_layers_async(new_root_path, dirty_layers) await self._app.next_update_async() # Wait anther frame for StageEvent.SAVED to be handled # Clear unique task since it's possible that # post-call to on_save_done needs to create unique # instance also. if _extension_instance and _extension_instance._task: _extension_instance._task = None if on_save_done: on_save_done(result, err) if result: message_bus = omni.kit.app.get_app().get_message_bus_event_stream() message_bus.push(file_utils.FILE_SAVED_EVENT, payload=file_utils.FileEventModel(url=new_root_path).dict()) else: self.ui_handler.show_save_layers_failed_prompt() FileWindowExtension._exclusive_task_wrapper(save_layers_job) except Exception as exc: carb.log_error(f"save error {exc}") traceback.print_exc() def prompt_if_unsaved_stage(self, callback: Callable): """Check if current stage is dirty. If it's dirty, ask to save the file, then execute callback. Otherwise runs callback directly.""" def should_show_stage_save_dialog(): # Use settings to control if it needs to show stage save dialog for layers save. # For application that uses kit and does not want this, it can disable this. settings = carb.settings.get_settings() settings.set_default_bool(SHOW_UNSAVED_LAYERS_DIALOG, True) show_stage_save_dialog = settings.get(SHOW_UNSAVED_LAYERS_DIALOG) return show_stage_save_dialog ignore_unsaved = self._settings.get(IGNORE_UNSAVED_STAGE) if omni.usd.get_context().has_pending_edit() and not ignore_unsaved: if omni.usd.get_context().is_new_stage() or should_show_stage_save_dialog(): if self._unsaved_stage_prompt: self._unsaved_stage_prompt.destroy() self._unsaved_stage_prompt = Prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")}', "Would you like to save this stage?", ["Save", "Don't Save", "Cancel"], [lambda *_: self.save(callback, allow_skip_sublayers=True), lambda *_: callback() if callback else None, None], modal=True) self._unsaved_stage_prompt.show() else: self.save(callback, allow_skip_sublayers=True) else: if callback: callback() def add_reference(self, is_payload=False): self.stop_timeline() def on_file_picked(is_payload: bool, filename: str, dirname: str, selections: List[str]): if ':/' in filename or filename.startswith('\\\\'): # Filename is a pasted fullpath. The first test finds paths that start with 'C:/' or 'omniverse://'; # the second finds MS network paths that start like '\\analogfs\VENDORS\...' reference_path = filename else: reference_path = f"{dirname or ''}/{filename}" name = os.path.splitext(os.path.basename(reference_path))[0] stage = omni.usd.get_context().get_stage() if stage.HasDefaultPrim(): prim_path = omni.usd.get_stage_next_free_path( stage, stage.GetDefaultPrim().GetPath().pathString + "/" + Tf.MakeValidIdentifier(name), False ) else: prim_path = omni.usd.get_stage_next_free_path(stage, "/" + Tf.MakeValidIdentifier(name), False) if is_payload: omni.kit.commands.execute( "CreatePayload", usd_context=omni.usd.get_context(), path_to=prim_path, asset_path=reference_path, instanceable=False ) else: omni.kit.commands.execute( "CreateReference", usd_context=omni.usd.get_context(), path_to=prim_path, asset_path=reference_path, instanceable=False ) file_importer = get_file_importer() if file_importer: file_importer.show_window( title="Select File", import_button_label="Add Reference" if not is_payload else "Add Payload", import_handler=partial(on_file_picked, is_payload)) def register_open_stage_addon(self, callback): return _CallbackRegistrySubscription(self._open_stage_callbacks, callback) def register_open_stage_complete(self, callback): return _CallbackRegistrySubscription(self._open_stage_complete_callbacks, callback) @staticmethod def _exclusive_task_wrapper(job: Awaitable, *args): # Only allow one task to be run if _extension_instance._task: carb.log_info("_exclusive_task_wrapper already running. Cancelling") _extension_instance._task.cancel() _extension_instance._task = None async def exclusive_task(): await job(*args) _extension_instance._task = None _extension_instance._task = asyncio.ensure_future(exclusive_task()) def post_notification(message: str, info: bool = False, duration: int = 3): try: import omni.kit.notification_manager as nm if info: type = nm.NotificationStatus.INFO else: type = nm.NotificationStatus.WARNING nm.post_notification(message, status=type, duration=duration) except ModuleNotFoundError: carb.log_warn(message) def get_instance(): return _extension_instance def new(template=None): file_window = get_instance() if file_window: file_window.new(template) def open(open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL): file_window = get_instance() if file_window: file_window.open(open_loadset) def open_stage(path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback: callable=None): file_window = get_instance() if file_window: file_window.open_stage(path, open_loadset=open_loadset, callback=callback) def open_with_new_edit_layer(path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback=None): file_window = get_instance() if file_window: file_window.open_with_new_edit_layer(path, open_loadset, callback) def reopen(): file_window = get_instance() if file_window: file_window.reopen() def share(): file_window = get_instance() if file_window: file_window.share() def save(on_save_done=None, exit=False, dialog_options=DialogOptions.NONE): file_window = get_instance() if file_window: file_window.save(on_save_done) def save_as(flatten, on_save_done=None): file_window = get_instance() if file_window: file_window.save_as(flatten, on_save_done) def close(on_closed=None): file_window = get_instance() if file_window: file_window.close(on_closed) def save_layers(new_root_path, dirty_layers, on_save_done, create_checkpoint=True, checkpoint_comment=""): file_window = get_instance() if file_window: file_window.save_layers(new_root_path, dirty_layers, on_save_done, create_checkpoint, checkpoint_comment) def prompt_if_unsaved_stage(job): file_window = get_instance() if file_window: file_window.prompt_if_unsaved_stage(job) def add_reference(is_payload=False): file_window = get_instance() if file_window: file_window.add_reference(is_payload=is_payload) def register_open_stage_addon(callback): file_window = get_instance() if file_window: return file_window.register_open_stage_addon(callback) def register_open_stage_complete(callback): file_window = get_instance() if file_window: return file_window.register_open_stage_complete(callback)
37,160
Python
45.048327
158
0.598681
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/app_ui.py
"""USD File interaction for Omniverse Kit. :mod:`omni.kit.window.file` provides util functions to new/open/save/close USD files. It handles file picking dialog and prompt for unsaved stage. """ import os import carb.settings import omni.ui as ui import omni.kit.ui from enum import Enum from typing import List, Callable from omni.kit.window.file_exporter import get_file_exporter, ExportOptionsDelegate from omni.kit.window.file_importer import ImportOptionsDelegate from omni.kit.widget.versioning import CheckpointHelper from .prompt_ui import Prompt from .save_stage_ui import StageSaveDialog from .style import get_style class DialogOptions(Enum): NONE = 0, 'Show dialog using is-required logic' FORCE = 1, 'Force dialog to show and ignore is-required logic' HIDE = 2, 'Never show dialog' class SaveOptionsDelegate(ExportOptionsDelegate): def __init__(self): super().__init__( build_fn=self._build_ui_impl, selection_changed_fn=lambda *_: self._build_ui_impl(), filename_changed_fn=lambda *_: self._build_ui_impl(), destroy_fn=self._destroy_impl ) self._widget = None self._comment_model = ui.SimpleStringModel() self._include_session_layer_checkbox = None self._hint_container = None self._sub_begin_edit = None self._sub_end_edit = None self._show_include_session_layer_option = False self._other_options_widget = None settings = carb.settings.get_settings() self._versioning_enabled = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False def get_comment(self): if self._comment_model: return self._comment_model.get_value_as_string() return "" def include_session_layer(self): """ When doing save-as or save-flattened-as, this option can tell if it needs to keep session layers's change or flatten session layer's change also. """ if self._include_session_layer_checkbox: return self._include_session_layer_checkbox.model.get_value_as_bool() return True @property def show_include_session_layer_option(self): return self._show_include_session_layer_option @show_include_session_layer_option.setter def show_include_session_layer_option(self, value): self._show_include_session_layer_option = value if self._other_options_widget: self._other_options_widget.visible = value def _build_ui_impl(self): if not self._versioning_enabled: return folder_url = "" file_exporter = get_file_exporter() if file_exporter and file_exporter._dialog: folder_url = file_exporter._dialog.get_current_directory() self._widget = ui.Frame() CheckpointHelper.is_checkpoint_enabled_with_callback(folder_url, self._build_options_box) def _build_option_checkbox(self, text, default_value, tooltip, identifier): with ui.VStack(): ui.Spacer() with ui.HStack(height=0): checkbox = ui.CheckBox(width=14, height=14, style={"font_size": 16}, identifier=identifier) checkbox.model.set_value(default_value) ui.Spacer(width=4) label = ui.Label(text, alignment=ui.Alignment.LEFT) label.set_tooltip(tooltip) ui.Spacer() return checkbox def _build_options_box(self, server_url: str, checkpoint_enabled: bool): with self._widget: with ui.VStack(height=0, style=get_style()): if checkpoint_enabled: ui.Label("Checkpoint comments:", height=20, alignment=ui.Alignment.LEFT_CENTER) ui.Separator(height=5) ui.Spacer(height=2) with ui.ZStack(): with ui.HStack(): ui.StringField(self._comment_model, multiline=True, height=64, style_type_name_override="Field") self._hint_container = ui.VStack() with self._hint_container: with ui.HStack(): ui.Label("Add checkpoint comments here.", height=20, style_type_name_override="Field.Hint") ui.Spacer() self._hint_container.visible = False self._sub_begin_edit = self._comment_model.subscribe_begin_edit_fn(self._on_begin_edit) self._sub_end_edit = self._comment_model.subscribe_end_edit_fn(self._on_end_edit) else: ui.Label("This server does not support checkpoints.", height=20, alignment=ui.Alignment.CENTER, word_wrap=True) # OM-55838: Add option to support excluding session layer from flattening. self._other_options_widget = ui.VStack(height=0) with self._other_options_widget: ui.Spacer(height=5) ui.Separator(height=5) ui.Label("Other Options:", height=20, alignment=ui.Alignment.LEFT_CENTER) ui.Spacer(height=5) self._include_session_layer_checkbox = self._build_option_checkbox( "Include Session Layer", False, "When this option is checked, it means it will include content\n" "of session layer into the flattened stage.", "include_session_layer" ) self._other_options_widget.visible = self.show_include_session_layer_option def _on_begin_edit(self, model): self._hint_container.visible = False def _on_end_edit(self, model: ui.AbstractValueModel): if self.get_comment(): self._hint_container.visible = False else: self._hint_container.visible = True def _destroy_impl(self, _): self._comment_model = None self._hint_container = None self._widget = None self._sub_begin_edit = None self._sub_end_edit = None self._include_session_layer_checkbox = None class OpenOptionsDelegate(ImportOptionsDelegate): def __init__(self): super().__init__( build_fn=self._build_ui_impl, destroy_fn=self._destroy_impl ) self._widget = None self._load_payload_checkbox = None def should_load_payload(self): if self._load_payload_checkbox: return self._load_payload_checkbox.model.get_value_as_bool() def _build_ui_impl(self): self._widget = ui.Frame() with self._widget: with ui.VStack(height=0, style=get_style()): ui.Separator(height=5) ui.Spacer(height=2) with ui.HStack(): ui.Spacer(width=2) self._load_payload_checkbox = ui.CheckBox(width=20, style_type_name_override="CheckBox") self._load_payload_checkbox.model.set_value(True) ui.Spacer(width=4) ui.Label("Open Payloads", width=0, height=20, style_type_name_override="Label") ui.Spacer() def _destroy_impl(self, _): self._load_payload_checkbox = None self._widget = None class AppUI: def __init__(self): self._open_stage_failed_prompt = None self._save_layers_failed_prompt = None self._save_stage_prompt = None def destroy(self): if self._open_stage_failed_prompt: self._open_stage_failed_prompt.destroy() self._open_stage_failed_prompt = None if self._save_layers_failed_prompt: self._save_layers_failed_prompt.destroy() self._save_layers_failed_prompt = None if self._save_stage_prompt: self._save_stage_prompt.destroy() self._save_stage_prompt = None def save_root_and_sublayers( self, new_root_path: str, dirty_sublayers: List[str], on_save_done: Callable = None, dialog_options: int = DialogOptions.NONE, save_comment: str = "", allow_skip_sublayers: bool = False): stage = omni.usd.get_context().get_stage() if not stage: return if dialog_options == DialogOptions.HIDE: self._save_layers(new_root_path, dirty_sublayers, on_save_done=on_save_done) return if len(dirty_sublayers) > 0 or dialog_options == DialogOptions.FORCE: if self._save_stage_prompt: self._save_stage_prompt.destroy() self._save_stage_prompt = StageSaveDialog( enable_dont_save=allow_skip_sublayers, on_save_fn=lambda layers, comment: self._save_layers( new_root_path, layers, on_save_done=on_save_done, checkpoint_comment=comment), on_dont_save_fn=lambda comment: self._dont_save_layers( new_root_path, on_save_done=on_save_done, checkpoint_comment=comment), on_cancel_fn=lambda comment: self._cancel_save(new_root_path, checkpoint_comment=comment), ) self._save_stage_prompt.show(dirty_sublayers) else: self._save_layers(new_root_path, [], on_save_done=on_save_done, checkpoint_comment=save_comment) def _save_layers( self, new_root_path, dirty_layers, on_save_done=None, create_checkpoint=True, checkpoint_comment="" ): settings = carb.settings.get_settings() versioning_enabled = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False if versioning_enabled and create_checkpoint: omni.client.create_checkpoint(new_root_path, checkpoint_comment) def save_done_fn(result, err): if result: if versioning_enabled and create_checkpoint: omni.client.create_checkpoint(new_root_path, checkpoint_comment) if on_save_done: on_save_done(result, err) omni.kit.window.file.save_layers( new_root_path, dirty_layers, save_done_fn, create_checkpoint, checkpoint_comment ) def _dont_save_layers(self, new_root_path, on_save_done=None, checkpoint_comment=""): if new_root_path: self._save_layers(new_root_path, [], on_save_done=on_save_done, checkpoint_comment=checkpoint_comment) elif on_save_done: on_save_done(True, "") def _cancel_save(self, new_root_path, checkpoint_comment=""): if new_root_path: self._save_layers(new_root_path, [], None, checkpoint_comment=checkpoint_comment) def show_open_stage_failed_prompt(self, path): if not self._open_stage_failed_prompt: self._open_stage_failed_prompt = Prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Open Stage Failed', "", ["OK"], [None], ) self._open_stage_failed_prompt.set_text( f"Failed to open stage {os.path.basename(path)}. Please check console for error." ) self._open_stage_failed_prompt.show() return self._open_stage_failed_prompt def show_save_layers_failed_prompt(self): if not self._save_layers_failed_prompt: self._save_layers_failed_prompt = Prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Save Layer(s) Failed', "Failed to save layers. Please check console for error.", ["OK"], [None], ) self._save_layers_failed_prompt.show() return self._save_layers_failed_prompt
11,906
Python
40.34375
131
0.592474
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/read_only_options_window.py
import carb import omni.usd import omni.ui as ui from pathlib import Path CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("icons") class ReadOnlyOptionsWindow: def __init__(self, open_with_new_edit_fn, open_original_fn, modal=False): self._title = "Opening a Read Only File" self._modal = modal self._buttons = [] self._content_buttons = [ ("Open With New Edit Layer", "open_edit_layer.svg", open_with_new_edit_fn), ("Open Original File", "pencil.svg", open_original_fn), ] self._build_ui() def destroy(self): for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() def show(self): self._window.visible = True def hide(self): self._window.visible = False def is_visible(self): return self._window.visible def _build_ui(self): self._window = ui.Window( self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED ) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE ) if self._modal: self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL button_style = { "Button": {"stack_direction": ui.Direction.LEFT_TO_RIGHT}, "Button.Image": {"alignment": ui.Alignment.CENTER}, "Button.Label": {"alignment": ui.Alignment.LEFT_CENTER} } def button_cliked_fn(button_fn): if button_fn: button_fn() self.hide() with self._window.frame: with ui.VStack(height=0): ui.Spacer(width=0, height=10) with ui.VStack(height=0): ui.Spacer(height=0) for button in self._content_buttons: (button_text, button_icon, button_fn) = button with ui.HStack(): ui.Spacer(width=40) ui_button = ui.Button( " " + button_text, image_url=f"{ICON_PATH}/{button_icon}", image_width=24, height=40, clicked_fn=lambda a=button_fn: button_cliked_fn(a), style=button_style ) ui.Spacer(width=40) ui.Spacer(height=5) self._buttons.append(ui_button) ui.Spacer(height=5) with ui.HStack(): ui.Spacer() cancel_button = ui.Button("Cancel", width=80, height=0) cancel_button.set_clicked_fn(lambda: self.hide()) self._buttons.append(cancel_button) ui.Spacer(width=40) ui.Spacer(height=0) ui.Spacer(width=0, height=10)
3,269
Python
34.543478
91
0.492199
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_stop_animation.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 platform import unittest import os import pathlib import asyncio import shutil import tempfile import omni.kit.app import omni.usd import omni.timeline from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper class FileWindowStopAnimation(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay() # load stage await open_stage(get_test_data_path(__name__, "physics_animation.usda")) # setup events self._future_test = None self._required_stage_event = -1 self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.window.file") # After running each test async def tearDown(self): # free events self._future_test = None self._required_stage_event = -1 self._stage_event_sub = None await wait_stage_loading() await omni.usd.get_context().new_stage_async() def _on_stage_event(self, event): if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done(): self._future_test.set_result(event.type) async def reset_stage_event(self, stage_event): self._required_stage_event = stage_event self._future_test = asyncio.Future() async def wait_for_stage_event(self): async def wait_for_event(): await self._future_test try: await asyncio.wait_for(wait_for_event(), timeout=30.0) except asyncio.TimeoutError: carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}") self._future_test = None self._required_stage_event = -1 async def test_l1_stop_animation_save(self): def get_box_pos(): stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath("/World/boxActor") attr = prim.GetAttribute("xformOp:translate") return attr.Get() def play_anim(): timeline = omni.timeline.get_timeline_interface() if timeline: timeline.play() # setup orig_pos = get_box_pos() tmpdir = tempfile.mkdtemp() orig_file = get_test_data_path(__name__, "physics_animation.usda").replace("\\", "/") new_file = f"{tmpdir}/physics_animation.usd".replace("\\", "/") # play anim play_anim() await ui_test.human_delay(100) # save as await self.reset_stage_event(omni.usd.StageEventType.SAVED) omni.kit.actions.core.get_action_registry().get_action("omni.kit.window.file", "save_as").execute() await ui_test.human_delay(10) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=new_file) await self.wait_for_stage_event() # play anim play_anim() await ui_test.human_delay(100) # save await self.reset_stage_event(omni.usd.StageEventType.SAVED) omni.kit.actions.core.get_action_registry().get_action("omni.kit.window.file", "save").execute() await ui_test.human_delay(10) # check _check_and_select_all and _on_select_all_fn for StageSaveDialog check_box = ui_test.find("Select Files to Save##file.py//Frame/VStack[0]/ScrollingFrame[0]/VStack[0]/HStack[0]/CheckBox[0]") await check_box.click(human_delay_speed=10) await check_box.click(human_delay_speed=10) await ui_test.human_delay() await ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'").click() await ui_test.human_delay() await self.wait_for_stage_event() # load saved file await open_stage(new_file) # verify boxActor is in same place new_pos = get_box_pos() self.assertAlmostEqual(orig_pos[0], new_pos[0], places=5) self.assertAlmostEqual(orig_pos[1], new_pos[1], places=5) self.assertAlmostEqual(orig_pos[2], new_pos[2], places=5)
5,013
Python
37.56923
157
0.655496
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_save.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb import os import tempfile import shutil import omni.kit.app import omni.kit.commands import omni.kit.test from pathlib import Path from unittest.mock import Mock, patch from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper from .. import FileWindowExtension, get_instance as get_window_file from .test_base import TestFileBase from pxr import Usd import unittest class TestFileSave(TestFileBase): async def setUp(self): await super().setUp() async def tearDown(self): await super().tearDown() async def test_file_save(self): """Testing that save should write to stage url""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) test_file = "test_file.usda" temp_path = os.path.join(tempfile.gettempdir(), test_file) shutil.copyfile(os.path.join(self._usd_path, test_file), temp_path) omni.kit.window.file.open_stage(temp_path) await self.wait_for_update() mock_callback = Mock() omni.kit.window.file.save(mock_callback) await self.wait_for_update() self.assertEqual(omni.usd.get_context().get_stage_url(), temp_path.replace("\\", "/")) self.assertTrue(os.path.isfile(temp_path)) mock_callback.assert_called_once() self.remove_file(temp_path) async def test_file_save_with_render_setting_changes_only(self): usd_context = omni.usd.get_context() await usd_context.new_stage_async() self.assertFalse(usd_context.has_pending_edit()) with tempfile.TemporaryDirectory() as tmp_dir_name: await omni.kit.app.get_app().next_update_async() # save tmp_file_path = Path(tmp_dir_name) / "tmp.usda" result = usd_context.save_as_stage(str(tmp_file_path)) self.assertTrue(result) self.assertFalse(usd_context.has_pending_edit()) # save the file with customized key value settings = carb.settings.get_settings() setting_key_ao = "/rtx/post/aa/op" settings.set_int(setting_key_ao, 3) await omni.kit.app.get_app().next_update_async() # After changing render settings, it will be dirty. self.assertTrue(usd_context.has_pending_edit()) # Saves stage, although no layers are dirty except render settings. omni.kit.window.file.save(None) # Waiting for save to be done as it's asynchronous. for _ in range(10): await omni.kit.app.get_app().next_update_async() # Making sure that render settings are saved into root layer. self.assertFalse(usd_context.has_pending_edit()) # Reloading stage will reload the settings also. await usd_context.reopen_stage_async() await omni.kit.app.get_app().next_update_async() self.assertFalse(usd_context.has_pending_edit()) setting_value_ao = settings.get(setting_key_ao) self.assertEqual(setting_value_ao, 3) # New stage to release temp file. await usd_context.new_stage_async() async def test_file_save_read_only_file(self): """Test saving read-only file calls save_as instead""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) test_file = "test_file.usda" temp_path = os.path.join(tempfile.gettempdir(), test_file) shutil.copyfile(os.path.join(self._usd_path, test_file), temp_path) omni.kit.window.file.open_stage(temp_path) await self.wait_for_update() class ListEntry: def __init__(self) -> None: self.flags = 0 mock_callback = Mock() with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False),\ patch.object(omni.client, "stat_async", return_value=(omni.client.Result.OK, ListEntry())),\ patch.object(FileWindowExtension, "save_as") as mock_save_as: omni.kit.window.file.save(mock_callback) await self.wait_for_update() mock_save_as.assert_called_once_with(False, mock_callback, allow_skip_sublayers=False) self.remove_file(temp_path) async def test_file_saveas(self): """Testing save as""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) temp_path = self._temp_path.replace('.usda', '.usd') mock_callback = Mock() async with FileExporterTestHelper() as file_export_helper: with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False): omni.kit.window.file.save_as(False, mock_callback) await self.wait_for_update() await file_export_helper.click_apply_async(filename_url=temp_path) await self.wait_for_update() mock_callback.assert_called_once() self.assertTrue(os.path.isfile(temp_path)) self.remove_file(temp_path) async def _test_file_saveas_with_empty_filename(self): # pragma: no cover """Testing save as with an empty filename, should not allow saving.""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) temp_path = self._temp_path.replace('.usda', '.usd') mock_callback = Mock() async with FileExporterTestHelper() as file_export_helper: with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False): omni.kit.window.file.save_as(False, mock_callback) await self.wait_for_update() await file_export_helper.click_apply_async() await self.wait_for_update() mock_callback.assert_not_called() self.assertFalse(os.path.isfile(temp_path)) async def _test_file_saveas_flattened_internal(self, include_session_layer): """Testing save as flatten""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) mock_callback = Mock() base, ext = os.path.splitext(self._temp_path) temp_path = base + str(include_session_layer) + ext temp_path = self._temp_path.replace('.usda', '.usd') async with FileExporterTestHelper() as file_export_helper: with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False): omni.kit.window.file.save_as(True, mock_callback) await self.wait_for_update() import omni.kit.ui_test as ui_test file_picker = ui_test.find("Save File As...") self.assertTrue(file_picker) await file_picker.focus() include_session_layer_checkbox = file_picker.find( "**/CheckBox[*].identifier=='include_session_layer'" ) self.assertTrue(include_session_layer_checkbox) include_session_layer_checkbox.model.set_value(include_session_layer) await file_export_helper.click_apply_async(filename_url=temp_path) await self.wait_for_update() stage = Usd.Stage.Open(temp_path) prim = stage.GetPrimAtPath("/OmniverseKit_Persp") if include_session_layer: self.assertTrue(prim) else: self.assertFalse(prim) stage = None mock_callback.assert_called_once() self.assertTrue(os.path.isfile(temp_path)) self.remove_file(temp_path) @unittest.skip("A.B. temp disable, omni.physx.bundle extension causes issues") async def test_file_saveas_flattened_with_session_layer(self): await self._test_file_saveas_flattened_internal(True) async def test_file_saveas_flattened_without_session_layer(self): await self._test_file_saveas_flattened_internal(False) async def test_show_save_layers_failed_prompt(self): omni.usd.get_context().new_stage() prompt = get_window_file().ui_handler.show_save_layers_failed_prompt() await self.wait_for_update() prompt.hide() async def test_file_saveas_existed_filename(self): """Testing save as with a filename which is already existed, should not allow saving.""" # create an empty stage await omni.usd.get_context().new_stage_async() omni.usd.get_context().set_pending_edit(False) file_name = f"4Lights.usda" temp_path = os.path.join(tempfile.gettempdir(), file_name) shutil.copyfile(os.path.join(self._usd_path, file_name), temp_path) # save the current stage to the temp path where the file name already exists async with FileExporterTestHelper() as file_export_helper: with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False): omni.kit.window.file.save_as(False, Mock()) await self.wait_for_update() await file_export_helper.click_apply_async(filename_url=temp_path) await self.wait_for_update() # check 4Lights.usda is not empty, which means saveas didn't happen stage = Usd.Stage.Open(str(temp_path)) await self.wait_for_update() prim = stage.GetPrimAtPath("/Stage/SphereLight_01") self.assertTrue(prim) self.remove_file(temp_path) async def test_invalid_save(self): """Test no valid stage save""" if omni.usd.get_context().get_stage(): await omni.usd.get_context().close_stage_async() mock_callback = Mock() omni.kit.window.file.save(mock_callback) mock_callback.assert_not_called()
10,185
Python
39.420635
104
0.633873
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_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 omni.kit.window.file from .test_base import TestFileBase from unittest.mock import Mock from omni.kit import ui_test from omni.kit.window.file import ReadOnlyOptionsWindow from omni.kit.window.file import register_open_stage_addon, register_open_stage_complete from omni.kit.window.file_importer import get_file_importer class TestFileWindow(TestFileBase): async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() async def test_read_only_options_window(self): """Testing read only options window""" self._readonly_window = ReadOnlyOptionsWindow(None, None, True) self._readonly_window.show() self.assertTrue(self._readonly_window.is_visible) self._readonly_window.destroy() async def test_stage_register(self): """Testing register_open_stage_addon and register_open_stage_complete subscription""" mock_callback1 = Mock() mock_callback2 = Mock() self._addon_subscription = register_open_stage_addon(mock_callback1) self._complete_subscription = register_open_stage_complete(mock_callback2) omni.kit.window.file.open_stage(f"{self._usd_path}/test_file.usda") await self.wait_for_update() mock_callback1.assert_called_once() mock_callback2.assert_called_once() async def test_add_reference(self): omni.kit.window.file.add_reference(is_payload=False) await ui_test.human_delay() file_importer = get_file_importer() self.assertTrue(file_importer.is_window_visible) file_importer.click_cancel()
2,103
Python
35.91228
93
0.717071
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/__init__.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from .test_file_new import * from .test_file_open import * from .test_file_save import * from .test_prompt_unsaved import * from .test_stop_animation import * from .test_file_window import * from .test_loadstage import *
657
Python
40.124997
77
0.7793
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_new.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.test import omni.usd import omni.kit.window from unittest.mock import patch from .test_base import TestFileBase class TestFileNew(TestFileBase): async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() async def test_file_new(self): """Testing file new""" omni.kit.window.file.new() await self.wait_for_update() # verify new layer has non-Null identifier self.assertTrue(bool(omni.usd.get_context().get_stage().GetRootLayer().identifier))
1,033
Python
32.354838
91
0.724105
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_loadstage.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 asyncio import omni.ui as ui import omni.kit.app import omni.kit.test import omni.kit.ui_test as ui_test from omni.ui.tests.test_base import OmniUiTest from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading from omni.kit import ui_test class TestOpenStage(OmniUiTest): """Testing omni.usd.core""" async def setUp(self): await super().setUp() await wait_stage_loading() self._future_test = None self._required_stage_event = -1 self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.menu.file") # After running each test async def tearDown(self): await super().tearDown() def _on_stage_event(self, event): if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done(): self._future_test.set_result(event.type) async def reset_stage_event(self, stage_event): self._required_stage_event = stage_event self._future_test = asyncio.Future() async def wait_for_stage_event(self): async def wait_for_event(): await self._future_test try: await asyncio.wait_for(wait_for_event(), timeout=30.0) except asyncio.TimeoutError: carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}") self._future_test = None self._required_stage_event = -1 async def test_open_stage(self): def on_load_complete(success): if not success: if self._future_test: self._future_test.set_result(False) usd_context = omni.usd.get_context() # test file not found stage = omni.usd.get_context().get_stage() await self.reset_stage_event(omni.usd.StageEventType.OPENED) omni.kit.window.file.open_stage("missing file", callback=on_load_complete) await self.wait_for_stage_event() stage = omni.usd.get_context().get_stage() self.assertEqual(stage, omni.usd.get_context().get_stage()) await ui_test.human_delay(50) # load valid stage stage = omni.usd.get_context().get_stage() await self.reset_stage_event(omni.usd.StageEventType.OPENED) omni.kit.window.file.open_stage(get_test_data_path(__name__, "4Lights.usda"), callback=on_load_complete) await self.wait_for_stage_event() self.assertNotEqual(stage, omni.usd.get_context().get_stage()) await ui_test.human_delay(50) # create new stage await usd_context.new_stage_async() await ui_test.human_delay(50) # load a material as usd file stage = omni.usd.get_context().get_stage() await self.reset_stage_event(omni.usd.StageEventType.OPENED) success = omni.kit.window.file.open_stage(get_test_data_path(__name__, "anno_material.mdl"), callback=on_load_complete) await self.wait_for_stage_event() self.assertEqual(stage, omni.usd.get_context().get_stage()) await ui_test.human_delay(50)
3,594
Python
38.076087
155
0.663884
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_prompt_unsaved.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.test import omni.usd import omni.kit.window from unittest.mock import Mock, patch from omni.usd import UsdContext from carb.settings import ISettings from .test_base import TestFileBase from .. import FileWindowExtension # run tests last as it doesn't cleanup modela dialogs class zzTestPromptIfUnsavedStage(TestFileBase): async def setUp(self): await super().setUp() self._show_unsaved_layers_dialog = False self._ignore_unsaved_stage = False # After running each test async def tearDown(self): await super().tearDown() def _mock_get_carb_setting(self, setting: str): from ..scripts.file_window import SHOW_UNSAVED_LAYERS_DIALOG, IGNORE_UNSAVED_STAGE if setting == SHOW_UNSAVED_LAYERS_DIALOG: return self._show_unsaved_layers_dialog elif setting == IGNORE_UNSAVED_STAGE: return self._ignore_unsaved_stage return False async def test_save_unsaved_stage(self): """Testing click save when prompted to save unsaved stage""" self._ignore_unsaved_stage = False self._show_unsaved_layers_dialog = True mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(UsdContext, "is_new_stage", return_value=True),\ patch.object(FileWindowExtension, "save") as mock_file_save: # Show prompt and click Save omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) await self.click_unsaved_stage_prompt(button=0) mock_file_save.assert_called_once_with(mock_callback, allow_skip_sublayers=True) async def test_dont_save_unsaved_stage(self): """Testing click don't save when prompted to save unsaved stage""" self._ignore_unsaved_stage = False self._show_unsaved_layers_dialog = True mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(UsdContext, "is_new_stage", return_value=True),\ patch.object(FileWindowExtension, "save") as mock_file_save: # Show prompt and click Don't Save omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) await self.click_unsaved_stage_prompt(button=1) mock_file_save.assert_not_called() mock_callback.assert_called_once() async def test_cancel_unsaved_stage(self): """Testing click cancel when prompted to save unsaved stage""" self._ignore_unsaved_stage = False self._show_unsaved_layers_dialog = True mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(UsdContext, "is_new_stage", return_value=True),\ patch.object(FileWindowExtension, "save") as mock_file_save: # Show prompt and click Don't Save omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) await self.click_unsaved_stage_prompt(button=2) mock_file_save.assert_not_called() mock_callback.assert_not_called() async def test_no_prompt(self): """Testing unsaved stage prompt not shown""" self._ignore_unsaved_stage = False self._show_unsaved_layers_dialog = False mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(UsdContext, "is_new_stage", return_value=False),\ patch.object(FileWindowExtension, "save") as mock_file_save: omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) mock_file_save.assert_called_once_with(mock_callback, allow_skip_sublayers=True) async def test_ignore_unsaved(self): """Testing ignore unsaved setting set to True""" self._ignore_unsaved_stage = True mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(FileWindowExtension, "save") as mock_file_save: omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) mock_file_save.assert_not_called() mock_callback.assert_called_once() async def test_no_pending_edit(self): """Testing stage with no pending edit""" self._ignore_unsaved_stage = False mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=False),\ patch.object(FileWindowExtension, "save") as mock_file_save: omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) mock_file_save.assert_not_called() mock_callback.assert_called_once()
5,662
Python
43.590551
90
0.668492
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_base.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 random import string import carb import omni.kit.app import omni.usd import asyncio import omni.kit.ui_test as ui_test from omni.ui.tests.test_base import OmniUiTest from .. import get_instance as get_window_file class TestFileBase(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.window.file.scripts.file_window import TEST_DATA_PATH self._usd_path = TEST_DATA_PATH.absolute() token = carb.tokens.get_tokens_interface() temp_dir = token.resolve("${temp}") def get_random_string(): return "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) self._temp_path = os.path.join(temp_dir, get_random_string(), "test.usda").replace("\\", "/") self._temp_edit_path = os.path.join(temp_dir, get_random_string(), "test_edit.usda").replace("\\", "/") self._dirname = os.path.dirname(self._temp_path).replace("\\", "/") self._filename = os.path.basename(self._temp_path) # After running each test async def tearDown(self): await super().tearDown() async def wait_for_update(self, usd_context=omni.usd.get_context(), wait_frames=20): 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 def remove_file(self, full_path: str): import stat try: os.chmod(full_path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777 os.remove(full_path) except Exception: # Don't know what's causing these errors: "PermissionError: [WinError 5] Access is denied", but don't want # to fail tests for this reason. pass async def click_file_existed_prompt(self, accept: bool = True): dialog = get_window_file()._file_existed_prompt button = 0 if accept else 1 if dialog and dialog._button_list[button][1]: # If file exists, click accept at the prompt to continue dialog._button_list[button][1]() await self.wait_for_update() async def click_save_stage_prompt(self, button: int = 0): dialog = get_window_file().ui_handler._save_stage_prompt if button == 0: dialog._on_save_fn() elif button == 1: dialog._on_dont_save_fn() elif button == 2: dialog._on_cacnel_fn() async def click_unsaved_stage_prompt(self, button: int = 0): dialog = get_window_file()._unsaved_stage_prompt _, click_fn = dialog._button_list[button] if click_fn: click_fn() await self.wait_for_update()
3,325
Python
37.229885
118
0.633383
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_open.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 tempfile import shutil import omni.kit.app import omni.kit.commands import omni.kit.test import unittest from unittest.mock import Mock, patch from carb.settings import ISettings from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper from omni.kit.window.file_importer.test_helper import FileImporterTestHelper from pxr import Sdf from omni.kit.widget.nucleus_connector import NucleusConnectorExtension from .. import get_instance as get_window_file from .test_base import TestFileBase class TestFileOpen(TestFileBase): async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() def _mock_get_carb_setting(self, setting: str): from ..scripts.file_window import SHOW_UNSAVED_LAYERS_DIALOG, IGNORE_UNSAVED_STAGE if setting == SHOW_UNSAVED_LAYERS_DIALOG: return True elif setting == IGNORE_UNSAVED_STAGE: return True return False async def test_file_open(self): """Testing file open""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) omni.kit.window.file.open_stage(f"{self._usd_path}/test_file.usda") await self.wait_for_update() # check file is loaded stage = omni.usd.get_context().get_stage() prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEquals(prim_list, ['/World', '/World/defaultLight']) async def test_open(self): """Test omni.kit.window.file.open""" async with FileImporterTestHelper() as file_importer_helper: omni.kit.window.file.open() from omni.kit.window.file_importer import get_file_importer file_importer = get_file_importer() self.assertTrue(file_importer.is_window_visible) async def test_file_open_with_new_edit_layer(self): """Testing that open with new edit layer executes the callback upon success""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) layer = Sdf.Layer.CreateNew(self._temp_path) self.assertTrue(layer, f"Failed to create temp layer {self._temp_path}.") layer.Save() layer = None mock_callback = Mock() async with FileExporterTestHelper() as file_export_helper: omni.kit.window.file.open_with_new_edit_layer(self._temp_path, callback=mock_callback) await self.wait_for_update() await file_export_helper.click_apply_async() await self.wait_for_update() mock_callback.assert_called_once() @unittest.skip("Crashes when run in random order") # OM-77535 async def test_file_open_with_new_edit_layer_overwrites_existing_file(self): """Testing that open with new edit layer overwrites existing file""" layer = Sdf.Layer.CreateNew(self._temp_path) self.assertTrue(layer, f"Failed to create temp layer {self._temp_path}.") layer.Save() layer = None layer = Sdf.Layer.CreateNew(self._temp_edit_path) self.assertTrue(layer, f"Failed to create temp layer {self._temp_edit_path}.") layer.Save() layer = None async def open_with_new_edit_layer(path): async with FileExporterTestHelper() as file_export_helper: omni.kit.window.file.open_with_new_edit_layer(path) await self.wait_for_update() await file_export_helper.click_apply_async() await self.wait_for_update() await self.click_file_existed_prompt(accept=True) current_stage = omni.usd.get_context().get_stage() self.assertTrue(current_stage) name, _ = os.path.splitext(path) expected_layer_name = f"{name}_edit" self.assertTrue(current_stage.GetRootLayer().anonymous) self.assertEqual(len(current_stage.GetRootLayer().subLayerPaths), 2) sublayer0 = current_stage.GetRootLayer().subLayerPaths[0] sublayer1 = current_stage.GetRootLayer().subLayerPaths[1] file_name, _ = os.path.splitext(sublayer0) self.assertEqual(file_name, expected_layer_name) self.assertEqual(os.path.normpath(sublayer1), os.path.normpath(path)) # First time, creates new edit layer await open_with_new_edit_layer(self._temp_path) # Second time, creates the same name to make sure it correctly overwrites. await omni.usd.get_context().close_stage_async() await open_with_new_edit_layer(self._temp_path) async def test_file_reopen(self): """Testing file reopen""" await omni.usd.get_context().new_stage_async() omni.usd.get_context().set_pending_edit(False) omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda") await self.wait_for_update() # verify its a unmodified stage self.assertFalse(omni.kit.undo.can_undo()) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # verify its a modified stage self.assertTrue(omni.kit.undo.can_undo()) # Skip unsaved stage prompt with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting): omni.kit.window.file.reopen() await self.wait_for_update() # verify its a unmodified stage self.assertFalse(omni.kit.undo.can_undo()) async def test_file_reopen_with_new_edit_layer(self): temp_dir = tempfile.mkdtemp() omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda") await self.wait_for_update() async with FileExporterTestHelper() as file_export_helper: stage = omni.usd.get_context().get_stage() stage_url = stage.GetRootLayer().identifier # Re-open with edit layer omni.kit.window.file.open_with_new_edit_layer(stage_url) await self.wait_for_update() # Save edit layer to temp dir temp_url = f"{temp_dir}/4Lights_layer.usd".replace("\\", "/") await file_export_helper.click_apply_async(filename_url=temp_url) await self.wait_for_update() layer = omni.usd.get_context().get_stage().GetRootLayer() expected = [temp_url, stage_url.replace("\\", "/")] self.assertTrue(layer.anonymous) self.assertTrue(len(layer.subLayerPaths) == 2) self.assertEqual(layer.subLayerPaths[0], expected[0]) self.assertEqual(layer.subLayerPaths[1], expected[1]) # cleanup shutil.rmtree(temp_dir, ignore_errors=True) async def test_show_open_stage_failed_prompt(self): """Testing show_open_stage_failed_prompt""" omni.usd.get_context().new_stage() prompt = get_window_file().ui_handler.show_open_stage_failed_prompt("Test Window File Show Open Stage Failed Prompt") await self.wait_for_update() prompt.hide() async def test_connect_nucleus_when_opening_unreachable_file(self): """Testing that when opening an unreachable file, will try to auto-connect to Nucleus server""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) test_host = "ov-unconnected" test_url = f"omniverse://{test_host}/test_file.usda" async def mock_stat_async(url: str): return (omni.client.Result.ERROR_CONNECTION, None) with patch("omni.client.stat_async", side_effect=mock_stat_async),\ patch.object(NucleusConnectorExtension, "connect") as mock_nucleus_connect: omni.kit.window.file.open_stage(test_url) await self.wait_for_update() # Confirm attempt to connect to Nucleus server self.assertEqual(mock_nucleus_connect.call_args[0], (test_host, f"omniverse://{test_host}")) async def test_file_close(self): """Testing try to close a file which has been modified""" await omni.usd.get_context().new_stage_async() omni.usd.get_context().set_pending_edit(False) omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda") await self.wait_for_update() # modify the stage omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # try to close a modified stage mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting): omni.kit.window.file.close(mock_callback) await self.wait_for_update() mock_callback.assert_called_once()
9,309
Python
40.377778
125
0.653883
omniverse-code/kit/exts/omni.kit.window.file/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.3.32] - 2023-01-13 ## Changed - Remove render settings save as it's driven by events already. ## [1.3.31] - 2023-01-04 ## Changed - skipping test_file_open_with_new_edit_layer_overwrites_existing_file which crashes when run in random order. ## [1.3.30] - 2022-11-04 ## Added - open stage complete callback register for the use of e.g. Activiy window ## [1.3.29] - 2022-10-28 ## Changed - When opening a stage, auto-connect to nucleus. ## [1.3.28] - 2022-10-01 ## Changed - Do not pass in a default filename for new stage for save-as; - Explicitly set file exporter to validate filename for save-as; ## [1.3.27] - 2022-09-21 ## Changed - When saving a checkpoint or read-only file, use save_as instead. ## [1.3.26] - 2022-09-14 ## Changed - Pass in default file url to file exporter for save-as option. ## [1.3.25] - 2022-09-05 ## Changed - Supports to flatten stage without session layer. ## [1.3.24] - 2022-07-22 ## Changed - Fixed checkpoint comments with latet omni.usd_resolver. ## [1.3.23] - 2022-07-19 ## Changed - As menus no longer use contextual greying - Improved error handing for actions & notifications ## [1.3.22] - 2022-07-19 ## Changed - Fixes comment field in save-as option ## [1.3.21] - 2022-06-27 ## Changed - Fixed save actions ## [1.3.20] - 2022-05-30 ## Changed - Added action "open_stage" - Added action "save_with_options" - Added action "save_as_flattened" - Added action "add_payload" ## [1.3.19] - 2022-06-15 ## Changed - Updated unittests. ## [1.3.18] - 2022-05-30 ## Changed - "Select Files to Save" window expands with length of filenames - Decoded URL in Opening URL popup window ## [1.3.17] - 2022-05-19 ## Changed - Fixed file export prompt when quitting an unsaved stage. ## [1.3.16] - 2022-05-05 ## Changed - Updated unittests. ## [1.3.15] - 2022-03-21 ## Changed - Disable checkpoint comments in save as dialog if server doesn't support checkpoints. ## [1.3.14] - 2022-03-21 ## Changed - Open payloads in file dialog. ## [1.3.13] - 2022-03-17 ## Changed - Fixed typo in the previous merge. ## [1.3.12] - 2022-03-17 ## Changed - Fixed UX flow for saving unsaved stage. ## [1.3.11] - 2022-03-08 ## Changed - Fixes Unsaved Layers dialog sometimes not enabling `Dont Save` flag. ## [1.3.10] - 2022-03-10 ## Changed - Pop up read only options dialog for read-only stage to keep consistent behavior as content browser. ## [1.3.9] - 2022-02-09 ## Changed - Refactor to use file_importer and file_exporter rather than FilePickerDialog. ## [1.3.8] - 2021-12-21 ## Changed - More fixes to `open_with_new_edit_layer` and tests added. - Fix memory leak caused by prompt. ## [1.3.7] - 2021-12-17 ## Changed - Fixed `open_with_new_edit_layer` function ## [1.3.6] - 2021-11-10 ## Changed - Cleans up on shutdown, including releasing handle to FilePickerDialog. ## [1.3.5] - 2021-11-02 ## Changed - Add open stage callback register for the use of e.g. Activiy window ## [1.3.4] - 2021-10-20 ## Changed - Don't return windows slashes in paths ## [1.3.3] - 2021-08-04 ## Changed - Fixed leak in popup modal dialog ## [1.3.2] - 2021-07-29 ## Changed - Added LoadSet flags to open_file, open_stage - Fixed Create Reference/Payload to use commands to they are undoable - Create Reference/Payload now uses correct rotation when created ## [1.3.1] - 2021-06-25 ## Changed - "Would you like to save this stage?" is modal ## [1.3.0] - 2021-06-08 ## Changed - Added checkpoint description to `Save As` file picker ## [1.2.2] - 2021-05-05 ## Changed - Updated Save so can either have no UI or UI ## [1.2.1] - 2021-04-08 ## Changed = Removed versioning pane from `Save As` file picker ## [1.2.0] - 2021-03-22 ## Changed = Unified `Save` and `Save with Comment` user interface. ## [1.1.1] - 2021-03-02 - Added test - Fixed leaks ## [1.1.0] - 2021-02-09 ### Changes - Changed checkpoint comment message: - When using Save As to save a new file and overwriting an existing file: "Replaced with new file" - When using Save As to save an existing file and overwriting an existing file: "Replaced with [the path of the file]" ## [1.0.2] - 2021-02-10 - Updated StyleUI handling ## [1.0.1] - 2020-08-28 ### Changes - added add_reference function ## [1.0.0] - 2020-08-28 ### Changes - converted to extension 2.0
4,357
Markdown
23.483146
120
0.683957
omniverse-code/kit/exts/omni.kit.window.file/docs/index.rst
omni.kit.window.file ########################### Provides utility functions to new/open/save/close USD files .. toctree:: :maxdepth: 1 CHANGELOG .. automodule:: omni.kit.window.file :platform: Windows-x86_64, Linux-x86_64, Linux-aarch64 :members: :undoc-members: :imported-members: :exclude-members: partial :noindex: pathlib
362
reStructuredText
17.149999
59
0.635359
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/__init__.py
from ._stats import *
22
Python
10.499995
21
0.681818
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/tests/test_bindings.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__ = ['TestStatsBindings'] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.hydra.engine.stats as engine_stats class TestStatsBindings(AsyncTestCase): '''Simple test against the interfaces of the bindings to fail if they change''' def setUp(self): super().setUp() # After running each test def tearDown(self): super().tearDown() def assertItemIsIndexable(self, item): self.assertTrue(hasattr(item, '__getitem__')) async def test_mem_stats(self): mem_stats = engine_stats.get_mem_stats() # Item should be indexable self.assertItemIsIndexable(mem_stats) # Items should have a caetgory field self.assertIsNotNone(mem_stats[0].get('category')) async def test_mem_stats_detailed(self): mem_stats_detailed = engine_stats.get_mem_stats(detailed=True) # Item should be indexable self.assertItemIsIndexable(mem_stats_detailed) # Items should have a caetgory field self.assertIsNotNone(mem_stats_detailed[0].get('category')) async def test_device_info(self): all_devices = engine_stats.get_device_info() # Item should be indexable self.assertItemIsIndexable(all_devices) # Test getting info on individual devices for i in range(len(all_devices)): cur_device = engine_stats.get_device_info(i) self.assertEqual(cur_device['description'], all_devices[i]['description']) self.assertTrue(cur_device, all_devices[i]) async def test_active_engine_stats(self): hd_stats = engine_stats.HydraEngineStats() a = hd_stats.get_nested_gpu_profiler_result() self.assertItemIsIndexable(a) b = hd_stats.get_gpu_profiler_result() self.assertItemIsIndexable(b) c = hd_stats.reset_gpu_profiler_containers() self.assertTrue(c) self.assertIsNotNone(hd_stats.save_gpu_profiler_result_to_json) async def test_specific_engine_stats(self): hd_stats = engine_stats.HydraEngineStats(usd_context_name='', hydra_engine_name='') a = hd_stats.get_nested_gpu_profiler_result() self.assertItemIsIndexable(a) b = hd_stats.get_gpu_profiler_result() self.assertItemIsIndexable(b) c = hd_stats.reset_gpu_profiler_containers() self.assertTrue(c) self.assertIsNotNone(hd_stats.save_gpu_profiler_result_to_json)
2,895
Python
33.891566
91
0.683247
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/tests/__init__.py
from .test_bindings import *
29
Python
13.999993
28
0.758621
omniverse-code/kit/exts/omni.kit.debug.vscode/PACKAGE-LICENSES/omni.kit.debug.vscode-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.debug.vscode/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "Kit Debug VSCode" description = "VSCode python debugger support window." # URL of the extension source repository. repository = "" # One of categories for UI. category = "Internal" feature = true # Keywords for the extension keywords = ["kit"] # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" [dependencies] "omni.ui" = {} "omni.kit.commands" = {} "omni.usd.libs" = {} "omni.kit.debug.python" = {} [[python.module]] name = "omni.kit.debug.vscode_debugger" [[test]] pyCoverageEnabled = false waiver = "Ultrasmall UI on top of omni.kit.debug.vscode." # OM-48108
968
TOML
22.071428
84
0.716942
omniverse-code/kit/exts/omni.kit.debug.vscode/omni/kit/debug/vscode_debugger.py
import omni.ext import omni.kit.commands import omni.kit.ui import omni.kit.debug.python EXTENSION_NAME = "VS Code Link" class DebugBreak(omni.kit.commands.Command): def do(self): omni.kit.debug.python.breakpoint() def toColor01(color): return tuple(c / 255.0 for c in color) + (1,) class Extension(omni.ext.IExt): """ Extension to enable connection of VS Code python debugger. It enables it using python ptvsd module and shows status. """ def on_startup(self): self._window = omni.kit.ui.Window(EXTENSION_NAME, 300, 150) layout = self._window.layout row_layout = layout.add_child(omni.kit.ui.RowLayout()) # Status label row_layout.add_child(omni.kit.ui.Label("Status:")) self._status_label = row_layout.add_child(omni.kit.ui.Label()) wait_info = omni.kit.debug.python.get_listen_address() info_label = layout.add_child(omni.kit.ui.Label()) info_label.text = f"Address: {wait_info}" if wait_info else "Error" # Break button self._break_button = layout.add_child(omni.kit.ui.Button("Break")) def on_click(*x): omni.kit.commands.execute("DebugBreak") self._break_button.set_clicked_fn(on_click) # Monitor for attachment self._attached = None self._set_attached(False) def on_update(dt): self._set_attached(omni.kit.debug.python.is_attached()) self._window.set_update_fn(on_update) def _set_attached(self, attached): if self._attached != attached: ATTACH_DISPLAY = { True: ("VS Code Debugger Attached", (0, 255, 255)), False: ("VS Code Debugger Unattached", (255, 0, 0)), } self._attached = attached self._break_button.enabled = attached self._status_label.text = ATTACH_DISPLAY[self._attached][0] self._status_label.set_text_color(toColor01(ATTACH_DISPLAY[self._attached][1]))
2,011
Python
29.484848
120
0.6181
omniverse-code/kit/exts/omni.kit.debug.vscode/docs/CHANGELOG.md
# CHANGELOG ## [0.1.0] - 2020-01-14 - Split from omni.kit.debug.utils
73
Markdown
9.571427
33
0.630137
omniverse-code/kit/exts/omni.kit.debug.vscode/docs/README.md
# Debug Utils ## omni.kit.debug.vscode_debugger VSCode python debugger support window.
88
Markdown
16.799997
38
0.784091
omniverse-code/kit/exts/omni.kit.debug.vscode/docs/index.rst
omni.kit.debug.vscode ########################### .. toctree:: :maxdepth: 1 CHANGELOG
96
reStructuredText
8.699999
27
0.447917
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/__init__.py
from .scripts import *
23
Python
10.999995
22
0.73913
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_attributes_widget.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. # from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT from omni.kit.tagging import OmniKitTaggingDelegate, get_tagging_instance from pxr import UsdShade, UsdUI import os.path import carb import carb.settings import omni.ui as ui import omni.kit.app import omni.kit.commands import omni.client EXCLUDED_NAMESPACE = "excluded" GENERATED_NAMESPACE = "generated" DOT_EXCLUDED_NAMESPACE = ".excluded" DOT_GENERATED_NAMESPACE = ".generated" EMPTY_NAMESPACE_DISPLAY_VALUE = "<empty namespace>" SPACING = 5 class TaggingAttributesWidget(SimplePropertyWidget, OmniKitTaggingDelegate): def __init__(self, style): super().__init__(title="Tagging", collapsed=False) self._style = style self._tagging = get_tagging_instance() self._tagging.set_delegate(self) self._advanced_view = False self._refresh_tags = True self._selected_asset = None self._path_names = [] self._current_tags = {} self._configured_namespaces = ["appearance"] self._init_settings() self._read_settings() def on_new_payload(self, payload): self._selected_asset = None self._refresh_tags = True # redraw if rebuild flag is true, or we have a new payload if not super().on_new_payload(payload): return False # exclude material/shaders for prim_path in self._payload: prim = self._get_prim(prim_path) if prim and (prim.IsA(UsdShade.Material) or prim.IsA(UsdShade.Shader) or prim.IsA(UsdShade.NodeGraph) or prim.IsA(UsdUI.Backdrop)): return False return payload is not None and len(payload) > 0 def clean(self): """Inherited function from subclass """ self._tag_event_sub = None self._selected_asset = None self._sub_show_advanced_view = None self._sub_hidden_tags = None self._sub_mod_hidden_tags = None self._stage_event = None self._tagging.set_delegate(None) self._tagging = None def _get_prim(self, prim_path): if prim_path: stage = self._payload.get_stage() if stage: return stage.GetPrimAtPath(prim_path) return None def _init_settings(self): settings = carb.settings.get_settings() self._sub_show_advanced_view = omni.kit.app.SettingChangeSubscription( "/persistent/exts/omni.kit.property.tagging/showAdvancedTagView", lambda *_: self._on_settings_change() ) self._sub_hidden_tags = omni.kit.app.SettingChangeSubscription( "/persistent/exts/omni.kit.property.tagging/showHiddenTags", lambda *_: self._on_settings_change() ) self._sub_mod_hidden_tags = omni.kit.app.SettingChangeSubscription( "/persistent/exts/omni.kit.property.tagging/modifyHiddenTags", lambda *_: self._on_settings_change() ) def _read_settings(self): settings = carb.settings.get_settings() self._allow_advanced_view = settings.get("/persistent/exts/omni.kit.property.tagging/showAdvancedTagView") self._show_hidden_tags = settings.get("/persistent/exts/omni.kit.property.tagging/showHiddenTags") self._modify_hidden_tags = settings.get("/persistent/exts/omni.kit.property.tagging/modifyHiddenTags") self._show_and_modify_hidden_tags = self._show_hidden_tags and self._modify_hidden_tags def _on_settings_change(self): self._read_settings() self.request_rebuild() def _get_tags_callback(self): self.request_rebuild() def updated_tags_for_url(self, url): if url in self._path_names: self._refresh_tags = True self.request_rebuild() def _get_prim_paths(self, payload): """Get the absolute paths of the full prim stack of the payload. """ stage = payload.get_stage() if stage is None: return [], [] prims = [] path_names = [] for path in payload: prim = stage.GetPrimAtPath(path) if prim: for prim_spec in prim.GetPrimStack(): identifier = prim_spec.layer.identifier broken_url = omni.client.break_url(identifier) if broken_url.scheme == "omniverse" and identifier not in path_names: path_names.append(identifier) prims.append(prim) return prims, path_names def _prim_selection_view(self): """Build the combo box that can select the absolute path of the asset whose tags we will display """ with ui.HStack(): ui.Label("Reference(s):", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT) with ui.VStack(spacing=SPACING): def current_index_changed(model, _index): index = model.get_item_value_model().get_value_as_int() self._selected_asset = self._path_names[index] self._refresh_tags = True self.request_rebuild() if self._selected_asset is None and len(self._path_names) > 0: # default - choose last asset path self._selected_asset = self._path_names[-1] index = self._path_names.index(self._selected_asset) # parse identifiers and create short readable names shorter_path_names = [] for path in self._path_names: broken_url = omni.client.break_url(path) if broken_url.path not in shorter_path_names: shorter_path_names.append(os.path.basename(broken_url.path)) if len(shorter_path_names) < len(self._path_names): shorter_path_names = self._path_names model = ui.ComboBox(index, *shorter_path_names).model model.add_item_changed_fn(lambda m, i: current_index_changed(m, i)) return shorter_path_names[index], index def _advanced_view_toggle(self): if self._allow_advanced_view: def toggle_advanced_view(model): val = model.get_value_as_bool() model.set_value(val) self._advanced_view = val self.request_rebuild() with ui.HStack(width=0, spacing=SPACING): ui.Label("Advanced view", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT) with ui.VStack(width=10): ui.Spacer() bool_check = ui.CheckBox(width=10, height=0, name="greenCheck") bool_check.model.set_value(self._advanced_view) bool_check.model.add_value_changed_fn(toggle_advanced_view) ui.Spacer() else: self._advanced_view = False def build_items(self): """Main function that builds the tagging ui """ self._sub_to_prim = None if len(self._payload) == 0: return with ui.VStack(spacing=SPACING, height=0): prims, path_names = self._get_prim_paths(self._payload) self._path_names = path_names if len(prims) == 0 or not prims[0].GetPath(): ui.Label("Nothing taggable selected") return if len(self._path_names) == 0: ui.Label("No asset paths found.", name="label", alignment=ui.Alignment.LEFT_TOP) return if len(self._path_names) == 0: with ui.VStack(height=0, spacing=SPACING): ui.Label( "No tagging service found", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT ) return if self._refresh_tags: # send a tag query to the tagging service asyncronously self._tagging.get_tags(self._path_names, self._get_tags_callback) self._refresh_tags = False path_tags = {} for path in self._path_names: # get the tags already cached from the tagging service results = self._tagging.tags_for_url(path) if results is None: results = [] path_tags[path] = self._tagging.unpack_raw_tags(results) # prim selection combo box selected_name, selected_index = self._prim_selection_view() # checkbox that enables advanced view (if enabled in preferences) self._advanced_view_toggle() if self._selected_asset is None or self._selected_asset not in path_tags: return self._current_tags = path_tags[self._selected_asset] if not self._current_tags: self._current_tags = {} for namespace in self._configured_namespaces: if namespace not in self._current_tags: self._current_tags[namespace] = {} # sort by namespace sorted_tags = [t for t in self._current_tags] sorted_tags = sorted(sorted_tags) if "" in sorted_tags: sorted_tags = sorted_tags[1:] + [""] with ui.CollapsableFrame(title=f"Tags for {selected_name}", name="groupFrame"): with ui.VStack(spacing=SPACING, height=0): for namespace in sorted_tags: if self._advanced_view: self._create_advanced_view(namespace) else: self._create_default_view(namespace) def _advanced_tag_row(self, namespace, hidden_label, key, value, editable): """Show one tag in advanced view along with buttons. A user tag will be an editable text field. A generated tag will be either hidden, non-editable, or editable, depending on preferences. """ full_tag = self._tagging.pack_tag(namespace, hidden_label, key=key, value=value) if not editable: with ui.HStack(spacing=SPACING, width=ui.Percent(100)): ui.Label(full_tag, name="hidden", style=self._style) return # remove a tag or revert (after an update) a change. def revert_tag(field, remove_btn): field.model.set_value(remove_btn.name) remove_btn.set_tooltip("Remove") # toggle revert and update buttons def on_tag_changed(field, update_btn, remove_btn, value): old_value = remove_btn.name valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags) changed = value != old_value and valid if not valid: remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: revert_tag(f, rb)) remove_btn.set_tooltip("Revert") remove_btn.enabled = True update_btn.visible = False elif changed: remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: revert_tag(f, rb)) remove_btn.set_tooltip("Revert") remove_btn.enabled = True update_btn.visible = True elif not changed: remove_btn.set_tooltip("Remove") remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: remove_tag(f, rb)) remove_btn.enabled = True update_btn.visible = False # update a tag via changing text field and clicking "update" button. def update_value(field, update_button, remove_button): full_tag = field.model.get_value_as_string() if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags): old_value = remove_button.name omni.kit.commands.execute( "UpdateTag", asset_path=self._selected_asset, old_tag=old_value, new_tag=full_tag ) update_button.visible = False # update names so we know when the value changes remove_button.name = full_tag # remove a tag or revert (after an update) a change. def remove_tag(field, remove_btn): full_tag = remove_btn.name if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags): omni.kit.commands.execute("RemoveTag", asset_path=self._selected_asset, tag=full_tag) field.visible = False remove_btn.visible = False with ui.HStack(spacing=SPACING, width=ui.Percent(100)): field = ui.StringField() update_button = ui.Button( tooltip="Update", style=self._style["check"], image_height=self._style["check"]["height"], image_width=self._style["check"]["width"], width=1, ) remove_button = ui.Button( tooltip="Remove", style=self._style["remove"], image_height=self._style["remove"]["height"], image_width=self._style["remove"]["width"], width=1, name=full_tag, ) ui.Spacer(width=2) remove_button.set_clicked_fn(lambda f=field, rb=remove_button: remove_tag(f, rb)) update_button.set_clicked_fn(lambda f=field, ub=update_button, rb=remove_button: update_value(f, ub, rb)) update_button.visible = False field.model.set_value(full_tag) field.model.add_value_changed_fn( lambda m, f=field, ub=update_button, rb=remove_button: on_tag_changed( f, ub, rb, m.get_value_as_string() ) ) def _advanced_new_tag_row(self, namespace): """This allows adding a new tag, but the text box must include the namespace (unlike in default view). For example: appearance.user.car """ # add a new tag (must be valid) def add_tag(model): full_tag = model.get_value_as_string() if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags): omni.kit.commands.execute("AddTag", asset_path=self._selected_asset, tag=full_tag) model.set_value("") # toggle add button enabled def on_new_tag_changed(btn, value): valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags) if valid: btn.enabled = True else: btn.enabled = False with ui.HStack(spacing=SPACING, width=ui.Percent(100)): model = ui.StringField(name="new_tag:" + namespace).model b = ui.Button( "Add", tooltip="Add new tag", style=self._style["plus"], image_height=self._style["plus"]["height"], image_width=self._style["plus"]["height"], width=60, clicked_fn=lambda m=model: add_tag(m), ) b.enabled = False model.add_value_changed_fn(lambda m, btn=b: on_new_tag_changed(btn, m.get_value_as_string())) def _create_advanced_view(self, namespace): """Create the full advanced view for each namespace. """ namespace_name = namespace or EMPTY_NAMESPACE_DISPLAY_VALUE with ui.CollapsableFrame(title=f"Advanced tag view: {namespace_name}", name="subFrame"): with ui.VStack(spacing=SPACING, height=0): # show non-hidden tags first for key in self._current_tags[namespace]: if not key[0] == ".": value = self._current_tags[namespace][key] self._advanced_tag_row(namespace, None, key, value, True) # show hidden tags if self._show_hidden_tags: for hidden_label in self._current_tags[namespace]: if hidden_label[0] == ".": for key, value in self._current_tags[namespace][hidden_label].items(): self._advanced_tag_row( namespace, hidden_label[1:], key, value, self._modify_hidden_tags ) self._advanced_new_tag_row(namespace) def _default_user_tag_row(self, namespace, key, generated_tags): """Show a user created tag and the button to remove it. """ with ui.HStack(spacing=SPACING): ui.Label(key, name="label") ui.Spacer() if namespace == "": full_tag = key else: full_tag = ".".join([namespace, key]) with ui.HStack(width=60): ui.Spacer(width=2) if key in generated_tags: if namespace == "": excluded_tag = "." + ".".join([EXCLUDED_NAMESPACE, key]) else: excluded_tag = "." + ".".join([namespace, EXCLUDED_NAMESPACE, key]) b = ui.Button( style=self._style["remove"], width=1, image_height=self._style["remove"]["height"], image_width=self._style["remove"]["width"], tooltip="Reject", clicked_fn=lambda t=full_tag, ap=self._selected_asset: omni.kit.commands.execute( "AddTag", asset_path=ap, tag=excluded_tag, excluded=t ), ) else: b = ui.Button( style=self._style["remove"], width=1, image_height=self._style["remove"]["height"], image_width=self._style["remove"]["width"], tooltip="Remove", clicked_fn=lambda t=full_tag, ap=self._selected_asset: omni.kit.commands.execute( "RemoveTag", asset_path=ap, tag=t ), ) ui.Spacer(width=2) def _default_generated_tag_row(self, namespace, key): """Show a generated created tag and the buttons to confirm it or reject it. """ with ui.HStack(spacing=SPACING): ui.Label(key, name="generated", style=self._style) ui.Spacer() if namespace == "": user_tag = key exclude_tag = "." + ".".join([EXCLUDED_NAMESPACE, key]) else: user_tag = ".".join([namespace, key]) exclude_tag = "." + ".".join([namespace, EXCLUDED_NAMESPACE, key]) with ui.HStack(width=60): ui.Spacer(width=2) a = ui.Button( width=1, style=self._style["check"], tooltip="Confirm", image_height=self._style["check"]["height"], image_width=self._style["check"]["width"], clicked_fn=lambda t=user_tag, ap=self._selected_asset: omni.kit.commands.execute( "AddTag", asset_path=ap, tag=t ), ) ui.Spacer(width=15) b = ui.Button( width=1, style=self._style["remove"], tooltip="Reject", image_height=self._style["remove"]["height"], image_width=self._style["remove"]["width"], clicked_fn=lambda t=exclude_tag, ap=self._selected_asset: omni.kit.commands.execute( "AddTag", asset_path=ap, tag=t ), ) ui.Spacer(width=2) def _default_new_tag_row(self, namespace): """Show a text box and button to create a new user tag in the given namespace. """ def add_tag(namespace, model): value = model.get_value_as_string() if namespace == "": full_tag = value else: full_tag = ".".join([namespace, value]) # if the tag we are adding is excluded, we want to remove the exclusion (this is undoable) excluded = "" if ( namespace in self._current_tags and DOT_EXCLUDED_NAMESPACE in self._current_tags[namespace] and value in self._current_tags[namespace][DOT_EXCLUDED_NAMESPACE] ): if namespace == "": excluded = "." + ".".join([EXCLUDED_NAMESPACE, value]) else: excluded = "." + ".".join([namespace, EXCLUDED_NAMESPACE, value]) if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags): omni.kit.commands.execute( "AddTag", asset_path=self._selected_asset, tag=full_tag, excluded=excluded ) model.set_value("") def on_new_tag_changed(btn, value): if not namespace == "": value = ".".join([namespace, value]) valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags) if valid: btn.enabled = True else: btn.enabled = False with ui.HStack(spacing=SPACING, width=ui.Percent(100)): field = ui.StringField(name="new_tag:" + namespace) model = field.model with ui.HStack(spacing=SPACING, width=60): b = ui.Button( "Add", style=self._style["plus"], image_height=self._style["plus"]["height"], image_width=self._style["plus"]["height"], tooltip="Add new tag", width=60, clicked_fn=lambda m=model, n=namespace: add_tag(n, m), ) b.enabled = False model.add_value_changed_fn(lambda m, btn=b: on_new_tag_changed(btn, m.get_value_as_string())) def _create_default_view(self, namespace): """ This is the default tag view, which shows tags both added by the user and generated hidden tags. When generated tags are "removed" we actually do not delete them, but add another tag with the namespace ".excluded" instead of ".generated" """ def safe_int(value): try: return int(value) except ValueError: return 0 # populate special namespaces user_tags = {} excluded_tags = [] generated_tags = {} if namespace in self._current_tags: user_tags = {n: self._current_tags[namespace][n] for n in self._current_tags[namespace] if n[0] != "."} if DOT_EXCLUDED_NAMESPACE in self._current_tags[namespace]: excluded_tags = self._current_tags[namespace][DOT_EXCLUDED_NAMESPACE] if DOT_GENERATED_NAMESPACE in self._current_tags[namespace]: generated_tags = { key: safe_int(value) for key, value in self._current_tags[namespace][DOT_GENERATED_NAMESPACE].items() if key not in excluded_tags } sorted_by_confidence = [key for key in generated_tags] sorted_by_confidence.sort(key=lambda x: -generated_tags[x]) # skip empty blocks unless they are "appearance" if len(user_tags) == 0 and len(sorted_by_confidence) == 0 and namespace not in self._configured_namespaces: return namespace_name = namespace or EMPTY_NAMESPACE_DISPLAY_VALUE with ui.CollapsableFrame(title=f"Tags for {namespace_name}", name="subFrame"): with ui.VStack(spacing=SPACING): # first list user added tags (non-hidden tags) for key, _ in user_tags.items(): self._default_user_tag_row(namespace, key, generated_tags) # generated tags if sorted_by_confidence and len(sorted_by_confidence) > 0: for key in sorted_by_confidence: if key in user_tags or key in excluded_tags: continue self._default_generated_tag_row(namespace, key) self._default_new_tag_row(namespace)
25,219
Python
41.673435
120
0.543558
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/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 UI_STYLES = {} UI_STYLES["NvidiaLight"] = { "Label::generated": {"color": 0xFF777777, "font_size": 14}, "Label::hidden": {"color": 0xFF777777, "font_size": 14}, "check": { "width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button": {"background_color": 0xFFD6D6D6}, }, "remove": { "width": 15, "height": 15, "Button.Image": {"color": 0xFF3333AA}, "Button": {"background_color": 0xFFD6D6D6}, }, "plus": { "Button.Label": {"color": 0xFF333333}, "Button.Label:disabled": {"color": 0xFF666666}, "width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button.Image:disabled": {"color": 0xFF666666}, "stack_direction": ui.Direction.LEFT_TO_RIGHT, }, } UI_STYLES["NvidiaDark"] = { "Label::generated": {"color": 0xFF777777, "font_size": 14}, "Label::hidden": {"color": 0xFF777777, "font_size": 14}, "check": {"width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button": {"background_color": 0x0}}, "remove": {"width": 15, "height": 15, "Button.Image": {"color": 0xFF3333AA}, "Button": {"background_color": 0x0}}, "plus": { "Button.Label": {"color": 0xFFCCCCCC}, "Button.Label:disabled": {"color": 0xFF666666}, "width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button.Image:disabled": {"color": 0xFF666666}, "stack_direction": ui.Direction.LEFT_TO_RIGHT, }, }
2,024
Python
35.818181
118
0.606719